index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/FieldInvariant.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.netflix.titus.common.model.sanitizer.internal.SpELFieldValidator;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotation for expressing field level invariants written in Spring SpEL language.
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {SpELFieldValidator.class})
public @interface FieldInvariant {
String value();
String message() default "{FieldInvariant.message}";
VerifierMode mode() default VerifierMode.Permissive;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Defines several {@link FieldInvariant} annotations on the same element.
*
* @see ClassInvariant
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@interface List {
FieldInvariant[] value();
}
}
| 1,000 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/ValidationError.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
/**
* Validation errors indicate various reasons why a Job may be malformed.
*/
public class ValidationError {
private final String field;
private final String description;
private final Type type;
/**
* The error type defined here is an indication of the seriousness of the error. In general "HARD" errors should be
* considered fatal, in that continued use of the validated object is not recommended. SOFT errors indicate that
* subsequent use of the validated object is possible.
*/
public enum Type {
HARD,
SOFT
}
public ValidationError(String field, String description) {
this(field, description, Type.HARD);
}
public ValidationError(String field, String description, Type type) {
this.field = field;
this.description = description;
this.type = type;
}
public String getField() {
return field;
}
public String getDescription() {
return description;
}
public Type getType() {
return type;
}
public String getMessage() {
return String.format("field: '%s', description: '%s', type: '%s'", field, description, type);
}
public boolean isHard() {
return getType().equals(Type.HARD);
}
public boolean isSoft() {
return getType().equals(Type.SOFT);
}
@Override
public String toString() {
return String.format("Validation failed: '%s'", getMessage());
}
}
| 1,001 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/Template.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation controls if and how a template value should be applied to a field.
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Template {
/**
* Set to true, to apply template if a collection/map, or {@link java.util.Optional} is empty.
* Otherwise, template value will be used only if the field is null.
*/
boolean onEmpty() default true;
}
| 1,002 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/ClassFieldsNotNull.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.netflix.titus.common.model.sanitizer.internal.NeverNullValidator;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Class level constraint, requiring all JavaBean fields to have non-null values.
*/
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {NeverNullValidator.class})
public @interface ClassFieldsNotNull {
String message() default "{NeverNull.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Defines several {@link ClassFieldsNotNull} annotations on the same element.
*/
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List {
ClassFieldsNotNull[] value();
}
}
| 1,003 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/AbstractConstraintValidator.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.model.sanitizer.internal;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.function.Function;
public abstract class AbstractConstraintValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {
/**
* Escape all special characters that participate in EL expressions so the the message string
* cannot be classified as a template for interpolation.
*
* @param message string that needs to be sanitized
* @return copy of the input string with '{','}','#' and '$' characters escaped
*/
private static String sanitizeMessage(String message) {
return message.replaceAll("([}{$#])", "\\\\$1");
}
@Override
final public boolean isValid(T type, ConstraintValidatorContext context) {
return this.isValid(type, message -> {
String sanitizedMessage = sanitizeMessage(message);
return context.buildConstraintViolationWithTemplate(sanitizedMessage);
});
}
/**
* Implementing classes will need to apply the builder function with the violation message string
* to retrieve the underlying instance of {@link javax.validation.ConstraintValidatorContext} in order
* to continue add any violations.
*
* @param type type of the object under validation
* @param constraintViolationBuilderFunction function to apply with a violation message string
* @return validation status
*/
abstract protected boolean isValid(T type, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction);
}
| 1,004 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/ConstraintValidatorFactoryWrapper.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.function.Function;
import java.util.function.Supplier;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl;
import org.springframework.expression.EvaluationContext;
/**
*/
public class ConstraintValidatorFactoryWrapper implements ConstraintValidatorFactory {
private final ConstraintValidatorFactoryImpl delegate;
private final VerifierMode verifierMode;
private final Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationConstraintValidatorFactory;
private final Supplier<EvaluationContext> spelContextFactory;
public ConstraintValidatorFactoryWrapper(VerifierMode verifierMode,
Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationConstraintValidatorFactory,
Supplier<EvaluationContext> spelContextFactory) {
this.verifierMode = verifierMode;
this.applicationConstraintValidatorFactory = applicationConstraintValidatorFactory;
this.spelContextFactory = spelContextFactory;
this.delegate = new ConstraintValidatorFactoryImpl();
}
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
if (key == SpELClassValidator.class) {
return (T) new SpELClassValidator(verifierMode, spelContextFactory);
}
if (key == SpELFieldValidator.class) {
return (T) new SpELFieldValidator(verifierMode, spelContextFactory);
}
ConstraintValidator<?, ?> instance = applicationConstraintValidatorFactory.apply(key).orElseGet(() -> delegate.getInstance(key));
return (T) instance;
}
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
if (instance instanceof SpELFieldValidator || instance instanceof SpELClassValidator) {
return;
}
delegate.releaseInstance(instance);
}
}
| 1,005 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/CollectionValidator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.ConstraintValidatorContext;
import com.netflix.titus.common.model.sanitizer.CollectionInvariants;
public class CollectionValidator extends AbstractConstraintValidator<CollectionInvariants, Object> {
private CollectionInvariants constraintAnnotation;
@Override
public void initialize(CollectionInvariants constraintAnnotation) {
this.constraintAnnotation = constraintAnnotation;
}
@Override
protected boolean isValid(Object value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
if (value == null) {
return true;
}
if (value instanceof Collection) {
return isValid((Collection<?>) value, constraintViolationBuilderFunction);
}
if (value instanceof Map) {
return isValid((Map<?, ?>) value, constraintViolationBuilderFunction);
}
return false;
}
private boolean isValid(Collection<?> value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
if (value.isEmpty()) {
return true;
}
if (!constraintAnnotation.allowNullValues()) {
if (value.stream().anyMatch(Objects::isNull)) {
attachMessage(constraintViolationBuilderFunction, "null values not allowed");
return false;
}
}
if (!constraintAnnotation.allowDuplicateValues()) {
if (value.stream().distinct().count() != value.size()) {
attachMessage(constraintViolationBuilderFunction, "duplicate values not allowed");
return false;
}
}
return true;
}
private boolean isValid(Map<?, ?> value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
if (value.isEmpty()) {
return true;
}
if (!constraintAnnotation.allowEmptyKeys()) {
if (value.keySet().stream().anyMatch(key -> key == null || (key instanceof String && ((String) key).isEmpty()))) {
attachMessage(constraintViolationBuilderFunction, "empty key names not allowed");
return false;
}
}
if (!constraintAnnotation.allowNullKeys()) {
if (value.keySet().stream().anyMatch(Objects::isNull)) {
attachMessage(constraintViolationBuilderFunction, "null key names not allowed");
return false;
}
}
if (!constraintAnnotation.allowNullValues()) {
Set<String> badEntryKeys = value.entrySet().stream()
.filter(e -> e.getValue() == null)
.map(e -> e.getKey() instanceof String ? (String) e.getKey() : "<not_string>")
.collect(Collectors.toSet());
if (!badEntryKeys.isEmpty()) {
attachMessage(constraintViolationBuilderFunction, "null values found for keys: " + new TreeSet<>(badEntryKeys));
return false;
}
}
return true;
}
private void attachMessage(Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction, String message) {
constraintViolationBuilderFunction.apply(message).addConstraintViolation().disableDefaultConstraintViolation();
}
}
| 1,006 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/SpELFieldValidator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.function.Function;
import java.util.function.Supplier;
import javax.validation.ConstraintValidatorContext;
import com.netflix.titus.common.model.sanitizer.FieldInvariant;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class SpELFieldValidator extends AbstractConstraintValidator<FieldInvariant, Object> {
private final ExpressionParser parser = new SpelExpressionParser();
private final VerifierMode verifierMode;
private final Supplier<EvaluationContext> spelContextFactory;
private boolean enabled;
private Expression expression;
private EvaluationContext spelContext;
public SpELFieldValidator(VerifierMode verifierMode, Supplier<EvaluationContext> spelContextFactory) {
this.verifierMode = verifierMode;
this.spelContextFactory = spelContextFactory;
}
@Override
public void initialize(FieldInvariant constraintAnnotation) {
this.enabled = verifierMode.includes(constraintAnnotation.mode());
if (enabled) {
this.expression = parser.parseExpression(constraintAnnotation.value());
this.spelContext = spelContextFactory.get();
}
}
@Override
protected boolean isValid(Object value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
if (!enabled) {
return true;
}
return (boolean) expression.getValue(spelContext, new Root(value));
}
public static class Root {
private final Object value;
public Root(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
}
}
| 1,007 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/StdValueSanitizer.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.Function;
public class StdValueSanitizer extends AbstractFieldSanitizer<Object> {
private final Function<Class<?>, Boolean> innerEntityPredicate;
public StdValueSanitizer(Function<Class<?>, Boolean> innerEntityPredicate) {
this.innerEntityPredicate = innerEntityPredicate;
}
@Override
public Optional<Object> apply(Object entity) {
return apply(entity, NOTHING);
}
@Override
protected Optional<Object> sanitizeFieldValue(Field field, Object fieldValue, Object context) {
Class<?> fieldType = field.getType();
if (fieldType.isPrimitive()) {
return Optional.empty();
}
if (fieldType == String.class) {
return doStringCleanup((String) fieldValue);
}
if (!fieldType.isAssignableFrom(Enum.class) && fieldValue != null && innerEntityPredicate.apply(fieldValue.getClass())) {
return apply(fieldValue, NOTHING);
}
return Optional.empty();
}
private Optional<Object> doStringCleanup(String value) {
if (value == null || value.isEmpty()) {
return Optional.empty();
}
String trimmed = value.trim();
return value == trimmed ? Optional.empty() : Optional.of(trimmed);
}
}
| 1,008 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/DefaultEntitySanitizer.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.validation.ConstraintValidator;
import javax.validation.Validation;
import javax.validation.Validator;
import com.netflix.titus.common.model.sanitizer.EntitySanitizer;
import com.netflix.titus.common.model.sanitizer.ValidationError;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.support.ReflectiveMethodResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class DefaultEntitySanitizer implements EntitySanitizer {
private final Validator validator;
private final List<Function<Object, Optional<Object>>> sanitizers;
public DefaultEntitySanitizer(VerifierMode verifierMode,
List<Function<Object, Optional<Object>>> sanitizers,
boolean annotationSanitizersEnabled,
boolean stdValueSanitizersEnabled,
Function<Class<?>, Boolean> includesPredicate,
Function<String, Optional<Object>> templateResolver,
Map<String, Method> registeredFunctions,
Map<String, Object> registeredBeans,
Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationValidatorFactory) {
Supplier<EvaluationContext> spelContextFactory = () -> {
StandardEvaluationContext context = new StandardEvaluationContext();
registeredFunctions.forEach(context::registerFunction);
context.setBeanResolver((ctx, beanName) -> registeredBeans.get(beanName));
context.setMethodResolvers(Collections.singletonList(new ReflectiveMethodResolver()));
return context;
};
this.validator = Validation.buildDefaultValidatorFactory()
.usingContext()
.constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(verifierMode, applicationValidatorFactory, spelContextFactory))
.messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
.getValidator();
List<Function<Object, Optional<Object>>> allSanitizers = new ArrayList<>();
if (annotationSanitizersEnabled) {
allSanitizers.add(new AnnotationBasedSanitizer(spelContextFactory.get(), includesPredicate));
}
if (stdValueSanitizersEnabled) {
allSanitizers.add(new StdValueSanitizer(includesPredicate));
}
allSanitizers.add(new TemplateSanitizer(templateResolver, includesPredicate));
allSanitizers.addAll(sanitizers);
this.sanitizers = allSanitizers;
}
@Override
public <T> Set<ValidationError> validate(T entity) {
return validator.validate(entity).stream()
.map(violation -> new ValidationError(violation.getPropertyPath().toString(), violation.getMessage()))
.collect(Collectors.toSet());
}
@Override
public <T> Optional<T> sanitize(T entity) {
Object sanitized = entity;
for (Function<Object, Optional<Object>> sanitizer : sanitizers) {
sanitized = sanitizer.apply(sanitized).orElse(sanitized);
}
return sanitized == entity ? Optional.empty() : Optional.of((T) sanitized);
}
}
| 1,009 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/TemplateSanitizer.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import com.netflix.titus.common.model.sanitizer.Template;
import com.netflix.titus.common.util.ReflectionExt;
/**
*/
public class TemplateSanitizer extends AbstractFieldSanitizer<String> {
private final Function<String, Optional<Object>> templateResolver;
private final Function<Class<?>, Boolean> innerEntityPredicate;
public TemplateSanitizer(Function<String, Optional<Object>> templateResolver,
Function<Class<?>, Boolean> innerEntityPredicate) {
this.templateResolver = templateResolver;
this.innerEntityPredicate = innerEntityPredicate;
}
@Override
public Optional<Object> apply(Object entity) {
return entity != null ? apply(entity, "") : Optional.empty();
}
@Override
protected Optional<Object> sanitizeFieldValue(Field field, Object value, String path) {
String fieldPath = path.isEmpty() ? field.getName() : path + '.' + field.getName();
if (value == null) {
return isEnabled(field) ? templateResolver.apply(fieldPath) : Optional.empty();
}
Class<?> fieldType = field.getType();
// Process empty collection/map/optional/string
if (Collection.class.isAssignableFrom(fieldType)) {
Collection<?> collectionValue = (Collection<?>) value;
if (collectionValue.isEmpty() && replaceEmptyValue(field)) {
return templateResolver.apply(fieldPath);
}
} else if (Map.class.isAssignableFrom(fieldType)) {
Map<?, ?> mapValue = (Map<?, ?>) value;
if (mapValue.isEmpty() && replaceEmptyValue(field)) {
return templateResolver.apply(fieldPath);
}
} else if (Optional.class == fieldType) {
Optional optionalValue = (Optional) value;
if (!optionalValue.isPresent() && replaceEmptyValue(field)) {
return templateResolver.apply(fieldPath);
}
} else if (String.class == fieldType) {
String stringValue = (String) value;
if (stringValue.isEmpty() && replaceEmptyValue(field)) {
return templateResolver.apply(fieldPath);
}
}
// Skip primitive type or collections/maps/optional
if (ReflectionExt.isStandardDataType(fieldType) || ReflectionExt.isContainerType(field)) {
return Optional.empty();
}
if (!innerEntityPredicate.apply(fieldType)) {
return Optional.empty();
}
return apply(value, fieldPath);
}
private static boolean isEnabled(Field field) {
return field.getAnnotation(Template.class) != null;
}
private static boolean replaceEmptyValue(Field field) {
Template annotation = field.getAnnotation(Template.class);
return annotation != null && annotation.onEmpty();
}
}
| 1,010 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/AnnotationBasedSanitizer.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.model.sanitizer.FieldSanitizer;
import com.netflix.titus.common.util.ReflectionExt;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import static com.netflix.titus.common.util.ReflectionExt.isNumeric;
import static java.lang.String.format;
/**
*/
public class AnnotationBasedSanitizer extends AbstractFieldSanitizer<Object> {
private static final SanitizerInfo EMPTY_SANITIZER_INFO = new SanitizerInfo(false, null, null, -1, -1);
private final static ConcurrentMap<Field, SanitizerInfo> FIELD_SANITIZER_INFOS = new ConcurrentHashMap<>();
private final ExpressionParser parser = new SpelExpressionParser();
private final EvaluationContext spelContext;
private final Function<Class<?>, Boolean> innerEntityPredicate;
public AnnotationBasedSanitizer(EvaluationContext spelContext,
Function<Class<?>, Boolean> innerEntityPredicate) {
this.innerEntityPredicate = innerEntityPredicate;
this.spelContext = spelContext;
}
@Override
public Optional<Object> apply(Object entity) {
return apply(entity, NOTHING);
}
@Override
protected Optional<Object> sanitizeFieldValue(Field field, Object value, Object context) {
// If has annotation, sanitize
SanitizerInfo sanitizerInfo = getSanitizerInfo(field);
if (sanitizerInfo != EMPTY_SANITIZER_INFO) {
return sanitizerInfo.isNumeric()
? sanitizeNumericValue(field, value, sanitizerInfo)
: sanitizeNotNumericValue(value, sanitizerInfo);
}
// If null, do nothing
if (value == null) {
return Optional.empty();
}
// Skip primitive type or enum or collections/maps/optional
Class<?> fieldType = field.getType();
if (ReflectionExt.isStandardDataType(fieldType) || value.getClass().isEnum() || ReflectionExt.isContainerType(field)) {
return Optional.empty();
}
return apply(value, NOTHING);
}
private Optional<Object> sanitizeNotNumericValue(Object value, SanitizerInfo sanitizerInfo) {
if (value == null) {
return Optional.empty();
}
Optional<Object> sanitized;
if (sanitizerInfo.getAdjusterExpression().isPresent()) {
sanitized = adjust(value, sanitizerInfo);
} else {
sanitized = sanitizerInfo.getSanitizer().apply(value);
}
if (!value.getClass().isEnum() && innerEntityPredicate.apply(value.getClass())) {
if (!sanitized.isPresent()) {
return apply(value, NOTHING);
}
return sanitized.map(v -> apply(v, NOTHING).orElse(v));
}
return sanitized;
}
private Optional<Object> sanitizeNumericValue(Field field, Object value, SanitizerInfo sanitizerInfo) {
Class<?> valueType = value.getClass();
if (valueType == Integer.class || valueType == Integer.TYPE) {
int effectiveValue = (int) Math.max((int) value, sanitizerInfo.getAtLeast());
effectiveValue = (int) Math.min(effectiveValue, sanitizerInfo.getAtMost());
if (sanitizerInfo.getAdjusterExpression() != null) {
effectiveValue = adjust(effectiveValue, sanitizerInfo).orElse(effectiveValue);
}
return effectiveValue == (int) value ? Optional.empty() : Optional.of(effectiveValue);
} else if (valueType == Long.class || valueType == Long.TYPE) {
long effectiveValue = Math.max((long) value, sanitizerInfo.getAtLeast());
effectiveValue = Math.min(effectiveValue, sanitizerInfo.getAtMost());
if (sanitizerInfo.getAdjusterExpression() != null) {
effectiveValue = adjust(effectiveValue, sanitizerInfo).orElse(effectiveValue);
}
return effectiveValue == (long) value ? Optional.empty() : Optional.of(effectiveValue);
}
if (valueType == Float.class || valueType == Float.TYPE) {
float effectiveValue = Math.max((float) value, sanitizerInfo.getAtLeast());
effectiveValue = Math.min(effectiveValue, sanitizerInfo.getAtMost());
if (sanitizerInfo.getAdjusterExpression() != null) {
effectiveValue = adjust(effectiveValue, sanitizerInfo).orElse(effectiveValue);
}
return effectiveValue == (float) value ? Optional.empty() : Optional.of(effectiveValue);
} else if (valueType == Double.class || valueType == Double.TYPE) {
double effectiveValue = Math.max((double) value, sanitizerInfo.getAtLeast());
effectiveValue = Math.min(effectiveValue, sanitizerInfo.getAtMost());
if (sanitizerInfo.getAdjusterExpression() != null) {
effectiveValue = adjust(effectiveValue, sanitizerInfo).orElse(effectiveValue);
}
return effectiveValue == (double) value ? Optional.empty() : Optional.of(effectiveValue);
}
throw new IllegalArgumentException(format("Not support numeric type %s in field %s", valueType, field));
}
private <T> Optional<T> adjust(T value, SanitizerInfo sanitizerInfo) {
return sanitizerInfo.getAdjusterExpression().map(e -> (T) e.getValue(spelContext, new SpELFieldValidator.Root(value)));
}
private SanitizerInfo getSanitizerInfo(Field field) {
return FIELD_SANITIZER_INFOS.computeIfAbsent(field, f -> {
FieldSanitizer annotation = f.getAnnotation(FieldSanitizer.class);
return annotation == null ? EMPTY_SANITIZER_INFO : buildSanitizerInfo(field, annotation);
});
}
private SanitizerInfo buildSanitizerInfo(Field field, FieldSanitizer annotation) {
Function<Object, Optional<Object>> serializer;
try {
serializer = annotation.sanitizer().newInstance();
} catch (Exception e) {
throw new IllegalArgumentException("Cannot instantiate sanitizer function from " + annotation.sanitizer(), e);
}
boolean numeric = isNumeric(field.getType());
Class<?> emptySanitizerClass = FieldSanitizer.EmptySanitizer.class;
boolean hasSanitizer = annotation.sanitizer().getClass() == emptySanitizerClass;
boolean hasAdjuster = !annotation.adjuster().isEmpty();
if (annotation.atLeast() != Long.MIN_VALUE || annotation.atMost() != Long.MAX_VALUE) {
Preconditions.checkArgument(numeric, "atLeast/atMost parameters can be used only with numeric types");
Preconditions.checkArgument(annotation.atLeast() <= annotation.atMost(), "Violated invariant: atLeast <= atMost in field " + field);
}
Preconditions.checkArgument(!(hasSanitizer && hasAdjuster), "Sanitizer and adjuster cannot be used at the same time in field: " + field);
Expression adjusterExpression = !hasAdjuster ? null : parser.parseExpression(annotation.adjuster());
return new SanitizerInfo(numeric, serializer, Optional.ofNullable(adjusterExpression), annotation.atLeast(), annotation.atMost());
}
static class SanitizerInfo {
private final boolean numeric;
private final Function<Object, Optional<Object>> sanitizer;
private final long atLeast;
private final long atMost;
private Optional<Expression> adjusterExpression;
SanitizerInfo(boolean numeric, Function<Object, Optional<Object>> sanitizer, Optional<Expression> adjusterExpression, long atLeast, long atMost) {
this.numeric = numeric;
this.sanitizer = sanitizer;
this.adjusterExpression = adjusterExpression;
this.atLeast = atLeast;
this.atMost = atMost;
}
boolean isNumeric() {
return numeric;
}
Function<Object, Optional<Object>> getSanitizer() {
return sanitizer;
}
Optional<Expression> getAdjusterExpression() {
return adjusterExpression;
}
long getAtLeast() {
return atLeast;
}
long getAtMost() {
return atMost;
}
}
}
| 1,011 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/SpELMessageInterpolator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Locale;
import java.util.function.Supplier;
import javax.validation.MessageInterpolator;
import com.netflix.titus.common.model.sanitizer.FieldInvariant;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class SpELMessageInterpolator implements MessageInterpolator {
private final ExpressionParser parser = new SpelExpressionParser();
private final Supplier<EvaluationContext> spelContextFactory;
public SpELMessageInterpolator(Supplier<EvaluationContext> spelContextFactory) {
this.spelContextFactory = spelContextFactory;
}
@Override
public String interpolate(String messageTemplate, Context context) {
Expression expression = parser.parseExpression(messageTemplate, new TemplateParserContext());
Object effectiveValue = context.getValidatedValue();
if (context.getConstraintDescriptor().getAnnotation() instanceof FieldInvariant) {
effectiveValue = new SpELFieldValidator.Root(effectiveValue);
}
return (String) expression.getValue(spelContextFactory.get(), effectiveValue);
}
@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
return interpolate(messageTemplate, context);
}
}
| 1,012 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/JavaBeanReflection.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import static com.netflix.titus.common.util.ReflectionExt.getAllFields;
import static java.lang.String.format;
import static java.util.Arrays.stream;
class JavaBeanReflection {
private static final ConcurrentMap<Class<?>, JavaBeanReflection> CACHE = new ConcurrentHashMap<>();
private final Constructor<?> constructor;
private final List<Field> fields;
JavaBeanReflection(Class<?> entityType) {
Preconditions.checkArgument(entityType.getConstructors().length == 1, "Expected single constructor in class %s", entityType);
this.constructor = entityType.getConstructors()[0];
Map<String, Field> fieldsByName = getAllFields(entityType).stream()
.filter(f -> !Modifier.isStatic(f.getModifiers()) && !f.getName().startsWith("$")) // Static fields and instrumentation (jacoco)
.collect(Collectors.toMap(Field::getName, Function.identity()));
this.fields = stream(constructor.getParameters())
.map(p -> {
Field field = fieldsByName.get(p.getName());
Preconditions.checkNotNull(field, "Constructor parameter %s does not map to any field in class %s", p.getName(), entityType);
return field;
})
.collect(Collectors.toList());
}
Object create(Object entity, Map<Field, Object> overrides) {
List<Object> newValues = new ArrayList<>();
for (Field field : fields) {
Object newValue = overrides.get(field);
if (newValue != null) {
newValues.add(newValue);
} else {
newValues.add(getFieldValue(entity, field));
}
}
try {
return constructor.newInstance(newValues.toArray());
} catch (Exception e) {
throw new IllegalArgumentException(format("Cannot instantiate %s with constructor arguments %s", entity.getClass(), newValues), e);
}
}
List<Field> getFields() {
return fields;
}
Object getFieldValue(Object entity, Field field) {
try {
return field.get(entity);
} catch (Exception e) {
throw new IllegalStateException(format("Cannot access value of field %s on %s", field.getName(), entity.getClass()), e);
}
}
static JavaBeanReflection forType(Class<?> entityType) {
return CACHE.computeIfAbsent(entityType, JavaBeanReflection::new);
}
}
| 1,013 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/AbstractFieldSanitizer.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
/**
*/
abstract class AbstractFieldSanitizer<CONTEXT> implements Function<Object, Optional<Object>> {
static final Object NOTHING = new Object();
protected Optional<Object> apply(Object entity, CONTEXT context) {
JavaBeanReflection javaBeanRefl = JavaBeanReflection.forType(entity.getClass());
Map<Field, Object> fixedValues = new HashMap<>();
javaBeanRefl.getFields().forEach(field -> {
Object fieldValue = javaBeanRefl.getFieldValue(entity, field);
sanitizeFieldValue(field, fieldValue, context).ifPresent(newValue -> fixedValues.put(field, newValue));
});
if (fixedValues.isEmpty()) {
return Optional.empty();
}
return Optional.of(javaBeanRefl.create(entity, fixedValues));
}
protected abstract Optional<Object> sanitizeFieldValue(Field field, Object value, CONTEXT context);
}
| 1,014 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/SpELClassValidator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.validation.ConstraintValidatorContext;
import com.netflix.titus.common.model.sanitizer.ClassInvariant;
import com.netflix.titus.common.model.sanitizer.VerifierMode;
import com.netflix.titus.common.util.CollectionsExt;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
/**
* Spring EL JavaBean validation framework class-level validator.
*/
public class SpELClassValidator extends AbstractConstraintValidator<ClassInvariant, Object> {
private final ExpressionParser parser = new SpelExpressionParser();
private final VerifierMode verifierMode;
private final Supplier<EvaluationContext> spelContextFactory;
private boolean enabled;
private Expression conditionExpression;
private Expression exprExpression;
private EvaluationContext spelContext;
public SpELClassValidator(VerifierMode verifierMode, Supplier<EvaluationContext> spelContextFactory) {
this.verifierMode = verifierMode;
this.spelContextFactory = spelContextFactory;
}
@Override
public void initialize(ClassInvariant constraintAnnotation) {
this.enabled = verifierMode.includes(constraintAnnotation.mode());
if (enabled) {
if (!constraintAnnotation.condition().isEmpty()) {
this.conditionExpression = parser.parseExpression(constraintAnnotation.condition());
} else if (!constraintAnnotation.expr().isEmpty()) {
this.exprExpression = parser.parseExpression(constraintAnnotation.expr());
}
this.spelContext = spelContextFactory.get();
}
}
@Override
protected boolean isValid(Object value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
if (!enabled) {
return true;
}
if (conditionExpression != null) {
return (boolean) conditionExpression.getValue(spelContext, value);
}
Map<String, String> violations = (Map<String, String>) exprExpression.getValue(spelContext, value);
if (CollectionsExt.isNullOrEmpty(violations)) {
return true;
}
violations.forEach((field, message) -> constraintViolationBuilderFunction.apply(message)
.addPropertyNode(field)
.addConstraintViolation()
.disableDefaultConstraintViolation());
return false;
}
}
| 1,015 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/model/sanitizer/internal/NeverNullValidator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.HashSet;
import java.util.Set;
import java.util.function.Function;
import javax.validation.ConstraintValidatorContext;
import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull;
import com.netflix.titus.common.util.ReflectionExt;
public class NeverNullValidator extends AbstractConstraintValidator<ClassFieldsNotNull, Object> {
@Override
public void initialize(ClassFieldsNotNull constraintAnnotation) {
}
@Override
protected boolean isValid(Object value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) {
Set<String> nullFields = validate(value);
if (nullFields.isEmpty()) {
return true;
}
constraintViolationBuilderFunction.apply(buildMessage(nullFields)).addConstraintViolation().disableDefaultConstraintViolation();
return false;
}
private String buildMessage(Set<String> nullFields) {
StringBuilder sb = new StringBuilder("'null' in fields: ");
for (String field : nullFields) {
sb.append(field).append(',');
}
return sb.substring(0, sb.length() - 1);
}
private Set<String> validate(Object value) {
JavaBeanReflection jbr = JavaBeanReflection.forType(value.getClass());
Set<String> nullFields = null;
for (Field field : jbr.getFields()) {
Object fieldValue = ReflectionExt.getFieldValue(field, value);
if (fieldValue == null) {
if (nullFields == null) {
nullFields = new HashSet<>();
}
nullFields.add(field.getName());
}
}
return nullFields == null ? Collections.emptySet() : nullFields;
}
}
| 1,016 |
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/environment/MyMutableEnvironment.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;
/**
* Specialized version of {@link MyEnvironment} that supports configuration updates. To be used by test code.
*/
public interface MyMutableEnvironment extends MyEnvironment {
/**
* Set a new property value, returning the previous value or null if previously not set.
*/
String setProperty(String key, String value);
/**
* Remove a property value, returning the previous value or null if previously not set.
*/
String removeProperty(String key);
}
| 1,017 |
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/environment/MyEnvironments.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;
import java.util.Collections;
import java.util.Map;
import com.netflix.archaius.api.Config;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.environment.internal.MyArchaiusEnvironment;
import com.netflix.titus.common.environment.internal.MyCachingEnvironment;
import com.netflix.titus.common.environment.internal.MyEmptyEnvironment;
import com.netflix.titus.common.environment.internal.MySpringEnvironment;
import com.netflix.titus.common.environment.internal.MyStaticEnvironment;
import com.netflix.titus.common.environment.internal.MyStaticMutableEnvironment;
import com.netflix.titus.common.util.closeable.CloseableReference;
import org.springframework.core.env.Environment;
public final class MyEnvironments {
private MyEnvironments() {
}
public static MyMutableEnvironment newMutable() {
return new MyStaticMutableEnvironment(Collections.emptyMap());
}
public static MyEnvironment newFromMap(Map<String, String> properties) {
return new MyStaticEnvironment(properties);
}
public static MyMutableEnvironment newMutableFromMap(Map<String, String> properties) {
return new MyStaticMutableEnvironment(properties);
}
public static MyEnvironment newSpring(Environment environment) {
return new MySpringEnvironment(environment);
}
public static MyEnvironment newArchaius(Config config) {
return new MyArchaiusEnvironment(config);
}
public static CloseableReference<MyEnvironment> newSpringCaching(Environment environment, long refreshCycleMs, Registry registry) {
MyCachingEnvironment cached = new MyCachingEnvironment(
"spring",
new MySpringEnvironment(environment),
refreshCycleMs,
registry
);
return CloseableReference.referenceOf(cached, c -> cached.close());
}
public static MyEnvironment empty() {
return MyEmptyEnvironment.getInstance();
}
}
| 1,018 |
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/environment/MyEnvironment.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;
/**
* An API to access application configuration data.
*/
public interface MyEnvironment {
String getProperty(String key);
String getProperty(String key, String defaultValue);
}
| 1,019 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MyCachingEnvironment.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.io.Closeable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import com.netflix.titus.common.environment.MyEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A wrapper around {@link MyEnvironment} that provides property values from cache. For all property that are requested,
* refreshes them in the background with the configured interval. This wrapper should be used when the underlying
* implementation is slow.
*/
public class MyCachingEnvironment implements MyEnvironment, Closeable {
private static final Logger logger = LoggerFactory.getLogger(MyCachingEnvironment.class);
private static final String METRICS_ROOT = "titus.myEnvironment.cache.";
private final String sourceId;
private final MyEnvironment source;
private final Thread updaterThread;
private final ConcurrentMap<String, ValueHolder> cache = new ConcurrentHashMap<>();
private final Counter updateCountMetric;
private final Timer updateTimeMetric;
public MyCachingEnvironment(String sourceId, MyEnvironment source, long refreshCycleMs, Registry registry) {
this.sourceId = sourceId;
this.source = source;
this.updateCountMetric = registry.counter(METRICS_ROOT + "updateCount", "sourceId", sourceId);
this.updateTimeMetric = registry.timer(METRICS_ROOT + "updateTime", "sourceId", sourceId);
this.updaterThread = new Thread("environment-updater") {
@Override
public void run() {
try {
while (true) {
refresh();
try {
Thread.sleep(refreshCycleMs);
} catch (InterruptedException e) {
break;
}
}
} catch (Exception e) {
logger.error("[{}] Environment refresh process terminated with an error", sourceId, e);
} finally {
logger.info("[{}] Environment refresh process terminated", sourceId);
}
}
};
updaterThread.setDaemon(true);
updaterThread.start();
}
private void refresh() {
int updatesCount = 0;
Stopwatch stopwatch = Stopwatch.createStarted();
try {
Set<String> keys = new HashSet<>(cache.keySet());
for (String key : keys) {
ValueHolder previous = cache.get(key);
ValueHolder current = new ValueHolder(source.getProperty(key));
if (previous != null && !Objects.equals(previous.getValue(), current.getValue())) {
updatesCount++;
cache.put(key, current);
logger.info("[{}] Property update: key={}, previous={}, current={}", sourceId, key, previous.getValue(), current.getValue());
}
}
} catch (Exception e) {
logger.error("[{}] Failed to refresh configuration properties", sourceId, e);
}
updateCountMetric.increment(updatesCount);
updateTimeMetric.record(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
}
@Override
public void close() {
updaterThread.interrupt();
}
@Override
public String getProperty(String key) {
ValueHolder valueHolder = cache.computeIfAbsent(key, k -> {
ValueHolder current = new ValueHolder(source.getProperty(key));
logger.info("[{}] Property first access: key={}, current={}", sourceId, key, current.getValue());
return current;
});
return valueHolder.getValue();
}
@Override
public String getProperty(String key, String defaultValue) {
String value = getProperty(key);
return value == null ? defaultValue : value;
}
private static class ValueHolder {
private final String value;
private ValueHolder(String value) {
this.value = value;
}
private String getValue() {
return value;
}
}
}
| 1,020 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MyEmptyEnvironment.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 com.netflix.titus.common.environment.MyEnvironment;
public class MyEmptyEnvironment implements MyEnvironment {
private static final MyEnvironment INSTANCE = new MyEmptyEnvironment();
@Override
public String getProperty(String key) {
return null;
}
@Override
public String getProperty(String key, String defaultValue) {
return defaultValue;
}
public static MyEnvironment getInstance() {
return INSTANCE;
}
}
| 1,021 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MyStaticEnvironment.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.Map;
import com.netflix.titus.common.environment.MyEnvironment;
public class MyStaticEnvironment implements MyEnvironment {
private final Map<String, String> properties;
public MyStaticEnvironment(Map<String, String> properties) {
this.properties = properties;
}
@Override
public String getProperty(String key) {
return properties.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return properties.getOrDefault(key, defaultValue);
}
}
| 1,022 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MyStaticMutableEnvironment.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.HashMap;
import java.util.Map;
import com.netflix.titus.common.environment.MyMutableEnvironment;
public class MyStaticMutableEnvironment implements MyMutableEnvironment {
private final Map<String, String> properties;
public MyStaticMutableEnvironment(Map<String, String> properties) {
// Copy as we want to update this map.
this.properties = new HashMap<>(properties);
}
@Override
public String getProperty(String key) {
return properties.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return properties.getOrDefault(key, defaultValue);
}
@Override
public String setProperty(String key, String value) {
return properties.put(key, value);
}
@Override
public String removeProperty(String key) {
return properties.remove(key);
}
}
| 1,023 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MySpringEnvironment.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 com.netflix.titus.common.environment.MyEnvironment;
import org.springframework.core.env.Environment;
public class MySpringEnvironment implements MyEnvironment {
private final Environment environment;
public MySpringEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public String getProperty(String key) {
return environment.getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return environment.getProperty(key, defaultValue);
}
}
| 1,024 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/environment/internal/MyArchaiusEnvironment.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 com.netflix.archaius.api.Config;
import com.netflix.titus.common.environment.MyEnvironment;
public class MyArchaiusEnvironment implements MyEnvironment {
private final Config config;
public MyArchaiusEnvironment(Config config) {
this.config = config;
}
@Override
public String getProperty(String key) {
return config.getString(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return config.getString(key, defaultValue);
}
}
| 1,025 |
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/aws/AwsInstanceDescriptor.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.aws;
/**
* AWS instance descriptor.
*/
public final class AwsInstanceDescriptor {
private String id;
private int vCPUs;
private int vGPUs;
private int memoryGB;
private int storageGB;
private boolean ebsOnly;
private int networkMbs;
private int ebsBandwidthMbs;
AwsInstanceDescriptor(Builder builder) {
this.id = builder.id;
this.vCPUs = builder.vCPUs;
this.vGPUs = builder.vGPUs;
this.memoryGB = builder.memoryGB;
this.storageGB = builder.storageGB;
this.ebsOnly = builder.ebsOnly;
this.networkMbs = builder.networkMbs;
this.ebsBandwidthMbs = builder.ebsBandwidthMbs;
}
public String getId() {
return id;
}
public int getvCPUs() {
return vCPUs;
}
public int getvGPUs() {
return vGPUs;
}
public int getMemoryGB() {
return memoryGB;
}
public int getStorageGB() {
return storageGB;
}
public boolean isEbsOnly() {
return ebsOnly;
}
public int getNetworkMbs() {
return networkMbs;
}
public int getEbsBandwidthMbs() {
return ebsBandwidthMbs;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsInstanceDescriptor that = (AwsInstanceDescriptor) o;
if (vCPUs != that.vCPUs) {
return false;
}
if (vGPUs != that.vGPUs) {
return false;
}
if (memoryGB != that.memoryGB) {
return false;
}
if (storageGB != that.storageGB) {
return false;
}
if (ebsOnly != that.ebsOnly) {
return false;
}
if (networkMbs != that.networkMbs) {
return false;
}
if (ebsBandwidthMbs != that.ebsBandwidthMbs) {
return false;
}
return id != null ? id.equals(that.id) : that.id == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + vCPUs;
result = 31 * result + vGPUs;
result = 31 * result + memoryGB;
result = 31 * result + storageGB;
result = 31 * result + (ebsOnly ? 1 : 0);
result = 31 * result + networkMbs;
result = 31 * result + ebsBandwidthMbs;
return result;
}
@Override
public String toString() {
return "AwsInstanceDescriptor{" +
"id='" + id + '\'' +
", vCPUs=" + vCPUs +
", vGPUs=" + vGPUs +
", memoryGB=" + memoryGB +
", storageGB=" + storageGB +
", ebsOnly=" + ebsOnly +
", networkMbs=" + networkMbs +
", ebsBandwidthMbs=" + ebsBandwidthMbs +
'}';
}
static Builder newBuilder(String model) {
return new Builder(model);
}
static final class Builder {
private final String id;
private int vCPUs;
private int vGPUs;
private int memoryGB;
private int storageGB;
private boolean ebsOnly;
private int networkMbs;
private int ebsBandwidthMbs;
private Builder(String id) {
this.id = id;
}
public Builder cpu(int vCPUs) {
this.vCPUs = vCPUs;
return this;
}
public Builder gpu(int vGPUs) {
this.vGPUs = vGPUs;
return this;
}
public Builder memoryGB(int memoryGB) {
this.memoryGB = memoryGB;
return this;
}
public Builder networkMbs(int networkMbs) {
this.networkMbs = networkMbs;
return this;
}
public Builder storageGB(int storageGB) {
this.storageGB = storageGB;
return this;
}
public Builder ebsOnly() {
this.ebsOnly = true;
return this;
}
public Builder ebsBandwidthMbs(int ebsBandwidthMbs) {
this.ebsBandwidthMbs = ebsBandwidthMbs;
return this;
}
public AwsInstanceDescriptor build() {
return new AwsInstanceDescriptor(this);
}
}
}
| 1,026 |
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/aws/AwsInstanceType.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.aws;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.StringExt;
public enum AwsInstanceType {
/*
* M3 family
*/
M3_LARGE(AwsInstanceDescriptor.newBuilder("m3.large")
.cpu(2)
.memoryGB(7)
.storageGB(32)
.networkMbs(300)
.build()
),
M3_XLARGE(AwsInstanceDescriptor.newBuilder("m3.xlarge")
.cpu(4)
.memoryGB(15)
.storageGB(80)
.networkMbs(500)
.build()
),
M3_2XLARGE(AwsInstanceDescriptor.newBuilder("m3.2xlarge")
.cpu(8)
.memoryGB(30)
.storageGB(160)
.networkMbs(700)
.build()
),
/*
* M4 family
*/
// TODO storage is assumed attached storage, network bandwidth is a guess
M4_Large(AwsInstanceDescriptor.newBuilder("m4.large")
.cpu(2)
.memoryGB(8)
.storageGB(128)
.networkMbs(500)
.ebsOnly()
.ebsBandwidthMbs(450)
.build()
),
M4_XLarge(AwsInstanceDescriptor.newBuilder("m4.xlarge")
.cpu(4)
.memoryGB(16)
.storageGB(256)
.networkMbs(1000)
.ebsOnly()
.ebsBandwidthMbs(750)
.build()
),
M4_2XLarge(AwsInstanceDescriptor.newBuilder("m4.2xlarge")
.cpu(8)
.memoryGB(32)
.storageGB(512)
.networkMbs(2000)
.ebsOnly()
.ebsBandwidthMbs(1000)
.build()
),
M4_4XLarge(AwsInstanceDescriptor.newBuilder("m4.4xlarge")
.cpu(16)
.memoryGB(64)
.storageGB(512)
.networkMbs(2000)
.ebsOnly()
.ebsBandwidthMbs(2000)
.build()
),
M4_10XLarge(AwsInstanceDescriptor.newBuilder("m4.10xlarge")
.cpu(40)
.memoryGB(160)
.storageGB(1024)
.networkMbs(10000)
.ebsOnly()
.ebsBandwidthMbs(4000)
.build()
),
M4_16XLarge(AwsInstanceDescriptor.newBuilder("m4.16xlarge")
.cpu(64)
.memoryGB(256)
.storageGB(1_000)
.networkMbs(25000)
.ebsOnly()
.ebsBandwidthMbs(10_000)
.build()
),
/*
* M5 family
*/
M5_Metal(AwsInstanceDescriptor.newBuilder("m5.metal")
.cpu(96)
.memoryGB(384)
.storageGB(1_024)
.networkMbs(25_000)
.ebsOnly()
.ebsBandwidthMbs(14_000)
.build()
),
/*
* R3 family
*/
// TODO network bandwidth is a guess
R3_2XLarge(AwsInstanceDescriptor.newBuilder("r3.2xlarge")
.cpu(8)
.memoryGB(61)
.networkMbs(1000)
.storageGB(160)
.build()
),
R3_4XLarge(AwsInstanceDescriptor.newBuilder("r3.4xlarge")
.cpu(16)
.memoryGB(122)
.networkMbs(2000)
.storageGB(320)
.build()
),
R3_8XLarge(AwsInstanceDescriptor.newBuilder("r3.8xlarge")
.cpu(32)
.memoryGB(244)
.networkMbs(10000)
.storageGB(640)
.build()
),
/*
* R4 family
*/
R4_2XLarge(AwsInstanceDescriptor.newBuilder("r4.2xlarge")
.cpu(8)
.memoryGB(61)
.networkMbs(10_000)
.storageGB(160)
.build()
),
R4_4XLarge(AwsInstanceDescriptor.newBuilder("r4.4xlarge")
.cpu(16)
.memoryGB(122)
.networkMbs(10_000)
.storageGB(320)
.build()
),
R4_8XLarge(AwsInstanceDescriptor.newBuilder("r4.8xlarge")
.cpu(32)
.memoryGB(244)
.networkMbs(10_000)
.storageGB(640)
.build()
),
R4_16XLarge(AwsInstanceDescriptor.newBuilder("r4.16xlarge")
.cpu(64)
.memoryGB(488)
.networkMbs(25_000)
.storageGB(1_280)
.build()
),
/*
* R5 family
*/
R5_Metal(AwsInstanceDescriptor.newBuilder("r5.metal")
.cpu(96)
.memoryGB(768)
.storageGB(1_500)
.networkMbs(25_000)
.ebsOnly()
.ebsBandwidthMbs(14_000)
.build()
),
R5_24XLarge(AwsInstanceDescriptor.newBuilder("r5.24xlarge")
.cpu(96)
.memoryGB(768)
.storageGB(1_500)
.networkMbs(25_000)
.ebsOnly()
.ebsBandwidthMbs(14_000)
.build()
),
/*
* G2 family
*/
G2_2XLarge(AwsInstanceDescriptor.newBuilder("g2.2xlarge")
.cpu(8)
.gpu(1)
.memoryGB(15)
.networkMbs(1000)
.storageGB(60)
.build()
),
G2_8XLarge(AwsInstanceDescriptor.newBuilder("g2.8xlarge")
.cpu(32)
.gpu(4)
.memoryGB(60)
.networkMbs(10000)
.storageGB(240)
.build()
),
/*
* G4 family
*/
G4DN_XLarge(AwsInstanceDescriptor.newBuilder("g4dn.xlarge")
.cpu(4)
.gpu(1)
.memoryGB(16)
.networkMbs(25000)
.storageGB(125)
.build()
),
G4DN_2XLarge(AwsInstanceDescriptor.newBuilder("g4dn.2xlarge")
.cpu(8)
.gpu(1)
.memoryGB(32)
.networkMbs(25000)
.storageGB(225)
.build()
),
G4DN_4XLarge(AwsInstanceDescriptor.newBuilder("g4dn.4xlarge")
.cpu(16)
.gpu(1)
.memoryGB(64)
.networkMbs(25000)
.storageGB(225)
.build()
),
G4DN_8XLarge(AwsInstanceDescriptor.newBuilder("g4dn.8xlarge")
.cpu(32)
.gpu(1)
.memoryGB(128)
.networkMbs(50000)
.storageGB(900)
.build()
),
G4DN_12XLarge(AwsInstanceDescriptor.newBuilder("g4dn.12xlarge")
.cpu(48)
.gpu(4)
.memoryGB(192)
.networkMbs(50000)
.storageGB(900)
.build()
),
G4DN_16XLarge(AwsInstanceDescriptor.newBuilder("g4dn.16xlarge")
.cpu(64)
.gpu(1)
.memoryGB(256)
.networkMbs(50000)
.storageGB(900)
.build()
),
G4DN_Metal(AwsInstanceDescriptor.newBuilder("g4dn.metal")
.cpu(96)
.gpu(8)
.memoryGB(384)
.networkMbs(100000)
.storageGB(1800)
.build()
),
/*
* P2 family
*/
P2_XLarge(AwsInstanceDescriptor.newBuilder("p2.xlarge")
.cpu(4)
.gpu(1)
.memoryGB(61)
.networkMbs(1000)
.storageGB(60)
.build()
),
P2_8XLarge(AwsInstanceDescriptor.newBuilder("p2.8xlarge")
.cpu(32)
.gpu(8)
.memoryGB(488)
.networkMbs(10_000)
.storageGB(240)
.build()
),
P2_16XLarge(AwsInstanceDescriptor.newBuilder("p2.16xlarge")
.cpu(64)
.gpu(16)
.memoryGB(732)
.networkMbs(25_000)
.storageGB(480)
.build()
),
/*
* P3 family
*/
P3_2XLarge(AwsInstanceDescriptor.newBuilder("p3.2xlarge")
.cpu(8)
.gpu(1)
.memoryGB(61)
.networkMbs(2_000)
.storageGB(125)
.build()
),
P3_8XLarge(AwsInstanceDescriptor.newBuilder("p3.8xlarge")
.cpu(32)
.gpu(4)
.memoryGB(244)
.networkMbs(10_000)
.storageGB(500)
.build()
),
P3_16XLarge(AwsInstanceDescriptor.newBuilder("p3.16xlarge")
.cpu(64)
.gpu(8)
.memoryGB(488)
.networkMbs(25_000)
.storageGB(500)
.build()
);
public static final String M4_LARGE_ID = "m4.large";
public static final String M4_XLARGE_ID = "m4.xlarge";
public static final String M4_2XLARGE_ID = "m4.2xlarge";
public static final String M4_4XLARGE_ID = "m4.4xlarge";
public static final String M4_10XLARGE_ID = "m4.10xlarge";
public static final String M4_16XLARGE_ID = "m4.16xlarge";
public static final String R3_2XLARGE_ID = "r3.2xlarge";
public static final String R3_4XLARGE_ID = "r3.4xlarge";
public static final String R3_8XLARGE_ID = "r3.8xlarge";
public static final String R4_2XLARGE_ID = "r4.2xlarge";
public static final String R4_4XLARGE_ID = "r4.4xlarge";
public static final String R4_8XLARGE_ID = "r4.8xlarge";
public static final String G2_XLARGE_ID = "g2.xlarge";
public static final String G2_2XLARGE_ID = "g2.2xlarge";
public static final String G2_8XLARGE_ID = "g2.8xlarge";
public static final String G4DN_XLARGE_ID = "g4dn.xlarge";
public static final String G4DN_2XLARGE_ID = "g4dn.2xlarge";
public static final String G4DN_4XLARGE_ID = "g4dn.4xlarge";
public static final String G4DN_8XLARGE_ID = "g4dn.8xlarge";
public static final String G4DN_12XLARGE_ID = "g4dn.12xlarge";
public static final String G4DN_16XLARGE_ID = "g4dn.16xlarge";
public static final String G4DN_METAL_ID = "g4dn.metal";
public static final String P2_XLARGE_ID = "p2.xlarge";
public static final String P2_2XLARGE_ID = "p2.2xlarge";
public static final String P2_8XLARGE_ID = "p2.8xlarge";
public static final String P3_2XLARGE_ID = "p3.2xlarge";
public static final String P3_8XLARGE_ID = "p3.8xlarge";
public static final String P3_16XLARGE_ID = "p3.16xlarge";
private static final Map<String, AwsInstanceType> INSTANCES_BY_MODEL = createInstanceByModelMap();
private final AwsInstanceDescriptor descriptor;
AwsInstanceType(AwsInstanceDescriptor descriptor) {
this.descriptor = descriptor;
}
public AwsInstanceDescriptor getDescriptor() {
return descriptor;
}
/**
* Returns {@link AwsInstanceType} given name in the standard format (for example 'm4.xlarge') or as enum ('M4_XLarge').
*/
public static AwsInstanceType withName(String instanceName) {
Preconditions.checkArgument(StringExt.isNotEmpty(instanceName), "non empty string expected with AWS instance type name");
AwsInstanceType type = INSTANCES_BY_MODEL.get(instanceName);
if (type != null) {
return type;
}
return AwsInstanceType.valueOf(instanceName);
}
private static Map<String, AwsInstanceType> createInstanceByModelMap() {
Map<String, AwsInstanceType> result = new HashMap<>();
for (AwsInstanceType type : values()) {
result.put(type.getDescriptor().getId(), type);
}
return Collections.unmodifiableMap(result);
}
}
| 1,027 |
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/kube/Annotations.java | // This file is autogenerated!!!
// DO NOT EDIT
//
// Instead make changes to titus-kube-common
// https://github.com/Netflix/titus-kube-common/blob/master/pod/annotations.go
// And then run make refresh in this directory
//
package com.netflix.titus.common.kube;
public class Annotations {
public static final String AnnotationKeyInstanceType = "node.titus.netflix.com/itype";
public static final String AnnotationKeyRegion = "node.titus.netflix.com/region";
public static final String AnnotationKeyStack = "node.titus.netflix.com/stack";
public static final String AnnotationKeyAZ = "failure-domain.beta.kubernetes.io/zone";
// Pod Networking
public static final String AnnotationKeyEgressBandwidth = "kubernetes.io/egress-bandwidth";
public static final String AnnotationKeyIngressBandwidth = "kubernetes.io/ingress-bandwidth";
// Pod ENI
// AnnotationKeyIPAddress represents a generic "primary", could be ipv4 or v6
public static final String AnnotationKeyIPAddress = "network.netflix.com/address-ip";
public static final String AnnotationKeyIPv4Address = "network.netflix.com/address-ipv4";
public static final String AnnotationKeyIPv4PrefixLength = "network.netflix.com/prefixlen-ipv4";
public static final String AnnotationKeyIPv6Address = "network.netflix.com/address-ipv6";
public static final String AnnotationKeyIPv6PrefixLength = "network.netflix.com/prefixlen-ipv6";
// AnnotationKeyIPv4TransitionAddress represents the "NAT" ip for certain IPv6-only modes
public static final String AnnotationKeyIPv4TransitionAddress = "network.netflix.com/address-transition-ipv4";
public static final String AnnotationKeyElasticIPv4Address = "network.netflix.com/address-elastic-ipv4";
public static final String AnnotationKeyElasticIPv6Address = "network.netflix.com/address-elastic-ipv6";
public static final String AnnotationKeyBranchEniID = "network.netflix.com/branch-eni-id";
public static final String AnnotationKeyBranchEniMac = "network.netflix.com/branch-eni-mac";
public static final String AnnotationKeyBranchEniVpcID = "network.netflix.com/branch-eni-vpc";
public static final String AnnotationKeyBranchEniSubnet = "network.netflix.com/branch-eni-subnet";
public static final String AnnotationKeyTrunkEniID = "network.netflix.com/trunk-eni-id";
public static final String AnnotationKeyTrunkEniMac = "network.netflix.com/trunk-eni-mac";
public static final String AnnotationKeyTrunkEniVpcID = "network.netflix.com/trunk-eni-vpc";
public static final String AnnotationKeyVlanID = "network.netflix.com/vlan-id";
public static final String AnnotationKeyAllocationIdx = "network.netflix.com/allocation-idx";
// Security
// matches kube2iam
public static final String AnnotationKeyIAMRole = "iam.amazonaws.com/role";
public static final String AnnotationKeySecurityGroupsLegacy = "network.titus.netflix.com/securityGroups";
// https://kubernetes.io/docs/tutorials/clusters/apparmor/#securing-a-pod
public static final String AnnotationKeyPrefixAppArmor = "container.apparmor.security.beta.kubernetes.io";
//
// v1 pod spec annotations
//
// AnnotationKeyPodSchemaVersion is an integer specifying what schema version a pod was created with
public static final String AnnotationKeyPodSchemaVersion = "pod.netflix.com/pod-schema-version";
// Workload-specific fields
public static final String AnnotationKeyWorkloadDetail = "workload.netflix.com/detail";
public static final String AnnotationKeyWorkloadName = "workload.netflix.com/name";
public static final String AnnotationKeyWorkloadOwnerEmail = "workload.netflix.com/owner-email";
public static final String AnnotationKeyWorkloadSequence = "workload.netflix.com/sequence";
public static final String AnnotationKeyWorkloadStack = "workload.netflix.com/stack";
// Titus-specific fields
public static final String AnnotationKeyJobAcceptedTimestampMs = "v3.job.titus.netflix.com/accepted-timestamp-ms";
public static final String AnnotationKeyJobID = "v3.job.titus.netflix.com/id";
public static final String AnnotationKeyJobType = "v3.job.titus.netflix.com/type";
public static final String AnnotationKeyJobDescriptor = "v3.job.titus.netflix.com/descriptor";
// AnnotationKeyPodTitusContainerInfo - to be removed once VK supports the full pod spec
public static final String AnnotationKeyPodTitusContainerInfo = "pod.titus.netflix.com/container-info";
// AnnotationKeyPodTitusEntrypointShellSplitting tells the executor to preserve the legacy shell splitting behaviour
public static final String AnnotationKeyPodTitusEntrypointShellSplitting = "pod.titus.netflix.com/entrypoint-shell-splitting-enabled";
// AnnotationKeyPodTitusSystemEnvVarNames tells the executor the names of the system-specified environment variables
public static final String AnnotationKeyPodTitusSystemEnvVarNames = "pod.titus.netflix.com/system-env-var-names";
// AnnotationKeyPodInjectedEnvVarNames tells the executor the names of the externally-injected environment variables,
// which neither come from the user nor titus itself, and should be ignored for identify verification purposes
public static final String AnnotationKeyPodInjectedEnvVarNames = "pod.titus.netflix.com/injected-env-var-names";
// AnnotationKeyImageTagPrefix stores the original tag for the an image.
// This is because on the v1 pod image field, there is only room for the digest and no room for the tag it came from
public static final String AnnotationKeyImageTagPrefix = "pod.titus.netflix.com/image-tag-";
// networking - used by the Titus CNI
public static final String AnnotationKeySubnetsLegacy = "network.titus.netflix.com/subnets";
public static final String AnnotationKeyAccountIDLegacy = "network.titus.netflix.com/accountId";
public static final String AnnotationKeyNetworkAccountID = "network.netflix.com/account-id";
public static final String AnnotationKeyNetworkBurstingEnabled = "network.netflix.com/network-bursting-enabled";
public static final String AnnotationKeyNetworkAssignIPv6Address = "network.netflix.com/assign-ipv6-address";
public static final String AnnotationKeyNetworkElasticIPPool = "network.netflix.com/elastic-ip-pool";
public static final String AnnotationKeyNetworkElasticIPs = "network.netflix.com/elastic-ips";
public static final String AnnotationKeyNetworkIMDSRequireToken = "network.netflix.com/imds-require-token";
public static final String AnnotationKeyNetworkJumboFramesEnabled = "network.netflix.com/jumbo-frames-enabled";
public static final String AnnotationKeyNetworkMode = "network.netflix.com/network-mode";
// AnnotationKeyEffectiveNetworkMode represents the network mode computed by the titus-executor
// This may not be the same as the original (potentially unset) requested network mode
public static final String AnnotationKeyEffectiveNetworkMode = "network.netflix.com/effective-network-mode";
public static final String AnnotationKeyNetworkSecurityGroups = "network.netflix.com/security-groups";
public static final String AnnotationKeyNetworkSubnetIDs = "network.netflix.com/subnet-ids";
// TODO: deprecate this in favor of using the UUID annotation below
public static final String AnnotationKeyNetworkStaticIPAllocationUUID = "network.netflix.com/static-ip-allocation-uuid";
// storage
public static final String AnnotationKeyStorageEBSVolumeID = "ebs.volume.netflix.com/volume-id";
public static final String AnnotationKeyStorageEBSMountPath = "ebs.volume.netflix.com/mount-path";
public static final String AnnotationKeyStorageEBSMountPerm = "ebs.volume.netflix.com/mount-perm";
public static final String AnnotationKeyStorageEBSFSType = "ebs.volume.netflix.com/fs-type";
// security
public static final String AnnotationKeySecurityWorkloadMetadata = "security.netflix.com/workload-metadata";
public static final String AnnotationKeySecurityWorkloadMetadataSig = "security.netflix.com/workload-metadata-sig";
// opportunistic resources (see control-plane and scheduler code)
// AnnotationKeyOpportunisticCPU - assigned opportunistic CPUs
public static final String AnnotationKeyOpportunisticCPU = "opportunistic.scheduler.titus.netflix.com/cpu";
// AnnotationKeyOpportunisticResourceID - name of the opportunistic resource CRD used during scheduling
public static final String AnnotationKeyOpportunisticResourceID = "opportunistic.scheduler.titus.netflix.com/id";
// AnnotationKeyPredictionRuntime - predicted runtime (Go’s time.Duration format)
public static final String AnnotationKeyPredictionRuntime = "predictions.scheduler.titus.netflix.com/runtime";
// AnnotationKeyPredictionConfidence - confidence (percentile) of the prediction picked above
public static final String AnnotationKeyPredictionConfidence = "predictions.scheduler.titus.netflix.com/confidence";
// AnnotationKeyPredictionModelID - model uuid used for the runtime prediction picked above
public static final String AnnotationKeyPredictionModelID = "predictions.scheduler.titus.netflix.com/model-id";
// AnnotationKeyPredictionModelVersion - version of the model used for the prediction above
public static final String AnnotationKeyPredictionModelVersion = "predictions.scheduler.titus.netflix.com/version";
// AnnotationKeyPredictionABTestCell - cell allocation for prediction AB tests
public static final String AnnotationKeyPredictionABTestCell = "predictions.scheduler.titus.netflix.com/ab-test";
// AnnotationKeyPredictionPredictionAvailable - array of predictions available during job admission
public static final String AnnotationKeyPredictionPredictionAvailable = "predictions.scheduler.titus.netflix.com/available";
// AnnotationKeyPredictionSelectorInfo - metadata from the prediction selection algorithm
public static final String AnnotationKeyPredictionSelectorInfo = "predictions.scheduler.titus.netflix.com/selector-info";
// pod features
public static final String AnnotationKeyPodCPUBurstingEnabled = "pod.netflix.com/cpu-bursting-enabled";
public static final String AnnotationKeyPodKvmEnabled = "pod.netflix.com/kvm-enabled";
public static final String AnnotationKeyPodFuseEnabled = "pod.netflix.com/fuse-enabled";
public static final String AnnotationKeyPodHostnameStyle = "pod.netflix.com/hostname-style";
public static final String AnnotationKeyPodOomScoreAdj = "pod.netflix.com/oom-score-adj";
public static final String AnnotationKeyPodSchedPolicy = "pod.netflix.com/sched-policy";
public static final String AnnotationKeyPodSeccompAgentNetEnabled = "pod.netflix.com/seccomp-agent-net-enabled";
public static final String AnnotationKeyPodSeccompAgentPerfEnabled = "pod.netflix.com/seccomp-agent-perf-enabled";
public static final String AnnotationKeyPodTrafficSteeringEnabled = "pod.netflix.com/traffic-steering-enabled";
// container annotations (specified on a pod about a container)
// Specific containers indicate they want to set something by appending
// a prefix key with their container name ($name.containers.netflix.com).
public static final String AnnotationKeySuffixContainers = "containers.netflix.com";
public static final String AnnotationKeySuffixContainersSidecar = "platform-sidecar";
// logging config
public static final String AnnotationKeyLogKeepLocalFile = "log.netflix.com/keep-local-file-after-upload";
public static final String AnnotationKeyLogS3BucketName = "log.netflix.com/s3-bucket-name";
public static final String AnnotationKeyLogS3PathPrefix = "log.netflix.com/s3-path-prefix";
public static final String AnnotationKeyLogS3WriterIAMRole = "log.netflix.com/s3-writer-iam-role";
public static final String AnnotationKeyLogStdioCheckInterval = "log.netflix.com/stdio-check-interval";
public static final String AnnotationKeyLogUploadThresholdTime = "log.netflix.com/upload-threshold-time";
public static final String AnnotationKeyLogUploadCheckInterval = "log.netflix.com/upload-check-interval";
public static final String AnnotationKeyLogUploadRegexp = "log.netflix.com/upload-regexp";
// service configuration
public static final String AnnotationKeyServicePrefix = "service.netflix.com";
// sidecar configuration
public static final String AnnotationKeySuffixSidecars = "platform-sidecars.netflix.com";
public static final String AnnotationKeySuffixSidecarsChannelOverride = "channel-override";
public static final String AnnotationKeySuffixSidecarsChannelOverrideReason = "channel-override-reason";
// release = $channel/$version
public static final String AnnotationKeySuffixSidecarsRelease = "release";
// scheduling soft SLAs
// priority handling in scheduling queue
public static final String AnnotationKeySchedLatencyReq = "scheduler.titus.netflix.com/sched-latency-req";
public static final String AnnotationValSchedLatencyDelay = "delay";
public static final String AnnotationValSchedLatencyFast = "fast";
// dynamic spreading behavior
public static final String AnnotationKeySchedSpreadingReq = "scheduler.titus.netflix.com/spreading-req";
public static final String AnnotationValSchedSpreadingPack = "pack";
public static final String AnnotationValSchedSpreadingSpread = "spread";
}
| 1,028 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/MutableDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public class MutableDataGenerator<A> {
private final AtomicReference<DataGenerator<A>> dataGeneratorRef;
public MutableDataGenerator(DataGenerator<A> dataGenerator) {
this.dataGeneratorRef = new AtomicReference<>(dataGenerator);
}
public boolean isClosed() {
return dataGeneratorRef.get().isClosed();
}
public A getValue() {
DataGenerator<A> current = dataGeneratorRef.get();
A value = current.getValue();
dataGeneratorRef.set(current.apply());
return value;
}
public List<A> getValues(int count) {
List<A> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
result.add(getValue());
}
return result;
}
public Optional<A> getOptionalValue() {
DataGenerator<A> current = dataGeneratorRef.get();
Optional<A> value = current.getOptionalValue();
dataGeneratorRef.set(current.apply());
return value;
}
}
| 1,029 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/DataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.netflix.titus.common.data.generator.internal.BatchDataGenerator;
import com.netflix.titus.common.data.generator.internal.BindBuilderDataGenerator;
import com.netflix.titus.common.data.generator.internal.BindDataGenerator;
import com.netflix.titus.common.data.generator.internal.CharRangeDataGenerator;
import com.netflix.titus.common.data.generator.internal.ConcatDataGenerator;
import com.netflix.titus.common.data.generator.internal.DataGeneratorOperators;
import com.netflix.titus.common.data.generator.internal.FilterDataGenerator;
import com.netflix.titus.common.data.generator.internal.FlatMappedDataGenerator;
import com.netflix.titus.common.data.generator.internal.FromContextGenerator;
import com.netflix.titus.common.data.generator.internal.ItemDataGenerator;
import com.netflix.titus.common.data.generator.internal.LimitDataGenerator;
import com.netflix.titus.common.data.generator.internal.LongRangeDataGenerator;
import com.netflix.titus.common.data.generator.internal.LoopedDataGenerator;
import com.netflix.titus.common.data.generator.internal.MappedDataGenerator;
import com.netflix.titus.common.data.generator.internal.MappedWithIndexDataGenerator;
import com.netflix.titus.common.data.generator.internal.MergeDataGenerator;
import com.netflix.titus.common.data.generator.internal.RandomDataGenerator;
import com.netflix.titus.common.data.generator.internal.SeqDataGenerator;
import com.netflix.titus.common.data.generator.internal.SeqNumberDataGenerators;
import com.netflix.titus.common.data.generator.internal.UnionBuilderDataGeneratorBase;
import com.netflix.titus.common.data.generator.internal.UnionDataGenerator;
import com.netflix.titus.common.data.generator.internal.ZipDataGenerator;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.common.util.tuple.Quadruple;
import com.netflix.titus.common.util.tuple.Triple;
import rx.functions.Func3;
import static java.util.Arrays.asList;
/**
* TODO Partial objects generation and merging
*/
public abstract class DataGenerator<A> {
public static abstract class BuilderDataGenerator<BUILDER> extends DataGenerator<BUILDER> {
public abstract <B> BuilderDataGenerator<BUILDER> bind(DataGenerator<B> codomain, BiConsumer<BUILDER, B> builderSetter);
}
public static abstract class BuilderDataGenerator2<BUILDER> extends DataGenerator<BUILDER> {
public abstract <B> BuilderDataGenerator2<BUILDER> combine(DataGenerator<B> codomain, BiConsumer<BUILDER, B> builderSetter);
}
public abstract DataGenerator<A> apply();
public DataGenerator<A> apply(Consumer<A> consumer) {
getOptionalValue().ifPresent(consumer);
return apply();
}
public DataGenerator<A> apply(Consumer<A> consumer, int times) {
DataGenerator<A> nextGen = this;
for (int i = 0; i < times && !nextGen.isClosed(); i++) {
consumer.accept(nextGen.getValue());
nextGen = nextGen.apply();
}
return nextGen;
}
public Pair<DataGenerator<A>, List<A>> getAndApply(int times) {
List<A> items = new ArrayList<>();
return Pair.of(apply(items::add, times), items);
}
public boolean isClosed() {
return !getOptionalValue().isPresent();
}
public A getValue() {
return getOptionalValue().orElseThrow(() -> new IllegalStateException("No more values"));
}
public List<A> getValues(int count) {
return getAndApply(count).getRight();
}
public abstract Optional<A> getOptionalValue();
public <B> DataGenerator<B> cast(Class<B> newType) {
return (DataGenerator<B>) this;
}
/**
* Generate batches of data.
*/
public DataGenerator<List<A>> batch(int batchSize) {
return BatchDataGenerator.newInstance(this, batchSize);
}
/**
* Create infinite data generator, repeating the same data sequence.
*/
public DataGenerator<A> loop() {
return LoopedDataGenerator.newInstance(this);
}
/**
* Create infinite data generator, repeating the same data sequence, appending to each item the iteration index.
*/
public DataGenerator<A> loop(BiFunction<A, Integer, A> decorator) {
return LoopedDataGenerator.newInstance(this, decorator);
}
/**
* Join two generated streams one after another.
*/
public DataGenerator<A> concat(DataGenerator<A> another) {
return ConcatDataGenerator.newInstance(this, another);
}
/**
* Emit items matching a given predicate.
*/
public DataGenerator<A> filter(Function<A, Boolean> predicate) {
return FilterDataGenerator.newInstance(this, predicate);
}
public <B> DataGenerator<B> flatMap(Function<A, DataGenerator<B>> transformer) {
return FlatMappedDataGenerator.newInstance(this, transformer);
}
/**
* Limit data stream to a given number of items.
*/
public DataGenerator<A> limit(int count) {
return LimitDataGenerator.newInstance(this, count);
}
public <B> DataGenerator<B> map(Function<A, B> transformer) {
return MappedDataGenerator.newInstance(this, transformer);
}
public <B> DataGenerator<B> map(BiFunction<Long, A, B> transformer) {
return MappedWithIndexDataGenerator.newInstance(this, transformer);
}
public DataGenerator<A> random() {
return RandomDataGenerator.newInstance(this);
}
public DataGenerator<A> random(double density, int initialChunkSize) {
return RandomDataGenerator.newInstance(this, density, initialChunkSize);
}
/**
* Skip a given number of items.
*/
public DataGenerator<A> skip(int number) {
DataGenerator<A> next = this;
for (int i = 0; i < number; i++) {
if (isClosed()) {
return (DataGenerator<A>) EOS;
}
next = next.apply();
}
return next;
}
public List<A> toList() {
return DataGeneratorOperators.toList(this);
}
public List<A> toList(int limit) {
return DataGeneratorOperators.toList(this.limit(limit));
}
public static <BUILDER> BuilderDataGenerator<BUILDER> bindBuilder(Supplier<BUILDER> builderSupplier) {
return BindBuilderDataGenerator.newInstance(builderSupplier);
}
/**
* For each item from 'source' assign exactly one item from 'into'. If the same value is repeated in the
* 'source' generator, the original assignment is returned.
*/
public static <A, B> DataGenerator<Pair<A, B>> bind(DataGenerator<A> source, DataGenerator<B> into) {
return BindDataGenerator.newInstance(source, into);
}
/**
* For each item from 'source' assign one item from 'ontoB', and next one item from 'ontoC'. If the same value is repeated in the
* 'source' generator, the original triple value is returned.
*/
public static <A, B, C> DataGenerator<Triple<A, B, C>> bind(DataGenerator<A> source, DataGenerator<B> intoB, DataGenerator<C> intoC) {
return BindDataGenerator.newInstance(BindDataGenerator.newInstance(source, intoB), intoC).map(
abc -> Triple.of(abc.getLeft().getLeft(), abc.getLeft().getRight(), abc.getRight())
);
}
/**
* Three level binding. See {@link #bind(DataGenerator, DataGenerator)}.
*/
public static <A, B, C, D> DataGenerator<Quadruple<A, B, C, D>> bind(DataGenerator<A> source, DataGenerator<B> intoB, DataGenerator<C> intoC, DataGenerator<D> intoD) {
return bind(bind(source, intoB, intoC), intoD).map(abcd ->
Quadruple.of(abcd.getLeft().getFirst(), abcd.getLeft().getSecond(), abcd.getLeft().getThird(), abcd.getRight())
);
}
/**
* Concatenates values from multiple sources into a string. For each emission, a new value from each source generator is taken.
*/
public static DataGenerator<String> concatenations(String separator, DataGenerator<String>... sources) {
return concatenations(separator, asList(sources));
}
/**
* Concatenates values from multiple sources into a string. For each emission, a new value from each source generator is taken.
*/
public static DataGenerator<String> concatenations(String separator, List<DataGenerator<String>> sources) {
return union(sources, "", (acc, v) -> acc.isEmpty() ? v : acc + separator + v);
}
public static <V> DataGenerator<V> empty() {
return (DataGenerator<V>) EOS;
}
/**
* Generate sequence of data based on a context. Stream is terminated when the generated optional value is empty.
*/
public static <CONTEXT, V> DataGenerator<V> fromContextOpt(CONTEXT initial, Function<CONTEXT, Pair<CONTEXT, Optional<V>>> valueSupplier) {
return FromContextGenerator.newInstance(initial, valueSupplier);
}
/**
* Generate sequence of data based on a context.
*/
public static <CONTEXT, V> DataGenerator<V> fromContext(CONTEXT initial, Function<CONTEXT, Pair<CONTEXT, V>> valueSupplier) {
return FromContextGenerator.newInstance(initial, context -> valueSupplier.apply(context).mapRight(Optional::ofNullable));
}
public static <A> DataGenerator<A> items(A... words) {
return new ItemDataGenerator(asList(words), 0);
}
public static <A> DataGenerator<A> items(List<A> words) {
return new ItemDataGenerator(words, 0);
}
public static DataGenerator<Character> range(char from, char to) {
return new CharRangeDataGenerator(from, to, from);
}
public static DataGenerator<Long> range(long from, long to) {
return new LongRangeDataGenerator(from, to, from);
}
public static DataGenerator<Integer> rangeInt(int from, int to) {
return new LongRangeDataGenerator(from, to, from).map(Math::toIntExact);
}
public static DataGenerator<Long> range(long from) {
return new LongRangeDataGenerator(from, Long.MAX_VALUE, from);
}
/**
* Multiplexes input from multiple data generators into single stream.
*/
public static <A> DataGenerator<A> merge(DataGenerator<A>... sources) {
return MergeDataGenerator.newInstance(asList(sources));
}
/**
* Multiplexes input from multiple data generators into single stream.
*/
public static <A> DataGenerator<A> merge(Collection<DataGenerator<A>> sources) {
return MergeDataGenerator.newInstance(new ArrayList<>(sources));
}
/**
* Creates batches of data using a provided factory method. When producer emits empty optional value, the stream
* is terminated.
*/
public static <CONTEXT, A> DataGenerator<A[]> sequenceOpt(CONTEXT context,
int size,
Function<CONTEXT, Pair<CONTEXT, Optional<A>>> producer) {
return SeqDataGenerator.newInstance(context, size, producer);
}
/**
* Creates batches of data using a provided factory method.
*/
public static <CONTEXT, A> DataGenerator<A[]> sequence(CONTEXT context,
int size,
Function<CONTEXT, Pair<CONTEXT, A>> producer) {
return SeqDataGenerator.newInstance(context, size, ctx -> producer.apply(ctx).mapRight(Optional::ofNullable));
}
/**
* Creates a stream of string values.
*/
public static <CONTEXT> DataGenerator<String> sequenceOfString(CONTEXT context,
int size,
Function<CONTEXT, Pair<CONTEXT, Character>> producer) {
return sequence(context, size, producer).map(chars -> new String(CollectionsExt.toPrimitiveCharArray(chars)));
}
/**
* Generates sequences of ascending numbers (a1, a2, a3, ..., aN), where N is the sequence size, a1 >= lowerBound,
* and aN <= upperBound.
*/
public static DataGenerator<int[]> sequenceOfAscendingIntegers(int size, int lowerBound, int upperBound) {
return SeqNumberDataGenerators.sequenceOfAscendingIntegers(size, lowerBound, upperBound);
}
/**
* Generates all permutations of data from source generators.
*/
public static <A> DataGenerator<List<A>> union(DataGenerator<A>... sources) {
return UnionDataGenerator.newInstance(asList(sources));
}
/**
* Generates all permutations of data from source generators.
*/
public static <A> DataGenerator<List<A>> union(List<DataGenerator<A>> sources) {
return UnionDataGenerator.newInstance(sources);
}
/**
* Generates all permutations of data from source generators.
*/
public static <A, B, R> DataGenerator<R> union(DataGenerator<A> first, DataGenerator<B> second, BiFunction<A, B, R> combiner) {
List<DataGenerator<Object>> sources = asList((DataGenerator<Object>) first, (DataGenerator<Object>) second);
return UnionDataGenerator.newInstance(sources).map(list -> combiner.apply((A) list.get(0), (B) list.get(1)));
}
/**
* Generates all permutations of data from source generators.
*/
public static <A, B, C, R> DataGenerator<R> union(DataGenerator<A> first,
DataGenerator<B> second,
DataGenerator<C> third,
Func3<A, B, C, R> combiner) {
List<DataGenerator<Object>> sources = asList((DataGenerator<Object>) first, (DataGenerator<Object>) second, (DataGenerator<Object>) third);
return UnionDataGenerator.newInstance(sources).map(list -> combiner.call((A) list.get(0), (B) list.get(1), (C) list.get(2)));
}
/**
* Generates all permutations of data from source generators.
*/
public static <A, R> DataGenerator<R> union(List<DataGenerator<A>> sources, R zero, BiFunction<R, A, R> combiner) {
return UnionDataGenerator.newInstance(sources).map(list -> {
R result = zero;
for (A e : list) {
result = combiner.apply(result, e);
}
return result;
});
}
/**
* Generates all permutations of data from source generators.
*/
public static <BUILDER> BuilderDataGenerator2<BUILDER> unionBuilder(Supplier<BUILDER> builderSupplier) {
return UnionBuilderDataGeneratorBase.newInstance(builderSupplier);
}
public static <A, B> DataGenerator<Pair<A, B>> zip(DataGenerator<A> first, DataGenerator<B> second) {
return ZipDataGenerator.newInstance(first, second);
}
protected static DataGenerator<?> EOS = new DataGenerator<Object>() {
@Override
public DataGenerator<Object> apply() {
throw new IllegalStateException("No more items");
}
@Override
public Optional<Object> getOptionalValue() {
return Optional.empty();
}
};
}
| 1,030 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/LoopedDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.BiFunction;
import com.netflix.titus.common.data.generator.DataGenerator;
public class LoopedDataGenerator<A> extends DataGenerator<A> {
private final DataGenerator<A> reference;
private final DataGenerator<A> currentSource;
private final int iterationNumber;
private final BiFunction<A, Integer, A> decorator;
private final Optional<A> current;
private LoopedDataGenerator(DataGenerator<A> reference,
DataGenerator<A> currentSource,
int iterationNumber,
BiFunction<A, Integer, A> decorator) {
this.reference = reference;
this.currentSource = currentSource;
this.iterationNumber = iterationNumber;
this.decorator = decorator;
this.current = Optional.of(decorator.apply(currentSource.getValue(), iterationNumber));
}
@Override
public DataGenerator<A> apply() {
DataGenerator<A> nextGen = currentSource.apply();
if (nextGen.isClosed()) {
return new LoopedDataGenerator<>(reference, reference, iterationNumber + 1, decorator);
}
return new LoopedDataGenerator<>(reference, nextGen, iterationNumber, decorator);
}
@Override
public Optional<A> getOptionalValue() {
return current;
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source) {
return newInstance(source, (a, idx) -> a);
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source, BiFunction<A, Integer, A> decorator) {
if (source.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new LoopedDataGenerator<>(source, source, 0, decorator);
}
}
| 1,031 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/ZipDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class ZipDataGenerator<A, B> extends DataGenerator<Pair<A, B>> {
private final DataGenerator<A> first;
private final DataGenerator<B> second;
private final Optional<Pair<A, B>> current;
private ZipDataGenerator(DataGenerator<A> first, DataGenerator<B> second) {
this.first = first;
this.second = second;
this.current = Optional.of(Pair.of(first.getValue(), second.getValue()));
}
@Override
public DataGenerator<Pair<A, B>> apply() {
return newInstance(first.apply(), second.apply());
}
@Override
public Optional<Pair<A, B>> getOptionalValue() {
return current;
}
public static <A, B> DataGenerator<Pair<A, B>> newInstance(DataGenerator<A> first, DataGenerator<B> second) {
if (first.isClosed() || second.isClosed()) {
return (DataGenerator<Pair<A, B>>) EOS;
}
return new ZipDataGenerator<>(first, second);
}
}
| 1,032 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/ConcatDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.netflix.titus.common.data.generator.DataGenerator;
public class ConcatDataGenerator<A> extends DataGenerator<A> {
private final DataGenerator<A> first;
private final DataGenerator<A> second;
private ConcatDataGenerator(DataGenerator<A> first, DataGenerator<A> second) {
this.first = first;
this.second = second;
}
@Override
public DataGenerator<A> apply() {
return newInstance(first.apply(), second);
}
@Override
public Optional<A> getOptionalValue() {
return first.getOptionalValue();
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> first, DataGenerator<A> second) {
if (first.isClosed()) {
if (second.isClosed()) {
return (DataGenerator<A>) EOS;
}
return second;
}
if (second.isClosed()) {
return first;
}
return new ConcatDataGenerator<>(first, second);
}
}
| 1,033 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/MergeDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Optional;
import com.netflix.titus.common.data.generator.DataGenerator;
public class MergeDataGenerator<A> extends DataGenerator<A> {
private final List<DataGenerator<A>> sources;
private final Optional<A> currentValue;
private final int currentIdx;
private MergeDataGenerator(List<DataGenerator<A>> sources, int startFrom) {
this.sources = sources;
this.currentIdx = findNext(sources, startFrom);
this.currentValue = (currentIdx == -1) ? Optional.empty() : sources.get(currentIdx).getOptionalValue();
}
@Override
public DataGenerator<A> apply() {
if (currentIdx == -1) {
return (DataGenerator<A>) EOS;
}
ArrayList<DataGenerator<A>> genCopy = new ArrayList<>(sources);
genCopy.set(currentIdx, sources.get(currentIdx).apply());
return new MergeDataGenerator<>(genCopy, (currentIdx + 1) % genCopy.size());
}
@Override
public Optional<A> getOptionalValue() {
return currentValue;
}
private int findNext(List<DataGenerator<A>> sources, int startFrom) {
int currentIdx = startFrom;
do {
if (!sources.get(currentIdx).isClosed()) {
return currentIdx;
}
currentIdx = (currentIdx + 1) % sources.size();
} while (currentIdx != startFrom);
return -1;
}
public static <A> DataGenerator<A> newInstance(List<DataGenerator<A>> sources) {
if (sources.isEmpty()) {
return (DataGenerator<A>) EOS;
}
return new MergeDataGenerator<>(sources, 0);
}
}
| 1,034 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/BindBuilderDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.CollectionsExt;
import static java.util.Arrays.asList;
public abstract class BindBuilderDataGenerator<BUILDER> extends DataGenerator.BuilderDataGenerator<BUILDER> {
private static final BindBuilderDataGenerator<?> EMPTY_BIND_BUILDER_GENERATOR = new EmptyBindBuilderDataGenerator<>();
protected abstract List<Object> values();
public static <BUILDER> BindBuilderDataGenerator<BUILDER> newInstance(Supplier<BUILDER> builderSupplier) {
return new InitialBindBuilderDataGenerator<>(builderSupplier);
}
private static class EmptyBindBuilderDataGenerator<BUILDER> extends BindBuilderDataGenerator<BUILDER> {
@Override
public <B> BindBuilderDataGenerator<BUILDER> bind(DataGenerator<B> codomain, BiConsumer<BUILDER, B> builderSetter) {
return this;
}
@Override
protected List<Object> values() {
throw new IllegalStateException("No more values");
}
@Override
public DataGenerator<BUILDER> apply() {
return this;
}
@Override
public Optional<BUILDER> getOptionalValue() {
return Optional.empty();
}
}
private static class InitialBindBuilderDataGenerator<BUILDER> extends BindBuilderDataGenerator<BUILDER> {
private final Supplier<BUILDER> builderSupplier;
InitialBindBuilderDataGenerator(Supplier<BUILDER> builderSupplier) {
this.builderSupplier = builderSupplier;
}
@Override
public DataGenerator<BUILDER> apply() {
return DataGenerator.empty();
}
@Override
public Optional<BUILDER> getOptionalValue() {
return Optional.empty();
}
@Override
public <B> BindBuilderDataGenerator<BUILDER> bind(DataGenerator<B> codomain, BiConsumer<BUILDER, B> builderSetter) {
return codomain.getOptionalValue().isPresent()
? new OneValueBindBuilderDataGenerator<>(builderSupplier, codomain, builderSetter)
: (BindBuilderDataGenerator<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
@Override
protected List<Object> values() {
throw new IllegalStateException("No more values");
}
}
private static class OneValueBindBuilderDataGenerator<A, BUILDER> extends BindBuilderDataGenerator<BUILDER> {
private final Supplier<BUILDER> builderSupplier;
private final DataGenerator<A> domain;
private final BiConsumer<BUILDER, A> firstBuilderSetter;
private final List<Object> current;
public OneValueBindBuilderDataGenerator(Supplier<BUILDER> builderSupplier,
DataGenerator<A> domain,
BiConsumer<BUILDER, A> firstBuilderSetter) {
this.builderSupplier = builderSupplier;
this.domain = domain;
this.firstBuilderSetter = firstBuilderSetter;
this.current = Collections.singletonList(domain.getValue());
}
@Override
public BindBuilderDataGenerator<BUILDER> apply() {
DataGenerator<A> nextDomain = domain.apply();
if (nextDomain.isClosed()) {
return (BindBuilderDataGenerator<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
return new OneValueBindBuilderDataGenerator<>(builderSupplier, nextDomain, firstBuilderSetter);
}
@Override
public Optional<BUILDER> getOptionalValue() {
List<Object> attributes = values();
BUILDER newBuilder = builderSupplier.get();
firstBuilderSetter.accept(newBuilder, (A) attributes.get(0));
return Optional.of(newBuilder);
}
@Override
public <B> BindBuilderDataGenerator<BUILDER> bind(DataGenerator<B> codomain, BiConsumer<BUILDER, B> builderSetter) {
return new MultiValueBindBuilderDataGenerator<>(
this,
codomain,
builderSupplier,
asList((BiConsumer<BUILDER, Object>) firstBuilderSetter, (BiConsumer<BUILDER, Object>) builderSetter),
ImmutableMap.of()
);
}
@Override
public List<Object> values() {
return current;
}
}
private static class MultiValueBindBuilderDataGenerator<B, BUILDER> extends BindBuilderDataGenerator<BUILDER> {
private final BindBuilderDataGenerator<BUILDER> domain;
private final DataGenerator<B> codomain;
private final ImmutableMap<List<Object>, B> mappings;
private final List<Object> current;
private final Supplier<BUILDER> builderSupplier;
private final List<BiConsumer<BUILDER, Object>> builderSetters;
private MultiValueBindBuilderDataGenerator(BindBuilderDataGenerator<BUILDER> domain,
DataGenerator<B> codomain,
Supplier<BUILDER> builderSupplier,
List<BiConsumer<BUILDER, Object>> builderSetters,
ImmutableMap<List<Object>, B> mappings) {
this.domain = domain;
this.codomain = codomain;
this.builderSupplier = builderSupplier;
this.builderSetters = builderSetters;
List<Object> a = domain.values();
B b = mappings.get(a);
if (b == null) {
b = codomain.getValue();
this.mappings = ImmutableMap.<List<Object>, B>builder().putAll(mappings).put(a, b).build();
} else {
this.mappings = mappings;
}
this.current = CollectionsExt.copyAndAdd(a, b);
}
@Override
public DataGenerator<BUILDER> apply() {
DataGenerator<BUILDER> newDomain = domain.apply();
DataGenerator<B> newCodomain = codomain.apply();
if (newDomain.isClosed() || newCodomain.isClosed()) {
return (DataGenerator<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
return new MultiValueBindBuilderDataGenerator<>(
(BindBuilderDataGenerator<BUILDER>) newDomain,
newCodomain,
builderSupplier,
builderSetters,
mappings
);
}
@Override
public Optional<BUILDER> getOptionalValue() {
List<Object> attributes = values();
BUILDER newBuilder = builderSupplier.get();
for (int i = 0; i < attributes.size(); i++) {
builderSetters.get(i).accept(newBuilder, attributes.get(i));
}
return Optional.of(newBuilder);
}
@Override
public <C> BindBuilderDataGenerator<BUILDER> bind(DataGenerator<C> codomain, BiConsumer<BUILDER, C> builderSetter) {
return new MultiValueBindBuilderDataGenerator<>(
this,
codomain,
builderSupplier,
CollectionsExt.copyAndAdd(builderSetters, (BiConsumer<BUILDER, Object>) builderSetter),
ImmutableMap.of()
);
}
@Override
public List<Object> values() {
return current;
}
}
} | 1,035 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/DataGeneratorOperators.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;
public class DataGeneratorOperators {
private static final int TO_LIST_LIMIT = 10000;
public static <A> List<A> toList(DataGenerator<A> source) {
List<A> result = new ArrayList<>();
DataGenerator<A> nextGen = source;
while (!nextGen.isClosed()) {
result.add(nextGen.getValue());
if (result.size() > TO_LIST_LIMIT) {
throw new IllegalStateException("Too many items");
}
nextGen = nextGen.apply();
}
return result;
}
}
| 1,036 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/FlatMappedDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.Function;
import com.netflix.titus.common.data.generator.DataGenerator;
/**
*/
public class FlatMappedDataGenerator<A, B> extends DataGenerator<B> {
private final DataGenerator<A> source;
private final DataGenerator<B> pending;
private final Function<A, DataGenerator<B>> transformer;
private FlatMappedDataGenerator(DataGenerator<A> source, DataGenerator<B> pending, Function<A, DataGenerator<B>> transformer) {
this.source = source;
this.pending = pending;
this.transformer = transformer;
}
@Override
public DataGenerator<B> apply() {
DataGenerator<B> next = pending.apply();
if (!next.isClosed()) {
return new FlatMappedDataGenerator<>(source, next, transformer);
}
return newInstance(source.apply(), transformer);
}
@Override
public Optional<B> getOptionalValue() {
return pending.getOptionalValue();
}
public static <A, B> DataGenerator<B> newInstance(DataGenerator<A> source, Function<A, DataGenerator<B>> transformer) {
for (DataGenerator<A> nextSource = source; !nextSource.isClosed(); nextSource = nextSource.apply()) {
DataGenerator<B> nextPending = transformer.apply(nextSource.getValue());
if (!nextPending.isClosed()) {
return new FlatMappedDataGenerator<>(nextSource, nextPending, transformer);
}
}
return (DataGenerator<B>) EOS;
}
}
| 1,037 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/Combinations.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Arrays;
import java.util.List;
import com.google.common.base.Preconditions;
/**
* Given collection of ranges (0..n1), (0..n2),...,(0..nk) of different sizes, generates a sequence
* of unique tuples, containing one element from the same range. The ranges can be re-sized, to increase number
* of available elements.
*/
class Combinations {
private static final int[][] EMPTY_TUPLES = new int[0][];
private final List<Integer> seqSizes;
private final int[][] tuples;
private Combinations(int tupleSize) {
this.seqSizes = createListFilledWithZeros(tupleSize);
this.tuples = EMPTY_TUPLES;
}
private Combinations(Combinations previous, List<Integer> newSeqSizes) {
this.seqSizes = newSeqSizes;
int total = seqSizes.stream().reduce(1, (acc, s) -> acc * s);
int[] currentTuple = new int[seqSizes.size()];
int[][] output = new int[total][];
copy(previous.tuples, output);
fill(currentTuple, previous.seqSizes, newSeqSizes, 0, output, previous.tuples.length, false);
this.tuples = output;
}
public int getSize() {
return tuples.length;
}
public int[] combinationAt(int pos) {
return tuples[pos];
}
public Combinations resize(List<Integer> newSeqSizes) {
Preconditions.checkArgument(newSeqSizes.size() == seqSizes.size());
for (int i = 0; i < newSeqSizes.size(); i++) {
Preconditions.checkArgument(newSeqSizes.get(i) >= seqSizes.get(i));
}
return new Combinations(this, newSeqSizes);
}
public static Combinations newInstance(int tupleSize) {
return new Combinations(tupleSize);
}
private List<Integer> createListFilledWithZeros(int size) {
List<Integer> result = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
result.add(0);
}
return result;
}
private static void copyTuple(int[] source, int[][] output, int outputPos) {
output[outputPos] = Arrays.copyOf(source, source.length);
}
private static void copy(int[][] source, int[][] output) {
System.arraycopy(source, 0, output, 0, source.length);
}
private static int fill(int[] currentTuple,
List<Integer> oldSeqSizes,
List<Integer> newSeqSizes,
int seqIdx,
int[][] output,
int outputPos,
boolean hasNewItem) {
int currentSeqSize = newSeqSizes.get(seqIdx);
int lastSeqIdx = newSeqSizes.size() - 1;
int startFrom = oldSeqSizes.get(seqIdx);
if (seqIdx == lastSeqIdx) {
for (int i = hasNewItem ? 0 : startFrom; i < currentSeqSize; i++, outputPos++) {
currentTuple[seqIdx] = i;
copyTuple(currentTuple, output, outputPos);
}
} else {
if (!hasNewItem) {
for (int i = 0; i < startFrom; i++) {
currentTuple[seqIdx] = i;
outputPos = fill(currentTuple, oldSeqSizes, newSeqSizes, seqIdx + 1, output, outputPos, false);
}
}
for (int i = hasNewItem ? 0 : startFrom; i < currentSeqSize; i++) {
currentTuple[seqIdx] = i;
outputPos = fill(currentTuple, oldSeqSizes, newSeqSizes, seqIdx + 1, output, outputPos, true);
}
}
return outputPos;
}
}
| 1,038 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/UnionDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Optional;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.tuple.Pair;
/**
*/
public class UnionDataGenerator<A> extends DataGenerator<List<A>> {
private static final double DEFAULT_DENSITY = 0.3;
private static final int DEFAULT_INITIAL_CHUNK_SIZE = 3;
private final double density;
private final int slice;
private final boolean extendable;
private final List<DataGenerator<A>> sources;
private final List<List<A>> items;
private final Combinations combinations;
private final int position;
private final int scaleUpLevel;
private final Optional<List<A>> currentValue;
private UnionDataGenerator(List<DataGenerator<A>> sources, double density, int initialSlice) {
this.density = density;
this.slice = initialSlice;
this.extendable = true;
Pair<List<DataGenerator<A>>, List<List<A>>> pair = fill(sources, initialSlice);
this.sources = pair.getLeft();
this.items = pair.getRight();
List<Integer> newSeqSizes = items.stream().map(List::size).collect(Collectors.toList());
this.combinations = Combinations.newInstance(sources.size()).resize(newSeqSizes);
this.position = 0;
this.scaleUpLevel = (int) (combinations.getSize() * density);
this.currentValue = valueAt(0);
}
private UnionDataGenerator(UnionDataGenerator<A> generator, int position) {
this.density = generator.density;
if (!generator.extendable || position < generator.scaleUpLevel) {
this.slice = generator.slice;
this.extendable = generator.extendable;
this.scaleUpLevel = generator.scaleUpLevel;
this.sources = generator.sources;
this.items = generator.items;
this.combinations = generator.combinations;
} else {
this.slice = generator.slice * 2;
Optional<Pair<List<DataGenerator<A>>, List<List<A>>>> resizedOpt = resizeSourceData(generator, slice);
if (resizedOpt.isPresent()) {
this.extendable = true;
Pair<List<DataGenerator<A>>, List<List<A>>> resized = resizedOpt.get();
this.sources = resized.getLeft();
this.items = resized.getRight();
this.combinations = resizeCombinations(generator.combinations, items);
this.scaleUpLevel = (int) (combinations.getSize() * density);
} else {
this.extendable = false;
this.scaleUpLevel = generator.combinations.getSize();
this.sources = generator.sources;
this.items = generator.items;
this.combinations = generator.combinations;
}
}
this.position = position;
this.currentValue = valueAt(position);
}
@Override
public DataGenerator<List<A>> apply() {
UnionDataGenerator nextGen = new UnionDataGenerator(this, position + 1);
return nextGen.isClosed() ? (DataGenerator<List<A>>) EOS : nextGen;
}
@Override
public Optional<List<A>> getOptionalValue() {
return currentValue;
}
private Pair<List<DataGenerator<A>>, List<List<A>>> fill(List<DataGenerator<A>> sources, int sliceSize) {
List<DataGenerator<A>> nextSources = new ArrayList<>(sources.size());
List<List<A>> items = new ArrayList<>();
for (DataGenerator<A> source : sources) {
Pair<DataGenerator<A>, List<A>> next = fill(source, sliceSize);
nextSources.add(next.getLeft());
items.add(next.getRight());
}
return Pair.of(nextSources, items);
}
private Pair<DataGenerator<A>, List<A>> fill(DataGenerator<A> source, int sliceSize) {
DataGenerator<A> nextSource = source;
List<A> values = new ArrayList<>(sliceSize);
for (int i = 0; i < sliceSize && !nextSource.isClosed(); i++) {
values.add(nextSource.getValue());
nextSource = nextSource.apply();
}
return Pair.of(nextSource, values);
}
private Optional<Pair<List<DataGenerator<A>>, List<List<A>>>> resizeSourceData(UnionDataGenerator<A> previous, int slice) {
List<DataGenerator<A>> previousSources = previous.sources;
List<DataGenerator<A>> nextSources = new ArrayList<>(previousSources.size());
List<List<A>> items = new ArrayList<>();
int added = 0;
for (int i = 0; i < previousSources.size(); i++) {
Pair<DataGenerator<A>, List<A>> pair = fill(previousSources.get(i), slice - previous.items.get(i).size());
nextSources.add(pair.getLeft());
added += pair.getRight().size();
items.add(CollectionsExt.merge(previous.items.get(i), pair.getRight()));
}
return added == 0 ? Optional.empty() : Optional.of(Pair.of(nextSources, items));
}
private Combinations resizeCombinations(Combinations previousCombinations, List<List<A>> items) {
List<Integer> newSeqSizes = items.stream().map(List::size).collect(Collectors.toList());
return previousCombinations.resize(newSeqSizes);
}
private Optional<List<A>> valueAt(int position) {
if (combinations.getSize() <= position) {
return Optional.empty();
}
int[] indexes = combinations.combinationAt(position);
List<A> tuple = new ArrayList<>(indexes.length);
for (int i = 0; i < indexes.length; i++) {
tuple.add(items.get(i).get(indexes[i]));
}
return Optional.of(tuple);
}
public static <A> DataGenerator<List<A>> newInstance(List<DataGenerator<A>> sources) {
return newInstance(sources, DEFAULT_DENSITY, DEFAULT_INITIAL_CHUNK_SIZE);
}
public static <A> DataGenerator<List<A>> newInstance(List<DataGenerator<A>> sources, double density, int initialSlice) {
Preconditions.checkArgument(density > 0.0, "Density must be > 0");
Preconditions.checkArgument(initialSlice > 0, "Initial slice must be > 0");
if (sources.isEmpty()) {
return (DataGenerator<List<A>>) EOS;
}
return new UnionDataGenerator<>(sources, density, initialSlice);
}
}
| 1,039 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/FilterDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.Function;
import com.netflix.titus.common.data.generator.DataGenerator;
public class FilterDataGenerator<A> extends DataGenerator<A> {
private final DataGenerator<A> source;
private final Function<A, Boolean> predicate;
private FilterDataGenerator(DataGenerator<A> source, Function<A, Boolean> predicate) {
this.source = findNext(source, predicate);
this.predicate = predicate;
}
@Override
public DataGenerator<A> apply() {
DataGenerator<A> nextGen = source.apply();
if (nextGen.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new FilterDataGenerator<>(nextGen, predicate);
}
@Override
public Optional<A> getOptionalValue() {
return source.getOptionalValue();
}
private static <A> DataGenerator<A> findNext(DataGenerator<A> source, Function<A, Boolean> predicate) {
DataGenerator<A> nextGen = source;
while (!nextGen.isClosed()) {
if (predicate.apply(nextGen.getValue())) {
return nextGen;
}
nextGen = nextGen.apply();
}
return (DataGenerator<A>) EOS;
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source, Function<A, Boolean> predicate) {
if (source.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new FilterDataGenerator<>(source, predicate);
}
}
| 1,040 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/ItemDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.netflix.titus.common.data.generator.DataGenerator;
public class ItemDataGenerator<A> extends DataGenerator<A> {
private final List<A> words;
private final int currentIdx;
private final Optional<A> currentValue;
public ItemDataGenerator(List<A> words, int currentIdx) {
this.words = words;
this.currentIdx = currentIdx;
this.currentValue = Optional.of(words.get(currentIdx));
}
@Override
public DataGenerator<A> apply() {
int nextIdx = currentIdx + 1;
if (nextIdx == words.size()) {
return (DataGenerator<A>) EOS;
}
return new ItemDataGenerator(words, nextIdx);
}
@Override
public Optional<A> getOptionalValue() {
return currentValue;
}
}
| 1,041 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/MappedDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.Function;
import com.netflix.titus.common.data.generator.DataGenerator;
/**
*/
public class MappedDataGenerator<A, B> extends DataGenerator<B> {
private final DataGenerator<A> sourceGenerator;
private final Function<A, B> transformer;
private final Optional<B> currentValue;
private MappedDataGenerator(DataGenerator<A> sourceGenerator, Function<A, B> transformer) {
this.sourceGenerator = sourceGenerator;
this.transformer = transformer;
this.currentValue = sourceGenerator.getOptionalValue().map(transformer::apply);
}
@Override
public DataGenerator<B> apply() {
return currentValue.isPresent() ? new MappedDataGenerator<>(sourceGenerator.apply(), transformer) : (DataGenerator<B>) EOS;
}
@Override
public Optional<B> getOptionalValue() {
return currentValue;
}
public static <A, B> DataGenerator<B> newInstance(DataGenerator<A> sourceGenerator, Function<A, B> transformer) {
if (sourceGenerator.isClosed()) {
return (DataGenerator<B>) EOS;
}
return new MappedDataGenerator<>(sourceGenerator, transformer);
}
}
| 1,042 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/UnionBuilderDataGeneratorBase.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.CollectionsExt;
import static java.util.Arrays.asList;
public abstract class UnionBuilderDataGeneratorBase<BUILDER> extends DataGenerator.BuilderDataGenerator2<BUILDER> {
private static final UnionBuilderDataGeneratorBase<?> EMPTY_BIND_BUILDER_GENERATOR = new EmptyBuilderDataGenerator<>();
protected abstract List<Object> values();
public static <BUILDER> DataGenerator.BuilderDataGenerator2<BUILDER> newInstance(Supplier<BUILDER> builderSupplier) {
return new InitialBindBuilderDataGenerator<>(builderSupplier);
}
static class EmptyBuilderDataGenerator<BUILDER> extends UnionBuilderDataGeneratorBase<BUILDER> {
@Override
public <B> BuilderDataGenerator2<BUILDER> combine(DataGenerator<B> source, BiConsumer<BUILDER, B> builderSetter) {
return this;
}
@Override
protected List<Object> values() {
throw new IllegalStateException("No more values");
}
@Override
public DataGenerator<BUILDER> apply() {
return this;
}
@Override
public Optional<BUILDER> getOptionalValue() {
return Optional.empty();
}
}
static class InitialBindBuilderDataGenerator<BUILDER> extends UnionBuilderDataGeneratorBase<BUILDER> {
private final Supplier<BUILDER> builderSupplier;
InitialBindBuilderDataGenerator(Supplier<BUILDER> builderSupplier) {
this.builderSupplier = builderSupplier;
}
@Override
public DataGenerator<BUILDER> apply() {
return DataGenerator.empty();
}
@Override
public Optional<BUILDER> getOptionalValue() {
return Optional.empty();
}
@Override
public <B> BuilderDataGenerator2<BUILDER> combine(DataGenerator<B> source, BiConsumer<BUILDER, B> builderSetter) {
return source.getOptionalValue().isPresent()
? new OneValueBindBuilderDataGenerator<>(builderSupplier, source, builderSetter)
: (BuilderDataGenerator2<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
@Override
protected List<Object> values() {
throw new IllegalStateException("No more values");
}
}
static class OneValueBindBuilderDataGenerator<A, BUILDER, CONTEXT> extends UnionBuilderDataGeneratorBase<BUILDER> {
private final Supplier<BUILDER> builderSupplier;
private final DataGenerator<A> domain;
private final BiConsumer<BUILDER, A> firstBuilderSetter;
private final List<Object> current;
OneValueBindBuilderDataGenerator(Supplier<BUILDER> builderSupplier,
DataGenerator<A> domain,
BiConsumer<BUILDER, A> firstBuilderSetter) {
this.builderSupplier = builderSupplier;
this.domain = domain;
this.firstBuilderSetter = firstBuilderSetter;
this.current = Collections.singletonList(domain.getValue());
}
@Override
public UnionBuilderDataGeneratorBase<BUILDER> apply() {
DataGenerator<A> nextDomain = domain.apply();
if (nextDomain.isClosed()) {
return (UnionBuilderDataGeneratorBase<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
return new OneValueBindBuilderDataGenerator<>(builderSupplier, nextDomain, firstBuilderSetter);
}
@Override
public Optional<BUILDER> getOptionalValue() {
List<Object> attributes = values();
BUILDER newBuilder = builderSupplier.get();
firstBuilderSetter.accept(newBuilder, (A) attributes.get(0));
return Optional.of(newBuilder);
}
@Override
public <B> BuilderDataGenerator2<BUILDER> combine(DataGenerator<B> source, BiConsumer<BUILDER, B> builderSetter) {
return new MultiValueBindBuilderDataGenerator<>(
this,
source,
source,
builderSupplier,
asList((BiConsumer<BUILDER, Object>) firstBuilderSetter, (BiConsumer<BUILDER, Object>) builderSetter)
);
}
@Override
public List<Object> values() {
return current;
}
}
static class MultiValueBindBuilderDataGenerator<B, BUILDER> extends UnionBuilderDataGeneratorBase<BUILDER> {
private final UnionBuilderDataGeneratorBase<BUILDER> domain;
private final DataGenerator<B> initialCodomain;
private final DataGenerator<B> codomain;
private final List<Object> current;
private final Supplier<BUILDER> builderSupplier;
private final List<BiConsumer<BUILDER, Object>> builderSetters;
MultiValueBindBuilderDataGenerator(UnionBuilderDataGeneratorBase<BUILDER> domain,
DataGenerator<B> initialCodomain,
DataGenerator<B> codomain,
Supplier<BUILDER> builderSupplier,
List<BiConsumer<BUILDER, Object>> builderSetters) {
this.initialCodomain = initialCodomain;
this.domain = domain;
this.builderSupplier = builderSupplier;
this.builderSetters = builderSetters;
List<Object> a = domain.values();
this.current = CollectionsExt.copyAndAdd(a, codomain.getValue());
this.codomain = codomain;
}
@Override
public DataGenerator<BUILDER> apply() {
DataGenerator<B> newCodomain = codomain.apply();
if (!newCodomain.isClosed()) {
return new MultiValueBindBuilderDataGenerator<>(
domain,
initialCodomain,
newCodomain,
builderSupplier,
builderSetters
);
}
DataGenerator<BUILDER> newDomain = domain.apply();
if (newDomain.isClosed()) {
return (DataGenerator<BUILDER>) EMPTY_BIND_BUILDER_GENERATOR;
}
return new MultiValueBindBuilderDataGenerator<>(
(UnionBuilderDataGeneratorBase<BUILDER>) newDomain,
initialCodomain,
initialCodomain,
builderSupplier,
builderSetters
);
}
@Override
public Optional<BUILDER> getOptionalValue() {
List<Object> attributes = values();
BUILDER newBuilder = builderSupplier.get();
for (int i = 0; i < attributes.size(); i++) {
builderSetters.get(i).accept(newBuilder, attributes.get(i));
}
return Optional.of(newBuilder);
}
@Override
public List<Object> values() {
return current;
}
@Override
public <C> UnionBuilderDataGeneratorBase<BUILDER> combine(DataGenerator<C> source, BiConsumer<BUILDER, C> builderSetter) {
return new MultiValueBindBuilderDataGenerator<>(
this,
source,
source,
builderSupplier,
CollectionsExt.copyAndAdd(builderSetters, (BiConsumer<BUILDER, Object>) builderSetter)
);
}
}
}
| 1,043 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/LimitDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.data.generator.DataGenerator;
public class LimitDataGenerator<A> extends DataGenerator<A> {
private final DataGenerator<A> source;
private final int remaining;
private LimitDataGenerator(DataGenerator<A> source, int count) {
this.source = source;
this.remaining = count - 1;
}
@Override
public DataGenerator<A> apply() {
if (remaining == 0) {
return (DataGenerator<A>) EOS;
}
DataGenerator nextGen = source.apply();
if (nextGen.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new LimitDataGenerator<>(nextGen, remaining);
}
@Override
public Optional<A> getOptionalValue() {
return source.getOptionalValue();
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source, int count) {
Preconditions.checkArgument(count > 0, "Limit must be > 0");
if (source.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new LimitDataGenerator<>(source, count);
}
}
| 1,044 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/SeqDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang.reflect.Array;
import java.util.Optional;
import java.util.function.Function;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class SeqDataGenerator<A, CONTEXT> extends DataGenerator<A[]> {
private final int size;
private final Function<CONTEXT, Pair<CONTEXT, Optional<A>>> factory;
private final Pair<CONTEXT, Optional<A[]>> current;
private SeqDataGenerator(CONTEXT context,
int size,
Function<CONTEXT, Pair<CONTEXT, Optional<A>>> producer) {
this.size = size;
this.factory = producer;
this.current = makeNext(context, size, producer);
}
@Override
public DataGenerator<A[]> apply() {
if (current.getRight().isPresent()) {
return new SeqDataGenerator<>(current.getLeft(), size, factory);
}
return (DataGenerator<A[]>) EOS;
}
@Override
public Optional<A[]> getOptionalValue() {
return current.getRight();
}
private Pair<CONTEXT, Optional<A[]>> makeNext(CONTEXT context, int size, Function<CONTEXT, Pair<CONTEXT, Optional<A>>> factory) {
Pair<CONTEXT, Optional<A>> firstOpt = factory.apply(context);
if (!firstOpt.getRight().isPresent()) {
return Pair.of(firstOpt.getLeft(), Optional.empty());
}
A first = firstOpt.getRight().get();
A[] result = (A[]) Array.newInstance(first.getClass(), size);
result[0] = first;
CONTEXT nextContext = firstOpt.getLeft();
for (int i = 1; i < size; i++) {
Pair<CONTEXT, Optional<A>> nextOpt = factory.apply(nextContext);
if (!nextOpt.getRight().isPresent()) {
return Pair.of(nextOpt.getLeft(), Optional.empty());
}
result[i] = nextOpt.getRight().get();
nextContext = nextOpt.getLeft();
}
return Pair.of(nextContext, Optional.of(result));
}
public static <CONTEXT, A> DataGenerator<A[]> newInstance(CONTEXT context, int size, Function<CONTEXT, Pair<CONTEXT, Optional<A>>> factory) {
return new SeqDataGenerator<>(context, size, factory);
}
}
| 1,045 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/MappedWithIndexDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.BiFunction;
import com.netflix.titus.common.data.generator.DataGenerator;
public class MappedWithIndexDataGenerator<A, B> extends DataGenerator<B> {
private final DataGenerator<A> sourceGenerator;
private final BiFunction<Long, A, B> transformer;
private final long index;
private final Optional<B> currentValue;
private MappedWithIndexDataGenerator(DataGenerator<A> sourceGenerator, BiFunction<Long, A, B> transformer, long index) {
this.sourceGenerator = sourceGenerator;
this.transformer = transformer;
this.index = index;
this.currentValue = sourceGenerator.getOptionalValue().map(t -> transformer.apply(index, t));
}
@Override
public DataGenerator<B> apply() {
return currentValue.isPresent() ? new MappedWithIndexDataGenerator<>(sourceGenerator.apply(), transformer, index + 1) : (DataGenerator<B>) EOS;
}
@Override
public Optional<B> getOptionalValue() {
return currentValue;
}
public static <A, B> DataGenerator<B> newInstance(DataGenerator<A> sourceGenerator, BiFunction<Long, A, B> transformer) {
if (sourceGenerator.isClosed()) {
return (DataGenerator<B>) EOS;
}
return new MappedWithIndexDataGenerator<>(sourceGenerator, transformer, 0);
}
}
| 1,046 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/LongRangeDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.data.generator.DataGenerator;
public class LongRangeDataGenerator extends DataGenerator<Long> {
private final long from;
private final long to;
private final Optional<Long> current;
public LongRangeDataGenerator(long from, long to, long current) {
Preconditions.checkArgument(from <= to, "Invalid value range: " + from + " > " + to);
this.from = from;
this.to = to;
this.current = Optional.of(current);
}
@Override
public DataGenerator<Long> apply() {
if (current.get() == (to - 1)) {
return (DataGenerator<Long>) EOS;
}
return new LongRangeDataGenerator(from, to, current.get() + 1);
}
@Override
public Optional<Long> getOptionalValue() {
return current;
}
}
| 1,047 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/BindDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.google.common.collect.ImmutableMap;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class BindDataGenerator<A, B> extends DataGenerator<Pair<A, B>> {
private final DataGenerator<A> domain;
private final DataGenerator<B> codomain;
private final ImmutableMap<A, B> mappings;
private final Optional<Pair<A, B>> current;
private BindDataGenerator(DataGenerator<A> domain, DataGenerator<B> codomain, ImmutableMap<A, B> mappings) {
this.domain = domain;
this.codomain = codomain;
A a = domain.getValue();
B b = mappings.get(a);
if (b == null) {
b = codomain.getValue();
this.mappings = ImmutableMap.<A, B>builder().putAll(mappings).put(a, b).build();
} else {
this.mappings = mappings;
}
this.current = Optional.of(Pair.of(a, b));
}
@Override
public DataGenerator<Pair<A, B>> apply() {
return newInstance(domain.apply(), codomain.apply(), mappings);
}
@Override
public Optional<Pair<A, B>> getOptionalValue() {
return current;
}
private static <A, B> DataGenerator<Pair<A, B>> newInstance(DataGenerator<A> domain, DataGenerator<B> codomain, ImmutableMap<A, B> mappings) {
if (domain.isClosed() || codomain.isClosed()) {
return (DataGenerator<Pair<A, B>>) EOS;
}
return new BindDataGenerator<>(domain, codomain, mappings);
}
public static <A, B> DataGenerator<Pair<A, B>> newInstance(DataGenerator<A> domain, DataGenerator<B> codomain) {
return newInstance(domain, codomain, ImmutableMap.of());
}
}
| 1,048 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/RandomDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Optional;
import java.util.Random;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class RandomDataGenerator<A> extends DataGenerator<A> {
private static final double DEFAULT_DENSITY = 0.3;
private static final int DEFAULT_INITIAL_CHUNK_SIZE = 10;
private final Random random;
private final double density;
private final int slice;
private final DataGenerator<A> source;
private final List<A> items;
private final int position;
private final int scaleUpLevel;
private final Optional<A> current;
private RandomDataGenerator(DataGenerator<A> source, double density, int initialSlice) {
this.random = new Random();
this.density = density;
this.slice = initialSlice;
Pair<DataGenerator<A>, List<A>> pair = source.getAndApply(initialSlice);
this.source = pair.getLeft();
this.items = randomize(pair.getRight(), 0);
this.position = 0;
this.scaleUpLevel = (int) (items.size() * density);
this.current = Optional.of(items.get(0));
}
private RandomDataGenerator(RandomDataGenerator<A> previousGen, int position) {
this.random = previousGen.random;
this.density = previousGen.density;
if (previousGen.source.isClosed() || position < previousGen.scaleUpLevel) {
this.items = previousGen.items;
this.scaleUpLevel = previousGen.scaleUpLevel;
this.slice = previousGen.slice;
if (position < items.size()) {
this.source = previousGen.source;
this.current = Optional.of(items.get(position));
} else {
this.source = (DataGenerator<A>) EOS;
this.current = Optional.empty();
}
} else {
this.slice = previousGen.slice * 2;
Pair<DataGenerator<A>, List<A>> pair = resize(previousGen.source, previousGen.items, slice);
this.source = pair.getLeft();
this.items = randomize(pair.getRight(), position);
this.scaleUpLevel = (int) (items.size() * density);
this.current = Optional.of(items.get(position));
}
this.position = position;
}
@Override
public DataGenerator<A> apply() {
RandomDataGenerator<A> nextGen = new RandomDataGenerator<>(this, position + 1);
return nextGen.isClosed() ? (DataGenerator<A>) EOS : nextGen;
}
@Override
public Optional<A> getOptionalValue() {
return current;
}
private List<A> randomize(List<A> items, int randomizeFromIdx) {
int outputSize = items.size();
int last = outputSize - 1;
for (int i = randomizeFromIdx; i < last; i++) {
int rpos = i + random.nextInt(outputSize - i);
A tmp = items.get(rpos);
items.set(rpos, items.get(i));
items.set(i, tmp);
}
return items;
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source) {
return newInstance(source, DEFAULT_DENSITY, DEFAULT_INITIAL_CHUNK_SIZE);
}
public static <A> DataGenerator<A> newInstance(DataGenerator<A> source, double density, int initialChunkSize) {
if (source.isClosed()) {
return (DataGenerator<A>) EOS;
}
return new RandomDataGenerator<>(source, density, initialChunkSize);
}
private static <A> Pair<DataGenerator<A>, List<A>> resize(DataGenerator<A> source, List<A> items, int slice) {
List<A> resized = new ArrayList<>(slice);
resized.addAll(items);
return Pair.of(source.apply(resized::add, slice - items.size()), resized);
}
}
| 1,049 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/FromContextGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import java.util.function.Function;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class FromContextGenerator<CONTEXT, V> extends DataGenerator<V> {
private final Function<CONTEXT, Pair<CONTEXT, Optional<V>>> valueSupplier;
private final Pair<CONTEXT, Optional<V>> current;
private FromContextGenerator(CONTEXT initial, Function<CONTEXT, Pair<CONTEXT, Optional<V>>> valueSupplier) {
this.valueSupplier = valueSupplier;
this.current = valueSupplier.apply(initial);
}
@Override
public DataGenerator<V> apply() {
if (current.getRight().isPresent()) {
return newInstance(current.getLeft(), valueSupplier);
}
return (DataGenerator<V>) EOS;
}
@Override
public Optional<V> getOptionalValue() {
return current.getRight();
}
public static <V, CONTEXT> DataGenerator<V> newInstance(CONTEXT initial, Function<CONTEXT, Pair<CONTEXT, Optional<V>>> valueSupplier) {
return new FromContextGenerator<>(initial, valueSupplier);
}
}
| 1,050 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/BatchDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Optional;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class BatchDataGenerator<T> extends DataGenerator<List<T>> {
private final DataGenerator<T> source;
private final int batchSize;
private final Optional<List<T>> currentBatch;
private BatchDataGenerator(DataGenerator<T> source, int batchSize) {
this.batchSize = batchSize;
Pair<List<T>, DataGenerator<T>> pair = nextBatch(source, batchSize);
this.currentBatch = Optional.of(pair.getLeft());
this.source = pair.getRight();
}
@Override
public DataGenerator<List<T>> apply() {
if (source.isClosed()) {
return (DataGenerator<List<T>>) EOS;
}
return new BatchDataGenerator<>(source, batchSize);
}
@Override
public Optional<List<T>> getOptionalValue() {
return currentBatch;
}
private Pair<List<T>, DataGenerator<T>> nextBatch(DataGenerator<T> source, int batchSize) {
List<T> batch = new ArrayList<>(batchSize);
DataGenerator<T> nextGen = source;
for (int i = 0; i < batchSize && !nextGen.isClosed(); i++) {
batch.add(nextGen.getValue());
nextGen = nextGen.apply();
}
return Pair.of(batch, nextGen);
}
public static <A> DataGenerator<List<A>> newInstance(DataGenerator<A> source, int batchSize) {
Preconditions.checkArgument(batchSize > 0);
if (source.isClosed()) {
return (DataGenerator<List<A>>) EOS;
}
return new BatchDataGenerator<>(source, batchSize);
}
}
| 1,051 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/CharRangeDataGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Optional;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.data.generator.DataGenerator;
public class CharRangeDataGenerator extends DataGenerator<Character> {
private final char from;
private final char to;
private final Optional<Character> current;
public CharRangeDataGenerator(char from, char to, char current) {
Preconditions.checkArgument(from <= to, "Invalid value range: " + from + " > " + to);
this.from = from;
this.to = to;
this.current = Optional.of(current);
}
@Override
public DataGenerator<Character> apply() {
if (current.get() == (to - 1)) {
return (DataGenerator<Character>) EOS;
}
char c = current.get();
c++;
return new CharRangeDataGenerator(from, to, c);
}
@Override
public Optional<Character> getOptionalValue() {
return current;
}
}
| 1,052 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/data/generator/internal/SeqNumberDataGenerators.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Arrays;
import java.util.Random;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
public class SeqNumberDataGenerators {
public static DataGenerator<int[]> sequenceOfAscendingIntegers(int size, int lowerBound, int upperBound) {
final int range = upperBound - lowerBound;
return DataGenerator.fromContext(new Random(), random -> {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = lowerBound + random.nextInt(range);
}
Arrays.sort(result);
return Pair.of(random, result);
});
}
}
| 1,053 |
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/jhiccup/JHiccupComponent.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.jhiccup;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.environment.MyEnvironment;
import com.netflix.titus.common.util.archaius2.Archaius2Ext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JHiccupComponent {
@Bean
public HiccupMeter getHiccupMeter(HiccupRecorderConfiguration configuration, Registry registry) {
return new HiccupMeter(configuration, registry);
}
@Bean
public HiccupRecorderConfiguration getHiccupRecorderConfiguration(MyEnvironment environment) {
return Archaius2Ext.newConfiguration(HiccupRecorderConfiguration.class, environment);
}
}
| 1,054 |
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/jhiccup/HiccupRecorderConfiguration.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
@Configuration(prefix = "titus.jhiccup")
public interface HiccupRecorderConfiguration {
/**
* Reporting interval.
*/
@DefaultValue("1000")
long getReportingIntervalMs();
/**
* An initial delay before reporting metrics.
*/
@DefaultValue("1000")
long getStartDelayMs();
/**
* Task execution deadline, which if crossed triggers additional reporting.
*/
@DefaultValue("50")
long getTaskExecutionDeadlineMs();
}
| 1,055 |
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/jhiccup/JHiccupModule.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.netflix.archaius.ConfigProxyFactory;
/**
* Load hiccup meter.
*/
public class JHiccupModule extends AbstractModule {
@Override
protected void configure() {
bind(HiccupMeter.class).asEagerSingleton();
}
@Provides
@Singleton
public HiccupRecorderConfiguration getConfiguration(ConfigProxyFactory factory) {
return factory.newProxy(HiccupRecorderConfiguration.class);
}
}
| 1,056 |
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/jhiccup/HiccupMeter.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 java.util.Arrays;
import java.util.List;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.jhiccup.sensor.HiccupSensor;
import com.netflix.titus.common.jhiccup.sensor.JvmHiccupSensor;
import com.netflix.titus.common.jhiccup.sensor.RxJavaComputationSchedulerSensor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JVM and event pool hiccups monitoring (inspired by jHiccup from http://www.azul.com/jhiccup/).
*/
@Singleton
public class HiccupMeter {
private static final Logger logger = LoggerFactory.getLogger(HiccupMeter.class);
/*
* Store configuration in object, instead of calling HiccupRecorderConfiguration on each invocation
* which may be expensive (especially for Spring Environment).
*/
private final long reportingIntervalMs;
private final long startDelayMs;
private final HiccupMeterController controller;
private volatile boolean doRun = true;
private final List<HiccupSensor> sensors;
@Inject
public HiccupMeter(HiccupRecorderConfiguration configuration, Registry registry) {
this.reportingIntervalMs = configuration.getReportingIntervalMs();
this.startDelayMs = configuration.getStartDelayMs();
this.sensors = Arrays.asList(
new JvmHiccupSensor(configuration, registry),
new RxJavaComputationSchedulerSensor(configuration, registry)
);
this.controller = new HiccupMeterController();
this.controller.start();
}
@PreDestroy
public void shutdown() {
doRun = false;
sensors.forEach(HiccupSensor::shutdown);
if (controller.isAlive()) {
try {
controller.join();
} catch (InterruptedException e) {
logger.warn("HiccupMeter terminate/join interrupted");
}
}
}
class HiccupMeterController extends Thread {
HiccupMeterController() {
this.setName("jhiccup");
this.setDaemon(true);
}
@Override
public void run() {
try {
// Warmup
if (startDelayMs > 0) {
Thread.sleep(startDelayMs);
}
// Main loop
runLoop();
} catch (InterruptedException e) {
logger.warn("HiccupMeter terminating...");
}
sensors.forEach(HiccupSensor::shutdown);
}
private void runLoop() throws InterruptedException {
sensors.forEach(HiccupSensor::reset);
long now = System.currentTimeMillis();
long nextReportingTime = now + reportingIntervalMs;
while (doRun) {
waitTillNextReporting(nextReportingTime);
sensors.forEach(HiccupSensor::report);
nextReportingTime += reportingIntervalMs;
}
}
private void waitTillNextReporting(long nextReportingTime) throws InterruptedException {
long now = System.currentTimeMillis();
if (now < nextReportingTime) {
Thread.sleep(nextReportingTime - now);
}
}
}
}
| 1,057 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup/sensor/HiccupSensorMetrics.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.spectator.api.Registry;
import org.HdrHistogram.Histogram;
class HiccupSensorMetrics {
private static final double[] RECORDED_PERCENTILES = {90.0, 95.0, 99.0, 99.5, 99.95, 99.995};
private final String name;
private final Map<String, String> tags;
private final Registry registry;
private final ConcurrentMap<Double, AtomicLong> hiccupMetrics = new ConcurrentHashMap<>();
HiccupSensorMetrics(String name, Registry registry) {
this(name, Collections.emptyMap(), registry);
}
HiccupSensorMetrics(String name, Map<String, String> tags, Registry registry) {
this.name = name;
this.tags = tags;
this.registry = registry;
}
void updateMetrics(Histogram intervalHistogram) {
for (double percentile : RECORDED_PERCENTILES) {
AtomicLong metric = hiccupMetrics.get(percentile);
if (metric == null) {
metric = new AtomicLong();
Map<String, String> myTags = new HashMap<>(tags);
myTags.put("percentile", Double.toString(percentile));
registry.gauge(registry.createId(name + ".histogram", myTags), metric);
hiccupMetrics.put(percentile, metric);
}
long value = intervalHistogram.getValueAtPercentile(percentile);
metric.set(TimeUnit.NANOSECONDS.toMillis(value));
}
}
}
| 1,058 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup/sensor/RxJavaComputationSchedulerSensor.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.jhiccup.HiccupRecorderConfiguration;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.SingleWriterRecorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Scheduler.Worker;
import rx.schedulers.Schedulers;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
/**
* Monitor RxJava computation event loop liveness.
*/
public class RxJavaComputationSchedulerSensor extends AbstractHiccupSensor {
private static final Logger logger = LoggerFactory.getLogger(RxJavaComputationSchedulerSensor.class);
private static final long MAX_INIT_PROCESSING_WAIT_TIME_MS = 5000;
private static final int MAX_LOOP_COUNT = 100;
private static final long DEFAULT_PROBING_INTERVAL_MS = 20;
private static final long DEFAULT_PROGRESS_CHECK_INTERVAL_MS = 20;
private static final long LOWEST_TRACKABLE_VALUE = 20000;
private static final long HIGHEST_TRACKABLE_VALUE = 3600000000000L; // 1h
private static final int NUMBER_OF_SIGNIFICANT_DIGITS = 2;
private final List<WorkerTaskScheduler> workerTaskSchedulers;
private final WorkerObserver workersObserver;
private final long probingIntervalNs;
private final long progressCheckIntervalMs;
private volatile boolean doRun = true;
@VisibleForTesting
RxJavaComputationSchedulerSensor(HiccupRecorderConfiguration configuration,
long probingIntervalMs,
long progressCheckIntervalMs,
Registry registry) {
super(configuration, registry);
this.probingIntervalNs = TimeUnit.MILLISECONDS.toNanos(probingIntervalMs);
this.progressCheckIntervalMs = progressCheckIntervalMs;
this.workerTaskSchedulers = findComputationSchedulerWorkers();
this.workersObserver = new WorkerObserver();
workersObserver.start();
}
public RxJavaComputationSchedulerSensor(HiccupRecorderConfiguration configuration, Registry registry) {
this(configuration, DEFAULT_PROBING_INTERVAL_MS, DEFAULT_PROGRESS_CHECK_INTERVAL_MS, registry);
}
@Override
public void reset() {
workerTaskSchedulers.forEach(WorkerTaskScheduler::reset);
}
@Override
public void shutdown() {
if (doRun) {
doRun = false;
try {
workersObserver.interrupt();
workersObserver.join();
} catch (InterruptedException ignore) {
}
workerTaskSchedulers.forEach(WorkerTaskScheduler::shutdown);
}
}
public void report() {
workerTaskSchedulers.forEach(WorkerTaskScheduler::report);
}
protected void reportBlockedThread(Thread blockedThread) {
List<StackTraceElement> blockedStackTrace = asList(blockedThread.getStackTrace());
// If JVM has a pause (for example due to GC) we may observe long delay, even if the computation queue is empty.
// We cannot solve this problem for all cases, but we do not report blocked thread here if we observe that
// computation thread is parked in executor pool.
boolean free = blockedStackTrace.get(0).getMethodName().equals("park");
for (int i = 1; free && i < blockedStackTrace.size(); i++) {
free = blockedStackTrace.get(i).getClassName().startsWith("java.");
}
if (!free) {
logger.warn("Rx computation scheduler thread {} blocked by long running task: {}", blockedThread.getName(), blockedStackTrace);
}
}
@VisibleForTesting
Map<String, Long> getLastPercentile(double percentile) {
Map<String, Long> result = new HashMap<>();
workerTaskSchedulers.forEach(w -> {
result.put(w.getThreadName(), (long) w.report(percentile));
});
return result;
}
private List<WorkerTaskScheduler> findComputationSchedulerWorkers() {
List<WorkerTaskScheduler> workerTaskSchedulers = new ArrayList<>();
try {
int cpuCount = Runtime.getRuntime().availableProcessors();
Set<Thread> threads = new HashSet<>();
int iterCount = 0;
while (workerTaskSchedulers.size() < cpuCount && iterCount < MAX_LOOP_COUNT) {
iterCount++;
Worker worker = Schedulers.computation().createWorker();
AtomicReference<Thread> workerThreadRef = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
worker.schedule(() -> {
workerThreadRef.set(Thread.currentThread());
latch.countDown();
});
if (!latch.await(MAX_INIT_PROCESSING_WAIT_TIME_MS, TimeUnit.MILLISECONDS)) {
logger.warn("RxJava computation scheduler sensor initialization error");
return Collections.emptyList();
}
if (threads.add(workerThreadRef.get())) {
workerTaskSchedulers.add(new WorkerTaskScheduler(workerThreadRef.get(), worker));
} else {
worker.unsubscribe();
}
}
return workerTaskSchedulers;
} catch (Exception e) {
logger.warn("RxJava computation scheduler sensor initialization error", e);
workerTaskSchedulers.forEach(WorkerTaskScheduler::shutdown);
return Collections.emptyList();
}
}
/**
* Test task runner on a single Rx computation thread.
*/
private class WorkerTaskScheduler {
private final Worker worker;
private final SingleWriterRecorder recorder;
private final Thread workerThread;
private volatile Histogram lastReturnedHistogram;
private volatile long pendingTaskStartTimeNs;
private final HiccupSensorMetrics metrics;
private long shortestObservedDeltaNs = Long.MAX_VALUE;
WorkerTaskScheduler(Thread workerThread, Worker worker) {
this.worker = worker;
this.workerThread = workerThread;
this.metrics = new HiccupSensorMetrics("titus.hiccup.computationScheduler", singletonMap("thread", workerThread.getName()), registry);
this.recorder = new SingleWriterRecorder(LOWEST_TRACKABLE_VALUE, HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_DIGITS);
registry.gauge(
registry.createId("titus.hiccup.computationScheduler.pendingTaskDuration", singletonMap("thread", workerThread.getName())),
0, v -> getPendingTaskRunningTime()
);
doRun();
}
String getThreadName() {
return workerThread.getName();
}
Thread getWorkerThread() {
return workerThread;
}
long getPendingTaskRunningTime() {
return TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - pendingTaskStartTimeNs - probingIntervalNs));
}
long getPendingTaskStartTimeNs() {
return pendingTaskStartTimeNs;
}
void reset() {
recorder.reset();
}
void report() {
report(99.5);
}
double report(double percentile) {
lastReturnedHistogram = recorder.getIntervalHistogram(lastReturnedHistogram);
if (lastReturnedHistogram.getTotalCount() > 0) {
metrics.updateMetrics(lastReturnedHistogram);
}
return TimeUnit.NANOSECONDS.toMillis(lastReturnedHistogram.getValueAtPercentile(percentile));
}
void shutdown() {
worker.unsubscribe();
}
private void doRun() {
pendingTaskStartTimeNs = System.nanoTime();
worker.schedule(() -> {
long deltaNs = System.nanoTime() - pendingTaskStartTimeNs;
shortestObservedDeltaNs = Math.min(shortestObservedDeltaNs, deltaNs);
long hiccupNs = deltaNs - shortestObservedDeltaNs;
try {
recorder.recordValueWithExpectedInterval(hiccupNs, probingIntervalNs);
} catch (Exception e) {
logger.warn("Could not update histogram of RxComputation thread {}: {}", workerThread.getName(), e.getMessage());
}
doRun();
}, probingIntervalNs, TimeUnit.NANOSECONDS);
}
}
/**
* This thread observes progress of work on the individual Rx compute threads, to detect event loop halts.
*/
private class WorkerObserver extends Thread {
private final Map<WorkerTaskScheduler, Long> blockedTasks = new ConcurrentHashMap<>();
WorkerObserver() {
super("rxHiccupSensor");
this.setDaemon(true);
}
@Override
public void run() {
try {
while (doRun) {
checkProgress();
try {
Thread.sleep(progressCheckIntervalMs);
} catch (InterruptedException ignore) {
}
}
} finally {
logger.info("Leaving WorkerObserver execution loop");
}
}
private void checkProgress() {
workerTaskSchedulers.forEach(ts -> {
long taskRunningTime = ts.getPendingTaskRunningTime();
if (taskRunningTime > taskExecutionDeadlineMs) {
Long lastReport = blockedTasks.get(ts);
long pendingTaskStartTimeNs = ts.getPendingTaskStartTimeNs();
if (lastReport == null || lastReport != pendingTaskStartTimeNs) {
blockedTasks.put(ts, pendingTaskStartTimeNs);
reportBlockedThread(ts.getWorkerThread());
}
}
});
}
}
}
| 1,059 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup/sensor/JvmHiccupSensor.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.concurrent.TimeUnit;
import com.netflix.spectator.api.Registry;
import com.netflix.titus.common.jhiccup.HiccupRecorderConfiguration;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.SingleWriterRecorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JVM hiccup monitor.
*/
public class JvmHiccupSensor extends AbstractHiccupSensor implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(JvmHiccupSensor.class);
private static final long LOWEST_TRACKABLE_VALUE = 20000;
private static final long HIGHEST_TRACKABLE_VALUE = 3600000000000L; // 1h
private static final int NUMBER_OF_SIGNIFICANT_DIGITS = 2;
private static final long SAMPLING_RESOLUTION_NS = 1000_000;
private final SingleWriterRecorder recorder;
private final Thread executor;
private final HiccupSensorMetrics metrics;
private volatile boolean doRun = true;
private volatile Histogram lastReturnedHistogram;
public volatile String nonOptimizableRef; // public volatile so it is not optimized away
public JvmHiccupSensor(HiccupRecorderConfiguration configuration, Registry registry) {
super(configuration, registry);
this.executor = new Thread(this, "jvmHiccupSensor");
this.executor.setDaemon(true);
this.recorder = new SingleWriterRecorder(LOWEST_TRACKABLE_VALUE, HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_DIGITS);
this.metrics = new HiccupSensorMetrics("titus.hiccup.jvm", registry);
executor.start();
}
@Override
public void reset() {
recorder.reset();
}
@Override
public void report() {
lastReturnedHistogram = recorder.getIntervalHistogram(lastReturnedHistogram);
if (lastReturnedHistogram.getTotalCount() > 0) {
metrics.updateMetrics(lastReturnedHistogram);
}
}
@Override
public void shutdown() {
this.doRun = false;
try {
executor.join();
} catch (InterruptedException ignore) {
}
}
public void run() {
try {
long shortestObservedDeltaNs = Long.MAX_VALUE;
while (doRun) {
long startTime = System.nanoTime();
TimeUnit.NANOSECONDS.sleep(SAMPLING_RESOLUTION_NS);
nonOptimizableRef = Long.toString(startTime); // Force heap allocation
long deltaNs = System.nanoTime() - startTime;
shortestObservedDeltaNs = Math.min(shortestObservedDeltaNs, deltaNs);
recorder.recordValueWithExpectedInterval(deltaNs - shortestObservedDeltaNs, SAMPLING_RESOLUTION_NS);
}
} catch (InterruptedException e) {
logger.warn("JvmHiccupSensor interrupted/terminating...");
}
}
} | 1,060 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup/sensor/AbstractHiccupSensor.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 com.netflix.spectator.api.Registry;
import com.netflix.titus.common.jhiccup.HiccupRecorderConfiguration;
abstract class AbstractHiccupSensor implements HiccupSensor {
/*
* Store configuration in object, instead of calling HiccupRecorderConfiguration on each invocation
* which may be expensive (especially for Spring Environment).
*/
protected final long reportingIntervalMs;
protected final long startDelayMs;
protected final long taskExecutionDeadlineMs;
protected final Registry registry;
protected AbstractHiccupSensor(HiccupRecorderConfiguration configuration,
Registry registry) {
this.reportingIntervalMs = configuration.getReportingIntervalMs();
this.startDelayMs = configuration.getStartDelayMs();
this.taskExecutionDeadlineMs = configuration.getTaskExecutionDeadlineMs();
this.registry = registry;
}
}
| 1,061 |
0 | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup | Create_ds/titus-control-plane/titus-common/src/main/java/com/netflix/titus/common/jhiccup/sensor/HiccupSensor.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;
public interface HiccupSensor {
void shutdown();
void reset();
void report();
}
| 1,062 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model/PrimitiveValueGeneratorsTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model;
import org.junit.Test;
import static com.netflix.titus.testkit.model.PrimitiveValueGenerators.HEX_DIGITS_SET;
import static com.netflix.titus.testkit.model.PrimitiveValueGenerators.hexValues;
import static com.netflix.titus.testkit.model.PrimitiveValueGenerators.ipv4CIDRs;
import static org.assertj.core.api.Assertions.assertThat;
public class PrimitiveValueGeneratorsTest {
@Test
public void testIpv4Cdirs() throws Exception {
assertThat(ipv4CIDRs("10.0.0.0/24").limit(2).toList()).contains("10.0.0.1", "10.0.0.2");
}
@Test
public void testInternetDomains() throws Exception {
assertThat(PrimitiveValueGenerators.internetDomains().getValue()).isEqualTo("serviceA.com");
}
@Test
public void testEmailAddresses() throws Exception {
assertThat(PrimitiveValueGenerators.emailAddresses().getValue()).isEqualTo("john@serviceA.com");
}
@Test
public void testSemanticVersion() throws Exception {
assertThat(PrimitiveValueGenerators.semanticVersions(3).getValue()).isEqualTo("1.0.0");
}
@Test
public void testHexValues() throws Exception {
char[] hexValue = hexValues(16).toList(1).get(0).toCharArray();
for (char c : hexValue) {
assertThat(HEX_DIGITS_SET.contains(c)).isTrue();
}
}
} | 1,063 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model/job/JobDescriptorGeneratorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.List;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
*/
public class JobDescriptorGeneratorTest {
@Test
public void testJobDescriptor() throws Exception {
List<JobDescriptor<BatchJobExt>> all = JobDescriptorGenerator.batchJobDescriptors().limit(10).toList();
assertThat(all).hasSize(10);
}
} | 1,064 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model/job/ContainersGeneratorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.List;
import com.netflix.titus.api.jobmanager.model.job.Container;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ContainersGeneratorTest {
@Test
public void testContainerCreation() throws Exception {
List<Container> all = ContainersGenerator.containers().loop().random().limit(10).toList();
assertThat(all).hasSize(10);
}
} | 1,065 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/model/job/JobGeneratorTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
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 JobGeneratorTest {
@Test
public void testJobIdGeneration() throws Exception {
List<String> jobIds = JobGenerator.jobIds(DataGenerator.range(1)).limit(2).toList();
assertThat(jobIds.get(0)).endsWith("Job#00000001");
assertThat(jobIds.get(1)).endsWith("Job#00000002");
}
@Test
public void testTaskIdGeneration() throws Exception {
List<String> jobIds = JobGenerator.taskIds(JobGenerator.jobIds().getValue(), DataGenerator.range(1)).limit(2).toList();
assertThat(jobIds.get(0)).endsWith("Job#00000001-Task#000000001");
assertThat(jobIds.get(1)).endsWith("Job#00000001-Task#000000002");
}
} | 1,066 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded/EmbeddedTitusCellTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.embedded;
import java.util.Arrays;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.testkit.embedded.cell.EmbeddedTitusCell;
import com.netflix.titus.testkit.embedded.cell.EmbeddedTitusCells;
import com.netflix.titus.testkit.junit.category.IntegrationTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
@Category(IntegrationTest.class)
public class EmbeddedTitusCellTest {
private static final Logger logger = LoggerFactory.getLogger(EmbeddedTitusCellTest.class);
private static final String[] OK_THREAD_GROUPS = {
"system"
};
private static final String[] OK_THREADS = {
// Java
"Timer.*",
// RxJava
"RxComputationScheduler.*",
"RxIoScheduler.*",
"RxNewThreadScheduler.*",
"RxScheduledExecutorPool.*",
// Netty
"globalEventExecutor.*",
"threadDeathWatcher.*",
// RxNetty
"rxnetty-nio-eventloop.*",
"global-client-idle-conn-cleanup-scheduler.*",
// Grpc
"grpc-shared-destroyer.*",
"grpc-default-boss.*",
// Governator
// It is shutting down shortly after injector is stopped, which causes test flakiness
"lifecycle-listener-monitor.*",
//Spectator TODO should this be here?
"spectator.*"
};
@Test
@Ignore
public void testShutdownCleanup() {
Set<Thread> threadsBefore = Thread.getAllStackTraces().keySet();
EmbeddedTitusCell titusStack = EmbeddedTitusCells.basicKubeCell(1);
titusStack.boot();
titusStack.shutdown();
Set<Thread> threadsAfter = Thread.getAllStackTraces().keySet();
// Filter-out non Titus threads
Set<Thread> titusRemainingThreads = threadsAfter.stream()
.filter(t -> {
ThreadGroup threadGroup = t.getThreadGroup();
if (threadGroup == null) { // if thread died
return false;
}
return !matches(OK_THREAD_GROUPS, threadGroup.getName());
})
.filter(t -> !matches(OK_THREADS, t.getName()))
.collect(Collectors.toSet());
CollectionsExt.copyAndRemove(titusRemainingThreads, threadsBefore).forEach(t -> {
logger.info("Unexpected thread {}:\n{}",
t.getName(),
String.join("\n", Arrays.stream(t.getStackTrace()).map(e -> " " + e).collect(Collectors.toList()))
);
}
);
assertThat(titusRemainingThreads).isSubsetOf(threadsBefore);
}
private boolean matches(String[] patterns, String text) {
for (String pattern : patterns) {
if (Pattern.matches(pattern, text)) {
return true;
}
}
return false;
}
} | 1,067 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded/kube/EmbeddedStdKubeApiFacadeTest.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.testkit.embedded.kube;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import com.netflix.titus.testkit.embedded.kube.event.EmbeddedKubeEvent;
import io.kubernetes.client.common.KubernetesObject;
import io.kubernetes.client.informer.ResourceEventHandler;
import io.kubernetes.client.informer.SharedIndexInformer;
import io.kubernetes.client.openapi.models.V1Node;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodStatus;
import org.junit.Test;
import static com.netflix.titus.testkit.embedded.kube.EmbeddedKubeClusters.RESOURCE_POOL_ELASTIC;
import static org.assertj.core.api.Assertions.assertThat;
public class EmbeddedStdKubeApiFacadeTest {
private static final int DESIRED = 1;
private final EmbeddedKubeCluster embeddedKubeCluster = EmbeddedKubeClusters.basicCluster(DESIRED);
private final EmbeddedStdKubeApiFacade integrator = new EmbeddedStdKubeApiFacade(embeddedKubeCluster);
@Test
public void testPodInformer() {
V1Pod pod1 = NodeAndPodCatalog.newPod(RESOURCE_POOL_ELASTIC);
integrator.createNamespacedPod("default", pod1);
SharedIndexInformer<V1Pod> podInformer = integrator.getPodInformer();
// Snapshot
List<String> podKeys = podInformer.getIndexer().listKeys();
assertThat(podKeys).hasSize(1);
LinkedBlockingQueue<EmbeddedKubeEvent<V1Pod>> eventQueue = eventCollector(podInformer);
List<EmbeddedKubeEvent<V1Pod>> snapshot = drain(eventQueue);
assertThat(snapshot).hasSize(1);
// Add
V1Pod addedPod = NodeAndPodCatalog.newPod(RESOURCE_POOL_ELASTIC);
integrator.createNamespacedPod("default", addedPod);
EmbeddedKubeEvent<V1Pod> addedEvent = nextEvent(eventQueue, EmbeddedKubeEvent.Kind.ADDED);
assertThat(addedEvent.getCurrent()).isEqualTo(addedPod);
// Update
V1Pod updatedPod = EmbeddedKubeUtil.copy(addedPod).status(new V1PodStatus().message("updated"));
embeddedKubeCluster.updatePod(updatedPod);
EmbeddedKubeEvent<V1Pod> updatedEvent = nextEvent(eventQueue, EmbeddedKubeEvent.Kind.UPDATED);
assertThat(updatedEvent.getCurrent()).isEqualTo(updatedPod);
assertThat(updatedEvent.getPrevious()).isEqualTo(addedPod);
// Delete (do not allow pod termination)
integrator.deleteNamespacedPod("default", updatedPod.getMetadata().getName());
nextEvent(eventQueue, EmbeddedKubeEvent.Kind.UPDATED);
// Delete (allow pod termination)
embeddedKubeCluster.allowPodTermination(true);
integrator.deleteNamespacedPod("default", updatedPod.getMetadata().getName());
nextEvent(eventQueue, EmbeddedKubeEvent.Kind.DELETED);
}
@Test
public void testNodeInformer() {
SharedIndexInformer<V1Node> nodeInformer = integrator.getNodeInformer();
// Snapshot
List<String> nodeKeys = nodeInformer.getIndexer().listKeys();
assertThat(nodeKeys).hasSize(3 * DESIRED);
LinkedBlockingQueue<EmbeddedKubeEvent<V1Node>> eventQueue = eventCollector(nodeInformer);
List<EmbeddedKubeEvent<V1Node>> snapshot = drain(eventQueue);
assertThat(snapshot).hasSize(3 * DESIRED);
// Add
EmbeddedKubeNode addedNode = embeddedKubeCluster.addNodeToServerGroup(EmbeddedKubeClusters.SERVER_GROUP_CRITICAL);
EmbeddedKubeEvent<V1Node> addedEvent = nextEvent(eventQueue, EmbeddedKubeEvent.Kind.ADDED);
assertThat(addedEvent.getCurrent()).isEqualTo(addedNode.getV1Node());
// Update
EmbeddedKubeNode updatedNode = embeddedKubeCluster.addNode(addedNode.toBuilder().withIpAddress("1.1.1.1").build());
EmbeddedKubeEvent<V1Node> updatedEvent = nextEvent(eventQueue, EmbeddedKubeEvent.Kind.UPDATED);
assertThat(updatedEvent.getCurrent()).isEqualTo(updatedNode.getV1Node());
assertThat(updatedEvent.getPrevious()).isEqualTo(addedNode.getV1Node());
// Delete
assertThat(embeddedKubeCluster.deleteNode(updatedNode.getName())).isTrue();
EmbeddedKubeEvent<V1Node> deletedEvent = nextEvent(eventQueue, EmbeddedKubeEvent.Kind.DELETED);
assertThat(deletedEvent.getCurrent()).isEqualTo(updatedNode.getV1Node());
}
private <T extends KubernetesObject> LinkedBlockingQueue<EmbeddedKubeEvent<T>> eventCollector(SharedIndexInformer<T> nodeInformer) {
LinkedBlockingQueue<EmbeddedKubeEvent<T>> eventQueue = new LinkedBlockingQueue<>();
nodeInformer.addEventHandler(new ResourceEventHandler<T>() {
@Override
public void onAdd(T node) {
eventQueue.add(EmbeddedKubeEvent.added(node));
}
@Override
public void onUpdate(T previous, T current) {
eventQueue.add(EmbeddedKubeEvent.updated(current, previous));
}
@Override
public void onDelete(T node, boolean deletedFinalStateUnknown) {
eventQueue.add(EmbeddedKubeEvent.deleted(node));
}
});
return eventQueue;
}
private <T> EmbeddedKubeEvent<T> nextEvent(LinkedBlockingQueue<EmbeddedKubeEvent<T>> queue, EmbeddedKubeEvent.Kind kind) {
EmbeddedKubeEvent<T> event = queue.poll();
assertThat(event).isNotNull();
assertThat(event.getKind()).isEqualTo(kind);
return event;
}
private <T> List<T> drain(LinkedBlockingQueue<T> queue) {
List<T> output = new ArrayList<>();
queue.drainTo(output);
return output;
}
} | 1,068 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded/kube/EmbeddedKubeClusterTest.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.testkit.embedded.kube;
import java.util.Iterator;
import com.netflix.titus.testkit.embedded.kube.event.EmbeddedKubeEvent;
import io.kubernetes.client.openapi.models.V1Pod;
import org.junit.Test;
import static com.netflix.titus.testkit.embedded.kube.EmbeddedKubeClusters.RESOURCE_POOL_ELASTIC;
import static org.assertj.core.api.Assertions.assertThat;
public class EmbeddedKubeClusterTest {
private static final int DESIRED = 1;
private final EmbeddedKubeCluster embeddedKubeCluster = EmbeddedKubeClusters.basicCluster(DESIRED);
@Test
public void testRunPod() {
V1Pod pod1 = NodeAndPodCatalog.newPod(RESOURCE_POOL_ELASTIC);
String pod1Name = pod1.getMetadata().getName();
Iterator<EmbeddedKubeEvent<V1Pod>> podEventIt = embeddedKubeCluster.observePods().toIterable().iterator();
embeddedKubeCluster.addPod(pod1);
expectPodEvent(podEventIt, EmbeddedKubeEvent.Kind.ADDED, pod1);
// Scheduled
embeddedKubeCluster.schedule();
V1Pod pod1Scheduled = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(pod1Scheduled.getStatus().getReason()).isEqualTo("SCHEDULED");
expectPodEvent(podEventIt, EmbeddedKubeEvent.Kind.UPDATED, pod1Scheduled);
String assignedNode = pod1Scheduled.getSpec().getNodeName();
assertThat(embeddedKubeCluster.getFleet().getNodes()).containsKey(assignedNode);
// StartInitiated
embeddedKubeCluster.moveToStartInitiatedState(pod1Name);
V1Pod pod1StartInitiated = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(pod1StartInitiated.getStatus().getPodIP()).isNotNull();
expectPodEvent(podEventIt, EmbeddedKubeEvent.Kind.UPDATED, pod1StartInitiated);
// Started
embeddedKubeCluster.moveToStartedState(pod1Name);
V1Pod pod1Started = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(pod1Started.getStatus().getPhase()).isEqualTo("Running");
expectPodEvent(podEventIt, EmbeddedKubeEvent.Kind.UPDATED, pod1Started);
EmbeddedKubeNode nodeAfterStarted = embeddedKubeCluster.getFleet().getNodes().get(assignedNode);
assertThat(nodeAfterStarted.getAssignedPods()).hasSize(1);
// Finished
embeddedKubeCluster.moveToFinishedSuccess(pod1Name);
V1Pod pod1Finished = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(pod1Finished.getStatus().getPhase()).isEqualTo("Succeeded");
expectPodEvent(podEventIt, EmbeddedKubeEvent.Kind.UPDATED, pod1Finished);
EmbeddedKubeNode nodeAfterFinished = embeddedKubeCluster.getFleet().getNodes().get(assignedNode);
assertThat(nodeAfterFinished.getAssignedPods()).isEmpty();
// Remove pod
embeddedKubeCluster.removePod(pod1Name);
assertThat(embeddedKubeCluster.getPods()).doesNotContainKey(pod1Name);
}
@Test
public void testRunAndTerminatePod() {
V1Pod pod1 = NodeAndPodCatalog.newPod(RESOURCE_POOL_ELASTIC);
String pod1Name = pod1.getMetadata().getName();
embeddedKubeCluster.addPod(pod1);
embeddedKubeCluster.schedule();
embeddedKubeCluster.moveToStartInitiatedState(pod1Name);
embeddedKubeCluster.moveToStartedState(pod1Name);
embeddedKubeCluster.moveToKillInitiatedState(pod1Name, 60_000);
// Kill initiated
V1Pod podKillInitiated = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(podKillInitiated.getMetadata().getDeletionGracePeriodSeconds()).isEqualTo(60L);
assertThat(podKillInitiated.getMetadata().getDeletionTimestamp()).isNotNull();
// Finished
embeddedKubeCluster.moveToFinishedFailed(pod1Name, "failed");
V1Pod pod1Finished = embeddedKubeCluster.getPods().get(pod1Name);
assertThat(pod1Finished.getStatus().getPhase()).isEqualTo("Failed");
}
private void expectPodEvent(Iterator<EmbeddedKubeEvent<V1Pod>> eventIt, EmbeddedKubeEvent.Kind expectedKind, V1Pod expected) {
assertThat(eventIt.hasNext()).isTrue();
EmbeddedKubeEvent<V1Pod> event = eventIt.next();
assertThat(event.getKind()).isEqualTo(expectedKind);
assertThat(event.getCurrent()).isEqualTo(expected);
}
} | 1,069 |
0 | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded | Create_ds/titus-control-plane/titus-testkit/src/test/java/com/netflix/titus/testkit/embedded/kube/NodeAndPodCatalog.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.testkit.embedded.kube;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.netflix.titus.api.jobmanager.model.job.ContainerResources;
import com.netflix.titus.runtime.kubernetes.KubeConstants;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.models.V1Affinity;
import io.kubernetes.client.openapi.models.V1Container;
import io.kubernetes.client.openapi.models.V1NodeAffinity;
import io.kubernetes.client.openapi.models.V1NodeSelector;
import io.kubernetes.client.openapi.models.V1NodeSelectorRequirement;
import io.kubernetes.client.openapi.models.V1NodeSelectorTerm;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodSpec;
import io.kubernetes.client.openapi.models.V1ResourceRequirements;
import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_CPU;
import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_EPHERMERAL_STORAGE;
import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_GPU;
import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_MEMORY;
import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_NETWORK;
class NodeAndPodCatalog {
static V1Pod newPod(String resourcePool) {
ContainerResources containerResources = ContainerResources.newBuilder()
.withCpu(4)
.withMemoryMB(8192)
.withDiskMB(10000)
.withNetworkMbps(256)
.build();
return new V1Pod()
.metadata(new V1ObjectMeta()
.name(UUID.randomUUID().toString())
)
.spec(new V1PodSpec()
.containers(Collections.singletonList(new V1Container()
.name("container1")
.resources(buildV1ResourceRequirements(containerResources))
))
.affinity(new V1Affinity()
.nodeAffinity(new V1NodeAffinity().requiredDuringSchedulingIgnoredDuringExecution(
new V1NodeSelector().nodeSelectorTerms(Collections.singletonList(
new V1NodeSelectorTerm().matchExpressions(Collections.singletonList(
new V1NodeSelectorRequirement()
.key(KubeConstants.NODE_LABEL_RESOURCE_POOL)
.values(Collections.singletonList(resourcePool))
))
))
)
)
)
);
}
static V1ResourceRequirements buildV1ResourceRequirements(ContainerResources containerResources) {
Map<String, Quantity> requests = new HashMap<>();
Map<String, Quantity> limits = new HashMap<>();
requests.put(RESOURCE_CPU, new Quantity(String.valueOf(containerResources.getCpu())));
limits.put(RESOURCE_CPU, new Quantity(String.valueOf(containerResources.getCpu())));
requests.put(RESOURCE_GPU, new Quantity(String.valueOf(containerResources.getGpu())));
limits.put(RESOURCE_GPU, new Quantity(String.valueOf(containerResources.getGpu())));
Quantity memory = new Quantity(containerResources.getMemoryMB() + "Mi");
Quantity disk = new Quantity(containerResources.getDiskMB() + "Mi");
Quantity network = new Quantity(containerResources.getNetworkMbps() + "M");
requests.put(RESOURCE_MEMORY, memory);
limits.put(RESOURCE_MEMORY, memory);
requests.put(RESOURCE_EPHERMERAL_STORAGE, disk);
limits.put(RESOURCE_EPHERMERAL_STORAGE, disk);
requests.put(RESOURCE_NETWORK, network);
limits.put(RESOURCE_NETWORK, network);
return new V1ResourceRequirements().requests(requests).limits(limits);
}
}
| 1,070 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/util | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/util/cli/CommandLineBuilder.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.util.cli;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CommandLineBuilder {
private final Options options = new Options();
private final Map<String, Object> defaults = new HashMap<>();
public CommandLineBuilder withHostAndPortOption(String target) {
options.addOption(Option.builder("H").longOpt("host").argName("host_name").hasArg()
.desc(String.format("%s host name", target))
.build());
options.addOption(Option.builder("p").longOpt("port").argName("port_number").hasArg().type(Number.class)
.desc(String.format("%s port number", target))
.build());
return this;
}
public CommandLineBuilder withHostAndPortOption(String target, String defaultHost, int defaultPort) {
options.addOption(Option.builder("H").longOpt("host").argName("host_name").hasArg()
.desc(String.format("%s host name (default %s)", target, defaultHost))
.build());
options.addOption(Option.builder("p").longOpt("port").argName("port_number").hasArg().type(Number.class)
.desc(String.format("%s port number (default %s)", target, defaultPort))
.build());
defaults.put("H", defaultHost);
defaults.put("p", defaultPort);
return this;
}
public CommandLineBuilder withOption(Option option) {
this.options.addOption(option);
return this;
}
public CommandLineFacade build(String[] args) {
if(hasHelpOption(args)) {
return new CommandLineFacade(options);
}
CommandLineParser parser = new DefaultParser();
try {
return new CommandLineFacade(options, parser.parse(options, args), defaults, hasHelpOption(args));
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public static CommandLineBuilder newApacheCli() {
return new CommandLineBuilder();
}
private static boolean hasHelpOption(String[] args) {
for (String arg : args) {
if (arg.equals("-h") || arg.equals("--help")) {
return true;
}
}
return false;
}
}
| 1,071 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/util | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/util/cli/CommandLineFacade.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.util.cli;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CommandLineFacade {
private final Options options;
private final CommandLine apacheCli;
private final Map<String, Object> defaults;
private final boolean includesHelpOption;
CommandLineFacade(Options options, CommandLine apacheCli, Map<String, Object> defaults, boolean helpOption) {
this.options = options;
this.apacheCli = apacheCli;
this.defaults = defaults;
this.includesHelpOption = helpOption;
}
CommandLineFacade(Options options) {
this.options = options;
this.apacheCli = null;
this.defaults = Collections.emptyMap();
this.includesHelpOption = true;
}
public boolean hasHelpOption() {
return includesHelpOption;
}
public String getString(String optionName) {
String value = apacheCli.getOptionValue(optionName);
if (value == null && defaults.get(optionName) != null) {
return defaults.get(optionName).toString();
}
return value;
}
public int getInt(String optionName) {
Object value;
try {
value = apacheCli.getParsedOptionValue(optionName);
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
if (value == null) {
return (int) defaults.get(optionName);
}
long longValue = (long) value;
return (int) longValue;
}
public boolean isEnabled(String optionName) {
return apacheCli.hasOption(optionName);
}
public void printHelp(String application) {
PrintWriter writer = new PrintWriter(System.out);
HelpFormatter formatter = new HelpFormatter();
writer.println(String.format("Usage: %s [params]", application));
writer.println();
writer.println("Options");
formatter.printOptions(writer, 128, options, 4, 4);
writer.println();
writer.flush();
}
}
| 1,072 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/grpc/TestStreamObserver.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.grpc;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.google.rpc.BadRequest;
import com.netflix.titus.common.util.rx.ObservableExt;
import com.netflix.titus.runtime.common.grpc.GrpcClientErrorUtils;
import com.netflix.titus.runtime.endpoint.v3.grpc.ErrorResponses;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import rx.Observable;
import rx.subjects.PublishSubject;
/**
* GRPC {@link io.grpc.stub.StreamObserver} implementation for testing.
*/
public class TestStreamObserver<T> implements ClientResponseObserver<Object, T> {
private static final Object EOS_MARKER = new Object();
private final List<T> emittedItems = new CopyOnWriteArrayList<>();
private final BlockingQueue<T> availableItems = new LinkedBlockingQueue<>();
private final PublishSubject<T> eventSubject = PublishSubject.create();
private final CountDownLatch terminatedLatch = new CountDownLatch(1);
private volatile Throwable error;
private volatile RuntimeException mappedError;
private volatile boolean completed;
private ClientCallStreamObserver<T> clientCallStreamObserver;
@Override
public void onNext(T value) {
emittedItems.add(value);
availableItems.add(value);
eventSubject.onNext(value);
}
@Override
public void onError(Throwable error) {
this.error = error;
this.mappedError = exceptionMapper(error);
eventSubject.onError(error);
doFinish();
}
@Override
public void onCompleted() {
completed = true;
eventSubject.onCompleted();
doFinish();
}
public Observable<T> toObservable() {
return eventSubject.compose(ObservableExt.head(() -> emittedItems));
}
private void doFinish() {
availableItems.add((T) EOS_MARKER);
terminatedLatch.countDown();
}
public List<T> getEmittedItems() {
return new ArrayList<>(emittedItems);
}
public T getLast() throws Exception {
terminatedLatch.await();
throwIfError();
if (isTerminated() && !emittedItems.isEmpty()) {
return emittedItems.get(0);
}
throw new IllegalStateException("No item emitted by the stream");
}
public T getLast(long timout, TimeUnit timeUnit) throws InterruptedException {
terminatedLatch.await(timout, timeUnit);
return isTerminated() && !emittedItems.isEmpty() ? emittedItems.get(0) : null;
}
public T takeNext() {
T next = availableItems.poll();
if ((next == null || next == EOS_MARKER) && isTerminated()) {
throw new IllegalStateException("Stream is already closed");
}
return next;
}
public T takeNext(long timeout, TimeUnit timeUnit) throws InterruptedException, IllegalStateException {
if (isTerminated()) {
return takeNext();
}
T next = availableItems.poll(timeout, timeUnit);
if (next == EOS_MARKER) {
throwIfError();
throw new IllegalStateException("Stream is already closed");
}
return next;
}
public boolean isTerminated() {
return completed || error != null;
}
public boolean isCompleted() {
return completed;
}
public boolean hasError() {
return error != null;
}
public Throwable getError() {
Preconditions.checkState(error != null, "Error not emitted");
return error;
}
public Throwable getMappedError() {
Preconditions.checkState(error != null, "Error not emitted");
return mappedError;
}
public void awaitDone() throws InterruptedException {
terminatedLatch.await();
if (hasError()) {
throw new IllegalStateException("GRPC stream terminated with an error", error);
}
}
public void awaitDone(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (!terminatedLatch.await(timeout, timeUnit)) {
throw new IllegalStateException("GRPC request not completed in time");
}
if (hasError()) {
throw new IllegalStateException("GRPC stream terminated with an error", error);
}
}
@Override
public void beforeStart(ClientCallStreamObserver clientCallStreamObserver) {
this.clientCallStreamObserver = clientCallStreamObserver;
}
public void cancel() {
if (clientCallStreamObserver != null) {
clientCallStreamObserver.cancel("client unsubscribed", null);
}
}
private RuntimeException exceptionMapper(Throwable error) {
if (error instanceof StatusRuntimeException) {
StatusRuntimeException e = (StatusRuntimeException) error;
String errorMessage = "GRPC status " + e.getStatus() + ": " + e.getTrailers().get(ErrorResponses.KEY_TITUS_ERROR_REPORT);
Optional<BadRequest> badRequest = GrpcClientErrorUtils.getDetail(e, BadRequest.class);
if (badRequest.isPresent()) {
return new RuntimeException(errorMessage + ". Invalid field values: " + badRequest, error);
}
return new RuntimeException(errorMessage, error);
}
return new RuntimeException(error.getMessage(), error);
}
private void throwIfError() throws RuntimeException {
if (error != null) {
throw mappedError;
}
}
}
| 1,073 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/grpc/TestKitGrpcClientErrorUtils.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.grpc;
import com.google.protobuf.Any;
import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.rpc.BadRequest;
import com.google.rpc.DebugInfo;
import com.netflix.titus.runtime.common.grpc.GrpcClientErrorUtils;
import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor;
import io.grpc.Metadata;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.MetadataUtils;
import static com.netflix.titus.runtime.common.grpc.GrpcClientErrorUtils.KEY_TITUS_ERROR_REPORT;
import static com.netflix.titus.runtime.common.grpc.GrpcClientErrorUtils.X_TITUS_ERROR;
import static com.netflix.titus.runtime.common.grpc.GrpcClientErrorUtils.X_TITUS_ERROR_BIN;
/**
* Titus GRPC error replies are based on Google RPC model: https://github.com/googleapis/googleapis/tree/master/google/rpc.
* Additional error context data is encoded in HTTP2 headers. A client is not required to understand and process the error
* context, but it will provide more insight into the cause of the error.
*/
public class TestKitGrpcClientErrorUtils {
public static <STUB extends AbstractStub<STUB>> STUB attachCallHeaders(STUB client) {
Metadata metadata = new Metadata();
metadata.put(V3HeaderInterceptor.CALLER_ID_KEY, "testkitClient");
metadata.put(V3HeaderInterceptor.CALL_REASON_KEY, "test call");
metadata.put(V3HeaderInterceptor.DEBUG_KEY, "true");
return client.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));
}
public static void printDetails(StatusRuntimeException error) {
System.out.println("Error context:");
if (error.getTrailers() == null) {
System.out.println("no trailers");
return;
}
// ASCII encoded error message
String errorMessage = error.getTrailers().get(KEY_TITUS_ERROR_REPORT);
if (errorMessage == null) {
System.out.println("no context data available");
return;
}
System.out.printf("%s=%s\n", X_TITUS_ERROR, errorMessage);
// GRPC RPC 'Status'
System.out.println(X_TITUS_ERROR_BIN + ':');
GrpcClientErrorUtils.getStatus(error).getDetailsList().forEach(TestKitGrpcClientErrorUtils::print);
}
private static void print(Any any) {
Descriptors.Descriptor descriptor = any.getDescriptorForType();
Descriptors.FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url");
String typeUrl = (String) any.getField(typeUrlField);
Class type;
if (typeUrl.contains(DebugInfo.class.getSimpleName())) {
type = DebugInfo.class;
} else if (typeUrl.contains(BadRequest.class.getSimpleName())) {
type = BadRequest.class;
} else {
System.out.println("Unknown detail type " + typeUrl);
return;
}
try {
System.out.printf("Detail %s:\n", type);
System.out.println(any.unpack(type));
} catch (InvalidProtocolBufferException e) {
System.out.println("Something went wrong with detail parsing");
e.printStackTrace();
}
}
}
| 1,074 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/asserts/ContainerHealthAsserts.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.asserts;
import java.util.List;
import java.util.function.Predicate;
import com.netflix.titus.api.containerhealth.model.ContainerHealthState;
import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthEvent;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthSnapshotEvent;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthUpdateEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public final class ContainerHealthAsserts {
@SafeVarargs
public static void assertContainerHealthSnapshot(ContainerHealthEvent event, Predicate<ContainerHealthStatus>... predicates) {
assertThat(event).isInstanceOf(ContainerHealthSnapshotEvent.class);
ContainerHealthSnapshotEvent snapshotEvent = (ContainerHealthSnapshotEvent) event;
List<ContainerHealthStatus> snapshotEvents = snapshotEvent.getSnapshot();
assertThat(snapshotEvents).describedAs("Expecting %s events, but got %s", predicates.length, snapshotEvents.size()).hasSize(predicates.length);
for (int i = 0; i < snapshotEvents.size(); i++) {
if (!predicates[i].test(snapshotEvents.get(i))) {
fail("Event %s does not match its predicate: event=%s", i, snapshotEvents.get(i));
}
}
}
public static void assertContainerHealth(ContainerHealthStatus healthStatus, String expectedTaskId, ContainerHealthState expectedHealthState) {
assertThat(healthStatus.getTaskId()).isEqualTo(expectedTaskId);
assertThat(healthStatus.getState()).isEqualTo(expectedHealthState);
assertThat(healthStatus.getReason()).isNotEmpty();
}
public static void assertContainerHealthEvent(ContainerHealthEvent event, String expectedTaskId, ContainerHealthState expectedHealthState) {
assertThat(event).isInstanceOf(ContainerHealthUpdateEvent.class);
assertContainerHealth(((ContainerHealthUpdateEvent) event).getContainerHealthStatus(), expectedTaskId, expectedHealthState);
}
public static void assertContainerHealthAndEvent(ContainerHealthEvent event, ContainerHealthStatus healthStatus, String expectedTaskId, ContainerHealthState expectedHealthState) {
assertContainerHealth(healthStatus, expectedTaskId, expectedHealthState);
assertContainerHealthEvent(event, expectedTaskId, expectedHealthState);
}
}
| 1,075 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/master/TitusStackResource.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.master;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.google.common.base.Preconditions;
import com.netflix.titus.common.util.ExceptionExt;
import com.netflix.titus.testkit.embedded.EmbeddedTitusOperations;
import com.netflix.titus.testkit.embedded.cell.EmbeddedTitusCell;
import com.netflix.titus.testkit.embedded.cell.gateway.EmbeddedTitusGateway;
import com.netflix.titus.testkit.embedded.cell.master.EmbeddedTitusMaster;
import com.netflix.titus.testkit.embedded.federation.EmbeddedTitusFederation;
import com.netflix.titus.testkit.embedded.kube.EmbeddedKubeCluster;
import org.junit.rules.ExternalResource;
public class TitusStackResource extends ExternalResource {
public static String V3_ENGINE_APP_PREFIX = "v3App";
private final List<EmbeddedTitusCell> embeddedTitusCells;
private final Optional<EmbeddedTitusFederation> federation;
public TitusStackResource(EmbeddedTitusCell embeddedTitusCell, boolean federationEnabled) {
if (federationEnabled) {
this.embeddedTitusCells = Collections.singletonList(embeddedTitusCell);
this.federation = Optional.of(EmbeddedTitusFederation.aDefaultTitusFederation().withCell(".*", embeddedTitusCell).build());
} else {
this.embeddedTitusCells = Collections.singletonList(embeddedTitusCell);
this.federation = Optional.empty();
}
}
public TitusStackResource(EmbeddedTitusCell embeddedTitusCell) {
this(embeddedTitusCell, "true".equalsIgnoreCase(System.getProperty("titus.test.federation", "true")));
}
public TitusStackResource(EmbeddedTitusFederation federation) {
this.embeddedTitusCells = federation.getCells();
this.federation = Optional.of(federation);
}
@Override
public void before() {
embeddedTitusCells.forEach(EmbeddedTitusCell::boot);
federation.ifPresent(EmbeddedTitusFederation::boot);
}
@Override
public void after() {
federation.ifPresent(EmbeddedTitusFederation::shutdown);
embeddedTitusCells.forEach(EmbeddedTitusCell::shutdown);
}
public EmbeddedTitusMaster getMaster() {
Preconditions.checkState(embeddedTitusCells.size() == 1, "Multiple TitusMasters");
return embeddedTitusCells.get(0).getMaster();
}
public EmbeddedTitusGateway getGateway() {
Preconditions.checkState(embeddedTitusCells.size() == 1, "Multiple TitusGateways");
return embeddedTitusCells.get(0).getGateway();
}
public EmbeddedTitusOperations getOperations() {
return federation.map(EmbeddedTitusFederation::getTitusOperations).orElse(embeddedTitusCells.get(0).getTitusOperations());
}
public EmbeddedKubeCluster getEmbeddedKubeCluster(int cellIdx) {
return embeddedTitusCells.get(cellIdx).getEmbeddedKubeCluster();
}
}
| 1,076 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/master/TitusMasterResource.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.master;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import com.netflix.titus.testkit.embedded.cell.EmbeddedCellTitusOperations;
import com.netflix.titus.testkit.embedded.EmbeddedTitusOperations;
import com.netflix.titus.testkit.embedded.cell.master.EmbeddedTitusMaster;
import org.junit.rules.ExternalResource;
/**
* Run TitusMaster server with mocked external integrations (Kubernetes, storage).
*/
public class TitusMasterResource extends ExternalResource {
private final EmbeddedTitusMaster embeddedTitusMaster;
public TitusMasterResource(EmbeddedTitusMaster embeddedTitusMaster) {
this.embeddedTitusMaster = embeddedTitusMaster;
}
@Override
public void before() throws Throwable {
embeddedTitusMaster.boot();
}
@Override
public void after() {
Stopwatch timer = Stopwatch.createStarted();
embeddedTitusMaster.shutdown();
System.out.println("Execution time: " + timer.elapsed(TimeUnit.MILLISECONDS));
}
public EmbeddedTitusMaster getMaster() {
return embeddedTitusMaster;
}
public EmbeddedTitusOperations getOperations() {
return new EmbeddedCellTitusOperations(embeddedTitusMaster);
}
}
| 1,077 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/resource/CloseableExternalResource.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.resource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.junit.rules.ExternalResource;
public class CloseableExternalResource extends ExternalResource {
private final List<Runnable> autoCloseActions = new ArrayList<>();
@Override
protected void after() {
autoCloseActions.forEach(a -> {
try {
a.run();
} catch (Exception ignore) {
}
});
super.after();
}
public <T> T autoCloseable(T value, Consumer<T> shutdownHook) {
autoCloseActions.add(() -> shutdownHook.accept(value));
return value;
}
}
| 1,078 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/resource/Log4jExternalResource.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.rules.ExternalResource;
public class Log4jExternalResource extends ExternalResource {
private final List<Logger> loggers = new ArrayList<>();
private final List<Level> levels = new ArrayList<>();
private Log4jExternalResource(List<String> categories) {
categories.forEach(c -> {
Logger logger = Logger.getLogger(c);
loggers.add(logger);
levels.add(logger.getLevel());
});
}
@Override
protected void before() throws Throwable {
loggers.forEach(l -> l.setLevel(Level.DEBUG));
}
@Override
protected void after() {
for (int i = 0; i < loggers.size(); i++) {
loggers.get(i).setLevel(levels.get(i));
}
}
public static Log4jExternalResource enableFor(Class<?> className) {
return new Log4jExternalResource(Collections.singletonList(className.getName()));
}
}
| 1,079 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/jaxrs/JaxRsServerResource.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.junit.jaxrs;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.ws.rs.core.Application;
import com.netflix.titus.common.network.socket.UnusedSocketPortAllocator;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.rules.ExternalResource;
public class JaxRsServerResource<S> extends ExternalResource {
private final S restService;
private final List<Filter> filters;
private final List<Object> providers;
private Server server;
private ExecutorService executor;
private int port;
private String baseURI;
private JaxRsServerResource(S restService, List<Filter> filters, List<Object> providers) {
this.restService = restService;
this.filters = filters;
this.providers = providers;
}
@Override
protected void before() throws Throwable {
Application application = new Application() {
@Override
public Set<Object> getSingletons() {
Set<Object> result = new HashSet<>();
result.addAll(providers);
result.add(restService);
return result;
}
};
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
filters.forEach(filter -> context.addFilter(
new FilterHolder(filter),
"/*",
EnumSet.of(DispatcherType.REQUEST)
));
context.addServlet(new ServletHolder(new ServletContainer(application)), "/*");
this.port = UnusedSocketPortAllocator.global().allocate();
server = new Server(port);
server.setHandler(context);
baseURI = "http://localhost:" + port;
executor = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "jettyServer");
t.setDaemon(true);
return t;
});
executor.execute(() -> {
try {
server.start();
server.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
// We cannot depend on Jetty running state, hence the active polling of the REST endpoint
int responseCode = -1;
do {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(baseURI + "/badEndpoint").openConnection();
responseCode = connection.getResponseCode();
} catch (IOException ignore) {
Thread.sleep(10);
}
} while (responseCode != 404);
}
@Override
protected void after() {
if (server != null && executor != null) {
try {
server.stop();
} catch (Exception ignore) {
}
executor.shutdownNow();
}
}
public static <S> Builder<S> newBuilder(S restService) {
return new Builder<>(restService);
}
public int getPort() {
return port;
}
public String getBaseURI() {
return baseURI;
}
public static class Builder<S> {
private final S restService;
private final List<Filter> filters = new ArrayList<>();
private final List<Object> providers = new ArrayList<>();
private Builder(S restService) {
this.restService = restService;
}
public Builder<S> withFilter(Filter filter) {
filters.add(filter);
return this;
}
public Builder<S> withProvider(Object provider) {
providers.add(provider);
return this;
}
public Builder<S> withProviders(Object... providers) {
for (Object provider : providers) {
this.providers.add(provider);
}
return this;
}
public JaxRsServerResource<S> build() {
return new JaxRsServerResource<>(restService, filters, providers);
}
}
}
| 1,080 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/junit/spring/SpringMockMvcUtil.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.testkit.junit.spring;
import java.util.Collections;
import java.util.Optional;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.api.model.callmetadata.Caller;
import com.netflix.titus.api.model.callmetadata.CallerType;
import com.netflix.titus.common.util.StringExt;
import com.netflix.titus.grpc.protogen.Page;
import com.netflix.titus.grpc.protogen.Pagination;
import com.netflix.titus.runtime.endpoint.metadata.spring.CallMetadataAuthentication;
import com.netflix.titus.runtime.endpoint.v3.rest.RestConstants;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Miscellaneous functions to use in the Spring MVC test setup.
*/
public final class SpringMockMvcUtil {
public static final CallMetadata JUNIT_REST_CALL_METADATA = CallMetadata.newBuilder()
.withCallers(Collections.singletonList(Caller.newBuilder()
.withId("junitTestCaller")
.withCallerType(CallerType.User)
.build())
)
.build();
public static final Authentication JUNIT_DELEGATE_AUTHENTICATION = new TestingAuthenticationToken("junitUser", "junitPassword");
public static final CallMetadataAuthentication JUNIT_AUTHENTICATION = new CallMetadataAuthentication(
JUNIT_REST_CALL_METADATA,
JUNIT_DELEGATE_AUTHENTICATION
);
public static final Page FIRST_PAGE_OF_1 = pageOf(1);
public static final Page NEXT_PAGE_OF_1 = pageOf(1, "testCursorPosition");
public static final Page NEXT_PAGE_OF_2 = pageOf(2, "testCursorPosition");
public static Page pageOf(int pageSize) {
return Page.newBuilder().setPageSize(pageSize).build();
}
public static Page pageOf(int pageSize, String cursor) {
return Page.newBuilder().setPageSize(pageSize).setCursor(cursor).build();
}
public static Pagination paginationOf(Page current) {
return Pagination.newBuilder()
.setCurrentPage(current)
.setTotalItems(Integer.MAX_VALUE)
.setHasMore(true)
.setCursor("testCursor")
.build();
}
public static <E extends Message> E doGet(MockMvc mockMvc, String path, Class<E> entityType) throws Exception {
return executeGet(mockMvc, newBuilder(entityType), MockMvcRequestBuilders.get(path).principal(JUNIT_AUTHENTICATION));
}
public static <E extends Message> E doPaginatedGet(MockMvc mockMvc, String path, Class<E> entityType, Page page, String... queryParameters) throws Exception {
MockHttpServletRequestBuilder requestBuilder = get(path)
.queryParam(RestConstants.PAGE_SIZE_QUERY_KEY, "" + page.getPageSize())
.principal(JUNIT_AUTHENTICATION);
for (int i = 0; i < queryParameters.length; i += 2) {
requestBuilder.queryParam(queryParameters[i], queryParameters[i + 1]);
}
if (StringExt.isNotEmpty(page.getCursor())) {
requestBuilder.queryParam(RestConstants.CURSOR_QUERY_KEY, "" + page.getCursor());
}
return executeGet(mockMvc, newBuilder(entityType), requestBuilder);
}
public static void doPost(MockMvc mockMvc, String path) throws Exception {
doPost(mockMvc, path, Optional.empty(), Optional.empty(), Optional.empty());
}
public static <B extends Message> void doPost(MockMvc mockMvc, String path, B body) throws Exception {
doPost(mockMvc, path, Optional.of(body), Optional.empty(), Optional.empty());
}
public static <B extends Message, E extends Message> E doPost(MockMvc mockMvc, String path, B body, Class<E> entityType) throws Exception {
return doPost(mockMvc, path, Optional.of(body), Optional.of(entityType), Optional.empty()).orElseThrow(() -> new IllegalStateException("Value not provided"));
}
public static <B extends Message, E extends Message> Optional<E> doPost(MockMvc mockMvc,
String path,
Optional<B> bodyOptional,
Optional<Class<E>> entityTypeOptional,
Optional<String[]> queryParametersOptional) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.principal(JUNIT_AUTHENTICATION);
if (queryParametersOptional.isPresent()) {
String[] queryParameters = queryParametersOptional.get();
for (int i = 0; i < queryParameters.length; i += 2) {
requestBuilder.queryParam(queryParameters[i], queryParameters[i + 1]);
}
}
if (bodyOptional.isPresent()) {
requestBuilder.content(JsonFormat.printer().print(bodyOptional.get()));
}
ResultActions resultActions = mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(r -> {
int status = r.getResponse().getStatus();
assertThat(status / 100 == 2).describedAs("2xx expected for POST, not: " + status).isTrue();
});
if (entityTypeOptional.isPresent()) {
resultActions.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
MvcResult mvcResult = resultActions.andReturn();
if (entityTypeOptional.isPresent()) {
Message.Builder builder = newBuilder(entityTypeOptional.get());
JsonFormat.parser().merge(mvcResult.getResponse().getContentAsString(), builder);
return Optional.of((E) builder.build());
}
return Optional.empty();
}
public static <B extends Message> void doPut(MockMvc mockMvc, String path, B body) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.put(path)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.principal(JUNIT_AUTHENTICATION)
.content(JsonFormat.printer().print(body));
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk() )
.andReturn();
}
public static void doDelete(MockMvc mockMvc, String path, String... queryParameters) throws Exception {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.delete(path)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.principal(JUNIT_AUTHENTICATION);
for (int i = 0; i < queryParameters.length; i += 2) {
requestBuilder.queryParam(queryParameters[i], queryParameters[i + 1]);
}
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
private static <E extends Message> E executeGet(MockMvc mockMvc, Message.Builder builder, MockHttpServletRequestBuilder requestBuilder) throws Exception {
MvcResult mvcResult = mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
JsonFormat.parser().merge(mvcResult.getResponse().getContentAsString(), builder);
return (E) builder.build();
}
private static <E> Message.Builder newBuilder(Class<E> entityType) {
try {
Message defaultInstance = (Message) entityType.getDeclaredMethod("getDefaultInstance").invoke(null, new Object[0]);
return defaultInstance.toBuilder();
} catch (Exception e) {
throw new IllegalStateException("Cannot create builder for type: " + entityType, e);
}
}
}
| 1,081 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/PrimitiveValueGenerators.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.NetworkExt;
import com.netflix.titus.common.util.tuple.Pair;
import static com.netflix.titus.common.data.generator.DataGenerator.concatenations;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.range;
import static com.netflix.titus.common.data.generator.DataGenerator.zip;
import static com.netflix.titus.common.util.CollectionsExt.asSet;
import static com.netflix.titus.common.util.NetworkExt.NetworkAddress;
import static com.netflix.titus.common.util.NetworkExt.parseCDIR;
/**
* Primitive value generators.
*/
public final class PrimitiveValueGenerators {
static Set<Character> HEX_DIGITS_SET = asSet(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
);
static Character[] HEX_DIGITS = HEX_DIGITS_SET.toArray(new Character[16]);
private PrimitiveValueGenerators() {
}
/**
* Generate sequence of IPv4 addresses within a given CIDR.
*/
public static DataGenerator<String> ipv4CIDRs(String cidr) {
NetworkAddress networkAddress = parseCDIR(cidr);
long networkAddressLong = networkAddress.getAddressLong() & networkAddress.getMask();
int lastAddress = 1 << networkAddress.getMaskLength();
return DataGenerator.range(1, lastAddress).map(n -> NetworkExt.toIPv4(networkAddressLong | n));
}
/**
* User names generator.
*/
public static DataGenerator<String> userNames() {
return items("john", "robert", "albert", "david", "mark");
}
/**
* Application names generator.
*/
public static DataGenerator<String> applicationNames() {
return items("titus", "spinnaker", "eureka", "properties", "cassandra");
}
/**
* Internet domain names generator.
*/
public static DataGenerator<String> internetDomains() {
return concatenations(".",
items("serviceA", "serviceB", "serviceC").loop(PrimitiveValueGenerators::appendIndex),
items("com", "net", "io")
);
}
/**
* Email addresses generator.
*/
public static DataGenerator<String> emailAddresses() {
return zip(userNames().loop(PrimitiveValueGenerators::appendIndex), internetDomains()).map(pair -> pair.getLeft() + '@' + pair.getRight());
}
/**
* Generates semantic version numbers up to a given depth.
*/
public static DataGenerator<String> semanticVersions(int depth) {
List<DataGenerator<String>> numberGenerators = new ArrayList<>();
numberGenerators.add(range(1, 10).map(n -> Long.toString(n)));
DataGenerator<String> subVersionGenerator = range(0, 10).map(n -> Long.toString(n));
for (int i = 1; i < depth; i++) {
numberGenerators.add(subVersionGenerator);
}
return concatenations(".", numberGenerators);
}
/**
* Sequences of hex-base values.
*/
public static DataGenerator<String> hexValues(int length) {
return DataGenerator.sequenceOfString(new Random(), length, random -> Pair.of(random, HEX_DIGITS[random.nextInt(16)]));
}
private static String appendIndex(String value, int idx) {
return idx == 0 ? value : value + idx;
}
}
| 1,082 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/CloudGenerators.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
/**
* Cloud data generator (IPv4 addresses, host names, server group names, etc).
*/
public final class CloudGenerators {
public static DataGenerator<String> vmIds() {
return PrimitiveValueGenerators.hexValues(8).map(v -> "i-" + v);
}
public static DataGenerator<String> serverGroupIds() {
return DataGenerator.range(1).map(idx -> "titusagent-" + idx);
}
public static DataGenerator<Pair<String, String>> ipAndHostNames() {
return PrimitiveValueGenerators.ipv4CIDRs("10.0.0.0/8").map(ip ->
Pair.of(ip, ip.replace('.', '_') + ".titus.dev")
);
}
}
| 1,083 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/relocation/RelocationServiceClientStub.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.testkit.model.relocation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.event.TaskRelocationEvent;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.grpc.protogen.TaskRelocationQuery;
import com.netflix.titus.runtime.connector.relocation.RelocationServiceClient;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class RelocationServiceClientStub implements RelocationServiceClient {
private final Map<String, TaskRelocationPlan> taskRelocationPlans = new HashMap<>();
private final DirectProcessor<TaskRelocationEvent> eventProcessor = DirectProcessor.create();
@Override
public Mono<Optional<TaskRelocationPlan>> findTaskRelocationPlan(String taskId) {
return Mono.fromCallable(() -> Optional.ofNullable(taskRelocationPlans.get(taskId)));
}
@Override
public Mono<List<TaskRelocationPlan>> findTaskRelocationPlans(Set<String> taskIds) {
return Mono.fromCallable(() -> taskIds.stream()
.filter(taskRelocationPlans::containsKey)
.map(taskRelocationPlans::get)
.collect(Collectors.toList())
);
}
@Override
public Flux<TaskRelocationEvent> events(TaskRelocationQuery query) {
return eventProcessor
.transformDeferred(ReactorExt.head(() -> {
List<TaskRelocationEvent> snapshot = taskRelocationPlans.values().stream()
.map(TaskRelocationEvent::taskRelocationPlanUpdated)
.collect(Collectors.toList());
snapshot.add(TaskRelocationEvent.newSnapshotEndEvent());
return snapshot;
}
));
}
public void addPlan(TaskRelocationPlan plan) {
taskRelocationPlans.put(plan.getTaskId(), plan);
eventProcessor.onNext(TaskRelocationEvent.taskRelocationPlanUpdated(plan));
}
public void removePlan(String taskId) {
if (taskRelocationPlans.remove(taskId) != null) {
eventProcessor.onNext(TaskRelocationEvent.taskRelocationPlanRemoved(taskId));
}
}
}
| 1,084 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/relocation/RelocationComponentStub.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.testkit.model.relocation;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.runtime.connector.relocation.RelocationServiceClient;
public class RelocationComponentStub {
private final RelocationServiceClientStub clientStub = new RelocationServiceClientStub();
private final TitusRuntime titusRuntime;
public RelocationComponentStub(TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
}
public RelocationServiceClient getClient() {
return clientStub;
}
public void addPlan(TaskRelocationPlan plan) {
clientStub.addPlan(plan);
}
public void removePlan(String taskId) {
clientStub.removePlan(taskId);
}
}
| 1,085 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/relocation/TaskRelocationPlanGenerator.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.testkit.model.relocation;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan;
import com.netflix.titus.api.relocation.model.TaskRelocationPlan.TaskRelocationReason;
import com.netflix.titus.api.relocation.model.TaskRelocationStatus;
import com.netflix.titus.api.relocation.model.TaskRelocationStatus.TaskRelocationState;
public class TaskRelocationPlanGenerator {
public static TaskRelocationPlan oneMigrationPlan() {
return TaskRelocationPlan.newBuilder()
.withTaskId("task1")
.withDecisionTime(101)
.withRelocationTime(123)
.withReason(TaskRelocationReason.TaskMigration)
.withReasonMessage("test")
.build();
}
public static TaskRelocationStatus oneSuccessfulRelocation() {
return TaskRelocationStatus.newBuilder()
.withTaskId("task1")
.withState(TaskRelocationState.Success)
.withStatusCode(TaskRelocationStatus.STATUS_CODE_TERMINATED)
.withStatusMessage("Successfully terminated")
.withTaskRelocationPlan(oneMigrationPlan())
.build();
}
}
| 1,086 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/NoOpGrpcObjectsCache.java | package com.netflix.titus.testkit.model.job;
import com.netflix.titus.grpc.protogen.Job;
import com.netflix.titus.grpc.protogen.Task;
import com.netflix.titus.runtime.endpoint.common.EmptyLogStorageInfo;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcObjectsCache;
public class NoOpGrpcObjectsCache implements GrpcObjectsCache {
@Override
public Job getJob(com.netflix.titus.api.jobmanager.model.job.Job<?> coreJob) {
return GrpcJobManagementModelConverters.toGrpcJob(coreJob);
}
@Override
public Task getTask(com.netflix.titus.api.jobmanager.model.job.Task coreTask) {
return GrpcJobManagementModelConverters.toGrpcTask(coreTask, EmptyLogStorageInfo.empty());
}
}
| 1,087 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobComponentStub.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import com.netflix.titus.api.containerhealth.model.ContainerHealthState;
import com.netflix.titus.api.containerhealth.service.ContainerHealthService;
import com.netflix.titus.api.jobmanager.TaskAttributes;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.TaskStatus;
import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt;
import com.netflix.titus.api.jobmanager.service.V3JobOperations;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.data.generator.MutableDataGenerator;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.grpc.protogen.JobChangeNotification;
import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters;
import rx.Observable;
public class JobComponentStub {
private static final JobChangeNotification GRPC_SNAPSHOT_MARKER = JobChangeNotification.newBuilder()
.setSnapshotEnd(JobChangeNotification.SnapshotEnd.getDefaultInstance())
.build();
private final Clock clock;
private final StubbedJobData stubbedJobData;
private final StubbedJobOperations stubbedJobOperations;
private final ContainerHealthService stubbedContainerHealthService;
private final MutableDataGenerator<Job> jobGenerator;
private final Map<String, MutableDataGenerator<JobDescriptor>> jobTemplates = new HashMap<>();
private boolean connectionDelay;
public JobComponentStub(TitusRuntime titusRuntime) {
this.stubbedJobData = new StubbedJobData(titusRuntime);
this.stubbedJobOperations = new StubbedJobOperations(stubbedJobData);
this.stubbedContainerHealthService = new StubbedContainerHealthService(stubbedJobData);
this.jobGenerator = new MutableDataGenerator<>(JobGenerator.jobs(titusRuntime.getClock()));
this.clock = titusRuntime.getClock();
}
public V3JobOperations getJobOperations() {
return stubbedJobOperations;
}
public ContainerHealthService getContainerHealthService() {
return stubbedContainerHealthService;
}
public JobComponentStub addJobTemplate(String templateId, DataGenerator<JobDescriptor> jobDescriptorGenerator) {
jobTemplates.put(templateId, new MutableDataGenerator<>(jobDescriptorGenerator));
return this;
}
public JobComponentStub addBatchTemplate(String templateId, DataGenerator<JobDescriptor<BatchJobExt>> jobDescriptorGenerator) {
return addJobTemplate(templateId, (DataGenerator) jobDescriptorGenerator);
}
public JobComponentStub addServiceTemplate(String templateId, DataGenerator<JobDescriptor<ServiceJobExt>> jobDescriptorGenerator) {
return addJobTemplate(templateId, (DataGenerator) jobDescriptorGenerator);
}
public Job createJob(String templateId) {
Job job = jobGenerator.getValue().toBuilder().withJobDescriptor(jobTemplates.get(templateId).getValue()).build();
return createJob(job);
}
public Job createJob(Job<?> job) {
stubbedJobData.addJob(job);
return job;
}
public List<Task> createDesiredTasks(Job<?> job) {
return stubbedJobData.createDesiredTasks(job);
}
public Pair<Job, List<Task>> createJobAndTasks(String templateId) {
Job job = createJob(templateId);
List<Task> tasks = createDesiredTasks(job);
return Pair.of(job, tasks);
}
public Pair<Job, List<Task>> createJobAndTasks(Job<?> job) {
createJob(job);
List<Task> tasks = createDesiredTasks(job);
return Pair.of(job, tasks);
}
public Pair<Job, List<Task>> createJobAndTasks(String templateId, BiConsumer<Job, List<Task>> processor) {
Pair<Job, List<Task>> pair = createJobAndTasks(templateId);
processor.accept(pair.getLeft(), pair.getRight());
return pair;
}
public List<Pair<Job, List<Task>>> creteMultipleJobsAndTasks(String... templateIds) {
List<Pair<Job, List<Task>>> result = new ArrayList<>();
for (String templateId : templateIds) {
result.add(createJobAndTasks(templateId));
}
return result;
}
public Job moveJobToKillInitiatedState(Job job) {
return stubbedJobData.moveJobToKillInitiatedState(job);
}
public <E extends JobDescriptor.JobDescriptorExt> Job<E> changeJob(Job<E> updatedJob) {
stubbedJobData.changeJob(updatedJob.getId(), j -> updatedJob);
return updatedJob;
}
public void addJobAttribute(String jobId, String attributeName, String attributeValue) {
stubbedJobData.changeJob(jobId, job -> {
JobDescriptor update = job.getJobDescriptor().toBuilder()
.withAttributes(CollectionsExt.copyAndAdd(job.getJobDescriptor().getAttributes(), attributeName, attributeValue))
.build();
return job.toBuilder().withJobDescriptor(update).build();
});
}
public void addTaskAttribute(String taskId, String attributeName, String attributeValue) {
stubbedJobData.changeTask(taskId, task ->
task.toBuilder()
.withAttributes(CollectionsExt.copyAndAdd(task.getAttributes(), attributeName, attributeValue))
.build()
);
}
public void changeJobEnabledStatus(Job<?> job, boolean enabled) {
stubbedJobData.changeJob(job.getId(), j -> JobFunctions.changeJobEnabledStatus(JobFunctions.asServiceJob(j), enabled));
}
public Job finishJob(Job job) {
return stubbedJobData.finishJob(job);
}
public Task moveTaskToState(String taskId, TaskState newState) {
Pair<Job<?>, Task> jobTaskPair = stubbedJobOperations.findTaskById(taskId).orElseThrow(() -> new IllegalArgumentException("Task not found: " + taskId));
return moveTaskToState(jobTaskPair.getRight(), newState);
}
public Task moveTaskToState(Task task, TaskState newState) {
return stubbedJobData.moveTaskToState(task, newState);
}
public void killTask(Task task, boolean shrink, boolean preventMinSizeUpdate, V3JobOperations.Trigger trigger) {
stubbedJobData.killTask(task.getId(), shrink, preventMinSizeUpdate, trigger);
}
public void changeContainerHealth(String taskId, ContainerHealthState healthState) {
stubbedJobData.changeContainerHealth(taskId, healthState);
}
public void place(String taskId, String agentId, String agentIpAddress) {
stubbedJobData.changeTask(taskId, task ->
task.toBuilder()
.withStatus(TaskStatus.newBuilder()
.withState(TaskState.Started)
.withReasonCode("placed")
.withReasonMessage("Task placed on agent")
.withTimestamp(clock.wallTime())
.build()
)
.addToTaskContext(TaskAttributes.TASK_ATTRIBUTES_AGENT_INSTANCE_ID, agentId)
.addToTaskContext(TaskAttributes.TASK_ATTRIBUTES_AGENT_HOST, agentIpAddress)
.build());
}
public void forget(Task task) {
stubbedJobData.removeTask(task, false);
}
public void delayConnection() {
connectionDelay = true;
}
public Observable<JobManagerEvent<?>> observeJobs(boolean snapshot) {
if (connectionDelay) {
connectionDelay = false;
return Observable.never();
}
return stubbedJobData.events(snapshot);
}
public Observable<JobChangeNotification> grpcObserveJobs(boolean snapshot) {
NoOpGrpcObjectsCache grpcObjectsCache = new NoOpGrpcObjectsCache();
return observeJobs(snapshot).map(coreEvent -> {
if (coreEvent == JobManagerEvent.snapshotMarker()) {
return GRPC_SNAPSHOT_MARKER;
}
return GrpcJobManagementModelConverters.toGrpcJobChangeNotification(coreEvent, grpcObjectsCache, clock.wallTime());
});
}
public void emitCheckpoint() {
stubbedJobData.emitCheckpoint();
}
}
| 1,088 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/StubbedContainerHealthService.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.Optional;
import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus;
import com.netflix.titus.api.containerhealth.model.event.ContainerHealthEvent;
import com.netflix.titus.api.containerhealth.service.ContainerHealthService;
import reactor.core.publisher.Flux;
class StubbedContainerHealthService implements ContainerHealthService {
private final StubbedJobData stubbedJobData;
StubbedContainerHealthService(StubbedJobData stubbedJobData) {
this.stubbedJobData = stubbedJobData;
}
@Override
public String getName() {
return "test";
}
@Override
public Optional<ContainerHealthStatus> findHealthStatus(String taskId) {
return stubbedJobData.findTask(taskId).map(task -> stubbedJobData.getTaskHealthStatus(taskId)).orElse(Optional.empty());
}
@Override
public Flux<ContainerHealthEvent> events(boolean snapshot) {
return null;
}
}
| 1,089 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import com.netflix.titus.api.jobmanager.TaskAttributes;
import com.netflix.titus.api.jobmanager.model.job.BatchJobTask;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.JobModel;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.JobStatus;
import com.netflix.titus.api.jobmanager.model.job.ServiceJobTask;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.TaskStatus;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.time.Clock;
import com.netflix.titus.common.util.time.Clocks;
import static com.netflix.titus.common.data.generator.DataGenerator.range;
import static com.netflix.titus.common.data.generator.DataGenerator.zip;
/**
*
*/
public class JobGenerator {
public static final JobDescriptor<JobDescriptor.JobDescriptorExt> EMPTY_JOB_DESCRIPTOR = JobModel.newJobDescriptor().build();
/**
* See {@link #jobIds(DataGenerator)}.
*/
public static DataGenerator<String> jobIds() {
return jobIds(range(1));
}
/**
* Generates job UUID like strings, with readable job number (for example "a35b8764-f3fa-4d55-9c1f-Job#00000001")
*/
public static DataGenerator<String> jobIds(DataGenerator<Long> numbers) {
return numbers.map(n -> String.format("%sJob#%08d", UUID.randomUUID().toString().substring(0, 24), n));
}
/**
* Generates task UUID like strings, with readable job/task numbers (for example "40df-8de3-Job#00000001-Task#000000001").
*/
public static DataGenerator<String> taskIds(String jobId, DataGenerator<Long> numbers) {
return numbers.map(n -> String.format("%s-Task#%09d", jobId, n));
}
/**
* Generates sequence of jobs with empty job descriptor.
*/
public static DataGenerator<Job> jobs() {
return jobs(Clocks.system());
}
/**
* Generates sequence of jobs with empty job descriptor.
*/
public static DataGenerator<Job> jobs(Clock clock) {
return jobIds().map(jobId ->
JobModel.newJob()
.withId(jobId)
.withStatus(JobStatus.newBuilder()
.withTimestamp(clock.wallTime())
.withState(JobState.Accepted).build()
)
.withJobDescriptor(EMPTY_JOB_DESCRIPTOR)
.build());
}
/**
* Generates a sequence of batch jobs for the given job descriptor.
*/
public static DataGenerator<Job<BatchJobExt>> batchJobs(JobDescriptor<BatchJobExt> jobDescriptor) {
return batchJobs(jobDescriptor, Clocks.system());
}
/**
* Generates a sequence of batch jobs for the given job descriptor.
*/
public static DataGenerator<Job<BatchJobExt>> batchJobs(JobDescriptor<BatchJobExt> jobDescriptor, Clock clock) {
return jobIds().map(jobId -> JobModel.<BatchJobExt>newJob()
.withId(jobId)
.withStatus(JobStatus.newBuilder()
.withTimestamp(clock.wallTime())
.withState(JobState.Accepted).build())
.withJobDescriptor(jobDescriptor)
.build());
}
public static DataGenerator<Job<BatchJobExt>> batchJobsOfSize(int size) {
return batchJobs(JobFunctions.changeBatchJobSize(JobDescriptorGenerator.oneTaskBatchJobDescriptor(), size));
}
public static DataGenerator<Job<BatchJobExt>> batchJobsOfSizeAndAttributes(int size, Map<String, String> jobAttributes) {
JobDescriptor<BatchJobExt> jobDescriptor = JobFunctions.appendJobDescriptorAttributes(
JobFunctions.changeBatchJobSize(
JobDescriptorGenerator.oneTaskBatchJobDescriptor(), size), jobAttributes);
return batchJobs(jobDescriptor);
}
/**
* Generates a sequence of service jobs for the given job descriptor.
*/
public static DataGenerator<Job<ServiceJobExt>> serviceJobs(JobDescriptor<ServiceJobExt> jobDescriptor) {
return serviceJobs(jobDescriptor, Clocks.system());
}
/**
* Generates a sequence of service jobs for the given job descriptor.
*/
public static DataGenerator<Job<ServiceJobExt>> serviceJobs(JobDescriptor<ServiceJobExt> jobDescriptor, Clock clock) {
return jobIds().map(jobId -> JobModel.<ServiceJobExt>newJob()
.withId(jobId)
.withStatus(JobStatus.newBuilder()
.withTimestamp(clock.wallTime())
.withState(JobState.Accepted).build())
.withJobDescriptor(jobDescriptor)
.build());
}
/**
* Generates a sequence of tasks for a given job.
*/
public static DataGenerator<BatchJobTask> batchTasks(Job<BatchJobExt> batchJob) {
int size = batchJob.getJobDescriptor().getExtensions().getSize();
return zip(taskIds(batchJob.getId(), range(1)), range(0, size).loop()).map(p -> {
String taskId = p.getLeft();
int taskIndex = p.getRight().intValue();
return BatchJobTask.newBuilder()
.withId(taskId)
.withOriginalId(taskId)
.withStatus(TaskStatus.newBuilder().withState(TaskState.Accepted).build())
.withJobId(batchJob.getId())
.withIndex(taskIndex)
.withTaskContext(Collections.singletonMap(TaskAttributes.TASK_ATTRIBUTES_TASK_INDEX, "" + taskIndex))
.build();
});
}
/**
* Generates a sequence of tasks for a given job.
*/
public static DataGenerator<ServiceJobTask> serviceTasks(Job<ServiceJobExt> serviceJob) {
int size = serviceJob.getJobDescriptor().getExtensions().getCapacity().getDesired();
return taskIds(serviceJob.getId(), range(1, size + 1)).map(taskId ->
ServiceJobTask.newBuilder()
.withId(taskId)
.withOriginalId(taskId)
.withStatus(TaskStatus.newBuilder().withState(TaskState.Accepted).build())
.withJobId(serviceJob.getId())
.build()
);
}
public static Job<ServiceJobExt> oneServiceJob() {
return serviceJobs(JobDescriptorGenerator.oneTaskServiceJobDescriptor()).getValue();
}
public static ServiceJobTask oneServiceTask() {
return JobGenerator.serviceTasks(oneServiceJob()).getValue();
}
public static Job<BatchJobExt> oneBatchJob() {
return batchJobs(JobDescriptorGenerator.oneTaskBatchJobDescriptor()).getValue();
}
public static BatchJobTask oneBatchTask() {
return JobGenerator.batchTasks(oneBatchJob()).getValue();
}
}
| 1,090 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobEbsVolumeGenerator.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.testkit.model.job;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.TaskAttributes;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.testkit.model.PrimitiveValueGenerators;
public class JobEbsVolumeGenerator {
private static DataGenerator<String> ebsVolumeIds() {
return PrimitiveValueGenerators.hexValues(8).map(hex -> "vol-" + hex);
}
public static DataGenerator<String> availabilityZones() {
return DataGenerator.items("us-east-1a", "us-east-1b", "us-east-1c")
.loop();
}
public static DataGenerator<EbsVolume> jobEbsVolumes(int count) {
List<String> ebsVolumeIds = ebsVolumeIds().getValues(count);
List<String> availabilityZones = availabilityZones().getValues(count);
List<EbsVolume> ebsVolumes = new ArrayList<>();
for (int i = 0; i < count; i++) {
ebsVolumes.add(EbsVolume.newBuilder()
.withVolumeId(ebsVolumeIds.get(i))
.withVolumeAvailabilityZone(availabilityZones.get(i))
.withVolumeCapacityGB(5)
.withMountPath("/ebs_mnt")
.withMountPermissions(EbsVolume.MountPerm.RW)
.withFsType("xfs")
.build());
}
return DataGenerator.items(ebsVolumes);
}
public static Map<String, String> jobEbsVolumesToAttributes(List<EbsVolume> ebsVolumes) {
Map<String, String> ebsAttributes = new HashMap<>();
String ebsVolumeIds = ebsVolumes.stream()
.map(EbsVolume::getVolumeId)
.collect(Collectors.joining(","));
ebsAttributes.put(JobAttributes.JOB_ATTRIBUTES_EBS_VOLUME_IDS, ebsVolumeIds);
ebsAttributes.put(JobAttributes.JOB_ATTRIBUTES_EBS_MOUNT_POINT, ebsVolumes.stream().findFirst().map(EbsVolume::getMountPath).orElse("/ebs_mnt"));
ebsAttributes.put(JobAttributes.JOB_ATTRIBUTES_EBS_MOUNT_PERM, ebsVolumes.stream().findFirst().map(EbsVolume::getMountPermissions).orElse(EbsVolume.MountPerm.RW).toString());
ebsAttributes.put(JobAttributes.JOB_ATTRIBUTES_EBS_FS_TYPE, ebsVolumes.stream().findFirst().map(EbsVolume::getFsType).orElse("xfs"));
return ebsAttributes;
}
public static Task appendEbsVolumeAttribute(Task task, String ebsVolumeId) {
return JobFunctions.appendTaskContext(task, TaskAttributes.TASK_ATTRIBUTES_EBS_VOLUME_ID, ebsVolumeId);
}
}
| 1,091 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/StubbedJobData.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import com.netflix.titus.api.containerhealth.model.ContainerHealthState;
import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus;
import com.netflix.titus.api.jobmanager.model.job.BatchJobTask;
import com.netflix.titus.api.jobmanager.model.job.Capacity;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.JobState;
import com.netflix.titus.api.jobmanager.model.job.JobStatus;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.api.jobmanager.model.job.TaskStatus;
import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent;
import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent;
import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt;
import com.netflix.titus.api.jobmanager.service.JobManagerException;
import com.netflix.titus.api.jobmanager.service.V3JobOperations;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.data.generator.MutableDataGenerator;
import com.netflix.titus.common.runtime.TitusRuntime;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.common.util.rx.ObservableExt;
import rx.Observable;
import rx.subjects.PublishSubject;
class StubbedJobData {
private final TitusRuntime titusRuntime;
private final ConcurrentMap<String, JobHolder> jobHoldersById = new ConcurrentHashMap<>();
private final PublishSubject<JobManagerEvent<?>> observeJobsSubject = PublishSubject.create();
private final CallMetadata callMetadata = CallMetadata.newBuilder().withCallerId("StubbedData").build();
StubbedJobData(TitusRuntime titusRuntime) {
this.titusRuntime = titusRuntime;
}
List<Job> getJobs() {
return jobHoldersById.values().stream().map(JobHolder::getJob).collect(Collectors.toList());
}
Optional<Job<?>> findJob(String jobId) {
return Optional.ofNullable(jobHoldersById.get(jobId)).map(JobHolder::getJob);
}
List<Task> getTasks() {
return jobHoldersById.values().stream().flatMap(h -> h.getTasksById().values().stream()).collect(Collectors.toList());
}
List<Task> getTasks(String jobId) {
return Optional.ofNullable(jobHoldersById.get(jobId))
.map(h -> (List<Task>) new ArrayList<>(h.getTasksById().values())
)
.orElse(Collections.emptyList());
}
Optional<Task> findTask(String taskId) {
return jobHoldersById.values().stream()
.filter(h -> h.getTasksById().containsKey(taskId))
.map(h -> h.getTasksById().get(taskId))
.findFirst();
}
Optional<ContainerHealthStatus> getTaskHealthStatus(String taskId) {
return jobHoldersById.values().stream()
.filter(h -> h.getTasksById().containsKey(taskId))
.map(h -> h.getTaskHealthStatus(taskId))
.findFirst();
}
void addJob(Job<?> job) {
jobHoldersById.put(job.getId(), new JobHolder(job));
observeJobsSubject.onNext(JobUpdateEvent.newJob(job, callMetadata));
}
String createJob(JobDescriptor<?> jobDescriptor) {
Job<?> job = Job.newBuilder()
.withId(UUID.randomUUID().toString())
.withJobDescriptor((JobDescriptor) jobDescriptor)
.withStatus(JobStatus.newBuilder()
.withState(JobState.Accepted)
.withReasonCode("created")
.withReasonMessage("Created by StubbedJobData")
.build()
)
.build();
addJob(job);
return job.getId();
}
Job<?> changeJob(String jobId, Function<Job<?>, Job<?>> transformer) {
return getJobHolderByJobId(jobId).changeJob(transformer);
}
Job moveJobToKillInitiatedState(Job job) {
return getJobHolderByJobId(job.getId()).moveJobToKillInitiatedState();
}
void killJob(String jobId) {
getJobHolderByJobId(jobId).killJob();
jobHoldersById.remove(jobId);
}
Job finishJob(Job job) {
Job removed = getJobHolderByJobId(job.getId()).finishJob();
jobHoldersById.remove(job.getId());
return removed;
}
List<Task> createDesiredTasks(Job<?> job) {
return getJobHolderByJobId(job.getId()).createDesiredTasks();
}
Task changeTask(String taskId, Function<Task, Task> transformer) {
return getJobHolderByTaskId(taskId).changeTask(taskId, transformer);
}
void changeContainerHealth(String taskId, ContainerHealthState healthState) {
getJobHolderByTaskId(taskId).changeContainerHealth(taskId, healthState);
}
Task moveTaskToState(Task task, TaskState newState) {
return getJobHolderByTaskId(task.getId()).moveTaskToState(task, V3JobOperations.Trigger.API, newState);
}
void killTask(String taskId, boolean shrink, boolean preventMinSizeUpdate, V3JobOperations.Trigger trigger) {
getJobHolderByTaskId(taskId).killTask(taskId, shrink, preventMinSizeUpdate, trigger);
}
void removeTask(Task task, boolean requireFinishedState) {
getJobHolderByTaskId(task.getId()).removeTask(task, requireFinishedState);
}
public Observable<JobManagerEvent<?>> events(boolean snapshot) {
return snapshot ? ObservableExt.fromCollection(this::getEventSnapshot).concatWith(observeJobsSubject) : observeJobsSubject;
}
public void emitCheckpoint() {
observeJobsSubject.onNext(JobManagerEvent.keepAliveEvent(System.nanoTime()));
}
private JobHolder getJobHolderByJobId(String jobId) {
JobHolder jobHolder = jobHoldersById.get(jobId);
if (jobHolder == null) {
throw JobManagerException.jobNotFound(jobId);
}
return jobHolder;
}
private JobHolder getJobHolderByTaskId(String taskId) {
return jobHoldersById.values().stream()
.filter(h -> h.getTasksById().containsKey(taskId))
.findFirst()
.orElseThrow(() -> JobManagerException.taskNotFound(taskId));
}
private Collection<JobManagerEvent<?>> getEventSnapshot() {
List<JobManagerEvent<?>> events = new ArrayList<>();
jobHoldersById.forEach((jobId, jobHolder) -> {
events.add(JobUpdateEvent.newJob(jobHolder.getJob(), callMetadata));
jobHolder.getTasksById().forEach((taskId, task) -> events.add(TaskUpdateEvent.newTask(jobHolder.getJob(), task, callMetadata)));
});
events.add(JobManagerEvent.snapshotMarker());
return events;
}
private class JobHolder {
private Job<?> job;
private final ConcurrentMap<String, Task> tasksById = new ConcurrentHashMap<>();
private final Map<String, ContainerHealthStatus> tasksHealthById = new HashMap<>();
private final MutableDataGenerator<Task> taskGenerator;
JobHolder(Job<?> job) {
this.job = job;
DataGenerator immutableTaskGenerator = JobFunctions.isServiceJob(job)
? JobGenerator.serviceTasks((Job<ServiceJobExt>) job)
: JobGenerator.batchTasks((Job<BatchJobExt>) job);
this.taskGenerator = new MutableDataGenerator<>(immutableTaskGenerator);
}
Job<?> getJob() {
return job;
}
Map<String, Task> getTasksById() {
return tasksById;
}
ContainerHealthStatus getTaskHealthStatus(String taskId) {
Task task = tasksById.get(taskId);
if (task == null) {
return ContainerHealthStatus.unknown(taskId, "not found", titusRuntime.getClock().wallTime());
}
if (task.getStatus().getState() != TaskState.Started) {
return ContainerHealthStatus.unhealthy(taskId, "not started", titusRuntime.getClock().wallTime());
}
return tasksHealthById.computeIfAbsent(taskId, tid -> ContainerHealthStatus.healthy(taskId, titusRuntime.getClock().wallTime()));
}
Job<?> changeJob(Function<Job<?>, Job<?>> transformer) {
Job<?> currentJob = job;
this.job = transformer.apply(job);
observeJobsSubject.onNext(JobUpdateEvent.jobChange(job, currentJob, callMetadata.toBuilder().withCallReason("observe jobs").build()));
return job;
}
Job moveJobToKillInitiatedState() {
Preconditions.checkState(job.getStatus().getState() == JobState.Accepted);
Job<?> currentJob = job;
this.job = job.toBuilder()
.withStatus(
JobStatus.newBuilder()
.withState(JobState.KillInitiated)
.withReasonCode("killed")
.withReasonMessage("call to moveJobToKillInitiatedState")
.withTimestamp(titusRuntime.getClock().wallTime())
.build()
).build();
observeJobsSubject.onNext(JobUpdateEvent.jobChange(job, currentJob, callMetadata.toBuilder().withCallReason("call to moveJobToKillInitiatedState").build()));
return job;
}
void killJob() {
throw new IllegalStateException("not implemented yet");
}
Job finishJob() {
Preconditions.checkState(job.getStatus().getState() == JobState.KillInitiated);
Preconditions.checkState(tasksById.isEmpty());
Job<?> currentJob = job;
this.job = currentJob.toBuilder()
.withStatus(
JobStatus.newBuilder()
.withState(JobState.Finished)
.withReasonCode("finished")
.withReasonMessage("call to finishJob")
.withTimestamp(titusRuntime.getClock().wallTime())
.build()
).build();
observeJobsSubject.onNext(JobUpdateEvent.jobChange(job, currentJob, callMetadata.toBuilder().withCallReason("Call to finish job").build()));
return job;
}
List<Task> createDesiredTasks() {
int desired = JobFunctions.getJobDesiredSize(job);
int missing = desired - tasksById.size();
List<Task> newTasks = taskGenerator.getValues(missing);
newTasks.forEach(task -> {
tasksById.put(task.getId(), task);
observeJobsSubject.onNext(TaskUpdateEvent.newTask(job, task, callMetadata.toBuilder().withCallReason("create desired tasks").build()));
});
// Now replace finished tasks with new tasks
tasksById.values().forEach(task -> {
if (task.getStatus().getState() == TaskState.Finished) {
tasksById.remove(task.getId());
Task newTask = createTaskReplacement(task);
tasksById.put(newTask.getId(), newTask);
newTasks.add(newTask);
}
});
return newTasks;
}
Task createTaskReplacement(Task task) {
Task.TaskBuilder<?, ?> taskBuilder = taskGenerator.getValue().toBuilder()
.withResubmitNumber(task.getResubmitNumber() + 1)
.withEvictionResubmitNumber(TaskStatus.hasSystemError(task) ? task.getSystemResubmitNumber() + 1 : task.getSystemResubmitNumber())
.withEvictionResubmitNumber(TaskStatus.isEvicted(task) ? task.getEvictionResubmitNumber() + 1 : task.getEvictionResubmitNumber())
.withOriginalId(task.getOriginalId())
.withResubmitOf(task.getId());
if (JobFunctions.isBatchJob(job)) {
BatchJobTask.Builder batchTaskBuilder = (BatchJobTask.Builder) taskBuilder;
batchTaskBuilder.withIndex(((BatchJobTask) task).getIndex());
}
return taskBuilder.build();
}
Task changeTask(String taskId, Function<Task, Task> transformer) {
Job<?> job = getJobHolderByTaskId(taskId).getJob();
Task currentTask = tasksById.get(taskId);
Task updatedTask = transformer.apply(currentTask);
boolean moved = currentTask != null && !currentTask.getJobId().equals(updatedTask.getJobId());
tasksById.put(updatedTask.getId(), updatedTask);
TaskUpdateEvent taskUpdateEvent;
if (moved) {
taskUpdateEvent = TaskUpdateEvent.newTaskFromAnotherJob(job, updatedTask, callMetadata);
} else if (currentTask != null) {
taskUpdateEvent = TaskUpdateEvent.taskChange(job, updatedTask, currentTask, callMetadata);
} else {
taskUpdateEvent = TaskUpdateEvent.newTask(job, updatedTask, callMetadata);
}
observeJobsSubject.onNext(taskUpdateEvent);
return updatedTask;
}
void changeContainerHealth(String taskId, ContainerHealthState healthState) {
tasksHealthById.put(taskId, ContainerHealthStatus.newBuilder()
.withTaskId(taskId)
.withState(healthState)
.withReason("On demand change")
.withTimestamp(titusRuntime.getClock().wallTime())
.build()
);
}
Task moveTaskToState(Task task, V3JobOperations.Trigger trigger, TaskState newState) {
Task currentTask = tasksById.get(task.getId());
Preconditions.checkState(currentTask != null && TaskState.isBefore(currentTask.getStatus().getState(), newState));
String reasonCode;
switch (trigger) {
case Scheduler:
reasonCode = TaskStatus.REASON_TRANSIENT_SYSTEM_ERROR;
break;
case Eviction:
case TaskMigration:
reasonCode = TaskStatus.REASON_TASK_EVICTED;
break;
case API:
case ComputeProvider:
case Reconciler:
default:
reasonCode = "test";
}
Task updatedTask = currentTask.toBuilder()
.withStatus(
TaskStatus.newBuilder()
.withState(newState)
.withReasonCode(reasonCode)
.withReasonMessage("call to moveTaskToState")
.withTimestamp(titusRuntime.getClock().wallTime())
.build()
)
.withStatusHistory(CollectionsExt.copyAndAdd(currentTask.getStatusHistory(), currentTask.getStatus()))
.build();
tasksById.put(task.getId(), updatedTask);
observeJobsSubject.onNext(TaskUpdateEvent.taskChange(job, updatedTask, currentTask, callMetadata));
return updatedTask;
}
void killTask(String taskId, boolean shrink, boolean preventMinSizeUpdate, V3JobOperations.Trigger trigger) {
Task killedTask = tasksById.get(taskId);
TaskState taskState = killedTask.getStatus().getState();
switch (taskState) {
case Accepted:
case Disconnected:
case KillInitiated:
moveTaskToState(killedTask, trigger, TaskState.Finished);
break;
case Launched:
case StartInitiated:
case Started:
moveTaskToState(killedTask, trigger, TaskState.KillInitiated);
moveTaskToState(killedTask, V3JobOperations.Trigger.ComputeProvider, TaskState.Finished);
break;
case Finished:
break;
}
killedTask = tasksById.remove(killedTask.getId());
observeJobsSubject.onNext(TaskUpdateEvent.taskChange(job, tasksById.get(taskId), killedTask, callMetadata));
if (shrink) {
if (!JobFunctions.isServiceJob(job)) {
throw JobManagerException.notServiceJob(job.getId());
}
Job<ServiceJobExt> serviceJob = (Job<ServiceJobExt>) job;
Capacity capacity = serviceJob.getJobDescriptor().getExtensions().getCapacity();
if (preventMinSizeUpdate && capacity.getDesired() <= capacity.getMin()) {
throw JobManagerException.terminateAndShrinkNotAllowed(serviceJob, killedTask);
}
tasksById.remove(taskId);
changeJob(job -> {
int desired = JobFunctions.getJobDesiredSize(job);
Capacity newCapacity = capacity.toBuilder().withDesired(desired).build();
Job<ServiceJobExt> updatedJob = JobFunctions.changeServiceJobCapacity(serviceJob, newCapacity);
return updatedJob;
});
} else {
Task newTask = createTaskReplacement(killedTask);
tasksById.put(newTask.getId(), newTask);
observeJobsSubject.onNext(TaskUpdateEvent.newTask(job, newTask, callMetadata));
}
}
void removeTask(Task task, boolean requireFinishedState) {
Task currentTask = tasksById.get(task.getId());
if (requireFinishedState) {
Preconditions.checkState(currentTask != null && currentTask.getStatus().getState() == TaskState.Finished);
}
tasksById.remove(task.getId());
}
}
}
| 1,092 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/ContainersGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.netflix.titus.api.jobmanager.model.job.Container;
import com.netflix.titus.api.jobmanager.model.job.ContainerResources;
import com.netflix.titus.api.jobmanager.model.job.Image;
import com.netflix.titus.api.jobmanager.model.job.JobModel;
import com.netflix.titus.api.jobmanager.model.job.SecurityProfile;
import com.netflix.titus.api.model.EfsMount;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.tuple.Pair;
import com.netflix.titus.common.util.tuple.Triple;
import static com.netflix.titus.common.data.generator.DataGenerator.concatenations;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.merge;
import static com.netflix.titus.common.data.generator.DataGenerator.range;
import static com.netflix.titus.common.data.generator.DataGenerator.union;
import static com.netflix.titus.common.data.generator.DataGenerator.zip;
import static com.netflix.titus.common.util.CollectionsExt.asMap;
import static com.netflix.titus.testkit.model.PrimitiveValueGenerators.hexValues;
import static com.netflix.titus.testkit.model.PrimitiveValueGenerators.semanticVersions;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
public final class ContainersGenerator {
private ContainersGenerator() {
}
public static DataGenerator<String> imageNames() {
return concatenations("/",
items("platform", "security", "applications"),
items("webUI", "backend", "database")
);
}
public static DataGenerator<String> imageTags() {
return merge(items("latest"), semanticVersions(3));
}
public static DataGenerator<String> imageDigests() {
return hexValues(32).map(hex -> "sha256:" + hex);
}
public static DataGenerator<Image> images() {
return zip(imageNames(), zip(imageTags(), imageDigests())).map(v ->
JobModel.newImage()
.withName(v.getLeft())
.withTag(v.getRight().getLeft())
//.withDigest(v.getRight().getRight()) digests not supported yet
.build()
);
}
public static DataGenerator<ContainerResources> resources() {
return union(range(1, 16), items(1, 2, 4), (cpu, ratio) ->
ContainerResources.newBuilder()
.withCpu(cpu)
.withMemoryMB((int) (cpu * ratio * 1024))
.withDiskMB((int) (cpu * ratio * 2 * 10_000))
.withNetworkMbps((int) (cpu * ratio * 128))
.withShmMB((int) (cpu * ratio * 1024 / 8))
.build()
);
}
public static DataGenerator<EfsMount> efsMounts() {
return range(1).map(id -> EfsMount.newBuilder()
.withEfsId("efs#" + id)
.withMountPerm(EfsMount.MountPerm.RW)
.withMountPoint("/data")
.withEfsRelativeMountPoint("/home/mydata")
.build()
);
}
public static DataGenerator<SecurityProfile> securityProfiles() {
return DataGenerator.union(
hexValues(8).map(sg -> "sg-" + sg).batch(2),
hexValues(8).map(iam -> "iam-" + iam),
(sgs, iam) -> SecurityProfile.newBuilder().withSecurityGroups(sgs).withIamRole(iam).build()
);
}
public static DataGenerator<Pair<Map<String, String>, Map<String, String>>> constraints() {
return DataGenerator.<Map<String, String>, Map<String, String>>zip(
items(
asMap(),
asMap("UniqueHost", "true")
),
items(
asMap(),
asMap("ZoneBalance", "true")
)
).loop();
}
private static DataGenerator<Triple<List<String>, List<String>, Map<String, String>>> executable() {
DataGenerator<Pair<List<String>, List<String>>> entryPointAndCommands = DataGenerator.zip(
items(asList("/bin/sh", "-c"), Collections.<String>emptyList()),
items(singletonList("echo 'Hello'"), Collections.<String>emptyList())
);
DataGenerator<Map<String, String>> envs = items(
asMap("ENV_A", "123"), asMap("ENV_B", "345")
);
return union(entryPointAndCommands, envs, (ec, e) -> Triple.of(ec.getLeft(), ec.getRight(), e)).loop();
}
public static DataGenerator<Container> containers() {
return DataGenerator.bindBuilder(JobModel::newContainer)
.bind(images(), Container.Builder::withImage)
.bind(resources(), Container.Builder::withContainerResources)
.bind(securityProfiles(), Container.Builder::withSecurityProfile)
.bind(constraints(), (builder, pair) -> builder
.withHardConstraints(pair.getLeft())
.withSoftConstraints(pair.getRight()))
.bind(executable(), (builder, ex) -> builder
.withEntryPoint(ex.getFirst())
.withCommand(ex.getSecond())
.withEnv(ex.getThird()))
.map(builder -> builder
.withAttributes(Collections.singletonMap("labelA", "valueA"))
.build());
}
}
| 1,093 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobIpAllocationGenerator.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.testkit.model.job;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.netflix.titus.api.jobmanager.TaskAttributes;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.vpc.IpAddressAllocation;
import com.netflix.titus.api.jobmanager.model.job.vpc.IpAddressLocation;
import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.testkit.model.PrimitiveValueGenerators;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
public final class JobIpAllocationGenerator {
private JobIpAllocationGenerator() {
}
private static DataGenerator<String> zones() { return items("zoneA", "zoneB").loop(); }
private static DataGenerator<String> subnets() { return items("subnet-1").loop(); }
private static DataGenerator<String> regions() { return items("us-east-1").loop(); }
private static DataGenerator<String> ipAddresses() {
return PrimitiveValueGenerators.ipv4CIDRs("96.96.96.1/28");
}
private static DataGenerator<IpAddressLocation> ipAddressLocations() {
return DataGenerator.union(
regions(),
subnets(),
zones(),
(region, subnet, zone) -> IpAddressLocation.newBuilder()
.withRegion(region)
.withSubnetId(subnet)
.withAvailabilityZone(zone)
.build()
);
}
public static DataGenerator<SignedIpAddressAllocation> jobIpAllocations(int count) {
List<String> ipAddressList = ipAddresses().getValues(count);
List<IpAddressLocation> ipAddressLocationList = ipAddressLocations().getValues(count);
List<SignedIpAddressAllocation> signedIpAddressAllocationList = new ArrayList<>();
for (int i = 0; i < count; i++) {
signedIpAddressAllocationList.add(SignedIpAddressAllocation.newBuilder()
.withIpAddressAllocation(IpAddressAllocation.newBuilder()
.withUuid(UUID.randomUUID().toString())
.withIpAddress(ipAddressList.get(i))
.withIpAddressLocation(ipAddressLocationList.get(i))
.build()
)
.withAuthoritativePublicKey(new byte[0])
.withHostPublicKey(new byte[0])
.withHostPublicKeySignature(new byte[0])
.withMessage(new byte[0])
.withMessageSignature(new byte[0])
.build());
}
return DataGenerator.items(signedIpAddressAllocationList);
}
public static Task appendIpAllocationAttribute(Task task, String ipAllocationId) {
return JobFunctions.appendTaskContext(task, TaskAttributes.TASK_ATTRIBUTES_IP_ALLOCATION_ID, ipAllocationId);
}
}
| 1,094 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/StubbedJobOperations.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.model.job.CapacityAttributes;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.ServiceJobProcesses;
import com.netflix.titus.api.jobmanager.model.job.Task;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget;
import com.netflix.titus.api.jobmanager.model.job.event.JobKeepAliveEvent;
import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent;
import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent;
import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent;
import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt;
import com.netflix.titus.api.jobmanager.service.V3JobOperations;
import com.netflix.titus.api.model.callmetadata.CallMetadata;
import com.netflix.titus.common.util.rx.ReactorExt;
import com.netflix.titus.common.util.tuple.Pair;
import reactor.core.publisher.Mono;
import rx.Completable;
import rx.Observable;
import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.asServiceJob;
import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.changeServiceJobCapacity;
import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.changeServiceJobProcesses;
class StubbedJobOperations implements V3JobOperations {
private final StubbedJobData stubbedJobData;
StubbedJobOperations(StubbedJobData stubbedJobData) {
this.stubbedJobData = stubbedJobData;
}
@Override
public List<Job> getJobs() {
return stubbedJobData.getJobs();
}
@Override
public Optional<Job<?>> getJob(String jobId) {
return stubbedJobData.findJob(jobId);
}
@Override
public List<Task> getTasks() {
return stubbedJobData.getTasks();
}
@Override
public List<Task> getTasks(String jobId) {
return stubbedJobData.getTasks(jobId);
}
@Override
public List<Pair<Job, List<Task>>> getJobsAndTasks() {
return getJobs().stream().map(job -> Pair.of(job, getTasks(job.getId()))).collect(Collectors.toList());
}
@Override
public List<Job<?>> findJobs(Predicate<Pair<Job<?>, List<Task>>> queryPredicate, int offset, int limit) {
List<Pair<Job<?>, List<Task>>> jobsAndTasks = (List) getJobsAndTasks();
return jobsAndTasks.stream()
.filter(queryPredicate)
.skip(offset)
.limit(limit)
.map(Pair::getLeft)
.collect(Collectors.toList());
}
@Override
public List<Pair<Job<?>, Task>> findTasks(Predicate<Pair<Job<?>, Task>> queryPredicate, int offset, int limit) {
List<Pair<Job<?>, List<Task>>> jobsAndTasks = (List) getJobsAndTasks();
return (List) jobsAndTasks.stream()
.flatMap(p -> p.getRight().stream().map(t -> (Pair) Pair.of(p.getLeft(), t)))
.filter(queryPredicate::test)
.skip(offset)
.limit(limit)
.collect(Collectors.toList());
}
@Override
public Optional<Pair<Job<?>, Task>> findTaskById(String taskId) {
return stubbedJobData
.findTask(taskId)
.flatMap(task -> stubbedJobData.findJob(task.getJobId()).map(j -> Pair.of(j, task)));
}
@Override
public Observable<JobManagerEvent<?>> observeJobs(Predicate<Pair<Job<?>, List<Task>>> jobsPredicate,
Predicate<Pair<Job<?>, Task>> tasksPredicate,
boolean withCheckpoints) {
return stubbedJobData.events(false)
.filter(event -> {
if (event instanceof JobKeepAliveEvent) {
return withCheckpoints;
}
if (event instanceof JobUpdateEvent) {
Job job = ((JobUpdateEvent) event).getCurrent();
return jobsPredicate.test(Pair.of(job, getTasks(job.getId())));
}
if (event instanceof TaskUpdateEvent) {
Task task = ((TaskUpdateEvent) event).getCurrentTask();
return stubbedJobData.findJob(task.getJobId()).map(job -> tasksPredicate.test(Pair.of(job, task))).orElse(false);
}
return false;
});
}
@Override
public Observable<JobManagerEvent<?>> observeJob(String jobId) {
return stubbedJobData.events(false)
.filter(event -> {
if (event instanceof JobUpdateEvent) {
Job job = ((JobUpdateEvent) event).getCurrent();
return job.getId().equals(jobId);
}
if (event instanceof TaskUpdateEvent) {
Task task = ((TaskUpdateEvent) event).getCurrentTask();
return task.getJobId().equals(jobId);
}
return false;
});
}
@Override
public Observable<String> createJob(JobDescriptor<?> jobDescriptor, CallMetadata callMetadata) {
return defer(() -> stubbedJobData.createJob(jobDescriptor));
}
@Override
public Observable<Void> updateJobCapacityAttributes(String jobId, CapacityAttributes capacityAttributes, CallMetadata callMetadata) {
return updateServiceJob(jobId, job -> changeServiceJobCapacity(job, capacityAttributes));
}
@Override
public Observable<Void> updateServiceJobProcesses(String jobId, ServiceJobProcesses serviceJobProcesses, CallMetadata callMetadata) {
return updateServiceJob(jobId, job -> changeServiceJobProcesses(job, serviceJobProcesses));
}
@Override
public Observable<Void> updateJobStatus(String serviceJobId, boolean enabled, CallMetadata callMetadata) {
return updateServiceJob(serviceJobId, job -> JobFunctions.changeJobEnabledStatus(job, enabled));
}
@Override
public Mono<Void> updateJobDisruptionBudget(String jobId, DisruptionBudget disruptionBudget, CallMetadata callMetadata) {
Observable<Void> observableAction = defer(() -> {
stubbedJobData.changeJob(jobId, job -> JobFunctions.changeDisruptionBudget(job, disruptionBudget));
});
return ReactorExt.toMono(observableAction);
}
@Override
public Mono<Void> updateJobAttributes(String jobId, Map<String, String> attributes, CallMetadata callMetadata) {
Observable<Void> observableAction = defer(() -> {
stubbedJobData.changeJob(jobId, job -> JobFunctions.updateJobAttributes(job, attributes));
});
return ReactorExt.toMono(observableAction);
}
@Override
public Mono<Void> deleteJobAttributes(String jobId, Set<String> keys, CallMetadata callMetadata) {
Observable<Void> observableAction = defer(() -> {
stubbedJobData.changeJob(jobId, job -> JobFunctions.deleteJobAttributes(job, keys));
});
return ReactorExt.toMono(observableAction);
}
private Observable<Void> updateServiceJob(String jobId, Function<Job<ServiceJobExt>, Job<ServiceJobExt>> transformer) {
return defer(() -> {
stubbedJobData.changeJob(jobId, job -> transformer.apply(asServiceJob(job)));
});
}
@Override
public Observable<Void> killJob(String jobId, String reason, CallMetadata callMetadata) {
return defer(() -> stubbedJobData.killJob(jobId));
}
@Override
public Mono<Void> killTask(String taskId, boolean shrink, boolean preventMinSizeUpdate, Trigger trigger, CallMetadata callMetadata) {
return ReactorExt.toMono(defer(() -> stubbedJobData.killTask(taskId, shrink, preventMinSizeUpdate, trigger)));
}
@Override
public Observable<Void> moveServiceTask(String sourceJobId, String targetJobId, String taskId, CallMetadata callMetadata) {
return defer(() -> {
stubbedJobData.changeJob(sourceJobId, job -> JobFunctions.incrementJobSize(job, -1));
stubbedJobData.changeJob(targetJobId, job -> JobFunctions.incrementJobSize(job, 1));
stubbedJobData.changeTask(taskId, task -> JobFunctions.moveTask(sourceJobId, targetJobId, task));
});
}
@Override
public Completable updateTask(String taskId, Function<Task, Optional<Task>> changeFunction, Trigger trigger, String reason, CallMetadata callMetadata) {
return deferCompletable(() -> stubbedJobData.changeTask(taskId, task -> changeFunction.apply(task).orElse(task)));
}
private <T> Observable<T> defer(Supplier<T> action) {
return Observable.defer(() -> Observable.just(action.get()));
}
private Observable<Void> defer(Runnable action) {
return Observable.defer(() -> {
action.run();
return Observable.empty();
});
}
private Completable deferCompletable(Runnable action) {
return Completable.defer(() -> {
action.run();
return Completable.complete();
});
}
}
| 1,095 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobDescriptorGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import com.netflix.titus.api.jobmanager.JobAttributes;
import com.netflix.titus.api.jobmanager.model.job.Capacity;
import com.netflix.titus.api.jobmanager.model.job.Image;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobFunctions;
import com.netflix.titus.api.jobmanager.model.job.JobModel;
import com.netflix.titus.api.jobmanager.model.job.Owner;
import com.netflix.titus.api.jobmanager.model.job.ServiceJobProcesses;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt;
import com.netflix.titus.api.jobmanager.model.job.retry.RetryPolicy;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.common.util.CollectionsExt;
import com.netflix.titus.testkit.model.PrimitiveValueGenerators;
import com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.union;
import static com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator.budgetSelfManagedBasic;
public final class JobDescriptorGenerator {
public static final String TEST_STACK_NAME = "embedded";
public static final String TEST_CELL_NAME = "embeddedCell";
private JobDescriptorGenerator() {
}
public static DataGenerator<Owner> owners() {
return PrimitiveValueGenerators.emailAddresses().map(ea -> JobModel.newOwner().withTeamEmail(ea).build());
}
public static DataGenerator<RetryPolicy> retryPolicies() {
return DataGenerator.items(JobModel.newDelayedRetryPolicy().withDelay(100, TimeUnit.MILLISECONDS).withRetries(5).build());
}
public static DataGenerator<String> capacityGroups() {
return DataGenerator.items("flex1", "flex2", "critical1", "critical2");
}
public static DataGenerator<BatchJobExt> batchJobExtensions() {
return retryPolicies().map(retryPolicy -> JobModel.newBatchJobExt()
.withSize(1)
.withRuntimeLimitMs(60_000)
.withRetryPolicy(retryPolicy)
.build()
);
}
public static DataGenerator<ServiceJobExt> serviceJobExtensions() {
return retryPolicies().map(retryPolicy -> JobModel.newServiceJobExt()
.withCapacity(JobModel.newCapacity().withMin(0).withDesired(1).withMax(2).build())
.withEnabled(true)
.withServiceJobProcesses(ServiceJobProcesses.newBuilder().withDisableDecreaseDesired(false).withDisableDecreaseDesired(false).build())
.withRetryPolicy(retryPolicy)
.build()
);
}
@SafeVarargs
public static DataGenerator<JobDescriptor<BatchJobExt>> batchJobDescriptors(Function<JobDescriptor<BatchJobExt>, JobDescriptor<BatchJobExt>>... modifiers) {
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withOwner = union(
items(JobModel.<BatchJobExt>newJobDescriptor().withDisruptionBudget(budgetSelfManagedBasic())),
owners(),
(builder, owners) -> builder.but().withOwner(owners)
);
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withJobGroupInfo = union(
withOwner,
DataGenerator.items(JobModel.newJobGroupInfo().withStack("").withDetail("").withSequence("").build()),
(builder, jobGroupInfos) -> builder.but().withJobGroupInfo(jobGroupInfos)
);
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withContainer = union(
withJobGroupInfo,
ContainersGenerator.containers(),
(builder, container) -> builder.but().withContainer(container)
);
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withCapacityGroup = union(
withContainer,
capacityGroups(),
(builder, capacityGroup) -> builder.but().withCapacityGroup(capacityGroup)
);
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withAppName = union(
withCapacityGroup,
PrimitiveValueGenerators.applicationNames(),
(builder, applicationName) -> builder.but().withApplicationName(applicationName)
);
DataGenerator<JobDescriptor.Builder<BatchJobExt>> withExtensions = union(
withAppName,
batchJobExtensions(),
(builder, batchJobExt) -> builder.but().withExtensions(batchJobExt)
);
return withExtensions
.map(builder -> builder.withAttributes(CollectionsExt.<String, String>newHashMap()
.entry(JobAttributes.JOB_ATTRIBUTES_CELL, TEST_CELL_NAME)
.entry(JobAttributes.JOB_ATTRIBUTES_STACK, TEST_STACK_NAME)
.entry("labelA", "valueA")
.toMap()).build()
)
.map(jd -> {
JobDescriptor<BatchJobExt> result = jd;
for (Function<JobDescriptor<BatchJobExt>, JobDescriptor<BatchJobExt>> modifier : modifiers) {
result = modifier.apply(result);
}
return result;
});
}
public static DataGenerator<JobDescriptor<ServiceJobExt>> serviceJobDescriptors(Function<JobDescriptor<ServiceJobExt>, JobDescriptor<ServiceJobExt>>... modifiers) {
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withOwner = union(
items(JobModel.<ServiceJobExt>newJobDescriptor().withDisruptionBudget(budgetSelfManagedBasic())),
owners(),
(builder, owners) -> builder.but().withOwner(owners)
);
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withJobGroupInfo = union(
withOwner,
JobClustersGenerator.jobGroupInfos(),
(builder, jobGroupInfos) -> builder.but().withJobGroupInfo(jobGroupInfos)
);
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withContainer = union(
withJobGroupInfo,
ContainersGenerator.containers().map(c -> c.but(cc -> cc.getContainerResources().toBuilder().withAllocateIP(true).build())),
(builder, container) -> builder.but().withContainer(container)
);
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withCapacityGroup = union(
withContainer,
capacityGroups(),
(builder, capacityGroup) -> builder.but().withCapacityGroup(capacityGroup)
);
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withAppName = union(
withCapacityGroup,
PrimitiveValueGenerators.applicationNames(),
(builder, applicationName) -> builder.but().withApplicationName(applicationName)
);
DataGenerator<JobDescriptor.Builder<ServiceJobExt>> withExtensions = union(
withAppName,
serviceJobExtensions(),
(builder, serviceJobExt) -> builder.but().withExtensions(serviceJobExt)
);
return withExtensions
.map(builder -> builder.withAttributes(CollectionsExt.<String, String>newHashMap()
.entry(JobAttributes.JOB_ATTRIBUTES_CELL, TEST_CELL_NAME)
.entry(JobAttributes.JOB_ATTRIBUTES_STACK, TEST_STACK_NAME)
.entry("labelA", "valueA")
.toMap()
).build()
)
.map(jd -> {
JobDescriptor<ServiceJobExt> result = jd;
for (Function<JobDescriptor<ServiceJobExt>, JobDescriptor<ServiceJobExt>> modifier : modifiers) {
result = modifier.apply(result);
}
return result;
});
}
public static JobDescriptor<BatchJobExt> batchJobDescriptor(int desired) {
return JobFunctions.changeBatchJobSize(oneTaskBatchJobDescriptor(), desired);
}
public static JobDescriptor<BatchJobExt> oneTaskBatchJobDescriptorWithAttributes(Map<String, String> attributes) {
return JobFunctions.appendJobDescriptorAttributes(oneTaskBatchJobDescriptor(), attributes);
}
public static JobDescriptor<ServiceJobExt> oneTaskServiceJobDescriptorWithAttributes(Map<String, String> attributes) {
return JobFunctions.appendJobDescriptorAttributes(oneTaskServiceJobDescriptor(), attributes);
}
public static JobDescriptor<BatchJobExt> oneTaskBatchJobDescriptor() {
JobDescriptor<BatchJobExt> jobDescriptor = batchJobDescriptors().getValue();
Image imageWithTag = JobModel.newImage().withName("titusops/alpine").withTag("latest").build();
return JobModel.newJobDescriptor(jobDescriptor)
.withContainer(JobModel.newContainer(jobDescriptor.getContainer()).withImage(imageWithTag).build())
.withDisruptionBudget(DisruptionBudgetGenerator.budget(
DisruptionBudgetGenerator.perTaskRelocationLimitPolicy(3),
DisruptionBudgetGenerator.hourlyRatePercentage(50),
Collections.singletonList(DisruptionBudgetGenerator.officeHourTimeWindow())
))
.withExtensions(JobModel.newBatchJobExt(jobDescriptor.getExtensions())
.withSize(1)
.withRetryPolicy(JobModel.newImmediateRetryPolicy().withRetries(0).build())
.build()
)
.withExtraContainers(jobDescriptor.getExtraContainers())
.withPlatformSidecars(jobDescriptor.getPlatformSidecars())
.build();
}
public static JobDescriptor<ServiceJobExt> oneTaskServiceJobDescriptor() {
JobDescriptor<ServiceJobExt> jobDescriptor = serviceJobDescriptors().getValue();
Image imageWithTag = JobModel.newImage().withName("titusops/alpine").withTag("latest").build();
return JobModel.newJobDescriptor(jobDescriptor)
.withContainer(JobModel.newContainer(jobDescriptor.getContainer()).withImage(imageWithTag).build())
.withDisruptionBudget(DisruptionBudgetGenerator.budget(
DisruptionBudgetGenerator.perTaskRelocationLimitPolicy(3),
DisruptionBudgetGenerator.hourlyRatePercentage(50),
Collections.singletonList(DisruptionBudgetGenerator.officeHourTimeWindow())
))
.withExtensions(JobModel.newServiceJobExt(jobDescriptor.getExtensions())
.withCapacity(Capacity.newBuilder().withMin(0).withDesired(1).withMax(2).build())
.withRetryPolicy(JobModel.newImmediateRetryPolicy().withRetries(0).build())
.withMigrationPolicy(JobModel.newSystemDefaultMigrationPolicy().build())
.withEnabled(true)
.withServiceJobProcesses(ServiceJobProcesses.newBuilder().build())
.build()
)
.build();
}
}
| 1,096 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobTestFunctions.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.Task;
public final class JobTestFunctions {
private JobTestFunctions() {
}
public static Map<String, Job<?>> toJobMap(Collection<Job> jobs) {
return jobs.stream().collect(Collectors.toMap(Job::getId, j -> j));
}
public static Map<String, Task> toTaskMap(Collection<Task> tasks) {
return tasks.stream().collect(Collectors.toMap(Task::getId, t -> t));
}
}
| 1,097 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/job/JobClustersGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.job;
import com.netflix.titus.api.jobmanager.model.job.JobGroupInfo;
import com.netflix.titus.api.jobmanager.model.job.JobModel;
import com.netflix.titus.common.data.generator.DataGenerator;
import static com.netflix.titus.common.data.generator.DataGenerator.items;
import static com.netflix.titus.common.data.generator.DataGenerator.range;
/**
*/
public final class JobClustersGenerator {
private JobClustersGenerator() {
}
public static DataGenerator<String> stacks() {
return items("main", "mainvpc", "dev");
}
public static DataGenerator<String> details() {
return items("GA", "canary", "prototype");
}
public static DataGenerator<String> versions() {
return range(0).map(version -> String.format("v%03d", version));
}
public static DataGenerator<JobGroupInfo> jobGroupInfos() {
return DataGenerator.union(
stacks(),
details(),
versions(),
(stack, detail, sequence) -> JobModel.newJobGroupInfo().withStack(stack).withDetail(detail).withSequence(sequence).build()
);
}
}
| 1,098 |
0 | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model | Create_ds/titus-control-plane/titus-testkit/src/main/java/com/netflix/titus/testkit/model/supervisor/MasterInstanceGenerator.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.supervisor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.netflix.titus.common.data.generator.DataGenerator;
import com.netflix.titus.api.supervisor.model.MasterInstance;
import com.netflix.titus.api.supervisor.model.MasterState;
import com.netflix.titus.api.supervisor.model.MasterStatus;
public class MasterInstanceGenerator {
public static DataGenerator<MasterInstance> masterInstances(MasterState initialState, String... ids) {
MasterStatus masterStatus = MasterStatus.newBuilder()
.withState(initialState)
.withMessage("Initial value")
.build();
List<MasterInstance> values = new ArrayList<>();
for (int i = 0; i < ids.length; i++) {
values.add(
MasterInstance.newBuilder()
.withInstanceId(ids[i])
.withInstanceGroupId("testInstanceGroup")
.withIpAddress("1.0.0." + i)
.withStatus(masterStatus)
.withStatusHistory(Collections.emptyList())
.build()
);
}
return DataGenerator.items(values);
}
public static MasterInstance getLocalMasterInstance(MasterState state) {
return masterInstances(state, "localMaster").getValue();
}
public static MasterInstance moveTo(MasterInstance current, MasterState state) {
return current.toBuilder()
.withStatus(MasterStatus.newBuilder()
.withState(state)
.withMessage("Requested by test")
.build()
)
.build();
}
}
| 1,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.