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/test/java/com/netflix/titus/common/network/http/internal | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/network/http/internal/okhttp/RxOkHttpClientTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.network.http.internal.okhttp;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.netflix.titus.common.network.http.EndpointResolver;
import com.netflix.titus.common.network.http.Request;
import com.netflix.titus.common.network.http.RequestBody;
import com.netflix.titus.common.network.http.Response;
import com.netflix.titus.common.network.http.RxHttpClient;
import com.netflix.titus.common.network.http.StatusCode;
import com.netflix.titus.common.network.http.internal.RoundRobinEndpointResolver;
import okhttp3.Interceptor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RxOkHttpClientTest {
private static final String TEST_REQUEST_BODY = "Test Request Body";
private static final String TEST_RESPONSE_BODY = "Test Response Body";
private MockWebServer server;
@Before
public void setUp() throws Exception {
server = new MockWebServer();
}
@After
public void tearDown() throws Exception {
server.shutdown();
}
@Test
public void testGet() throws Exception {
MockResponse mockResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
server.enqueue(mockResponse);
RxHttpClient client = RxOkHttpClient.newBuilder()
.build();
Request request = new Request.Builder()
.url(server.url("/").toString())
.get()
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(response.isSuccessful()).isTrue();
InputStream inputStream = response.getBody().get(InputStream.class);
String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);
RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS);
Assertions.assertThat(recordedRequest).isNotNull();
Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
}
@Test
public void testPost() throws Exception {
MockResponse mockResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
server.enqueue(mockResponse);
RxHttpClient client = RxOkHttpClient.newBuilder()
.build();
Request request = new Request.Builder()
.url(server.url("/").toString())
.post()
.body(RequestBody.create(TEST_REQUEST_BODY))
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(response.isSuccessful()).isTrue();
String actualResponseBody = response.getBody().get(String.class);
Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);
RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS);
Assertions.assertThat(recordedRequest).isNotNull();
String actualRequestBody = recordedRequest.getBody().readUtf8();
Assertions.assertThat(actualRequestBody).isEqualTo(TEST_REQUEST_BODY);
}
@Test
public void testGetWithEndpointResolver() throws Exception {
MockResponse mockResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
server.enqueue(mockResponse);
EndpointResolver roundRobinEndpointResolver = new RoundRobinEndpointResolver(server.url("").toString());
Interceptor endpointResolverInterceptor = new EndpointResolverInterceptor(roundRobinEndpointResolver);
RxHttpClient client = RxOkHttpClient.newBuilder()
.interceptor(endpointResolverInterceptor)
.build();
Request request = new Request.Builder()
.url("/")
.get()
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(response.isSuccessful()).isTrue();
InputStream inputStream = response.getBody().get(InputStream.class);
String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);
RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS);
Assertions.assertThat(recordedRequest).isNotNull();
Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
}
@Test
public void testGetWithRetries() throws Exception {
MockResponse notAvailableResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.SERVICE_UNAVAILABLE.getCode());
server.enqueue(notAvailableResponse);
MockResponse internalErrorResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.INTERNAL_SERVER_ERROR.getCode());
server.enqueue(internalErrorResponse);
MockResponse successfulResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
server.enqueue(successfulResponse);
Interceptor passthroughInterceptor = new PassthroughInterceptor();
Interceptor compositeRetryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(passthroughInterceptor), 3);
RxHttpClient client = RxOkHttpClient.newBuilder()
.interceptor(compositeRetryInterceptor)
.build();
Request request = new Request.Builder()
.url(server.url("/").toString())
.get()
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(response.isSuccessful()).isTrue();
InputStream inputStream = response.getBody().get(InputStream.class);
String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);
server.takeRequest(1, TimeUnit.MILLISECONDS);
server.takeRequest(1, TimeUnit.MILLISECONDS);
RecordedRequest recordedRequest = server.takeRequest(1, TimeUnit.MILLISECONDS);
Assertions.assertThat(recordedRequest).isNotNull();
Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
}
@Test
public void testPostWithRetriesSendsOnlyOneRequest() throws Exception {
MockResponse notAvailableResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.SERVICE_UNAVAILABLE.getCode());
server.enqueue(notAvailableResponse);
MockResponse successfulResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
server.enqueue(successfulResponse);
Interceptor passthroughInterceptor = new PassthroughInterceptor();
Interceptor compositeRetryInterceptor = new CompositeRetryInterceptor(Collections.singletonList(passthroughInterceptor), 3);
RxHttpClient client = RxOkHttpClient.newBuilder()
.interceptor(compositeRetryInterceptor)
.build();
Request request = new Request.Builder()
.url(server.url("/").toString())
.post()
.body(RequestBody.create(TEST_REQUEST_BODY))
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(server.getRequestCount()).isEqualTo(1);
Assertions.assertThat(response.getStatusCode()).isEqualTo(StatusCode.SERVICE_UNAVAILABLE);
Assertions.assertThat(response.getBody().get(String.class)).isEqualTo(TEST_RESPONSE_BODY);
}
@Test
public void testGetWithSslContext() throws Exception {
String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
HeldCertificate localhostCertificate = new HeldCertificate.Builder()
.addSubjectAlternativeName(localhost)
.build();
HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()
.heldCertificate(localhostCertificate)
.build();
try (MockWebServer sslServer = new MockWebServer()) {
sslServer.useHttps(serverCertificates.sslSocketFactory(), false);
String url = sslServer.url("/").toString();
MockResponse mockResponse = new MockResponse()
.setBody(TEST_RESPONSE_BODY)
.setResponseCode(StatusCode.OK.getCode());
sslServer.enqueue(mockResponse);
HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
.addTrustedCertificate(localhostCertificate.certificate())
.build();
RxHttpClient client = RxOkHttpClient.newBuilder()
.sslContext(clientCertificates.sslContext())
.trustManager(clientCertificates.trustManager())
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = client.execute(request).toBlocking().first();
Assertions.assertThat(response.isSuccessful()).isTrue();
InputStream inputStream = response.getBody().get(InputStream.class);
String actualResponseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
Assertions.assertThat(actualResponseBody).isEqualTo(TEST_RESPONSE_BODY);
RecordedRequest recordedRequest = sslServer.takeRequest(1, TimeUnit.MILLISECONDS);
Assertions.assertThat(recordedRequest).isNotNull();
Assertions.assertThat(recordedRequest.getBodySize()).isLessThanOrEqualTo(0);
}
}
} | 600 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/network | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/network/socket/UnusedSocketPortAllocatorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.network.socket;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UnusedSocketPortAllocatorTest {
@Test
public void testPortAllocation() {
int first = UnusedSocketPortAllocator.global().allocate();
int second = UnusedSocketPortAllocator.global().allocate();
assertThat(first != second).isTrue();
}
} | 601 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/SpELClassValidatorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.NullableChild;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SpELClassValidatorTest {
@Test
public void testSpELCondition() {
Validator validator = TestValidator.testStrictValidator();
Root root = new Root(
"root1",
new Child("child1", 0, 2),
new NullableChild("child2")
);
Set<ConstraintViolation<Root>> violations = validator.validate(root);
System.out.println(violations);
assertThat(violations).hasSize(1);
}
@Test
public void testSpELExpression() {
Validator validator = TestValidator.testValidator("myUtil", this);
ExprCheckModel entity = new ExprCheckModel("abc");
Set<ConstraintViolation<ExprCheckModel>> violations = validator.validate(entity);
System.out.println(violations);
assertThat(violations).hasSize(1);
}
@Test
public void testRegisteredFunctions() {
assertThat(testRegisteredFunctions(TestValidator.testStrictValidator())).hasSize(1);
}
@Test
public void testPermissiveMode() {
assertThat(testRegisteredFunctions(TestValidator.testPermissiveValidator())).isEmpty();
}
private Set<ConstraintViolation<Root>> testRegisteredFunctions(Validator validator) {
Root root = new Root(
"Root1",
new Child("Child1", 0, 2),
new NullableChild("Child2")
);
TestModel.setFit(false);
Set<ConstraintViolation<Root>> violations = validator.validate(root);
System.out.println(violations);
return violations;
}
public Map<String, String> check(String name) {
if (!name.startsWith("my")) {
return Collections.singletonMap("name", "Should start with prefix 'my'");
}
return Collections.emptyMap();
}
@ClassInvariant(expr = "@myUtil.check(name)")
public static class ExprCheckModel {
private final String name;
public ExprCheckModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
} | 602 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/TestModel.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import com.google.common.base.Preconditions;
public class TestModel {
@ClassFieldsNotNull
@ClassInvariant(condition = "#fit()", message = "Simulated failure (OS=#{@env['os.name']})", mode = VerifierMode.Strict)
public static class Root {
@FieldInvariant(value = "value == null || T(java.lang.Character).isUpperCase(value.charAt(0))", message = "Name '#{value}' must start with a capital letter")
private final String name;
@FieldSanitizer(sanitizer = MinMaxOrderSanitizer.class)
@Valid
private final Child child;
@Valid
private final NullableChild nullableChild;
public Root(String name, Child child, NullableChild nullableChild) {
this.name = name;
this.child = child;
this.nullableChild = nullableChild;
}
public String getName() {
return name;
}
public Child getChild() {
return child;
}
public NullableChild getNullableChild() {
return nullableChild;
}
}
@ClassFieldsNotNull
@ClassInvariant(condition = "min <= max", message = "'min'(#{min} must be <= 'max'(#{max}")
public static class Child {
@Template
private final String childName;
@Min(value = 0, message = "'min' must be >= 0, but is #{#root}")
@FieldInvariant(value = "value % 2 == 0", message = "'min' must be even number")
private final int min;
@FieldSanitizer(atLeast = 10, atMost = 100, adjuster = "(value / 2) * 2")
@Max(100)
private final int max;
public Child(String childName, int min, int max) {
this.childName = childName;
this.min = min;
this.max = max;
}
public String getChildName() {
return childName;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
public static class NullableChild {
private final String optionalValue;
public NullableChild(String optionalValue) {
this.optionalValue = optionalValue;
}
public String getOptionalValue() {
return optionalValue;
}
}
public static class ChildExt extends Child {
private final int desired;
public ChildExt(String childName, int min, int desired, int max) {
super(childName, min, max);
this.desired = desired;
}
public int getDesired() {
return desired;
}
}
public static class CollectionHolder {
@Template
private final List<String> values;
public CollectionHolder(List<String> values) {
this.values = values;
}
public List<String> getValues() {
return values;
}
}
public static class StringWithPrefixCheck {
@FieldInvariant("@myObj.containsPrefix(value)")
private final String value;
public StringWithPrefixCheck(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public static final class MinMaxOrderSanitizer implements Function<Object, Optional<Object>> {
@Override
public Optional<Object> apply(Object childObject) {
Preconditions.checkArgument(childObject instanceof Child);
Child child = (Child) childObject;
if (child.getMax() < child.getMin()) {
return Optional.of(new Child(child.getChildName(), child.getMin(), child.getMin()));
}
return Optional.empty();
}
}
private static ThreadLocal<Boolean> fitStatus = new ThreadLocal<>();
public static void setFit(boolean status) {
fitStatus.set(status);
}
public static boolean fit() {
return fitStatus.get() == null || fitStatus.get();
}
public static Method getFitMethod() {
try {
return TestModel.class.getDeclaredMethod("fit");
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
public static class SampleValidationMethods {
private final String prefix;
public SampleValidationMethods(String prefix) {
this.prefix = prefix;
}
public Boolean containsPrefix(String stringValue) {
return stringValue != null && stringValue.contains(stringValue);
}
}
}
| 603 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/EntitySanitizerBuilderTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.util.Optional;
import java.util.Set;
import org.junit.Test;
import static com.netflix.titus.common.util.ReflectionExt.isStandardDataType;
import static org.assertj.core.api.Assertions.assertThat;
public class EntitySanitizerBuilderTest {
private final EntitySanitizer sanitizer = EntitySanitizerBuilder.stdBuilder()
.processEntities(type -> !isStandardDataType(type))
.addTemplateResolver(path -> path.equals("child.childName") ? Optional.of("GuestChild") : Optional.empty())
.registerFunction("fit", TestModel.getFitMethod())
.registerBean("myObj", new TestModel.SampleValidationMethods("test"))
.build();
@Test
public void testCompleteSetup() throws Exception {
TestModel.Root root = new TestModel.Root(
null,
new TestModel.Child(null, -2, 1),
new TestModel.NullableChild(null)
);
// Null values violation + min
Set<ValidationError> violations = sanitizer.validate(root);
System.out.println(violations);
assertThat(violations).hasSize(3);
// Now fix this by sanitizing
TestModel.Root sanitizedRoot = sanitizer.sanitize(root).get();
Set<ValidationError> rangeViolations = sanitizer.validate(sanitizedRoot);
System.out.println(violations);
assertThat(rangeViolations).hasSize(2);
}
@Test
public void testRegisteredObjects() throws Exception {
Set<ValidationError> violations = sanitizer.validate(new TestModel.StringWithPrefixCheck("testXXX"));
assertThat(violations).isEmpty();
}
}
| 604 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/TestValidator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import javax.validation.Validation;
import javax.validation.Validator;
import com.netflix.titus.common.model.sanitizer.internal.ConstraintValidatorFactoryWrapper;
import com.netflix.titus.common.model.sanitizer.internal.SpELMessageInterpolator;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.support.ReflectiveMethodResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static java.util.Collections.singletonMap;
/**
* Pre-configured JavaBean validators with Titus validation extensions, used by unit tests.
*/
public final class TestValidator {
public static Validator testStrictValidator() {
return testValidator(VerifierMode.Strict);
}
public static Validator testPermissiveValidator() {
return testValidator(VerifierMode.Permissive);
}
public static Validator testValidator(VerifierMode verifierMode) {
TestModel.setFit(true);
Map<String, Object> registeredObjects = singletonMap("env", System.getProperties());
Supplier<EvaluationContext> spelContextFactory = () -> {
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction("fit", TestModel.getFitMethod());
context.setBeanResolver((ctx, beanName) -> registeredObjects.get(beanName));
return context;
};
return Validation.buildDefaultValidatorFactory()
.usingContext()
.constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(verifierMode, type -> Optional.empty(), spelContextFactory))
.messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
.getValidator();
}
public static Validator testValidator(String alias, Object bean) {
Supplier<EvaluationContext> spelContextFactory = () -> {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver((ctx, beanName) -> beanName.equals(alias) ? bean : null);
context.setMethodResolvers(Collections.singletonList(new ReflectiveMethodResolver()));
return context;
};
return Validation.buildDefaultValidatorFactory()
.usingContext()
.constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(VerifierMode.Strict, type -> Optional.empty(), spelContextFactory))
.messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
.getValidator();
}
}
| 605 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/CollectionValidatorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.common.model.sanitizer.CollectionInvariants;
import com.netflix.titus.common.model.sanitizer.TestValidator;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.titus.common.util.CollectionsExt.first;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class CollectionValidatorTest {
private Validator validator;
@Before
public void setUp() {
validator = TestValidator.testStrictValidator();
}
@Test
public void testValidCollection() {
assertThat(validator.validate(new ListWrapper(asList("A", "A", "C")))).isEmpty();
}
@Test
public void testCollectionWithNullValues() {
Set<ConstraintViolation<ListWrapper>> violations = validator.validate(new ListWrapper(asList("A", null, "C")));
assertThat(violations).hasSize(1);
assertThat(first(violations).getMessage()).isEqualTo("null values not allowed");
}
@Test
public void testCollectionWithDuplicateValues() {
Set<ConstraintViolation<ListWrapperWithUniqueValues>> violations = validator.validate(new ListWrapperWithUniqueValues(asList("A", "A", "C")));
assertThat(violations).hasSize(1);
assertThat(first(violations).getMessage()).isEqualTo("duplicate values not allowed");
}
@Test
public void testValidMap() {
assertThat(validator.validate(new MapWrapper(ImmutableMap.of(
"k1", "v1",
"k2", "v2",
"k3", "v3"
)))).isEmpty();
}
@Test
public void testMapWithEmptyKeys() {
Map<String, String> mapWithEmptyKeys = new HashMap<>();
mapWithEmptyKeys.put("k1", "v1");
mapWithEmptyKeys.put("", "v2");
Set<ConstraintViolation<MapWrapper>> violations = validator.validate(new MapWrapper(mapWithEmptyKeys));
assertThat(violations).hasSize(1);
assertThat(first(violations).getMessage()).isEqualTo("empty key names not allowed");
}
@Test
public void testMapWithNullKeys() {
Map<String, String> mapWithNullKeys = new HashMap<>();
mapWithNullKeys.put("k1", "v1");
mapWithNullKeys.put(null, "v2");
Set<ConstraintViolation<MapWrapperWithEmptyKeys>> violations = validator.validate(new MapWrapperWithEmptyKeys(mapWithNullKeys));
assertThat(violations).hasSize(1);
assertThat(first(violations).getMessage()).isEqualTo("null key names not allowed");
}
@Test
public void testMapWithNullValues() {
Map<String, String> mapWithNullValues = new HashMap<>();
mapWithNullValues.put("k1", "v1");
mapWithNullValues.put("k2", null);
mapWithNullValues.put("k3", null);
Set<ConstraintViolation<MapWrapper>> violations = validator.validate(new MapWrapper(mapWithNullValues));
assertThat(violations).hasSize(1);
assertThat(first(violations).getMessage()).isEqualTo("null values found for keys: [k2, k3]");
}
static class ListWrapper {
@CollectionInvariants
List<String> values;
ListWrapper(List<String> values) {
this.values = values;
}
}
static class MapWrapper {
@CollectionInvariants(allowEmptyKeys = false)
Map<String, String> values;
MapWrapper(Map<String, String> values) {
this.values = values;
}
}
static class MapWrapperWithEmptyKeys {
@CollectionInvariants(allowEmptyKeys = true, allowNullValues = false)
Map<String, String> values;
MapWrapperWithEmptyKeys(Map<String, String> values) {
this.values = values;
}
}
static class ListWrapperWithUniqueValues {
@CollectionInvariants(allowDuplicateValues = false)
List<String> values;
ListWrapperWithUniqueValues(List<String> values) {
this.values = values;
}
}
} | 606 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/JavaBeanReflectionTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.ChildExt;
import com.netflix.titus.common.model.sanitizer.TestModel.NullableChild;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import org.junit.Test;
import static com.netflix.titus.common.util.ReflectionExt.getField;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaBeanReflectionTest {
@Test
public void testGetFields() throws Exception {
JavaBeanReflection jbr = JavaBeanReflection.forType(Root.class);
Set<String> fieldNames = jbr.getFields().stream().map(Field::getName).collect(Collectors.toSet());
assertThat(fieldNames).contains("name", "child");
}
@Test
public void testGetFieldsWithInheritanceHierarchy() throws Exception {
JavaBeanReflection jbr = JavaBeanReflection.forType(ChildExt.class);
Set<String> fieldNames = jbr.getFields().stream().map(Field::getName).collect(Collectors.toSet());
assertThat(fieldNames).contains("childName", "min", "desired", "max");
}
@Test
public void testObjectCreate() throws Exception {
JavaBeanReflection jbr = JavaBeanReflection.forType(Root.class);
Root root = new Root(
"root",
new Child("child1", 1, 2),
new NullableChild("child2")
);
Root updatedRoot = (Root) jbr.create(root, Collections.singletonMap(getField(Root.class, "name"), "Root"));
assertThat(updatedRoot.getName()).isEqualTo("Root");
}
} | 607 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/TemplateSanitizerTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.util.Collections;
import java.util.Optional;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.CollectionHolder;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class TemplateSanitizerTest {
@Test
public void testPrimitiveValueTemplate() throws Exception {
Root root = new Root(
null,
new Child(null, 1, 2),
null
);
Optional<Object> sanitizedOpt = new TemplateSanitizer(
path -> path.equals("child.childName") ? Optional.of("ChildGuest") : Optional.empty(),
type -> true
).apply(root);
assertThat(sanitizedOpt).isPresent();
Root sanitized = (Root) sanitizedOpt.get();
assertThat(sanitized.getName()).isNull();
assertThat(sanitized.getChild().getChildName()).isEqualTo("ChildGuest");
assertThat(sanitized.getChild().getMin()).isEqualTo(1);
assertThat(sanitized.getChild().getMax()).isEqualTo(2);
assertThat(sanitized.getNullableChild()).isNull();
}
@Test
public void testCollectionTemplate() throws Exception {
CollectionHolder root = new CollectionHolder(Collections.emptyList());
Optional<Object> sanitizedOpt = new TemplateSanitizer(
path -> path.equals("values") ? Optional.of(asList("a", "b")) : Optional.empty(),
type -> true
).apply(root);
assertThat(sanitizedOpt).isPresent();
}
} | 608 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/ClassFieldsNotNullValidatorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.NullableChild;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import com.netflix.titus.common.model.sanitizer.TestValidator;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ClassFieldsNotNullValidatorTest {
private Validator validator;
@Before
public void setUp() throws Exception {
validator = TestValidator.testStrictValidator();
}
@Test
public void testNullTopLevelField() throws Exception {
Root root = new Root(
null,
new Child("child1", 0, 2),
new NullableChild("child2")
);
Set<ConstraintViolation<Root>> violations = validator.validate(root);
System.out.println(violations);
assertThat(violations).hasSize(1);
}
@Test
public void testNullNestedField() throws Exception {
Root root = new Root(
"Root1",
new Child(null, 0, 2),
new NullableChild(null)
);
Set<ConstraintViolation<Root>> violations = validator.validate(root);
System.out.println(violations);
assertThat(violations).hasSize(1);
}
} | 609 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/StdValueSanitizerTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.util.Optional;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.NullableChild;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StdValueSanitizerTest {
@Test
public void testPrimitiveDataSanitization() throws Exception {
Root root = new Root(
" root1 ",
new Child(" child1 ", 1, 2),
new NullableChild(" child2 ")
);
Optional<Object> sanitizedOpt = new StdValueSanitizer(type -> true).apply(root);
assertThat(sanitizedOpt).isPresent();
Root sanitized = (Root) sanitizedOpt.get();
assertThat(sanitized.getName()).isEqualTo("root1");
assertThat(sanitized.getChild().getChildName()).isEqualTo("child1");
assertThat(sanitized.getChild().getMin()).isEqualTo(1);
assertThat(sanitized.getChild().getMax()).isEqualTo(2);
assertThat(sanitized.getNullableChild().getOptionalValue()).isEqualTo("child2");
}
@Test
public void testSanitizationOfNullNestedObjects() {
Root root = new Root(
" root1 ",
null,
null
);
Optional<Object> sanitizedOpt = new StdValueSanitizer(type -> true).apply(root);
assertThat(sanitizedOpt).isPresent();
Root sanitized = (Root) sanitizedOpt.get();
assertThat(sanitized.getName()).isEqualTo("root1");
}
} | 610 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/model/sanitizer/internal/AnnotationBasedSanitizerTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import java.util.Optional;
import com.netflix.titus.common.model.sanitizer.TestModel.Child;
import com.netflix.titus.common.model.sanitizer.TestModel.NullableChild;
import com.netflix.titus.common.model.sanitizer.TestModel.Root;
import org.junit.Test;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
public class AnnotationBasedSanitizerTest {
@Test
public void testSanitizerOption() throws Exception {
Root root = new Root(
"root1",
new Child("child1", 20, 1),
new NullableChild("child2")
);
Root sanitized = apply(root);
// Check that min/max order has been fixed
Child child = sanitized.getChild();
assertThat(child.getChildName()).isEqualTo("child1");
assertThat(child.getMin()).isEqualTo(20);
assertThat(child.getMax()).isEqualTo(20);
}
@Test
public void testAtLeastOption() throws Exception {
Root root = new Root(
"root1",
new Child("child1", 2, 5),
new NullableChild("child2")
);
Root sanitized = apply(root);
assertThat(sanitized.getChild().getMax()).isEqualTo(10);
}
@Test
public void testAtMostOption() throws Exception {
Root root = new Root(
"root1",
new Child("child1", 2, 150),
new NullableChild("child2")
);
Root sanitized = apply(root);
assertThat(sanitized.getChild().getMax()).isEqualTo(100);
}
@Test
public void testAdjusterOption() throws Exception {
Root root = new Root(
"root1",
new Child("child1", 5, 25),
new NullableChild("child2")
);
Root sanitized = apply(root);
assertThat(sanitized.getChild().getMax()).isEqualTo(24);
}
private Root apply(Root root) {
Optional<Object> sanitizedOpt = new AnnotationBasedSanitizer(new StandardEvaluationContext(), t -> true).apply(root);
assertThat(sanitizedOpt).isPresent();
return (Root) sanitizedOpt.get();
}
} | 611 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/environment/internal/MyCachingEnvironmentTest.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.environment.internal;
import java.util.Collections;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.titus.common.environment.MyEnvironments;
import com.netflix.titus.common.environment.MyMutableEnvironment;
import org.junit.Test;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
public class MyCachingEnvironmentTest {
private final DefaultRegistry registry = new DefaultRegistry();
private final MyMutableEnvironment source = MyEnvironments.newMutableFromMap(Collections.emptyMap());
private final MyCachingEnvironment cache = new MyCachingEnvironment(
"junit",
source,
1,
registry
);
@Test
public void testRefresh() {
source.setProperty("key1", "value1");
assertThat(cache.getProperty("key1")).contains("value1");
source.setProperty("key1", "value2");
await().until(() -> cache.getProperty("key1").contains("value2"));
}
@Test
public void testMissingProperty() {
assertThat(cache.getProperty("key1")).isNull();
source.setProperty("key1", "value1");
await().until(() -> cache.getProperty("key1").contains("value1"));
}
@Test
public void testRemovedProperty() {
source.setProperty("key1", "value1");
assertThat(cache.getProperty("key1")).contains("value1");
source.removeProperty("key1");
await().until(() -> cache.getProperty("key1") == null);
}
}
| 612 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/SeqNumberDataGeneratorsTest.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.data.generator.internal;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SeqNumberDataGeneratorsTest {
@Test
public void testIntAscending() throws Exception {
List<int[]> sequences = DataGenerator.sequenceOfAscendingIntegers(5, -10, 10).toList(3);
for (int[] seq : sequences) {
for (int i = 1; i < seq.length; i++) {
assertThat(seq[i - 1] <= seq[i]).isTrue();
}
}
}
} | 613 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/UnionBuilderDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.netflix.titus.common.data.generator.DataGenerator;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static org.assertj.core.api.Assertions.assertThat;
public class UnionBuilderDataGeneratorTest {
@Test
public void testUnionBuilder() throws Exception {
DataGenerator<String> values = DataGenerator.unionBuilder(SampleBuilder::new)
.combine(items("a", "b", "a", "b"), SampleBuilder::withA)
.combine(items("x", "y", "z"), SampleBuilder::withB)
.combine(items("1", "2", "3", "4"), SampleBuilder::withC)
.map(SampleBuilder::build);
List<String> expected = Stream.of("a", "b", "a", "b").
flatMap(i1 -> Stream.of("x", "y", "z").map(i2 -> i1 + i2))
.flatMap(i12 -> Stream.of("1", "2", "3", "4").map(i3 -> i12 + i3))
.collect(Collectors.toList());
List<String> actual = values.toList();
assertThat(actual).hasSize(expected.size());
assertThat(actual).containsAll(expected);
}
static class SampleBuilder {
private String a;
private String b;
private String c;
SampleBuilder withA(String a) {
this.a = a;
return this;
}
SampleBuilder withB(String b) {
this.b = b;
return this;
}
SampleBuilder withC(String c) {
this.c = c;
return this;
}
String build() {
return a + b + c;
}
}
} | 614 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/CombinationsTest.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.data.generator.internal;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class CombinationsTest {
private static final List<int[]> COMBINATIONS_2x2 = asList(new int[]{0, 0}, new int[]{0, 1}, new int[]{1, 0}, new int[]{1, 1});
private static final List<int[]> COMBINATIONS_3x3 = asList(
new int[]{0, 0}, new int[]{0, 1}, new int[]{0, 2},
new int[]{1, 0}, new int[]{1, 1}, new int[]{1, 2},
new int[]{2, 0}, new int[]{2, 1}, new int[]{2, 2}
);
@Test
public void testInit() throws Exception {
Combinations combinations = Combinations.newInstance(2).resize(asList(2, 2));
assertThat(combinations.getSize()).isEqualTo(4);
List<int[]> tuples = take(combinations, 4);
assertThat(tuples).containsAll(COMBINATIONS_2x2);
}
@Test
public void testResize() throws Exception {
Combinations combinations = Combinations.newInstance(2)
.resize(asList(2, 2))
.resize(asList(3, 3));
List<int[]> tuples = take(combinations, 9);
assertThat(tuples.get(0)).isIn(COMBINATIONS_2x2);
assertThat(tuples.get(1)).isIn(COMBINATIONS_2x2);
assertThat(tuples).containsAll(COMBINATIONS_3x3);
}
private List<int[]> take(Combinations combinations, int count) {
List<int[]> tuples = new ArrayList<>();
for (int i = 0; i < count; i++) {
tuples.add(combinations.combinationAt(i));
}
return tuples;
}
} | 615 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/FilterDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class FilterDataGeneratorTest {
@Test
public void testFilter() throws Exception {
DataGenerator<List<Long>> filteredBatch = DataGenerator.range(0, 9).filter(v -> v % 2 == 0).batch(5);
assertThat(filteredBatch.getValue()).contains(0L, 2L, 4L, 6L, 8L);
assertThat(filteredBatch.isClosed()).isFalse();
assertThat(filteredBatch.apply().isClosed()).isTrue();
}
} | 616 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/ConcatDataGeneratorTest.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.data.generator.internal;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static org.assertj.core.api.Assertions.assertThat;
public class ConcatDataGeneratorTest {
@Test
public void testConcat() throws Exception {
assertThat(items("a", "b").concat(items("c", "d")).toList()).containsExactly("a", "b", "c", "d");
}
} | 617 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/BindDataGeneratorTest.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.data.generator.internal;
import java.util.HashSet;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.bind;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static org.assertj.core.api.Assertions.assertThat;
public class BindDataGeneratorTest {
@Test
public void testBind() throws Exception {
assertThat(bind(items("a", "b", "c", "d"), items(1, 2).loop()).toList()).contains(
Pair.of("a", 1),
Pair.of("b", 2),
Pair.of("c", 1),
Pair.of("d", 2)
);
}
@Test
public void testBuilder() throws Exception {
DataGenerator<String> values = DataGenerator.bindBuilder(SampleBuilder::new)
.bind(items("a", "b", "a", "b"), SampleBuilder::withA)
.bind(items("x", "y", "z").loop(), SampleBuilder::withB)
.bind(items("1", "2", "3", "4").loop(), SampleBuilder::withC)
.map(SampleBuilder::build);
List<String> all = values.toList();
assertThat(all).hasSize(4);
assertThat(new HashSet<>(all)).hasSize(2);
}
static class SampleBuilder {
private String a;
private String b;
private String c;
SampleBuilder withA(String a) {
this.a = a;
return this;
}
SampleBuilder withB(String b) {
this.b = b;
return this;
}
SampleBuilder withC(String c) {
this.c = c;
return this;
}
String build() {
return a + b + c;
}
}
} | 618 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/BatchDataGeneratorTest.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.data.generator.internal;
import java.util.ArrayList;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class BatchDataGeneratorTest {
@Test
public void testBatches() throws Exception {
DataGenerator<List<Long>> batchGen = DataGenerator.range(0, 10).batch(2);
Pair<DataGenerator<List<Long>>, List<List<Long>>> result = take(batchGen, 5);
DataGenerator<List<Long>> lastGen = result.getLeft();
List<List<Long>> values = result.getRight();
assertThat(lastGen.isClosed()).isTrue();
assertThat(values).contains(asList(0L, 1L), asList(2L, 3L), asList(4L, 5L), asList(6L, 7L), asList(8L, 9L));
}
private <T> Pair<DataGenerator<T>, List<T>> take(DataGenerator<T> generator, int count) {
List<T> result = new ArrayList<>();
DataGenerator<T> nextG = generator;
for (int i = 0; i < count; i++) {
result.add(nextG.getValue());
nextG = nextG.apply();
}
return Pair.of(nextG, result);
}
} | 619 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/RandomDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.range;
import static org.assertj.core.api.Assertions.assertThat;
public class RandomDataGeneratorTest {
@Test
public void testRandom() throws Exception {
List<Long> allItems = range(0, 20).random(0.5, 10).toList();
assertThat(allItems.subList(0, 5)).isSubsetOf(range(0, 10).toList());
assertThat(allItems).containsAll(range(0, 20).toList());
}
} | 620 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/SeqDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import com.netflix.titus.common.util.tuple.Pair;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.sequenceOfString;
import static org.assertj.core.api.Assertions.assertThat;
public class SeqDataGeneratorTest {
@Test
public void testSeq() throws Exception {
List<String> values = sequenceOfString('a', 2, context -> {
char c = context;
c++;
return Pair.of(c, context);
}).limit(2).toList();
assertThat(values).contains("ab", "cd");
}
} | 621 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/ZipDataGeneratorTest.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.data.generator.internal;
import com.netflix.titus.common.util.tuple.Pair;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.zip;
import static org.assertj.core.api.Assertions.assertThat;
public class ZipDataGeneratorTest {
@Test
public void testZip() throws Exception {
assertThat(zip(items("a", "b"), items(1, 2, 3)).toList()).contains(Pair.of("a", 1), Pair.of("b", 2));
}
} | 622 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/MergeDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.merge;
import static org.assertj.core.api.Assertions.assertThat;
public class MergeDataGeneratorTest {
@Test
public void testMerge() throws Exception {
List<String> items = merge(items("a", "b"), items("c", "d")).toList();
assertThat(items).contains("a", "b", "c", "d");
}
} | 623 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/LimitDataGeneratorTest.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.data.generator.internal;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class LimitDataGeneratorTest {
@Test
public void testLimit() throws Exception {
DataGenerator<Long> genWithLimit = DataGenerator.range(0, 9).limit(2);
DataGenerator<List<Long>> batchGen = genWithLimit.batch(2);
assertThat(batchGen.getValue()).isEqualTo(asList(0L, 1L));
assertThat(batchGen.apply().isClosed()).isTrue();
}
} | 624 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/LoopedDataGeneratorTest.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.data.generator.internal;
import org.junit.Test;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static org.assertj.core.api.Assertions.assertThat;
public class LoopedDataGeneratorTest {
@Test
public void testLoop() throws Exception {
assertThat(items("a", "b").loop().limit(4).toList()).containsExactly("a", "b", "a", "b");
}
@Test
public void testLoopWithIndex() throws Exception {
assertThat(items("a", "b").loop((v, idx) -> v + idx).limit(4).toList()).containsExactly("a0", "b0", "a1", "b1");
}
} | 625 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/data/generator/internal/UnionDataGeneratorTest.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.data.generator.internal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.netflix.titus.common.data.generator.DataGenerator;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class UnionDataGeneratorTest {
@Test
public void testUnion() throws Exception {
List<String> words = asList("a", "b", "c", "d", "e");
DataGenerator<List<String>> batchGen = DataGenerator.union(
DataGenerator.items(words),
DataGenerator.range(0, 5),
(t, n) -> t + '-' + n
).batch(25);
List<String> data = batchGen.getValue();
data.sort(Comparator.naturalOrder());
List<String> expected = words.stream().flatMap(w -> {
List<String> items = new ArrayList<>();
for (int i = 0; i < 5; i++) {
items.add(w + '-' + i);
}
return items.stream();
}).collect(Collectors.toList());
assertThat(data).containsAll(expected);
assertThat(batchGen.apply().isClosed()).isTrue();
}
} | 626 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/jhiccup/HiccupMeterTest.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.jhiccup;
import com.netflix.spectator.api.DefaultRegistry;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class HiccupMeterTest {
private final HiccupRecorderConfiguration config = mock(HiccupRecorderConfiguration.class);
@Before
public void setUp() throws Exception {
when(config.getTaskExecutionDeadlineMs()).thenReturn(1000L);
when(config.getReportingIntervalMs()).thenReturn(1000L);
}
@Test
public void testStartupShutdownSequence() throws Exception {
HiccupMeter hiccupMeter = new HiccupMeter(config, new DefaultRegistry());
hiccupMeter.shutdown();
}
} | 627 |
0 | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/test/java/com/netflix/titus/common/jhiccup/sensor/RxJavaComputationSchedulerSensorTest.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.jhiccup.sensor;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.titus.common.jhiccup.HiccupRecorderConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RxJavaComputationSchedulerSensorTest {
private static final long PROBING_INTERVAL_MS = 10;
private static final long PROGRESS_CHECK_INTERVAL_MS = 10;
private final HiccupRecorderConfiguration configuration = mock(HiccupRecorderConfiguration.class);
private RxJavaComputationSchedulerSensor sensor;
private final AtomicReference<StackTraceElement[]> blockedThreadRef = new AtomicReference<>();
@Before
public void setUp() {
when(configuration.getTaskExecutionDeadlineMs()).thenReturn(100L);
sensor = new RxJavaComputationSchedulerSensor(configuration, PROBING_INTERVAL_MS, PROGRESS_CHECK_INTERVAL_MS, new DefaultRegistry()) {
@Override
protected void reportBlockedThread(Thread blockedThread) {
blockedThreadRef.set(blockedThread.getStackTrace());
}
};
}
@After
public void tearDown() {
if (sensor != null) {
sensor.shutdown();
}
}
@Test
public void testExpectedNumberOfComputationThreadsIsDetected() {
assertThat(sensor.getLastPercentile(99.5).keySet()).hasSize(Runtime.getRuntime().availableProcessors());
}
@Test(timeout = 30_000)
public void testLongRunningTask() throws Exception {
Exception lastError = null;
for (int multiplier = 2; multiplier < 5; multiplier++) {
try {
tryTestLongRunningTask(multiplier);
lastError = null;
break;
} catch (Exception e) {
lastError = e;
}
}
if (lastError != null) {
throw lastError;
}
}
// To avoid a long pause in the unit test, we try first with a short delay, and the risk of detection miss.
// If the latter happens, the delay is increased and the test is repeated.
private void tryTestLongRunningTask(int delayMultiplier) throws InterruptedException {
Scheduler.Worker worker = Schedulers.computation().createWorker();
CountDownLatch latch = new CountDownLatch(1);
try {
worker.schedule(() -> {
try {
Thread.sleep(PROBING_INTERVAL_MS * delayMultiplier);
} catch (InterruptedException ignore) {
}
latch.countDown();
});
latch.await();
} finally {
worker.unsubscribe();
}
// Now give some time for pending tasks to complete
await().pollDelay(1, TimeUnit.MILLISECONDS)
.timeout(2 * delayMultiplier * PROBING_INTERVAL_MS, TimeUnit.MILLISECONDS)
.until(() -> {
Map<String, Long> percentiles = sensor.getLastPercentile(99.99);
long paused = percentiles.entrySet().stream().filter(e -> e.getValue() >= PROBING_INTERVAL_MS).count();
return paused > 0;
});
}
@Test(timeout = 30_000)
public void testBlockedThreadsDetection() throws Exception {
Scheduler.Worker worker = Schedulers.computation().createWorker();
CountDownLatch latch = new CountDownLatch(1);
try {
worker.schedule(() -> {
try {
while (blockedThreadRef.get() == null) {
Thread.sleep(1);
}
} catch (InterruptedException ignore) {
}
latch.countDown();
});
latch.await();
} finally {
worker.unsubscribe();
}
Optional<StackTraceElement> ourElement = Arrays.stream(blockedThreadRef.get())
.filter(l -> l.getClassName().contains(RxJavaComputationSchedulerSensorTest.class.getSimpleName()))
.findFirst();
assertThat(ourElement).isPresent();
}
} | 628 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/ExceptionExt.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;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
*
*/
public class ExceptionExt {
public interface RunnableWithExceptions {
void run() throws Exception;
}
public static <T> void silent(T object, Consumer<T> invocation) {
if (object == null) {
return;
}
try {
invocation.accept(object);
} catch (Throwable e) {
// Ignore
}
}
public static void silent(RunnableWithExceptions runnable) {
try {
runnable.run();
} catch (Throwable e) {
// Ignore
}
}
public static Optional<Throwable> doCatch(Runnable action) {
try {
action.run();
} catch (Throwable e) {
return Optional.of(e);
}
return Optional.empty();
}
public static RuntimeException rethrow(Throwable e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
if (e instanceof Error) {
throw (Error) e;
}
throw new UncheckedExceptionWrapper(e);
}
public static <T> T rethrow(Callable<T> func) {
try {
return func.call();
} catch (Throwable e) {
rethrow(e);
return null;
}
}
public static void rethrow(RunnableWithExceptions func) {
try {
func.run();
} catch (Throwable e) {
rethrow(e);
}
}
public static void rethrow(RunnableWithExceptions func, Consumer<Throwable> onErrorHandler) {
try {
func.run();
} catch (Throwable e) {
try {
onErrorHandler.accept(e);
} catch (Exception e2) {
// Ignore
}
rethrow(e);
}
}
public static <T> Optional<T> doTry(Supplier<T> callable) {
try {
return Optional.ofNullable(callable.get());
} catch (Throwable e) {
return Optional.empty();
}
}
public static String toMessage(Throwable error) {
return error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage();
}
public static String toMessageChain(Throwable error) {
StringBuilder sb = new StringBuilder();
Throwable current = error;
while (current != null) {
String message = current.getMessage() != null ? current.getMessage() : "<no_message>";
sb.append('(').append(current.getClass().getSimpleName()).append(')').append(' ').append(message);
if (current.getCause() != null) {
sb.append(" -CAUSED BY-> ");
}
current = current.getCause();
}
return sb.toString();
}
public static Throwable unpackRuntimeException(Throwable exception) {
Throwable current = exception;
while (current instanceof RuntimeException && current.getCause() != null) {
current = current.getCause();
}
return current;
}
public static class UncheckedExceptionWrapper extends RuntimeException {
private UncheckedExceptionWrapper(Throwable cause) {
super(cause);
}
}
}
| 629 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/TimeSeriesData.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;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Simple, concurrent time series data collector. Each data point consists of a value and a timestamp. The amount
* of data to keep is controlled by a retention time. Data older than the retention time period are removed from
* the data set. The class provides an aggregate of all currently held values. The raw values can be adjusted
* by the user provided adjuster function. For example, the values can be weighted based on how old they are.
*/
public class TimeSeriesData {
private static final Pair<Double, Long> CLEANUP_MARKER = Pair.of(-1.0, 0L);
private static final Pair<Double, Long> NOTHING = Pair.of(0.0, 0L);
private final long retentionMs;
private final long stepMs;
private final BiFunction<Double, Long, Double> adjuster;
private final Clock clock;
private final Queue<Pair<Double, Long>> offers = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedDeque<Pair<Double, Long>> data = new ConcurrentLinkedDeque<>();
private final AtomicReference<Pair<Double, Long>> lastAggregate;
private final AtomicInteger wipMarker = new AtomicInteger();
/**
* Constructor.
*
* @param retentionMs data retention time (data older than that are removed from the data set)
* @param stepMs computation accuracy with respect to time (important when the adjuster function uses elapsed time in the formula)
* @param adjuster a value adjuster function, taking as an argument the value itself, and the amount of time from its creation
*/
public TimeSeriesData(long retentionMs,
long stepMs,
BiFunction<Double, Long, Double> adjuster,
Clock clock) {
this.retentionMs = retentionMs;
this.stepMs = stepMs;
this.adjuster = adjuster;
this.clock = clock;
this.lastAggregate = new AtomicReference<>(NOTHING);
}
public void add(double value, long timestamp) {
long now = clock.wallTime();
if (now - retentionMs < timestamp) {
offers.add(Pair.of(value, timestamp));
process(now);
}
}
public void clear() {
if (!data.isEmpty()) {
offers.add(CLEANUP_MARKER);
process(clock.wallTime());
}
}
public double getAggregatedValue() {
if (data.isEmpty()) {
return 0.0;
}
long now = clock.wallTime();
if (now - lastAggregate.get().getRight() >= stepMs) {
if (!process(now)) {
return computeAggregatedValue(now).getLeft();
}
}
return lastAggregate.get().getLeft();
}
private boolean process(long now) {
if (wipMarker.getAndIncrement() != 0) {
return false;
}
do {
boolean changed = false;
// Remove expired entries
long expiredTimestamp = now - retentionMs;
for (Pair<Double, Long> next; (next = data.peek()) != null && next.getRight() <= expiredTimestamp; ) {
data.poll();
changed = true;
}
// Add new entries
Pair<Double, Long> offer;
while ((offer = offers.poll()) != null) {
long latest = data.isEmpty() ? 0 : data.getLast().getRight();
if (offer == CLEANUP_MARKER) {
data.clear();
changed = true;
} else if (offer.getRight() >= latest) {
data.add(offer);
changed = true;
}
}
// Recompute the aggregated value if needed
if (changed || now - lastAggregate.get().getRight() >= stepMs) {
lastAggregate.set(computeAggregatedValue(now));
}
} while (wipMarker.decrementAndGet() != 0);
return true;
}
private Pair<Double, Long> computeAggregatedValue(long now) {
if (data.isEmpty()) {
return NOTHING;
}
double sum = 0;
for (Pair<Double, Long> next : data) {
sum += adjuster.apply(next.getLeft(), now - next.getRight());
}
return Pair.of(sum, now);
}
}
| 630 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/NetworkExt.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;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A set of network related functions.
*/
public class NetworkExt {
private static final Logger logger = LoggerFactory.getLogger(NetworkExt.class);
public static final String IP4_LOOPBACK = "127.0.0.1";
public static final String IP6_LOOPBACK = "0:0:0:0:0:0:0:1";
private static final AtomicReference<Optional<String>> resolvedHostNameRef = new AtomicReference<>();
private static final AtomicReference<Optional<List<String>>> resolvedLocalIPsRef = new AtomicReference<>();
public static int findUnusedPort() {
int port;
try {
ServerSocket serverSocket = new ServerSocket(0);
port = serverSocket.getLocalPort();
serverSocket.close();
} catch (IOException e) {
throw new IllegalStateException("Unused port allocation failure", e);
}
return port;
}
/**
* Return resolved local host name. The value is cached, so actual resolution happens only during the first call.
*
* @return host name or {@link Optional#empty()} if resolution failed.
*/
public static Optional<String> getHostName() {
if (resolvedHostNameRef.get() == null) {
try {
resolvedHostNameRef.set(Optional.of(resolveHostName()));
} catch (Exception e) {
logger.error("Cannot resolve local host name");
resolvedHostNameRef.set(Optional.empty());
}
}
return resolvedHostNameRef.get();
}
/**
* Resolve host name. No caching mechanism is implemented in this method, so these calls are expensive.
* Use {@link #getHostName()} for faster operation.
*
* @return host name
* @throws RuntimeException if host name resolution fails
*/
public static String resolveHostName() {
// Try first hostname system call, to avoid potential
// issues with InetAddress.getLocalHost().getHostName()
try {
Process process = Runtime.getRuntime().exec("hostname");
InputStream input = process.getInputStream();
StringBuilder sb = new StringBuilder();
byte[] bytes = new byte[256];
int len;
while ((len = input.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len, Charset.defaultCharset()));
}
if (process.exitValue() == 0) {
return sb.toString().trim();
}
} catch (Exception ignore) {
// Ignore this exception, we will try different way
}
// Try InetAddress.getLocalHost().getHostName()
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
throw new RuntimeException("cannot resolve local host name", e);
}
}
/**
* Returns true if the given IP is a loopback address.
*/
public static boolean isLoopbackIP(String ip) {
return ip.equals(IP4_LOOPBACK) || ip.startsWith(IP6_LOOPBACK);
}
/**
* Returns true if the given IP is IPv6.
*/
public static boolean isIPv6(String ip) {
return ip.indexOf(':') != -1;
}
/**
* Return resolved local IP addresses. The value is cached, so actual resolution happens only during the first call.
*
* @return IP address list or {@link Optional#empty()} if resolution failed.
*/
public static Optional<List<String>> getLocalIPs(boolean ipv4Only) {
if (resolvedLocalIPsRef.get() == null) {
try {
resolvedLocalIPsRef.set(Optional.of(resolveLocalIPs(ipv4Only)));
} catch (Exception e) {
logger.error("Cannot resolve local IP addresses");
resolvedLocalIPsRef.set(Optional.empty());
}
}
return resolvedLocalIPsRef.get();
}
/**
* @deprecated For backward compatibility we restrict the default local addresses to IPv4.
*/
public static Optional<List<String>> getLocalIPs() {
return getLocalIPs(true);
}
/**
* Returns all local IP addresses (IPv4 and IPv6).
*
* @throws RuntimeException if resolution fails
*/
public static List<String> resolveLocalIPs(boolean ipv4Only) {
ArrayList<String> addresses = new ArrayList<>();
try {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress address = inetAddresses.nextElement();
if (address instanceof Inet6Address) {
if (!ipv4Only) {
addresses.add(toIpV6AddressName((Inet6Address) address));
}
} else {
addresses.add(address.getHostAddress());
}
}
}
} catch (SocketException e) {
throw new RuntimeException("Cannot resolve local network addresses", e);
}
return Collections.unmodifiableList(addresses);
}
public static String toIPv4(long addressLong) {
return Long.toString(addressLong >> 24 & 0xFF) + '.' +
Long.toString(addressLong >> 16 & 0xFF) + '.' +
Long.toString(addressLong >> 8 & 0xFF) + '.' +
Long.toString(addressLong & 0xFF);
}
public static String toIpV6AddressName(Inet6Address inet6Address) {
String address = inet6Address.getHostAddress();
int idx = address.lastIndexOf('%');
return idx < 0 ? address : address.substring(0, idx);
}
public static long toNetworkBitMask(int maskLength) {
Preconditions.checkArgument(maskLength > 0 && maskLength <= 32, "Mask length must be in (0, 32> range: " + maskLength);
long subnet = 0;
for (int i = 0; i < maskLength; i++) {
subnet = (subnet << 1) | 1;
}
return 0xFFFFFFFFL ^ subnet;
}
public static boolean matches(String ipAddress, NetworkAddress networkAddress) {
return matches(toBits(ipAddress), networkAddress);
}
public static boolean matches(long ipAddress, NetworkAddress networkAddress) {
return (ipAddress & networkAddress.getMask()) == networkAddress.getAddressLong();
}
public static Function<String, Boolean> buildNetworkMatchPredicate(List<String> cdirs) {
List<NetworkAddress> networkAddresses = cdirs.stream().map(NetworkExt::parseCDIR).collect(Collectors.toList());
return address -> {
if (!isIpV4(address)) {
return false;
}
long addressBits = toBits(address);
for (NetworkAddress networkAddress : networkAddresses) {
if (matches(addressBits, networkAddress)) {
return true;
}
}
return false;
};
}
public static NetworkAddress parseCDIR(String cdir) {
Matcher matcher = IPV4_CDIR_RE.matcher(cdir);
Preconditions.checkArgument(matcher.matches(), "Expected network address in CDIR format, but got " + cdir);
return new NetworkAddress(matcher.group(1), Integer.parseInt(matcher.group(2)));
}
private static final Pattern IPV4_CDIR_RE = Pattern.compile("(\\d+[.]\\d+[.]\\d+[.]\\d+)/(\\d+)");
private static final Pattern IPV4_RE = Pattern.compile("(\\d+)[.](\\d+)[.](\\d+)[.](\\d+)");
/**
* Limited to IPv4.
*/
public static class NetworkAddress {
private final String address;
private final int maskLength;
private final long mask;
private final long addressLong;
private NetworkAddress(String address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
this.mask = toNetworkBitMask(maskLength);
this.addressLong = toBits(address) & mask;
}
public String getAddress() {
return address;
}
public int getMaskLength() {
return maskLength;
}
public long getMask() {
return mask;
}
public long getAddressLong() {
return addressLong;
}
}
public static boolean isIpV4(String address) {
return parseIpV4(address).isPresent();
}
public static long toBits(String ipv4Address) {
Optional<int[]> parsedOpt = parseIpV4(ipv4Address);
if (!parsedOpt.isPresent()) {
throw new IllegalArgumentException("Not an IPv4 address: " + ipv4Address);
}
int[] bytes = parsedOpt.get();
return ((bytes[3] << 8 | bytes[2]) << 8 | bytes[1]) << 8 | bytes[0];
}
private static Optional<int[]> parseIpV4(String address) {
Matcher matcher = IPV4_RE.matcher(address);
if (!matcher.matches()) {
return Optional.empty();
}
int b3 = Integer.parseInt(matcher.group(1));
int b2 = Integer.parseInt(matcher.group(2));
int b1 = Integer.parseInt(matcher.group(3));
int b0 = Integer.parseInt(matcher.group(4));
if (b3 < 0 || b3 > 255 || b2 < 0 || b2 > 255 | b1 < 0 || b1 > 255 || b0 < 0 || b0 > 255) {
return Optional.empty();
}
return Optional.of(new int[]{b0, b1, b2, b3});
}
}
| 631 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/LoggingExt.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;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LoggingExt {
private static final Logger logger = LoggerFactory.getLogger(LoggingExt.class);
private LoggingExt() {
}
/**
* Execute an action with logging its execution time when it completes or fails.
*/
public static <T> T timed(String message, Supplier<T> fun) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Logger tLogger;
if (stackTrace.length > 2) {
tLogger = LoggerFactory.getLogger(stackTrace[2].getClassName());
} else {
tLogger = logger;
}
long startTime = System.currentTimeMillis();
try {
T result = fun.get();
tLogger.info("{} finished after {}[ms]", message, System.currentTimeMillis() - startTime);
return result;
} catch (Exception e) {
tLogger.info("{} failed after {}[ms]", message, System.currentTimeMillis() - startTime);
throw e;
}
}
}
| 632 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/StringExt.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;
import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import com.netflix.titus.common.util.tuple.Either;
import static java.util.Arrays.asList;
/**
* A set of string manipulation related functions.
*/
public final class StringExt {
public final static Pattern COMMA_SPLIT_RE = Pattern.compile("\\s*,\\s*");
public final static Pattern DOT_SPLIT_RE = Pattern.compile("\\s*\\.\\s*");
public final static Pattern SEMICOLON_SPLIT_RE = Pattern.compile("\\s*;\\s*");
public final static Pattern COLON_SPLIT_RE = Pattern.compile("\\s*:\\s*");
public final static Pattern EQUAL_SPLIT_RE = Pattern.compile("\\s*=\\s*");
// For each enum type, contains a map with keys being enum names in lower case, and the values are their
// corresponding enum values.
private static ConcurrentMap<Class<? extends Enum>, Map<String, Object>> ENUM_NAMES_MAP = new ConcurrentHashMap<>();
private StringExt() {
}
/**
* Return true if the string value is not null, and it is not an empty string.
*/
public static boolean isNotEmpty(String s) {
return s != null && !s.isEmpty();
}
/**
* Check if the given string is a valid UUID value.
*/
public static boolean isUUID(String s) {
try {
UUID.fromString(s);
} catch (Exception ignore) {
return false;
}
return true;
}
/**
* Return true if the string value is null or an empty string.
*/
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
/**
* Return string with trimmed whitespace characters. If the argument is null, return empty string.
*/
public static String safeTrim(String s) {
if (s == null || s.isEmpty()) {
return "";
}
String trimmed = s.trim();
return trimmed.isEmpty() ? "" : trimmed;
}
public static String nonNull(String value) {
return value == null ? "" : value;
}
/**
* Return prefix until first occurrence of the end marker.
*/
public static String takeUntil(String value, String endMarker) {
if (value == null) {
return "";
}
if (endMarker == null) {
return value;
}
if (value.length() < endMarker.length()) {
return value;
}
int idx = value.indexOf(endMarker);
if (idx < 0) {
return value;
}
return value.substring(0, idx);
}
/**
* Pass a string value to the consumer if it is not null, and non-empty.
*/
public static void applyIfNonEmpty(String value, Consumer<String> consumer) {
if (value != null) {
if (!value.isEmpty()) {
consumer.accept(value);
}
}
}
/**
* Execute an action if the argument is an empty string.
*/
public static void runIfEmpty(String value, Runnable action) {
if (isEmpty(value)) {
action.run();
}
}
/**
* Pass a trimmed string value to the consumer if it is not null, and non-empty.
*/
public static void trimAndApplyIfNonEmpty(String value, Consumer<String> consumer) {
if (value != null) {
String trimmed = value.trim();
if (!trimmed.isEmpty()) {
consumer.accept(trimmed);
}
}
}
/**
* Concatenate strings from the given string collection, separating the items with the given delimiter.
*/
public static String concatenate(Collection<String> stringCollection, String delimiter) {
if (stringCollection == null) {
return null;
}
Iterator<String> it = stringCollection.iterator();
if (!it.hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder(it.next());
while (it.hasNext()) {
sb.append(delimiter);
sb.append(it.next());
}
return sb.toString();
}
/**
* Concatenate object values converted to string using provided mapping function, separating the items with the given delimiter.
*/
public static <T> String concatenate(T[] array, String delimiter, Function<T, String> mapping) {
if (array == null) {
return null;
}
if (array.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder(mapping.apply(array[0]));
for (int i = 1; i < array.length; i++) {
sb.append(delimiter);
sb.append(mapping.apply(array[i]));
}
return sb.toString();
}
/**
* Concatenate object values converted to string, separating the items with the given delimiter.
*/
public static String concatenate(Object[] array, String delimiter) {
return concatenate(array, delimiter, Object::toString);
}
/**
* Concatenate enum values.
*/
public static <E extends Enum> String concatenate(E[] array, String delimiter) {
return concatenate(array, delimiter, Enum::name);
}
/**
* Concatenate enum values.
*/
public static <E extends Enum> String concatenate(Class<E> enumType, String delimiter, Function<E, Boolean> filter) {
StringBuilder sb = new StringBuilder();
for (E value : enumType.getEnumConstants()) {
if (filter.apply(value)) {
sb.append(value).append(delimiter);
}
}
if (sb.length() == 0) {
return "";
}
sb.setLength(sb.length() - delimiter.length());
return sb.toString();
}
public static String getNonEmptyOrDefault(String value, String defaultValue) {
return isNotEmpty(value) ? value : defaultValue;
}
/**
* Given sequence of string values, return the first one that is not empty (see {@link #isNotEmpty(String)} or
* {@link Optional#empty()}.
*/
public static Optional<String> firstNonEmpty(String... values) {
for (String v : values) {
if (isNotEmpty(v)) {
return Optional.of(v);
}
}
return Optional.empty();
}
/**
* Trim list values, or remove them if a value is an empty string or null.
*/
public static List<String> trim(List<String> list) {
List<String> result = new ArrayList<>();
for (String value : list) {
if (isNotEmpty(value)) {
String trimmed = value.trim();
if (trimmed.length() > 0) {
result.add(trimmed);
}
}
}
return result;
}
/**
* Returns pattern for splitting string by ',' separator optionally surrounded by spaces.
*/
public static Pattern getCommaSeparator() {
return COMMA_SPLIT_RE;
}
/**
* Returns pattern for splitting string by '.' separator optionally surrounded by spaces.
*/
public static Pattern getDotSeparator() {
return DOT_SPLIT_RE;
}
/**
* Returns pattern for splitting string by ';' separator optionally surrounded by spaces.
*/
public static Pattern getSemicolonSeparator() {
return SEMICOLON_SPLIT_RE;
}
/**
* Returns a list of comma separated values from the parameter. The white space characters around each value
* is removed as well.
*/
public static List<String> splitByComma(String value) {
if (!isNotEmpty(value)) {
return Collections.emptyList();
}
String trimmed = value.trim();
return trimmed.isEmpty() ? Collections.emptyList() : asList(COMMA_SPLIT_RE.split(trimmed));
}
/**
* See {@link #splitByComma(String)}.
*/
public static Set<String> splitByCommaIntoSet(String value) {
if (!isNotEmpty(value)) {
return Collections.emptySet();
}
String trimmed = value.trim();
return trimmed.isEmpty() ? Collections.emptySet() : CollectionsExt.asSet(COMMA_SPLIT_RE.split(trimmed));
}
/**
* Returns a list of dot separated values from the parameter. The white space characters around each value
* is removed as well.
*/
public static List<String> splitByDot(String value) {
if (!isNotEmpty(value)) {
return Collections.emptyList();
}
String trimmed = value.trim();
return trimmed.isEmpty() ? Collections.emptyList() : asList(DOT_SPLIT_RE.split(trimmed));
}
/**
* Parse enum name ignoring case.
*/
public static <E extends Enum<E>> E parseEnumIgnoreCase(String enumName, Class<E> enumType) {
String trimmed = safeTrim(enumName);
if (isEmpty(trimmed)) {
throw new IllegalArgumentException("Empty string passed as enum name");
}
Map<String, Object> enumLowerCaseNameMap = getEnumLowerCaseNameMap(enumType);
E result = (E) enumLowerCaseNameMap.get(trimmed.toLowerCase());
if (result == null) {
throw new IllegalArgumentException("Invalid enum value " + trimmed);
}
return result;
}
/**
* Parse a comma separated list of enum values.
*
* @throws IllegalArgumentException if the passed names do not represent valid enum values
*/
public static <E extends Enum<E>> List<E> parseEnumListIgnoreCase(String enumNames, Class<E> enumType) {
return parseEnumListIgnoreCase(enumNames, enumType, null);
}
/**
* Parse a comma separated list of enum values. A name can denote a set of values, that is replaced during parsing process.
* Argument to 'groupings' function is in lower case.
*
* @throws IllegalArgumentException if the passed names do not represent valid enum values
*/
public static <E extends Enum<E>> List<E> parseEnumListIgnoreCase(String enumNames, Class<E> enumType, Function<String, List<E>> groupings) {
if (isEmpty(enumNames)) {
return Collections.emptyList();
}
List<String> names = splitByComma(enumNames);
if (names.isEmpty()) {
return Collections.emptyList();
}
Map<String, Object> enumLowerCaseNameMap = getEnumLowerCaseNameMap(enumType);
List<E> result = new ArrayList<>();
for (String name : names) {
String lowerCaseName = name.toLowerCase();
E enumName = (E) enumLowerCaseNameMap.get(lowerCaseName);
if (enumName == null && groupings != null) {
List<E> valueSet = groupings.apply(lowerCaseName);
if (valueSet != null) {
result.addAll(valueSet);
continue;
}
}
if (enumName == null) {
throw new IllegalArgumentException("Invalid enum value " + name);
}
result.add(enumName);
}
return result;
}
/**
* Given a text value in format "key1=value1 <separator> key2=value2", convert it to a map.
*/
public static <A> Map<String, A> parseKeyValueList(String text, Pattern entrySeparator, Pattern pairSeparator,
BiFunction<A, String, A> accumulator) {
String trimmed = safeTrim(text);
if (isEmpty(trimmed)) {
return Collections.emptyMap();
}
List<String> keyValuePairs = asList(entrySeparator.split(trimmed));
if (keyValuePairs.isEmpty()) {
return Collections.emptyMap();
}
Map<String, A> result = new HashMap<>();
for (String keyValuePair : keyValuePairs) {
int idx = indexOf(pairSeparator, keyValuePair);
String key;
String value;
if (idx == -1) {
key = keyValuePair;
value = "";
} else if (idx == keyValuePair.length() - 1) {
key = keyValuePair.substring(0, idx);
value = "";
} else {
key = keyValuePair.substring(0, idx);
value = keyValuePair.substring(idx + 1);
}
result.put(key, accumulator.apply(result.get(key), value));
}
return result;
}
/**
* Given a text value in format "key1:value1,key2:value2", convert it to a map. If there are multiple values
* for the same key, the last one wins.
*/
public static Map<String, String> parseKeyValueList(String text) {
return parseKeyValueList(text, COMMA_SPLIT_RE, COLON_SPLIT_RE, (a, v) -> v);
}
/**
* Given a text value in format "key1:value1,key2:value2", convert it to a map.
*/
public static Map<String, Set<String>> parseKeyValuesList(String text) {
return parseKeyValueList(text, COMMA_SPLIT_RE, COLON_SPLIT_RE, (a, v) -> {
if (a == null) {
a = new HashSet<>();
}
a.add(v);
return a;
});
}
private static <E extends Enum<E>> Map<String, Object> getEnumLowerCaseNameMap(Class<E> enumType) {
Map<String, Object> mapping = ENUM_NAMES_MAP.get(enumType);
if (mapping != null) {
return mapping;
}
mapping = new HashMap<>();
for (E value : enumType.getEnumConstants()) {
mapping.put(value.name().toLowerCase(), value);
}
return mapping;
}
public static boolean isAsciiLetter(char c) {
return (c > 64 && c < 91) || (c > 96 && c < 123);
}
public static boolean isAsciiDigit(char c) {
return c >= 48 && c <= 57;
}
public static boolean isAsciiLetterOrDigit(char c) {
return isAsciiLetter(c) || isAsciiDigit(c);
}
public static String removeNonAlphanumeric(String text) {
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray()) {
if (StringExt.isAsciiLetterOrDigit(c)) {
sb.append(c);
}
}
return sb.toString();
}
public static int indexOf(Pattern pattern, String text) {
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.start() : -1;
}
public static String doubleQuotes(String text) {
return "\"" + text + "\"";
}
/**
* Removes quotes (single or double) around the provided text. If a quote is provided on the left or right side
* only it is not removed. For example "abc" becomes abc, but "abc is left as "abc.
*/
public static String removeSurroundingQuotes(String text) {
if (isEmpty(text) || text.length() < 2) {
return text;
}
char first = text.charAt(0);
char last = text.charAt(text.length() - 1);
if (first != last) {
return text;
}
if (first == '"' || first == '\'') {
return text.substring(1, text.length() - 1);
}
return text;
}
/**
* Append the value to the end of the text if the value is not already there.
*/
public static String appendToEndIfMissing(String text, String value) {
return text.endsWith(value) ? text : text + value;
}
public static String startWithLowercase(String text) {
if (text == null || text.length() == 0 || !Character.isUpperCase(text.charAt(0))) {
return text;
}
return Character.toLowerCase(text.charAt(0)) + text.substring(1);
}
public static Optional<Integer> parseInt(String s) {
if (StringExt.isEmpty(s)) {
return Optional.empty();
}
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static Optional<Long> parseLong(String s) {
if (StringExt.isEmpty(s)) {
return Optional.empty();
}
try {
return Optional.of(Long.parseLong(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static Optional<Double> parseDouble(String s) {
if (StringExt.isEmpty(s)) {
return Optional.empty();
}
try {
return Optional.of(Double.parseDouble(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
/**
* Parse string value like "1, 10, 1000" to an array of {@link Duration} values, assuming the values represent
* milliseconds.
*
* @returns {@link Optional#empty()} ()} if string is empty or cannot be parsed, and {@link Duration} list otherwise.
*/
public static Optional<List<Duration>> parseDurationMsList(String s) {
String list = StringExt.safeTrim(s);
if (list.isEmpty()) {
return Optional.empty();
}
String[] parts = list.split(",");
List<Duration> result = new ArrayList<>(parts.length);
for (String part : parts) {
try {
result.add(Duration.ofMillis(Integer.parseInt(part.trim())));
} catch (Exception e) {
return Optional.empty();
}
}
return Optional.of(result);
}
/**
* GZip a string and base64 encode the result in order to compress a string while keeping the String type.
*
* @return gzipped and base64 encoded string.
*/
public static String gzipAndBase64Encode(String s) {
if (StringExt.isEmpty(s)) {
return s;
}
try (
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
) {
gzip.write(s.getBytes());
gzip.finish();
return Base64.getEncoder().encodeToString(out.toByteArray());
} catch (Exception e) {
throw ExceptionExt.rethrow(e);
}
}
public static Either<String, IllegalArgumentException> nameFromJavaBeanGetter(String getterName) {
if (isEmpty(getterName)) {
return Either.ofError(new IllegalArgumentException("getter name is empty"));
}
int prefixLen;
if (getterName.startsWith("get")) {
prefixLen = 3;
} else if (getterName.startsWith("is")) {
prefixLen = 2;
} else if (getterName.startsWith("has")) {
prefixLen = 3;
} else {
return Either.ofError(new IllegalArgumentException(String.format("getter '%s' does not start with a valid prefix (get|is|has)", getterName)));
}
if (getterName.length() == prefixLen) {
return Either.ofError(new IllegalArgumentException(String.format("getter '%s' has only prefix with empty base name", getterName)));
}
return Either.ofValue(Character.toLowerCase(getterName.charAt(prefixLen)) + getterName.substring(prefixLen + 1));
}
} | 633 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/CollectionsExt.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;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.common.util.collections.OneItemIterator;
import com.netflix.titus.common.util.collections.TwoItemIterator;
import com.netflix.titus.common.util.tuple.Pair;
/**
* A set of additional collections related functions.
*/
public final class CollectionsExt {
private CollectionsExt() {
}
public static <K, V> boolean isNullOrEmpty(Map<K, V> map) {
return map == null || map.isEmpty();
}
public static <T> boolean isNullOrEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
public static <T> boolean isNullOrEmpty(T[] array) {
return array == null || array.length == 0;
}
public static <T, C extends Collection<T>> void ifNotEmpty(C collection, Runnable runnable) {
if (!isNullOrEmpty(collection)) {
runnable.run();
}
}
public static <T, C extends Collection<T>> void applyNotEmpty(C collection, Consumer<C> consumer) {
if (!isNullOrEmpty(collection)) {
consumer.accept(collection);
}
}
public static <T> List<T> nonNull(List<T> collection) {
return collection == null ? Collections.emptyList() : collection;
}
public static <T> Set<T> nonNull(Set<T> collection) {
return collection == null ? Collections.emptySet() : collection;
}
public static <K, V> Map<K, V> nonNull(Map<K, V> map) {
return map == null ? Collections.emptyMap() : map;
}
public static <T> T first(Collection<T> collection) {
Iterator<T> it = collection.iterator();
return it.hasNext() ? it.next() : null;
}
public static <T> T firstOrDefault(Collection<T> collection, T defaultValue) {
return isNullOrEmpty(collection) ? defaultValue : collection.iterator().next();
}
public static <T> T last(List<T> list) {
return list.isEmpty() ? null : list.get(list.size() - 1);
}
public static <T> T last(Stream<T> stream) {
return last(stream.collect(Collectors.toList()));
}
public static <T> T getOrDefault(T[] array, int idx, T defaultValue) {
Preconditions.checkArgument(idx >= 0, "Index cannot be negative number");
if (array == null || array.length <= idx) {
return defaultValue;
}
return array[idx];
}
public static <T> void addAll(Collection<T> target, T[] source) {
for (T v : source) {
target.add(v);
}
}
public static <T> List<T> asList(T[] source, int from) {
return asList(source, from, source.length);
}
public static <T> List<T> asList(T[] source, int from, int to) {
Preconditions.checkArgument(from >= 0, "Negative index value");
Preconditions.checkArgument(from <= to, "Invalid range (from > to)");
Preconditions.checkArgument(source.length >= to, "Index out of bound");
List<T> result = new ArrayList<>();
for (int i = from; i < to; i++) {
result.add(source[i]);
}
return result;
}
public static <T> Set<T> take(Set<T> collection, int count) {
return copy(collection, new HashSet<>(), count);
}
public static <T, C extends Collection<T>> C copy(C source, C destination, int count) {
Iterator<T> it = source.iterator();
for (int i = 0; i < count && it.hasNext(); i++) {
destination.add(it.next());
}
return destination;
}
public static <T> List<T> copyAndAdd(List<T> original, T newItem) {
return copyAndAddToList(original, newItem);
}
public static <T> List<T> copyAndAddToList(Collection<T> original, T newItem) {
List<T> newList = new ArrayList<>(original);
newList.add(newItem);
return newList;
}
public static <T> Set<T> copyAndAdd(Set<T> original, T newItem) {
Set<T> newSet = new HashSet<>(original);
newSet.add(newItem);
return newSet;
}
public static <K, V> Map<K, V> copyAndAdd(Map<K, V> original, K key, V value) {
if (original.isEmpty()) {
return Collections.singletonMap(key, value);
}
Map<K, V> result = new HashMap<>(original);
result.put(key, value);
return result;
}
public static <K, V> Map<K, V> copyAndAdd(Map<K, V> original, Map<K, V> additions) {
Map<K, V> result = new HashMap<>(original);
result.putAll(additions);
return result;
}
public static <T> List<T> nullableImmutableCopyOf(List<T> original) {
return original == null ? null : ImmutableList.copyOf(original);
}
public static <T> List<T> nonNullImmutableCopyOf(List<T> original) {
return ImmutableList.copyOf(nonNull(original));
}
public static <K, V> Map<K, V> nullableImmutableCopyOf(Map<K, V> original) {
return original == null ? null : ImmutableMap.copyOf(original);
}
public static <T> List<T> copyAndRemove(List<T> original, Predicate<T> removePredicate) {
if (isNullOrEmpty(original)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>();
original.forEach(value -> {
if (!removePredicate.test(value)) {
result.add(value);
}
});
return result.isEmpty() ? Collections.emptyList() : result;
}
public static <T> Set<T> copyAndRemove(Set<T> original, T toRemove) {
if (original.isEmpty()) {
return original;
}
if (!original.contains(toRemove)) {
return original;
}
Set<T> result = new HashSet<>(original);
result.remove(toRemove);
return result;
}
public static <T> Set<T> copyAndRemove(Set<T> original, Collection<T> toRemove) {
if (original.isEmpty()) {
return Collections.emptySet();
}
Set<T> result = new HashSet<>(original);
if (!toRemove.isEmpty()) {
result.removeAll(toRemove);
}
return result;
}
public static <K, V> Map<K, V> copyAndRemove(Map<K, V> original, K... keys) {
return copyAndRemove(original, Arrays.asList(keys));
}
public static <K, V> Map<K, V> copyAndRemove(Map<K, V> original, Collection<K> keys) {
Map<K, V> result = new HashMap<>(original);
for (K key : keys) {
if (key != null) {
result.remove(key);
}
}
return result;
}
public static <K, V> Map<K, V> copyAndRemoveByKey(Map<K, V> original, Predicate<K> keysPredicate) {
return original.entrySet().stream()
.filter(entry -> !keysPredicate.test(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
public static <K, V> Map<K, V> copyAndRemoveByValue(Map<K, V> original, Predicate<V> removePredicate) {
return original.entrySet().stream()
.filter(entry -> !removePredicate.test(entry.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
/**
* Helper for adding items to <tt>MultiMaps</tt> represented as <tt>Map<K, List<V>></tt> types.
*/
public static <K, V> List<V> multiMapAddValue(Map<K, List<V>> multiMap, K key, V value) {
return multiMap.compute(key, (ignored, old) -> old == null ? Collections.singletonList(value) : copyAndAdd(old, value));
}
@SafeVarargs
public static <T> List<T> merge(List<T>... lists) {
if (isNullOrEmpty(lists)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>();
for (List<T> next : lists) {
if (next != null) {
result.addAll(next);
}
}
return result;
}
@SafeVarargs
public static <T> Set<T> merge(Set<T>... sets) {
return merge(HashSet::new, sets);
}
@SafeVarargs
public static <T> Set<T> merge(Supplier<Set<T>> supplier, Set<T>... sets) {
if (isNullOrEmpty(sets)) {
return Collections.emptySet();
}
Set<T> result = supplier.get();
for (Set<T> next : sets) {
result.addAll(next);
}
return result;
}
@SafeVarargs
public static <K, V> Map<K, V> merge(Map<K, V>... maps) {
if (isNullOrEmpty(maps)) {
return Collections.emptyMap();
}
Map<K, V> result = new HashMap<>();
for (Map<K, V> next : maps) {
result.putAll(next);
}
return result;
}
/**
* Merges two maps together by iterating through each key and copying it to a new map. If the same key exists
* in both maps then the conflictFunction is called with both values and should return a value to use.
*
* @param first the first map to merge
* @param second the second map to merge
* @param conflictFunction a custom function that should resolve conflicts between two values
* @return the merged map
*/
public static <K, V> Map<K, V> merge(Map<K, V> first, Map<K, V> second, BiFunction<V, V, V> conflictFunction) {
Map<K, V> result = new HashMap<>();
Set<K> keys = CollectionsExt.merge(first.keySet(), second.keySet());
for (K key : keys) {
V firstValue = first.get(key);
V secondValue = second.get(key);
if (firstValue != null && secondValue != null) {
V newValue = conflictFunction.apply(firstValue, secondValue);
result.put(key, newValue);
} else if (firstValue == null) {
result.put(key, secondValue);
} else {
result.put(key, firstValue);
}
}
return result;
}
public static <K, U, V> Map<K, V> mapValues(Map<K, U> source, Function<U, V> valueMapper, Supplier<Map<K, V>> mapSupplier) {
return mapValuesWithKeys(source, (key, value) -> valueMapper.apply(value), mapSupplier);
}
public static <K, U, V> Map<K, V> mapValuesWithKeys(Map<K, U> source, BiFunction<K, U, V> valueMapper, Supplier<Map<K, V>> mapSupplier) {
return source.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey, entry -> valueMapper.apply(entry.getKey(), entry.getValue()),
(v1, v2) -> v1, mapSupplier
));
}
public static <T> Set<T> xor(Set<T>... sets) {
if (sets.length == 0) {
return Collections.emptySet();
}
if (sets.length == 1) {
return sets[0];
}
Set<T> result = new HashSet<>(sets[0]);
Set<T> all = new HashSet<>(sets[0]);
for (int i = 1; i < sets.length; i++) {
Set<T> current = sets[i];
result.removeAll(current);
result.addAll(copyAndRemove(current, all));
all.addAll(current);
}
return result;
}
public static <T> Pair<List<T>, List<T>> split(List<T> items, Predicate<T> predicate) {
List<T> matching = new ArrayList<>();
List<T> notMatching = new ArrayList<>();
items.forEach(item -> {
if (predicate.test(item)) {
matching.add(item);
} else {
notMatching.add(item);
}
});
return Pair.of(matching, notMatching);
}
public static <T, R> Set<R> transformSet(Set<T> source, Function<T, R> transformer) {
if (isNullOrEmpty(source)) {
return Collections.emptySet();
}
Set<R> result = new HashSet<>(source.size());
for (T item : source) {
result.add(transformer.apply(item));
}
return result;
}
public static <K, V, R> Map<K, R> transformValues(Map<K, V> source, Function<V, R> transformer) {
if (isNullOrEmpty(source)) {
return Collections.emptyMap();
}
Map<K, R> result = new HashMap<>();
source.forEach((k, v) -> result.put(k, transformer.apply(v)));
return result;
}
@SafeVarargs
public static <T> Set<T> asSet(T... values) {
Set<T> newSet = new HashSet<>();
Collections.addAll(newSet, values);
return newSet;
}
public static <T> Set<T> asSet(T[] values, int from, int to) {
Preconditions.checkArgument(from >= 0, "Invalid sub-sequence first position: %s", from);
Preconditions.checkArgument(to >= from && to <= values.length, "Invalid sub-sequence last to position: %s", to);
Set<T> newSet = new HashSet<>();
for (int i = from; i < to; i++) {
newSet.add(values[i]);
}
return newSet;
}
@SafeVarargs
public static <T> Map<T, T> asMap(T... values) {
Preconditions.checkArgument(values.length % 2 == 0, "Expected even number of arguments");
Map<T, T> result = new HashMap<>();
for (int i = 0; i < values.length; i += 2) {
result.put(values[i], values[i + 1]);
}
return result;
}
public static <K, V> Map<K, V> zipToMap(Collection<K> keys, Collection<V> values) {
Preconditions.checkArgument(keys.size() == values.size(), "Expected collections of the same size");
if (keys.isEmpty()) {
return Collections.emptyMap();
}
Map<K, V> result = new HashMap<>();
Iterator<K> kIt = keys.iterator();
Iterator<V> vIt = values.iterator();
while (kIt.hasNext()) {
result.put(kIt.next(), vIt.next());
}
return result;
}
public static <K, V> MapBuilder<K, V> newMap(Supplier<Map<K, V>> mapTypeBuilder) {
return new MapBuilder<>(mapTypeBuilder.get());
}
public static <K, V> MapBuilder<K, V> newHashMap() {
return newMap(HashMap::new);
}
public static <K, V> MapBuilder<K, V> newHashMap(Map<K, V> original) {
return newMap(() -> new HashMap<>(original));
}
public static <K, V> Map<K, V> newMapFrom(K[] keys, Function<K, V> valueFun) {
Map<K, V> result = new HashMap<>();
for (K key : keys) {
result.put(key, valueFun.apply(key));
}
return result;
}
public static int[] toPrimitiveArray(Collection<Integer> collection) {
int[] result = new int[collection.size()];
Iterator<Integer> it = collection.iterator();
for (int i = 0; it.hasNext(); i++) {
result[i] = it.next();
}
return result;
}
public static char[] toPrimitiveCharArray(Collection<Character> collection) {
char[] result = new char[collection.size()];
Iterator<Character> it = collection.iterator();
for (int i = 0; it.hasNext(); i++) {
result[i] = it.next();
}
return result;
}
public static char[] toPrimitiveCharArray(Character[] arrayOfChar) {
char[] result = new char[arrayOfChar.length];
for (int i = 0; i < arrayOfChar.length; i++) {
result[i] = arrayOfChar[i];
}
return result;
}
public static List<Integer> toWrapperList(int[] intArray) {
List<Integer> result = new ArrayList<>();
for (int v : intArray) {
result.add(v);
}
return result;
}
public static <T> List<List<T>> chop(List<T> list, int chunkSize) {
if (list.size() <= chunkSize) {
return Collections.singletonList(list);
}
List<List<T>> result = new ArrayList<>();
for (int i = 0; i < list.size(); i += chunkSize) {
result.add(list.subList(i, Math.min(i + chunkSize, list.size())));
}
return result;
}
/**
* {@link Optional#empty()} if the collection is <tt>null</tt> or {@link Collection#isEmpty() empty}.
*/
public static <T, C extends Collection<T>> Optional<C> optionalOfNotEmpty(C collection) {
if (isNullOrEmpty(collection)) {
return Optional.empty();
}
return Optional.of(collection);
}
/**
* @return true when the <tt>map</tt> contains all keys
*/
@SafeVarargs
public static <T> boolean containsKeys(Map<T, ?> map, T... keys) {
if (map == null) {
return false;
}
for (T key : keys) {
if (!map.containsKey(key)) {
return false;
}
}
return true;
}
/**
* @return true when the <tt>map</tt> contains any of the keys
*/
@SafeVarargs
public static <T> boolean containsAnyKeys(Map<T, ?> map, T... keys) {
if (map == null) {
return false;
}
for (T key : keys) {
if (map.containsKey(key)) {
return true;
}
}
return false;
}
/**
* Items with the same index key will be discarded (only the first is kept in the result {@link Map}.
*/
public static <T, I> Map<I, T> indexBy(List<T> items, Function<T, I> keyMapper) {
return items.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (v1, v2) -> v1));
}
/**
* @param equal custom logic for equality between items from both <tt>Collections</tt>
* @return items present in <tt>one</tt> that are not present in <tt>other</tt>, according to a custom predicate for each pair
*/
public static <T> Collection<T> difference(Collection<T> one, Collection<T> other, BiPredicate<T, T> equal) {
return one.stream()
.filter(it -> other.stream().noneMatch(ot -> equal.test(it, ot)))
.collect(Collectors.toSet());
}
/**
* Binary search for cases where the searched for item is not materialized into an object, but instead it is embedded
* into 'targetComparator'. Building a value of type T is not possible in a generic way, and requiring a client
* to provide it may be inconvenient. This could be circumvented by using an intermediate object that wraps the
* state we compare against, but this would create too much garbage on the heap.
*
* @param items an ordered list
* @param targetComparator a function with an embedded searched for element, equivalent to Comparator.compare(targetItem, items.get(pos))
* @return see {@link Collections#binarySearch(List, Object)}
*/
public static <T> int binarySearchLeftMost(List<T> items, Function<T, Integer> targetComparator) {
if (items.isEmpty()) {
return -1;
}
int from = 0;
int to = items.size();
while (from < to) {
int pos = (from + to) / 2;
int result = targetComparator.apply(items.get(pos));
if (result > 0) {
from = pos + 1;
} else {
to = pos;
}
}
if (from >= items.size()) {
return -items.size() - 1;
}
if (targetComparator.apply(items.get(from)) == 0) {
return from;
}
return -from - 1;
}
/**
* Convert all keys to lower case, the behavior is undefined when values clash, and only one will be kept
*/
public static <V> Map<String, V> toLowerCaseKeys(Map<String, V> entries) {
return entries.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toLowerCase(),
Map.Entry::getValue,
(o, n) -> n
));
}
/**
* Convert all keys to lower case, the behavior is undefined when values clash, and only one will be kept
*/
public static <V> Map<String, V> toLowerCaseKeys(Map<String, V> entries, Supplier<Map<String, V>> mapSupplier) {
return entries.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toLowerCase(),
Map.Entry::getValue,
(o, n) -> n,
mapSupplier
));
}
@SafeVarargs
public static <T> Iterator<T> newIterator(T... items) {
if (items.length == 0) {
return Collections.emptyIterator();
}
if (items.length == 1) {
return new OneItemIterator<>(items[0]);
}
if (items.length == 2) {
return new TwoItemIterator<>(items[0], items[1]);
}
return Arrays.asList(items).iterator();
}
public static class MapBuilder<K, V> {
private final Map<K, V> out;
private MapBuilder(Map<K, V> out) {
this.out = out;
}
public MapBuilder<K, V> entry(K key, V value) {
out.put(key, value);
return this;
}
public Map<K, V> toMap() {
return out;
}
public Map<K, V> build() {
return toMap();
}
}
}
| 634 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/FunctionExt.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;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public final class FunctionExt {
private static final Predicate TRUE_PREDICATE = ignored -> true;
private static final Predicate FALSE_PREDICATE = ignored -> false;
private static final Runnable NOOP = () -> {
};
public static <T> Predicate<T> alwaysTrue() {
return TRUE_PREDICATE;
}
public static <T> Predicate<T> alwaysFalse() {
return FALSE_PREDICATE;
}
public static Runnable noop() {
return NOOP;
}
public static <T> Optional<T> ifNotPresent(Optional<T> opt, Runnable what) {
if (!opt.isPresent()) {
what.run();
}
return opt;
}
/**
* {@link UnaryOperator} does not have an equivalent of {@link Function#andThen(Function)}, so this can be used when
* the more specific type ({@link UnaryOperator}) is required.
*/
public static <T> UnaryOperator<T> andThen(UnaryOperator<T> op, UnaryOperator<T> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(op.apply(t));
}
}
| 635 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/ExecutorsExt.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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.ThreadPoolMonitor;
/**
* Factory methods and utilities for {@link java.util.concurrent.ExecutorService executors}.
*/
public final class ExecutorsExt {
private ExecutorsExt() {
}
public static ExecutorService namedSingleThreadExecutor(String name) {
return Executors.newSingleThreadExecutor(runnable -> {
Thread thread = new Thread(runnable, name);
thread.setDaemon(true);
return thread;
});
}
public static ScheduledExecutorService namedSingleThreadScheduledExecutor(String name) {
return Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, name);
thread.setDaemon(true);
return thread;
});
}
/**
* Unbounded elastic thread pool that grows and shrinks as necessary.
*/
public static ExecutorService instrumentedCachedThreadPool(Registry registry, String name) {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name + "-%d")
.setDaemon(true)
.build();
// similar to Executors.newCachedThreadPool(), but explicitly use the concrete ThreadPoolExecutor type to ensure
// it can be instrumented by Spectator
ThreadPoolExecutor executor = new ThreadPoolExecutor(
0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
threadFactory
);
ThreadPoolMonitor.attach(registry, executor, name);
return executor;
}
/**
* Fixed size thread pool that pre-allocates all threads. When no more threads are available, requests will block.
*/
public static ExecutorService instrumentedFixedSizeThreadPool(Registry registry, String name, int size) {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(name + "-%d")
.setDaemon(true)
.build();
// similar to Executors.newFixedSizeThreadPool(), but explicitly use the concrete ThreadPoolExecutor type
// to ensure it can be instrumented by Spectator
ThreadPoolExecutor executor = new ThreadPoolExecutor(
size, size,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
threadFactory
);
ThreadPoolMonitor.attach(registry, executor, name);
return executor;
}
}
| 636 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/ReflectionExt.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;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.netflix.titus.common.util.tuple.Pair;
import static java.lang.String.format;
import static java.util.Arrays.asList;
/**
* Helper reflection functions.
*/
public final class ReflectionExt {
private static final Set<Class<?>> WRAPPERS = CollectionsExt.asSet(
Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class,
Boolean.class
);
private static final Set<Class<?>> STD_DATA_TYPES = CollectionsExt.asSet(
String.class
);
private static final ConcurrentMap<Class<?>, List<Field>> CLASS_FIELDS = new ConcurrentHashMap<>();
private static final ConcurrentMap<Method, Optional<Method>> FIND_INTERFACE_METHOD_CACHE = new ConcurrentHashMap<>();
private static final List<Pair<String, Class<?>[]>> OBJECT_METHODS = Stream.of(Object.class.getMethods())
.map(m -> Pair.of(m.getName(), m.getParameterTypes()))
.collect(Collectors.toList());
private ReflectionExt() {
}
public static boolean isPrimitiveOrWrapper(Class<?> type) {
if (type.isPrimitive()) {
return true;
}
return WRAPPERS.contains(type);
}
public static boolean isStandardDataType(Class<?> type) {
return isPrimitiveOrWrapper(type) || STD_DATA_TYPES.contains(type);
}
public static boolean isContainerType(Field field) {
Class<?> fieldType = field.getType();
if (Collection.class.isAssignableFrom(fieldType)) {
return true;
}
if (Map.class.isAssignableFrom(fieldType)) {
return true;
}
return Optional.class.isAssignableFrom(fieldType);
}
public static boolean isNumeric(Class<?> type) {
if (Number.class.isAssignableFrom(type)) {
return true;
}
if (Integer.TYPE == type || Long.TYPE == type || Float.TYPE == type || Double.TYPE == type) {
return true;
}
return false;
}
public static boolean isObjectMethod(Method method) {
for (Pair<String, Class<?>[]> objectMethod : OBJECT_METHODS) {
Class<?>[] objectMethodArgs = objectMethod.getRight();
if (method.getName().equals(objectMethod.getLeft()) && method.getParameterCount() == objectMethodArgs.length) {
boolean allMatch = true;
for (int i = 0; i < method.getParameterCount() && allMatch; i++) {
allMatch = method.getParameterTypes()[i] == objectMethodArgs[i];
}
if (allMatch) {
return true;
}
}
}
return false;
}
public static List<Class<?>> findAllInterfaces(Class<?> type) {
List<Class<?>> result = new ArrayList<>();
Collections.addAll(result, type.getInterfaces());
if (type.getSuperclass() != Object.class) {
result.addAll(findAllInterfaces(type.getSuperclass()));
}
return result;
}
public static <T, A extends Annotation> List<Method> findAnnotatedMethods(T instance, Class<A> methodAnnotation) {
Class<?> instanceType = bypassBytecodeGeneratedWrappers(instance);
List<Method> result = new ArrayList<>();
for (Method m : instanceType.getMethods()) {
for (Annotation a : m.getAnnotations()) {
if (a.annotationType() == methodAnnotation) {
result.add(m);
}
}
}
return result;
}
public static Optional<StackTraceElement> findCallerStackTrace() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = 3; i < stackTrace.length; i++) {
StackTraceElement element = stackTrace[i];
String className = element.getClassName();
if (!className.contains("cglib")
&& !className.contains("com.google.inject")
&& !className.contains("EnhancerByGuice")
&& !className.contains("ProxyMethodInterceptor")
&& !className.contains("util.proxy")) {
return Optional.of(element);
}
}
return Optional.empty();
}
private static <T> Class<?> bypassBytecodeGeneratedWrappers(T instance) {
Class<?> instanceType = instance.getClass();
while (true) {
if (instanceType.getName().contains("EnhancerByGuice")) {
instanceType = instanceType.getSuperclass();
} else {
break;
}
}
return instanceType;
}
public static Optional<Method> findInterfaceMethod(Method method) {
return FIND_INTERFACE_METHOD_CACHE.computeIfAbsent(method, m -> {
if (method.getDeclaringClass().isInterface()) {
return Optional.of(method);
}
for (Class<?> interf : method.getDeclaringClass().getInterfaces()) {
try {
Method interfMethod = interf.getMethod(method.getName(), method.getParameterTypes());
if (interfMethod != null) {
return Optional.of(interfMethod);
}
} catch (NoSuchMethodException ignore) {
}
}
return Optional.empty();
});
}
public static Field getField(Class<?> type, String name) {
try {
return type.getDeclaredField(name);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(format("Class %s has no field %s", type, name));
}
}
public static <T> T getFieldValue(Field field, Object object) {
try {
return (T) field.get(object);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(format("Cannot access field %s in %s", field.getName(), object.getClass()));
}
}
public static List<Field> getAllFields(Class<?> type) {
return CLASS_FIELDS.computeIfAbsent(type, t -> {
List<Field> fields = new ArrayList<>();
for (Class<?> current = t; current != Object.class; current = current.getSuperclass()) {
fields.addAll(asList(current.getDeclaredFields()));
}
fields.forEach(f -> f.setAccessible(true));
return fields;
});
}
/*
* Dynamic proxies with default interface methods. Based on Slack discussion here:
* https://stackoverflow.com/questions/26206614/java8-dynamic-proxy-and-default-methods
*/
private static final Constructor<MethodHandles.Lookup> lookupConstructor;
static {
try {
lookupConstructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
lookupConstructor.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static final ConcurrentMap<Pair<Class, Method>, MethodHandle> DEFAULT_METHOD_HANDLES = new ConcurrentHashMap<>();
private static MethodHandle findDefaultMethodHandle(Class<?> apiInterface, Method method) {
return DEFAULT_METHOD_HANDLES.computeIfAbsent(Pair.of(apiInterface, method), k -> buildDefaultMethodHandle(apiInterface, method));
}
private static MethodHandle buildDefaultMethodHandle(Class<?> apiInterface, Method method) {
try {
Class<?> declaringClass = method.getDeclaringClass();
MethodHandles.Lookup lookup = lookupConstructor.newInstance(declaringClass, -1);
try {
return lookup.findSpecial(apiInterface, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()), declaringClass);
} catch (IllegalAccessException e) {
try {
return lookup.unreflectSpecial(method, declaringClass);
} catch (IllegalAccessException x) {
x.addSuppressed(e);
throw x;
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object invokeDefault(Object proxy, Class<?> apiInterface, Method method, Object[] args) throws Throwable {
MethodHandle mh = findDefaultMethodHandle(apiInterface, method);
return mh.bindTo(proxy).invokeWithArguments(args);
}
}
| 637 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/MathExt.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;
import com.google.common.base.Preconditions;
public class MathExt {
/**
* Scale the value using feature scaling such that the value is normalized between the range of [0.0, 1.0].
*
* @param value the value to scale
* @param min the min value
* @param max the max value
* @return the scaled value
*/
public static double scale(double value, double min, double max) {
Preconditions.checkArgument(min < max, "min must be less than max");
return (value - min) / (max - min);
}
/**
* Scale the value using feature scaling such that the value is normalized between the range of [minRangeValue, maxRangeValue].
*
* @param value the value to scale
* @param min the min value
* @param max the max value
* @param minRangeValue the min range value
* @param maxRangeValue the max range value
* @return the scaled value
*/
public static double scale(double value, double min, double max, double minRangeValue, double maxRangeValue) {
Preconditions.checkArgument(min < max, "min must be less than max");
Preconditions.checkArgument(minRangeValue <= maxRangeValue, "minRangeValue must be less than or equal to maxRangeValue");
return minRangeValue + (((value - min) * (maxRangeValue - minRangeValue)) / (max - min));
}
/**
* Return the value if it falls within the range [min, max] otherwise return min if value is less than min or max if value
* is greater than max.
*
* @param value the value
* @param min the min value
* @param max the max value
* @return the value in the range [min, max]
*/
public static double between(double value, double min, double max) {
Preconditions.checkArgument(min <= max, "min must be less than or equal to max");
return Math.max(Math.min(value, max), min);
}
/**
* Return the value if it falls within the range [min, max] otherwise return min if value is less than min or max if value
* is greater than max.
*
* @param value the value
* @param min the min value
* @param max the max value
* @return the value in the range [min, max]
*/
public static long between(long value, long min, long max) {
Preconditions.checkArgument(min <= max, "min must be less than or equal to max");
return Math.max(Math.min(value, max), min);
}
}
| 638 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/PropertiesExt.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;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import com.netflix.titus.common.util.tuple.Pair;
/**
* A collection of methods for property name/values processing.
*/
public final class PropertiesExt {
private PropertiesExt() {
}
/**
* Load properties from classpath.
*/
public static Optional<Map<String, String>> loadFromClassPath(String resourceName) throws IOException {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
if (is == null) {
return Optional.empty();
}
Properties properties = new Properties();
properties.load(is);
Map<String, String> mapInstance = properties.entrySet()
.stream()
.collect(Collectors.toMap(p -> (String) p.getKey(), p -> (String) p.getValue()));
return Optional.of(mapInstance);
}
/**
* Group properties by their name's root part. For example properties ['my.a', 'my.b', 'your.x', 'your.y'], would
* be in groups 'my' and 'your', with property names ['a', 'b'] and ['x', 'y'] respectively.
*/
public static Map<String, Map<String, String>> groupByRootName(Map<String, String> properties, int rootParts) {
if (CollectionsExt.isNullOrEmpty(properties)) {
return Collections.emptyMap();
}
Map<String, Map<String, String>> result = new HashMap<>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
Pair<String, String> parts = split(entry.getKey(), rootParts);
if (parts == null) {
continue;
}
String rootPart = parts.getLeft();
String internalName = parts.getRight();
Map<String, String> internalProps = result.get(rootPart);
if (internalProps == null) {
result.put(rootPart, internalProps = new HashMap<>());
}
internalProps.put(internalName, entry.getValue());
}
return result;
}
/**
* Returns properties with the common name prefix.
*/
public static Map<String, String> getPropertiesOf(String namePrefix, Map<String, String> properties) {
if (CollectionsExt.isNullOrEmpty(properties)) {
return Collections.emptyMap();
}
String namePrefixWithDot = namePrefix + '.';
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
String name = entry.getKey().trim();
if (name.isEmpty() || !name.startsWith(namePrefixWithDot)) {
continue;
}
String internalName = name.substring(namePrefixWithDot.length());
result.put(internalName, entry.getValue());
}
return result;
}
/**
* For given properties, examine their names, and check that each property name's root part is in the expected
* name set. For example property names ['my.a', 'your'], have their root parts equal to ['my', 'your']. The
* latter set must be a subset of the expected root names.
*
* @return a collection of not matching property names (or empty list if all match)
*/
public static List<String> verifyRootNames(Map<String, String> properties, Set<String> expectedRootNames) {
if (CollectionsExt.isNullOrEmpty(properties)) {
return Collections.emptyList();
}
List<String> notMatching = new ArrayList<>();
for (String key : properties.keySet()) {
String name = key.trim();
int idx = name.indexOf('.');
String rootPart = (idx == -1 || idx == name.length() - 1)
? name
: name.substring(0, idx);
if (!expectedRootNames.contains(rootPart)) {
notMatching.add(name);
}
}
return notMatching;
}
/**
* Splits names into two parts, and returns set of top names.
*/
public static Set<String> getRootNames(Collection<String> names, int rootSegments) {
// Split nested field names
Set<String> topNames = new HashSet<>();
names.forEach(n -> {
Pair<String, String> parts = split(n, rootSegments);
if (parts != null) {
topNames.add(parts.getLeft());
}
});
return topNames;
}
/**
* Split property names into two parts, where the first part may include one or more segments separated with dot.
* The second part may be null, if the name is too short.
*/
public static Map<String, Set<String>> splitNames(Collection<String> names, int rootSegments) {
// Split nested field names
Map<String, Set<String>> topNames = new HashMap<>();
names.forEach(n -> {
Pair<String, String> parts = split(n, rootSegments);
if (parts == null) {
topNames.put(n, null);
} else {
Set<String> nested = topNames.get(parts.getLeft());
if (nested == null) {
nested = new HashSet<>();
topNames.put(parts.getLeft(), nested);
}
nested.add(parts.getRight());
}
});
return topNames;
}
/**
* Split property name into two parts, where the first part may include one or more segments separated with dot.
* The second part may be null, if the name is too short.
*/
public static Pair<String, String> split(String name, int rootParts) {
if (name.isEmpty()) {
return null;
}
int idx = 0;
for (int i = 0; i < rootParts && (idx = name.indexOf('.', idx)) != -1; i++) {
idx++;
}
if (idx == -1 || idx == name.length()) {
return null;
}
return Pair.of(name.substring(0, idx - 1), name.substring(idx));
}
/**
* Split property names into dot separated parts in a tree form.
*/
public static PropertyNode<Boolean> fullSplit(Collection<String> names) {
PropertyNode<Boolean> root = new PropertyNode<>("ROOT", Optional.empty(), new HashMap<>());
names.forEach(n -> {
List<String> parts = StringExt.splitByDot(n);
PropertyNode<Boolean> current = root;
int lastIdx = parts.size() - 1;
for (int i = 0; i < parts.size(); i++) {
String name = parts.get(i);
PropertyNode<Boolean> next = current.getChildren().get(name);
if (next == null) {
next = new PropertyNode<>(name, Optional.empty(), new HashMap<>());
current.getChildren().put(name, next);
}
if (i == lastIdx) {
next.value = Optional.of(Boolean.TRUE);
}
current = next;
}
});
return root;
}
public static class PropertyNode<V> {
private final String name;
private Optional<V> value;
private final Map<String, PropertyNode<V>> children;
private PropertyNode(String name, Optional<V> value, Map<String, PropertyNode<V>> children) {
this.name = name;
this.value = value;
this.children = children;
}
public String getName() {
return name;
}
public Optional<V> getValue() {
return value;
}
public Map<String, PropertyNode<V>> getChildren() {
return children;
}
}
}
| 639 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/NumberSequence.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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.tuple.Either;
/**
* Ordered sequence of integers. The sequence is parsed from string which could include individual values, a range or
* mixture of both. For example:
* <ul>
* <li>1, 2, 5</li>
* <li>1..5</li>
* <li>1..</li>
* <li>1, 2, 5..10, 20, 50..</li>
* </ul>
*/
public abstract class NumberSequence {
private static final Pattern PART_RE = Pattern.compile("(\\d+)(..(\\d+)?)?");
private static final NumberSequence EMPTY_SEQUENCE = new EmptySequence();
public abstract long getCount();
public abstract Iterator<Long> getIterator();
public abstract boolean matches(long number);
public abstract NumberSequence skip(long skipCount);
public abstract NumberSequence step(long step);
public static NumberSequence from(long from) {
return new RangeSequence(from, Long.MAX_VALUE, 1);
}
public static Either<NumberSequence, String> parse(String value) {
List<String> parts = StringExt.splitByComma(value);
List<NumberSequence> subsequences = new ArrayList<>();
for (String part : parts) {
Matcher matcher = PART_RE.matcher(part);
if (!matcher.matches()) {
return Either.ofError(String.format("Syntax error in sequence fragment '%s'", part));
}
if (matcher.group(2) == null) {
subsequences.add(new ValuesSequence(Integer.parseInt(part)));
} else if (matcher.group(3) == null) {
subsequences.add(new RangeSequence(Long.parseLong(matcher.group(1)), Long.MAX_VALUE, 1));
} else {
long from = Long.parseLong(matcher.group(1));
long to = Long.parseLong(matcher.group(3));
if (from >= to) {
return Either.ofError(String.format("Invalid range: %s (from) >= %s (to)", from, to));
}
subsequences.add(new RangeSequence(from, to, 1));
}
}
return Either.ofValue(subsequences.isEmpty() ? EMPTY_SEQUENCE : new CompositeSequence(subsequences));
}
private static class EmptySequence extends NumberSequence {
@Override
public long getCount() {
return 0;
}
@Override
public Iterator<Long> getIterator() {
return new Iterator<Long>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Long next() {
throw new IllegalStateException("End of sequence");
}
};
}
@Override
public boolean matches(long number) {
return false;
}
@Override
public NumberSequence skip(long skipCount) {
return this;
}
@Override
public NumberSequence step(long step) {
return this;
}
@Override
public String toString() {
return "EmptySequence{}";
}
}
private static class ValuesSequence extends NumberSequence {
private final List<Long> numbers;
private ValuesSequence(long number) {
this.numbers = Collections.singletonList(number);
}
@Override
public long getCount() {
return 1;
}
@Override
public Iterator<Long> getIterator() {
return numbers.iterator();
}
@Override
public boolean matches(long number) {
return numbers.get(0) == number;
}
@Override
public NumberSequence skip(long skipCount) {
return skipCount == 0 ? this : EMPTY_SEQUENCE;
}
@Override
public NumberSequence step(long step) {
return this;
}
@Override
public String toString() {
return "ValuesSequence{numbers=" + numbers.get(0) + "}";
}
}
private static class RangeSequence extends NumberSequence {
private final long from;
private final long to;
private final long step;
private final long count;
private RangeSequence(long from, long to, long step) {
this.from = from;
this.to = to;
this.step = step;
this.count = 1 + (to - from - 1) / step;
}
@Override
public long getCount() {
return count;
}
@Override
public Iterator<Long> getIterator() {
return new Iterator<Long>() {
private long next = from;
@Override
public boolean hasNext() {
return next < to;
}
@Override
public Long next() {
Preconditions.checkState(hasNext(), "End of sequence");
long result = next;
next = next + step;
return result;
}
};
}
@Override
public boolean matches(long number) {
if (number < from || number >= to) {
return false;
}
return (number - from) % step == 0;
}
@Override
public NumberSequence skip(long skipCount) {
if (count <= skipCount) {
return EMPTY_SEQUENCE;
}
return new RangeSequence(from + skipCount * step, to, step);
}
@Override
public NumberSequence step(long step) {
Preconditions.checkArgument(step > 0, "Step value cannot be <= 0");
if (step == 1) {
return this;
}
return new RangeSequence(from, to, this.step * step);
}
@Override
public String toString() {
return "RangeSequence{" +
"from=" + from +
", to=" + to +
", step=" + step +
"}";
}
}
private static class CompositeSequence extends NumberSequence {
private final List<NumberSequence> subsequences;
private final long count;
private CompositeSequence(List<NumberSequence> subsequences) {
this.subsequences = subsequences;
this.count = subsequences.stream().mapToLong(NumberSequence::getCount).sum();
}
@Override
public long getCount() {
return count;
}
@Override
public Iterator<Long> getIterator() {
return new Iterator<Long>() {
private int subsequenceIndex = 0;
private Iterator<Long> currentIterator = subsequences.get(0).getIterator();
@Override
public boolean hasNext() {
if (subsequenceIndex >= subsequences.size()) {
return false;
}
if (currentIterator.hasNext()) {
return true;
}
subsequenceIndex++;
if (subsequenceIndex >= subsequences.size()) {
return false;
}
currentIterator = subsequences.get(subsequenceIndex).getIterator();
return true; // We know it is true, as we hold only non-empty sequences
}
@Override
public Long next() {
Preconditions.checkState(hasNext(), "End of sequence");
return currentIterator.next();
}
};
}
@Override
public boolean matches(long number) {
return subsequences.stream().anyMatch(s -> s.matches(number));
}
@Override
public NumberSequence skip(long skipCount) {
List<NumberSequence> newSubsequences = new ArrayList<>();
long left = skipCount;
int pos = 0;
while (pos < subsequences.size() && subsequences.get(pos).getCount() <= left) {
left -= subsequences.get(pos).getCount();
pos++;
}
if (pos == subsequences.size()) {
return EMPTY_SEQUENCE;
}
newSubsequences.add(subsequences.get(pos).skip(left));
for (pos++; pos < subsequences.size(); pos++) {
newSubsequences.add(subsequences.get(pos));
}
return new CompositeSequence(newSubsequences);
}
@Override
public NumberSequence step(long step) {
List<NumberSequence> newSubsequences = new ArrayList<>();
long skip = 0;
for (NumberSequence nextSeq : subsequences) {
long count = nextSeq.getCount();
if (skip < count) {
newSubsequences.add(nextSeq.skip(skip).step(step));
skip = (int) ((count - skip) % step);
} else {
skip -= count;
}
}
if (newSubsequences.isEmpty()) {
return EMPTY_SEQUENCE;
}
if (newSubsequences.size() == 1) {
return newSubsequences.get(0);
}
return new CompositeSequence(newSubsequences);
}
@Override
public String toString() {
return "CompositeSequence{subsequences=" + subsequences + "}";
}
}
}
| 640 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/RegExpExt.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;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
public final class RegExpExt {
private RegExpExt() {
}
/**
* Create a {@link Matcher} factory function, with dynamic update of the regular expression pattern.
* This class is primarily to be used with patterns setup via dynamic configuration.
*/
public static Function<String, Matcher> dynamicMatcher(Supplier<String> regExpSource, int flags, Consumer<Throwable> onError) {
return dynamicMatcherInternal(regExpSource, flags, onError);
}
/**
* A convenience wrapper for {@link #dynamicMatcher(Supplier, int, Consumer)} which automatically logs errors to the provided logger.
*/
public static Function<String, Matcher> dynamicMatcher(Supplier<String> regExpSource, String propertyName, int flags, Logger errorLogger) {
return dynamicMatcherInternal(
regExpSource,
flags,
e -> errorLogger.warn("Not valid regular expression value in '{}' property: {}", propertyName, e.getMessage())
);
}
private static Function<String, Matcher> dynamicMatcherInternal(Supplier<String> regExpSource, int flags, Consumer<Throwable> onError) {
Function<String, Pattern> compilePattern = Evaluators.memoizeLast((patternString, lastGoodPattern) -> {
try {
return Pattern.compile(patternString, flags);
} catch (Exception e) {
onError.accept(e);
// there is nothing that can be done if the first patternString is invalid
return lastGoodPattern.orElseThrow(() -> new RuntimeException(e));
}
});
return text -> compilePattern.apply(regExpSource.get()).matcher(text);
}
}
| 641 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/SystemExt.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;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* System/process helper methods.
*/
public class SystemExt {
/**
* Convert {@link System#getProperties()} to a map of strings.
*/
public static Map<String, String> getSystemPropertyMap() {
Map<String, String> properties = new HashMap<>();
System.getProperties().forEach((key, value) -> {
// Build the string representation of key
String keyStr = key == null ? null : key.toString();
if (keyStr == null) {
return;
}
// Build the string representation of value
String valueStr = value == null ? null : value.toString();
properties.put(keyStr, valueStr);
});
return Collections.unmodifiableMap(properties);
}
/**
* Terminate the JVM process.
*/
public static void forcedProcessExit(int status) {
System.err.println("Forced exit: statusCode=" + status);
new Exception().printStackTrace(System.err);
System.err.flush();
Runtime.getRuntime().halt(status);
}
}
| 642 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/DateTimeExt.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;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.google.protobuf.Duration;
import com.google.protobuf.util.Durations;
/**
* Data and time supplementary functions.
*/
public final class DateTimeExt {
private static final DateTimeFormatter ISO_UTC_DATE_TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.of("UTC"));
private static final DateTimeFormatter ISO_LOCAL_DATE_TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.systemDefault());
private DateTimeExt() {
}
public static ZoneId toZoneId(String timeZoneName) {
String full = ZoneId.SHORT_IDS.get(timeZoneName);
if (full == null) {
full = timeZoneName;
}
return ZoneId.of(full);
}
public static ZoneOffset toZoneOffset(String timeZoneName) {
return toZoneId(timeZoneName).getRules().getOffset(Instant.now());
}
/**
* The time given in the argument is scoped to a local (system default) time zone. The result
* is adjusted to UTC time zone.
*/
public static String toUtcDateTimeString(long msSinceEpoch) {
if (msSinceEpoch == 0L) {
return null;
}
return ISO_UTC_DATE_TIME_FORMATTER.format(Instant.ofEpochMilli(msSinceEpoch)) + 'Z';
}
public static String toLocalDateTimeString(long msSinceEpoch) {
if (msSinceEpoch == 0L) {
return null;
}
return ISO_LOCAL_DATE_TIME_FORMATTER.format(Instant.ofEpochMilli(msSinceEpoch));
}
public static String toTimeUnitAbbreviation(TimeUnit timeUnit) {
switch (timeUnit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "us";
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
case MINUTES:
return "min";
case HOURS:
return "h";
case DAYS:
return "d";
}
throw new IllegalArgumentException("Unknown time unit: " + timeUnit);
}
/**
* Given a duration with milliseconds resolution, format it using time units.
* For example 3600,000 is formatted as 1h.
*/
public static String toTimeUnitString(Duration duration) {
return toTimeUnitString(Durations.toMillis(duration));
}
/**
* Given a duration in milliseconds, format it using time units. For example 3600,000 is formatted as 1h.
*/
public static String toTimeUnitString(long timeMs) {
StringBuilder sb = new StringBuilder();
long sec = timeMs / 1000;
long min = sec / 60;
long hour = min / 60;
long day = hour / 24;
if (day > 0) {
sb.append(' ').append(day).append("d");
}
if (hour % 24 > 0) {
sb.append(' ').append(hour % 24).append("h");
}
if (min % 60 > 0) {
sb.append(' ').append(min % 60).append("min");
}
if (sec % 60 > 0) {
sb.append(' ').append(sec % 60).append("s");
}
if (timeMs % 1000 > 0) {
sb.append(' ').append(timeMs % 1000).append("ms");
}
if (sb.length() == 0) {
return "0ms";
} else if (sb.charAt(0) == ' ') {
return sb.substring(1);
}
return sb.toString();
}
/**
* Given a duration in milliseconds, format it using time units rounded to the given number of parts.
*/
public static String toTimeUnitString(long timeMs, int parts) {
Preconditions.checkArgument(parts > 0, "At least one unit must be requested");
StringBuilder sb = new StringBuilder();
long sec = timeMs / 1000;
long min = sec / 60;
long hour = min / 60;
long day = hour / 24;
long addedParts = 0;
if (day > 0) {
sb.append(' ').append(day).append("d");
addedParts++;
}
if (addedParts < parts) {
if (hour % 24 > 0) {
sb.append(' ').append(hour % 24).append("h");
addedParts++;
} else if (addedParts > 0) {
addedParts++;
}
if (addedParts < parts) {
if (min % 60 > 0) {
sb.append(' ').append(min % 60).append("min");
addedParts++;
} else if (addedParts > 0) {
addedParts++;
}
if (addedParts < parts) {
if (sec % 60 > 0) {
sb.append(' ').append(sec % 60).append("s");
addedParts++;
} else if (addedParts > 0) {
addedParts++;
}
if (addedParts < parts) {
if (timeMs % 1000 > 0) {
sb.append(' ').append(timeMs % 1000).append("ms");
}
}
}
}
}
if (sb.length() == 0) {
return "0ms";
} else if (sb.charAt(0) == ' ') {
return sb.substring(1);
}
return sb.toString();
}
/**
* Given an interval, and a number of items generated per interval, create string representation of the
* corresponding rate. For example, interval=10sec, itemsPerInterval=5 gives rate="0.5 items/sec".
*/
public static String toRateString(long interval, long itemsPerInterval, TimeUnit timeUnit, String rateType) {
TimeUnit matchedTimeUnit = timeUnit;
for (TimeUnit nextTimeUnit : TimeUnit.values()) {
double ratio = nextTimeUnit.toNanos(1) / (double) timeUnit.toNanos(1);
double rate = itemsPerInterval / (double) interval * ratio;
if (rate >= 0.1) {
matchedTimeUnit = nextTimeUnit;
break;
}
}
double ratio = matchedTimeUnit.toNanos(1) / (double) timeUnit.toNanos(1);
double rate = itemsPerInterval / (double) interval * ratio;
return String.format("%.2f %s/%s", rate, rateType, toTimeUnitAbbreviation(matchedTimeUnit));
}
/**
* Get the {@link OffsetDateTime} representation from specified epoch in milliseconds.
*/
public static OffsetDateTime fromMillis(long epochMillis) {
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault());
}
}
| 643 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/ProtobufExt.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;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.truth.AbstractFailureStrategy;
import com.google.common.truth.TestVerb;
import com.google.common.truth.extensions.proto.ProtoTruth;
import com.google.protobuf.Descriptors;
import com.google.protobuf.MapEntry;
import com.google.protobuf.Message;
/**
* Given set of field names, creates a copy of protobuf object, with only the indicated fields included.
*/
public final class ProtobufExt {
private ProtobufExt() {
}
public static <T extends Message> T copy(T entity, Set<String> fields) {
// Split nested field names
Map<String, Set<String>> topNames = PropertiesExt.splitNames(fields, 1);
// Filter
Message.Builder builder = entity.toBuilder();
// As we modify the builder, we need to take a snapshot this
Set<Descriptors.FieldDescriptor> fieldDescriptors = new HashSet<>(builder.getAllFields().keySet());
for (Descriptors.FieldDescriptor field : fieldDescriptors) {
if (!topNames.containsKey(field.getName())) {
builder.clearField(field);
} else {
Set<String> nested = topNames.get(field.getName());
if (nested != null) {
Object value = builder.getField(field);
if (value != null) {
if (value instanceof Message) {
Message messageValue = (Message) value;
if (!messageValue.getAllFields().isEmpty()) {
builder.setField(field, copy(messageValue, nested));
}
} else if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (!collection.isEmpty()) {
Object first = CollectionsExt.first(collection);
if (first instanceof MapEntry) {
if (((MapEntry) first).getKey() instanceof String) {
List<?> filteredMap = collection.stream().filter(item -> {
MapEntry<String, Object> entry = (MapEntry<String, Object>) item;
return nested.contains(entry.getKey());
}).collect(Collectors.toList());
builder.setField(field, filteredMap);
}
} else if (first instanceof Message) {
Iterator<?> it = collection.iterator();
int size = collection.size();
for (int i = 0; i < size; i++) {
builder.setRepeatedField(field, i, copy((Message) it.next(), nested));
}
}
}
}
}
}
}
}
return (T) builder.build();
}
/**
* Deep comparison between two protobuf {@link Message entities}, including nested entities. The two messages *must*
* be of the same type (i.e.: {@code getDescriptorForType()} must return the same {@code Descriptor} for both).
*
* @return an @{@link Optional} {@link String} report of the differences, {@link Optional#empty()} if none are found.
* @throws IllegalArgumentException when both messages are not of the same type
* @throws NullPointerException when any of the messages are <tt>null</tt>
*/
public static <T extends Message> Optional<String> diffReport(T one, T other) {
ErrorCollector collector = new ErrorCollector();
new TestVerb(collector)
.about(ProtoTruth.protos())
.that(other)
.named(one.getDescriptorForType().getName())
.reportingMismatchesOnly()
.isEqualTo(one);
return collector.getFailure();
}
private static class ErrorCollector extends AbstractFailureStrategy {
private volatile Optional<String> failure = Optional.empty();
public Optional<String> getFailure() {
return failure;
}
@Override
public void fail(String message, Throwable cause) {
this.failure = Optional.of(message);
}
}
}
| 644 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/IOExt.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;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Preconditions;
/**
* IO utils.
*/
public final class IOExt {
private IOExt() {
}
/**
* Close the given resource, swallowing any emitted exceptions.
*/
public static void closeSilently(Closeable... closeables) {
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignore) {
}
}
}
}
/**
* Read all lines from the given file, using default system character encoding.
*/
public static List<String> readLines(File file) throws IOException {
return readLines(file, Charset.defaultCharset());
}
/**
* Read all lines from the given file, with a client provided character encoding.
*/
public static List<String> readLines(File file, Charset charset) throws IOException {
Preconditions.checkArgument(file.exists(), "File %s not found", file);
Preconditions.checkArgument(file.isFile(), "%s is not a normal file", file);
return readLines(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Read all lines from the provided input stream. The stream is guaranteed to be closed when the function exits.
*/
public static List<String> readLines(Reader source) throws IOException {
LineNumberReader lr = new LineNumberReader(source);
List<String> lines = new ArrayList<>();
try {
String line;
while ((line = lr.readLine()) != null) {
lines.add(line);
}
} finally {
closeSilently(source);
}
return lines;
}
/**
* Get the stream of resource file
*
* @param path the relative path to the resource file
* @return the stream or null if the file does not exist
*/
public static InputStream getFileResourceAsStream(String path) {
String resourcePath = path.charAt(0) == '/' ? path : '/' + path;
InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
if (source == null) {
source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath.substring(1));
if (source == null) {
return null;
}
}
return source;
}
}
| 645 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/AwaitExt.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;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* A collection of functions for polling/executing a predicate periodically until it succeeds or timeout occurs.
*/
public final class AwaitExt {
private AwaitExt() {
}
/**
* Periodically executes a provided predicate, and returns immediately when succeeds (return true). Returns
* false if timeout occurs.
*/
public static boolean awaitUntil(Supplier<Boolean> predicate, long timeout, TimeUnit timeUnit) throws InterruptedException {
long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
long delayMs = 1;
do {
long now = System.currentTimeMillis();
boolean currentStatus = predicate.get();
if (currentStatus || now >= endTime) {
return currentStatus;
}
Thread.sleep(delayMs);
delayMs *= 2;
} while (true);
}
}
| 646 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/ErrorGenerator.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;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.time.Clocks;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Based on the provided configuration generates error occurrences in a stream of actions.
*/
public class ErrorGenerator {
private final Supplier<Pair<Supplier<Boolean>, Long>> nextCycleFactory;
private final Clock clock;
private volatile Supplier<Boolean> failureIndicator;
private volatile long endOfCycleTimestamp;
private final Object lock = new Object();
private ErrorGenerator(Supplier<Pair<Supplier<Boolean>, Long>> nextCycleFactory, Clock clock) {
this.nextCycleFactory = nextCycleFactory;
this.clock = clock;
}
/**
* Returns true if the next operation should fail, and true if not.
*/
public boolean shouldFail() {
if (endOfCycleTimestamp >= 0 && endOfCycleTimestamp <= clock.wallTime()) {
nextCycle();
}
return failureIndicator.get();
}
private void nextCycle() {
synchronized (lock) {
Pair<Supplier<Boolean>, Long> next = nextCycleFactory.get();
long nexWindowMs = next.getRight();
Supplier<Boolean> newFailureIndicator = next.getLeft();
this.endOfCycleTimestamp = nexWindowMs < 0 ? -1 : clock.wallTime() + nexWindowMs;
this.failureIndicator = newFailureIndicator;
}
}
public static ErrorGenerator never() {
return new ErrorGenerator(() -> Pair.of(() -> false, Long.MAX_VALUE / 2), Clocks.system());
}
public static ErrorGenerator always() {
return new ErrorGenerator(() -> Pair.of(() -> true, Long.MAX_VALUE / 2), Clocks.system());
}
public static ErrorGenerator failuresWithFixedRate(double ratio, Clock clock) {
return new ErrorGenerator(() -> failuresWithFixedRateInternal(ratio, -1), clock);
}
public static ErrorGenerator periodicOutages(long upTimeMs, long downTimeMs, Clock clock) {
return new ErrorGenerator(alternating(alwaysUpFactory(upTimeMs), alwaysDownFactory(downTimeMs)), clock);
}
public static ErrorGenerator periodicFailures(long upTimeMs, long errorTimeMs, double ratio, Clock clock) {
Preconditions.checkArgument(upTimeMs > 0 || errorTimeMs > 0, "Both upTime and errorTime cannot be equal to 0");
if (upTimeMs <= 0) {
return failuresWithFixedRate(ratio, clock);
}
if (errorTimeMs <= 0) {
return never();
}
return new ErrorGenerator(alternating(alwaysUpFactory(upTimeMs), failuresWithFixedRateInternal(ratio, errorTimeMs)), clock);
}
private static Pair<Supplier<Boolean>, Long> failuresWithFixedRateInternal(double ratio, long downTimeMs) {
AtomicLong total = new AtomicLong(1);
AtomicLong failures = new AtomicLong(0);
Supplier<Boolean> errorFunction = () -> {
double currentRatio = ((double) failures.get()) / total.incrementAndGet();
if (currentRatio < ratio) {
failures.incrementAndGet();
return true;
}
return false;
};
return Pair.of(errorFunction, downTimeMs);
}
private static Pair<Supplier<Boolean>, Long> alwaysUpFactory(long upTimeMs) {
return Pair.of(() -> false, upTimeMs);
}
private static Pair<Supplier<Boolean>, Long> alwaysDownFactory(long downTimeMs) {
return Pair.of(() -> true, downTimeMs);
}
private static Supplier<Pair<Supplier<Boolean>, Long>> alternating(Pair<Supplier<Boolean>, Long>... sources) {
AtomicLong index = new AtomicLong(0);
return () -> {
int current = (int) (index.getAndIncrement() % sources.length);
return sources[current];
};
}
}
| 647 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/Evaluators.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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.tuple.Either;
import com.netflix.titus.common.util.tuple.Pair;
/**
* A collection of higher order functions helping in conditional expression evaluations.
*/
public final class Evaluators {
private Evaluators() {
}
/**
* Do nothing consumer.
*/
public static <T> void consumeNothing(T value) {
}
/**
* Do nothing runnable.
*/
public static void doNothing() {
}
/**
* Evaluate the given function only if the value is not null.
*/
public static <T> void acceptNotNull(T value, Consumer<T> consumer) {
if (value != null) {
consumer.accept(value);
}
}
/**
* Evaluate the given consumer only if the value is true.
*/
public static <T> void acceptIfTrue(T value, Consumer<Boolean> consumer) {
if (value instanceof Boolean && value == Boolean.TRUE) {
consumer.accept(true);
} else if (value instanceof String && Boolean.parseBoolean((String) value)) {
consumer.accept(true);
}
}
/**
* Evaluate the given function only if value is not null and return the evaluated value.
* Otherwise return null.
*/
public static <T, R> R applyNotNull(T value, Function<T, R> transformer) {
return value != null ? transformer.apply(value) : null;
}
public static <T> T getOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
/**
* Returns first non-null value
*/
public static <T> T getFirstNotNull(T... values) {
for (T value : values) {
if (value != null) {
return value;
}
}
return null;
}
public static void times(int count, Runnable task) {
for (int i = 0; i < count; i++) {
task.run();
}
}
public static void times(int count, Consumer<Integer> task) {
for (int i = 0; i < count; i++) {
task.accept(i);
}
}
public static <T> List<T> evaluateTimes(int count, Function<Integer, T> transformer) {
Preconditions.checkArgument(count >= 0);
if (count == 0) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
result.add(transformer.apply(i));
}
return result;
}
@SafeVarargs
public static <T> Optional<T> firstPresent(Supplier<Optional<T>>... optionalSuppliers) {
for (Supplier<Optional<T>> optionalSupplier : optionalSuppliers) {
Optional<T> optional = optionalSupplier.get();
if (optional.isPresent()) {
return optional;
}
}
return Optional.empty();
}
/**
* Remember last function execution result, and return the cached value on subsequent invocations, until the
* argument changes.
* <h1>
* For memoizing suppliers use {@link com.google.common.base.Suppliers#memoize(com.google.common.base.Supplier)}.
* </h1>
*/
public static <T, R> Function<T, R> memoizeLast(Function<T, R> function) {
AtomicReference<Pair<T, Either<R, Throwable>>> lastRef = new AtomicReference<>();
return argument -> {
Pair<T, Either<R, Throwable>> last = lastRef.get();
if (last != null && Objects.equals(argument, last.getLeft())) {
if (last.getRight().hasValue()) {
return last.getRight().getValue();
}
Throwable error = last.getRight().getError();
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
if (error instanceof Error) {
throw (Error) error;
}
throw new IllegalStateException(error);
}
try {
R result = function.apply(argument);
lastRef.set(Pair.of(argument, Either.ofValue(result)));
return result;
} catch (Throwable e) {
lastRef.set(Pair.of(argument, Either.ofError(e)));
throw e;
}
};
}
/**
* Implementation of a {@link Function} that keeps a cache of its last computed result. Sequential calls to
* the memoized function with _the same input_ will not yield multiple computations and will return the
* cached result.
*/
public static <T, R> Function<T, R> memoizeLast(BiFunction<T, Optional<R>, R> computation) {
AtomicReference<Pair<T, R>> cachedInputResultPair = new AtomicReference<>();
return argument -> {
Pair<T, R> lastPair = cachedInputResultPair.get();
final Optional<R> optionalLastResult = lastPair == null ? Optional.empty() : Optional.of(lastPair.getRight());
if (optionalLastResult.isPresent()) {
T lastArgument = lastPair.getLeft();
if (Objects.equals(argument, lastArgument)) {
return optionalLastResult.get(); // cached
}
}
Pair<T, R> newPair = Pair.of(argument, computation.apply(argument, optionalLastResult));
cachedInputResultPair.set(newPair);
return newPair.getRight();
};
}
}
| 648 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/GraphExt.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;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
/**
* Graph algorithm implementations.
*/
public class GraphExt {
/**
* In the directed graph, given a list of nodes and their edges, return an ordered list of nodes. The ordering
* rule is that if there is a path from node A to B, the node A is ahead of the node B in the list. This is a
* stable sort, so services order is intact unless necessary.
* <p>
* FIXME this is a quick and dirty implementation that works for the single edge scenario only (which we need in ActivationProvisionListener)
*/
public static <T> List<T> order(List<T> nodes, BiFunction<T, T, Boolean> hasEdge) {
List<T> result = new ArrayList<>(nodes);
for (int i = 0; i < nodes.size(); i++) {
for (int j = 0; j < nodes.size(); j++) {
if (i != j) {
T from = nodes.get(i);
T to = nodes.get(j);
// There is an edge from right to left, so we need to move left element after right
if (hasEdge.apply(from, to) && i > j) {
result.remove(j);
result.add(i, to);
return result;
}
}
}
}
return result;
}
}
| 649 |
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/unit/MemoryUnit.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.unit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
public enum MemoryUnit {
BYTES() {
@Override
public long toBytes(long memorySize) {
return memorySize;
}
@Override
public long toKiloBytes(long memorySize) {
return memorySize / _1KB;
}
@Override
public long toMegaBytes(long memorySize) {
return memorySize / _1MB;
}
@Override
public long toGigaBytes(long memorySize) {
return memorySize / _1GB;
}
@Override
public long convert(long memorySize, MemoryUnit memoryUnit) {
return memoryUnit.toBytes(memorySize);
}
@Override
public String format(long memorySize) {
return memorySize + "B";
}
},
KILOBYTES {
@Override
public long toBytes(long memorySize) {
return memorySize * _1KB;
}
@Override
public long toKiloBytes(long memorySize) {
return memorySize;
}
@Override
public long toMegaBytes(long memorySize) {
return memorySize / _1KB;
}
@Override
public long toGigaBytes(long memorySize) {
return memorySize / _1MB;
}
@Override
public long convert(long memorySize, MemoryUnit memoryUnit) {
return memoryUnit.toKiloBytes(memorySize);
}
@Override
public String format(long memorySize) {
return memorySize + "KB";
}
},
MEGABYTES {
@Override
public long toBytes(long memorySize) {
return memorySize * _1MB;
}
@Override
public long toKiloBytes(long memorySize) {
return memorySize * _1KB;
}
@Override
public long toMegaBytes(long memorySize) {
return memorySize;
}
@Override
public long toGigaBytes(long memorySize) {
return memorySize / _1KB;
}
@Override
public long convert(long memorySize, MemoryUnit memoryUnit) {
return memoryUnit.toMegaBytes(memorySize);
}
@Override
public String format(long memorySize) {
return memorySize + "MB";
}
},
GIGABYTES {
@Override
public long toBytes(long memorySize) {
return memorySize * _1GB;
}
@Override
public long toKiloBytes(long memorySize) {
return memorySize * _1MB;
}
@Override
public long toMegaBytes(long memorySize) {
return memorySize * _1KB;
}
@Override
public long toGigaBytes(long memorySize) {
return memorySize;
}
@Override
public long convert(long memorySize, MemoryUnit memoryUnit) {
return memoryUnit.toGigaBytes(memorySize);
}
@Override
public String format(long memorySize) {
return memorySize + "GB";
}
};
static final long _1KB = 1024;
static final long _1MB = _1KB * _1KB;
static final long _1GB = _1MB * _1KB;
private static final Pattern BYTES_RE = Pattern.compile("\\s*(\\d+)\\s*(B|Bytes)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern KB_RE = Pattern.compile("\\s*(\\d+)\\s*(K|KB|KBytes|KiloBytes)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern MB_RE = Pattern.compile("\\s*(\\d+)\\s*(M|MB|MBytes|MegaBytes)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern GB_RE = Pattern.compile("\\s*(\\d+)\\s*(G|GB|GBytes|GigaBytes)\\s*", Pattern.CASE_INSENSITIVE);
public long toBytes(long memorySize) {
throw new AbstractMethodError();
}
public long toKiloBytes(long memorySize) {
throw new AbstractMethodError();
}
public long toMegaBytes(long memorySize) {
throw new AbstractMethodError();
}
public long toGigaBytes(long memorySize) {
throw new AbstractMethodError();
}
public long convert(long memorySize, MemoryUnit memoryUnit) {
throw new AbstractMethodError();
}
public String format(long memorySize) {
throw new AbstractMethodError();
}
public static long bytesOf(String memorySize) {
Preconditions.checkNotNull(memorySize);
Matcher bytesMatcher = BYTES_RE.matcher(memorySize);
if (bytesMatcher.matches()) {
return Long.parseLong(bytesMatcher.group(1));
}
Matcher kbMatcher = KB_RE.matcher(memorySize);
if (kbMatcher.matches()) {
return KILOBYTES.toBytes(Long.parseLong(kbMatcher.group(1)));
}
Matcher mbMatcher = MB_RE.matcher(memorySize);
if (mbMatcher.matches()) {
return MEGABYTES.toBytes(Long.parseLong(mbMatcher.group(1)));
}
Matcher gbMatcher = GB_RE.matcher(memorySize);
if (gbMatcher.matches()) {
return GIGABYTES.toBytes(Long.parseLong(gbMatcher.group(1)));
}
throw new IllegalArgumentException("Invalid memory size format: " + memorySize);
}
public static long kiloBytesOf(String memorySize) {
return BYTES.toKiloBytes(bytesOf(memorySize));
}
public static long megaBytesOf(String memorySize) {
return BYTES.toMegaBytes(bytesOf(memorySize));
}
public static long gigaBytesOf(String memorySize) {
return BYTES.toGigaBytes(bytesOf(memorySize));
}
}
| 650 |
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/unit/TimeUnitExt.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.unit;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Supplementary methods for time interval with unit parsing.
*/
public class TimeUnitExt {
private static final Pattern INTERVAL_WITH_UNIT_RE = Pattern.compile("(\\d+)(ms|s|m|h|d)");
public static Optional<Pair<Long, TimeUnit>> parse(String intervalWithUnit) {
Matcher matcher = INTERVAL_WITH_UNIT_RE.matcher(intervalWithUnit);
if (!matcher.matches()) {
return Optional.empty();
}
long interval = Long.parseLong(matcher.group(1));
String unit = matcher.group(2);
switch (unit) {
case "ms":
return Optional.of(Pair.of(interval, TimeUnit.MILLISECONDS));
case "s":
return Optional.of(Pair.of(interval, TimeUnit.SECONDS));
case "m":
return Optional.of(Pair.of(interval, TimeUnit.MINUTES));
case "h":
return Optional.of(Pair.of(interval, TimeUnit.HOURS));
case "d":
return Optional.of(Pair.of(interval, TimeUnit.DAYS));
}
return Optional.empty();
}
public static Optional<Long> toMillis(String intervalWithUnit) {
return parse(intervalWithUnit).map(p -> p.getRight().toMillis(p.getLeft()));
}
}
| 651 |
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/unit/BandwidthUnit.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.unit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
public enum BandwidthUnit {
BPS() {
@Override
public long toBps(long rate) {
return rate;
}
@Override
public long toKbps(long rate) {
return rate / _1K;
}
@Override
public long toMbps(long rate) {
return rate / _1M;
}
@Override
public long toGbps(long rate) {
return rate / _1G;
}
@Override
public long convert(long rate, BandwidthUnit bandwidthUnit) {
return bandwidthUnit.toBps(rate);
}
@Override
public String format(long rate) {
return rate + "bps";
}
},
KBPS() {
@Override
public long toBps(long rate) {
return rate * _1K;
}
@Override
public long toKbps(long rate) {
return rate;
}
@Override
public long toMbps(long rate) {
return rate / _1K;
}
@Override
public long toGbps(long rate) {
return rate / _1M;
}
@Override
public long convert(long rate, BandwidthUnit bandwidthUnit) {
return bandwidthUnit.toKbps(rate);
}
@Override
public String format(long rate) {
return rate + "kbps";
}
},
MBPS() {
@Override
public long toBps(long rate) {
return rate * _1M;
}
@Override
public long toKbps(long rate) {
return rate * _1K;
}
@Override
public long toMbps(long rate) {
return rate;
}
@Override
public long toGbps(long rate) {
return rate / _1K;
}
@Override
public long convert(long rate, BandwidthUnit bandwidthUnit) {
return bandwidthUnit.toMbps(rate);
}
@Override
public String format(long rate) {
return rate + "mbps";
}
},
GBPS {
@Override
public long toBps(long rate) {
return rate * _1G;
}
@Override
public long toKbps(long rate) {
return rate * _1M;
}
@Override
public long toMbps(long rate) {
return rate * _1K;
}
@Override
public long toGbps(long rate) {
return rate;
}
@Override
public long convert(long rate, BandwidthUnit bandwidthUnit) {
return bandwidthUnit.toGbps(rate);
}
@Override
public String format(long rate) {
return rate + "gbps";
}
};
public long toBps(long rate) {
throw new AbstractMethodError();
}
public long toKbps(long rate) {
throw new AbstractMethodError();
}
public long toMbps(long rate) {
throw new AbstractMethodError();
}
public long toGbps(long rate) {
throw new AbstractMethodError();
}
public long convert(long rate, BandwidthUnit bandwidthUnit) {
throw new AbstractMethodError();
}
public String format(long rate) {
throw new AbstractMethodError();
}
static final long _1K = 1000;
static final long _1M = _1K * _1K;
static final long _1G = _1M * _1K;
private static final Pattern BPS_RE = Pattern.compile("\\s*(\\d+)\\s*(b|bps)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern KBPS_RE = Pattern.compile("\\s*(\\d+)\\s*(k|kbps)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern MBPS_RE = Pattern.compile("\\s*(\\d+)\\s*(m|mbps)\\s*", Pattern.CASE_INSENSITIVE);
private static final Pattern GBPS_RE = Pattern.compile("\\s*(\\d+)\\s*(g|gbps)\\s*", Pattern.CASE_INSENSITIVE);
public static long bpsOf(String rate) {
Preconditions.checkNotNull(rate);
Matcher bpsMatcher = BPS_RE.matcher(rate);
if (bpsMatcher.matches()) {
return Long.parseLong(bpsMatcher.group(1));
}
Matcher kbpsMatcher = KBPS_RE.matcher(rate);
if (kbpsMatcher.matches()) {
return KBPS.toBps(Long.parseLong(kbpsMatcher.group(1)));
}
Matcher mbpsMatcher = MBPS_RE.matcher(rate);
if (mbpsMatcher.matches()) {
return MBPS.toBps(Long.parseLong(mbpsMatcher.group(1)));
}
Matcher gbpsMatcher = GBPS_RE.matcher(rate);
if (gbpsMatcher.matches()) {
return GBPS.toBps(Long.parseLong(gbpsMatcher.group(1)));
}
throw new IllegalArgumentException("Invalid bandwidth format: " + rate);
}
public static long kbpsOf(String rate) {
return BPS.toKbps(bpsOf(rate));
}
public static long mbpsOf(String rate) {
return BPS.toMbps(bpsOf(rate));
}
public static long gbpsOf(String rate) {
return BPS.toGbps(bpsOf(rate));
}
}
| 652 |
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/proxy/ProxyCatalog.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.proxy;
import java.lang.reflect.Proxy;
import java.util.function.Supplier;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.proxy.internal.GuardingInvocationHandler;
import com.netflix.titus.common.util.proxy.internal.InvocationHandlerBridge;
import com.netflix.titus.common.util.proxy.internal.SpectatorInvocationHandler;
/**
* A collection of common interface decorators (logging, metrics collection).
*/
public final class ProxyCatalog {
private ProxyCatalog() {
}
public static <API, INSTANCE extends API> LoggingProxyBuilder<API, INSTANCE> createLoggingProxy(
Class<API> apiInterface, INSTANCE instance) {
return new LoggingProxyBuilder<>(apiInterface, instance);
}
/**
* A default proxy logger logs:
* <ul>
* <li>requests/successful replies at DEBUG level</li>
* <li>exceptions (including error observable replies) at ERROR level</li>
* </ul>
*/
public static <API, INSTANCE extends API> API createDefaultLoggingProxy(Class<API> apiInterface, INSTANCE instance) {
return new LoggingProxyBuilder<>(apiInterface, instance).build();
}
public static <API, INSTANCE extends API> API createSpectatorProxy(String instanceName,
Class<API> apiInterface,
INSTANCE instance,
TitusRuntime titusRuntime,
boolean followObservableResults) {
return (API) Proxy.newProxyInstance(
apiInterface.getClassLoader(),
new Class<?>[]{apiInterface},
new InvocationHandlerBridge<>(new SpectatorInvocationHandler<>(instanceName, apiInterface, titusRuntime, followObservableResults), instance)
);
}
public static <API, INSTANCE extends API> API createGuardingProxy(Class<API> apiInterface, INSTANCE instance, Supplier<Boolean> predicate) {
return (API) Proxy.newProxyInstance(
apiInterface.getClassLoader(),
new Class<?>[]{apiInterface},
new InvocationHandlerBridge<>(new GuardingInvocationHandler<>(apiInterface, myInstance -> predicate.get()), instance)
);
}
}
| 653 |
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/proxy/ProxyInvocationChain.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.proxy;
import java.lang.reflect.Method;
/**
*/
public interface ProxyInvocationChain<NATIVE> {
Object invoke(Object proxy, Method method, Object[] args, NATIVE nativeHandler) throws Throwable;
}
| 654 |
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/proxy/LoggingProxyBuilder.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.proxy;
import java.lang.reflect.Proxy;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.runtime.TitusRuntimes;
import com.netflix.titus.common.util.proxy.internal.InvocationHandlerBridge;
import com.netflix.titus.common.util.proxy.internal.LoggingInvocationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A builder for {@link LoggingInvocationHandler} proxy.
*/
public final class LoggingProxyBuilder<API, INSTANCE extends API> {
public enum Priority {ERROR, INFO, DEBUG, NEVER}
private final Class<API> apiInterface;
private final INSTANCE instance;
private Priority requestLevel = Priority.DEBUG;
private Priority replyLevel = Priority.DEBUG;
private Priority observableReplyLevel = Priority.DEBUG;
private Priority exceptionLevel = Priority.ERROR;
private Priority observableErrorLevel = Priority.ERROR;
private Logger logger;
private TitusRuntime titusRuntime;
public LoggingProxyBuilder(Class<API> apiInterface, INSTANCE instance) {
this.apiInterface = apiInterface;
this.instance = instance;
}
public LoggingProxyBuilder<API, INSTANCE> request(Priority level) {
this.requestLevel = level;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> reply(Priority level) {
this.replyLevel = level;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> observableReply(Priority level) {
this.observableReplyLevel = level;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> exception(Priority level) {
this.exceptionLevel = level;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> observableError(Priority level) {
this.observableErrorLevel = level;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> logger(Logger logger) {
this.logger = logger;
return this;
}
public LoggingProxyBuilder<API, INSTANCE> titusRuntime(TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
return this;
}
public ProxyInvocationHandler buildHandler() {
if (logger == null) {
logger = LoggerFactory.getLogger(getCategory(apiInterface, instance));
}
if (titusRuntime == null) {
titusRuntime = TitusRuntimes.internal();
}
return new LoggingInvocationHandler(
apiInterface,
logger,
requestLevel,
replyLevel,
observableReplyLevel,
exceptionLevel,
observableErrorLevel,
titusRuntime
);
}
public API build() {
return (API) Proxy.newProxyInstance(
apiInterface.getClassLoader(),
new Class<?>[]{apiInterface},
new InvocationHandlerBridge<>(buildHandler(), instance)
);
}
static <API, INSTANCE extends API> Class<?> getCategory(Class<API> apiInterface, INSTANCE instance) {
if (instance == null || instance instanceof java.lang.reflect.Proxy) {
return apiInterface;
}
return instance.getClass();
}
}
| 655 |
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/proxy/ProxyInvocationHandler.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.proxy;
import java.lang.reflect.Method;
/**
*/
public interface ProxyInvocationHandler<NATIVE> {
Object invoke(Object proxy, Method method, Object[] args, NATIVE nativeHandler, ProxyInvocationChain chain) throws Throwable;
}
| 656 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/GuardingInvocationHandler.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.proxy.internal;
import java.lang.reflect.Method;
import java.util.function.Function;
import com.netflix.titus.common.util.proxy.ProxyInvocationChain;
/**
* Given condition function, allows or dis-allows calls to a wrapped API.
*/
public class GuardingInvocationHandler<API, NATIVE> extends AbstractInvocationHandler<API, NATIVE> {
private final Function<API, Boolean> predicate;
private final String errorMessage;
public GuardingInvocationHandler(Class<API> apiInterface, Function<API, Boolean> predicate) {
super(apiInterface);
this.predicate = predicate;
this.errorMessage = apiInterface.getName() + " service call not allowed; service not in active state";
}
@Override
public Object invoke(Object proxy, Method method, Object[] args, NATIVE nativeHandler, ProxyInvocationChain chain) throws Throwable {
if (!getIncludedMethods().contains(method)) {
return chain.invoke(proxy, method, args, nativeHandler);
}
if (!predicate.apply((API) proxy)) {
throw new IllegalStateException(errorMessage);
}
return chain.invoke(proxy, method, args, nativeHandler);
}
}
| 657 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/ProxyMethodSegregator.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.proxy.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import com.netflix.titus.common.util.proxy.annotation.ObservableResult;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
class ProxyMethodSegregator<API> {
private final Set<Method> followedObservables = new HashSet<>();
private final Set<Method> followedFlux = new HashSet<>();
private final Set<Method> followedCompletables = new HashSet<>();
private final Set<Method> followedMonos = new HashSet<>();
ProxyMethodSegregator(Class<API> apiInterface, boolean followObservableResults, Set<Method> includedMethodSet) {
boolean enabledByDefault = followObservableResults || enablesTarget(apiInterface.getAnnotations());
for (Method method : includedMethodSet) {
boolean isObservableResult = method.getReturnType().isAssignableFrom(Observable.class);
boolean isFluxResult = method.getReturnType().isAssignableFrom(Flux.class);
boolean isCompletableResult = method.getReturnType().isAssignableFrom(Completable.class);
boolean isMonoResult = method.getReturnType().isAssignableFrom(Mono.class);
if (isObservableResult || isFluxResult || isCompletableResult || isMonoResult) {
boolean methodEnabled = enabledByDefault || enablesTarget(method.getAnnotations());
if (methodEnabled) {
if (isObservableResult) {
followedObservables.add(method);
} else if (isFluxResult) {
followedFlux.add(method);
} else if (isCompletableResult) {
followedCompletables.add(method);
} else if (isMonoResult) {
followedMonos.add(method);
}
}
}
}
}
Set<Method> getFollowedObservables() {
return followedObservables;
}
Set<Method> getFollowedFlux() {
return followedFlux;
}
Set<Method> getFollowedCompletables() {
return followedCompletables;
}
Set<Method> getFollowedMonos() {
return followedMonos;
}
private boolean enablesTarget(Annotation[] annotations) {
Optional<Annotation> result = find(annotations, ObservableResult.class);
return result.isPresent() && ((ObservableResult) result.get()).enabled();
}
private Optional<Annotation> find(Annotation[] annotations, Class<? extends Annotation> expected) {
for (Annotation current : annotations) {
if (current.annotationType().equals(expected)) {
return Optional.of(current);
}
}
return Optional.empty();
}
}
| 658 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/InterceptingInvocationHandler.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.proxy.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import com.netflix.titus.common.util.ReflectionExt;
import com.netflix.titus.common.util.proxy.ProxyInvocationChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
/**
*/
abstract class InterceptingInvocationHandler<API, NATIVE, CONTEXT> extends AbstractInvocationHandler<API, NATIVE> {
private static final Logger logger = LoggerFactory.getLogger(InterceptingInvocationHandler.class);
private final Set<Method> observableResultFollowers;
private final Set<Method> fluxResultFollowers;
private final Set<Method> completableResultFollowers;
private final Set<Method> monoResultFollowers;
InterceptingInvocationHandler(Class<API> apiInterface, boolean followObservableResults) {
super(apiInterface);
ProxyMethodSegregator<API> methodSegregator = new ProxyMethodSegregator<>(apiInterface, followObservableResults, getIncludedMethods());
this.observableResultFollowers = methodSegregator.getFollowedObservables();
this.fluxResultFollowers = methodSegregator.getFollowedFlux();
this.completableResultFollowers = methodSegregator.getFollowedCompletables();
this.monoResultFollowers = methodSegregator.getFollowedMonos();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args, NATIVE nativeHandler, ProxyInvocationChain chain) throws Throwable {
Method effectiveMethod = ReflectionExt.findInterfaceMethod(method).orElse(method);
if (!getIncludedMethods().contains(effectiveMethod)) {
return chain.invoke(proxy, method, args, nativeHandler);
}
// Before
CONTEXT context = null;
try {
context = before(method, args);
} catch (Throwable e) {
logger.warn("Interceptor {}#before hook execution error ({}={})", getClass().getName(), e.getClass().getName(), e.getMessage());
}
// Actual
Object result;
try {
result = chain.invoke(proxy, method, args, nativeHandler);
} catch (InvocationTargetException e) {
try {
afterException(method, e, context);
} catch (Throwable ie) {
logger.warn("Interceptor {}#afterException hook execution error ({}={})", getClass().getName(), ie.getClass().getName(), ie.getMessage());
}
throw e.getCause();
}
// After
try {
after(method, result, context);
} catch (Throwable e) {
logger.warn("Interceptor {}#after hook execution error ({}={})", getClass().getName(), e.getClass().getName(), e.getMessage());
}
if (observableResultFollowers.contains(method)) {
result = afterObservable(method, (Observable<Object>) result, context);
} else if (fluxResultFollowers.contains(method)) {
result = afterFlux(method, (Flux<Object>) result, context);
} else if (completableResultFollowers.contains(method)) {
result = afterCompletable(method, (Completable) result, context);
} else if (monoResultFollowers.contains(method)) {
result = afterMono(method, (Mono<Object>) result, context);
}
return result;
}
protected abstract CONTEXT before(Method method, Object[] args);
protected abstract void after(Method method, Object result, CONTEXT context);
protected abstract void afterException(Method method, Throwable cause, CONTEXT context);
protected abstract Observable<Object> afterObservable(Method method, Observable<Object> result, CONTEXT context);
protected abstract Flux<Object> afterFlux(Method method, Flux<Object> result, CONTEXT context);
protected abstract Completable afterCompletable(Method method, Completable result, CONTEXT context);
protected abstract Mono<Object> afterMono(Method method, Mono<Object> result, CONTEXT context);
}
| 659 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/InvocationHandlerBridge.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.proxy.internal;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import com.netflix.titus.common.util.proxy.ProxyInvocationHandler;
/**
*/
public class InvocationHandlerBridge<T> implements InvocationHandler {
private static final Object NONE = new Object();
private final DefaultProxyInvocationChain<Object> chain;
public InvocationHandlerBridge(ProxyInvocationHandler<Object> delegate, T instance) {
this.chain = new DefaultProxyInvocationChain<>(Arrays.asList(
delegate,
(proxy, method, args, nativeHandler, chain) -> method.invoke(instance, args)
));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return chain.invoke(proxy, method, args, NONE);
}
}
| 660 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/SpectatorInvocationHandler.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.proxy.internal;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Tag;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.time.Clock;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import rx.Subscription;
import static java.util.Arrays.asList;
/**
* Method invocation metrics collector.
*/
public class SpectatorInvocationHandler<API, NATIVE> extends InterceptingInvocationHandler<API, NATIVE, Long> {
private static final String INVOCATION_COUNTER_METRIC_NAME = "titusMaster.api.invocation.count";
private static final String INVOCATION_TIME_METRIC_NAME = "titusMaster.api.invocation.executionTime";
private static final String RESULT_SUBSCRIPTION_COUNT_METRIC_NAME = "titusMaster.api.invocation.subscriptions";
private static final String RESULT_SUBSCRIPTION_EMITS_METRIC_NAME = "titusMaster.api.invocation.subscriptionEmits";
private static final String RESULT_SUBSCRIPTION_TIME_METRIC_NAME = "titusMaster.api.invocation.subscriptionTime";
private static final Tag TAG_STATUS_SUCCESS = new BasicTag("status", "success");
private static final Tag TAG_STATUS_ERROR = new BasicTag("status", "error");
private static final Tag TAG_CALL_STAGE_ON_METHOD_EXIT = new BasicTag("callStage", "onMethodExit");
private static final Tag TAG_CALL_STAGE_ON_COMPLETED = new BasicTag("callStage", "onCompleted");
private static final Tag TAG_CALL_STAGE_ON_MONO_SUCCESS = new BasicTag("callStage", "onSuccess");
private final Registry registry;
private final Clock clock;
private final List<Tag> commonTags;
public SpectatorInvocationHandler(String instanceName, Class<API> apiInterface, TitusRuntime titusRuntime, boolean followObservableResults) {
super(apiInterface, followObservableResults);
this.registry = titusRuntime.getRegistry();
this.clock = titusRuntime.getClock();
this.commonTags = asList(
new BasicTag("instance", instanceName),
new BasicTag("class", apiInterface.getName())
);
}
@Override
protected Long before(Method method, Object[] args) {
return clock.wallTime();
}
@Override
protected void after(Method method, Object result, Long startTime) {
registry.counter(
INVOCATION_COUNTER_METRIC_NAME,
tags(
"method", method.getName(),
"status", "success"
)
).increment();
reportExecutionTime(method, startTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_METHOD_EXIT);
if (!isAsynchronous(result)) {
reportExecutionTime(method, startTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_COMPLETED);
}
}
@Override
protected void afterException(Method method, Throwable error, Long startTime) {
registry.counter(
INVOCATION_COUNTER_METRIC_NAME,
tags(
"method", method.getName(),
"status", "error",
"exception", getExceptionName(error)
)
).increment();
reportExecutionTime(method, startTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_METHOD_EXIT);
}
@Override
protected Observable<Object> afterObservable(Method method, Observable<Object> result, Long startTime) {
long methodExitTime = clock.wallTime();
return Observable.unsafeCreate(subscriber -> {
long subscriptionTime = clock.wallTime();
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "subscribed"
)
).increment();
reportSubscriptionExecutionTime(method, methodExitTime, subscriptionTime);
Subscription subscription = result.doOnUnsubscribe(() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "unsubscribed"
)
).increment();
}).subscribe(
next -> {
registry.counter(
RESULT_SUBSCRIPTION_EMITS_METRIC_NAME,
tags("method", method.getName())
).increment();
subscriber.onNext(next);
},
error -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onError",
"exception", getExceptionName(error)
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_COMPLETED);
subscriber.onError(error);
},
() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onCompleted"
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_COMPLETED);
subscriber.onCompleted();
}
);
subscriber.add(subscription);
});
}
@Override
protected Flux<Object> afterFlux(Method method, Flux<Object> result, Long startTime) {
long methodExitTime = clock.wallTime();
return Flux.create(emitter -> {
long subscriptionTime = clock.wallTime();
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "subscribed"
)
).increment();
reportSubscriptionExecutionTime(method, methodExitTime, subscriptionTime);
Disposable subscription = result.doOnCancel(() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "unsubscribed"
)
).increment();
}).subscribe(
next -> {
registry.counter(
RESULT_SUBSCRIPTION_EMITS_METRIC_NAME,
tags("method", method.getName())
).increment();
emitter.next(next);
},
error -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onError",
"exception", getExceptionName(error)
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_COMPLETED);
emitter.error(error);
},
() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onCompleted"
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_COMPLETED);
emitter.complete();
}
);
emitter.onCancel(subscription);
});
}
@Override
protected Completable afterCompletable(Method method, Completable result, Long aLong) {
long methodExitTime = clock.wallTime();
return Completable.create(subscriber -> {
long subscriptionTime = clock.wallTime();
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "subscribed"
)
).increment();
reportSubscriptionExecutionTime(method, methodExitTime, subscriptionTime);
Subscription subscription = result
.doOnUnsubscribe(() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "unsubscribed"
)
).increment();
}).subscribe(
() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onCompleted"
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_COMPLETED);
subscriber.onCompleted();
},
error -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onError",
"exception", getExceptionName(error)
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_COMPLETED);
subscriber.onError(error);
}
);
subscriber.onSubscribe(subscription);
});
}
@Override
protected Mono<Object> afterMono(Method method, Mono<Object> result, Long aLong) {
long methodExitTime = clock.wallTime();
return Mono.create(sink -> {
long subscriptionTime = clock.wallTime();
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "subscribed"
)
).increment();
reportSubscriptionExecutionTime(method, methodExitTime, subscriptionTime);
AtomicBoolean emittedValue = new AtomicBoolean();
Disposable subscription = result
.doOnCancel(() -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "unsubscribed"
)
).increment();
}).subscribe(
next -> {
emittedValue.set(true);
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onSuccess",
"monoWithValue", "true"
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_MONO_SUCCESS);
sink.success(next);
},
error -> {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onError",
"exception", getExceptionName(error)
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_MONO_SUCCESS);
sink.error(error);
},
() -> {
if (!emittedValue.get()) {
registry.counter(
RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
tags(
"method", method.getName(),
"subscriptionStage", "onSuccess",
"monoWithValue", "false"
)
).increment();
reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_MONO_SUCCESS);
sink.success();
}
}
);
sink.onCancel(subscription);
});
}
private void reportExecutionTime(Method method, Long startTime, Tag... tags) {
Id id = registry.createId(INVOCATION_TIME_METRIC_NAME,
tags("method", method.getName())
).withTags(tags);
registry.timer(id).record(clock.wallTime() - startTime, TimeUnit.MILLISECONDS);
}
private void reportSubscriptionExecutionTime(Method method, Long startTime, long endTime) {
registry.timer(
RESULT_SUBSCRIPTION_TIME_METRIC_NAME,
tags("method", method.getName())
).record(endTime - startTime, TimeUnit.MILLISECONDS);
}
private boolean isAsynchronous(Object result) {
return result instanceof Observable || result instanceof Completable;
}
private String getExceptionName(Throwable error) {
return error instanceof InvocationHandler
? error.getCause().getClass().getName()
: error.getClass().getName();
}
private List<Tag> tags(String... values) {
List<Tag> result = new ArrayList<>(commonTags.size() + values.length / 2);
result.addAll(commonTags);
for (int i = 0; i < values.length / 2; i++) {
result.add(new BasicTag(values[i * 2], values[i * 2 + 1]));
}
return result;
}
}
| 661 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/DefaultProxyInvocationChain.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.proxy.internal;
import java.lang.reflect.Method;
import java.util.List;
import com.netflix.titus.common.util.proxy.ProxyInvocationChain;
import com.netflix.titus.common.util.proxy.ProxyInvocationHandler;
public class DefaultProxyInvocationChain<NATIVE> implements ProxyInvocationChain<NATIVE> {
private static final ProxyInvocationHandler UNTERMINATED_HANDLER = (proxy, method, args, nativeHandler, chain) -> {
throw new IllegalStateException("Method " + method.getName() + " invocation not handled");
};
private final ProxyInvocationHandler<NATIVE> handler;
private final ProxyInvocationChain<NATIVE> remainingChain;
public DefaultProxyInvocationChain(List<ProxyInvocationHandler<NATIVE>> handlers) {
if (handlers.isEmpty()) {
this.handler = UNTERMINATED_HANDLER;
this.remainingChain = null;
} else {
this.handler = handlers.get(0);
this.remainingChain = new DefaultProxyInvocationChain(handlers.subList(1, handlers.size()));
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args, NATIVE nativeHandler) throws Throwable {
return handler.invoke(proxy, method, args, nativeHandler, remainingChain);
}
}
| 662 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/LoggingInvocationHandler.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.proxy.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.proxy.LoggingProxyBuilder;
import com.netflix.titus.common.util.time.Clock;
import org.slf4j.Logger;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
/**
* Method invocations logger.
*/
public class LoggingInvocationHandler<API, NATIVE> extends InterceptingInvocationHandler<API, NATIVE, Long> {
private static final int MAX_CONTENT_LENGTH = 512;
private static final int MAX_EMITTED_ITEMS_BUFFER = 10;
private final LoggingProxyBuilder.Priority requestLevel;
private final LoggingProxyBuilder.Priority replyLevel;
private final LoggingProxyBuilder.Priority observableReplyLevel;
private final LoggingProxyBuilder.Priority exceptionLevel;
private final LoggingProxyBuilder.Priority observableErrorLevel;
private final Logger logger;
private final Clock clock;
public LoggingInvocationHandler(Class<API> apiInterface,
Logger logger,
LoggingProxyBuilder.Priority requestLevel,
LoggingProxyBuilder.Priority replyLevel,
LoggingProxyBuilder.Priority observableReplyLevel,
LoggingProxyBuilder.Priority exceptionLevel,
LoggingProxyBuilder.Priority observableErrorLevel,
TitusRuntime titusRuntime) {
super(apiInterface, observableReplyLevel != LoggingProxyBuilder.Priority.NEVER);
this.logger = logger;
this.requestLevel = requestLevel;
this.replyLevel = replyLevel;
this.observableReplyLevel = observableReplyLevel;
this.exceptionLevel = exceptionLevel;
this.observableErrorLevel = observableErrorLevel;
this.clock = titusRuntime.getClock();
}
@Override
protected Long before(Method method, Object[] args) {
logWithPriority(requestLevel, () -> {
StringBuilder sb = new StringBuilder("Starting ").append(getMethodSignature(method));
if (args == null || args.length == 0) {
sb.append("()");
} else {
sb.append('(');
for (int i = 0; i < args.length; i++) {
if (i != 0) {
sb.append(',');
}
sb.append(args[i]);
}
sb.append(')');
}
return sb;
});
return clock.wallTime();
}
@Override
protected void after(Method method, Object result, Long startTime) {
logWithPriority(replyLevel, () -> {
StringBuilder sb = new StringBuilder("Returned from ").append(getMethodSignature(method));
sb.append(" after ").append(clock.wallTime() - startTime).append("[ms]");
if (result == null) {
if (void.class.equals(method.getReturnType())) {
sb.append(": void");
} else {
sb.append(": null");
}
} else {
sb.append(": ").append(result.toString());
}
return sb;
});
}
@Override
protected void afterException(Method method, Throwable cause, Long startTime) {
logWithPriority(exceptionLevel, () -> {
Throwable realCause = cause instanceof InvocationTargetException ? cause.getCause() : cause;
StringBuilder sb = new StringBuilder().append("Exception throw in ").append(getMethodSignature(method));
sb.append(" after ").append(clock.wallTime() - startTime).append("[ms]");
sb.append(": (").append(realCause.getClass().getSimpleName()).append(") ").append(realCause.getMessage());
return sb;
});
}
@Override
protected Observable<Object> afterObservable(Method method, Observable<Object> result, Long startTime) {
long methodExitTime = clock.wallTime();
AtomicInteger subscriptionCount = new AtomicInteger();
return Observable.unsafeCreate(subscriber -> {
long start = clock.wallTime();
int idx = subscriptionCount.incrementAndGet();
logOnSubscribe(method, methodExitTime, start, idx);
Queue<Object> emittedItems = new ConcurrentLinkedQueue<>();
AtomicInteger emittedCounter = new AtomicInteger();
result.subscribe(
next -> {
if (emittedCounter.getAndIncrement() < MAX_EMITTED_ITEMS_BUFFER) {
emittedItems.add(next);
}
subscriber.onNext(next);
},
cause -> {
logWithPriority(observableErrorLevel, () -> {
Throwable realCause = cause instanceof InvocationTargetException ? cause.getCause() : cause;
StringBuilder sb = new StringBuilder("Error in subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
sb.append(" with ").append(realCause.getClass().getSimpleName()).append(" (")
.append(realCause.getMessage()).append(')');
sb.append("; emitted ").append(emittedCounter.get()).append(" items ").append(emittedItems);
if (emittedCounter.get() > emittedItems.size()) {
sb.append("...");
}
return sb;
});
subscriber.onError(cause);
},
() -> {
logWithPriority(observableReplyLevel, () -> {
StringBuilder sb = new StringBuilder("Completed subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
sb.append("; emitted ").append(emittedCounter.get()).append(" items ").append(emittedItems);
if (emittedCounter.get() > emittedItems.size()) {
sb.append("...");
}
return sb;
});
subscriber.onCompleted();
}
);
});
}
@Override
protected Flux<Object> afterFlux(Method method, Flux<Object> result, Long aLong) {
// TODO implement
return result;
}
@Override
protected Completable afterCompletable(Method method, Completable result, Long aLong) {
long methodExitTime = clock.wallTime();
AtomicInteger subscriptionCount = new AtomicInteger();
return Completable.create(subscriber -> {
long start = clock.wallTime();
int idx = subscriptionCount.incrementAndGet();
logOnSubscribe(method, methodExitTime, start, idx);
result.subscribe(
() -> {
logWithPriority(observableReplyLevel, () -> {
StringBuilder sb = new StringBuilder("Completed subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
return sb;
});
subscriber.onCompleted();
},
cause -> {
logWithPriority(observableErrorLevel, () -> {
Throwable realCause = cause instanceof InvocationTargetException ? cause.getCause() : cause;
StringBuilder sb = new StringBuilder("Error in subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
sb.append(" with ").append(realCause.getClass().getSimpleName()).append(" (")
.append(realCause.getMessage()).append(')');
return sb;
});
subscriber.onError(cause);
}
);
});
}
@Override
protected Mono<Object> afterMono(Method method, Mono<Object> result, Long aLong) {
long methodExitTime = clock.wallTime();
AtomicInteger subscriptionCount = new AtomicInteger();
return Mono.create(sink -> {
long start = clock.wallTime();
int idx = subscriptionCount.incrementAndGet();
logOnSubscribe(method, methodExitTime, start, idx);
AtomicBoolean emittedValue = new AtomicBoolean();
Disposable subscription = result.subscribe(
next -> {
emittedValue.set(true);
logWithPriority(observableReplyLevel, () -> {
StringBuilder sb = new StringBuilder("Completed subscription with value #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
return sb;
});
sink.success(next);
},
cause -> {
logWithPriority(observableErrorLevel, () -> {
Throwable realCause = cause instanceof InvocationTargetException ? cause.getCause() : cause;
StringBuilder sb = new StringBuilder("Error in subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
sb.append(" with ").append(realCause.getClass().getSimpleName()).append(" (")
.append(realCause.getMessage()).append(')');
return sb;
});
sink.error(cause);
},
() -> {
if (!emittedValue.get()) {
logWithPriority(observableReplyLevel, () -> {
StringBuilder sb = new StringBuilder("Completed subscription without value #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
return sb;
});
sink.success();
}
}
);
sink.onCancel(subscription);
});
}
private void logOnSubscribe(Method method, long methodExitTime, long start, int idx) {
logWithPriority(observableReplyLevel, () -> {
StringBuilder sb = new StringBuilder("Subscription #").append(idx);
sb.append(" in ").append(getMethodSignature(method));
sb.append(" after ").append(start - methodExitTime).append("[ms]");
return sb;
});
}
private void logWithPriority(LoggingProxyBuilder.Priority priority, Supplier<StringBuilder> logBuilder) {
switch (priority) {
case ERROR:
if (logger.isErrorEnabled()) {
logger.error(trimToMaxContentLength(logBuilder.get()));
}
break;
case INFO:
if (logger.isInfoEnabled()) {
logger.info(trimToMaxContentLength(logBuilder.get()));
}
break;
case DEBUG:
if (logger.isDebugEnabled()) {
logger.debug(trimToMaxContentLength(logBuilder.get()));
}
break;
case NEVER:
// Do Nothing
}
}
private String trimToMaxContentLength(StringBuilder sb) {
if (sb.length() > MAX_CONTENT_LENGTH) {
sb.setLength(MAX_CONTENT_LENGTH);
sb.append("...");
}
return sb.toString();
}
}
| 663 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/internal/AbstractInvocationHandler.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.proxy.internal;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.netflix.titus.common.util.proxy.ProxyInvocationHandler;
abstract class AbstractInvocationHandler<API, NATIVE> implements ProxyInvocationHandler<NATIVE> {
private static final Set<Method> EXCLUDED_METHODS = buildExcludedMethodsSet();
private final Set<Method> includedMethodSet;
private final Map<Method, String> methodSignatures;
AbstractInvocationHandler(Class<API> apiInterface) {
this.includedMethodSet = buildIncludedMethodsSet(apiInterface);
this.methodSignatures = buildMethodSignatures(apiInterface, includedMethodSet);
}
Set<Method> getIncludedMethods() {
return includedMethodSet;
}
String getMethodSignature(Method method) {
return methodSignatures.get(method);
}
private Set<Method> buildIncludedMethodsSet(Class<API> apiInterface) {
Set<Method> result = new HashSet<>();
for (Method method : apiInterface.getMethods()) {
if (!EXCLUDED_METHODS.contains(method)) {
result.add(method);
}
}
return result;
}
private Map<Method, String> buildMethodSignatures(Class<API> apiInterface, Set<Method> methods) {
Map<Method, String> result = new HashMap<>();
methods.forEach(method -> result.put(
method,
apiInterface.getSimpleName() + '.' + method.getName()
));
return result;
}
private static Set<Method> buildExcludedMethodsSet() {
Set<Method> result = new HashSet<>();
Collections.addAll(result, Object.class.getMethods());
return result;
}
}
| 664 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/annotation/ObservableResult.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.proxy.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import rx.Observable;
/**
* For methods returning {@link Observable} track its subscription and lifecycle.
* By default, such methods are handled like any other (method entry/exit).
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ObservableResult {
boolean enabled() default true;
}
| 665 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/proxy/annotation/NoIntercept.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.proxy.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Methods annotated with {@link NoIntercept} will not be intercepted.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NoIntercept {
}
| 666 |
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/cache/Caches.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.cache;
import java.time.Duration;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.util.cache.internal.InstrumentedCache;
public class Caches {
public static <K, V> Cache<K, V> instrumentedCacheWithMaxSize(long maxSize, String metricNameRoot, Registry registry) {
com.github.benmanes.caffeine.cache.Cache<K, V> cache = Caffeine.newBuilder()
.maximumSize(maxSize)
.recordStats()
.build();
return new InstrumentedCache<>(metricNameRoot, cache, registry);
}
public static <K, V> Cache<K, V> instrumentedCacheWithMaxSize(long maxSize, Duration timeout, String metricNameRoot, Registry registry) {
com.github.benmanes.caffeine.cache.Cache<K, V> cache = Caffeine.newBuilder()
.maximumSize(maxSize)
.expireAfterWrite(timeout)
.recordStats()
.build();
return new InstrumentedCache<>(metricNameRoot, cache, registry);
}
}
| 667 |
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/cache/Cache.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.cache;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
/**
* A generic cache interface based on the open source library <a href="https://github.com/ben-manes/caffeine">Caffeine</a>.
*
* @param <K> - the type of the keys in the cache
* @param <V> - the type of the values in the cache
*/
@ThreadSafe
public interface Cache<K, V> {
/**
* Returns the value associated with the {@code key} in this cache, or {@code null} if there is no
* cached value for the {@code key}.
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or {@code null} if this map contains no
* mapping for the key
* @throws NullPointerException if the specified key is null
*/
@Nullable
V getIfPresent(@Nonnull Object key);
/**
* Returns the value associated with the {@code key} in this cache, obtaining that value from the
* {@code mappingFunction} if necessary. This method provides a simple substitute for the
* conventional "if cached, return; otherwise create, cache and return" pattern.
* <p>
* If the specified key is not already associated with a value, attempts to compute its value
* using the given mapping function and enters it into this cache unless {@code null}. The entire
* method invocation is performed atomically, so the function is applied at most once per key.
* Some attempted update operations on this cache by other threads may be blocked while the
* computation is in progress, so the computation should be short and simple, and must not attempt
* to update any other mappings of this cache.
* <p>
* <b>Warning:</b> {@code mappingFunction} <b>must not</b>
* attempt to update any other mappings of this cache.
*
* @param key the key with which the specified value is to be associated
* @param mappingFunction the function to compute a value
* @return the current (existing or computed) value associated with the specified key, or null if
* the computed value is null
* @throws NullPointerException if the specified key or mappingFunction is null
* @throws IllegalStateException if the computation detectably attempts a recursive update to this
* cache that would otherwise never complete
* @throws RuntimeException or Error if the mappingFunction does so, in which case the mapping is
* left unestablished
*/
@Nullable
V get(@Nonnull K key, @Nonnull Function<? super K, ? extends V> mappingFunction);
/**
* Returns a map of the values associated with the {@code keys} in this cache. The returned map
* will only contain entries which are already present in the cache.
* <p>
* Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will be
* ignored.
*
* @param keys the keys whose associated values are to be returned
* @return the unmodifiable mapping of keys to values for the specified keys found in this cache
* @throws NullPointerException if the specified collection is null or contains a null element
*/
@Nonnull
Map<K, V> getAllPresent(@Nonnull Iterable<?> keys);
/**
* Associates the {@code value} with the {@code key} in this cache. If the cache previously
* contained a value associated with the {@code key}, the old value is replaced by the new
* {@code value}.
* <p>
* Prefer {@link #get(Object, Function)} when using the conventional "if cached, return; otherwise
* create, cache and return" pattern.
*
* @param key the key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @throws NullPointerException if the specified key or value is null
*/
void put(@Nonnull K key, @Nonnull V value);
/**
* Copies all of the mappings from the specified map to the cache. The effect of this call is
* equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
* {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
* if the specified map is modified while the operation is in progress.
*
* @param map the mappings to be stored in this cache
* @throws NullPointerException if the specified map is null or the specified map contains null
* keys or values
*/
void putAll(@Nonnull Map<? extends K, ? extends V> map);
/**
* Discards any cached value for the {@code key}. The behavior of this operation is undefined for
* an entry that is being loaded and is otherwise not present.
*
* @param key the key whose mapping is to be removed from the cache
* @throws NullPointerException if the specified key is null
*/
void invalidate(@Nonnull Object key);
/**
* Discards any cached values for the {@code keys}. The behavior of this operation is undefined
* for an entry that is being loaded and is otherwise not present.
*
* @param keys the keys whose associated values are to be removed
* @throws NullPointerException if the specified collection is null or contains a null element
*/
void invalidateAll(@Nonnull Iterable<?> keys);
/**
* Returns the approximate number of entries in this cache. The value returned is an estimate; the
* actual count may differ if there are concurrent insertions or removals, or if some entries are
* pending removal due to expiration or weak/soft reference collection. In the case of stale
* entries this inaccuracy can be mitigated by performing a {@link #cleanUp()} first.
*
* @return the estimated number of mappings
*/
void invalidateAll();
/**
* Returns a current snapshot of this cache's cumulative statistics. All statistics are
* initialized to zero, and are monotonically increasing over the lifetime of the cache.
* <p>
* Due to the performance penalty of maintaining statistics, some implementations may not record
* the usage history immediately or at all.
*
* @return the current snapshot of the statistics of this cache
*/
@Nonnegative
long estimatedSize();
/**
* Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
* the map directly affect the cache.
* <p>
* Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for
* concurrent use, but if the cache is modified (including by eviction) after the iterator is
* created, it is undefined which of the changes (if any) will be reflected in that iterator.
*
* @return a thread-safe view of this cache supporting all of the optional {@link Map} operations
*/
@Nonnull
ConcurrentMap<K, V> asMap();
/**
* Performs any pending maintenance operations needed by the cache
*/
void cleanUp();
/**
* Shuts down the cache
*/
void shutdown();
}
| 668 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/cache | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/cache/internal/InstrumentedCache.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.cache.internal;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import com.google.common.base.Preconditions;
import com.netflix.spectator.api.Gauge;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.util.rx.ObservableExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Completable;
import rx.Subscription;
import rx.schedulers.Schedulers;
public class InstrumentedCache<K, V> implements com.netflix.titus.common.util.cache.Cache<K, V> {
private static final Logger logger = LoggerFactory.getLogger(InstrumentedCache.class);
private static final String UPDATE_CACHE_METRICS_NAME = "updateCacheMetrics";
private static final long UPDATE_METRICS_INTERVAL_SEC = 60;
private final Cache<K, V> cache;
private final Subscription metricSubscription;
private final Gauge requestCountGauge;
private final Gauge hitCountGauge;
private final Gauge missCountGauge;
private final Gauge loadSuccessCountGauge;
private final Gauge loadFailureCountGauge;
private final Gauge totalLoadTimeGauge;
private final Gauge evictionCountGauge;
private final Gauge evictionWeightGauge;
private final Gauge estimatedSizeGauge;
private volatile CacheStats lastStatsSnapshot;
public InstrumentedCache(String metricNameRoot, Cache<K, V> cache, Registry registry) {
this.cache = cache;
Preconditions.checkNotNull(registry, "registry");
Preconditions.checkNotNull(cache, "cache");
String metricPrefix = metricNameRoot + ".cache.";
requestCountGauge = registry.gauge(metricPrefix + "requestCount");
hitCountGauge = registry.gauge(metricPrefix + "hitCount");
missCountGauge = registry.gauge(metricPrefix + "missCount");
loadSuccessCountGauge = registry.gauge(metricPrefix + "loadSuccessCount");
loadFailureCountGauge = registry.gauge(metricPrefix + "loadFailureCount");
totalLoadTimeGauge = registry.gauge(metricPrefix + "totalLoadTime");
evictionCountGauge = registry.gauge(metricPrefix + "evictionCount");
evictionWeightGauge = registry.gauge(metricPrefix + "evictionWeight");
estimatedSizeGauge = registry.gauge(metricPrefix + "estimatedSize");
metricSubscription = ObservableExt.schedule(metricNameRoot, registry, UPDATE_CACHE_METRICS_NAME,
Completable.fromAction(this::updateMetrics), 0, UPDATE_METRICS_INTERVAL_SEC, TimeUnit.SECONDS, Schedulers.computation()
).subscribe(
next -> {
if (next.isPresent()) {
Throwable cause = next.get();
logger.error("Unable to update cache metrics with error", cause);
} else {
logger.debug("Successfully updated cache metrics");
}
}
);
}
@Nullable
@Override
public V getIfPresent(@Nonnull Object key) {
return cache.getIfPresent(key);
}
@Nullable
@Override
public V get(@Nonnull K key, @Nonnull Function<? super K, ? extends V> mappingFunction) {
return cache.get(key, mappingFunction);
}
@Nonnull
@Override
public Map<K, V> getAllPresent(@Nonnull Iterable<?> keys) {
return cache.getAllPresent(keys);
}
@Override
public void put(@Nonnull K key, @Nonnull V value) {
cache.put(key, value);
}
@Override
public void putAll(@Nonnull Map<? extends K, ? extends V> map) {
cache.putAll(map);
}
@Override
public void invalidate(@Nonnull Object key) {
cache.invalidate(key);
}
@Override
public void invalidateAll(@Nonnull Iterable<?> keys) {
cache.invalidateAll(keys);
}
@Override
public void invalidateAll() {
cache.invalidateAll();
}
@Override
public long estimatedSize() {
return cache.estimatedSize();
}
@Nonnull
@Override
public ConcurrentMap<K, V> asMap() {
return cache.asMap();
}
@Override
public void cleanUp() {
cache.cleanUp();
}
@Override
public void shutdown() {
ObservableExt.safeUnsubscribe(metricSubscription);
invalidateAll();
cleanUp();
}
private void updateMetrics() {
CacheStats currentStatsSnapshot = cache.stats();
if (lastStatsSnapshot != null) {
CacheStats statsDifference = currentStatsSnapshot.minus(lastStatsSnapshot);
requestCountGauge.set(statsDifference.requestCount());
hitCountGauge.set(statsDifference.hitCount());
missCountGauge.set(statsDifference.missCount());
loadSuccessCountGauge.set(statsDifference.loadSuccessCount());
loadFailureCountGauge.set(statsDifference.loadFailureCount());
totalLoadTimeGauge.set(statsDifference.totalLoadTime());
evictionCountGauge.set(statsDifference.evictionCount());
evictionWeightGauge.set(statsDifference.evictionWeight());
}
estimatedSizeGauge.set(estimatedSize());
lastStatsSnapshot = currentStatsSnapshot;
}
}
| 669 |
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/retry/Retryer.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.retry;
import java.util.Optional;
/**
*/
public interface Retryer {
Optional<Long> getDelayMs();
Retryer retry();
}
| 670 |
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/retry/Retryers.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.retry;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.retry.internal.ExponentialBackoffRetryer;
import com.netflix.titus.common.util.retry.internal.ImmediateRetryer;
import com.netflix.titus.common.util.retry.internal.IntervalRetryer;
import com.netflix.titus.common.util.retry.internal.MaxManyRetryers;
import com.netflix.titus.common.util.retry.internal.NeverRetryer;
/**
*
*/
public final class Retryers {
private Retryers() {
}
public static Retryer never() {
return NeverRetryer.INSTANCE;
}
public static Retryer immediate() {
return ImmediateRetryer.UNLIMITED;
}
public static Retryer immediate(int limit) {
Preconditions.checkArgument(limit > 0, "Retry limit (%s) must be > 0", limit);
return new ImmediateRetryer(limit);
}
public static Retryer interval(long delay, TimeUnit timeUnit) {
return interval(delay, timeUnit, Integer.MAX_VALUE);
}
public static Retryer interval(long delay, TimeUnit timeUnit, int limit) {
Preconditions.checkArgument(delay >= 0, "Delay cannot be negative: %s", delay);
Preconditions.checkArgument(limit > 0, "Retry limit (%s) must be > 0", limit);
return new IntervalRetryer(Optional.of(timeUnit.toMillis(delay)), limit);
}
public static Retryer exponentialBackoff(long initialDelay, long maxDelay, TimeUnit timeUnit) {
return exponentialBackoff(initialDelay, maxDelay, timeUnit, Integer.MAX_VALUE);
}
public static Retryer exponentialBackoff(long initialDelay, long maxDelay, TimeUnit timeUnit, int limit) {
Preconditions.checkArgument(initialDelay >= 0, "Initial delay cannot be negative: %s", initialDelay);
Preconditions.checkArgument(maxDelay >= initialDelay, "Max delay (%s) must be >= initial delay (%s)", maxDelay, initialDelay);
Preconditions.checkArgument(limit > 0, "Retry limit (%s) must be > 0", limit);
return new ExponentialBackoffRetryer(
Optional.of(timeUnit.toMillis(initialDelay)),
timeUnit.toMillis(maxDelay),
limit
);
}
/**
* For each execution evaluates all retryers and returns the maximum delay.
*/
public static Retryer max(Retryer... retryers) {
Preconditions.checkArgument(retryers.length > 0, "At least one retryer expected");
if (retryers.length == 1) {
return retryers[0];
}
return new MaxManyRetryers(retryers);
}
}
| 671 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry/internal/IntervalRetryer.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.retry.internal;
import java.util.Optional;
import com.netflix.titus.common.util.retry.Retryer;
/**
*/
public class IntervalRetryer implements Retryer {
private final Optional<Long> delayMs;
private final int limit;
public IntervalRetryer(Optional<Long> delayMs, int limit) {
this.delayMs = delayMs;
this.limit = limit;
}
@Override
public Optional<Long> getDelayMs() {
return delayMs;
}
@Override
public Retryer retry() {
if (limit == Integer.MAX_VALUE) {
return this;
}
if (limit == 0) {
return NeverRetryer.INSTANCE;
}
return new IntervalRetryer(delayMs, limit - 1);
}
}
| 672 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry/internal/ImmediateRetryer.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.retry.internal;
import java.util.Optional;
import com.netflix.titus.common.util.retry.Retryer;
/**
*/
public class ImmediateRetryer implements Retryer {
private static final Optional<Long> NO_DELAY = Optional.of(0L);
public static final ImmediateRetryer UNLIMITED = new ImmediateRetryer(-1);
private final int limit;
public ImmediateRetryer(int limit) {
this.limit = limit;
}
@Override
public Optional<Long> getDelayMs() {
return NO_DELAY;
}
@Override
public Retryer retry() {
if (limit == Integer.MAX_VALUE) {
return this;
}
if (limit == 0) {
return NeverRetryer.INSTANCE;
}
return new ImmediateRetryer(limit - 1);
}
}
| 673 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry/internal/MaxManyRetryers.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.retry.internal;
import java.util.Optional;
import com.netflix.titus.common.util.retry.Retryer;
public class MaxManyRetryers implements Retryer {
private final Retryer[] retryers;
public MaxManyRetryers(Retryer[] retryers) {
this.retryers = retryers;
}
@Override
public Optional<Long> getDelayMs() {
long maxDelay = -1;
for (Retryer retryer : retryers) {
Optional<Long> next = retryer.getDelayMs();
if (next.isPresent()) {
long nextLong = next.get();
if (nextLong > maxDelay) {
maxDelay = nextLong;
}
} else {
return Optional.empty();
}
}
return maxDelay < 0 ? Optional.empty() : Optional.of(maxDelay);
}
@Override
public Retryer retry() {
Retryer[] newRetryers = new Retryer[retryers.length];
for (int i = 0; i < retryers.length; i++) {
Retryer next = retryers[i].retry();
if (next instanceof NeverRetryer) {
return NeverRetryer.INSTANCE;
}
newRetryers[i] = next;
}
return new MaxManyRetryers(newRetryers);
}
}
| 674 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry/internal/NeverRetryer.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.retry.internal;
import java.util.Optional;
import com.netflix.titus.common.util.retry.Retryer;
/**
*/
public class NeverRetryer implements Retryer {
public static final NeverRetryer INSTANCE = new NeverRetryer();
@Override
public Optional<Long> getDelayMs() {
return Optional.empty();
}
@Override
public Retryer retry() {
return this;
}
}
| 675 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/retry/internal/ExponentialBackoffRetryer.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.retry.internal;
import java.util.Optional;
import com.netflix.titus.common.util.retry.Retryer;
/**
*/
public class ExponentialBackoffRetryer implements Retryer {
private final Optional<Long> currentDelayMs;
private final long maxDelayMs;
private final int limit;
public ExponentialBackoffRetryer(Optional<Long> currentDelayMs, long maxDelayMs, int limit) {
this.currentDelayMs = currentDelayMs;
this.maxDelayMs = maxDelayMs;
this.limit = limit;
}
@Override
public Optional<Long> getDelayMs() {
return currentDelayMs;
}
@Override
public Retryer retry() {
if (limit == Integer.MAX_VALUE && currentDelayMs.get() == maxDelayMs) {
return this;
}
if (limit == 0) {
return NeverRetryer.INSTANCE;
}
return new ExponentialBackoffRetryer(
Optional.of(Math.min(currentDelayMs.get() * 2, maxDelayMs)),
maxDelayMs,
limit - 1
);
}
}
| 676 |
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/loadshedding/AdmissionBackoffStrategy.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.loadshedding;
/**
* Based on observed success / error invocations, computes an adjustment factor for an admission control rate.
*/
public interface AdmissionBackoffStrategy {
/**
* In range 0-1. For example, if admission rate is 100, and throttle factor is 0.5, the effective admission
* rate is computed as 100 * 0.5 = 50.
*/
double getThrottleFactor();
void onSuccess(long elapsedMs);
void onError(long elapsedMs, AdaptiveAdmissionController.ErrorKind errorKind, Throwable cause);
}
| 677 |
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/loadshedding/AdmissionControllerResponse.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.loadshedding;
import java.util.Objects;
import com.netflix.titus.common.util.Evaluators;
public class AdmissionControllerResponse {
/**
* Set to true, if request can be executed, and false if it should be discarded.
*/
private final boolean allowed;
/**
* Human readable explanation of the result.
*/
private final String reasonMessage;
/**
* The name of a {@link AdmissionController} making the final decision.
*/
private final String decisionPoint;
/**
* All requests within the equivalence group are regarded as identical, and share the rate limits.
*/
private final String equivalenceGroup;
public AdmissionControllerResponse(boolean allowed,
String reasonMessage,
String decisionPoint,
String equivalenceGroup) {
this.allowed = allowed;
this.reasonMessage = Evaluators.getOrDefault(reasonMessage, "");
this.decisionPoint = Evaluators.getOrDefault(decisionPoint, "");
this.equivalenceGroup = Evaluators.getOrDefault(equivalenceGroup, "");
}
public boolean isAllowed() {
return allowed;
}
public String getReasonMessage() {
return reasonMessage;
}
public String getDecisionPoint() {
return decisionPoint;
}
public String getEquivalenceGroup() {
return equivalenceGroup;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AdmissionControllerResponse that = (AdmissionControllerResponse) o;
return allowed == that.allowed &&
Objects.equals(reasonMessage, that.reasonMessage) &&
Objects.equals(decisionPoint, that.decisionPoint) &&
Objects.equals(equivalenceGroup, that.equivalenceGroup);
}
@Override
public int hashCode() {
return Objects.hash(allowed, reasonMessage, decisionPoint, equivalenceGroup);
}
@Override
public String toString() {
return "AdmissionControllerResponse{" +
"allowed=" + allowed +
", reasonMessage='" + reasonMessage + '\'' +
", decisionPoint='" + decisionPoint + '\'' +
", equivalenceGroup='" + equivalenceGroup + '\'' +
'}';
}
public Builder toBuilder() {
return newBuilder().withAllowed(allowed).withReasonMessage(reasonMessage).withDecisionPoint(decisionPoint).withEquivalenceGroup(equivalenceGroup);
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private boolean allowed;
private String reasonMessage;
private String decisionPoint;
private String equivalenceGroup;
private Builder() {
}
public Builder withAllowed(boolean allowed) {
this.allowed = allowed;
return this;
}
public Builder withReasonMessage(String reasonMessage) {
this.reasonMessage = reasonMessage;
return this;
}
public Builder withDecisionPoint(String decisionPoint) {
this.decisionPoint = decisionPoint;
return this;
}
public Builder withEquivalenceGroup(String equivalenceGroup) {
this.equivalenceGroup = equivalenceGroup;
return this;
}
public AdmissionControllerResponse build() {
return new AdmissionControllerResponse(allowed, reasonMessage, decisionPoint, equivalenceGroup);
}
}
}
| 678 |
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/loadshedding/AdmissionController.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.loadshedding;
import java.util.function.Function;
/**
* {@link AdmissionController} monitors incoming request rate, and decides if an arriving request
* should be allowed or discarded. All implementations must be thread safe and support concurrent invocations.
*/
public interface AdmissionController extends Function<AdmissionControllerRequest, AdmissionControllerResponse> {
}
| 679 |
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/loadshedding/FixedResponseAdmissionController.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.loadshedding;
public class FixedResponseAdmissionController implements AdaptiveAdmissionController {
private final AdmissionControllerResponse response;
public FixedResponseAdmissionController(AdmissionControllerResponse response) {
this.response = response;
}
@Override
public AdmissionControllerResponse apply(AdmissionControllerRequest admissionControllerRequest) {
return response;
}
@Override
public void onSuccess(long elapsedMs) {
}
@Override
public void onError(long elapsedMs, ErrorKind errorKind, Throwable cause) {
}
}
| 680 |
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/loadshedding/AdmissionControllerRequest.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.loadshedding;
import java.util.Objects;
public class AdmissionControllerRequest {
private final String endpointName;
private final String callerId;
private final int hash;
private AdmissionControllerRequest(String endpointName, String callerId) {
this.endpointName = endpointName;
this.callerId = callerId;
this.hash = Objects.hash(endpointName, callerId);
}
public String getEndpointName() {
return endpointName;
}
public String getCallerId() {
return callerId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AdmissionControllerRequest that = (AdmissionControllerRequest) o;
return Objects.equals(endpointName, that.endpointName) &&
Objects.equals(callerId, that.callerId);
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return "AdmissionControllerRequest{" +
"endpointName='" + endpointName + '\'' +
", callerId='" + callerId + '\'' +
'}';
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private String endpointName;
private String callerId;
private Builder() {
}
public Builder withEndpointName(String endpointName) {
this.endpointName = endpointName;
return this;
}
public Builder withCallerId(String callerId) {
this.callerId = callerId;
return this;
}
public Builder but() {
return newBuilder().withEndpointName(endpointName).withCallerId(callerId);
}
public AdmissionControllerRequest build() {
return new AdmissionControllerRequest(endpointName, callerId);
}
}
}
| 681 |
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/loadshedding/AdmissionControllers.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.loadshedding;
import java.util.function.Supplier;
import com.netflix.archaius.api.Config;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.loadshedding.backoff.NoOpAdmissionBackoffStrategy;
import com.netflix.titus.common.util.loadshedding.backoff.SimpleAdmissionBackoffStrategy;
import com.netflix.titus.common.util.loadshedding.backoff.SimpleAdmissionBackoffStrategyConfiguration;
import com.netflix.titus.common.util.loadshedding.tokenbucket.ArchaiusTokenBucketAdmissionConfigurationParser;
import com.netflix.titus.common.util.loadshedding.tokenbucket.ConfigurableTokenBucketAdmissionController;
/**
* {@link AdmissionController} factory.
*/
public final class AdmissionControllers {
public static AdmissionBackoffStrategy noBackoff() {
return NoOpAdmissionBackoffStrategy.getInstance();
}
public static AdmissionBackoffStrategy simpleBackoff(String id,
SimpleAdmissionBackoffStrategyConfiguration configuration,
TitusRuntime titusRuntime) {
return new SimpleAdmissionBackoffStrategy(id, configuration, titusRuntime);
}
public static AdmissionController circuitBreaker(AdmissionController delegate, Supplier<Boolean> condition) {
return new CircuitBreakerAdmissionController(delegate, condition);
}
public static AdaptiveAdmissionController circuitBreaker(AdaptiveAdmissionController delegate, Supplier<Boolean> condition) {
return new CircuitBreakerAdaptiveAdmissionController(delegate, condition);
}
public static AdaptiveAdmissionController fixed(AdmissionControllerResponse response) {
return new FixedResponseAdmissionController(response);
}
public static AdmissionController spectator(AdmissionController delegate, TitusRuntime titusRuntime) {
return new SpectatorAdmissionController(delegate, titusRuntime);
}
public static AdaptiveAdmissionController spectator(AdaptiveAdmissionController delegate, TitusRuntime titusRuntime) {
return new SpectatorAdaptiveAdmissionController(delegate, titusRuntime);
}
public static AdmissionController tokenBucketsFromArchaius(Config config, boolean includeDetailsInResponse, TitusRuntime titusRuntime) {
return tokenBucketsFromArchaius(config, noBackoff(), includeDetailsInResponse, titusRuntime);
}
public static AdaptiveAdmissionController tokenBucketsFromArchaius(Config config,
AdmissionBackoffStrategy backoffStrategy,
boolean includeDetailsInResponse,
TitusRuntime titusRuntime) {
return new ConfigurableTokenBucketAdmissionController(
new ArchaiusTokenBucketAdmissionConfigurationParser(config),
backoffStrategy,
includeDetailsInResponse,
titusRuntime
);
}
}
| 682 |
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/loadshedding/CircuitBreakerAdmissionController.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.loadshedding;
import java.util.function.Supplier;
/**
* {@link CircuitBreakerAdmissionController} short circuits the admission process if 'enabled' returns false.
*/
public class CircuitBreakerAdmissionController implements AdmissionController {
private static final AdmissionControllerResponse OK_FROM_CIRCUIT_BREAKER = AdmissionControllerResponse.newBuilder()
.withAllowed(true)
.withReasonMessage("Enforced by circuit breaker")
.withDecisionPoint(CircuitBreakerAdmissionController.class.getSimpleName())
.withEquivalenceGroup("all")
.build();
final AdmissionController delegate;
private final Supplier<Boolean> enabled;
public CircuitBreakerAdmissionController(AdmissionController delegate, Supplier<Boolean> enabled) {
this.delegate = delegate;
this.enabled = enabled;
}
@Override
public AdmissionControllerResponse apply(AdmissionControllerRequest request) {
if (enabled.get()) {
return delegate.apply(request);
}
return OK_FROM_CIRCUIT_BREAKER;
}
}
| 683 |
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/loadshedding/CircuitBreakerAdaptiveAdmissionController.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.loadshedding;
import java.util.function.Supplier;
public class CircuitBreakerAdaptiveAdmissionController extends CircuitBreakerAdmissionController implements AdaptiveAdmissionController {
public CircuitBreakerAdaptiveAdmissionController(AdmissionController delegate, Supplier<Boolean> enabled) {
super(delegate, enabled);
}
@Override
public void onSuccess(long elapsedMs) {
((AdaptiveAdmissionController) delegate).onSuccess(elapsedMs);
}
@Override
public void onError(long elapsedMs, AdaptiveAdmissionController.ErrorKind errorKind, Throwable cause) {
((AdaptiveAdmissionController) delegate).onError(elapsedMs, errorKind, cause);
}
}
| 684 |
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/loadshedding/SpectatorAdmissionController.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.loadshedding;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.runtime.TitusRuntime;
import static com.netflix.titus.common.util.StringExt.getNonEmptyOrDefault;
public class SpectatorAdmissionController implements AdmissionController {
private static final String METRIC_NAME = "titus.admissionController.decision";
final AdmissionController delegate;
private final Registry registry;
public SpectatorAdmissionController(AdmissionController delegate, TitusRuntime titusRuntime) {
this.delegate = delegate;
this.registry = titusRuntime.getRegistry();
}
@Override
public AdmissionControllerResponse apply(AdmissionControllerRequest request) {
try {
AdmissionControllerResponse result = delegate.apply(request);
registry.counter(METRIC_NAME,
"callerId", getNonEmptyOrDefault(request.getCallerId(), "requiredButNotSet"),
"endpointName", getNonEmptyOrDefault(request.getEndpointName(), "requiredButNotSet)"),
"allowed", "" + result.isAllowed(),
"decisionPoint", getNonEmptyOrDefault(result.getDecisionPoint(), "requiredButNotSet"),
"equivalenceGroup", getNonEmptyOrDefault(result.getEquivalenceGroup(), "requiredButNotSet")
).increment();
return result;
} catch (Exception e) {
registry.counter(METRIC_NAME,
"callerId", getNonEmptyOrDefault(request.getCallerId(), "requiredButNotSet"),
"endpointName", getNonEmptyOrDefault(request.getEndpointName(), "requiredButNotSet"),
"error", e.getClass().getSimpleName()
).increment();
throw e;
}
}
}
| 685 |
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/loadshedding/AdaptiveAdmissionController.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.loadshedding;
/**
* {@link AdmissionController} variant that allows for dynamic adjustment of admission rate limits.
* All implementations must be thread safe and support concurrent invocations.
*/
public interface AdaptiveAdmissionController extends AdmissionController {
enum ErrorKind {
RateLimited,
Unavailable,
}
void onSuccess(long elapsedMs);
void onError(long elapsedMs, ErrorKind errorKind, Throwable cause);
}
| 686 |
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/loadshedding/SpectatorAdaptiveAdmissionController.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.loadshedding;
import com.netflix.titus.common.runtime.TitusRuntime;
public class SpectatorAdaptiveAdmissionController extends SpectatorAdmissionController implements AdaptiveAdmissionController {
public SpectatorAdaptiveAdmissionController(AdaptiveAdmissionController delegate, TitusRuntime titusRuntime) {
super(delegate, titusRuntime);
}
@Override
public void onSuccess(long elapsedMs) {
((AdaptiveAdmissionController) delegate).onSuccess(elapsedMs);
}
@Override
public void onError(long elapsedMs, ErrorKind errorKind, Throwable cause) {
((AdaptiveAdmissionController) delegate).onError(elapsedMs, errorKind, cause);
}
}
| 687 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/backoff/SimpleAdmissionBackoffStrategy.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.loadshedding.backoff;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
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.loadshedding.AdaptiveAdmissionController;
import com.netflix.titus.common.util.loadshedding.AdmissionBackoffStrategy;
import com.netflix.titus.common.util.time.Clock;
/**
* A simple strategy that aims at achieving an effective admission rate close to the maximum that can be handled by
* the request handler.
*/
public class SimpleAdmissionBackoffStrategy implements AdmissionBackoffStrategy {
private static final String METRIC_ROOT = "titus.admissionController.simpleBackoff.";
private final SimpleAdmissionBackoffStrategyConfiguration configuration;
private final Clock clock;
private final Registry registry;
private volatile long beginningTimestamp;
private volatile double throttleFactor;
private final Lock lock = new ReentrantLock();
private final AtomicLong successCount = new AtomicLong();
private final AtomicLong unavailableCount = new AtomicLong();
private final AtomicLong rateLimitedCount = new AtomicLong();
private final Id metricIdThrottleFactor;
public SimpleAdmissionBackoffStrategy(String id,
SimpleAdmissionBackoffStrategyConfiguration configuration,
TitusRuntime titusRuntime) {
this.configuration = configuration;
this.clock = titusRuntime.getClock();
this.registry = titusRuntime.getRegistry();
this.beginningTimestamp = clock.wallTime();
this.throttleFactor = 1.0;
this.metricIdThrottleFactor = registry.createId(METRIC_ROOT + "throttleFactor", "id", id);
PolledMeter.using(registry).withId(metricIdThrottleFactor).monitorValue(this, self -> self.throttleFactor);
}
public void close() {
PolledMeter.remove(registry, metricIdThrottleFactor);
}
@Override
public double getThrottleFactor() {
long now = clock.wallTime();
if ((beginningTimestamp + configuration.getMonitoringIntervalMs()) > now) {
return throttleFactor;
}
if (!lock.tryLock()) {
return throttleFactor;
}
try {
adjustThrottleFactor(now);
} finally {
lock.unlock();
}
return throttleFactor;
}
@Override
public void onSuccess(long elapsedMs) {
successCount.getAndIncrement();
}
@Override
public void onError(long elapsedMs, AdaptiveAdmissionController.ErrorKind errorKind, Throwable cause) {
switch (errorKind) {
case RateLimited:
default:
rateLimitedCount.getAndIncrement();
break;
case Unavailable:
unavailableCount.getAndIncrement();
break;
}
}
private void adjustThrottleFactor(long now) {
// Order is important here. First check for unavailable errors. Next rate limited, and only as the last one success.
if (unavailableCount.get() > 0) {
this.throttleFactor = configuration.getUnavailableThrottleFactor();
} else if (rateLimitedCount.get() > 0) {
this.throttleFactor = Math.max(
configuration.getUnavailableThrottleFactor(),
throttleFactor - configuration.getRateLimitedDownAdjustment()
);
} else if (successCount.get() > 0) {
this.throttleFactor = Math.min(
1.0,
throttleFactor + configuration.getRateLimitedUpAdjustment()
);
}
successCount.set(0);
rateLimitedCount.set(0);
unavailableCount.set(0);
beginningTimestamp = now;
}
}
| 688 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/backoff/NoOpAdmissionBackoffStrategy.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.loadshedding.backoff;
import com.netflix.titus.common.util.loadshedding.AdaptiveAdmissionController;
import com.netflix.titus.common.util.loadshedding.AdmissionBackoffStrategy;
public class NoOpAdmissionBackoffStrategy implements AdmissionBackoffStrategy {
private static final NoOpAdmissionBackoffStrategy INSTANCE = new NoOpAdmissionBackoffStrategy();
@Override
public double getThrottleFactor() {
return 1.0;
}
@Override
public void onSuccess(long elapsedMs) {
}
@Override
public void onError(long elapsedMs, AdaptiveAdmissionController.ErrorKind errorKind, Throwable cause) {
}
public static AdmissionBackoffStrategy getInstance() {
return INSTANCE;
}
}
| 689 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/backoff/SimpleAdmissionBackoffStrategyConfiguration.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.loadshedding.backoff;
import com.netflix.archaius.api.annotations.DefaultValue;
public interface SimpleAdmissionBackoffStrategyConfiguration {
@DefaultValue("5000")
long getMonitoringIntervalMs();
@DefaultValue("0.1")
double getUnavailableThrottleFactor();
@DefaultValue("0.25")
double getRateLimitedDownAdjustment();
@DefaultValue("0.05")
double getRateLimitedUpAdjustment();
}
| 690 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/tokenbucket/TokenBucketAdmissionController.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.loadshedding.tokenbucket;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.cache.Cache;
import com.netflix.titus.common.util.cache.Caches;
import com.netflix.titus.common.util.limiter.Limiters;
import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket;
import com.netflix.titus.common.util.loadshedding.AdaptiveAdmissionController;
import com.netflix.titus.common.util.loadshedding.AdmissionBackoffStrategy;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerResponse;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Admission controller with multiple token buckets. A token bucket is selected by evaluating matching criteria in
* declaration order until first match is found. The selected bucket is tried, and either success or failure is
* returned to the caller.
* <p/>
* <h1>Example: shared caller bucket</h1>
* slowMethods.sharedByCallers=true<br/>
* slowMethods.callerPattern=.*<br/>
* slowMethods.endpointPattern=create.*<br/>
* ...</br>
* <p/>
* fastMethods.sharedByCallers=true<br/>
* fastMethods.callerPattern=.*<br/>
* fastMethods.endpointPattern=get.*<br/>
* ...</br>
* <p/>
* Caller Alice and Bob making a call to createJob method will share a single bucket with id (.*, create.*), and
* a single bucket for methods getJob/getTask/etc with id (.*, get.*).
* <p/>
* <h1>Example: per caller bucket</h1>
* slowMethods.sharedByCallers=false<br/>
* slowMethods.callerPattern=.*<br/>
* slowMethods.endpointPattern=create.*<br/>
* ...</br>
* <p/>
* fastMethods.sharedByCallers=false<br/>
* fastMethods.callerPattern=.*<br/>
* fastMethods.endpointPattern=get.*<br/>
* ...</br>
* <p/>
* Caller Alice and Bob making a call to createJob method will have own buckets with ids (Alice, create.*) and
* (Bob, create.*). Similarly, for methods getJob/getTask/etc there will be two buckets (Alice, get.*) and
* (Bob, get.*) respectively.
*/
public class TokenBucketAdmissionController implements AdaptiveAdmissionController {
private static final Logger logger = LoggerFactory.getLogger(TokenBucketAdmissionController.class);
private static final String METRIC_ROOT = "titus.tokenBucketAdmissionController.";
private static final AdmissionControllerResponse RESPONSE_DEFAULT_OK = AdmissionControllerResponse.newBuilder()
.withAllowed(true)
.withReasonMessage("Rate limits not configured")
.build();
private static final AdmissionControllerResponse RESPONSE_ALLOWED = AdmissionControllerResponse.newBuilder()
.withAllowed(true)
.withReasonMessage("Consumed one token")
.build();
private static final AdmissionControllerResponse RESPONSE_NO_TOKENS = AdmissionControllerResponse.newBuilder()
.withAllowed(false)
.withReasonMessage("No more tokens")
.build();
private static final AdmissionControllerResponse RESPONSE_BACKOFF = AdmissionControllerResponse.newBuilder()
.withAllowed(false)
.withReasonMessage("Rate limited due to backoff")
.build();
private static final int MAX_CACHE_SIZE = 10_000;
private static final Duration CACHE_ITEM_TIMEOUT = Duration.ofSeconds(600);
private final List<TokenBucketConfiguration> tokenBucketConfigurations;
private final AdmissionBackoffStrategy admissionBackoffStrategy;
/**
* String concatenation is expensive, so request detailed response message explicitly if desired.
*/
private final boolean includeDetailsInResponse;
/**
* Bucket id consists of a caller id (or caller pattern), and endpoint pattern.
*/
private final Cache<Pair<String, String>, TokenBucketInstance> bucketsById;
private final Random random = new Random();
/**
* Maps requests to its assigned bucket ids. We cannot map to the {@link TokenBucketInstance} directly, as its
* lifecycle is managed by {@link #bucketsById} cache, and we would not know when it was recreated.
*/
private final Cache<AdmissionControllerRequest, Pair<String, String>> requestToBucketIdCache;
private final TitusRuntime titusRuntime;
public TokenBucketAdmissionController(List<TokenBucketConfiguration> tokenBucketConfigurations,
AdmissionBackoffStrategy admissionBackoffStrategy,
boolean includeDetailsInResponse,
TitusRuntime titusRuntime) {
this.tokenBucketConfigurations = tokenBucketConfigurations;
this.admissionBackoffStrategy = admissionBackoffStrategy;
this.includeDetailsInResponse = includeDetailsInResponse;
this.bucketsById = Caches.instrumentedCacheWithMaxSize(
MAX_CACHE_SIZE,
CACHE_ITEM_TIMEOUT,
METRIC_ROOT + "cache",
titusRuntime.getRegistry()
);
this.requestToBucketIdCache = Caches.instrumentedCacheWithMaxSize(
MAX_CACHE_SIZE,
CACHE_ITEM_TIMEOUT,
METRIC_ROOT + "requestCache",
titusRuntime.getRegistry()
);
this.titusRuntime = titusRuntime;
}
@Override
public AdmissionControllerResponse apply(AdmissionControllerRequest request) {
TokenBucketInstance tokenBucket = findTokenBucket(request).orElse(null);
if (tokenBucket == null) {
return RESPONSE_DEFAULT_OK;
}
return includeDetailsInResponse ? consumeWithDetailedResponse(tokenBucket) : consumeFast(tokenBucket);
}
@Override
public void onSuccess(long elapsedMs) {
admissionBackoffStrategy.onSuccess(elapsedMs);
}
@Override
public void onError(long elapsedMs, ErrorKind errorKind, Throwable cause) {
admissionBackoffStrategy.onError(elapsedMs, errorKind, cause);
}
private Optional<TokenBucketInstance> findTokenBucket(AdmissionControllerRequest request) {
Pair<String, String> bucketId = requestToBucketIdCache.getIfPresent(request);
if (bucketId != null) {
TokenBucketInstance instance = bucketsById.getIfPresent(bucketId);
if (instance != null) {
return Optional.of(instance);
}
}
TokenBucketConfiguration tokenBucketConfiguration = tokenBucketConfigurations.stream()
.filter(configuration -> matches(configuration, request))
.findFirst()
.orElse(null);
if (tokenBucketConfiguration == null) {
return Optional.empty();
}
// If shared, use pattern name as key, otherwise use caller id
String effectiveCallerId = tokenBucketConfiguration.isSharedByCallers()
? tokenBucketConfiguration.getCallerPatternString()
: request.getCallerId();
if (bucketId == null) {
bucketId = Pair.of(effectiveCallerId, tokenBucketConfiguration.getEndpointPatternString());
requestToBucketIdCache.put(request, bucketId);
}
return Optional.ofNullable(bucketsById.get(bucketId, i ->
new TokenBucketInstance(effectiveCallerId, tokenBucketConfiguration, titusRuntime.getClock())
));
}
private boolean matches(TokenBucketConfiguration configuration, AdmissionControllerRequest request) {
try {
if (!configuration.getCallerPattern().matcher(request.getCallerId()).matches()) {
return false;
}
if (!configuration.getEndpointPattern().matcher(request.getEndpointName()).matches()) {
return false;
}
return true;
} catch (Exception e) {
logger.warn("Unexpected error", e);
return false;
}
}
private AdmissionControllerResponse consumeFast(TokenBucketInstance tokenBucketInstance) {
TokenBucket tokenBucket = tokenBucketInstance.getTokenBucket();
if (tokenBucket.tryTake()) {
double factor = admissionBackoffStrategy.getThrottleFactor();
if (factor < 1.0 && random.nextDouble() >= factor) {
return RESPONSE_BACKOFF;
}
return RESPONSE_ALLOWED;
}
return RESPONSE_NO_TOKENS;
}
private AdmissionControllerResponse consumeWithDetailedResponse(TokenBucketInstance tokenBucketInstance) {
AdmissionControllerResponse.Builder builder = AdmissionControllerResponse.newBuilder();
TokenBucket tokenBucket = tokenBucketInstance.getTokenBucket();
if (tokenBucket.tryTake()) {
double factor = admissionBackoffStrategy.getThrottleFactor();
if (factor < 1.0 && random.nextDouble() >= factor) {
builder.withAllowed(false)
.withReasonMessage("Rate limited due to backoff: bucketName=" +
tokenBucketInstance.getConfiguration().getName() + ", backoffFactor=" + factor);
} else {
builder.withAllowed(true)
.withReasonMessage("Consumed token of: bucketName=" +
tokenBucketInstance.getConfiguration().getName() + ", remainingTokens=" + tokenBucket.getNumberOfTokens());
}
} else {
builder.withAllowed(false)
.withReasonMessage("No more tokens: bucketName=" +
tokenBucketInstance.getConfiguration().getName() + ", remainingTokens=" + tokenBucket.getNumberOfTokens());
}
return builder.withDecisionPoint(TokenBucketAdmissionController.class.getSimpleName())
.withEquivalenceGroup(tokenBucketInstance.getId())
.build();
}
private static class TokenBucketInstance {
private final TokenBucketConfiguration configuration;
private final TokenBucket tokenBucket;
private final String id;
private TokenBucketInstance(String effectiveCallerId, TokenBucketConfiguration configuration, Clock clock) {
this.configuration = configuration;
this.tokenBucket = Limiters.createFixedIntervalTokenBucket(
configuration.getName(),
configuration.getCapacity(),
configuration.getCapacity(),
configuration.getRefillRateInSec(),
1,
TimeUnit.SECONDS,
clock
);
this.id = String.format("%s/%s", configuration.getName(), effectiveCallerId);
}
public TokenBucketConfiguration getConfiguration() {
return configuration;
}
public String getId() {
return id;
}
public TokenBucket getTokenBucket() {
return tokenBucket;
}
}
}
| 691 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/tokenbucket/ConfigurableTokenBucketAdmissionController.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.loadshedding.tokenbucket;
import java.io.Closeable;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.titus.common.framework.scheduler.ExecutionContext;
import com.netflix.titus.common.framework.scheduler.ScheduleReference;
import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.loadshedding.AdaptiveAdmissionController;
import com.netflix.titus.common.util.loadshedding.AdmissionBackoffStrategy;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerResponse;
import com.netflix.titus.common.util.loadshedding.FixedResponseAdmissionController;
import com.netflix.titus.common.util.retry.Retryers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A wrapper around {@link TokenBucketAdmissionController} which is created from the dynamically loaded configuration.
* When configuration changes, the current {@link TokenBucketAdmissionController} instance is discarded, a new one
* is created. As a result token buckets state is reset, which is fine as long as changes do not happen too
* frequently.
*/
public class ConfigurableTokenBucketAdmissionController implements AdaptiveAdmissionController, Closeable {
private static final Logger logger = LoggerFactory.getLogger(ConfigurableTokenBucketAdmissionController.class);
@VisibleForTesting
static final ScheduleDescriptor SCHEDULE_DESCRIPTOR = ScheduleDescriptor.newBuilder()
.withName(ConfigurableTokenBucketAdmissionController.class.getSimpleName())
.withDescription("Configuration re-loader")
.withInitialDelay(Duration.ZERO)
.withInterval(Duration.ofSeconds(1))
.withTimeout(Duration.ofSeconds(1))
.withRetryerSupplier(Retryers::never)
.withOnErrorHandler((action, error) -> {
logger.warn("Cannot load configuration: {}", error.getMessage());
logger.debug(error.getMessage(), error);
})
.build();
private static final AdmissionControllerResponse ALL_ALLOWED = AdmissionControllerResponse.newBuilder()
.withAllowed(true)
.withReasonMessage("Admission controller configuration not found")
.withDecisionPoint(ConfigurableTokenBucketAdmissionController.class.getSimpleName())
.withEquivalenceGroup("all")
.build();
private final Supplier<List<TokenBucketConfiguration>> configurationSupplier;
private final Function<List<TokenBucketConfiguration>, AdaptiveAdmissionController> delegateFactory;
private final ScheduleReference ref;
private volatile List<TokenBucketConfiguration> activeConfiguration = Collections.emptyList();
private volatile AdaptiveAdmissionController delegate = new FixedResponseAdmissionController(ALL_ALLOWED);
public ConfigurableTokenBucketAdmissionController(Supplier<List<TokenBucketConfiguration>> configurationSupplier,
AdmissionBackoffStrategy admissionBackoffStrategy,
boolean includeDetailsInResponse,
TitusRuntime titusRuntime) {
this(configurationSupplier,
tokenBucketConfigurations -> new TokenBucketAdmissionController(tokenBucketConfigurations,
admissionBackoffStrategy, includeDetailsInResponse, titusRuntime),
SCHEDULE_DESCRIPTOR,
titusRuntime
);
}
@VisibleForTesting
ConfigurableTokenBucketAdmissionController(Supplier<List<TokenBucketConfiguration>> configurationSupplier,
Function<List<TokenBucketConfiguration>, AdaptiveAdmissionController> delegateFactory,
ScheduleDescriptor scheduleDescriptor,
TitusRuntime titusRuntime) {
this.configurationSupplier = configurationSupplier;
this.delegateFactory = delegateFactory;
this.ref = titusRuntime.getLocalScheduler().schedule(scheduleDescriptor, this::reload, false);
}
@Override
public void close() {
ref.cancel();
}
@Override
public AdmissionControllerResponse apply(AdmissionControllerRequest request) {
return delegate.apply(request);
}
@Override
public void onSuccess(long elapsedMs) {
delegate.onSuccess(elapsedMs);
}
@Override
public void onError(long elapsedMs, ErrorKind errorKind, Throwable cause) {
delegate.onError(elapsedMs, errorKind, cause);
}
private void reload(ExecutionContext context) {
List<TokenBucketConfiguration> current = configurationSupplier.get();
if (!current.equals(activeConfiguration)) {
this.delegate = delegateFactory.apply(current);
this.activeConfiguration = current;
logger.info("Reloaded configuration: {}", current);
}
}
}
| 692 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/tokenbucket/ArchaiusTokenBucketAdmissionConfigurationParser.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.loadshedding.tokenbucket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import com.google.common.base.Preconditions;
import com.netflix.archaius.api.Config;
import com.netflix.titus.common.util.PropertiesExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Example configuration layout:
* default.order=100
* default.sharedByCallers=true
* default.callerPattern=.*
* default.endpointPattern=.*
* default.capacity=100
* default.refillRateInSec=20
*/
public class ArchaiusTokenBucketAdmissionConfigurationParser implements Supplier<List<TokenBucketConfiguration>> {
private static final Logger logger = LoggerFactory.getLogger(ArchaiusTokenBucketAdmissionConfigurationParser.class);
private final Config config;
private volatile List<TokenBucketConfiguration> bucketConfigurations = Collections.emptyList();
public ArchaiusTokenBucketAdmissionConfigurationParser(Config config) {
this.config = config;
}
public List<TokenBucketConfiguration> get() {
List<TokenBucketConfiguration> currentConfiguration = parseToBucketConfiguration();
currentConfiguration.sort(Comparator.comparingInt(TokenBucketConfiguration::getOrder));
if (currentConfiguration.equals(bucketConfigurations)) {
return bucketConfigurations;
}
return this.bucketConfigurations = currentConfiguration;
}
private List<TokenBucketConfiguration> parseToBucketConfiguration() {
Map<String, String> allKeyValues = new HashMap<>();
config.getKeys().forEachRemaining(key -> allKeyValues.put(key, config.getString(key)));
Map<String, Map<String, String>> bucketProperties = PropertiesExt.groupByRootName(allKeyValues, 1);
List<TokenBucketConfiguration> currentBucketConfigurations = new ArrayList<>();
bucketProperties.forEach((name, bucketConfiguration) -> {
try {
currentBucketConfigurations.add(new TokenBucketConfiguration(
name,
Integer.parseInt(bucketConfiguration.get("order")),
Boolean.parseBoolean(bucketConfiguration.get("sharedByCallers")),
Preconditions.checkNotNull(bucketConfiguration.get("callerPattern"), "Caller pattern is null"),
Preconditions.checkNotNull(bucketConfiguration.get("endpointPattern"), "Endpoint pattern is null"),
Integer.parseInt(bucketConfiguration.get("capacity")),
Integer.parseInt(bucketConfiguration.get("refillRateInSec"))
));
} catch (Exception e) {
logger.warn("Invalid bucket configuration: {}={}", name, bucketConfiguration);
}
});
return currentBucketConfigurations;
}
}
| 693 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/tokenbucket/TokenBucketConfiguration.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.loadshedding.tokenbucket;
import java.util.Objects;
import java.util.regex.Pattern;
public class TokenBucketConfiguration {
/**
* A unique token bucket identifier.
*/
private final String name;
/**
* Execution priority order (lower value == higher priority).
*/
private final int order;
/**
* If true, token bucket is shared by all matching callers. If false, a new bucket is created for each caller name.
*/
private final boolean sharedByCallers;
/**
* Caller pattern.
*/
private final String callerPatternString;
/**
* Called endpoint pattern.
*/
private final String endpointPatternString;
/**
* Total capacity of the bucket. It is also its initial state (bucket starts full).
*/
private final int capacity;
/**
* How many tokens should be added each second.
*/
private final int refillRateInSec;
private final Pattern callerPattern;
private final Pattern endpointPattern;
public TokenBucketConfiguration(String name,
int order,
boolean sharedByCallers,
String callerPatternString,
String endpointPatternString,
int capacity,
int refillRateInSec) {
this.name = name;
this.order = order;
this.sharedByCallers = sharedByCallers;
this.callerPatternString = callerPatternString;
this.endpointPatternString = endpointPatternString;
this.capacity = capacity;
this.refillRateInSec = refillRateInSec;
this.callerPattern = Pattern.compile(callerPatternString);
this.endpointPattern = Pattern.compile(endpointPatternString);
}
public String getName() {
return name;
}
public int getOrder() {
return order;
}
public boolean isSharedByCallers() {
return sharedByCallers;
}
public String getCallerPatternString() {
return callerPatternString;
}
public String getEndpointPatternString() {
return endpointPatternString;
}
public Pattern getCallerPattern() {
return callerPattern;
}
public Pattern getEndpointPattern() {
return endpointPattern;
}
public int getCapacity() {
return capacity;
}
public int getRefillRateInSec() {
return refillRateInSec;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TokenBucketConfiguration that = (TokenBucketConfiguration) o;
return order == that.order &&
sharedByCallers == that.sharedByCallers &&
capacity == that.capacity &&
refillRateInSec == that.refillRateInSec &&
Objects.equals(name, that.name) &&
Objects.equals(callerPatternString, that.callerPatternString) &&
Objects.equals(endpointPatternString, that.endpointPatternString);
}
@Override
public int hashCode() {
return Objects.hash(name, order, sharedByCallers, callerPatternString, endpointPatternString, capacity, refillRateInSec, callerPattern, endpointPattern);
}
@Override
public String toString() {
return "TokenBucketConfiguration{" +
"name='" + name + '\'' +
", order=" + order +
", sharedByCallers=" + sharedByCallers +
", callerPatternString='" + callerPatternString + '\'' +
", endpointPatternString='" + endpointPatternString + '\'' +
", capacity=" + capacity +
", refillRateInSec=" + refillRateInSec +
", callerPattern=" + callerPattern +
", endpointPattern=" + endpointPattern +
'}';
}
}
| 694 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/util/loadshedding/grpc/GrpcAdmissionControllerServerInterceptor.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.loadshedding.grpc;
import java.util.function.Supplier;
import com.netflix.titus.common.util.loadshedding.AdmissionController;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerRequest;
import com.netflix.titus.common.util.loadshedding.AdmissionControllerResponse;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GrpcAdmissionControllerServerInterceptor implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(GrpcAdmissionControllerServerInterceptor.class);
private static final ServerCall.Listener<Object> NO_OP_LISTENER = new ServerCall.Listener<Object>() {
};
private final AdmissionController admissionController;
private final Supplier<String> callerIdResolver;
public GrpcAdmissionControllerServerInterceptor(AdmissionController admissionController,
Supplier<String> callerIdResolver) {
this.admissionController = admissionController;
this.callerIdResolver = callerIdResolver;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
AdmissionControllerResponse result;
try {
AdmissionControllerRequest request = AdmissionControllerRequest.newBuilder()
.withCallerId(callerIdResolver.get())
.withEndpointName(call.getMethodDescriptor().getFullMethodName())
.build();
result = admissionController.apply(request);
} catch (Exception e) {
logger.warn("Admission controller error: {}", e.getMessage());
logger.debug("Stack trace", e);
return next.startCall(call, headers);
}
if (result.isAllowed()) {
return next.startCall(call, headers);
}
call.close(Status.RESOURCE_EXHAUSTED.withDescription(result.getReasonMessage()), new Metadata());
return (ServerCall.Listener<ReqT>) NO_OP_LISTENER;
}
}
| 695 |
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/limiter/ImmutableLimiters.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;
import java.util.concurrent.TimeUnit;
import com.netflix.titus.common.util.limiter.tokenbucket.ImmutableTokenBucket;
import com.netflix.titus.common.util.limiter.tokenbucket.ImmutableTokenBucket.ImmutableRefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.DefaultImmutableTokenBucket;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.ImmutableFixedIntervalRefillStrategy;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.time.Clocks;
/**
*/
public final class ImmutableLimiters {
private ImmutableLimiters() {
}
public static ImmutableRefillStrategy refillAtFixedInterval(long numberOfTokensPerInterval, long interval, TimeUnit timeUnit, Clock clock) {
return new ImmutableFixedIntervalRefillStrategy(numberOfTokensPerInterval, timeUnit.toNanos(interval), clock);
}
public static ImmutableRefillStrategy refillAtFixedInterval(long numberOfTokensPerInterval, long interval, TimeUnit timeUnit) {
return new ImmutableFixedIntervalRefillStrategy(numberOfTokensPerInterval, timeUnit.toNanos(interval), Clocks.system());
}
public static ImmutableTokenBucket tokenBucket(long bucketSize, ImmutableRefillStrategy refillStrategy) {
return new DefaultImmutableTokenBucket(bucketSize, bucketSize, refillStrategy);
}
}
| 696 |
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/limiter/Limiters.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;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import com.netflix.titus.common.runtime.TitusRuntime;
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.limiter.tokenbucket.internal.DefaultTokenBucket;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.DynamicTokenBucketDelegate;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.FixedIntervalRefillStrategy;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.FixedIntervalTokenBucketSupplier;
import com.netflix.titus.common.util.limiter.tokenbucket.internal.SpectatorTokenBucketDecorator;
import com.netflix.titus.common.util.time.Clock;
public class Limiters {
private Limiters() {
}
/**
* Useful for testing.
*/
public static TokenBucket unlimited(String name) {
return new Unlimited(name);
}
/**
* Create a {@link TokenBucket} with a fixed interval {@link RefillStrategy}.
*/
public static TokenBucket createFixedIntervalTokenBucket(String name, long capacity, long initialNumberOfTokens,
long numberOfTokensPerInterval, long interval, TimeUnit unit,
Clock clock) {
RefillStrategy refillStrategy = new FixedIntervalRefillStrategy(numberOfTokensPerInterval, interval, unit, clock);
return new DefaultTokenBucket(name, capacity, refillStrategy, initialNumberOfTokens);
}
/**
* Create a {@link TokenBucket} with a fixed interval {@link RefillStrategy}. The token bucket configuration is
* checked on each invocation, and the bucket is automatically recreated if it changes.
*/
public static TokenBucket createFixedIntervalTokenBucket(String name,
FixedIntervalTokenBucketConfiguration configuration,
Consumer<TokenBucket> onChangeListener) {
return new DynamicTokenBucketDelegate(
new FixedIntervalTokenBucketSupplier(name, configuration, onChangeListener, Optional.empty())
);
}
/**
* Functionally equivalent to {@link #createFixedIntervalTokenBucket(String, FixedIntervalTokenBucketConfiguration, Consumer)},
* but with Spectator metrics.
*/
public static TokenBucket createInstrumentedFixedIntervalTokenBucket(String name,
FixedIntervalTokenBucketConfiguration configuration,
Consumer<TokenBucket> onChangeListener,
TitusRuntime titusRuntime) {
return new SpectatorTokenBucketDecorator(
new DynamicTokenBucketDelegate(
new FixedIntervalTokenBucketSupplier(name, configuration, onChangeListener, Optional.of(titusRuntime))
),
titusRuntime
);
}
private static class Unlimited implements TokenBucket {
private final String name;
private final UnlimitedRefillStrategy strategy = new UnlimitedRefillStrategy();
public Unlimited(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public long getCapacity() {
return Long.MAX_VALUE;
}
@Override
public long getNumberOfTokens() {
return Long.MAX_VALUE;
}
@Override
public boolean tryTake() {
return true;
}
@Override
public boolean tryTake(long numberOfTokens) {
return true;
}
@Override
public void take() {
}
@Override
public void take(long numberOfTokens) {
}
@Override
public void refill(long numberOfToken) {
}
@Override
public RefillStrategy getRefillStrategy() {
return strategy;
}
}
private static class UnlimitedRefillStrategy implements RefillStrategy {
@Override
public long refill() {
return 0;
}
@Override
public long getTimeUntilNextRefill(TimeUnit unit) {
return 0;
}
}
}
| 697 |
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/TokenBucket.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;
/**
* Create a token bucket that can be used to rate limit both synchronously and asynchronously based on the number of
* available tokens. Tokens will get refilled based on the {@link RefillStrategy}.
*/
public interface TokenBucket {
/**
* @return the name of the token bucket.
*/
String getName();
/**
* @return the maximum number of tokens of capacity this bucket can hold.
*/
long getCapacity();
/**
* @return the number of tokens currently in the bucket.
*/
long getNumberOfTokens();
/**
* Attempt to take a token from the bucket.
*
* @return true if a token was taken
*/
boolean tryTake();
/**
* Attempt to take a token from the bucket.
*
* @param numberOfTokens the number of tokens to take
* @return true if the number of tokens were taken
*/
boolean tryTake(long numberOfTokens);
/**
* Take a token from the bucket and block until the token is taken.
*/
void take();
/**
* Take tokens from the bucket and block until the tokens are taken.
*
* @param numberOfTokens the number of tokens to take
*/
void take(long numberOfTokens);
/**
* Refill the token bucket with specified number of tokens. Note that this is an out of bound
* way to add more tokens to the bucket, but the {@link RefillStrategy} should be doing this.
*
* @param numberOfToken the number of tokens to add to the bucket
*/
void refill(long numberOfToken);
/**
* @return the {@link RefillStrategy} of the bucket.
*/
RefillStrategy getRefillStrategy();
}
| 698 |
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/RefillStrategy.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.concurrent.TimeUnit;
/**
* The strategy for refilling a {@link TokenBucket}.
*/
public interface RefillStrategy {
/**
* @return the number of tokens that should be added to the bucket
*/
long refill();
/**
* @param unit the unit of the time
* @return the time until the next refill occurs
*/
long getTimeUntilNextRefill(TimeUnit unit);
}
| 699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.