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/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/Computation.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 io.mantisrx.runtime.computation; import io.mantisrx.runtime.Context; public interface Computation { default void init(final Context context) { } }
8,700
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/ScalarComputation.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 io.mantisrx.runtime.computation; import io.mantisrx.runtime.Context; import rx.Observable; import rx.functions.Func2; public interface ScalarComputation<T, R> extends Computation, Func2<Context, Observable<T>, Observable<R>> { }
8,701
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/ToKeyComputation.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 io.mantisrx.runtime.computation; import io.mantisrx.runtime.Context; import rx.Observable; import rx.functions.Func2; import rx.observables.GroupedObservable; public interface ToKeyComputation<T, K, R> extends Computation, Func2<Context, Observable<T>, Observable<GroupedObservable<K, R>>> { }
8,702
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/ToGroupComputation.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 io.mantisrx.runtime.computation; import io.mantisrx.common.MantisGroup; import io.mantisrx.runtime.Context; import rx.Observable; import rx.functions.Func2; /** * Alternative to ToKeyComputation that generates a MantisGroup K,R instead * * @param <T> * @param <K> * @param <R> * * @author njoshi */ public interface ToGroupComputation<T, K, R> extends Computation, Func2<Context, Observable<T>, Observable<MantisGroup<K, R>>> { }
8,703
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/MantisOperatorMerge.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 io.mantisrx.runtime.computation; public class MantisOperatorMerge<T> /*extends OperatorMerge<T> */ { }
8,704
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/CollectComputation.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 io.mantisrx.runtime.computation; import io.mantisrx.runtime.Context; import rx.Observable; import rx.functions.Func2; public interface CollectComputation<T> extends Computation, Func2<Context, Observable<Observable<T>>, Observable<T>> { }
8,705
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/StageInfo.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 io.mantisrx.runtime.descriptor; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class StageInfo { private final int stageNumber; private final String description; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public StageInfo(@JsonProperty("stageNumber") int stageNumber, @JsonProperty("description") String description) { this.stageNumber = stageNumber; this.description = description; } public int getStageNumber() { return stageNumber; } public String getDescription() { return description; } }
8,706
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/ParameterInfo.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 io.mantisrx.runtime.descriptor; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class ParameterInfo { private final String name; private final String description; private final String defaultValue; private final String parameterType; private final String validatorDescription; private final boolean required; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public ParameterInfo(@JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("defaultValue") String defaultValue, @JsonProperty("parmaterType") String parameterType, @JsonProperty("validatorDescription") String validatorDescription, @JsonProperty("required") boolean required) { this.name = name; this.description = description; this.defaultValue = defaultValue; this.parameterType = parameterType; this.validatorDescription = validatorDescription; this.required = required; } public String getName() { return name; } public String getDescription() { return description; } public String getDefaultValue() { return defaultValue; } public String getParameterType() { return parameterType; } public String getValidatorDescription() { return validatorDescription; } public boolean isRequired() { return required; } @Override public String toString() { return "ParameterInfo{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", defaultValue='" + defaultValue + '\'' + ", parameterType='" + parameterType + '\'' + ", validatorDescription='" + validatorDescription + '\'' + ", required=" + required + '}'; } }
8,707
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/MetadataInfo.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 io.mantisrx.runtime.descriptor; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class MetadataInfo { private String name; private String description; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public MetadataInfo(@JsonProperty("name") String name, @JsonProperty("description") String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } }
8,708
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/ResourceRequest.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 io.mantisrx.runtime.descriptor; public class ResourceRequest { }
8,709
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/JobDescriptor.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 io.mantisrx.runtime.descriptor; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class JobDescriptor { private final JobInfo jobInfo; private final String project; private final String version; private final long timestamp; // flag for rolling out the job master changes, Job Master is launched by MantisMaster only if this flag is set private final boolean readyForJobMaster; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobDescriptor( @JsonProperty("jobInfo") JobInfo jobInfo, @JsonProperty("project") String project, @JsonProperty("version") String version, @JsonProperty("timestamp") long timestamp, @JsonProperty("readyForJobMaster") boolean readyForJobMaster) { this.jobInfo = jobInfo; this.version = version; this.timestamp = timestamp; this.project = project; this.readyForJobMaster = readyForJobMaster; } public String getVersion() { return version; } public JobInfo getJobInfo() { return jobInfo; } public String getProject() { return project; } public long getTimestamp() { return timestamp; } public boolean isReadyForJobMaster() { return readyForJobMaster; } }
8,710
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/descriptor/JobInfo.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 io.mantisrx.runtime.descriptor; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; public class JobInfo extends MetadataInfo { private final int numberOfStages; private final MetadataInfo sourceInfo; private final MetadataInfo sinkInfo; private final Map<Integer, StageInfo> stages; private final Map<String, ParameterInfo> parameterInfo; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobInfo( @JsonProperty("name") final String name, @JsonProperty("description") final String description, @JsonProperty("numberOfStages") final int numberOfStages, @JsonProperty("parameterInfo") final Map<String, ParameterInfo> parameterInfo, @JsonProperty("sourceInfo") final MetadataInfo sourceInfo, @JsonProperty("sinkInfo") final MetadataInfo sinkInfo, @JsonProperty("stages") final Map<Integer, StageInfo> stages) { super(name, description); this.numberOfStages = numberOfStages; this.parameterInfo = parameterInfo; this.sourceInfo = sourceInfo; this.sinkInfo = sinkInfo; this.stages = stages; } public int getNumberOfStages() { return numberOfStages; } public Map<String, ParameterInfo> getParameterInfo() { return parameterInfo; } public MetadataInfo getSourceInfo() { return sourceInfo; } public MetadataInfo getSinkInfo() { return sinkInfo; } public Map<Integer, StageInfo> getStages() { return stages; } }
8,711
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/ParameterDefinition.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 io.mantisrx.runtime.parameter; import io.mantisrx.runtime.parameter.validator.Validator; public class ParameterDefinition<T> { private final String name; private final String description; private final T defaultValue; private final String typeDescription; private final Validator<? super T> validator; private final boolean required; private final ParameterDecoder<T> decoder; ParameterDefinition(Builder<T> builder) { this.name = builder.name; this.description = builder.description; this.validator = builder.validator; this.required = builder.required; this.typeDescription = builder.getTypeDescription(); this.defaultValue = builder.defaultValue; this.decoder = builder.decoder(); } public ParameterDecoder<T> getDecoder() { return decoder; } public String getTypeDescription() { return typeDescription; } public String getName() { return name; } public String getDescription() { return description; } public Validator<? super T> getValidator() { return validator; } public boolean isRequired() { return required; } public T getDefaultValue() { return defaultValue; } @Override public String toString() { return "ParameterDefinition [name=" + name + ", description=" + description + ", validator=" + validator + ", required=" + required + "]"; } public abstract static class Builder<T> { protected String name; protected String description; protected T defaultValue; protected Validator<? super T> validator; protected boolean required = false; public abstract ParameterDecoder<T> decoder(); public abstract String getTypeDescription(); /** * @deprecated use {@link #getTypeDescription()} instead. */ @Deprecated public abstract Class<T> classType(); public Builder<T> name(String name) { this.name = name; return this; } public Builder<T> defaultValue(T defaultValue) { this.defaultValue = defaultValue; return this; } public Builder<T> description(String description) { this.description = description; return this; } public Builder<T> validator(Validator<? super T> validator) { this.validator = validator; return this; } public Builder<T> required() { this.required = true; return this; } public ParameterDefinition<T> build() { if (validator == null) { throw new ParameterException("A validator must be specified for parameter: " + name); } return new ParameterDefinition<>(this); } } }
8,712
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/SourceJobParameters.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 io.mantisrx.runtime.parameter; import com.mantisrx.common.utils.MantisSSEConstants; import io.mantisrx.runtime.Context; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.shaded.com.fasterxml.jackson.core.type.TypeReference; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SourceJobParameters { public static final String MANTIS_SOURCEJOB_TARGET_KEY = "target"; public static final String MANTIS_SOURCEJOB_NAME_PARAM = "sourceJobName"; public static final String MANTIS_SOURCEJOB_CRITERION = "criterion"; public static final String MANTIS_SOURCEJOB_CLIENT_ID = "clientId"; public static final String MANTIS_SOURCEJOB_IS_BROADCAST_MODE = "isBroadcastMode"; private static final Logger log = LoggerFactory.getLogger(SourceJobParameters.class); private static final ObjectMapper mapper = new ObjectMapper(); public static List<TargetInfo> parseInputParameters(Context ctx) { String targetListStr = (String) ctx.getParameters() .get(MANTIS_SOURCEJOB_TARGET_KEY, "{}"); return parseTargetInfo(targetListStr); } public static List<TargetInfo> parseTargetInfo(String targetListStr) { List<TargetInfo> targetList = new ArrayList<>(); try { Map<String, List<TargetInfo>> targets = mapper.readValue(targetListStr, new TypeReference<Map<String, List<TargetInfo>>>() {}); if (targets.get("targets") != null) { return targets.get("targets"); } } catch (Exception ex) { log.error("Failed to parse target list: {}", targetListStr, ex); } return targetList; } @JsonIgnoreProperties(ignoreUnknown = true) public static class TargetInfo { @JsonProperty(MANTIS_SOURCEJOB_NAME_PARAM) public String sourceJobName; @JsonProperty(MANTIS_SOURCEJOB_CRITERION) public String criterion; @JsonProperty(MANTIS_SOURCEJOB_CLIENT_ID) public String clientId; @JsonProperty(MantisSSEConstants.SAMPLE) public int samplePerSec = -1; @JsonProperty(MANTIS_SOURCEJOB_IS_BROADCAST_MODE) public boolean isBroadcastMode; @JsonProperty(MantisSSEConstants.ENABLE_META_MESSAGES) public boolean enableMetaMessages; @JsonProperty(MantisSSEConstants.MANTIS_ENABLE_COMPRESSION) public boolean enableCompressedBinary; @JsonProperty(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER) public String delimiter; public TargetInfo(String jobName, String criterion, String clientId, int samplePerSec, boolean isBroadcastMode, boolean enableMetaMessages, boolean enableCompressedBinary, String delimiter) { this.sourceJobName = jobName; this.criterion = criterion; this.clientId = clientId; this.samplePerSec = samplePerSec; this.isBroadcastMode = isBroadcastMode; this.enableMetaMessages = enableMetaMessages; this.enableCompressedBinary = enableCompressedBinary; this.delimiter = delimiter; } public TargetInfo() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TargetInfo that = (TargetInfo) o; return Objects.equals(sourceJobName, that.sourceJobName) && Objects.equals(criterion, that.criterion) && Objects.equals(clientId, that.clientId) && Objects.equals(samplePerSec, that.samplePerSec) && Objects.equals(isBroadcastMode, that.isBroadcastMode) && Objects.equals(enableMetaMessages, that.enableMetaMessages) && Objects.equals(enableCompressedBinary, that.enableCompressedBinary) && Objects.equals(delimiter, that.delimiter); } @Override public int hashCode() { return Objects.hash(sourceJobName, criterion, clientId, samplePerSec, isBroadcastMode, enableMetaMessages, enableCompressedBinary, delimiter); } @Override public String toString() { return "TargetInfo{" + "sourceJobName=" + sourceJobName + "," + "criterion=" + criterion + "," + "clientId=" + clientId + "," + "samplePerSec=" + samplePerSec + "," + "isBroadcastMode=" + isBroadcastMode + "," + "enableMetaMessages=" + enableMetaMessages + "," + "enableCompressedBinary=" + enableCompressedBinary + "," + "delimiter=" + delimiter + "," + "}"; } } public static class TargetInfoBuilder { private String sourceJobName; private String criterion; private String clientId; private int samplePerSec = -1; private boolean isBroadcastMode = false; private boolean enableMetaMessages = false; private boolean enableCompressedBinary = false; private String delimiter = null; public TargetInfoBuilder() { } public TargetInfoBuilder withSourceJobName(String srcJobName) { this.sourceJobName = srcJobName; return this; } public TargetInfoBuilder withQuery(String query) { this.criterion = query; return this; } public TargetInfoBuilder withSamplePerSec(int samplePerSec) { this.samplePerSec = samplePerSec; return this; } public TargetInfoBuilder withBroadCastMode() { this.isBroadcastMode = true; return this; } public TargetInfoBuilder withMetaMessagesEnabled() { this.enableMetaMessages = true; return this; } public TargetInfoBuilder withBinaryCompressionEnabled() { this.enableCompressedBinary = true; return this; } public TargetInfoBuilder withClientId(String clientId) { this.clientId = clientId; return this; } public TargetInfoBuilder withDelimiter(String delimiter) { this.delimiter = delimiter; return this; } public TargetInfo build() { return new TargetInfo( sourceJobName, criterion, clientId, samplePerSec, isBroadcastMode, enableMetaMessages, enableCompressedBinary, delimiter); } } /** * Ensures that a list of TargetInfo contains a sane set of sourceJobName, ClientId pairs. * TODO: Currently mutates the list, which isn't problematic here, but it would be prudent to clean this up. * * @param targets A List of TargetInfo for which to validate and correct clientId inconsistencies. * * @return The original List modified to have consistent clientIds. */ public static List<TargetInfo> enforceClientIdConsistency(List<TargetInfo> targets, String defaultClientId) { targets.sort(Comparator.comparing(t -> t.criterion)); HashSet<Map.Entry<String, String>> connectionPairs = new HashSet<>(targets.size()); for (TargetInfo target : targets) { if (target.clientId == null) { target.clientId = defaultClientId; } Map.Entry<String, String> connectionPair = new AbstractMap.SimpleEntry<>(target.sourceJobName, target.clientId); int attempts = 0; while (connectionPairs.contains(connectionPair)) { connectionPair = new AbstractMap.SimpleEntry<>(target.sourceJobName, target.clientId + "_" + ++attempts); } target.clientId = connectionPair.getValue(); connectionPairs.add(connectionPair); } return targets; } }
8,713
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/ParameterException.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 io.mantisrx.runtime.parameter; public class ParameterException extends RuntimeException { private static final long serialVersionUID = 1L; public ParameterException(String message) { super(message); } }
8,714
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/ParameterUtils.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 io.mantisrx.runtime.parameter; import static io.mantisrx.common.SystemParameters.JOB_MASTER_AUTOSCALE_METRIC_SYSTEM_PARAM; import static io.mantisrx.common.SystemParameters.JOB_MASTER_AUTOSCALE_SOURCEJOB_DROP_METRIC_PATTERNS_PARAM; import static io.mantisrx.common.SystemParameters.JOB_MASTER_AUTOSCALE_SOURCEJOB_METRIC_PARAM; import static io.mantisrx.common.SystemParameters.JOB_MASTER_AUTOSCALE_SOURCEJOB_TARGET_PARAM; import static io.mantisrx.common.SystemParameters.JOB_MASTER_CLUTCH_EXPERIMENTAL_PARAM; import static io.mantisrx.common.SystemParameters.JOB_MASTER_CLUTCH_SYSTEM_PARAM; import static io.mantisrx.common.SystemParameters.JOB_WORKER_HEARTBEAT_INTERVAL_SECS; import static io.mantisrx.common.SystemParameters.JOB_WORKER_TIMEOUT_SECS; import static io.mantisrx.common.SystemParameters.MAX_NUM_STAGES_FOR_JVM_OPTS_OVERRIDE; import static io.mantisrx.common.SystemParameters.PER_STAGE_JVM_OPTS_FORMAT; import static io.mantisrx.common.SystemParameters.STAGE_CONCURRENCY; import com.mantisrx.common.utils.MantisSSEConstants; import io.mantisrx.common.compression.CompressionUtils; import io.mantisrx.runtime.parameter.type.BooleanParameter; import io.mantisrx.runtime.parameter.type.IntParameter; import io.mantisrx.runtime.parameter.type.StringParameter; import io.mantisrx.runtime.parameter.validator.Validation; import io.mantisrx.runtime.parameter.validator.Validators; 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 lombok.extern.slf4j.Slf4j; import rx.functions.Func1; @Slf4j public class ParameterUtils { static final Map<String, ParameterDefinition<?>> systemParams = new ConcurrentHashMap<>(); static { ParameterDefinition<Integer> keyBuffer = new IntParameter() .name("mantis.w2w.toKeyBuffer") .validator(Validators.range(1, 100000)) .defaultValue(50000) .description("per connection buffer from Scalar To Key stage") .build(); systemParams.put(keyBuffer.getName(), keyBuffer); ParameterDefinition<Boolean> useSPSC4sse = new BooleanParameter() .name("mantis.sse.spsc") .description("Whether to use spsc or blocking queue for SSE") .defaultValue(false) .build(); systemParams.put(useSPSC4sse.getName(), useSPSC4sse); ParameterDefinition<Boolean> useSPSC4w2w = new BooleanParameter() .name("mantis.w2w.spsc") .description("Whether to use spsc or blocking queue") .defaultValue(false) .build(); systemParams.put(useSPSC4w2w.getName(), useSPSC4w2w); ParameterDefinition<Boolean> singleNettyThread = new BooleanParameter() .name("mantis.netty.useSingleThread") .description("use single netty thread") .defaultValue(false) .build(); systemParams.put(singleNettyThread.getName(), singleNettyThread); //mantis.w2w.toKeyMaxChunkSize 1000 ParameterDefinition<Integer> w2wtoKeyMaxChunkSize = new IntParameter() .name("mantis.w2w.toKeyMaxChunkSize") .validator(Validators.range(1, 100000)) .defaultValue(1000) .description("batch size for bytes drained from Scalar To Key stage") .build(); systemParams.put(w2wtoKeyMaxChunkSize.getName(), w2wtoKeyMaxChunkSize); //mantis.w2w.toKeyThreads 1 ParameterDefinition<Integer> w2wtoKeyThreads = new IntParameter() .name("mantis.w2w.toKeyThreads") .validator(Validators.range(1, 8)) .description("number of drainer threads on the ScalarToKey stage") .defaultValue(1) .build(); systemParams.put(w2wtoKeyThreads.getName(), w2wtoKeyThreads); // mantis.sse.bufferCapacity 25000 ParameterDefinition<Integer> sseBuffer = new IntParameter() .name("mantis.sse.bufferCapacity") .validator(Validators.range(1, 100000)) .description("buffer on SSE per connection") .defaultValue(25000) .build(); systemParams.put(sseBuffer.getName(), sseBuffer); //mantis.sse.maxChunkSize 1000 ParameterDefinition<Integer> sseChunkSize = new IntParameter() .name("mantis.sse.maxChunkSize") .validator(Validators.range(1, 100000)) .description("SSE chunk size") .defaultValue(1000) .build(); systemParams.put(sseChunkSize.getName(), sseChunkSize); // mantis.sse.maxReadTimeMSec", "250" ParameterDefinition<Integer> sseMaxReadTime = new IntParameter() .name("mantis.sse.maxReadTimeMSec") .validator(Validators.range(1, 100000)) .description("interval at which buffer is drained to write to SSE") .defaultValue(250) .build(); systemParams.put(sseMaxReadTime.getName(), sseMaxReadTime); //mantis.sse.numConsumerThreads 1 ParameterDefinition<Integer> sse_numConsumerThreads = new IntParameter() .name("mantis.sse.numConsumerThreads") .validator(Validators.range(1, 8)) .description("number of consumer threads draining the queue to write to SSE") .defaultValue(1) .build(); systemParams.put(sse_numConsumerThreads.getName(), sse_numConsumerThreads); // mantis.sse.maxNotWritableTimeSec", "-1" ParameterDefinition<Integer> maxNotWritableTimeSec = new IntParameter() .name("mantis.sse.maxNotWritableTimeSec") .validator(Validators.range(-1, 100000)) .description("maximum time the SSE connection can remain not writable before we proactively terminated it on server side. <= 0 means unlimited.") .defaultValue(-1) .build(); systemParams.put(maxNotWritableTimeSec.getName(), maxNotWritableTimeSec); // mantis.jobmaster.autoscale.metric ParameterDefinition<String> jobMasterAutoScaleMetric = new StringParameter() .name(JOB_MASTER_AUTOSCALE_METRIC_SYSTEM_PARAM) .validator(Validators.alwaysPass()) .description("Custom autoscale metric for Job Master to use with UserDefined Scaling Strategy. Format: <metricGroup>::<metricName>::<algo> where metricGroup and metricName should exactly match the metric published via Mantis MetricsRegistry and algo = MAX/AVERAGE") .defaultValue("") .build(); systemParams.put(jobMasterAutoScaleMetric.getName(), jobMasterAutoScaleMetric); // mantis.jobmaster.clutch.config ParameterDefinition<String> jobMasterAutoScaleConfig = new StringParameter() .name(JOB_MASTER_CLUTCH_SYSTEM_PARAM) .validator(Validators.alwaysPass()) .description("Configuration for the clutch autoscaler.") .defaultValue("") .build(); systemParams.put(jobMasterAutoScaleConfig.getName(), jobMasterAutoScaleConfig); // mantis.jobmaster.clutch.experimental.enabled ParameterDefinition<Boolean> clutchExperimentalEnabled = new BooleanParameter() .name(JOB_MASTER_CLUTCH_EXPERIMENTAL_PARAM) .validator(Validators.alwaysPass()) .description("Enables the experimental version of the Clutch autoscaler. Note this is different from the Clutch used in production today.") .defaultValue(false) .build(); systemParams.put(clutchExperimentalEnabled.getName(), clutchExperimentalEnabled); // set MantisWorker commandline JVM options for all stages of a job ParameterDefinition<String> jvmOptions = new StringParameter() .name("MANTIS_WORKER_JVM_OPTS") .validator(Validators.alwaysPass()) .defaultValue("") .description("command line options for the mantis worker JVM, setting this field would override the default GC settings") .build(); systemParams.put(jvmOptions.getName(), jvmOptions); ParameterDefinition<Integer> stageConcurrency = new IntParameter() .name(STAGE_CONCURRENCY) .validator(Validators.range(-1, 16)) .defaultValue(-1) .description("Number of cores to use for stage processing") .build(); systemParams.put(stageConcurrency.getName(), stageConcurrency); // set per stage mantis worker commandline JVM args, this takes precedence over MANTIS_WORKER_JVM_OPTS for (int stageNum = 0; stageNum <= MAX_NUM_STAGES_FOR_JVM_OPTS_OVERRIDE; stageNum++) { final String paramName = String.format(PER_STAGE_JVM_OPTS_FORMAT, stageNum); systemParams.put(paramName, new StringParameter() .name(paramName) .validator(Validators.alwaysPass()) .defaultValue("") .description("command line options for stage " + stageNum + " mantis worker JVM, setting this field would override the default GC settings") .build()); } ParameterDefinition<Boolean> sseBinary = new BooleanParameter() .name(MantisSSEConstants.MANTIS_ENABLE_COMPRESSION) .validator(Validators.alwaysPass()) .defaultValue(false) .description("Enables binary compression of SSE data") .build(); systemParams.put(sseBinary.getName(), sseBinary); ParameterDefinition<String> compressionDelimiter = new StringParameter() .name(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER) .validator(Validators.alwaysPass()) .defaultValue(CompressionUtils.MANTIS_SSE_DELIMITER) .description("Delimiter for separating SSE data before compression") .build(); systemParams.put(compressionDelimiter.getName(), compressionDelimiter); ParameterDefinition<Boolean> autoscaleSourceJobMetricEnabled = new BooleanParameter() .name(JOB_MASTER_AUTOSCALE_SOURCEJOB_METRIC_PARAM) .validator(Validators.alwaysPass()) .defaultValue(false) .description("Enable source job drop metrics to be used for autoscaling the 1st stage") .build(); systemParams.put(autoscaleSourceJobMetricEnabled.getName(), autoscaleSourceJobMetricEnabled); ParameterDefinition<String> autoscaleSourceJobTarget = new StringParameter() .name(JOB_MASTER_AUTOSCALE_SOURCEJOB_TARGET_PARAM) .validator(Validators.alwaysPass()) .defaultValue("{}") .description("Json config to specify source job targets for autoscale metrics. This param is not needed if the 'target' param is already present. Example: {\"targets\": [{\"sourceJobName\":<jobName>, \"clientId\":<clientId>}]}") .build(); systemParams.put(autoscaleSourceJobTarget.getName(), autoscaleSourceJobTarget); ParameterDefinition<String> autoscaleSourceJobDropMetricPattern = new StringParameter() .name(JOB_MASTER_AUTOSCALE_SOURCEJOB_DROP_METRIC_PATTERNS_PARAM) .validator(Validators.alwaysPass()) .defaultValue("") .description("Additional metrics pattern for source job drops. Comma separated list, supports dynamic client ID by using '_CLIENT_ID_' as a token. " + "Each metric should be expressed in the same format as '" + JOB_MASTER_AUTOSCALE_METRIC_SYSTEM_PARAM + "'. " + "Example: PushServerSse:clientId=_CLIENT_ID_:*::droppedCounter::MAX,ServerSentEventRequestHandler:clientId=_CLIENT_ID_:*::droppedCounter::MAX") .build(); systemParams.put(autoscaleSourceJobDropMetricPattern.getName(), autoscaleSourceJobDropMetricPattern); ParameterDefinition<Integer> workerHeartbeatInterval = new IntParameter() .name(JOB_WORKER_HEARTBEAT_INTERVAL_SECS) .validator(Validators.alwaysPass()) .defaultValue(0) .description("Configures heartbeat interval (in seconds) for job workers. This is useful to configure worker restart logic.") .build(); systemParams.put(workerHeartbeatInterval.getName(), workerHeartbeatInterval); ParameterDefinition<Integer> workerTimeout = new IntParameter() .name(JOB_WORKER_TIMEOUT_SECS) .validator(Validators.alwaysPass()) .defaultValue(0) .description("Configures timeout interval (in seconds) for job workers. There is some grace period and retries " + "built in to allow for network delays and/or miss a few worker heartbeats before being killed.") .build(); systemParams.put(workerTimeout.getName(), workerTimeout); } private ParameterUtils() { } public static Parameters createContextParameters( Map<String, ParameterDefinition<?>> parameterDefinitions, Parameter... parameters) { // index parameters by name Map<String, Parameter> indexed = new HashMap<>(); parameterDefinitions.putAll(systemParams); for (Parameter parameter : parameters) { indexed.put(parameter.getName(), parameter); } return new Parameters(checkThenCreateState(parameterDefinitions, indexed), getRequiredParameters(parameterDefinitions), getParameterDefinitions(parameterDefinitions)); } public static Parameters createContextParameters( Map<String, ParameterDefinition<?>> parameterDefinitions, List<Parameter> parameters) { parameterDefinitions.putAll(systemParams); Parameter[] array = parameters.toArray(new Parameter[parameters.size()]); return createContextParameters(parameterDefinitions, array); } @SuppressWarnings( {"unchecked", "rawtypes"}) private static void validationCheck(Func1 validator, Object value, String name) throws IllegalArgumentException { if (validator == null) { throw new IllegalArgumentException("Validator for parameter definition: " + name + " is null"); } Validation validatorOutcome; try { validatorOutcome = (Validation) validator.call(value); } catch (Throwable t) { throw new IllegalArgumentException("Parameter: " + name + " with value: " + value + " failed validator: " + t.getMessage(), t); } if (validatorOutcome.isFailedValidation()) { throw new IllegalArgumentException("Parameter: " + name + " with value: " + value + " failed validator: " + validatorOutcome.getFailedValidationReason()); } } @SuppressWarnings( {"rawtypes"}) public static <T> Map<String, Object> checkThenCreateState( Map<String, ParameterDefinition<?>> parameterDefinitions, Map<String, Parameter> parameters) throws IllegalArgumentException { Map<String, Object> parameterState = new HashMap<>(); // check all required parameters are present for (ParameterDefinition<?> definition : parameterDefinitions.values()) { if (definition.isRequired()) { // check if required is present in parameters // and there is not a default value if (!parameters.containsKey(definition.getName()) && definition.getDefaultValue() == null) { throw new IllegalArgumentException("Missing required parameter: " + definition.getName() + ", check job parameter definitions."); } } // if default value, check validation if (definition.getDefaultValue() != null) { validationCheck(definition.getValidator().getValidator(), definition.getDefaultValue(), "[default value] " + definition.getName()); // add default value parameterState.put(definition.getName(), definition.getDefaultValue()); } } // run all validators for (Parameter parameter : parameters.values()) { String name = parameter.getName(); Object value; ParameterDefinition<?> definition; definition = parameterDefinitions.get(name); if (definition == null) { if (name.startsWith("mantis.") || name.startsWith("MANTIS")) { log.info("mantis runtime parameter {} used, looking up definition >>>", name); definition = systemParams.get(name); } else { log.warn("No parameter definition for parameter with name: {}, will skip parameter", name); continue; } } Func1 validator = definition.getValidator().getValidator(); value = definition.getDecoder().decode(parameter.getValue()); validationCheck(validator, value, name); parameterState.put(name, value); } return parameterState; } public static Set<String> getRequiredParameters(Map<String, ParameterDefinition<?>> parameterDefinitions) { Set<String> requiredParameters = new HashSet<>(); for (ParameterDefinition<?> definition : parameterDefinitions.values()) { if (definition.isRequired()) { requiredParameters.add(definition.getName()); } } return requiredParameters; } public static Set<String> getParameterDefinitions(Map<String, ParameterDefinition<?>> parameterDefinitions) { Set<String> parameters = new HashSet<>(); for (ParameterDefinition<?> definition : parameterDefinitions.values()) { parameters.add(definition.getName()); } return parameters; } public static Map<String, ParameterDefinition<?>> getSystemParameters() { return Collections.unmodifiableMap(systemParams); } }
8,715
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/Parameters.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 io.mantisrx.runtime.parameter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Parameters { private Set<String> requiredParameters = new HashSet<>(); private Set<String> parameterDefinitions = new HashSet<>(); private Map<String, Object> state = new HashMap<>(); public Parameters() {} public Parameters(Map<String, Object> state, Set<String> requiredParameters, Set<String> parameterDefinitions) { this.state = state; this.requiredParameters = requiredParameters; this.parameterDefinitions = parameterDefinitions; } /** * Get parameter value given key with validation. * <p> * If the key is required, parameters must have a value provided otherwise it will throw an exception. * If the key is not defined, it will throw an exception. */ public Object get(String key) { // check if required parameter, make sure has a value if (requiredParameters.contains(key) && !state.containsKey(key)) { throw new ParameterException("Attempting to reference a required parameter witn no value: " + key + ", check parameter definitions for job."); } // check if parameter definition exists if (!parameterDefinitions.contains(key)) { throw new ParameterException("Attempting to reference parameter: " + key + ", with no definition, check parameter definitions in job."); } return state.get(key); } /** * Get parameter value given key without validation. * <p> * If the key is not defined, value is missing or is null, given {@code defaultValue} will be returned. */ public Object get(String key, Object defaultValue) { try { final Object value = get(key); return value != null ? value : defaultValue; } catch (ParameterException ex) { return defaultValue; } } }
8,716
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/ParameterDecoder.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 io.mantisrx.runtime.parameter; public interface ParameterDecoder<T> { public T decode(String value); }
8,717
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/validator/Validation.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 io.mantisrx.runtime.parameter.validator; public class Validation { private final boolean failedValidation; private final String failedValidationReason; Validation(boolean failedValidation, String failedValidationReason) { this.failedValidation = failedValidation; this.failedValidationReason = failedValidationReason; } public static Validation failed(String reason) { return new Validation(true, reason); } public static Validation passed() { return new Validation(false, null); } public boolean isFailedValidation() { return failedValidation; } public String getFailedValidationReason() { return failedValidationReason; } }
8,718
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/validator/Validator.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 io.mantisrx.runtime.parameter.validator; import rx.functions.Func1; public class Validator<T> { private final String description; private final Func1<T, Validation> validator; public Validator(String description, Func1<T, Validation> validator) { this.description = description; this.validator = validator; } public String getDescription() { return description; } public Func1<T, Validation> getValidator() { return validator; } @Override public String toString() { return "Validator [description=" + description + "]"; } }
8,719
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/validator/Validators.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 io.mantisrx.runtime.parameter.validator; import java.util.EnumSet; import rx.functions.Func1; public class Validators { private Validators() {} public static <T extends Number> Validator<T> range(final Number start, final Number end) { Func1<T, Validation> func = new Func1<T, Validation>() { @Override public Validation call(Number t1) { if (t1.doubleValue() >= start.doubleValue() && t1.doubleValue() <= end.doubleValue()) { return Validation.passed(); } else { return Validation.failed("range must be between" + " " + start + " and " + end); } } }; return new Validator<>("range >=" + start + "<=" + end, func); } public static Validator<String> notNullOrEmpty() { Func1<String, Validation> func = new Func1<String, Validation>() { @Override public Validation call(String t1) { if (t1 == null || t1.length() == 0) { return Validation.failed("string must not be null or empty"); } else { return Validation.passed(); } } }; return new Validator<>("not null or empty", func); } public static <T> Validator<T> alwaysPass() { Func1<T, Validation> func = new Func1<T, Validation>() { @Override public Validation call(T t1) { return Validation.passed(); } }; return new Validator<>("always passes validation", func); } public static <T extends Enum<T>> Validator<EnumSet<T>> notNullOrEmptyEnumCSV() { Func1<EnumSet<T>, Validation> func = new Func1<EnumSet<T>, Validation>() { @Override public Validation call(EnumSet<T> t1) { if (t1.isEmpty()) { return Validation.failed("enum constant csv list must not be null or empty"); } else { return Validation.passed(); } } }; return new Validator<>("not null or empty", func); } }
8,720
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/IntParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition.Builder; public class IntParameter extends Builder<Integer> { @Override public ParameterDecoder<Integer> decoder() { return Integer::parseInt; } @Override public String getTypeDescription() { return Integer.class.getSimpleName(); } @Override public Class<Integer> classType() { return Integer.class; } }
8,721
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/DoubleParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition.Builder; public class DoubleParameter extends Builder<Double> { @Override public ParameterDecoder<Double> decoder() { return Double::parseDouble; } @Override public String getTypeDescription() { return Double.class.getSimpleName(); } @Override public Class<Double> classType() { return Double.class; } }
8,722
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/LongParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition.Builder; public class LongParameter extends Builder<Long> { @Override public ParameterDecoder<Long> decoder() { return Long::parseLong; } @Override public String getTypeDescription() { return Long.class.getSimpleName(); } @Override public Class<Long> classType() { return Long.class; } }
8,723
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/EnumCSVParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.stream.Collectors; /** * @author hrangarajan@netflix.com */ public class EnumCSVParameter<T extends Enum<T>> extends ParameterDefinition.Builder<EnumSet<T>> { private final Class<T> clazz; public EnumCSVParameter(Class<T> clazz) { this.clazz = clazz; } @Override public ParameterDecoder<EnumSet<T>> decoder() { return new ParameterDecoder<EnumSet<T>>() { @Override public EnumSet<T> decode(String value) { String[] values = value.split(","); if (values.length == 0) { return EnumSet.noneOf(clazz); } List<T> enumVals = new ArrayList<>(); for (String val : values) { String trim = val.trim(); if (trim.length() > 0) { enumVals.add(T.valueOf(clazz, trim)); } } EnumSet<T> set = EnumSet.noneOf(clazz); set.addAll(enumVals); return set; } }; } @Override public String getTypeDescription() { List<String> ts = Arrays.stream(clazz.getEnumConstants()).map(Enum::name).collect(Collectors.toList()); return "Comma separated set of values: " + String.join(",", ts); } @Override public Class<EnumSet<T>> classType() { return null; } }
8,724
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/BooleanParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition.Builder; import io.mantisrx.runtime.parameter.validator.Validators; public class BooleanParameter extends Builder<Boolean> { public BooleanParameter() { super.validator = Validators.alwaysPass(); } @Override public ParameterDecoder<Boolean> decoder() { return Boolean::parseBoolean; } @Override public String getTypeDescription() { return Boolean.class.getSimpleName(); } @Override public Class<Boolean> classType() { return Boolean.class; } }
8,725
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/StringParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition; public class StringParameter extends ParameterDefinition.Builder<String> { @Override public ParameterDecoder<String> decoder() { return new ParameterDecoder<String>() { @Override public String decode(String value) { return value; } }; } @Override public String getTypeDescription() { return String.class.getSimpleName(); } @Override public Class<String> classType() { return String.class; } }
8,726
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/parameter/type/EnumParameter.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 io.mantisrx.runtime.parameter.type; import io.mantisrx.runtime.parameter.ParameterDecoder; import io.mantisrx.runtime.parameter.ParameterDefinition; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class EnumParameter<T extends Enum<T>> extends ParameterDefinition.Builder<Enum<T>> { private final Class<T> clazz; public EnumParameter(Class<T> clazz) { this.clazz = clazz; } @Override public ParameterDecoder<Enum<T>> decoder() { return value -> T.valueOf(clazz, value.trim()); } @Override public String getTypeDescription() { List<String> ts = Arrays.stream(clazz.getEnumConstants()).map(Enum::name).collect(Collectors.toList()); return "One of (" + String.join(",", ts) + ")"; } @Override public Class<Enum<T>> classType() { return null; } }
8,727
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/WorkerPublisher.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 io.mantisrx.runtime.executor; import io.mantisrx.runtime.StageConfig; import io.reactivex.mantis.remote.observable.RxMetrics; import java.io.Closeable; import rx.Observable; /** * WorkerPublisher is an abstraction for a sink operator execution. * @param <T> type of the observable that's getting published */ public interface WorkerPublisher<T> extends Closeable { void start(StageConfig<?, T> stage, Observable<Observable<T>> observableToPublish); RxMetrics getMetrics(); }
8,728
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/StageExecutors.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 io.mantisrx.runtime.executor; import static io.mantisrx.common.SystemParameters.STAGE_CONCURRENCY; import com.mantisrx.common.utils.Closeables; import io.mantisrx.common.MantisGroup; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.rx.MonitorOperator; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.GroupToGroup; import io.mantisrx.runtime.GroupToScalar; import io.mantisrx.runtime.Groups; import io.mantisrx.runtime.KeyToKey; import io.mantisrx.runtime.KeyToScalar; import io.mantisrx.runtime.ScalarToGroup; import io.mantisrx.runtime.ScalarToKey; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.SinkHolder; import io.mantisrx.runtime.SourceHolder; import io.mantisrx.runtime.StageConfig; import io.mantisrx.runtime.computation.Computation; import io.mantisrx.runtime.markers.MantisMarker; import io.mantisrx.runtime.scheduler.MantisRxSingleThreadScheduler; import io.mantisrx.runtime.source.Index; import io.mantisrx.server.core.ServiceRegistry; import io.reactivex.mantis.remote.observable.RxMetrics; import io.reactivx.mantis.operators.GroupedObservableUtils; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func2; import rx.internal.util.RxThreadFactory; import rx.observables.GroupedObservable; import rx.schedulers.Schedulers; public class StageExecutors { private static final Logger logger = LoggerFactory.getLogger(StageExecutors.class); private static Counter groupsExpiredCounter; private static long stageBufferIntervalMs = 100; private static int maxItemsInBuffer = 100; static { Metrics m = new Metrics.Builder() .name("StageExecutors") .addCounter("groupsExpiredCounter") .build(); m = MetricsRegistry.getInstance().registerAndGet(m); groupsExpiredCounter = m.getCounter("groupsExpiredCounter"); String stageBufferIntervalMillisStr = ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.stage.buffer.intervalMs", "100"); //.info("Read fast property mantis.sse.batchInterval" + flushIntervalMillisStr); stageBufferIntervalMs = Integer.parseInt(stageBufferIntervalMillisStr); String stageBufferMaxStr = ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("mantis.stage.buffer.maxSize", "100"); //.info("Read fast property mantis.sse.batchInterval" + flushIntervalMillisStr); maxItemsInBuffer = Integer.parseInt(stageBufferMaxStr); } private StageExecutors() { } @SuppressWarnings( {"rawtypes", "unchecked"}) public static Closeable executeSingleStageJob(final SourceHolder source, final StageConfig stage, final SinkHolder sink, final PortSelector portSelector, RxMetrics rxMetrics, final Context context, Action0 sinkObservableTerminatedCallback, final int workerIndex, final Observable<Integer> totalWorkerAtStageObservable, final Action0 onSinkSubscribe, final Action0 onSinkUnsubscribe, Action0 observableOnCompleteCallback, Action1<Throwable> observableOnErrorCallback) { // no previous stage for single stage job // source consumer WorkerConsumer sourceConsumer = new WorkerConsumer() { @Override public Observable start(StageConfig previousStage) { Index index = new Index(workerIndex, totalWorkerAtStageObservable); // call init on source source.getSourceFunction().init(context, index); Observable<Observable<?>> sourceObservable = (Observable) source.getSourceFunction().call( context, index); if (stage.getInputStrategy() == StageConfig.INPUT_STRATEGY.CONCURRENT) { return sourceObservable; } else { return Observable.just(Observable.merge(sourceObservable)); } } @Override public void close() throws IOException { source.getSourceFunction().close(); } }; // sink publisher with metrics WorkerPublisher sinkPublisher = new SinkPublisher(sink, portSelector, context, sinkObservableTerminatedCallback, onSinkSubscribe, onSinkUnsubscribe, observableOnCompleteCallback, observableOnErrorCallback); return StageExecutors.executeIntermediate(sourceConsumer, stage, sinkPublisher, context); } @SuppressWarnings( {"rawtypes", "unchecked"}) public static Closeable executeSource(final int workerIndex, final SourceHolder source, final StageConfig stage, WorkerPublisher publisher, final Context context, final Observable<Integer> totalWorkerAtStageObservable) { // create a consumer from passed in source WorkerConsumer sourceConsumer = new WorkerConsumer() { @Override public Observable start(StageConfig stage) { Index index = new Index(workerIndex, totalWorkerAtStageObservable); // call init on source source.getSourceFunction().init(context, index); Observable<Observable<?>> sourceObservable = (Observable) source.getSourceFunction().call(context, new Index(workerIndex, totalWorkerAtStageObservable)); return MantisMarker.sourceOut(sourceObservable); } @Override public void close() throws IOException { source.getSourceFunction().close(); } }; return executeIntermediate(sourceConsumer, stage, publisher, context); } @SuppressWarnings("unchecked") private static <K, T, R> Observable<Observable<R>> executeGroupsInParallel(Observable<GroupedObservable<K, T>> go, final Computation computation, final Context context, final long groupTakeUntil) { logger.info("initializing {}", computation.getClass().getCanonicalName()); computation.init(context); // from groups to observable final Func2<Context, GroupedObservable<K, T>, Observable<R>> c = (Func2<Context, GroupedObservable<K, T>, Observable<R>>) computation; return go .lift(new MonitorOperator<>("worker_stage_outer")) .map(group -> c .call(context, GroupedObservableUtils.createGroupedObservable(group.getKey(), group // comment out as it induces NPE in merge supposedly fixed in rxJava 1.0 .doOnUnsubscribe(() -> { //logger.info("Expiring group in executeGroupsInParallel" + group.getKey()); if (groupsExpiredCounter != null) groupsExpiredCounter.increment(); }) .timeout(groupTakeUntil, TimeUnit.SECONDS, Observable.empty()) .subscribeOn(Schedulers.computation()) .lift(new MonitorOperator<>("worker_stage_inner_input")))) .lift(new MonitorOperator("worker_stage_inner_output"))); } @SuppressWarnings("unchecked") private static <K, T, R> Observable<Observable<R>> executeMantisGroups(Observable<Observable<MantisGroup<K, T>>> go, final Computation computation, final Context context, final long groupTakeUntil) { logger.info("initializing {}", computation.getClass().getCanonicalName()); computation.init(context); // from groups to observable final Func2<Context, Observable<MantisGroup<K, T>>, Observable<R>> c = (Func2<Context, Observable<MantisGroup<K, T>>, Observable<R>>) computation; return go .lift(new MonitorOperator<>("worker_stage_outer")) .map(group -> c .call(context, group .lift(new MonitorOperator<>("worker_stage_inner_input"))) .lift(new MonitorOperator("worker_stage_inner_output"))); } /** * @param go * @param computation * * @return untyped to support multiple callers return types */ @SuppressWarnings("unchecked") private static <K, T, R> Observable<Observable<R>> executeMantisGroupsInParallel(Observable<Observable<MantisGroup<K, T>>> go, Computation computation, final Context context, final boolean applyTimeoutToInners, final long timeout, final int concurrency) { logger.info("initializing {}", computation.getClass().getCanonicalName()); computation.init(context); // from groups to observable final Func2<Context, Observable<MantisGroup<K, T>>, Observable<R>> c = (Func2<Context, Observable<MantisGroup<K, T>>, Observable<R>>) computation; if(concurrency == StageConfig.DEFAULT_STAGE_CONCURRENCY) { return go .lift(new MonitorOperator<>("worker_stage_outer")) .map(observable -> c .call(context, observable .observeOn(Schedulers.computation()) .lift(new MonitorOperator<>("worker_stage_inner_input"))) .lift(new MonitorOperator<>("worker_stage_inner_output"))); } else { final MantisRxSingleThreadScheduler[] mantisRxSingleThreadSchedulers = new MantisRxSingleThreadScheduler[concurrency]; RxThreadFactory rxThreadFactory = new RxThreadFactory("MantisRxSingleThreadScheduler-"); logger.info("creating {} Mantis threads", concurrency); for (int i = 0; i < concurrency; i++) { mantisRxSingleThreadSchedulers[i] = new MantisRxSingleThreadScheduler(rxThreadFactory); } return go .lift(new MonitorOperator<>("worker_stage_outer")) .map(observable -> observable .groupBy(e -> Math.abs(e.getKeyValue().hashCode()) % concurrency) .flatMap(gbo -> c .call(context, gbo .observeOn(mantisRxSingleThreadSchedulers[gbo.getKey()]) .lift(new MonitorOperator<MantisGroup<K, T>>("worker_stage_inner_input"))) .lift(new MonitorOperator<R>("worker_stage_inner_output")))); } } /** * @param oo * @param computation * * @return untyped to support multiple callers return types */ @SuppressWarnings("unchecked") private static <T, R> Observable<Observable<R>> executeInners(Observable<Observable<T>> oo, Computation computation, final Context context, final boolean applyTimeoutToInners, final long timeout) { logger.info("initializing {}", computation.getClass().getCanonicalName()); computation.init(context); // from groups to observable final Func2<Context, Observable<T>, Observable<R>> c = (Func2<Context, Observable<T>, Observable<R>>) computation; return oo .lift(new MonitorOperator<>("worker_stage_outer")) .map(observable -> c .call(context, observable .lift(new MonitorOperator<T>("worker_stage_inner_input"))) .lift(new MonitorOperator<R>("worker_stage_inner_output"))); } /** * @param oo * @param computation * * @return untyped to support multiple callers return types */ @SuppressWarnings("unchecked") private static <T, R> Observable<Observable<R>> executeInnersInParallel(Observable<Observable<T>> oo, Computation computation, final Context context, final boolean applyTimeoutToInners, final long timeout, final int concurrency) { logger.info("initializing {}", computation.getClass().getCanonicalName()); computation.init(context); // from groups to observable final Func2<Context, Observable<T>, Observable<R>> c = (Func2<Context, Observable<T>, Observable<R>>) computation; if (concurrency == StageConfig.DEFAULT_STAGE_CONCURRENCY) { return oo .lift(new MonitorOperator<>("worker_stage_outer")) .map(observable -> c .call(context, observable .observeOn(Schedulers.computation()) .lift(new MonitorOperator<T>("worker_stage_inner_input"))) .lift(new MonitorOperator<R>("worker_stage_inner_output"))); } else { final MantisRxSingleThreadScheduler[] mantisRxSingleThreadSchedulers = new MantisRxSingleThreadScheduler[concurrency]; RxThreadFactory rxThreadFactory = new RxThreadFactory("MantisRxSingleThreadScheduler-"); logger.info("creating {} Mantis threads", concurrency); for (int i = 0; i < concurrency; i++) { mantisRxSingleThreadSchedulers[i] = new MantisRxSingleThreadScheduler(rxThreadFactory); } return oo .lift(new MonitorOperator<>("worker_stage_outer")) .map(observable -> observable .groupBy(e -> System.nanoTime() % concurrency) .flatMap(go -> c .call(context, go .observeOn(mantisRxSingleThreadSchedulers[go.getKey().intValue()]) .lift(new MonitorOperator<>("worker_stage_inner_input"))) .lift(new MonitorOperator<>("worker_stage_inner_output")))); } } /** * If stage concurrency is not specified on the stage config check job param and use it if set. * * @param givenStageConcurrency * * @return */ private static int resolveStageConcurrency(Context context, int givenStageConcurrency) { if (givenStageConcurrency == StageConfig.DEFAULT_STAGE_CONCURRENCY) { String jobParamPrefix = "JOB_PARAM_"; String stageConcurrencyParam = jobParamPrefix + STAGE_CONCURRENCY; // Need to be compatible for both Mesos and TaskExecutor. int jobParamConcurrency = (int) context.getParameters().get(STAGE_CONCURRENCY, givenStageConcurrency); logger.info("Job param: " + stageConcurrencyParam + " value: " + jobParamConcurrency); if (jobParamConcurrency <= 0) { return givenStageConcurrency; } else { return jobParamConcurrency; } } return givenStageConcurrency; } private static <T, R> Observable<Observable<R>> setupScalarToScalarStage(ScalarToScalar<T, R> stage, Observable<Observable<T>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up ScalarToScalar stage with input type: {}", inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { return executeInnersInParallel( source, stage.getComputation(), context, false, Integer.MAX_VALUE, resolveStageConcurrency(context, stage.getConcurrency())); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<Observable<T>> merged = Observable.just(Observable.merge(source)); return executeInners(merged, stage.getComputation(), context, false, Integer.MAX_VALUE); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } private static <K, T, R> Observable<Observable<GroupedObservable<String, R>>> setupScalarToKeyStage(ScalarToKey<K, T, R> stage, Observable<Observable<T>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up ScalarToKey stage with input type: " + inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { return executeInnersInParallel(source, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds(), resolveStageConcurrency(context, stage.getConcurrency())); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<Observable<T>> merged = Observable.just(Observable.merge(source)); return executeInners(merged, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds()); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } // NJ private static <K, T, R> Observable<Observable<MantisGroup<String, R>>> setupScalarToGroupStage(ScalarToGroup<K, T, R> stage, Observable<Observable<T>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up ScalarToGroup stage with input type: " + inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { return executeInnersInParallel(source, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds(),resolveStageConcurrency(context, stage.getConcurrency())); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<Observable<T>> merged = Observable.just(Observable.merge(source)); return executeInners(merged, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds()); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } private static <K1, T, K2, R> Observable<Observable<GroupedObservable<K2, R>>> setupKeyToKeyStage(KeyToKey<K1, T, K2, R> stage, Observable<Observable<GroupedObservable<K1, T>>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up KeyToKey stage with input type: " + inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { throw new RuntimeException("Concurrency is not a supported input strategy for KeyComputation"); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<GroupedObservable<K1, T>> shuffled = Groups.flatten(source); return executeGroupsInParallel(shuffled, stage.getComputation(), context, stage.getKeyExpireTimeSeconds()); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } private static <K1, T, K2, R> Observable<Observable<MantisGroup<K2, R>>> setupGroupToGroupStage(GroupToGroup<K1, T, K2, R> stage, Observable<Observable<MantisGroup<K1, T>>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up GroupToGroup stage with input type: " + inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { throw new RuntimeException("Concurrency is not a supported input strategy for KeyComputation"); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<Observable<MantisGroup<K1, T>>> merged = Observable.just(Observable.merge(source)); return executeMantisGroups(merged, stage.getComputation(), context, stage.getKeyExpireTimeSeconds()); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } // NJ private static <K, T, R> Observable<Observable<R>> setupKeyToScalarStage(KeyToScalar<K, T, R> stage, Observable<Observable<MantisGroup<K, T>>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up KeyToScalar stage with input type: " + inputType); // need to 'shuffle' groups across observables into // single observable<GroupedObservable> Observable<GroupedObservable<K, T>> shuffled = Groups.flattenMantisGroupsToGroupedObservables(source); return executeGroupsInParallel(shuffled, stage.getComputation(), context, stage.getKeyExpireTimeSeconds()); } // NJ private static <K, T, R> Observable<Observable<R>> setupGroupToScalarStage(GroupToScalar<K, T, R> stage, Observable<Observable<MantisGroup<K, T>>> source, Context context) { StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy(); logger.info("Setting up GroupToScalar stage with input type: " + inputType); // check if job overrides the default input strategy if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) { logger.info("Execute Groups in PARALLEL!!!!"); return executeMantisGroupsInParallel(source, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds(),resolveStageConcurrency(context, stage.getConcurrency())); } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) { Observable<Observable<MantisGroup<K, T>>> merged = Observable.just(Observable.merge(source)); return executeMantisGroups(merged, stage.getComputation(), context, stage.getKeyExpireTimeSeconds()); } else { throw new RuntimeException("Unsupported input type: " + inputType.name()); } } @SuppressWarnings( {"rawtypes", "unchecked"}) public static <K, T, R> Closeable executeIntermediate(WorkerConsumer consumer, final StageConfig<T, R> stage, WorkerPublisher publisher, final Context context) { if (consumer == null) { throw new IllegalArgumentException("consumer cannot be null"); } if (stage == null) { throw new IllegalArgumentException("stage cannot be null"); } if (publisher == null) { throw new IllegalArgumentException("producer cannot be null"); } Observable<?> toSink = null; if (stage instanceof ScalarToScalar) { ScalarToScalar scalarStage = (ScalarToScalar) stage; Observable<Observable<T>> source = consumer.start(scalarStage); toSink = setupScalarToScalarStage(scalarStage, source, context); } else if (stage instanceof ScalarToKey) { ScalarToKey scalarStage = (ScalarToKey) stage; Observable<Observable<T>> source = consumer.start(scalarStage); toSink = setupScalarToKeyStage(scalarStage, source, context); } // NJ else if (stage instanceof ScalarToGroup) { ScalarToGroup scalarStage = (ScalarToGroup) stage; Observable<Observable<T>> source = consumer.start(scalarStage); toSink = setupScalarToGroupStage(scalarStage, source, context); } else if (stage instanceof KeyToKey) { KeyToKey keyToKey = (KeyToKey) stage; Observable<Observable<GroupedObservable<K, T>>> source = consumer.start(keyToKey); toSink = setupKeyToKeyStage(keyToKey, source, context); } else if (stage instanceof GroupToGroup) { GroupToGroup groupToGroup = (GroupToGroup) stage; Observable<Observable<MantisGroup<K, T>>> source = consumer.start(groupToGroup); toSink = setupGroupToGroupStage(groupToGroup, source, context); } else if (stage instanceof KeyToScalar) { KeyToScalar scalarToKey = (KeyToScalar) stage; Observable<Observable<MantisGroup<K, T>>> source = consumer.start(scalarToKey); toSink = setupKeyToScalarStage(scalarToKey, source, context); } else if (stage instanceof GroupToScalar) { GroupToScalar groupToScalar = (GroupToScalar) stage; Observable<Observable<MantisGroup<K, T>>> source = consumer.start(groupToScalar); toSink = setupGroupToScalarStage(groupToScalar, source, context); } publisher.start(stage, toSink); // the ordering is important here as we want to first close the sinks so that the subscriptions // are first cut off before closing the sources. return Closeables.combine(publisher, consumer); } @SuppressWarnings( {"rawtypes", "unchecked"}) public static Closeable executeSink(WorkerConsumer consumer, StageConfig stage, SinkHolder sink, PortSelector portSelector, RxMetrics rxMetrics, Context context, Action0 sinkObservableCompletedCallback, final Action0 onSinkSubscribe, final Action0 onSinkUnsubscribe, Action0 observableOnCompleteCallback, Action1<Throwable> observableOnErrorCallback) { WorkerPublisher sinkPublisher = new SinkPublisher(sink, portSelector, context, sinkObservableCompletedCallback, onSinkSubscribe, onSinkUnsubscribe, observableOnCompleteCallback, observableOnErrorCallback); return executeIntermediate(consumer, stage, sinkPublisher, context); } }
8,729
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/WorkerConsumerRemoteObservable.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 io.mantisrx.runtime.executor; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.runtime.*; import io.reactivex.mantis.remote.observable.ConnectToGroupedObservable; import io.reactivex.mantis.remote.observable.ConnectToObservable; import io.reactivex.mantis.remote.observable.DynamicConnectionSet; import io.reactivex.mantis.remote.observable.EndpointInjector; import io.reactivex.mantis.remote.observable.reconciliator.Reconciliator; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; public class WorkerConsumerRemoteObservable<T, R> implements WorkerConsumer<T> { private static final Logger logger = LoggerFactory.getLogger(WorkerConsumerRemoteObservable.class); private final String name; private final EndpointInjector injector; private DynamicConnectionSet<T> connectionSet; private Reconciliator<T> reconciliator; public WorkerConsumerRemoteObservable(String name, EndpointInjector endpointInjector) { this.name = name; this.injector = endpointInjector; } @SuppressWarnings( {"rawtypes", "unchecked"}) @Override public Observable<Observable<T>> start(StageConfig<T, ?> stage) { if (stage instanceof KeyToKey || stage instanceof KeyToScalar || stage instanceof GroupToScalar || stage instanceof GroupToGroup) { logger.info("Remote connection to stage " + name + " is KeyedStage"); ConnectToGroupedObservable.Builder connectToBuilder = new ConnectToGroupedObservable.Builder() .name(name) // need to include index offset here .keyDecoder(stage.getInputKeyCodec()) .valueDecoder(stage.getInputCodec()) .subscribeAttempts(30); // max retry before failure connectionSet = DynamicConnectionSet.createMGO(connectToBuilder); } else if (stage instanceof ScalarToScalar || stage instanceof ScalarToKey || stage instanceof ScalarToGroup) { logger.info("Remote connection to stage " + name + " is ScalarStage"); ConnectToObservable.Builder connectToBuilder = new ConnectToObservable.Builder() .name(name) .decoder(stage.getInputCodec()) .subscribeAttempts(30); // max retry before failure connectionSet = DynamicConnectionSet.create(connectToBuilder); } else { throw new RuntimeException("Unsupported stage type: " + stage); } reconciliator = new Reconciliator.Builder() .name("worker2worker_" + name) .connectionSet(connectionSet) .injector(injector) .build(); registerMetrics(reconciliator.getMetrics()); registerMetrics(connectionSet.getConnectionMetrics()); return reconciliator.observables(); } private void registerMetrics(Metrics metrics) { MetricsRegistry.getInstance().registerAndGet(metrics); } @Override public void close() throws IOException { } }
8,730
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/PortSelector.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 io.mantisrx.runtime.executor; public interface PortSelector { public int acquirePort(); }
8,731
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/LocalJobExecutorNetworked.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 io.mantisrx.runtime.executor; import io.mantisrx.common.MantisProperties; import io.mantisrx.common.WorkerPorts; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.MetricsServer; import io.mantisrx.common.metrics.netty.MantisNettyEventsListenerFactory; import io.mantisrx.common.network.Endpoint; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MachineDefinitions; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.SinkHolder; import io.mantisrx.runtime.SourceHolder; import io.mantisrx.runtime.StageConfig; import io.mantisrx.runtime.WorkerInfo; import io.mantisrx.runtime.WorkerMap; import io.mantisrx.runtime.command.CommandException; import io.mantisrx.runtime.command.ValidateJob; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.descriptor.StageSchedulingInfo; import io.mantisrx.runtime.lifecycle.Lifecycle; import io.mantisrx.runtime.lifecycle.ServiceLocator; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.ParameterUtils; import io.reactivex.mantis.remote.observable.EndpointChange; import io.reactivex.mantis.remote.observable.EndpointChange.Type; import io.reactivex.mantis.remote.observable.EndpointInjector; import io.reactivex.mantis.remote.observable.RxMetrics; 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.Optional; import java.util.Set; import java.util.concurrent.CountDownLatch; import mantis.io.reactivex.netty.RxNetty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.subjects.BehaviorSubject; public class LocalJobExecutorNetworked { private static final Logger logger = LoggerFactory.getLogger(LocalJobExecutorNetworked.class); private static final int numPartitions = 1; private static final Action0 nullAction = () -> System.exit(0); private LocalJobExecutorNetworked() {} @SuppressWarnings("rawtypes") private static void startSource(int index, int port, int workersAtNextStage, SourceHolder source, StageConfig stage, Context context, Observable<Integer> stageWorkersObservable) { logger.debug("Creating source publisher on port " + port); WorkerPublisherRemoteObservable publisher = new WorkerPublisherRemoteObservable<>(port, null, Observable.just(workersAtNextStage * numPartitions), null); // name is set to null, defaul // to start job StageExecutors.executeSource(index, source, stage, publisher, context, stageWorkersObservable); } @SuppressWarnings( {"rawtypes", "unchecked"}) private static void startIntermediate(int[] previousStagePorts, int port, StageConfig stage, Context context, int workerIndex, int workersAtNextStage, int stageNumber, int workersAtPreviousStage) { if (logger.isDebugEnabled()) { StringBuilder portsToString = new StringBuilder(); for (int previousPort : previousStagePorts) { portsToString.append(previousPort + " "); } logger.debug("Creating intermediate consumer connecting to publishers on ports " + portsToString); } Observable<Set<Endpoint>> endpoints = staticEndpoints(previousStagePorts, stageNumber, workerIndex, numPartitions); WorkerConsumerRemoteObservable intermediateConsumer = new WorkerConsumerRemoteObservable(null, // name=null local staticInjector(endpoints)); logger.debug("Creating intermediate publisher on port " + port); WorkerPublisherRemoteObservable intermediatePublisher = new WorkerPublisherRemoteObservable<>(port, null, Observable.just(workersAtNextStage * numPartitions), null); // name is null for local StageExecutors.executeIntermediate(intermediateConsumer, stage, intermediatePublisher, context); } @SuppressWarnings( {"rawtypes", "unchecked"}) private static void startSink(StageConfig previousStage, int[] previousStagePorts, StageConfig stage, PortSelector portSelector, SinkHolder sink, Context context, Action0 sinkObservableCompletedCallback, Action0 sinkObservableTerminatedCompletedCallback, Action1<Throwable> sinkObservableErrorCallback, int stageNumber, int workerIndex, int workersAtPreviousStage) { if (logger.isDebugEnabled()) { StringBuilder portsToString = new StringBuilder(); for (int previousPort : previousStagePorts) { portsToString.append(previousPort + " "); } logger.debug("Creating sink consumer connecting to publishers on ports " + portsToString); } Observable<Set<Endpoint>> endpoints = staticEndpoints(previousStagePorts, stageNumber, workerIndex, numPartitions); WorkerConsumerRemoteObservable sinkConsumer = new WorkerConsumerRemoteObservable(null, // name=null for local staticInjector(endpoints)); StageExecutors.executeSink(sinkConsumer, stage, sink, portSelector, new RxMetrics(), context, sinkObservableTerminatedCompletedCallback, null, null, sinkObservableCompletedCallback, sinkObservableErrorCallback); } public static Map<String, Object> checkAndGetParameters(Map<String, ParameterDefinition<?>> parameterDefinitions, Parameter... parameters) throws IllegalArgumentException { Map<String, Parameter> indexedParameters = new HashMap<>(); for (Parameter parameter : parameters) { indexedParameters.put(parameter.getName(), parameter); } return ParameterUtils.checkThenCreateState(parameterDefinitions, indexedParameters); } @SuppressWarnings( {"rawtypes", "unchecked"}) public static void execute(Job job, Parameter... parameters) throws IllegalMantisJobException { List<StageConfig> stages = job.getStages(); SchedulingInfo.Builder builder = new SchedulingInfo.Builder(); for (@SuppressWarnings("unused") StageConfig stage : stages) { builder.singleWorkerStage(MachineDefinitions.micro()); } builder.numberOfStages(stages.size()); execute(job, builder.build(), parameters); } @SuppressWarnings( {"rawtypes", "unchecked"}) public static void execute(Job job, SchedulingInfo schedulingInfo, Parameter... parameters) throws IllegalMantisJobException { // validate job try { new ValidateJob(job).execute(); } catch (CommandException e) { throw new IllegalMantisJobException(e); } // execute job List<StageConfig> stages = job.getStages(); final SourceHolder source = job.getSource(); final SinkHolder sink = job.getSink(); final PortSelector portSelector = new PortSelectorInRange(8000, 9000); // register netty metrics RxNetty.useMetricListenersFactory(new MantisNettyEventsListenerFactory()); // start our metrics server MetricsServer metricsServer = new MetricsServer(portSelector.acquirePort(), 1, Collections.EMPTY_MAP); metricsServer.start(); Lifecycle lifecycle = job.getLifecycle(); lifecycle.startup(); // create job context Map parameterDefinitions = job.getParameterDefinitions(); final String user = Optional.ofNullable(MantisProperties.getProperty("USER")).orElse( "userUnknown"); String jobId = String.format("localJob-%s-%d", user, (int) (Math.random() * 10000)); logger.info("jobID {}", jobId); final ServiceLocator serviceLocator = lifecycle.getServiceLocator(); int numInstances = schedulingInfo.forStage(1).getNumberOfInstances(); BehaviorSubject<Integer> workersInStageOneObservable = BehaviorSubject.create(numInstances); BehaviorSubject<WorkerMap> workerMapObservable = BehaviorSubject.create(); if (stages.size() == 1) { // single stage job final StageConfig stage = stages.get(0); // use latch to wait for all instances to complete final CountDownLatch waitUntilAllCompleted = new CountDownLatch(numInstances); Action0 countDownLatchOnComplete = new Action0() { @Override public void call() { waitUntilAllCompleted.countDown(); } }; Action0 nullOnCompleted = new Action0() { @Override public void call() {} }; Action1<Throwable> nullOnError = new Action1<Throwable>() { @Override public void call(Throwable t) {} }; Map<Integer, List<WorkerInfo>> workerInfoMap = new HashMap<>(); List<WorkerInfo> workerInfoList = new ArrayList<>(); // run for num of instances for (int i = 0; i < numInstances; i++) { WorkerPorts workerPorts = new WorkerPorts(portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort()); WorkerInfo workerInfo = new WorkerInfo(jobId, jobId, 1, i, i + 1, MantisJobDurationType.Perpetual, "localhost", workerPorts); workerInfoList.add(workerInfo); Context context = new Context( ParameterUtils.createContextParameters(parameterDefinitions, parameters), lifecycle.getServiceLocator(), //new WorkerInfo(jobId, jobId, 1, i, i, MantisJobDurationType.Perpetual, "localhost", new ArrayList<>(),-1,-1), workerInfo, MetricsRegistry.getInstance(), () -> { System.exit(0); }, workerMapObservable, Thread.currentThread().getContextClassLoader()); // workers for stage 1 workerInfoMap.put(1, workerInfoList); workerMapObservable.onNext(new WorkerMap(workerInfoMap)); StageExecutors.executeSingleStageJob(source, stage, sink, () -> workerInfo.getWorkerPorts().getSinkPort(), new RxMetrics(), context, countDownLatchOnComplete, i, workersInStageOneObservable, null, null, nullOnCompleted, nullOnError); } // wait for all instances to complete try { waitUntilAllCompleted.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { // multi-stage job int workerNumber = 0; // start source stages StageConfig currentStage = stages.get(0); StageConfig previousStage = null; StageSchedulingInfo currentStageScalingInfo = schedulingInfo.forStage(1); StageSchedulingInfo nextStageScalingInfo = schedulingInfo.forStage(2); int[] previousPorts = new int[currentStageScalingInfo.getNumberOfInstances()]; // num ports Map<Integer, List<WorkerInfo>> workerInfoMap = new HashMap<>(); List<WorkerInfo> workerInfoList = new ArrayList<>(); for (int i = 0; i < currentStageScalingInfo.getNumberOfInstances(); i++) { WorkerPorts workerPorts = new WorkerPorts(portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort()); WorkerInfo workerInfo = new WorkerInfo(jobId, jobId, 1, i, i + 1, MantisJobDurationType.Perpetual, "localhost", workerPorts); workerInfoList.add(workerInfo); //int sourcePort = portSelector.acquirePort(); int sourcePort = workerInfo.getWorkerPorts().getSinkPort(); previousPorts[i] = sourcePort; Context context = new Context( ParameterUtils.createContextParameters(parameterDefinitions, parameters), serviceLocator, workerInfo, MetricsRegistry.getInstance(), nullAction, workerMapObservable, Thread.currentThread().getContextClassLoader()); startSource(i, sourcePort, nextStageScalingInfo.getNumberOfInstances(), job.getSource(), currentStage, context, workersInStageOneObservable); } // workers for stage 1 workerInfoMap.put(1, workerInfoList); workerMapObservable.onNext(new WorkerMap(workerInfoMap)); // start intermediate stages, all but last stage for (int i = 1; i < stages.size() - 1; i++) { previousStage = currentStage; StageSchedulingInfo previousStageScalingInfo = schedulingInfo.forStage(i); currentStageScalingInfo = schedulingInfo.forStage(i + 1); // stages indexed starting at 1 currentStage = stages.get(i); nextStageScalingInfo = schedulingInfo.forStage(i + 2); // stages indexed starting at 1 int[] currentPorts = new int[currentStageScalingInfo.getNumberOfInstances()]; workerInfoList = new ArrayList<>(); for (int j = 0; j < currentStageScalingInfo.getNumberOfInstances(); j++) { WorkerPorts workerPorts = new WorkerPorts(portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort()); WorkerInfo workerInfo = new WorkerInfo(jobId, jobId, i + 1, j, workerNumber++, MantisJobDurationType.Perpetual, "localhost", workerPorts); workerInfoList.add(workerInfo); //int port = portSelector.acquirePort(); int port = workerInfo.getWorkerPorts().getSinkPort(); currentPorts[j] = port; Context context = new Context( ParameterUtils.createContextParameters(parameterDefinitions, parameters), serviceLocator, workerInfo, MetricsRegistry.getInstance(), nullAction, workerMapObservable, Thread.currentThread().getContextClassLoader()); startIntermediate(previousPorts, port, currentStage, context, j, nextStageScalingInfo.getNumberOfInstances(), i, previousStageScalingInfo.getNumberOfInstances()); } // workers for current stage workerInfoMap.put(i + 1, workerInfoList); workerMapObservable.onNext(new WorkerMap(workerInfoMap)); previousPorts = currentPorts; } // start sink stage StageSchedulingInfo previousStageScalingInfo = schedulingInfo.forStage(stages.size() - 1); previousStage = stages.get(stages.size() - 2); currentStage = stages.get(stages.size() - 1); currentStageScalingInfo = schedulingInfo.forStage(stages.size()); numInstances = currentStageScalingInfo.getNumberOfInstances(); // use latch to wait for all instances to complete final CountDownLatch waitUntilAllCompleted = new CountDownLatch(numInstances); Action0 countDownLatchOnTerminated = new Action0() { @Override public void call() { waitUntilAllCompleted.countDown(); } }; Action0 nullOnCompleted = new Action0() { @Override public void call() {} }; Action1<Throwable> nullOnError = new Action1<Throwable>() { @Override public void call(Throwable t) {} }; workerInfoList = new ArrayList<>(); for (int i = 0; i < numInstances; i++) { WorkerPorts workerPorts = new WorkerPorts(portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort(), portSelector.acquirePort()); WorkerInfo workerInfo = new WorkerInfo(jobId, jobId, stages.size(), i, workerNumber++, MantisJobDurationType.Perpetual, "localhost", workerPorts); workerInfoList.add(workerInfo); Context context = new Context( ParameterUtils.createContextParameters(parameterDefinitions, parameters), serviceLocator, workerInfo, MetricsRegistry.getInstance(), nullAction, workerMapObservable, Thread.currentThread().getContextClassLoader()); startSink(previousStage, previousPorts, currentStage, () -> workerInfo.getWorkerPorts().getSinkPort(), sink, context, countDownLatchOnTerminated, nullOnCompleted, nullOnError, stages.size(), i, previousStageScalingInfo.getNumberOfInstances()); } workerInfoMap.put(stages.size(), workerInfoList); workerMapObservable.onNext(new WorkerMap(workerInfoMap)); // wait for all instances to complete try { waitUntilAllCompleted.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } lifecycle.shutdown(); metricsServer.shutdown(); } private static Observable<Set<Endpoint>> staticEndpoints(final int[] ports, final int stageNum, final int workerIndex, final int numPartitions) { return Observable.create(new OnSubscribe<Set<Endpoint>>() { @Override public void call(Subscriber<? super Set<Endpoint>> subscriber) { Set<Endpoint> endpoints = new HashSet<>(); for (int i = 0; i < ports.length; i++) { int port = ports[i]; for (int j = 1; j <= numPartitions; j++) { Endpoint endpoint = new Endpoint("localhost", port, "stage_" + stageNum + "_index_" + workerIndex + "_partition_" + j); logger.info("adding static endpoint:" + endpoint); endpoints.add(endpoint); } } subscriber.onNext(endpoints); subscriber.onCompleted(); } }); } private static EndpointInjector staticInjector(final Observable<Set<Endpoint>> endpointsToAdd) { return new EndpointInjector() { @Override public Observable<EndpointChange> deltas() { return endpointsToAdd.flatMap(new Func1<Set<Endpoint>, Observable<EndpointChange>>() { @Override public Observable<EndpointChange> call(Set<Endpoint> t1) { return Observable.from(t1) .map(new Func1<Endpoint, EndpointChange>() { @Override public EndpointChange call(Endpoint t1) { logger.info("injected endpoint:" + t1); return new EndpointChange(Type.add, new Endpoint(t1.getHost(), t1.getPort(), t1.getSlotId())); } }); } }); } }; } }
8,732
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/PortSelectorInRange.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 io.mantisrx.runtime.executor; import io.reactivex.mantis.remote.observable.PortSelectorWithinRange; public class PortSelectorInRange implements PortSelector { private PortSelectorWithinRange portSelector; public PortSelectorInRange(int start, int end) { this.portSelector = new PortSelectorWithinRange(start, end); } @Override public int acquirePort() { return portSelector.acquirePort(); } }
8,733
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/WorkerPublisherRemoteObservable.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 io.mantisrx.runtime.executor; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.properties.MantisPropertiesLoader; import io.mantisrx.runtime.GroupToGroup; import io.mantisrx.runtime.GroupToScalar; import io.mantisrx.runtime.KeyToKey; import io.mantisrx.runtime.KeyToScalar; import io.mantisrx.runtime.KeyValueStageConfig; import io.mantisrx.runtime.ScalarToGroup; import io.mantisrx.runtime.ScalarToKey; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.StageConfig; import io.mantisrx.server.core.ServiceRegistry; import io.mantisrx.shaded.com.google.common.base.Preconditions; import io.reactivex.mantis.network.push.HashFunctions; import io.reactivex.mantis.network.push.KeyValuePair; import io.reactivex.mantis.network.push.LegacyTcpPushServer; import io.reactivex.mantis.network.push.PushServers; import io.reactivex.mantis.network.push.Routers; import io.reactivex.mantis.network.push.ServerConfig; import io.reactivex.mantis.remote.observable.RemoteRxServer; import io.reactivex.mantis.remote.observable.RxMetrics; import io.reactivex.mantis.remote.observable.ServeNestedObservable; import io.reactivex.mantis.remote.observable.slotting.RoundRobin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; /** * Execution of WorkerPublisher that publishes the stream to the next stage. * * @param <T> incoming codec */ public class WorkerPublisherRemoteObservable<T> implements WorkerPublisher<T> { private static final Logger logger = LoggerFactory.getLogger(WorkerPublisherRemoteObservable.class); private final String name; private final int serverPort; private RemoteRxServer server; private final MantisPropertiesLoader propService; private String jobName; public WorkerPublisherRemoteObservable(int serverPort, String name, Observable<Integer> minConnectionsToSubscribe, String jobName) { this.name = name; this.serverPort = serverPort; this.propService = ServiceRegistry.INSTANCE.getPropertiesService(); this.jobName = jobName; } @SuppressWarnings( {"rawtypes", "unchecked"}) @Override public void start(final StageConfig<?, T> stage, Observable<Observable<T>> toServe) { RemoteRxServer.Builder serverBuilder = new RemoteRxServer.Builder(); if (stage instanceof KeyValueStageConfig) { LegacyTcpPushServer modernServer = startKeyValueStage((KeyValueStageConfig<?, ?, T>) stage, toServe); server = new LegacyRxServer<>(modernServer); } else if (stage instanceof ScalarToScalar || stage instanceof KeyToScalar || stage instanceof GroupToScalar) { if (runNewW2Wserver(jobName)) { logger.info("Modern server setup for name: " + name + " type: Scalarstage"); Func1<T, byte[]> encoder = t1 -> stage.getOutputCodec().encode(t1); ServerConfig<T> config = new ServerConfig.Builder<T>() .name(name) .port(serverPort) .metricsRegistry(MetricsRegistry.getInstance()) .router(Routers.roundRobinLegacyTcpProtocol(name, encoder)) .build(); final LegacyTcpPushServer<T> modernServer = PushServers.infiniteStreamLegacyTcpNested(config, toServe); // support legacy server interface server = new LegacyRxServer<>(modernServer); } else { logger.info("Legacy server setup for name: " + name + " type: Scalarstage"); RoundRobin slotting = new RoundRobin(); serverBuilder .addObservable(new ServeNestedObservable.Builder() .name(name) .encoder(stage.getOutputCodec()) .observable(toServe) // going up stream. .slottingStrategy(slotting) .build()); MetricsRegistry.getInstance().registerAndGet(slotting.getMetrics()); server = serverBuilder .port(serverPort) .build(); } } else { throw new RuntimeException("Unsupported stage type: " + stage); } server.start(); } private <K> LegacyTcpPushServer<KeyValuePair<K, T>> startKeyValueStage(KeyValueStageConfig<?, K, T> stage, Observable<Observable<T>> toServe) { Preconditions.checkArgument(runNewW2WserverGroups(jobName), String.format("Need to use new worker2worker server group for jobName %s", jobName)); logger.info("Modern server setup for name: {} type: Keyedstage", name); long expiryTimeInSecs = Long.MAX_VALUE; if (stage instanceof KeyToKey) { expiryTimeInSecs = ((KeyToKey) stage).getKeyExpireTimeSeconds(); } else if (stage instanceof ScalarToKey) { expiryTimeInSecs = ((ScalarToKey) stage).getKeyExpireTimeSeconds(); } Func1<T, byte[]> valueEncoder = t1 -> stage.getOutputCodec().encode(t1); Func1<K, byte[]> keyEncoder = t1 -> stage.getOutputKeyCodec().encode(t1); ServerConfig<KeyValuePair<K, T>> config = new ServerConfig.Builder<KeyValuePair<K, T>>() .name(name) .port(serverPort) .metricsRegistry(MetricsRegistry.getInstance()) .numQueueConsumers(numConsumerThreads()) .maxChunkSize(maxChunkSize()) .maxChunkTimeMSec(maxChunkTimeMSec()) .bufferCapacity(bufferCapacity()) .useSpscQueue(useSpsc()) .router(Routers.consistentHashingLegacyTcpProtocol(jobName, keyEncoder, valueEncoder)) .build(); if (stage instanceof ScalarToGroup || stage instanceof GroupToGroup) { return PushServers.infiniteStreamLegacyTcpNestedMantisGroup( config, (Observable) toServe, expiryTimeInSecs, keyEncoder, HashFunctions.ketama()); } // ScalarToKey or KeyTKey return PushServers.infiniteStreamLegacyTcpNestedGroupedObservable( config, (Observable) toServe, expiryTimeInSecs, keyEncoder, HashFunctions.ketama()); } private boolean useSpsc() { String stringValue = propService.getStringValue("mantis.w2w.spsc", "false"); return Boolean.parseBoolean(stringValue); } private int bufferCapacity() { String stringValue = propService.getStringValue("mantis.w2w.toKeyBuffer", "50000"); return Integer.parseInt(stringValue); } private int maxChunkTimeMSec() { String stringValue = propService.getStringValue("mantis.w2w.toKeyMaxChunkTimeMSec", "250"); return Integer.parseInt(stringValue); } private int maxChunkSize() { String stringValue = propService.getStringValue("mantis.w2w.toKeyMaxChunkSize", "1000"); return Integer.parseInt(stringValue); } private int numConsumerThreads() { // num threads to read/process from consumer queue String stringValue = propService.getStringValue("mantis.w2w.toKeyThreads", "1"); return Integer.parseInt(stringValue); } private boolean runNewW2Wserver(String jobName) { String legacyServerString = propService.getStringValue("mantis.w2w.newServerImplScalar", "true"); String legacyServerStringPerJob = propService.getStringValue(jobName + ".mantis.w2w.newServerImplScalar", "false"); return Boolean.parseBoolean(legacyServerString) || Boolean.parseBoolean(legacyServerStringPerJob); } private boolean runNewW2WserverGroups(String jobName) { String legacyServerString = propService.getStringValue("mantis.w2w.newServerImplKeyed", "true"); String legacyServerStringPerJob = propService.getStringValue(jobName + ".mantis.w2w.newServerImplKeyed", "false"); return Boolean.parseBoolean(legacyServerString) || Boolean.parseBoolean(legacyServerStringPerJob); } @Override public void close() { server.shutdown(); } public RemoteRxServer getServer() { return server; } @Override public RxMetrics getMetrics() { return server.getMetrics(); } private static class LegacyRxServer<T> extends RemoteRxServer { private final LegacyTcpPushServer<T> modernServer; public LegacyRxServer(LegacyTcpPushServer<T> modernServer) { this.modernServer = modernServer; } @Override public void start() { this.modernServer.start(); } @Override public void startAndWait() { } @Override public void shutdown() { modernServer.shutdown(); } @Override public void blockUntilServerShutdown() { modernServer.blockUntilShutdown(); } } }
8,734
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/SinkPublisher.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 io.mantisrx.runtime.executor; import io.mantisrx.common.metrics.rx.MonitorOperator; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.PortRequest; import io.mantisrx.runtime.SinkHolder; import io.mantisrx.runtime.StageConfig; import io.mantisrx.runtime.sink.Sink; import io.reactivex.mantis.remote.observable.RxMetrics; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; /** * Implementation that publishes the results of a stage to a sink such as an SSE port. * @param <T> type of the data-item that's getting consumed by the sink. */ public class SinkPublisher<T> implements WorkerPublisher<T> { private static final Logger logger = LoggerFactory.getLogger(SinkPublisher.class); private final SinkHolder<T> sinkHolder; private final PortSelector portSelector; private final Context context; private final Action0 observableTerminatedCallback; private final Action0 onSubscribeAction; private final Action0 onUnsubscribeAction; private final Action0 observableOnCompleteCallback; private final Action1<Throwable> observableOnErrorCallback; // state created during the lifecycle of the sink. private Subscription eagerSubscription; private Sink<T> sink; public SinkPublisher(SinkHolder<T> sinkHolder, PortSelector portSelector, Context context, Action0 observableTerminatedCallback, Action0 onSubscribeAction, Action0 onUnsubscribeAction, Action0 observableOnCompleteCallback, Action1<Throwable> observableOnErrorCallback) { this.sinkHolder = sinkHolder; this.portSelector = portSelector; this.context = context; this.observableTerminatedCallback = observableTerminatedCallback; this.onSubscribeAction = onSubscribeAction; this.onUnsubscribeAction = onUnsubscribeAction; this.observableOnCompleteCallback = observableOnCompleteCallback; this.observableOnErrorCallback = observableOnErrorCallback; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public void start(StageConfig<?, T> stage, Observable<Observable<T>> observablesToPublish) { sink = sinkHolder.getSinkAction(); int sinkPort = -1; if (sinkHolder.isPortRequested()) { sinkPort = portSelector.acquirePort(); } // apply transform Observable<T> merged = Observable.merge(observablesToPublish); final Observable wrappedO = merged.lift(new MonitorOperator("worker_sink")); Observable o = Observable .create(subscriber -> { logger.info("Got sink subscription with onSubscribeAction={}", onSubscribeAction); wrappedO .doOnCompleted(observableOnCompleteCallback) .doOnError(observableOnErrorCallback) .doOnTerminate(observableTerminatedCallback) .subscribe(subscriber); if (onSubscribeAction != null) { onSubscribeAction.call(); } }) .doOnCompleted(() -> logger.info("Sink observable subscription completed.")) .doOnError(err -> logger.error("Sink observable subscription onError:", err)) .doOnTerminate(() -> logger.info("Sink observable subscription termindated.")) .doOnUnsubscribe(() -> { logger.info("Sink subscriptions clean up, action={}", onUnsubscribeAction); if (onUnsubscribeAction != null) onUnsubscribeAction.call(); }) .share(); if (context.getWorkerInfo().getDurationType() == MantisJobDurationType.Perpetual) { // eager subscribe, don't allow unsubscribe back logger.info("eagerSubscription subscribed for Perpetual job."); eagerSubscription = o.subscribe(); } sink.init(context); sink.call(context, new PortRequest(sinkPort), o); } @Override public RxMetrics getMetrics() {return null;} @Override public void close() throws IOException { try { sink.close(); } finally { sink = null; if (eagerSubscription != null) { eagerSubscription.unsubscribe(); eagerSubscription = null; } } } }
8,735
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/IllegalMantisJobException.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 io.mantisrx.runtime.executor; import io.mantisrx.runtime.command.CommandException; public class IllegalMantisJobException extends RuntimeException { private static final long serialVersionUID = 1L; public IllegalMantisJobException(String string) { super(string); } public IllegalMantisJobException(CommandException e) { super(e); } }
8,736
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/executor/WorkerConsumer.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 io.mantisrx.runtime.executor; import io.mantisrx.runtime.StageConfig; import java.io.Closeable; import rx.Observable; /** * Abstraction for executing source observables. Source observables can be of two forms: * 1). ones that consume from previous jobs or act as direct sources somehow * 2). ones that consume from workers in previous stages. * * @param <T> type of the data that the observable emits */ public interface WorkerConsumer<T> extends Closeable { Observable<Observable<T>> start(StageConfig<T, ?> stage); }
8,737
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/LoadValidateCreateZip.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import java.io.File; import lombok.extern.slf4j.Slf4j; @Slf4j public class LoadValidateCreateZip implements Command { private final String jobZipFile; private final String artifactName; private final String version; private final String outputLocation; private final boolean readyForJobMaster; public LoadValidateCreateZip(final String jobZipFile, final String artifactName, final String version, final String outputLocation, final boolean readyForJobMaster) { this.jobZipFile = jobZipFile; this.outputLocation = outputLocation; this.version = version; this.artifactName = artifactName; this.readyForJobMaster = readyForJobMaster; } public static void main(String[] args) throws CommandException { if (args.length < 4) { System.err.println("usage: zipFile artifactName version outputLocation"); System.exit(1); } else { // print all the args log.info("args: "); for (String arg : args) { log.info(arg); } } String jobZipFile = args[0]; String name = args[1]; String version = args[2]; String outputLocation = args[3]; boolean readyForJobMaster = false; if (args.length == 5) { readyForJobMaster = Boolean.parseBoolean(args[4]); } try { new LoadValidateCreateZip(jobZipFile, name, version, outputLocation, readyForJobMaster).execute(); } catch (Exception e) { // print stack trace log.error("Failed with the following exception: ", e); System.exit(1); } } @SuppressWarnings("rawtypes") @Override public void execute() throws CommandException { ReadJobFromZip readCommand = new ReadJobFromZip(jobZipFile, artifactName, version); readCommand.execute(); Job job = readCommand.getJob(); new ValidateJob(job).execute(); File jobDescriptor = new File(outputLocation + "/" + artifactName + "-" + version + ".json"); new CreateJobDescriptorFile(job, jobDescriptor, version, artifactName, readyForJobMaster).execute(); } }
8,738
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/CreateJobDescriptorFile.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 io.mantisrx.runtime.command; import io.mantisrx.common.SystemParameters; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.Metadata; import io.mantisrx.runtime.StageConfig; import io.mantisrx.runtime.descriptor.JobDescriptor; import io.mantisrx.runtime.descriptor.JobInfo; import io.mantisrx.runtime.descriptor.MetadataInfo; import io.mantisrx.runtime.descriptor.ParameterInfo; import io.mantisrx.runtime.descriptor.StageInfo; import io.mantisrx.runtime.parameter.ParameterDefinition; import io.mantisrx.runtime.parameter.ParameterUtils; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; public class CreateJobDescriptorFile implements Command { private final static ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @SuppressWarnings("rawtypes") private final Job job; private final String project; private final String version; private final File descriptorFile; private final boolean readyForJobMaster; @SuppressWarnings("rawtypes") public CreateJobDescriptorFile(final Job job, final File descriptorFile, final String version, final String project) { this(job, descriptorFile, version, project, false); } @SuppressWarnings("rawtypes") public CreateJobDescriptorFile(final Job job, final File descriptorFile, final String version, final String project, final boolean readyForJobMaster) { this.job = job; this.descriptorFile = descriptorFile; this.version = version; this.project = project; this.readyForJobMaster = readyForJobMaster; } private MetadataInfo toMetaDataInfo(Metadata metadata) { MetadataInfo metadataInfo = null; if (metadata != null) { metadataInfo = new MetadataInfo(metadata.getName(), metadata.getDescription()); } return metadataInfo; } @SuppressWarnings("unchecked") @Override public void execute() throws CommandException { Metadata jobMetadata = job.getMetadata(); // create stage info Map<Integer, StageInfo> stagesInfo = new HashMap<>(); List<StageConfig<?, ?>> stages = job.getStages(); int numStages = 0; for (StageConfig<?, ?> stage : stages) { stagesInfo.put(numStages, new StageInfo(numStages, stage.getDescription())); numStages++; } // create parameter info final Map<String, ParameterInfo> parameterInfo = createParameterInfo(job.getParameterDefinitions()); final Map<String, ParameterInfo> systemParameterInfo = createParameterInfo(ParameterUtils.getSystemParameters()); final int totalNumStages = numStages; final Map<String, ParameterInfo> sysParams = systemParameterInfo.entrySet().stream().filter(sysParam -> { for (int stageNum = totalNumStages + 1; stageNum <= SystemParameters.MAX_NUM_STAGES_FOR_JVM_OPTS_OVERRIDE; stageNum++) { if (sysParam.getKey().equals(String.format(SystemParameters.PER_STAGE_JVM_OPTS_FORMAT, stageNum))) { return false; } } return true; }).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); parameterInfo.putAll(sysParams); // create source/sink info Metadata sourceMetadata = job.getSource().getMetadata(); MetadataInfo sourceMetadataInfo = toMetaDataInfo(sourceMetadata); Metadata sinkMetadata = job.getSink().getMetadata(); MetadataInfo sinkMetadataInfo = toMetaDataInfo(sinkMetadata); JobInfo jobInfo = new JobInfo(jobMetadata.getName(), jobMetadata.getDescription(), numStages, parameterInfo, sourceMetadataInfo, sinkMetadataInfo, stagesInfo); JobDescriptor jobDescriptor = new JobDescriptor(jobInfo, project, version, System.currentTimeMillis(), readyForJobMaster); try { mapper.writeValue(descriptorFile, jobDescriptor); } catch (IOException e) { throw new DescriptorException(e); } } private Map<String, ParameterInfo> createParameterInfo(final Map<String, ParameterDefinition<?>> parameters) { final Map<String, ParameterInfo> parameterInfo = new HashMap<>(); for (Entry<String, ParameterDefinition<?>> entry : parameters.entrySet()) { ParameterDefinition<?> definition = entry.getValue(); String defaultValue = null; if (definition.getDefaultValue() != null) { defaultValue = definition.getDefaultValue().toString(); } parameterInfo.put(entry.getKey(), new ParameterInfo(definition.getName(), definition.getDescription(), defaultValue, definition.getTypeDescription(), definition.getValidator() .getDescription(), definition.isRequired())); } return parameterInfo; } }
8,739
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/ReadJobFromJarException.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 io.mantisrx.runtime.command; public class ReadJobFromJarException extends CommandException { private static final long serialVersionUID = 1L; public ReadJobFromJarException(Throwable t) { super(t); } public ReadJobFromJarException(String string) { super(string); } }
8,740
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/Command.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 io.mantisrx.runtime.command; public interface Command { void execute() throws CommandException; }
8,741
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/ReadJobFromZipException.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 io.mantisrx.runtime.command; public class ReadJobFromZipException extends CommandException { private static final long serialVersionUID = 1L; public ReadJobFromZipException(Throwable t) { super(t); } public ReadJobFromZipException(String string) { super(string); } }
8,742
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/LoadValidateCreate.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import java.io.File; public class LoadValidateCreate implements Command { private final String jobJarFile; private final String artifactName; private final String version; private final String project; private final String outputLocation; public LoadValidateCreate(String jobJarFile, String artifactName, String version, String outputLocation, String project) { this.jobJarFile = jobJarFile; this.outputLocation = outputLocation; this.version = version; this.artifactName = artifactName; this.project = project; } public static void main(String[] args) throws CommandException { if (args.length < 4) { System.err.println("usage: jarFile name version outputLocation project"); System.exit(1); } String jobJarFile = args[0]; String name = args[1]; String version = args[2]; String outputLocation = args[3]; new LoadValidateCreate(jobJarFile, name, version, outputLocation, name).execute(); } @SuppressWarnings("rawtypes") @Override public void execute() throws CommandException { ReadJobFromJar readCommand = new ReadJobFromJar(jobJarFile); readCommand.execute(); Job job = readCommand.getJob(); new ValidateJob(job).execute(); File jobDescriptor = new File(outputLocation + "/" + artifactName + "-" + version + ".json"); new CreateJobDescriptorFile(job, jobDescriptor, version, project).execute(); new CreateZipFile(new File(outputLocation + "/" + artifactName + "-" + version + ".mantis") , new File(jobJarFile), jobDescriptor).execute(); } }
8,743
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/LoadValidateCreateDir.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoadValidateCreateDir implements Command { private static final Logger logger = LoggerFactory.getLogger(LoadValidateCreateDir.class); private final String jarPath; public LoadValidateCreateDir(String jarPath) { this.jarPath = jarPath; } public static void main(String[] args) throws CommandException { if (args.length < 1) { System.err.println("usage: directory to scan"); System.exit(1); } String classpath = System.getProperty("java.class.path"); System.out.println(classpath); // loop through each file in directory and process it String jarPath = args[0]; new LoadValidateCreateDir(jarPath).execute(); System.exit(0); } @SuppressWarnings("rawtypes") @Override public void execute() throws CommandException { File dir = new File(jarPath); File[] directoryListing = dir.listFiles(); if (directoryListing != null) { for (File child : directoryListing) { System.out.println("================================"); // Absolute Path System.out.println("Absolute Path:" + child.getAbsolutePath()); // File name only System.out.println("File name only:" + child.getName()); // JSON file name File fileLoop = new File(child.getAbsolutePath()); System.out.println("Dirname: " + fileLoop.getParent()); System.out.println("Basename: " + fileLoop.getName()); String fileBase = fileLoop.getName().substring(0, fileLoop.getName().lastIndexOf(".")); String fileExtension = fileLoop.getName().substring(fileLoop.getName().lastIndexOf(".") + 1); String jsonFile = fileBase + ".json"; String fileVersion = fileLoop.getName().substring(fileLoop.getName().lastIndexOf("-") + 1, fileLoop.getName().lastIndexOf(".")); System.out.println("fileBase: " + fileBase); System.out.println("fileExtension: " + fileExtension); System.out.println("jsonFile: " + jsonFile); System.out.println("fileVersion: " + fileVersion); try { ReadJobFromJar readCommand = new ReadJobFromJar(child.getAbsolutePath()); readCommand.execute(); Job job = readCommand.getJob(); new ValidateJob(job).execute(); File jobDescriptor = new File(fileLoop.getParent() + "/" + jsonFile); new CreateJobDescriptorFile(job, jobDescriptor, fileVersion, fileBase).execute(); } catch (Exception e) { logger.error("Got an error " + e.getMessage()); System.exit(1); } System.out.println("================================"); } } else { // Handle the case where dir is not really a directory. // Checking dir.isDirectory() above would not be sufficient // to avoid race conditions with another process that deletes // directories. System.out.println("not a dir"); System.exit(1); } } }
8,744
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/ReadJobFromJar.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJobProvider; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.ServiceLoader; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class ReadJobFromJar implements Command { private final String jobJarFile; @SuppressWarnings("rawtypes") private Job job; public ReadJobFromJar(String jobJarFile) { this.jobJarFile = jobJarFile; } @SuppressWarnings("rawtypes") public Job getJob() { return job; } @SuppressWarnings("rawtypes") @Override public void execute() throws CommandException { try { // check jar file for service file JarFile jf = new JarFile(jobJarFile); Enumeration<JarEntry> en = jf.entries(); String serviceFile = "META-INF/services/io.mantisrx.runtime.MantisJobProvider"; boolean serviceFileFound = false; while (en.hasMoreElements()) { JarEntry entry = en.nextElement(); if (serviceFile.equals(entry.getName())) { serviceFileFound = true; } } jf.close(); if (!serviceFileFound) { throw new ReadJobFromJarException("Service file not found in jar at location: META-INF/services/io.mantisrx.runtime.MantisJobProvider"); } // put jar into classpath to get MantisJob instance // Note, hard coded to file protocol ClassLoader cl = URLClassLoader.newInstance(new URL[] {new URL("file://" + jobJarFile)}, Thread.currentThread().getContextClassLoader()); int providerCount = 0; ServiceLoader<MantisJobProvider> provider = ServiceLoader.load(MantisJobProvider.class, cl); for (MantisJobProvider jobProvider : provider) { job = jobProvider.getJobInstance(); providerCount++; } if (providerCount != 1) { throw new ReadJobFromJarException("Provider count not equal to 1 for MantisJobProvider, count: " + providerCount + ". Either no " + "entry exists in META-INF/services/io.mantisrx.runtime.MantisJobProvider, or more than one entry exists." ); } } catch (IOException e) { //MalformedURLException is Subclass of the IOException throw new ReadJobFromJarException(e); } } }
8,745
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/ValidateJob.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.SinkHolder; import io.mantisrx.runtime.SourceHolder; import io.mantisrx.runtime.StageConfig; import java.util.List; public class ValidateJob implements Command { @SuppressWarnings("rawtypes") private final Job job; @SuppressWarnings("rawtypes") public ValidateJob(Job job) { this.job = job; } @SuppressWarnings( {"rawtypes", "unchecked"}) @Override public void execute() throws CommandException { if (job == null) { throw new InvalidJobException("job reference cannot be null"); } SourceHolder source = job.getSource(); if (source == null || source.getSourceFunction() == null) { throw new InvalidJobException("A job requires a source"); } List<StageConfig<?, ?>> stages = job.getStages(); if (stages == null || stages.isEmpty()) { throw new InvalidJobException("A job requires at least one stage"); } int i = 0; for (StageConfig<?, ?> stage : stages) { if (stage == null) { throw new InvalidJobException("Stage cannot be null, for stage number: " + i); } i++; } SinkHolder sink = job.getSink(); if (sink == null || sink.getSinkAction() == null) { throw new InvalidJobException("A job requires a sink"); } } }
8,746
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/ReadJobFromZip.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 io.mantisrx.runtime.command; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJobProvider; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReadJobFromZip implements Command { private static final Logger logger = LoggerFactory.getLogger(ReadJobFromZip.class); private final String jobZipFile; private final String artifactName; private final String version; @SuppressWarnings("rawtypes") private Job job; public ReadJobFromZip(String jobZipFile, String artifactName, String version) { this.jobZipFile = jobZipFile; this.artifactName = artifactName; this.version = version; } @SuppressWarnings("rawtypes") public Job getJob() { return job; } @SuppressWarnings("rawtypes") @Override public void execute() throws CommandException { try { ZipFile zipFile = new ZipFile(jobZipFile); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); String jobProviderFilename = "io.mantisrx.runtime.MantisJobProvider"; boolean jobProviderFound = false; while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); if (!zipEntry.isDirectory() && zipEntry.getName().matches("^.*" + jobProviderFilename + "$")) { jobProviderFound = true; final InputStream mainClassInputStream = zipFile.getInputStream(zipEntry); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(mainClassInputStream)); final String jobProviderClassName = bufferedReader.readLine(); logger.info("loading MantisJobProvider from " + jobProviderClassName); final Class<?> clazz = Class.forName(jobProviderClassName); final MantisJobProvider jobProvider = (MantisJobProvider) clazz.getDeclaredConstructor().newInstance(); job = jobProvider.getJobInstance(); break; } } if (!jobProviderFound) { throw new ReadJobFromZipException("no entries in ZipFile matching jobProvider " + jobProviderFilename); } if (job == null) { throw new ReadJobFromZipException("failed to load job from classname in " + jobProviderFilename); } } catch (IOException | IllegalAccessException | ClassNotFoundException | InstantiationException e) { throw new ReadJobFromZipException(e); } catch (InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } } }
8,747
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/DescriptorException.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 io.mantisrx.runtime.command; public class DescriptorException extends CommandException { private static final long serialVersionUID = 1L; public DescriptorException(Throwable cause) { super(cause); } }
8,748
0
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime
Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/command/CreateZipFile.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 io.mantisrx.runtime.command; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CreateZipFile implements Command { private final File jobJarFile; private final File jobDescriptor; private final File zipFileName; public CreateZipFile(File zipFileName, File jobJarFile, File jobDescriptor) { this.zipFileName = zipFileName; this.jobJarFile = jobJarFile; this.jobDescriptor = jobDescriptor; } private void readBytesFromFile(File file, ZipOutputStream os) throws CommandException { BufferedInputStream is = null; try { is = new BufferedInputStream(Files.newInputStream(Paths.get(file.toURI()))); byte[] in = new byte[1024]; int bytesRead; while ((bytesRead = is.read(in)) > 0) { os.write(in, 0, bytesRead); } } catch (IOException e) { throw new CommandException(e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { throw new CommandException(e); } } } @Override public void execute() throws CommandException { ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName))); ZipEntry jobJarEntry = new ZipEntry(jobJarFile.getName()); out.putNextEntry(jobJarEntry); readBytesFromFile(jobJarFile, out); out.closeEntry(); ZipEntry jobDescriptorEntry = new ZipEntry(jobDescriptor.getName()); out.putNextEntry(jobDescriptorEntry); readBytesFromFile(jobDescriptor, out); out.closeEntry(); } catch (IOException e) { throw new CommandException(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { throw new CommandException(e); } } } } }
8,749
0
Create_ds/mantis/mantis-network/src/test/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/test/java/io/reactivex/mantis/network/push/TimedChunkerTest.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 io.reactivex.mantis.network.push; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TimedChunkerTest { private static Logger logger = LoggerFactory.getLogger(TimedChunkerTest.class); private TestProcessor<Integer> processor; private MonitoredQueue<Integer> monitoredQueue; @BeforeEach public void setup() { monitoredQueue = new MonitoredQueue<>("test-queue", 100, false); processor = new TestProcessor<>(0); } @Test public void testProcessData() throws Exception { TimedChunker<Integer> timedChunker = new TimedChunker<>(monitoredQueue, 100, 500, processor, null); List<Integer> expected = new ArrayList<>(); for (int i = 0; i < 50; i++) { expected.add(i); } ExecutorService service = Executors.newFixedThreadPool(2); Future<Void> chunkerFuture = service.submit(timedChunker); // Send 50 events in 100ms interval. Should take 5s total to send. Future senderFuture = service.submit(() -> { for (int i : expected) { logger.info("sending event {}", i); monitoredQueue.write(i); try { Thread.sleep(100); } catch (InterruptedException ex) { logger.info("sender interrupted", ex); } } }); Thread.sleep(6000); assertTrue(senderFuture.isDone()); chunkerFuture.cancel(true); assertEquals(expected, processor.getProcessed()); } @Test public void testBufferLength() throws Exception { TimedChunker<Integer> timedChunker = new TimedChunker<>(monitoredQueue, 5, 500, processor, null); List<Integer> expected = new ArrayList<>(); for (int i = 0; i < 50; i++) { expected.add(i); } ExecutorService service = Executors.newFixedThreadPool(2); Future<Void> chunkerFuture = service.submit(timedChunker); // Send 50 events in 100ms interval. Should take 5s total to send. Future senderFuture = service.submit(() -> { for (int i : expected) { logger.info("sending event {}", i); monitoredQueue.write(i); try { Thread.sleep(100); } catch (InterruptedException ex) { logger.info("sender interrupted", ex); } } }); Thread.sleep(6000); assertTrue(senderFuture.isDone()); chunkerFuture.cancel(true); assertEquals(expected, processor.getProcessed()); } @Test public void testMaxTime() throws Exception { TimedChunker<Integer> timedChunker = new TimedChunker<>(monitoredQueue, 100, 200, processor, null); List<Integer> expected = new ArrayList<>(); for (int i = 0; i < 50; i++) { expected.add(i); } ExecutorService service = Executors.newFixedThreadPool(2); Future<Void> chunkerFuture = service.submit(timedChunker); // Send 50 events in 100ms interval. Should take 5s total to send. Future senderFuture = service.submit(() -> { for (int i : expected) { logger.info("sending event {}", i); monitoredQueue.write(i); try { Thread.sleep(100); } catch (InterruptedException ex) { logger.info("sender interrupted", ex); } } }); Thread.sleep(6000); assertTrue(senderFuture.isDone()); chunkerFuture.cancel(true); assertEquals(expected, processor.getProcessed()); } @Disabled("flaky test") public void testLongProcessing() throws Exception { // Processing time take longer than drain interval. processor = new TestProcessor<>(400); TimedChunker<Integer> timedChunker = new TimedChunker<>(monitoredQueue, 100, 200, processor, null); List<Integer> expected = new ArrayList<>(); for (int i = 0; i < 50; i++) { expected.add(i); } ExecutorService service = Executors.newFixedThreadPool(2); Future<Void> chunkerFuture = service.submit(timedChunker); // Send 50 events in 100ms interval. Should take 5s total to send. Future senderFuture = service.submit(() -> { for (int i : expected) { logger.info("sending event {}", i); monitoredQueue.write(i); try { Thread.sleep(100); } catch (InterruptedException ex) { logger.info("sender interrupted", ex); } } }); Thread.sleep(6000); assertTrue(senderFuture.isDone()); chunkerFuture.cancel(true); assertEquals(expected, processor.getProcessed()); } public static class TestProcessor<T> extends ChunkProcessor<T> { private ScheduledExecutorService scheduledService = Executors.newSingleThreadScheduledExecutor(); private List<T> processed = new ArrayList(); private long processingTimeMs = 0; public TestProcessor(long processingTimeMs) { super(null); this.processingTimeMs = processingTimeMs; } @Override public void process(ConnectionManager<T> connectionManager, List<T> chunks) { if (processingTimeMs > 0) { ScheduledFuture<Boolean> f = scheduledService.schedule(() -> true, processingTimeMs, TimeUnit.MILLISECONDS); while (!f.isDone()) { } } logger.info("processing {}", chunks); processed.addAll(chunks); } public List<T> getProcessed() { return processed; } } }
8,750
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/PushTrigger.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.Metrics; import rx.functions.Action1; public class PushTrigger<T> { protected MonitoredQueue<T> buffer; protected Action1<MonitoredQueue<T>> doOnStart; protected Action1<MonitoredQueue<T>> doOnStop; protected Metrics metrics; public PushTrigger(Action1<MonitoredQueue<T>> doOnStart, Action1<MonitoredQueue<T>> doOnStop, Metrics metrics) { this.doOnStart = doOnStart; this.doOnStop = doOnStop; this.metrics = metrics; } public void setBuffer(MonitoredQueue<T> buffer) { this.buffer = buffer; } public void start() { doOnStart.call(buffer); } public void stop() { doOnStop.call(buffer); } public Metrics getMetrics() { return metrics; } }
8,751
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ChunkProcessor.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 io.reactivex.mantis.network.push; import java.util.List; public class ChunkProcessor<T> { protected Router<T> router; public ChunkProcessor(Router<T> router) { this.router = router; } public void process(ConnectionManager<T> connectionManager, List<T> chunks) { router.route(connectionManager.connections(), chunks); } }
8,752
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/NamedThreadFactory.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 io.reactivex.mantis.network.push; import java.util.concurrent.ThreadFactory; public class NamedThreadFactory implements ThreadFactory { private int count = 0; private String name; public NamedThreadFactory(String name) { this.name = name; } public Thread newThread(Runnable r) { Thread t = new Thread(r, name + "-" + count++); t.setDaemon(true); return t; } }
8,753
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/PushServers.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 io.reactivex.mantis.network.push; import io.mantisrx.common.MantisGroup; import java.util.List; import java.util.Map; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.GroupedObservable; import rx.subjects.PublishSubject; public class PushServers { private PushServers() {} public static <T> LegacyTcpPushServer<T> infiniteStreamLegacyTcpNested(ServerConfig<T> config, Observable<Observable<T>> o) { final PublishSubject<String> serverSignals = PublishSubject.create(); final String serverName = config.getName(); Action0 onComplete = new ErrorOnComplete(serverSignals, serverName); Action1<Throwable> onError = serverSignals::onError; PushTrigger<T> trigger = ObservableTrigger.oo(serverName, o, onComplete, onError); return new LegacyTcpPushServer<>(trigger, config, serverSignals); } public static <K, V> LegacyTcpPushServer<KeyValuePair<K, V>> infiniteStreamLegacyTcpNestedGroupedObservable(ServerConfig<KeyValuePair<K, V>> config, Observable<Observable<GroupedObservable<K, V>>> go, long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, HashFunction hashFunction) { final PublishSubject<String> serverSignals = PublishSubject.create(); final String serverName = config.getName(); Action0 onComplete = new ErrorOnComplete(serverSignals, serverName); Action1<Throwable> onError = serverSignals::onError; PushTrigger<KeyValuePair<K, V>> trigger = ObservableTrigger.oogo(serverName, go, onComplete, onError, groupExpirySeconds, keyEncoder, hashFunction); return new LegacyTcpPushServer<>(trigger, config, serverSignals); } // NJ public static <K, V> LegacyTcpPushServer<KeyValuePair<K, V>> infiniteStreamLegacyTcpNestedMantisGroup(ServerConfig<KeyValuePair<K, V>> config, Observable<Observable<MantisGroup<K, V>>> go, long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, HashFunction hashFunction) { final PublishSubject<String> serverSignals = PublishSubject.create(); final String serverName = config.getName(); Action0 onComplete = new ErrorOnComplete(serverSignals, serverName); Action1<Throwable> onError = serverSignals::onError; PushTrigger<KeyValuePair<K, V>> trigger = ObservableTrigger.oomgo(serverName, go, onComplete, onError, groupExpirySeconds, keyEncoder, hashFunction); return new LegacyTcpPushServer<>(trigger, config, serverSignals); } public static <T, S> PushServerSse<T, S> infiniteStreamSse(ServerConfig<T> config, Observable<T> o, Func2<Map<String, List<String>>, S, Void> requestPreprocessor, Func2<Map<String, List<String>>, S, Void> requestPostprocessor, final Func2<Map<String, List<String>>, S, Void> subscribeProcessor, S state, boolean supportLegacyMetrics) { final String serverName = config.getName(); final PublishSubject<String> serverSignals = PublishSubject.create(); Action0 onComplete = new ErrorOnComplete(serverSignals, serverName); Action1<Throwable> onError = serverSignals::onError; PushTrigger<T> trigger = ObservableTrigger.o(serverName, o, onComplete, onError); return new PushServerSse<>(trigger, config, serverSignals, requestPreprocessor, requestPostprocessor, subscribeProcessor, state, supportLegacyMetrics); } public static <T> PushServerSse<T, Void> infiniteStreamSse(ServerConfig<T> config, Observable<T> o) { return infiniteStreamSse(config, o, null, null, null, null, false); } private static class ErrorOnComplete implements Action0 { private final PublishSubject<String> serverSignals; private final String serverName; public ErrorOnComplete(PublishSubject<String> serverSignals, String serverName) { this.serverSignals = serverSignals; this.serverName = serverName; } @Override public void call() { serverSignals.onNext("ILLEGAL_STATE_COMPLETED"); throw new IllegalStateException("OnComplete signal received, Server: " + serverName + " is pushing an infinite stream, should not complete"); } } }
8,754
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ObservableTrigger.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 io.reactivex.mantis.network.push; import io.mantisrx.common.MantisGroup; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.reactivx.mantis.operators.DisableBackPressureOperator; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.GroupedObservable; import rx.schedulers.Schedulers; public final class ObservableTrigger { private static final Logger logger = LoggerFactory.getLogger(ObservableTrigger.class); private static Scheduler timeoutScheduler = Schedulers.from(Executors.newFixedThreadPool(5)); private ObservableTrigger() {} private static <T> PushTrigger<T> trigger(final String name, final Observable<T> o, final Action0 doOnComplete, final Action1<Throwable> doOnError) { final AtomicReference<Subscription> subRef = new AtomicReference<>(); final Gauge subscriptionActive; Metrics metrics = new Metrics.Builder() .name("ObservableTrigger_" + name) .addGauge("subscriptionActive") .build(); subscriptionActive = metrics.getGauge("subscriptionActive"); // Share the Observable so we don't create a new Observable on every subscription. final Observable<T> sharedO = o.share(); Action1<MonitoredQueue<T>> doOnStart = queue -> { Subscription oldSub = subRef.getAndSet( sharedO .filter((T t1) -> t1 != null) .doOnSubscribe(() -> { logger.info("Subscription is ACTIVE for observable trigger with name: " + name); subscriptionActive.increment(); }) .doOnUnsubscribe(() -> { logger.info("Subscription is INACTIVE for observable trigger with name: " + name); subscriptionActive.decrement(); }) .subscribe( (T data) -> queue.write(data), (Throwable e) -> { logger.warn("Observable used to push data errored, on server with name: " + name, e); if (doOnError != null) { doOnError.call(e); } }, () -> { logger.info("Observable used to push data completed, on server with name: " + name); if (doOnComplete != null) { doOnComplete.call(); } } ) ); if (oldSub != null) { logger.info("A new subscription is ACTIVE. " + "Unsubscribe from previous subscription observable trigger with name: " + name); oldSub.unsubscribe(); } }; Action1<MonitoredQueue<T>> doOnStop = t1 -> { if (subRef.get() != null) { logger.warn("Connections from next stage has dropped to 0. Do not propagate unsubscribe"); // subRef.get().unsubscribe(); } }; return new PushTrigger<>(doOnStart, doOnStop, metrics); } private static <T> PushTrigger<T> ssetrigger(final String name, final Observable<T> o, final Action0 doOnComplete, final Action1<Throwable> doOnError) { final AtomicReference<Subscription> subRef = new AtomicReference<>(); final Gauge subscriptionActive; Metrics metrics = new Metrics.Builder() .name("ObservableTrigger_" + name) .addGauge("subscriptionActive") .build(); subscriptionActive = metrics.getGauge("subscriptionActive"); Action1<MonitoredQueue<T>> doOnStart = queue -> subRef.set( o .filter((T t1) -> t1 != null) .doOnSubscribe(() -> { logger.info("Subscription is ACTIVE for observable trigger with name: " + name); subscriptionActive.increment(); }) .doOnUnsubscribe(() -> { logger.info("Subscription is INACTIVE for observable trigger with name: " + name); subscriptionActive.decrement(); }) .subscribe( (T data) -> queue.write(data), (Throwable e) -> { logger.warn("Observable used to push data errored, on server with name: " + name, e); if (doOnError != null) { doOnError.call(e); } }, () -> { logger.info("Observable used to push data completed, on server with name: " + name); if (doOnComplete != null) { doOnComplete.call(); } } ) ); Action1<MonitoredQueue<T>> doOnStop = t1 -> { if (subRef.get() != null) { logger.warn("Connections from next stage has dropped to 0 for SSE stage. propagate unsubscribe"); subRef.get().unsubscribe(); } }; return new PushTrigger<>(doOnStart, doOnStop, metrics); } private static <K, V> PushTrigger<KeyValuePair<K, V>> groupTrigger(final String name, final Observable<GroupedObservable<K, V>> o, final Action0 doOnComplete, final Action1<Throwable> doOnError, final long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, final HashFunction hashFunction) { final AtomicReference<Subscription> subRef = new AtomicReference<>(); final Gauge subscriptionActive; Metrics metrics = new Metrics.Builder() .name("ObservableTrigger_" + name) .addGauge("subscriptionActive") .build(); subscriptionActive = metrics.getGauge("subscriptionActive"); // Share the Observable so we don't create a new Observable on every subscription. final Observable<GroupedObservable<K, V>> sharedO = o.share(); Action1<MonitoredQueue<KeyValuePair<K, V>>> doOnStart = queue -> { Subscription oldSub = subRef.getAndSet( sharedO .doOnSubscribe(() -> { logger.info("Subscription is ACTIVE for observable trigger with name: " + name); subscriptionActive.increment(); }) .doOnUnsubscribe(() -> { logger.info("Subscription is INACTIVE for observable trigger with name: " + name); subscriptionActive.decrement(); }) .flatMap((final GroupedObservable<K, V> group) -> { final byte[] keyBytes = keyEncoder.call(group.getKey()); final long keyBytesHashed = hashFunction.computeHash(keyBytes); return group .timeout(groupExpirySeconds, TimeUnit.SECONDS, Observable.empty(), timeoutScheduler) .lift(new DisableBackPressureOperator<V>()) .buffer(250, TimeUnit.MILLISECONDS) .filter((List<V> t1) -> t1 != null && !t1.isEmpty()) .map((List<V> list) -> { List<KeyValuePair<K, V>> keyPairList = new ArrayList<>(list.size()); for (V data : list) { keyPairList.add(new KeyValuePair<>(keyBytesHashed, keyBytes, data)); } return keyPairList; } ); } ) .subscribe( (List<KeyValuePair<K, V>> list) -> { for (KeyValuePair<K, V> data : list) { queue.write(data); } }, (Throwable e) -> { logger.warn("Observable used to push data errored, on server with name: " + name, e); if (doOnError != null) { doOnError.call(e); } }, () -> { logger.info("Observable used to push data completed, on server with name: " + name); if (doOnComplete != null) { doOnComplete.call(); } } ) ); if (oldSub != null) { logger.info("A new subscription is ACTIVE. " + "Unsubscribe from previous subscription observable trigger with name: " + name); oldSub.unsubscribe(); } }; Action1<MonitoredQueue<KeyValuePair<K, V>>> doOnStop = t1 -> { if (subRef.get() != null) { logger.warn("Connections from next stage has dropped to 0. " + "Do not propagate unsubscribe until a new connection is made."); //subRef.get().unsubscribe(); } }; return new PushTrigger<>(doOnStart, doOnStop, metrics); } private static <K, V> PushTrigger<KeyValuePair<K, V>> mantisGroupTrigger(final String name, final Observable<MantisGroup<K, V>> o, final Action0 doOnComplete, final Action1<Throwable> doOnError, final long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, final HashFunction hashFunction) { final AtomicReference<Subscription> subRef = new AtomicReference<>(); final Gauge subscriptionActive; Metrics metrics = new Metrics.Builder() .name("ObservableTrigger_" + name) .addGauge("subscriptionActive") .build(); subscriptionActive = metrics.getGauge("subscriptionActive"); // Share the Observable so we don't create a new Observable on every subscription. final Observable<MantisGroup<K, V>> sharedO = o.share(); Action1<MonitoredQueue<KeyValuePair<K, V>>> doOnStart = queue -> { Subscription oldSub = subRef.getAndSet( sharedO .doOnSubscribe(() -> { logger.info("Subscription is ACTIVE for observable trigger with name: " + name); subscriptionActive.increment(); }) .doOnUnsubscribe(() -> { logger.info("Subscription is INACTIVE for observable trigger with name: " + name); subscriptionActive.decrement(); }) .map((MantisGroup<K, V> data) -> { final byte[] keyBytes = keyEncoder.call(data.getKeyValue()); final long keyBytesHashed = hashFunction.computeHash(keyBytes); return (new KeyValuePair<K, V>(keyBytesHashed, keyBytes, data.getValue())); }) .subscribe( (KeyValuePair<K, V> data) -> queue.write(data), (Throwable e) -> { logger.warn("Observable used to push data errored, on server with name: " + name, e); if (doOnError != null) { doOnError.call(e); } }, () -> { logger.info("Observable used to push data completed, on server with name: " + name); if (doOnComplete != null) { doOnComplete.call(); } } ) ); if (oldSub != null) { logger.info("A new subscription is ACTIVE. " + "Unsubscribe from previous subscription observable trigger with name: " + name); oldSub.unsubscribe(); } }; Action1<MonitoredQueue<KeyValuePair<K, V>>> doOnStop = t1 -> { if (subRef.get() != null) { logger.warn("Connections from next stage has dropped to 0. " + "Do not propagate unsubscribe until a new connection is made."); // subRef.get().unsubscribe(); } }; return new PushTrigger<>(doOnStart, doOnStop, metrics); } public static <T> PushTrigger<T> o(String name, final Observable<T> o, Action0 doOnComplete, Action1<Throwable> doOnError) { return ssetrigger(name, o, doOnComplete, doOnError); } public static <T> PushTrigger<T> oo(String name, final Observable<Observable<T>> oo, Action0 doOnComplete, Action1<Throwable> doOnError) { return trigger(name, Observable.merge(oo), doOnComplete, doOnError); } public static <K, V> PushTrigger<KeyValuePair<K, V>> oogo(String name, final Observable<Observable<GroupedObservable<K, V>>> oo, Action0 doOnComplete, Action1<Throwable> doOnError, long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, HashFunction hashFunction) { return groupTrigger(name, Observable.merge(oo), doOnComplete, doOnError, groupExpirySeconds, keyEncoder, hashFunction); } // NJ public static <K, V> PushTrigger<KeyValuePair<K, V>> oomgo(String name, final Observable<Observable<MantisGroup<K, V>>> oo, Action0 doOnComplete, Action1<Throwable> doOnError, long groupExpirySeconds, final Func1<K, byte[]> keyEncoder, HashFunction hashFunction) { return mantisGroupTrigger(name, Observable.merge(oo), doOnComplete, doOnError, groupExpirySeconds, keyEncoder, hashFunction); } }
8,755
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/Router.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import java.util.List; import java.util.Set; import rx.functions.Func1; public abstract class Router<T> { protected Func1<T, byte[]> encoder; protected Counter numEventsRouted; protected Counter numEventsProcessed; private Metrics metrics; public Router(String name, Func1<T, byte[]> encoder) { this.encoder = encoder; metrics = new Metrics.Builder() .name("Router_" + name) .addCounter("numEventsRouted") .addCounter("numEventsProcessed") .build(); numEventsRouted = metrics.getCounter("numEventsRouted"); numEventsProcessed = metrics.getCounter("numEventsProcessed"); } public abstract void route(Set<AsyncConnection<T>> connections, List<T> chunks); public Metrics getMetrics() { return metrics; } }
8,756
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/PushServer.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 io.reactivex.mantis.network.push; import static com.mantisrx.common.utils.MantisMetricStringConstants.GROUP_ID_TAG; import static io.reactivex.mantis.network.push.PushServerSse.CLIENT_ID_TAG_NAME; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.compression.CompressionUtils; import io.mantisrx.common.messages.MantisMetaDroppedMessage; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.spectator.MetricGroupId; import io.mantisrx.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.Channel; import io.netty.util.concurrent.GenericFutureListener; import io.reactivx.mantis.operators.DisableBackPressureOperator; import io.reactivx.mantis.operators.DropOperator; import java.nio.ByteBuffer; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import mantis.io.reactivex.netty.channel.DefaultChannelWriter; import mantis.io.reactivex.netty.server.RxServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Func1; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; public abstract class PushServer<T, R> { private static final Logger logger = LoggerFactory.getLogger(PushServer.class); final byte[] prefix = "data: ".getBytes(); final byte[] nwnw = "\n\n".getBytes(); protected int port; protected MonitoredQueue<T> outboundBuffer; protected ConnectionManager<T> connectionManager; private int writeRetryCount; private RxServer<?, ?> server; private Counter processedWrites; private Counter successfulWrites; private Counter failedWrites; private Gauge batchWriteSize; private Set<Future<Void>> consumerThreadFutures = new HashSet<>(); private Observable<String> serverSignals; private String serverName; private final int maxNotWritableTimeSec; private final ScheduledExecutorService scheduledExecutorService; private final MetricsRegistry metricsRegistry; public PushServer(final PushTrigger<T> trigger, ServerConfig<T> config, Observable<String> serverSignals) { this.serverSignals = serverSignals; serverName = config.getName(); maxNotWritableTimeSec = config.getMaxNotWritableTimeSec(); metricsRegistry = config.getMetricsRegistry(); outboundBuffer = new MonitoredQueue<T>(serverName, config.getBufferCapacity(), config.useSpscQueue()); trigger.setBuffer(outboundBuffer); Action0 doOnFirstConnection = new Action0() { @Override public void call() { trigger.start(); } }; Action0 doOnZeroConnections = new Action0() { @Override public void call() { logger.info("doOnZeroConnections Triggered"); trigger.stop(); } }; final String serverNameValue = Optional.ofNullable(serverName).orElse("none"); final BasicTag idTag = new BasicTag(GROUP_ID_TAG, serverNameValue); final MetricGroupId metricsGroup = new MetricGroupId("PushServer", idTag); // manager will auto add metrics for connection groups connectionManager = new ConnectionManager<T>(metricsRegistry, doOnFirstConnection, doOnZeroConnections); int numQueueProcessingThreads = config.getNumQueueConsumers(); MonitoredThreadPool consumerThreads = new MonitoredThreadPool("QueueConsumerPool", new ThreadPoolExecutor(numQueueProcessingThreads, numQueueProcessingThreads, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numQueueProcessingThreads), new NamedThreadFactory("QueueConsumerPool"))); logger.info("PushServer create consumer threads, use spsc: {}, num threads: {}, buffer capacity: {}, " + "chunk size: {}, chunk time ms: {}", config.useSpscQueue(), numQueueProcessingThreads, config.getBufferCapacity(), config.getMaxChunkSize(), config.getMaxChunkTimeMSec()); if (config.useSpscQueue()) { consumerThreadFutures.add(consumerThreads.submit(new SingleThreadedChunker<T>( config.getChunkProcessor(), outboundBuffer, config.getMaxChunkSize(), config.getMaxChunkTimeMSec(), connectionManager ))); } else { for (int i = 0; i < numQueueProcessingThreads; i++) { consumerThreadFutures.add(consumerThreads.submit(new TimedChunker<T>( outboundBuffer, config.getMaxChunkSize(), config.getMaxChunkTimeMSec(), config.getChunkProcessor(), connectionManager ))); } } Metrics serverMetrics = new Metrics.Builder() .id(metricsGroup) .addCounter("numProcessedWrites") .addCounter("numSuccessfulWrites") .addCounter("numFailedWrites") .addGauge(connectionManager.getActiveConnections(metricsGroup)) .addGauge("batchWriteSize") .build(); successfulWrites = serverMetrics.getCounter("numSuccessfulWrites"); failedWrites = serverMetrics.getCounter("numFailedWrites"); batchWriteSize = serverMetrics.getGauge("batchWriteSize"); processedWrites = serverMetrics.getCounter("numProcessedWrites"); registerMetrics(metricsRegistry, serverMetrics, consumerThreads.getMetrics(), outboundBuffer.getMetrics(), trigger.getMetrics(), config.getChunkProcessor().router.getMetrics()); port = config.getPort(); writeRetryCount = config.getWriteRetryCount(); scheduledExecutorService = new ScheduledThreadPoolExecutor(10, new ThreadFactoryBuilder().setNameFormat("netty-channel-checker-%d").build()); } private void registerMetrics(MetricsRegistry registry, Metrics serverMetrics, Metrics consumerPoolMetrics, Metrics queueMetrics, Metrics pushTriggerMetrics, Metrics routerMetrics) { registry.registerAndGet(serverMetrics); registry.registerAndGet(consumerPoolMetrics); registry.registerAndGet(queueMetrics); registry.registerAndGet(pushTriggerMetrics); registry.registerAndGet(routerMetrics); } protected Observable<Void> manageConnection(final DefaultChannelWriter<R> writer, String host, int port, String groupId, String slotId, String id, final AtomicLong lastWriteTime, final boolean applicationHeartbeats, final Subscription heartbeatSubscription, boolean applySampling, long samplingRateMSec, Func1<T, Boolean> predicate, final Action0 connectionClosedCallback, final Counter legacyMsgProcessedCounter, final Counter legacyDroppedWrites, final Action0 connectionSubscribeCallback) { return manageConnection(writer, host, port, groupId, slotId, id, lastWriteTime, applicationHeartbeats, heartbeatSubscription, applySampling, samplingRateMSec, null, null, predicate, connectionClosedCallback, legacyMsgProcessedCounter, legacyDroppedWrites, connectionSubscribeCallback); } protected Observable<Void> manageConnection(final DefaultChannelWriter<R> writer, String host, int port, String groupId, String slotId, String id, final AtomicLong lastWriteTime, final boolean applicationHeartbeats, final Subscription heartbeatSubscription, boolean applySampling, long samplingRateMSec, final SerializedSubject<String, String> metaMsgSubject, final Subscription metaMsgSubscription, Func1<T, Boolean> predicate, final Action0 connectionClosedCallback, final Counter legacyMsgProcessedCounter, final Counter legacyDroppedWrites, final Action0 connectionSubscribeCallback) { return manageConnectionWithCompression(writer, host, port, groupId, slotId, id, lastWriteTime, applicationHeartbeats, heartbeatSubscription, applySampling, samplingRateMSec, null, null, predicate, connectionClosedCallback, legacyMsgProcessedCounter, legacyDroppedWrites, connectionSubscribeCallback, false, false, null); } /** * Adding this for backwards compatibility until all SSE producers and consumers can be migrated to using the pipeline * Replace with a pipeline configurator in the future * * @param writer * @param host * @param port * @param groupId * @param slotId * @param id * @param lastWriteTime * @param applicationHeartbeats * @param heartbeatSubscription * @param applySampling * @param samplingRateMSec * @param metaMsgSubject * @param metaMsgSubscription * @param predicate * @param connectionClosedCallback * @param legacyMsgProcessedCounter * @param legacyDroppedWrites * @param connectionSubscribeCallback * @param compressOutput * * @return */ protected Observable<Void> manageConnectionWithCompression(final DefaultChannelWriter<R> writer, String host, int port, String groupId, String slotId, String id, final AtomicLong lastWriteTime, final boolean applicationHeartbeats, final Subscription heartbeatSubscription, boolean applySampling, long samplingRateMSec, final SerializedSubject<String, String> metaMsgSubject, final Subscription metaMsgSubscription, Func1<T, Boolean> predicate, final Action0 connectionClosedCallback, final Counter legacyMsgProcessedCounter, final Counter legacyDroppedWrites, final Action0 connectionSubscribeCallback, boolean compressOutput, boolean isSSE, byte[] delimiter) { if (id == null || id.isEmpty()) { id = host + "_" + port + "_" + System.currentTimeMillis(); } if (slotId == null || slotId.isEmpty()) { slotId = id; } if (groupId == null || groupId.isEmpty()) { groupId = id; } final BasicTag slotIdTag = new BasicTag("slotId", slotId); SerializedSubject<List<byte[]>, List<byte[]>> subject = new SerializedSubject<>(PublishSubject.<List<byte[]>>create()); Observable<List<byte[]>> observable = subject.lift(new DropOperator<>("batch_writes", slotIdTag)); if (applySampling) { observable = observable .sample(samplingRateMSec, TimeUnit.MILLISECONDS) .map((List<byte[]> list) -> { // get most recent item from sample List<byte[]> singleItem = new LinkedList<>(); if (!list.isEmpty()) { singleItem.add(list.get(list.size() - 1)); } return singleItem; } ); } final BasicTag clientIdTag = new BasicTag(CLIENT_ID_TAG_NAME, Optional.ofNullable(groupId).orElse("none")); Metrics writableMetrics = new Metrics.Builder() .id("PushServer", clientIdTag) .addCounter("channelWritable") .addCounter("channelNotWritable") .addCounter("channelNotWritableTimeout") .build(); metricsRegistry.registerAndGet(writableMetrics); Counter channelWritableCounter = writableMetrics.getCounter("channelWritable"); Counter channelNotWritableCounter = writableMetrics.getCounter("channelNotWritable"); Counter channelNotWritableTimeoutCounter = writableMetrics.getCounter("channelNotWritableTimeout"); final Future<?> writableCheck; AtomicLong lastWritableTS = new AtomicLong(System.currentTimeMillis()); if (maxNotWritableTimeSec > 0) { writableCheck = scheduledExecutorService.scheduleAtFixedRate( () -> { long currentTime = System.currentTimeMillis(); if (writer.getChannel().isWritable()) { channelWritableCounter.increment(); lastWritableTS.set(currentTime); } else if (currentTime - lastWritableTS.get() > TimeUnit.SECONDS.toMillis(maxNotWritableTimeSec)) { logger.warn("Closing connection due to channel not writable for more than {} secs", maxNotWritableTimeSec); channelNotWritableTimeoutCounter.increment(); try { writer.close(); } catch (Throwable ex) { logger.error("Failed to close connection.", ex); } } else { channelNotWritableCounter.increment(); } }, 0, 10, TimeUnit.SECONDS ); } else { writableCheck = null; } final AsyncConnection<T> connection = new AsyncConnection<T>(host, port, id, slotId, groupId, subject, predicate); final Channel channel = writer.getChannel(); channel.closeFuture().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Void>>() { @Override public void operationComplete(io.netty.util.concurrent.Future<Void> future) throws Exception { connectionManager.remove(connection); connectionCleanup(heartbeatSubscription, connectionClosedCallback, metaMsgSubscription); // Callback from the channel is closed, we don't need to check channel status anymore. if (writableCheck != null) { writableCheck.cancel(false); } } }); return observable .doOnSubscribe(() -> { connectionManager.add(connection); if (connectionSubscribeCallback != null) { connectionSubscribeCallback.call(); } } ) // per connection buffer .lift(new DisableBackPressureOperator<List<byte[]>>()) .buffer(200, TimeUnit.MILLISECONDS) .flatMap((List<List<byte[]>> bufferOfBuffers) -> { if (bufferOfBuffers != null && !bufferOfBuffers.isEmpty()) { ByteBuffer blockBuffer = null; int size = 0; for (List<byte[]> buffer : bufferOfBuffers) { size += buffer.size(); } final int batchSize = size; processedWrites.increment(batchSize); if (channel.isActive() && channel.isWritable()) { lastWritableTS.set(System.currentTimeMillis()); if (isSSE) { if (compressOutput) { boolean useSnappy = true; byte[] compressedData = delimiter == null ? CompressionUtils.compressAndBase64EncodeBytes(bufferOfBuffers, useSnappy) : CompressionUtils.compressAndBase64EncodeBytes(bufferOfBuffers, useSnappy, delimiter); blockBuffer = ByteBuffer.allocate(prefix.length + compressedData.length + nwnw.length); blockBuffer.put(prefix); blockBuffer.put(compressedData); blockBuffer.put(nwnw); } else { int totalBytes = 0; for (List<byte[]> buffer : bufferOfBuffers) { for (byte[] data : buffer) { totalBytes += (data.length + prefix.length + nwnw.length); } } byte[] block = new byte[totalBytes]; blockBuffer = ByteBuffer.wrap(block); for (List<byte[]> buffer : bufferOfBuffers) { for (byte[] data : buffer) { blockBuffer.put(prefix); blockBuffer.put(data); blockBuffer.put(nwnw); } } } } else { int totalBytes = 0; for (List<byte[]> buffer : bufferOfBuffers) { for (byte[] data : buffer) { totalBytes += (data.length); } } byte[] block = new byte[totalBytes]; blockBuffer = ByteBuffer.wrap(block); for (List<byte[]> buffer : bufferOfBuffers) { for (byte[] data : buffer) { blockBuffer.put(data); } } } return writer .writeBytesAndFlush(blockBuffer.array()) .retry(writeRetryCount) .doOnError((Throwable t1) -> failedToWriteBatch(connection, batchSize, legacyDroppedWrites, metaMsgSubject)) .doOnCompleted(() -> { if (applicationHeartbeats && lastWriteTime != null) { lastWriteTime.set(System.currentTimeMillis()); } if (legacyMsgProcessedCounter != null) { legacyMsgProcessedCounter.increment(batchSize); } successfulWrites.increment(batchSize); connectionManager.successfulWrites(connection, batchSize); } ) .doOnTerminate(() -> batchWriteSize.set(batchSize)); } else { // connection is not active or writable failedToWriteBatch(connection, batchSize, legacyDroppedWrites, metaMsgSubject); } } return Observable.empty(); } ); } protected void failedToWriteBatch(AsyncConnection<T> connection, int batchSize, Counter legacyDroppedWrites, SerializedSubject<String, String> metaMsgSubject) { if (legacyDroppedWrites != null) { legacyDroppedWrites.increment(batchSize); } if (metaMsgSubject != null) { MantisMetaDroppedMessage msg = new MantisMetaDroppedMessage(batchSize, System.currentTimeMillis()); metaMsgSubject.onNext(msg.toString()); } failedWrites.increment(batchSize); connectionManager.failedWrites(connection, batchSize); } protected void connectionCleanup(Subscription heartbeatSubscription, Action0 connectionClosedCallback, Subscription metaMsgSubscription) { if (heartbeatSubscription != null) { logger.info("Unsubscribing from heartbeats"); heartbeatSubscription.unsubscribe(); } if (metaMsgSubscription != null) { logger.info("Unsubscribing from metaMsg subject"); metaMsgSubscription.unsubscribe(); } if (connectionClosedCallback != null) { connectionClosedCallback.call(); } } public abstract RxServer<?, ?> createServer(); public void start() { server = createServer(); server.start(); serverSignals .subscribe( (String message) -> logger.info("Signal received for server: " + serverName + " signal: " + message), (Throwable t) -> logger.info("Signal received for server: " + serverName + " signal: SERVER_ERROR", t), () -> logger.info("Signal received for server: " + serverName + " signal: SERVER_COMPLETED") ); } public void blockUntilShutdown() { // block on server signal until completed serverSignals.toBlocking() .forEach((String message) -> { /* no op */ }); } public void startAndBlock() { server = createServer(); server.start(); try { serverSignals.toBlocking() .forEach((String message) -> logger.info("Signal received for server: " + serverName + " signal: " + message)); } catch (Throwable t) { logger.info("Signal received for server: " + serverName + " signal: SERVER_ERROR", t); throw t; } logger.info("Signal received for server: " + serverName + " signal: SERVER_COMPLETED"); } public void shutdown() { for (Future<Void> thread : consumerThreadFutures) { thread.cancel(true); } try { server.shutdown(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
8,757
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ConnectionGroup.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 io.reactivex.mantis.network.push; import com.mantisrx.common.utils.MantisMetricStringConstants; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.spectator.GaugeCallback; import io.mantisrx.common.metrics.spectator.MetricGroupId; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; public class ConnectionGroup<T> { private static final Logger logger = LoggerFactory.getLogger(ConnectionGroup.class); private String groupId; private Map<String, AsyncConnection<T>> connections; private Metrics metrics; private MetricGroupId metricsGroup; private Counter successfulWrites; private Counter numSlotSwaps; private Counter failedWrites; public ConnectionGroup(String groupId) { this.groupId = groupId; this.connections = new HashMap<>(); final String grpId = Optional.ofNullable(groupId).orElse("none"); final BasicTag groupIdTag = new BasicTag(MantisMetricStringConstants.GROUP_ID_TAG, grpId); this.metricsGroup = new MetricGroupId("ConnectionGroup", groupIdTag); Gauge activeConnections = new GaugeCallback(metricsGroup, "activeConnections", new Func0<Double>() { @Override public Double call() { synchronized (this) { return (double) connections.size(); } } }); this.metrics = new Metrics.Builder() .id(metricsGroup) .addCounter("numSlotSwaps") .addCounter("numSuccessfulWrites") .addCounter("numFailedWrites") .addGauge(activeConnections) .build(); this.successfulWrites = metrics.getCounter("numSuccessfulWrites"); this.failedWrites = metrics.getCounter("numFailedWrites"); this.numSlotSwaps = metrics.getCounter("numSlotSwaps"); } public synchronized void incrementSuccessfulWrites(int count) { successfulWrites.increment(count); } public synchronized void incrementFailedWrites(int count) { failedWrites.increment(count); } public synchronized void removeConnection(AsyncConnection<T> connection) { AsyncConnection<T> existingConn = connections.get(connection.getSlotId()); logger.info("Attempt to remove connection: " + connection + " existing connection entry " + existingConn); if (existingConn != null && existingConn.getId() == connection.getId()) { connections.remove(connection.getSlotId()); } else { logger.warn("Attempt to remove connection ignored. Either there is no such connection or a" + " a new connection has already been swapped in the place of the old connection"); } } public synchronized void addConnection(AsyncConnection<T> connection) { // check if connection previously existed with slotId String slotId = connection.getSlotId(); AsyncConnection<T> previousConnection = connections.get(slotId); // add new connection connections.put(slotId, connection); // close previous if (previousConnection != null) { logger.info("Swapping connection: " + previousConnection + " with new connection: " + connection); previousConnection.close(); numSlotSwaps.increment(); } } public synchronized boolean isEmpty() { return connections.isEmpty(); } public synchronized Set<AsyncConnection<T>> getConnections() { Set<AsyncConnection<T>> copy = new HashSet<>(); copy.addAll(connections.values()); return copy; } public Metrics getMetrics() { return metrics; } public MetricGroupId getMetricsGroup() { return metricsGroup; } @Override public String toString() { return "ConnectionGroup [groupId=" + groupId + ", connections=" + connections + "]"; } }
8,758
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/Routers.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 io.reactivex.mantis.network.push; import java.nio.ByteBuffer; import java.nio.charset.Charset; import rx.functions.Func1; public class Routers { private Routers() {} public static <K, V> Router<KeyValuePair<K, V>> consistentHashingLegacyTcpProtocol(String name, final Func1<K, byte[]> keyEncoder, final Func1<V, byte[]> valueEncoder) { return new ConsistentHashingRouter<K, V>(name, new Func1<KeyValuePair<K, V>, byte[]>() { @Override public byte[] call(KeyValuePair<K, V> kvp) { byte[] keyBytes = kvp.getKeyBytes(); byte[] valueBytes = valueEncoder.call(kvp.getValue()); return // length + opcode + notification type + key length ByteBuffer.allocate(4 + 1 + 1 + 4 + keyBytes.length + valueBytes.length) .putInt(1 + 1 + 4 + keyBytes.length + valueBytes.length) // length .put((byte) 1) // opcode .put((byte) 1) // notification type .putInt(keyBytes.length) // key length .put(keyBytes) // key bytes .put(valueBytes) // value bytes .array(); } }, HashFunctions.ketama()); } private static byte[] dataPayload(byte[] data) { ByteBuffer buffer = ByteBuffer.allocate(4 + 1 + data.length); buffer.putInt(1 + data.length); // length, plus additional byte for opcode buffer.put((byte) 1); // opcode for next operator buffer.put(data); return buffer.array(); } public static <T> Router<T> roundRobinLegacyTcpProtocol(String name, final Func1<T, byte[]> toBytes) { return new RoundRobinRouter<>(name, new Func1<T, byte[]>() { @Override public byte[] call(T t1) { byte[] data = toBytes.call(t1); return dataPayload(data); } }); } public static <T> Router<T> roundRobinSse(String name, final Func1<T, String> toString) { final byte[] prefix = "data: ".getBytes(); final byte[] nwnw = "\n\n".getBytes(); return new RoundRobinRouter<>(name, new Func1<T, byte[]>() { @Override public byte[] call(T data) { byte[] bytes = string().call(toString.call(data)); return bytes; // ByteBuffer buffer = ByteBuffer.allocate(prefix.length+bytes.length+nwnw.length); // buffer.put(prefix); // buffer.put(bytes); // buffer.put(nwnw); // return buffer.array(); } }); } private static Func1<String, byte[]> stringWithEncoding(String encoding) { final Charset charset = Charset.forName(encoding); return new Func1<String, byte[]>() { @Override public byte[] call(final String value) { return value.getBytes(charset); } }; } public static Func1<String, byte[]> stringAscii() { return new Func1<String, byte[]>() { @Override public byte[] call(final String value) { final byte[] bytes = new byte[value.length()]; for (int i = 0; i < value.length(); i++) bytes[i] = (byte) value.charAt(i); return bytes; } }; } public static Func1<String, byte[]> stringUtf8() { return stringWithEncoding("UTF-8"); } public static Func1<String, byte[]> string() { return stringUtf8(); } }
8,759
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/HeartbeatHandler.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 io.reactivex.mantis.network.push; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HeartbeatHandler extends ChannelDuplexHandler { static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { logger.warn("Read idle, due to missed heartbeats, closing connection: " + ctx.channel().remoteAddress()); ctx.close(); } else if (e.state() == IdleState.WRITER_IDLE) { ByteBuffer buffer = ByteBuffer.allocate(4 + 1); // length plus one byte buffer.putInt(1); // length of op code buffer.put((byte) 6); // op code for heartbeat for legacy protocol ctx.channel().writeAndFlush(buffer.array()); } } super.userEventTriggered(ctx, evt); } }
8,760
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/MonitoredQueue.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 io.reactivex.mantis.network.push; import com.mantisrx.common.utils.MantisMetricStringConstants; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.spectator.MetricGroupId; import java.util.AbstractQueue; import java.util.Optional; import java.util.concurrent.LinkedBlockingQueue; import org.jctools.queues.SpscArrayQueue; public class MonitoredQueue<T> { final boolean isSpsc; //private BlockingQueue<T> queue; private AbstractQueue<T> queue; private Metrics metrics; private Counter numSuccessEnqueu; private Counter numFailedEnqueu; private Gauge queueDepth; public MonitoredQueue(String name, int capacity) { this(name, capacity, true); } public MonitoredQueue(String name, int capacity, boolean useSpsc) { this.isSpsc = useSpsc; if (!useSpsc) { queue = new LinkedBlockingQueue<>(capacity); } else { queue = new SpscArrayQueue<>(capacity); } final String qId = Optional.ofNullable(name).orElse("none"); final BasicTag idTag = new BasicTag(MantisMetricStringConstants.GROUP_ID_TAG, qId); final MetricGroupId metricGroup = new MetricGroupId("MonitoredQueue", idTag); metrics = new Metrics.Builder() .id(metricGroup) .addCounter("numFailedToQueue") .addCounter("numSuccessQueued") .addGauge("queueDepth") .build(); numSuccessEnqueu = metrics.getCounter("numSuccessQueued"); numFailedEnqueu = metrics.getCounter("numFailedToQueue"); queueDepth = metrics.getGauge("queueDepth"); } public boolean write(T data) { boolean offer = queue.offer(data); queueDepth.set(queue.size()); if (offer) { numSuccessEnqueu.increment(); } else { numFailedEnqueu.increment(); } return offer; } public Metrics getMetrics() { return metrics; } public T get() throws InterruptedException { if (!isSpsc) { return ((LinkedBlockingQueue<T>) queue).take(); } //return queue.take(); //spsc does not implement take return queue.poll(); } // public T poll(long timeout, TimeUnit unit) throws InterruptedException{ // return queue.poll(timeout, unit); // } public T poll() { return queue.poll(); } public void clear() { queue.clear(); } }
8,761
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ConsistentHashingRouter.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 io.reactivex.mantis.network.push; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func1; public class ConsistentHashingRouter<K, V> extends Router<KeyValuePair<K, V>> { private static final Logger logger = LoggerFactory.getLogger(ConsistentHashingRouter.class); private static int connectionRepetitionOnRing = 1000; private static long validCacheAgeMSec = 5000; private HashFunction hashFunction; private AtomicReference<SnapshotCache<SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>>>> cachedRingRef = new AtomicReference<>(); public ConsistentHashingRouter(String name, Func1<KeyValuePair<K, V>, byte[]> dataEncoder, HashFunction hashFunction) { super("ConsistentHashingRouter_" + name, dataEncoder); this.hashFunction = hashFunction; } @Override public void route(Set<AsyncConnection<KeyValuePair<K, V>>> connections, List<KeyValuePair<K, V>> chunks) { if (connections != null && !connections.isEmpty() && chunks != null && !chunks.isEmpty()) { int numConnections = connections.size(); int bufferCapacity = (chunks.size() / numConnections) + 1; // assume even distribution Map<AsyncConnection<KeyValuePair<K, V>>, List<byte[]>> writes = new HashMap<>(numConnections); // hash connections into slots SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> ring = hashConnections(connections); // process chunks for (KeyValuePair<K, V> kvp : chunks) { long hash = kvp.getKeyBytesHashed(); // lookup slot AsyncConnection<KeyValuePair<K, V>> connection = lookupConnection(hash, ring); // add to writes Func1<KeyValuePair<K, V>, Boolean> predicate = connection.getPredicate(); if (predicate == null || predicate.call(kvp)) { List<byte[]> buffer = writes.get(connection); if (buffer == null) { buffer = new ArrayList<>(bufferCapacity); writes.put(connection, buffer); } buffer.add(encoder.call(kvp)); } } // process writes if (!writes.isEmpty()) { for (Entry<AsyncConnection<KeyValuePair<K, V>>, List<byte[]>> entry : writes.entrySet()) { AsyncConnection<KeyValuePair<K, V>> connection = entry.getKey(); List<byte[]> toWrite = entry.getValue(); connection.write(toWrite); numEventsRouted.increment(toWrite.size()); } } } } private AsyncConnection<KeyValuePair<K, V>> lookupConnection(long hash, SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> ring) { if (!ring.containsKey(hash)) { SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> tailMap = ring.tailMap(hash); hash = tailMap.isEmpty() ? ring.firstKey() : tailMap.firstKey(); } return ring.get(hash); } private void computeRing(Set<AsyncConnection<KeyValuePair<K, V>>> connections) { SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> ring = new TreeMap<Long, AsyncConnection<KeyValuePair<K, V>>>(); for (AsyncConnection<KeyValuePair<K, V>> connection : connections) { for (int i = 0; i < connectionRepetitionOnRing; i++) { // hash node on ring String connectionId = connection.getSlotId(); if (connectionId == null) { throw new IllegalStateException("Connection must specify an id for consistent hashing"); } byte[] connectionBytes = (connectionId + "-" + i).getBytes(); long hash = hashFunction.computeHash(connectionBytes); ring.put(hash, connection); } } cachedRingRef.set(new SnapshotCache<SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>>>(ring)); } private SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> hashConnections(Set<AsyncConnection<KeyValuePair<K, V>>> connections) { SnapshotCache<SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>>> cache = cachedRingRef.get(); if (cache == null) { logger.info("Recomputing ring due null reference"); computeRing(connections); } else { SortedMap<Long, AsyncConnection<KeyValuePair<K, V>>> cachedRing = cache.getCache(); // determine if need to recompute cache if (cachedRing.size() != (connections.size() * connectionRepetitionOnRing)) { // number of connections not equal logger.info("Recomputing ring due to difference in number of connections versus cache"); computeRing(connections); } else { // number of connections equal, check timestamp long timestamp = cache.getTimestamp(); if (System.currentTimeMillis() - timestamp > validCacheAgeMSec) { computeRing(connections); } } } return cachedRingRef.get().getCache(); } }
8,762
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/KeyValuePair.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 io.reactivex.mantis.network.push; public class KeyValuePair<K, V> { private long keyBytesHashed; private byte[] keyBytes; private V value; public KeyValuePair(long keyBytesHashed, byte[] keyBytes, V value) { this.keyBytesHashed = keyBytesHashed; this.keyBytes = keyBytes; this.value = value; } public long getKeyBytesHashed() { return keyBytesHashed; } public byte[] getKeyBytes() { return keyBytes; } public V getValue() { return value; } }
8,763
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ConnectionManager.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.spectator.GaugeCallback; import io.mantisrx.common.metrics.spectator.MetricGroupId; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Action0; public class ConnectionManager<T> { private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class); private Map<String, ConnectionGroup<T>> managedConnections = new LinkedHashMap<String, ConnectionGroup<T>>(); private MetricsRegistry metricsRegistry; private AtomicReference<Gauge> activeConnectionsRef = new AtomicReference<>(null); private Action0 doOnFirstConnection; private Action0 doOnZeroConnections; private Lock connectionState = new ReentrantLock(); private AtomicBoolean subscribed = new AtomicBoolean(); public ConnectionManager(MetricsRegistry metricsRegistry, Action0 doOnFirstConnection, Action0 doOnZeroConnections) { this.doOnFirstConnection = doOnFirstConnection; this.doOnZeroConnections = doOnZeroConnections; this.metricsRegistry = metricsRegistry; } private int activeConnections() { connectionState.lock(); try { int connections = 0; for (ConnectionGroup<T> group : managedConnections.values()) { connections += group.getConnections().size(); } return connections; } finally { connectionState.unlock(); } } protected Gauge getActiveConnections(final MetricGroupId metricsGroup) { activeConnectionsRef.compareAndSet(null, new GaugeCallback(metricsGroup, "activeConnections", () -> (double) activeConnections())); return activeConnectionsRef.get(); } public Set<AsyncConnection<T>> connections(String groupId) { connectionState.lock(); try { Set<AsyncConnection<T>> connections = new HashSet<>(); ConnectionGroup<T> group = managedConnections.get(groupId); if (group != null) { connections.addAll(group.getConnections()); } return connections; } finally { connectionState.unlock(); } } protected void successfulWrites(AsyncConnection<T> connection, Integer numWrites) { connectionState.lock(); try { String groupId = connection.getGroupId(); ConnectionGroup<T> current = managedConnections.get(groupId); if (current != null) { current.incrementSuccessfulWrites(numWrites); } } finally { connectionState.unlock(); } } protected void failedWrites(AsyncConnection<T> connection, Integer numWrites) { connectionState.lock(); try { String groupId = connection.getGroupId(); ConnectionGroup<T> current = managedConnections.get(groupId); if (current != null) { current.incrementFailedWrites(numWrites); } } finally { connectionState.unlock(); } } protected void add(AsyncConnection<T> connection) { connectionState.lock(); try { String groupId = connection.getGroupId(); ConnectionGroup<T> current = managedConnections.get(groupId); if (current == null) { ConnectionGroup<T> newGroup = new ConnectionGroup<T>(groupId); current = managedConnections.putIfAbsent(groupId, newGroup); if (current == null) { current = newGroup; metricsRegistry.registerAndGet(current.getMetrics()); } } current.addConnection(connection); logger.info("Connection added to group: " + groupId + ", connection: " + connection + ", group: " + current); } finally { connectionState.unlock(); } if (subscribed.compareAndSet(false, true)) { logger.info("Calling callback when active connections is one"); doOnFirstConnection.call(); logger.info("Completed callback when active connections is one"); } } protected void remove(AsyncConnection<T> connection) { connectionState.lock(); try { String groupId = connection.getGroupId(); ConnectionGroup<T> current = managedConnections.get(groupId); if (current != null) { current.removeConnection(connection); logger.info("Connection removed from group: " + groupId + ", connection: " + connection + ", group: " + current); if (current.isEmpty()) { logger.info("Removing group: " + groupId + ", zero connections"); // deregister metrics metricsRegistry.remove(current.getMetricsGroup()); // remove group managedConnections.remove(groupId); } } } finally { connectionState.unlock(); } if (activeConnections() == 0 && subscribed.compareAndSet(true, false)) { logger.info("Connection Manager Calling callback when active connections is zero"); doOnZeroConnections.call(); logger.info("Completed callback when active connections is zero"); } } public Set<AsyncConnection<T>> connections() { connectionState.lock(); try { Set<AsyncConnection<T>> connections = new HashSet<>(); for (ConnectionGroup<T> group : managedConnections.values()) { connections.addAll(group.getConnections()); } return connections; } finally { connectionState.unlock(); } } public Map<String, ConnectionGroup<T>> groups() { connectionState.lock(); try { return new HashMap<String, ConnectionGroup<T>>(managedConnections); } finally { connectionState.unlock(); } } }
8,764
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/LegacyTcpPipelineConfigurator.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 io.reactivex.mantis.network.push; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import mantis.io.reactivex.netty.pipeline.PipelineConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LegacyTcpPipelineConfigurator implements PipelineConfigurator<RemoteRxEvent, List<RemoteRxEvent>> { private static final Logger logger = LoggerFactory.getLogger(LegacyTcpPipelineConfigurator.class); private static final byte PROTOCOL_VERSION = 1; private String name; public LegacyTcpPipelineConfigurator(String name) { this.name = name; } @SuppressWarnings("unchecked") static Map<String, String> fromBytesToMap(byte[] bytes) { Map<String, String> map = null; ByteArrayInputStream bis = null; ObjectInput in = null; try { bis = new ByteArrayInputStream(bytes); in = new ObjectInputStream(bis); map = (Map<String, String>) in.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } finally { try { if (bis != null) {bis.close();} if (in != null) {in.close();} } catch (IOException e) { throw new RuntimeException(e); } } return map; } static byte[] fromMapToBytes(Map<String, String> map) { ByteArrayOutputStream baos = null; ObjectOutput out = null; try { baos = new ByteArrayOutputStream(); out = new ObjectOutputStream(baos); out.writeObject(map); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (out != null) {out.close();} if (baos != null) {baos.close();} } catch (IOException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } } return baos.toByteArray(); } @Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast(new ChannelDuplexHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean handled = false; if (ByteBuf.class.isAssignableFrom(msg.getClass())) { ByteBuf byteBuf = (ByteBuf) msg; if (byteBuf.isReadable()) { int protocolVersion = byteBuf.readByte(); if (protocolVersion != PROTOCOL_VERSION) { throw new RuntimeException("Unsupported protocol version: " + protocolVersion); } int observableNameLength = byteBuf.readByte(); String observableName = null; if (observableNameLength > 0) { // read name byte[] observableNameBytes = new byte[observableNameLength]; byteBuf.readBytes(observableNameBytes); observableName = new String(observableNameBytes, Charset.forName("UTF-8")); } while (byteBuf.isReadable()) { int lengthOfEvent = byteBuf.readInt(); int operation = byteBuf.readByte(); RemoteRxEvent.Type type = null; Map<String, String> subscribeParams = null; byte[] valueData = null; if (operation == 1) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: next"); } type = RemoteRxEvent.Type.next; valueData = new byte[lengthOfEvent - 1]; //subtract op code byteBuf.readBytes(valueData); } else if (operation == 2) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: error"); } type = RemoteRxEvent.Type.error; valueData = new byte[lengthOfEvent - 1]; byteBuf.readBytes(valueData); } else if (operation == 3) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: completed"); } type = RemoteRxEvent.Type.completed; } else if (operation == 4) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: subscribed"); } type = RemoteRxEvent.Type.subscribed; // read subscribe parameters int subscribeParamsLength = byteBuf.readInt(); if (subscribeParamsLength > 0) { // read byte into map byte[] subscribeParamsBytes = new byte[subscribeParamsLength]; byteBuf.readBytes(subscribeParamsBytes); subscribeParams = fromBytesToMap(subscribeParamsBytes); } } else if (operation == 5) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: unsubscribed"); } type = RemoteRxEvent.Type.unsubscribed; } else if (operation == 6) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: heartbeat"); } } else if (operation == 7) { if (logger.isDebugEnabled()) { logger.debug("READ request for RemoteRxEvent: nonDataError"); } type = RemoteRxEvent.Type.nonDataError; valueData = new byte[lengthOfEvent - 1]; byteBuf.readBytes(valueData); } else { throw new RuntimeException("operation: " + operation + " not support."); } // don't send heartbeats through pipeline if (operation != 6) { ctx.fireChannelRead(new RemoteRxEvent(observableName, type, valueData, subscribeParams)); } } handled = true; byteBuf.release(); } } if (!handled) { super.channelRead(ctx, msg); } } }); pipeline.addLast(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (ByteBuf.class.isAssignableFrom(msg.getClass())) { // handle data writes ByteBuf bytes = (ByteBuf) msg; ByteBuf buf = ctx.alloc().buffer(bytes.readableBytes()); writeHeader(buf, name); buf.writeBytes(bytes); bytes.release(); super.write(ctx, buf, promise); } else if (msg instanceof byte[]) { // handle heart beat writes ByteBuf buf = ctx.alloc().buffer(); writeHeader(buf, name); buf.writeBytes((byte[]) msg); super.write(ctx, buf, promise); super.flush(ctx); } else { super.write(ctx, msg, promise); } } }); } private void writeHeader(ByteBuf buf, String name) { buf.writeByte(PROTOCOL_VERSION); String observableName = name; if (observableName != null && !observableName.isEmpty()) { // write length int nameLength = observableName.length(); if (nameLength < 127) { buf.writeByte(nameLength); buf.writeBytes(observableName.getBytes()); } else { throw new RuntimeException("observableName " + observableName + " exceeds max limit of 127 characters"); } } else { // no name provided, write 0 bytes for name length buf.writeByte(0); } } }
8,765
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/AsyncConnection.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 io.reactivex.mantis.network.push; import java.util.List; import rx.Observer; import rx.functions.Func1; public class AsyncConnection<T> { private String host; private int port; // connections sharing data // should have the same group Id: test-job // a fixed number of slotId's: [1-5] // and a unique id: monotonically increasing number private String groupId; private String slotId; private String id; private Observer<List<byte[]>> subject; private Func1<T, Boolean> predicate; public AsyncConnection(String host, int port, String id, String slotId, String groupId, Observer<List<byte[]>> subject, Func1<T, Boolean> predicate) { this.host = host; this.port = port; this.id = id; this.groupId = groupId; this.subject = subject; this.predicate = predicate; this.slotId = slotId; } public Func1<T, Boolean> getPredicate() { return predicate; } public String getGroupId() { return groupId; } public String getHost() { return host; } public String getSlotId() { return slotId; } public int getPort() { return port; } public String getId() { return id; } public void close() { subject.onCompleted(); } public void write(List<byte[]> data) { subject.onNext(data); } @Override public String toString() { return "AsyncConnection [host=" + host + ", port=" + port + ", groupId=" + groupId + ", slotId=" + slotId + ", id=" + id + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AsyncConnection<T> other = (AsyncConnection<T>) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
8,766
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/HashFunctions.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 io.reactivex.mantis.network.push; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashFunctions { private HashFunctions() {} public static HashFunction ketama() { return new HashFunction() { @Override public long computeHash(byte[] keyBytes) { byte[] bKey = computeMd5(keyBytes); return ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[1] & 0xFF) << 8) | (bKey[0] & 0xFF); } }; } public static byte[] computeMd5(byte[] keyBytes) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported", e); } md5.reset(); md5.update(keyBytes); return md5.digest(); } }
8,767
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/LegacyTcpPushServer.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.WriteBufferWaterMark; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.compression.JdkZlibDecoder; import io.netty.handler.codec.compression.JdkZlibEncoder; import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.timeout.IdleStateHandler; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import mantis.io.reactivex.netty.RxNetty; import mantis.io.reactivex.netty.channel.ConnectionHandler; import mantis.io.reactivex.netty.channel.ObservableConnection; import mantis.io.reactivex.netty.pipeline.PipelineConfigurator; import mantis.io.reactivex.netty.pipeline.PipelineConfiguratorComposite; import mantis.io.reactivex.netty.server.RxServer; import rx.Observable; import rx.functions.Func1; public class LegacyTcpPushServer<T> extends PushServer<T, RemoteRxEvent> { private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate; private String name; private MetricsRegistry metricsRegistry; public LegacyTcpPushServer(PushTrigger<T> trigger, ServerConfig<T> config, Observable<String> serverSignals) { super(trigger, config, serverSignals); this.predicate = config.getPredicate(); this.name = config.getName(); this.metricsRegistry = config.getMetricsRegistry(); } @Override public RxServer<?, ?> createServer() { RxServer<RemoteRxEvent, RemoteRxEvent> server = RxNetty.newTcpServerBuilder(port, new ConnectionHandler<RemoteRxEvent, RemoteRxEvent>() { @Override public Observable<Void> handle( final ObservableConnection<RemoteRxEvent, RemoteRxEvent> newConnection) { final InetSocketAddress socketAddress = (InetSocketAddress) newConnection.getChannel().remoteAddress(); // extract groupId, id, predicate from incoming byte[] return newConnection.getInput() .flatMap(new Func1<RemoteRxEvent, Observable<Void>>() { @Override public Observable<Void> call( RemoteRxEvent incomingRequest) { if (incomingRequest.getType() == RemoteRxEvent.Type.subscribed) { Map<String, String> params = incomingRequest.getSubscribeParameters(); // client state String id = null; String slotId = null; String groupId = null; // sample state boolean enableSampling = false; long samplingTimeMsec = 0; // predicate state Map<String, List<String>> predicateParams = null; if (params != null && !params.isEmpty()) { predicateParams = new HashMap<String, List<String>>(); for (Entry<String, String> entry : params.entrySet()) { List<String> values = new LinkedList<>(); values.add(entry.getValue()); predicateParams.put(entry.getKey(), values); } if (params.containsKey("id")) { id = params.get("id"); } if (params.containsKey("slotId")) { slotId = params.get("slotId"); } if (params.containsKey("groupId")) { groupId = params.get("groupId"); } if (params.containsKey("sample")) { samplingTimeMsec = Long.parseLong(params.get("sample")) * 1000; if (samplingTimeMsec < 50) { throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec); } enableSampling = true; } if (params.containsKey("sampleMSec")) { samplingTimeMsec = Long.parseLong(params.get("sampleMSec")); if (samplingTimeMsec < 50) { throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec); } enableSampling = true; } } Func1<T, Boolean> predicateFunction = null; if (predicate != null) { predicateFunction = predicate.call(predicateParams); } // support legacy metrics per connection Metrics sseSinkMetrics = new Metrics.Builder() .name("DropOperator_outgoing_subject_" + slotId) .addCounter("onNext") .addCounter("dropped") .build(); sseSinkMetrics = metricsRegistry.registerAndGet(sseSinkMetrics); Counter legacyMsgProcessedCounter = sseSinkMetrics.getCounter("onNext"); Counter legacyDroppedWrites = sseSinkMetrics.getCounter("dropped"); return manageConnection(newConnection, socketAddress.getHostString(), socketAddress.getPort(), groupId, slotId, id, null, false, null, enableSampling, samplingTimeMsec, predicateFunction, null, legacyMsgProcessedCounter, legacyDroppedWrites, null); } return null; } }); } }) .pipelineConfigurator(new PipelineConfiguratorComposite<RemoteRxEvent, RemoteRxEvent>( new PipelineConfigurator<RemoteRxEvent, RemoteRxEvent>() { @Override public void configureNewPipeline(ChannelPipeline pipeline) { // pipeline.addLast(new LoggingHandler(LogLevel.ERROR)); // uncomment to enable debug logging pipeline.addLast("idleStateHandler", new IdleStateHandler(10, 2, 0)); pipeline.addLast("heartbeat", new HeartbeatHandler()); pipeline.addLast("gzipInflater", new JdkZlibEncoder(ZlibWrapper.GZIP)); pipeline.addLast("gzipDeflater", new JdkZlibDecoder(ZlibWrapper.GZIP)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); // 4 bytes to encode length pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(5242880, 0, 4, 0, 4)); // max frame = half MB } }, new LegacyTcpPipelineConfigurator(name))) .channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024)) .build(); return server; } }
8,768
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/PushServerSse.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 io.reactivex.mantis.network.push; import com.mantisrx.common.utils.MantisSSEConstants; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.compression.CompressionUtils; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.mql.jvm.core.Query; import io.mantisrx.mql.jvm.interfaces.MQLServer; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelOption; import io.netty.channel.WriteBufferWaterMark; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import mantis.io.reactivex.netty.RxNetty; import mantis.io.reactivex.netty.pipeline.PipelineConfigurators; import mantis.io.reactivex.netty.protocol.http.server.HttpServerRequest; import mantis.io.reactivex.netty.protocol.http.server.HttpServerResponse; import mantis.io.reactivex.netty.protocol.http.server.RequestHandler; import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent; import mantis.io.reactivex.netty.server.RxServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Func1; import rx.functions.Func2; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; public class PushServerSse<T, S> extends PushServer<T, ServerSentEvent> { private static final Logger logger = LoggerFactory.getLogger(PushServerSse.class); public static final String PUSH_SERVER_METRIC_GROUP_NAME = "PushServerSse"; public static final String PUSH_SERVER_LEGACY_METRIC_GROUP_NAME = "ServerSentEventRequestHandler"; public static final String PROCESSED_COUNTER_METRIC_NAME = "processedCounter"; public static final String DROPPED_COUNTER_METRIC_NAME = "droppedCounter"; public static final String CLIENT_ID_TAG_NAME = "clientId"; public static final String SOCK_ADDR_TAG_NAME = "sockAddr"; private Func2<Map<String, List<String>>, S, Void> requestPreprocessor; private Func2<Map<String, List<String>>, S, Void> requestPostprocessor; private final Func2<Map<String, List<String>>, S, Void> subscribeProcessor; private S processorState; private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate; private boolean supportLegacyMetrics; private MetricsRegistry metricsRegistry; public PushServerSse(PushTrigger<T> trigger, ServerConfig<T> config, PublishSubject<String> serverSignals, Func2<Map<String, List<String>>, S, Void> requestPreprocessor, Func2<Map<String, List<String>>, S, Void> requestPostprocessor, final Func2<Map<String, List<String>>, S, Void> subscribeProcessor, S state, boolean supportLegacyMetrics) { super(trigger, config, serverSignals); this.metricsRegistry = config.getMetricsRegistry(); this.predicate = config.getPredicate(); this.processorState = state; this.requestPostprocessor = requestPostprocessor; this.requestPreprocessor = requestPreprocessor; this.subscribeProcessor = subscribeProcessor; this.supportLegacyMetrics = supportLegacyMetrics; } private Metrics registerSseMetrics(String uniqueClientId, String socketAddrStr) { final BasicTag clientIdTag = new BasicTag(CLIENT_ID_TAG_NAME, Optional.ofNullable(uniqueClientId).orElse("none")); final BasicTag sockAddrTag = new BasicTag(SOCK_ADDR_TAG_NAME, Optional.ofNullable(socketAddrStr).orElse("none")); final String metricGroup = supportLegacyMetrics ? PUSH_SERVER_LEGACY_METRIC_GROUP_NAME : PUSH_SERVER_METRIC_GROUP_NAME; Metrics sseSinkMetrics = new Metrics.Builder() .id(metricGroup, clientIdTag, sockAddrTag) .addCounter(PROCESSED_COUNTER_METRIC_NAME) .addCounter(DROPPED_COUNTER_METRIC_NAME) .build(); sseSinkMetrics = metricsRegistry.registerAndGet(sseSinkMetrics); return sseSinkMetrics; } @Override public RxServer<?, ?> createServer() { RxServer<HttpServerRequest<String>, HttpServerResponse<ServerSentEvent>> server = RxNetty.newHttpServerBuilder(port, new RequestHandler<String, ServerSentEvent>() { @Override public Observable<Void> handle( HttpServerRequest<String> request, final HttpServerResponse<ServerSentEvent> response) { final Map<String, List<String>> queryParameters = request.getQueryParameters(); final Counter sseProcessedCounter; final Counter sseDroppedCounter; // heartbeat state boolean enableHeartbeats = false; boolean enableBinaryOutput = false; final AtomicLong heartBeatReadIdleSec = new AtomicLong(2); SerializedSubject<String, String> metaMsgSubject = PublishSubject.<String>create().toSerialized(); final AtomicLong metaMessagesFreqMSec = new AtomicLong(1000); boolean enableMetaMessages = false; final AtomicLong lastWriteTime = new AtomicLong(); Subscription heartbeatSubscription = null; Subscription metaMsgSubscription = null; // sample state boolean enableSampling = false; long samplingTimeMsec = 0; // client state String groupId = null; String slotId = null; String id = null; Func1<T, Boolean> predicateFunction = null; if (predicate != null) { predicateFunction = predicate.call(queryParameters); } byte[] delimiter = CompressionUtils.MANTIS_SSE_DELIMITER_BINARY; if (queryParameters != null && !queryParameters.isEmpty()) { if (queryParameters.containsKey(MantisSSEConstants.ID)) { id = queryParameters.get(MantisSSEConstants.ID).get(0); } if (queryParameters.containsKey(MantisSSEConstants.SLOT_ID)) { slotId = queryParameters.get(MantisSSEConstants.SLOT_ID).get(0); } // support groupId and clientId for grouping if (queryParameters.containsKey(MantisSSEConstants.GROUP_ID)) { groupId = queryParameters.get(MantisSSEConstants.GROUP_ID).get(0); } if (queryParameters.containsKey(MantisSSEConstants.CLIENT_ID)) { groupId = queryParameters.get(MantisSSEConstants.CLIENT_ID).get(0); } if (queryParameters.containsKey(MantisSSEConstants.HEARTBEAT_SEC)) { heartBeatReadIdleSec.set(Long.parseLong(queryParameters.get(MantisSSEConstants.HEARTBEAT_SEC).get(0))); if (heartBeatReadIdleSec.get() < 1) { throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec); } enableHeartbeats = true; } if (queryParameters != null && queryParameters.containsKey(MantisSSEConstants.MANTIS_ENABLE_COMPRESSION)) { String enableBinaryOutputStr = queryParameters.get(MantisSSEConstants.MANTIS_ENABLE_COMPRESSION).get(0); if ("true".equalsIgnoreCase(enableBinaryOutputStr)) { logger.info("Binary compression requested"); enableBinaryOutput = true; } } if (queryParameters.containsKey(MantisSSEConstants.ENABLE_PINGS)) { String enablePings = queryParameters.get(MantisSSEConstants.ENABLE_PINGS).get(0); if ("true".equalsIgnoreCase(enablePings)) { enableHeartbeats = true; } } if (queryParameters.containsKey(MantisSSEConstants.ENABLE_META_MESSAGES)) { String enableMetaMessagesStr = queryParameters.get(MantisSSEConstants.ENABLE_META_MESSAGES).get(0); if ("true".equalsIgnoreCase(enableMetaMessagesStr)) { enableMetaMessages = true; } } if (queryParameters.containsKey(MantisSSEConstants.META_MESSAGES_SEC)) { metaMessagesFreqMSec.set(Long.parseLong(queryParameters.get(MantisSSEConstants.META_MESSAGES_SEC).get(0))); if (metaMessagesFreqMSec.get() < 250) { throw new IllegalArgumentException("Meta message frequence rate too low: " + metaMessagesFreqMSec.get()); } enableMetaMessages = true; } if (queryParameters.containsKey(MantisSSEConstants.SAMPLE)) { samplingTimeMsec = Long.parseLong(queryParameters.get(MantisSSEConstants.SAMPLE).get(0)) * 1000; if (samplingTimeMsec < 50) { throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec); } enableSampling = true; } if (queryParameters.containsKey(MantisSSEConstants.SAMPLE_M_SEC)) { samplingTimeMsec = Long.parseLong(queryParameters.get(MantisSSEConstants.SAMPLE_M_SEC).get(0)); if (samplingTimeMsec < 50) { throw new IllegalArgumentException("Sampling rate too low: " + samplingTimeMsec); } enableSampling = true; } if (queryParameters.containsKey(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER)) { String rawDelimiter = queryParameters.get(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER).get(0); if (rawDelimiter != null && !rawDelimiter.isEmpty()) { delimiter = rawDelimiter.getBytes(); } } if (queryParameters.containsKey(MantisSSEConstants.MQL)) { String query = queryParameters.get(MantisSSEConstants.MQL).get(0); if (MQLServer.parses(query)) { Query q = MQLServer.parse(query); predicateFunction = (T datum) -> datum instanceof Map ? q.matches((Map) datum) : true; } } } InetSocketAddress socketAddress = (InetSocketAddress) response.getChannel().remoteAddress(); Metrics metrics; if (groupId == null) { String address = socketAddress.getAddress().toString(); metrics = registerSseMetrics(address, address); } else { metrics = registerSseMetrics(groupId, socketAddress.getAddress().toString()); } sseProcessedCounter = metrics.getCounter(PROCESSED_COUNTER_METRIC_NAME); sseDroppedCounter = metrics.getCounter(DROPPED_COUNTER_METRIC_NAME); response.getHeaders().set("Access-Control-Allow-Origin", "*"); response.getHeaders().set("content-type", "text/event-stream"); response.getHeaders().set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.getHeaders().set("Pragma", "no-cache"); response.flush(); if (queryParameters != null && requestPreprocessor != null) { requestPreprocessor.call(queryParameters, processorState); } if (enableMetaMessages && metaMessagesFreqMSec.get() > 0) { logger.info("Enabling Meta messages, interval : " + metaMessagesFreqMSec.get() + " ms"); metaMsgSubscription = metaMsgSubject .throttleLast(metaMessagesFreqMSec.get(), TimeUnit.MILLISECONDS) .doOnNext((String t) -> { if (t != null && !t.isEmpty()) { long currentTime = System.currentTimeMillis(); ByteBuf data = response.getAllocator().buffer().writeBytes(t.getBytes()); response.writeAndFlush(new ServerSentEvent(data)); lastWriteTime.set(currentTime); } } ).subscribe(); } if (enableHeartbeats && heartBeatReadIdleSec.get() > 0) { logger.info("Enabling hearts, interval: " + heartBeatReadIdleSec); heartbeatSubscription = Observable .interval(2, heartBeatReadIdleSec.get(), TimeUnit.SECONDS) .doOnNext((Long t1) -> { long currentTime = System.currentTimeMillis(); long diff = (currentTime - lastWriteTime.get()) / 1000; if (diff > heartBeatReadIdleSec.get()) { ByteBuf data = response.getAllocator().buffer().writeBytes("ping".getBytes()); response.writeAndFlush(new ServerSentEvent(data)); lastWriteTime.set(currentTime); } } ).subscribe(); } Action0 connectionClosedCallback = null; if (queryParameters != null && requestPostprocessor != null) { connectionClosedCallback = new Action0() { @Override public void call() { requestPostprocessor.call(queryParameters, processorState); } }; } class SubscribeCallback implements Action0 { @Override public void call() { if (queryParameters != null && subscribeProcessor != null) { subscribeProcessor.call(queryParameters, processorState); } } } return manageConnectionWithCompression(response, socketAddress.getHostString(), socketAddress.getPort(), groupId, slotId, id, lastWriteTime, enableHeartbeats, heartbeatSubscription, enableSampling, samplingTimeMsec, metaMsgSubject, metaMsgSubscription, predicateFunction, connectionClosedCallback, sseProcessedCounter, sseDroppedCounter, new SubscribeCallback(), enableBinaryOutput, true, delimiter); } }) .pipelineConfigurator(PipelineConfigurators.serveSseConfigurator()) .channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024)) .build(); return server; } }
8,769
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/TimedChunker.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.common.metrics.spectator.MetricGroupId; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class TimedChunker<T> implements Callable<Void> { private static ThreadFactory namedFactory = new NamedThreadFactory("TimedChunkerGroup"); private MonitoredQueue<T> buffer; private ChunkProcessor<T> processor; private ScheduledExecutorService scheduledService = Executors.newSingleThreadScheduledExecutor(namedFactory); private int maxBufferLength; private int maxTimeMSec; private ConnectionManager<T> connectionManager; private List<T> internalBuffer; private Counter interrupted; private Counter numEventsDrained; private Counter drainTriggeredByTimer; private Counter drainTriggeredByBatch; public TimedChunker(MonitoredQueue<T> buffer, int maxBufferLength, int maxTimeMSec, ChunkProcessor<T> processor, ConnectionManager<T> connectionManager) { this.maxBufferLength = maxBufferLength; this.maxTimeMSec = maxTimeMSec; this.buffer = buffer; this.processor = processor; this.connectionManager = connectionManager; this.internalBuffer = new ArrayList<>(maxBufferLength); MetricGroupId metricsGroup = new MetricGroupId("TimedChunker"); Metrics metrics = new Metrics.Builder() .id(metricsGroup) .addCounter("interrupted") .addCounter("numEventsDrained") .addCounter("drainTriggeredByTimer") .addCounter("drainTriggeredByBatch") .build(); interrupted = metrics.getCounter("interrupted"); numEventsDrained = metrics.getCounter("numEventsDrained"); drainTriggeredByTimer = metrics.getCounter("drainTriggeredByTimer"); drainTriggeredByBatch = metrics.getCounter("drainTriggeredByBatch"); MetricsRegistry.getInstance().registerAndGet(metrics); } @Override public Void call() throws Exception { ScheduledFuture periodicDrain = scheduledService.scheduleAtFixedRate(() -> { drainTriggeredByTimer.increment(); drain(); }, maxTimeMSec, maxTimeMSec, TimeUnit.MILLISECONDS); while (!stopCondition()) { try { T data = buffer.get(); synchronized (internalBuffer) { internalBuffer.add(data); } if (internalBuffer.size() >= maxBufferLength) { drainTriggeredByBatch.increment(); drain(); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); periodicDrain.cancel(true); interrupted.increment(); } } drain(); return null; } private boolean stopCondition() { return Thread.currentThread().isInterrupted(); } private void drain() { if (internalBuffer.size() > 0) { List<T> copy = new ArrayList<>(internalBuffer.size()); synchronized (internalBuffer) { // internalBuffer content may have changed since acquiring the lock. copy.addAll(internalBuffer); internalBuffer.clear(); } if (copy.size() > 0) { processor.process(connectionManager, copy); numEventsDrained.increment(copy.size()); } } } }
8,770
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/HashFunction.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 io.reactivex.mantis.network.push; public interface HashFunction { public long computeHash(byte[] bytes); }
8,771
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/SnapshotCache.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 io.reactivex.mantis.network.push; public class SnapshotCache<T> { private T cache; private long timestamp; public SnapshotCache(T cache) { this.cache = cache; this.timestamp = System.currentTimeMillis(); } public T getCache() { return cache; } public long getTimestamp() { return timestamp; } }
8,772
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/GroupChunkProcessor.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 io.reactivex.mantis.network.push; import java.util.List; import java.util.Map; public class GroupChunkProcessor<T> extends ChunkProcessor<T> { public GroupChunkProcessor(Router<T> router) { super(router); } @Override public void process(ConnectionManager<T> connectionManager, List<T> chunks) { Map<String, ConnectionGroup<T>> groups = connectionManager.groups(); for (ConnectionGroup<T> group : groups.values()) { router.route(group.getConnections(), chunks); } } }
8,773
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/MonitoredThreadPool.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 io.reactivex.mantis.network.push; import com.mantisrx.common.utils.MantisMetricStringConstants; import com.netflix.spectator.api.BasicTag; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.spectator.GaugeCallback; import io.mantisrx.common.metrics.spectator.MetricGroupId; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MonitoredThreadPool { private static final Logger logger = LoggerFactory.getLogger(MonitoredThreadPool.class); private String name; private ThreadPoolExecutor threadPool; private Metrics metrics; private Counter rejectCount; private Counter exceptions; public MonitoredThreadPool(String name, final ThreadPoolExecutor threadPool) { this.name = name; this.threadPool = threadPool; this.threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) { rejected(); } }); final String poolId = Optional.ofNullable(name).orElse("none"); final BasicTag tag = new BasicTag(MantisMetricStringConstants.GROUP_ID_TAG, poolId); final MetricGroupId metricsGroup = new MetricGroupId("MonitoredThreadPool", tag); Gauge activeTasks = new GaugeCallback(metricsGroup, "activeTasks", () -> (double) threadPool.getActiveCount()); Gauge queueLength = new GaugeCallback(metricsGroup, "queueLength", () -> (double) threadPool.getQueue().size()); metrics = new Metrics.Builder() .id(metricsGroup) .addCounter("rejectCount") .addCounter("exceptions") .addGauge(activeTasks) .addGauge(queueLength) .build(); rejectCount = metrics.getCounter("rejectCount"); exceptions = metrics.getCounter("exceptions"); } private void rejected() { logger.warn("Monitored thread pool: " + name + " rejected task."); rejectCount.increment(); } public Metrics getMetrics() { return metrics; } public int getMaxPoolSize() { return threadPool.getMaximumPoolSize(); } public <T> Future<T> submit(final Callable<T> task) { // wrap with exception handling Future<T> future = threadPool.submit(new Callable<T>() { @Override public T call() throws Exception { T returnValue = null; try { returnValue = task.call(); } catch (Exception e) { logger.warn("Exception occured in running thread", e); exceptions.increment(); } return returnValue; } }); return future; } public void execute(final Runnable task) { // wrap with exception handling threadPool.execute(new Runnable() { @Override public void run() { try { task.run(); } catch (Exception e) { logger.warn("Exception occured in running thread", e); exceptions.increment(); } } }); } }
8,774
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/ServerConfig.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 io.reactivex.mantis.network.push; import io.mantisrx.common.metrics.MetricsRegistry; import java.util.List; import java.util.Map; import rx.functions.Func1; public class ServerConfig<T> { private String name; private int port; private int numQueueConsumers = 1; // number of threads chunking queue private int bufferCapacity = 100; // max queue size private int writeRetryCount = 2; // num retries before fail to write private int maxChunkSize = 25; // max items to read from queue, for a single chunk private int maxChunkTimeMSec = 100; // max time to read from queue, for a single chunk private int maxNotWritableTimeSec = -1; // max time the channel can stay not writable, <= 0 means unlimited private ChunkProcessor<T> chunkProcessor; // logic to process chunk private MetricsRegistry metricsRegistry; // registry used to store metrics private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate; private boolean useSpscQueue = false; public ServerConfig(Builder<T> builder) { this.name = builder.name; this.port = builder.port; this.bufferCapacity = builder.bufferCapacity; this.writeRetryCount = builder.writeRetryCount; this.maxChunkSize = builder.maxChunkSize; this.maxChunkTimeMSec = builder.maxChunkTimeMSec; this.chunkProcessor = builder.chunkProcessor; this.metricsRegistry = builder.metricsRegistry; this.numQueueConsumers = builder.numQueueConsumers; this.predicate = builder.predicate; this.useSpscQueue = builder.useSpscQueue; this.maxNotWritableTimeSec = builder.maxNotWritableTimeSec; } public Func1<Map<String, List<String>>, Func1<T, Boolean>> getPredicate() { return predicate; } public int getNumQueueConsumers() { return numQueueConsumers; } public String getName() { return name; } public int getPort() { return port; } public int getBufferCapacity() { return bufferCapacity; } public int getWriteRetryCount() { return writeRetryCount; } public int getMaxChunkSize() { return maxChunkSize; } public int getMaxChunkTimeMSec() { return maxChunkTimeMSec; } public int getMaxNotWritableTimeSec() { return maxNotWritableTimeSec; } public ChunkProcessor<T> getChunkProcessor() { return chunkProcessor; } public MetricsRegistry getMetricsRegistry() { return metricsRegistry; } public boolean useSpscQueue() { return useSpscQueue; } public static class Builder<T> { private String name; private int port; private int numQueueConsumers = 1; // number of threads chunking queue private int bufferCapacity = 100; // max queue size private int writeRetryCount = 2; // num retries before fail to write private int maxChunkSize = 25; // max items to read from queue, for a single chunk private int maxChunkTimeMSec = 100; // max time to read from queue, for a single chunk private int maxNotWritableTimeSec = -1; // max time the channel can stay not writable, <= 0 means unlimited private ChunkProcessor<T> chunkProcessor; // logic to process chunk private MetricsRegistry metricsRegistry; // registry used to store metrics private Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate; private boolean useSpscQueue = false; public Builder<T> predicate(Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate) { this.predicate = predicate; return this; } public Builder<T> name(String name) { this.name = name; return this; } public Builder<T> bufferCapacity(int bufferCapacity) { this.bufferCapacity = bufferCapacity; return this; } public Builder<T> useSpscQueue(boolean useSpsc) { this.useSpscQueue = useSpsc; return this; } public Builder<T> port(int port) { this.port = port; return this; } public Builder<T> numQueueConsumers(int numQueueConsumers) { this.numQueueConsumers = numQueueConsumers; return this; } public Builder<T> writeRetryCount(int writeRetryCount) { this.writeRetryCount = writeRetryCount; return this; } public Builder<T> maxChunkSize(int maxChunkSize) { this.maxChunkSize = maxChunkSize; return this; } public Builder<T> maxChunkTimeMSec(int maxChunkTimeMSec) { this.maxChunkTimeMSec = maxChunkTimeMSec; return this; } public Builder<T> maxNotWritableTimeSec(int maxNotWritableTimeSec) { this.maxNotWritableTimeSec = maxNotWritableTimeSec; return this; } public Builder<T> groupRouter(Router<T> router) { this.chunkProcessor = new GroupChunkProcessor<>(router); return this; } public Builder<T> router(Router<T> router) { this.chunkProcessor = new ChunkProcessor<>(router); return this; } public Builder<T> metricsRegistry(MetricsRegistry metricsRegistry) { this.metricsRegistry = metricsRegistry; return this; } public ServerConfig<T> build() { return new ServerConfig<>(this); } } }
8,775
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/SingleThreadedChunker.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 io.reactivex.mantis.network.push; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; public class SingleThreadedChunker<T> implements Callable<Void> { final MonitoredQueue<T> inputQueue; final int TIME_PROBE_COUNT = 100000; final private int chunkSize; final private long maxChunkInterval; final private ConnectionManager<T> connectionManager; final private ChunkProcessor<T> processor; final private Object[] chunk; int iteration = 0; private int index = 0; public SingleThreadedChunker(ChunkProcessor<T> processor, MonitoredQueue<T> iQ, int chunkSize, long maxChunkInterval, ConnectionManager<T> connMgr) { this.inputQueue = iQ; this.chunkSize = chunkSize; this.maxChunkInterval = maxChunkInterval; this.processor = processor; this.connectionManager = connMgr; chunk = new Object[this.chunkSize]; } private boolean stopCondition() { return Thread.currentThread().isInterrupted(); } @Override public Void call() throws Exception { long chunkStartTime = System.currentTimeMillis(); while (true) { iteration++; if (iteration == TIME_PROBE_COUNT) { long currTime = System.currentTimeMillis(); if (currTime - maxChunkInterval > chunkStartTime) { drain(); } iteration = 0; if (stopCondition()) { break; } } if (index < this.chunkSize) { T ele = inputQueue.poll(); if (ele != null) { chunk[index++] = ele; } } else { drain(); chunkStartTime = System.currentTimeMillis(); if (stopCondition()) { break; } } } return null; } private void drain() { if (index > 0) { List<T> copy = new ArrayList<T>(index); for (int i = 0; i < index; i++) { copy.add((T) chunk[i]); } processor.process(connectionManager, copy); index = 0; } } }
8,776
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/RemoteRxEvent.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 io.reactivex.mantis.network.push; import java.util.ArrayList; import java.util.List; import java.util.Map; public class RemoteRxEvent { private String name; private Type type; private byte[] data; private Map<String, String> subscriptionParameters; public RemoteRxEvent(String name, Type type, byte[] data, Map<String, String> subscriptionParameters) { this.name = name; this.type = type; this.data = data; this.subscriptionParameters = subscriptionParameters; } public static List<RemoteRxEvent> heartbeat() { List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1); list.add(new RemoteRxEvent(null, Type.heartbeat, null, null)); return list; } public static RemoteRxEvent nonDataError(String name, byte[] errorData) { return new RemoteRxEvent(null, Type.nonDataError, errorData, null); } public static RemoteRxEvent next(String name, byte[] nextData) { return new RemoteRxEvent(name, Type.next, nextData, null); } public static RemoteRxEvent completed(String name) { return new RemoteRxEvent(name, Type.completed, null, null); } public static RemoteRxEvent error(String name, byte[] errorData) { return new RemoteRxEvent(name, Type.error, errorData, null); } public static List<RemoteRxEvent> subscribed(String name, Map<String, String> subscriptionParameters) { List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1); list.add(new RemoteRxEvent(name, Type.subscribed, null, subscriptionParameters)); return list; } public static List<RemoteRxEvent> unsubscribed(String name) { List<RemoteRxEvent> list = new ArrayList<RemoteRxEvent>(1); list.add(new RemoteRxEvent(name, Type.unsubscribed, null, null)); return list; } public byte[] getData() { return data; } public Type getType() { return type; } public String getName() { return name; } Map<String, String> getSubscribeParameters() { return subscriptionParameters; } @Override public String toString() { return "RemoteRxEvent [name=" + name + ", type=" + type + ", subscriptionParameters=" + subscriptionParameters + "]"; } public enum Type { next, completed, error, subscribed, unsubscribed, heartbeat, // used by clients to close connection // during a network partition to avoid // scenario where client subscription is active // but server has forced unsubscribe due to partition. // A server will force unsubscribe if unable to // write to client after a certain number of attempts. nonDataError // used by server to inform client of errors // occurred that are not on the data // stream, example: slotting error } }
8,777
0
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network
Create_ds/mantis/mantis-network/src/main/java/io/reactivex/mantis/network/push/RoundRobinRouter.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 io.reactivex.mantis.network.push; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import rx.functions.Func1; public class RoundRobinRouter<T> extends Router<T> { public RoundRobinRouter(String name, Func1<T, byte[]> encoder) { super("RoundRobinRouter_" + name, encoder); } @Override public void route(Set<AsyncConnection<T>> connections, List<T> chunks) { if (chunks != null && !chunks.isEmpty()) { numEventsProcessed.increment(chunks.size()); } List<AsyncConnection<T>> randomOrder = new ArrayList<>(connections); Collections.shuffle(randomOrder); if (chunks != null && !chunks.isEmpty() && !randomOrder.isEmpty()) { Iterator<AsyncConnection<T>> iter = loopingIterator(randomOrder); Map<AsyncConnection<T>, List<byte[]>> writes = new HashMap<>(); // process chunks for (T chunk : chunks) { AsyncConnection<T> connection = iter.next(); Func1<T, Boolean> predicate = connection.getPredicate(); if (predicate == null || predicate.call(chunk)) { List<byte[]> buffer = writes.get(connection); if (buffer == null) { buffer = new LinkedList<>(); writes.put(connection, buffer); } buffer.add(encoder.call(chunk)); } } if (!writes.isEmpty()) { for (Entry<AsyncConnection<T>, List<byte[]>> entry : writes.entrySet()) { AsyncConnection<T> connection = entry.getKey(); List<byte[]> toWrite = entry.getValue(); connection.write(toWrite); numEventsRouted.increment(toWrite.size()); } } } } private Iterator<AsyncConnection<T>> loopingIterator(final Collection<AsyncConnection<T>> connections) { final AtomicReference<Iterator<AsyncConnection<T>>> iterRef = new AtomicReference<>(connections.iterator()); return new Iterator<AsyncConnection<T>>() { @Override public boolean hasNext() { return true; } @Override public AsyncConnection<T> next() { Iterator<AsyncConnection<T>> iter = iterRef.get(); if (iter.hasNext()) { return iter.next(); } else { iterRef.set(connections.iterator()); return iterRef.get().next(); } } }; } }
8,778
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/MergedObservableTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import org.junit.Assert; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.observables.MathObservable; public class MergedObservableTest { @Test public void testMergeCount() { MergeCounts counts = new MergeCounts(3); Assert.assertEquals(false, counts.incrementTerminalCountAndCheck()); Assert.assertEquals(false, counts.incrementTerminalCountAndCheck()); Assert.assertEquals(true, counts.incrementTerminalCountAndCheck()); } @Test public void testFixedMerge() throws InterruptedException { MergedObservable<Integer> merged = MergedObservable.createWithReplay(2); merged.mergeIn("t1", Observable.range(1, 50)); merged.mergeIn("t2", Observable.range(51, 50)); MathObservable.sumInteger(Observable.merge(merged.get())) .toBlocking() .forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); } }); } @Test(expected = RuntimeException.class) public void testMergeInBadObservable() throws InterruptedException { MergedObservable<Integer> merged = MergedObservable.createWithReplay(2); merged.mergeIn("t1", Observable.range(1, 50)); Observable<Integer> badObservable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 100; i < 200; i++) { subscriber.onNext(i); if (i == 150) { subscriber.onError(new Exception("bad")); } } } }); merged.mergeIn("t2", badObservable); MathObservable.sumInteger(Observable.merge(merged.get())) .toBlocking() .forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); } }); } @Test public void testSingleRemoteObservableMerge() { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect Observable<Integer> ro = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); MergedObservable<Integer> merged = MergedObservable.createWithReplay(1); merged.mergeIn("t1", ro); // assert MathObservable.sumInteger(Observable.merge(merged.get())) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testThreeRemoteObservablesMerge() { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect Observable<Integer> ro1 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); Observable<Integer> ro2 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); Observable<Integer> ro3 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); MergedObservable<Integer> merged = MergedObservable.createWithReplay(3); merged.mergeIn("t1", ro1); merged.mergeIn("t2", ro2); merged.mergeIn("t3", ro3); // assert MathObservable.sumInteger(Observable.merge(merged.get())) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(15150, t1.intValue()); // sum of number 0-100 } }); } //@Test public void testMergeFromMultipleSources() { // setup Observable<Integer> os1 = Observable.range(1, 100); Observable<Integer> os2 = Observable.range(101, 100); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort1 = portSelector.acquirePort(); int serverPort2 = portSelector.acquirePort(); RemoteRxServer server1 = RemoteObservable.serve(serverPort1, os1, Codecs.integer()); server1.start(); RemoteRxServer server2 = RemoteObservable.serve(serverPort2, os2, Codecs.integer()); server2.start(); // connect Observable<Integer> ro1 = RemoteObservable.connect("localhost", serverPort1, Codecs.integer()); Observable<Integer> ro2 = RemoteObservable.connect("localhost", serverPort2, Codecs.integer()); MergedObservable<Integer> merged = MergedObservable.createWithReplay(2); merged.mergeIn("t1", ro1); merged.mergeIn("t2", ro2); // assert MathObservable.sumInteger(Observable.merge(merged.get())) .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(20100, t1.intValue()); // sum of number 0-100 } }); } }
8,779
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/DynamicConnectionSetTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import io.mantisrx.common.network.Endpoint; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.observables.MathObservable; import rx.subjects.ReplaySubject; public class DynamicConnectionSetTest { @Test public void testMergeInConnections() throws InterruptedException { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, Observable.range(51, 50), Codecs.integer()); server1.start(); server2.start(); EndpointInjector staticEndpoints = new EndpointInjector() { @Override public Observable<EndpointChange> deltas() { return Observable.create(new OnSubscribe<EndpointChange>() { @Override public void call(Subscriber<? super EndpointChange> subscriber) { subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server1Port, "1"))); subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server2Port, "2"))); subscriber.onCompleted(); } }); } }; DynamicConnectionSet<Integer> cm = DynamicConnectionSet.create(new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer())); cm.setEndpointInjector(staticEndpoints); int sum = MathObservable.sumInteger(Observable.merge(cm.observables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } @Test public void testMergeInWithDeltaEndpointService() { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, Observable.range(51, 50), Codecs.integer()); server1.start(); server2.start(); ReplaySubject<List<Endpoint>> subject = ReplaySubject.create(); List<Endpoint> endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", server1Port)); endpoints.add(new Endpoint("localhost", server2Port)); subject.onNext(endpoints); subject.onCompleted(); DynamicConnectionSet<Integer> cm = DynamicConnectionSet.create(new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer())); cm.setEndpointInjector(new ToDeltaEndpointInjector(subject)); int sum = MathObservable.sumInteger(Observable.merge(cm.observables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } @Test(expected = RuntimeException.class) public void testMergeInBadObservable() throws InterruptedException { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); Observable<Integer> badObservable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 100; i < 200; i++) { subscriber.onNext(i); if (i == 150) { subscriber.onError(new Exception("error")); } } } }); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, badObservable, Codecs.integer()); server1.start(); server2.start(); EndpointInjector staticEndpoints = new EndpointInjector() { @Override public Observable<EndpointChange> deltas() { return Observable.create(new OnSubscribe<EndpointChange>() { @Override public void call(Subscriber<? super EndpointChange> subscriber) { subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server1Port, "1"))); subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server2Port, "2"))); subscriber.onCompleted(); } }); } }; DynamicConnectionSet<Integer> cm = DynamicConnectionSet.create(new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer())); cm.setEndpointInjector(staticEndpoints); int sum = MathObservable.sumInteger(Observable.merge(cm.observables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } }
8,780
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/Pair.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 io.reactivex.mantis.remote.observable; public class Pair { private String name; private Integer value; public Pair(String name, Integer value) { this.name = name; this.value = value; } public String getName() { return name; } public Integer getValue() { return value; } @Override public String toString() { return "Pair [name=" + name + ", value=" + value + "]"; } }
8,781
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/DynamicConnectionTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import io.mantisrx.common.network.Endpoint; import junit.framework.Assert; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.observables.MathObservable; public class DynamicConnectionTest { @Test public void dynamicConnectionTest() throws InterruptedException { // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int serverPort1 = portSelector.acquirePort(); final int serverPort2 = portSelector.acquirePort(); RemoteRxServer server1 = RemoteObservable.serve(serverPort1, Observable.range(1, 100), Codecs.integer()); server1.start(); RemoteRxServer server2 = RemoteObservable.serve(serverPort2, Observable.range(101, 100), Codecs.integer()); server2.start(); Observable<Endpoint> endpointSwitch = Observable.create(new OnSubscribe<Endpoint>() { @Override public void call(Subscriber<? super Endpoint> subscriber) { subscriber.onNext(new Endpoint("localhost", serverPort1)); // switch connection subscriber.onNext(new Endpoint("localhost", serverPort2)); } }); ConnectToObservable.Builder<Integer> config = new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer()); DynamicConnection<Integer> connection = DynamicConnection.create(config, endpointSwitch); MathObservable.sumInteger(connection.observable()) .last() .subscribe(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(20100, t1.intValue()); } }); Thread.sleep(1000); // wait for async computation connection.close(); } }
8,782
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/RemoteGroupedObservableTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import io.reactivex.mantis.remote.observable.slotting.ConsistentHashing; import org.junit.Assert; import org.junit.Test; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.GroupedObservable; import rx.schedulers.Schedulers; public class RemoteGroupedObservableTest { @Test public void testConsistentSlottingServer() throws InterruptedException { // setup Observable<Observable<GroupedObservable<String, Integer>>> go = Observable.just( Observable.range(1, 10) // subscribeOn to unblock range operator .subscribeOn(Schedulers.io()) .groupBy(new Func1<Integer, String>() { @Override public String call(Integer t1) { if (t1 % 2 == 0) { return "even"; } else { return "odd"; } } })); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeGroupedObservable.Builder<String, Integer>() .name("grouped") .keyEncoder(Codecs.string()) .valueEncoder(Codecs.integer()) .observable(go) .slottingStrategy(new ConsistentHashing<Group<String, Integer>>()) .build()) .build(); server.start(); Observable<GroupedObservable<String, Integer>> ro1 = RemoteObservable .connect(new ConnectToGroupedObservable.Builder<String, Integer>() .host("localhost") .port(serverPort) .name("grouped") .keyDecoder(Codecs.string()) .valueDecoder(Codecs.integer()) .build()) .getObservable(); Observable<GroupedObservable<String, Integer>> ro2 = RemoteObservable .connect(new ConnectToGroupedObservable.Builder<String, Integer>() .host("localhost") .port(serverPort) .name("grouped") .keyDecoder(Codecs.string()) .valueDecoder(Codecs.integer()) .build()) .getObservable(); final MutableReference<Integer> intRef = new MutableReference<>(0); Observable.merge(ro1, ro2) .flatMap(new Func1<GroupedObservable<String, Integer>, Observable<Result>>() { @Override public Observable<Result> call(final GroupedObservable<String, Integer> group) { return group.reduce(new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }) .map(new Func1<Integer, Result>() { @Override public Result call(Integer t1) { return new Result(group.getKey(), t1); } }); } }).toBlocking().forEach(new Action1<Result>() { @Override public void call(Result result) { if (result.getKey().equals("odd")) { Assert.assertEquals(25, result.getResults().intValue()); intRef.setValue(intRef.getValue() + 1); } else { Assert.assertEquals(30, result.getResults().intValue()); intRef.setValue(intRef.getValue() + 1); } } }); Assert.assertEquals(2, intRef.getValue().intValue()); } }
8,783
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/FixedConnectionSetTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import io.mantisrx.common.network.Endpoint; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.observables.MathObservable; import rx.subjects.ReplaySubject; public class FixedConnectionSetTest { @Test public void testMergeInConnections() throws InterruptedException { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, Observable.range(51, 50), Codecs.integer()); server1.start(); server2.start(); EndpointInjector staticEndpoints = new EndpointInjector() { @Override public Observable<EndpointChange> deltas() { return Observable.create(new OnSubscribe<EndpointChange>() { @Override public void call(Subscriber<? super EndpointChange> subscriber) { subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server1Port, "1"))); subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server2Port, "2"))); subscriber.onCompleted(); } }); } }; FixedConnectionSet<Integer> cm = FixedConnectionSet.create(2, new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer()), staticEndpoints); int sum = MathObservable.sumInteger(Observable.merge(cm.getObservables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } @Test public void testMergeInWithDeltaEndpointService() { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, Observable.range(51, 50), Codecs.integer()); server1.start(); server2.start(); ReplaySubject<List<Endpoint>> subject = ReplaySubject.create(); List<Endpoint> endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", server1Port)); endpoints.add(new Endpoint("localhost", server2Port)); subject.onNext(endpoints); FixedConnectionSet<Integer> cm = FixedConnectionSet.create(2, new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer()), new ToDeltaEndpointInjector(subject)); int sum = MathObservable.sumInteger(Observable.merge(cm.getObservables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } @Test(expected = RuntimeException.class) public void testMergeInBadObservable() throws InterruptedException { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); final int server1Port = portSelector.acquirePort(); final int server2Port = portSelector.acquirePort(); Observable<Integer> badObservable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 100; i < 200; i++) { subscriber.onNext(i); if (i == 150) { subscriber.onError(new Exception("error")); } } } }); // setup servers RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer()); RemoteRxServer server2 = RemoteObservable.serve(server2Port, badObservable, Codecs.integer()); server1.start(); server2.start(); EndpointInjector staticEndpoints = new EndpointInjector() { @Override public Observable<EndpointChange> deltas() { return Observable.create(new OnSubscribe<EndpointChange>() { @Override public void call(Subscriber<? super EndpointChange> subscriber) { subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server1Port, "1"))); subscriber.onNext(new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", server2Port, "2"))); subscriber.onCompleted(); } }); } }; FixedConnectionSet<Integer> cm = FixedConnectionSet.create(2, new ConnectToObservable.Builder<Integer>() .decoder(Codecs.integer()), staticEndpoints); int sum = MathObservable.sumInteger(Observable.merge(cm.getObservables())) .toBlocking() .last(); Assert.assertEquals(5050, sum); } }
8,784
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/ServeNestedTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import org.junit.Assert; import org.junit.Test; import rx.Observable; import rx.functions.Action1; import rx.observables.MathObservable; public class ServeNestedTest { @Test public void testServeNested() { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); Observable<Observable<Integer>> oo = Observable.just(Observable.range(1, 100)); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeNestedObservable.Builder<Integer>() .name("ints") .encoder(Codecs.integer()) .observable(oo) .build()) .build(); server.start(); Observable<Integer> ro = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .name("ints") .decoder(Codecs.integer()) .build()) .getObservable(); MathObservable.sumInteger(ro).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testServeNestedChained() { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort1 = portSelector.acquirePort(); int serverPort2 = portSelector.acquirePort(); Observable<Observable<Integer>> oo = Observable.just(Observable.range(1, 100)); RemoteRxServer server1 = new RemoteRxServer.Builder() .port(serverPort1) .addObservable(new ServeNestedObservable.Builder<Integer>() .name("ints") .encoder(Codecs.integer()) .observable(oo) .build()) .build(); server1.start(); Observable<Integer> ro1 = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort1) .name("ints") .decoder(Codecs.integer()) .build()) .getObservable(); RemoteRxServer server2 = new RemoteRxServer.Builder() .port(serverPort2) .addObservable(new ServeNestedObservable.Builder<Integer>() .name("ints") .encoder(Codecs.integer()) .observable(Observable.just(ro1)) .build()) .build(); server2.start(); Observable<Integer> ro2 = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort2) .name("ints") .decoder(Codecs.integer()) .build()) .getObservable(); MathObservable.sumInteger(ro2).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } }
8,785
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/RemoteObservableTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import io.reactivex.mantis.remote.observable.filter.ServerSideFilters; import io.reactivex.mantis.remote.observable.slotting.RoundRobin; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Assert; import org.junit.Test; import rx.Notification; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.MathObservable; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import rx.subjects.ReplaySubject; public class RemoteObservableTest { @After public void waitForServerToShutdown() { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testServeObservable() throws InterruptedException { // setup Observable<Integer> os = Observable.range(0, 101).subscribeOn(Schedulers.io()); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testServeNestedObservable() throws InterruptedException { // setup Observable<Observable<Integer>> os = Observable.just(Observable.range(1, 100), Observable.range(1, 100), Observable.range(1, 100)); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeNestedObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(os) .build()) .build(); server.start(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(15150, t1.intValue()); // sum of number 0-100 } }); } @Test public void testServeManyObservable() throws InterruptedException { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect Observable<Integer> oc1 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc1).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); // connect Observable<Integer> oc2 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc2).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); // connect Observable<Integer> oc3 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc3).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } // @Test public void testServeManyWithErrorObservable() throws InterruptedException { // setup Observable<Integer> os = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 0; i < 5; i++) { subscriber.onNext(i); if (i == 2) { throw new RuntimeException("error!"); } } } }); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); int errorCount = 0; // connect Observable<Integer> oc1 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); try { MathObservable.sumInteger(oc1).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } catch (RuntimeException e) { errorCount++; } Observable<Integer> oc2 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); try { MathObservable.sumInteger(oc2).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } catch (RuntimeException e) { errorCount++; } Observable<Integer> oc3 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); try { MathObservable.sumInteger(oc3).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } catch (RuntimeException e) { errorCount++; } Assert.assertEquals(3, errorCount); } @Test public void testServeUsingByteEncodedObservable() throws InterruptedException { // manual encode data to byte[] Observable<byte[]> os = Observable.range(0, 101) // convert to bytes .map(new Func1<Integer, byte[]>() { @Override public byte[] call(Integer value) { return ByteBuffer.allocate(4).putInt(value).array(); } }); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.bytearray()); server.start(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testServeObservableByName() throws InterruptedException { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, "integers-from-0-100", os, Codecs.integer()); server.start(); // connect to observable by name Observable<Integer> oc = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .name("integers-from-0-100") .decoder(Codecs.integer()) .build()) .getObservable(); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test(expected = RuntimeException.class) public void testFailedToConnect() throws InterruptedException { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); int wrongPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", wrongPort, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testServeTwoObservablesOnSamePort() throws InterruptedException { // setup Observable<Integer> os1 = Observable.range(0, 101); Observable<String> os2 = Observable.from(new String[] {"a", "b", "c", "d", "e"}); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .name("ints") .encoder(Codecs.integer()) .observable(os1) .build()) .addObservable(new ServeObservable.Builder<String>() .name("strings") .encoder(Codecs.string()) .observable(os2) .build()) .build(); server.start(); // connect to observable by name Observable<Integer> ro1 = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .name("ints") .decoder(Codecs.integer()) .build()) .getObservable(); Observable<String> ro2 = RemoteObservable.connect(new ConnectToObservable.Builder<String>() .host("localhost") .port(serverPort) .name("strings") .decoder(Codecs.string()) .build()) .getObservable(); // assert MathObservable.sumInteger(ro1).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); ro2.reduce(new Func2<String, String, String>() { @Override public String call(String t1, String t2) { return t1 + t2; // concat string } }).toBlocking().forEach(new Action1<String>() { @Override public void call(String t1) { Assert.assertEquals("abcde", t1); } }); } @Test public void testServedMergedObservables() { // setup Observable<Integer> os1 = Observable.range(0, 101); Observable<Integer> os2 = Observable.range(100, 101); ReplaySubject<Observable<Integer>> subject = ReplaySubject.create(); subject.onNext(os1); subject.onNext(os2); subject.onCompleted(); PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int port = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(port) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(Observable.merge(subject)) .build()) .build(); // serve server.start(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", port, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(20200, t1.intValue()); // sum of number 0-200 } }); } @Test public void testServedMergedObservablesAddAfterServe() { // setup Observable<Integer> os1 = Observable.range(0, 100); Observable<Integer> os2 = Observable.range(100, 100); ReplaySubject<Observable<Integer>> subject = ReplaySubject.create(); subject.onNext(os1); subject.onNext(os2); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(Observable.merge(subject)) .build()) .build(); server.start(); // add after serve Observable<Integer> os3 = Observable.range(200, 101); subject.onNext(os3); subject.onCompleted(); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(45150, t1.intValue()); // sum of number 0-200 } }); } @Test public void testServedMergedObservablesAddAfterConnect() { // setup Observable<Integer> os1 = Observable.range(0, 100); Observable<Integer> os2 = Observable.range(100, 100); ReplaySubject<Observable<Integer>> subject = ReplaySubject.create(); subject.onNext(os1); subject.onNext(os2); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(Observable.merge(subject)) .build()) .build(); server.start(); // add after serve Observable<Integer> os3 = Observable.range(200, 100); subject.onNext(os3); // connect Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // add after connect Observable<Integer> os4 = Observable.range(300, 101); subject.onNext(os4); subject.onCompleted(); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(80200, t1.intValue()); // sum of number 0-200 } }); } // @Test public void testRoundRobinSlottingServer() { // setup Observable<Integer> os = Observable.range(1, 100); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(os) .slottingStrategy(new RoundRobin<Integer>()) .build()) .build(); server.start(); // connect with 2 remotes Observable<Integer> oc1 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); Observable<Integer> oc2 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); // merge results Observable<Integer> merged = Observable.merge(oc1, oc2); // assert MathObservable.sumInteger(merged).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testChainedRemoteObservables() throws InterruptedException { // first node PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); Observable<Integer> os = Observable.range(0, 100); int serverPort = portSelector.acquirePort(); RemoteObservable.serve(serverPort, "source", os, Codecs.integer()) .start(); // middle node, receiving input from first node Observable<Integer> oc = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .name("source") .decoder(Codecs.integer()) .build()) .getObservable(); // transform stream from first node Observable<Integer> transformed = oc.map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return t1 + 1; // shift sequence by one } }); int serverPort2 = portSelector.acquirePort(); RemoteObservable.serve(serverPort2, "transformed", transformed, Codecs.integer()) .start(); // connect to second node Observable<Integer> oc2 = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort2) .name("transformed") .decoder(Codecs.integer()) .build()) .getObservable(); MathObservable.sumInteger(oc2).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test(expected = RuntimeException.class) public void testError() { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); Observable<Integer> os = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { subscriber.onNext(1); subscriber.onError(new Exception("test-exception")); } }); int serverPort = portSelector.acquirePort(); RemoteObservable.serve(serverPort, os, Codecs.integer()) .start(); Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(5050, t1.intValue()); // sum of number 0-100 } }); } @Test public void testUnsubscribeForRemoteObservable() throws InterruptedException { PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); // serve up first observable final MutableReference<Boolean> sourceSubscriptionUnsubscribed = new MutableReference<Boolean>(); Observable<Integer> os = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { int i = 0; sourceSubscriptionUnsubscribed.setValue(subscriber.isUnsubscribed()); while (!sourceSubscriptionUnsubscribed.getValue()) { subscriber.onNext(i++); sourceSubscriptionUnsubscribed.setValue(subscriber.isUnsubscribed()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).subscribeOn(Schedulers.io()); int serverPort = portSelector.acquirePort(); RemoteObservable.serve(serverPort, os, Codecs.integer()) .start(); // connect to remote observable Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); Subscription sub = oc.subscribe(); Assert.assertEquals(false, sub.isUnsubscribed()); Thread.sleep(1000); // allow a few iterations sub.unsubscribe(); Thread.sleep(5000); // allow time for unsubscribe to propagate Assert.assertEquals(true, sub.isUnsubscribed()); Assert.assertEquals(true, sourceSubscriptionUnsubscribed.getValue()); } @Test public void testUnsubscribeForChainedRemoteObservable() throws InterruptedException { // serve first node in chain final MutableReference<Boolean> sourceSubscriptionUnsubscribed = new MutableReference<Boolean>(); PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); Observable<Integer> os = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { int i = 0; sourceSubscriptionUnsubscribed.setValue(subscriber.isUnsubscribed()); while (!sourceSubscriptionUnsubscribed.getValue()) { subscriber.onNext(i++); sourceSubscriptionUnsubscribed.setValue(subscriber.isUnsubscribed()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).subscribeOn(Schedulers.io()); int serverPort = portSelector.acquirePort(); RemoteObservable.serve(serverPort, os, Codecs.integer()) .start(); // serve second node in chain, using first node's observable Observable<Integer> oc1 = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); int serverPort2 = portSelector.acquirePort(); RemoteObservable.serve(serverPort2, oc1, Codecs.integer()) .start(); // connect to second node Observable<Integer> oc2 = RemoteObservable.connect("localhost", serverPort2, Codecs.integer()); Subscription subscription = oc2.subscribe(); // check client subscription Assert.assertEquals(false, subscription.isUnsubscribed()); Thread.sleep(4000); // allow a few iterations to complete // unsubscribe to client subscription subscription.unsubscribe(); Thread.sleep(7000); // allow time for unsubscribe to propagate // check client Assert.assertEquals(true, subscription.isUnsubscribed()); // check source Assert.assertEquals(true, sourceSubscriptionUnsubscribed.getValue()); } @Test public void testSubscribeParametersByFilteringOnServer() { // setup Observable<Integer> os = Observable.range(0, 101); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(os) .serverSideFilter(ServerSideFilters.oddsAndEvens()) .build()) .build(); server.start(); // connect Map<String, String> subscribeParameters = new HashMap<String, String>(); subscribeParameters.put("type", "even"); Observable<Integer> oc = RemoteObservable.connect(new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .subscribeParameters(subscribeParameters) .decoder(Codecs.integer()) .build()) .getObservable(); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(2550, t1.intValue()); // sum of number 0-100 } }); } @Test public void testOnCompletedFromReplaySubject() { PublishSubject<Integer> subject = PublishSubject.create(); subject.onNext(1); subject.onNext(2); subject.onNext(3); subject.onCompleted(); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = new RemoteRxServer.Builder() .port(serverPort) .addObservable(new ServeObservable.Builder<Integer>() .encoder(Codecs.integer()) .observable(subject) .serverSideFilter(ServerSideFilters.oddsAndEvens()) .build()) .build(); server.start(); // connect Observable<Integer> ro = RemoteObservable.connect("localhost", serverPort, Codecs.integer()); final MutableReference<Boolean> completed = new MutableReference<Boolean>(); ro.materialize().toBlocking().forEach(new Action1<Notification<Integer>>() { @Override public void call(Notification<Integer> notification) { if (notification.isOnCompleted()) { completed.setValue(true); } } }); Assert.assertEquals(true, completed.getValue()); } }
8,786
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/ToDeltaEndpointInjectorTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.network.Endpoint; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import rx.observables.BlockingObservable; import rx.subjects.ReplaySubject; public class ToDeltaEndpointInjectorTest { @Test public void deltaTest() { ReplaySubject<List<Endpoint>> subject = ReplaySubject.create(); ToDeltaEndpointInjector service = new ToDeltaEndpointInjector(subject); // 1 add endpoints List<Endpoint> endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234)); endpoints.add(new Endpoint("localhost", 2468)); subject.onNext(endpoints); // 2 remove endpoint by leaving out second endpoint endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234)); subject.onNext(endpoints); // 3 remove other endpoints = new LinkedList<Endpoint>(); subject.onNext(endpoints); // 4 add back endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234)); endpoints.add(new Endpoint("localhost", 2468)); subject.onNext(endpoints); subject.onCompleted(); BlockingObservable<EndpointChange> be = service.deltas().toBlocking(); // check for two adds Iterator<EndpointChange> iter = be.getIterator(); Assert.assertTrue(iter.hasNext()); EndpointChange ce1 = iter.next(); Assert.assertEquals(ce1.getEndpoint().getSlotId(), "localhost:1234"); Assert.assertEquals(ce1.getType(), EndpointChange.Type.add); EndpointChange ce2 = iter.next(); Assert.assertEquals(ce2.getEndpoint().getSlotId(), "localhost:2468"); Assert.assertEquals(ce2.getType(), EndpointChange.Type.add); // check for complete EndpointChange ce3 = iter.next(); Assert.assertEquals(ce3.getEndpoint().getSlotId(), "localhost:2468"); Assert.assertEquals(ce3.getType(), EndpointChange.Type.complete); // check for complete EndpointChange ce4 = iter.next(); Assert.assertEquals(ce4.getEndpoint().getSlotId(), "localhost:1234"); Assert.assertEquals(ce4.getType(), EndpointChange.Type.complete); // check for add EndpointChange ce5 = iter.next(); Assert.assertEquals(ce5.getEndpoint().getSlotId(), "localhost:1234"); Assert.assertEquals(ce5.getType(), EndpointChange.Type.add); EndpointChange ce6 = iter.next(); Assert.assertEquals(ce6.getEndpoint().getSlotId(), "localhost:2468"); Assert.assertEquals(ce6.getType(), EndpointChange.Type.add); } @Test public void deltaTestWithIds() { ReplaySubject<List<Endpoint>> subject = ReplaySubject.create(); ToDeltaEndpointInjector service = new ToDeltaEndpointInjector(subject); // 1. add endpoints List<Endpoint> endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234, "abc")); endpoints.add(new Endpoint("localhost", 2468, "xyz")); subject.onNext(endpoints); // 2. nothing changes endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234, "abc")); endpoints.add(new Endpoint("localhost", 2468, "xyz")); subject.onNext(endpoints); // 3. remove endpoint by leaving out second endpoint endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234, "abc")); subject.onNext(endpoints); // 4. remove all endpoints = new LinkedList<Endpoint>(); subject.onNext(endpoints); // 5. add back endpoints = new LinkedList<Endpoint>(); endpoints.add(new Endpoint("localhost", 1234, "abc")); endpoints.add(new Endpoint("localhost", 2468, "xyz")); subject.onNext(endpoints); subject.onCompleted(); BlockingObservable<EndpointChange> be = service.deltas().toBlocking(); Iterator<EndpointChange> iter = be.getIterator(); Assert.assertTrue(iter.hasNext()); EndpointChange ce2 = iter.next(); Assert.assertEquals(ce2.getEndpoint().getSlotId(), "xyz"); Assert.assertEquals(ce2.getType(), EndpointChange.Type.add); EndpointChange ce1 = iter.next(); Assert.assertEquals(ce1.getEndpoint().getSlotId(), "abc"); Assert.assertEquals(ce1.getType(), EndpointChange.Type.add); EndpointChange ce3 = iter.next(); Assert.assertEquals(ce3.getEndpoint().getSlotId(), "xyz"); Assert.assertEquals(ce3.getType(), EndpointChange.Type.complete); EndpointChange ce4 = iter.next(); Assert.assertEquals(ce4.getEndpoint().getSlotId(), "abc"); Assert.assertEquals(ce4.getType(), EndpointChange.Type.complete); EndpointChange ce6 = iter.next(); Assert.assertEquals(ce6.getEndpoint().getSlotId(), "xyz"); Assert.assertEquals(ce6.getType(), EndpointChange.Type.add); EndpointChange ce5 = iter.next(); Assert.assertEquals(ce5.getEndpoint().getSlotId(), "abc"); Assert.assertEquals(ce5.getType(), EndpointChange.Type.add); } }
8,787
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/MetricsTest.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Codecs; import org.junit.Assert; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.observables.MathObservable; public class MetricsTest { @Test public void testConnectionMetrics() { // setup Observable<Integer> os = Observable.range(1, 1000); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect ConnectToObservable<Integer> cc = new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .decoder(Codecs.integer()) .build(); RemoteRxConnection<Integer> rc = RemoteObservable.connect(cc); // assert MathObservable.sumInteger(rc.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); Assert.assertEquals(1000, rc.getMetrics().getOnNextCount()); Assert.assertEquals(0, rc.getMetrics().getOnErrorCount()); Assert.assertEquals(1, rc.getMetrics().getOnCompletedCount()); } @Test public void testServerMetrics() { // setup Observable<Integer> os = Observable.range(1, 1000); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect ConnectToObservable<Integer> cc = new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .decoder(Codecs.integer()) .build(); Observable<Integer> oc = RemoteObservable.connect(cc).getObservable(); // assert MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); Assert.assertEquals(1000, server.getMetrics().getOnNextCount()); Assert.assertEquals(0, server.getMetrics().getOnErrorCount()); Assert.assertEquals(1, server.getMetrics().getOnCompletedCount()); } @Test public void testMutlipleConnectionsSingleServerMetrics() throws InterruptedException { // setup Observable<Integer> os = Observable.range(1, 1000); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, os, Codecs.integer()); server.start(); // connect ConnectToObservable<Integer> cc = new ConnectToObservable.Builder<Integer>() .host("localhost") .port(serverPort) .decoder(Codecs.integer()) .build(); RemoteRxConnection<Integer> ro1 = RemoteObservable.connect(cc); // assert MathObservable.sumInteger(ro1.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); RemoteRxConnection<Integer> ro2 = RemoteObservable.connect(cc); // assert MathObservable.sumInteger(ro2.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); // client asserts Assert.assertEquals(1000, ro1.getMetrics().getOnNextCount()); Assert.assertEquals(0, ro1.getMetrics().getOnErrorCount()); Assert.assertEquals(1, ro1.getMetrics().getOnCompletedCount()); Assert.assertEquals(1000, ro2.getMetrics().getOnNextCount()); Assert.assertEquals(0, ro2.getMetrics().getOnErrorCount()); Assert.assertEquals(1, ro2.getMetrics().getOnCompletedCount()); // server asserts Assert.assertEquals(2000, server.getMetrics().getOnNextCount()); Assert.assertEquals(0, server.getMetrics().getOnErrorCount()); Assert.assertEquals(2, server.getMetrics().getOnCompletedCount()); Assert.assertEquals(2, server.getMetrics().getSubscribedCount()); Thread.sleep(1000); // allow time for unsub, connections to close Assert.assertEquals(2, server.getMetrics().getUnsubscribedCount()); } @Test public void testMutlipleConnectionsSingleServerErrorsMetrics() throws InterruptedException { // setup Observable<Integer> o = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 0; i < 10; i++) { if (i == 5) { subscriber.onError(new RuntimeException("error")); } subscriber.onNext(i); } } }); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, o, Codecs.integer()); server.start(); // connect ConnectToObservable<Integer> cc = new ConnectToObservable.Builder<Integer>() .subscribeAttempts(1) .host("localhost") .port(serverPort) .decoder(Codecs.integer()) .build(); RemoteRxConnection<Integer> ro1 = RemoteObservable.connect(cc); try { MathObservable.sumInteger(ro1.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); } catch (Exception e) { // noOp } RemoteRxConnection<Integer> ro2 = RemoteObservable.connect(cc); try { MathObservable.sumInteger(ro2.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); } catch (Exception e) { // noOp } // client asserts Assert.assertEquals(5, ro1.getMetrics().getOnNextCount()); Assert.assertEquals(1, ro1.getMetrics().getOnErrorCount()); Assert.assertEquals(0, ro1.getMetrics().getOnCompletedCount()); Assert.assertEquals(5, ro2.getMetrics().getOnNextCount()); Assert.assertEquals(1, ro2.getMetrics().getOnErrorCount()); Assert.assertEquals(0, ro2.getMetrics().getOnCompletedCount()); // server asserts Assert.assertEquals(10, server.getMetrics().getOnNextCount()); Assert.assertEquals(2, server.getMetrics().getOnErrorCount()); Assert.assertEquals(0, server.getMetrics().getOnCompletedCount()); Assert.assertEquals(2, server.getMetrics().getSubscribedCount()); Thread.sleep(1000); // allow time for unsub, connections to close Assert.assertEquals(2, server.getMetrics().getUnsubscribedCount()); } @Test public void testConnectionOnErrorCount() { // setup Observable<Integer> o = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { for (int i = 0; i < 10; i++) { if (i == 5) { subscriber.onError(new RuntimeException("error")); } subscriber.onNext(i); } } }); // serve PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000); int serverPort = portSelector.acquirePort(); RemoteRxServer server = RemoteObservable.serve(serverPort, o, Codecs.integer()); server.start(); // connect ConnectToObservable<Integer> cc = new ConnectToObservable.Builder<Integer>() .subscribeAttempts(1) .host("localhost") .port(serverPort) .decoder(Codecs.integer()) .build(); RemoteRxConnection<Integer> rc = RemoteObservable.connect(cc); // assert try { MathObservable.sumInteger(rc.getObservable()).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { Assert.assertEquals(500500, t1.intValue()); // sum of number 0-100 } }); } catch (Exception e) { // noOp } Assert.assertEquals(5, rc.getMetrics().getOnNextCount()); Assert.assertEquals(1, rc.getMetrics().getOnErrorCount()); Assert.assertEquals(0, rc.getMetrics().getOnCompletedCount()); } }
8,788
0
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/test/java/io/reactivex/mantis/remote/observable/Result.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 io.reactivex.mantis.remote.observable; public class Result { private String key; private Integer results; public Result(String key, Integer results) { this.key = key; this.results = results; } public String getKey() { return key; } public Integer getResults() { return results; } @Override public String toString() { return "Result [key=" + key + ", results=" + results + "]"; } }
8,789
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ToDeltaEndpointInjector.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.network.Endpoint; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; public class ToDeltaEndpointInjector implements EndpointInjector { private static final Logger logger = LoggerFactory.getLogger(ToDeltaEndpointInjector.class); private Observable<List<Endpoint>> endpointObservable; private Observable<EndpointChange> reconcileChanges; public ToDeltaEndpointInjector(Observable<List<Endpoint>> endpointObservable) { this(endpointObservable, Observable.<EndpointChange>empty()); } public ToDeltaEndpointInjector(Observable<List<Endpoint>> endpointObservable, Observable<EndpointChange> reconcileChanges) { this.endpointObservable = endpointObservable; this.reconcileChanges = reconcileChanges; } private String uniqueHost(String host, int port, String slotId) { return host + ":" + port + ":" + slotId; } private List<EndpointChange> changes(List<Endpoint> previous, List<Endpoint> current) { logger.info("Sets to evaluate for differences, current: " + current + " previous: " + previous); Map<String, Endpoint> previousSet = new HashMap<>(); // fill previous for (Endpoint endpoint : previous) { previousSet.put(uniqueHost(endpoint.getHost(), endpoint.getPort(), endpoint.getSlotId()), endpoint); } // collect into two buckets: add, complete List<EndpointChange> toAdd = new LinkedList<>(); Set<String> completeCheck = new HashSet<>(); for (Endpoint endpoint : current) { String id = uniqueHost(endpoint.getHost(), endpoint.getPort(), endpoint.getSlotId()); if (!previousSet.containsKey(id)) { EndpointChange ce = new EndpointChange(EndpointChange.Type.add, endpoint); toAdd.add(ce); } else { completeCheck.add(id); } } List<EndpointChange> toComplete = new LinkedList<EndpointChange>(); // check if need to complete any from current set: set difference for (Map.Entry<String, Endpoint> controlledEndpoint : previousSet.entrySet()) { if (!completeCheck.contains(controlledEndpoint.getKey())) { Endpoint ce = controlledEndpoint.getValue(); EndpointChange ceToCompletd = new EndpointChange(EndpointChange.Type.complete, ce); toComplete.add(ceToCompletd); } } Map<String, EndpointChange> nextSet = new HashMap<>(); // apply completes for (EndpointChange controlledEndpoint : toComplete) { nextSet.put(uniqueHost(controlledEndpoint.getEndpoint().getHost(), controlledEndpoint.getEndpoint().getPort(), controlledEndpoint.getEndpoint().getSlotId()), controlledEndpoint); } // apply adds for (EndpointChange controlledEndpoint : toAdd) { nextSet.put(uniqueHost(controlledEndpoint.getEndpoint().getHost(), controlledEndpoint.getEndpoint().getPort(), controlledEndpoint.getEndpoint().getSlotId()), controlledEndpoint); } logger.info("Differences to be applied: " + nextSet); return new ArrayList<>(nextSet.values()); } @Override public Observable<EndpointChange> deltas() { return Observable.merge( reconcileChanges, endpointObservable .startWith(Collections.<Endpoint>emptyList()) .buffer(2, 1) // stagger current and previous .flatMap(new Func1<List<List<Endpoint>>, Observable<EndpointChange>>() { @Override public Observable<EndpointChange> call(List<List<Endpoint>> previousAndCurrent) { if (previousAndCurrent.size() == 2) { List<Endpoint> previous = previousAndCurrent.get(0); List<Endpoint> current = previousAndCurrent.get(1); return Observable.from(changes(previous, current)); } else { // skipping last entry, already processed on the // last previousAndCurrent pair return Observable.empty(); } } })); } }
8,790
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/SubscribeInfo.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 io.reactivex.mantis.remote.observable; import java.util.Map; public class SubscribeInfo { private String host; private int port; private String name; private Map<String, String> subscribeParameters; private int subscribeRetryAttempts; public SubscribeInfo(String host, int port, String name, Map<String, String> subscribeParameters, int subscribeRetryAttempts) { this.host = host; this.port = port; this.name = name; this.subscribeParameters = subscribeParameters; this.subscribeRetryAttempts = subscribeRetryAttempts; } public int getSubscribeRetryAttempts() { return subscribeRetryAttempts; } public String getHost() { return host; } public int getPort() { return port; } public String getName() { return name; } public Map<String, String> getSubscribeParameters() { return subscribeParameters; } }
8,791
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/FixedConnectionSet.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.network.Endpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.GroupedObservable; import rx.subscriptions.BooleanSubscription; public class FixedConnectionSet<T> { private static final Logger logger = LoggerFactory.getLogger(FixedConnectionSet.class); private EndpointInjector endpointInjector; private Func1<Endpoint, Observable<T>> toObservableFunc; private MergedObservable<T> mergedObservable; public FixedConnectionSet(int expectedTerminalCount, EndpointInjector endpointInjector, Func1<Endpoint, Observable<T>> toObservableFunc) { this.endpointInjector = endpointInjector; this.toObservableFunc = toObservableFunc; this.mergedObservable = MergedObservable.create(expectedTerminalCount); } public static <K, V> FixedConnectionSet<GroupedObservable<K, V>> create(int expectedTerminalCount, final ConnectToGroupedObservable.Builder<K, V> config, EndpointInjector endpointService) { Func1<Endpoint, Observable<GroupedObservable<K, V>>> toObservableFunc = new Func1<Endpoint, Observable<GroupedObservable<K, V>>>() { @Override public Observable<GroupedObservable<K, V>> call(Endpoint endpoint) { config.host(endpoint.getHost()) .port(endpoint.getPort()); return RemoteObservable.connect(config.build()).getObservable(); } }; return new FixedConnectionSet<GroupedObservable<K, V>>(expectedTerminalCount, endpointService, toObservableFunc); } public static <T> FixedConnectionSet<T> create(int expectedTerminalCount, final ConnectToObservable.Builder<T> config, EndpointInjector endpointService) { Func1<Endpoint, Observable<T>> toObservableFunc = new Func1<Endpoint, Observable<T>>() { @Override public Observable<T> call(Endpoint endpoint) { config.host(endpoint.getHost()) .port(endpoint.getPort()); return RemoteObservable.connect(config.build()).getObservable(); } }; return new FixedConnectionSet<T>(expectedTerminalCount, endpointService, toObservableFunc); } public Observable<Observable<T>> getObservables() { return Observable.create(new OnSubscribe<Observable<T>>() { @Override public void call(final Subscriber<? super Observable<T>> subscriber) { final BooleanSubscription subscription = new BooleanSubscription(); // clean up state if unsubscribe subscriber.add(new Subscription() { @Override public void unsubscribe() { // NOTE, this assumes one // unsubscribe should // clear all state. Which // is ok if the O<O<T>> // is published.refCounted() mergedObservable.clear(); subscription.unsubscribe(); } @Override public boolean isUnsubscribed() { return subscription.isUnsubscribed(); } }); subscriber.add(mergedObservable.get().subscribe(new Observer<Observable<T>>() { @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(Observable<T> t) { subscriber.onNext(t); } })); subscriber.add(endpointInjector.deltas().subscribe(new Action1<EndpointChange>() { @Override public void call(EndpointChange ec) { String id = Endpoint.uniqueHost(ec.getEndpoint().getHost(), ec.getEndpoint().getPort(), ec.getEndpoint().getSlotId()); if (EndpointChange.Type.add == ec.getType()) { logger.info("Adding new connection to host: " + ec.getEndpoint().getHost() + " at port: " + ec.getEndpoint().getPort() + " with id: " + id); mergedObservable.mergeIn(id, toObservableFunc.call(ec.getEndpoint()), ec.getEndpoint().getErrorCallback(), ec.getEndpoint().getCompletedCallback()); } else if (EndpointChange.Type.complete == ec.getType()) { logger.info("Forcing connection to complete host: " + ec.getEndpoint().getHost() + " at port: " + ec.getEndpoint().getPort() + " with id: " + id); mergedObservable.forceComplete(id); } } })); } }); } }
8,792
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/DynamicConnection.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.network.Endpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.GroupedObservable; import rx.subjects.PublishSubject; public class DynamicConnection<T> { private static final Logger logger = LoggerFactory.getLogger(DynamicConnection.class); private Observable<Endpoint> changeEndpointObservable; private PublishSubject<Observable<T>> subject = PublishSubject.create(); private Func1<Endpoint, Observable<T>> toObservableFunc; DynamicConnection(Func1<Endpoint, Observable<T>> toObservableFunc, Observable<Endpoint> changeEndpointObservable) { this.changeEndpointObservable = changeEndpointObservable; this.toObservableFunc = toObservableFunc; } public static <K, V> DynamicConnection<GroupedObservable<K, V>> create( final ConnectToGroupedObservable.Builder<K, V> config, Observable<Endpoint> endpoints) { Func1<Endpoint, Observable<GroupedObservable<K, V>>> toObservableFunc = new Func1<Endpoint, Observable<GroupedObservable<K, V>>>() { @Override public Observable<GroupedObservable<K, V>> call(Endpoint endpoint) { // copy config, change host, port and id ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config); configCopy .host(endpoint.getHost()) .port(endpoint.getPort()) .slotId(endpoint.getSlotId()); return RemoteObservable.connect(configCopy.build()).getObservable(); } }; return new DynamicConnection<GroupedObservable<K, V>>(toObservableFunc, endpoints); } public static <T> DynamicConnection<T> create( final ConnectToObservable.Builder<T> config, Observable<Endpoint> endpoints) { Func1<Endpoint, Observable<T>> toObservableFunc = new Func1<Endpoint, Observable<T>>() { @Override public Observable<T> call(Endpoint endpoint) { // copy config, change host, port and id ConnectToObservable.Builder<T> configCopy = new ConnectToObservable.Builder<T>(config); configCopy .host(endpoint.getHost()) .port(endpoint.getPort()) .slotId(endpoint.getSlotId()); return RemoteObservable.connect(configCopy.build()).getObservable(); } }; return new DynamicConnection<T>(toObservableFunc, endpoints); } public void close() { subject.onCompleted(); } public Observable<T> observable() { return Observable.create(new OnSubscribe<T>() { @Override public void call(final Subscriber<? super T> subscriber) { subscriber.add(subject.flatMap(new Func1<Observable<T>, Observable<T>>() { @Override public Observable<T> call(Observable<T> t1) { return t1; } }).subscribe(new Observer<T>() { @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(T t) { subscriber.onNext(t); } })); subscriber.add(changeEndpointObservable.subscribe(new Action1<Endpoint>() { @Override public void call(Endpoint endpoint) { logger.debug("New endpoint: " + endpoint); subject.onNext(toObservableFunc.call(endpoint)); } })); } }); } }
8,793
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/Group.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 io.reactivex.mantis.remote.observable; import rx.Notification; public class Group<K, V> { private K keyValue; private byte[] keyBytes; private Notification<V> notification; public Group(K keyValue, byte[] keyBytes, Notification<V> notification) { this.keyValue = keyValue; this.keyBytes = keyBytes; this.notification = notification; } public K getKeyValue() { return keyValue; } public byte[] getKeyBytes() { return keyBytes; } public Notification<V> getNotification() { return notification; } }
8,794
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ConnectToGroupedObservable.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Decoder; import java.util.HashMap; import java.util.Map; import rx.functions.Action0; import rx.functions.Action3; import rx.subjects.PublishSubject; public class ConnectToGroupedObservable<K, V> extends ConnectToConfig { private Decoder<K> keyDecoder; private Decoder<V> valueDecoder; private Action3<K, V, Throwable> deocdingErrorHandler; ConnectToGroupedObservable(Builder<K, V> builder) { super(builder.host, builder.port, builder.name, builder.subscribeParameters, builder.subscribeAttempts, builder.suppressDecodingErrors, builder.connectionDisconnectCallback, builder.closeTrigger); this.keyDecoder = builder.keyDecoder; this.valueDecoder = builder.valueDecoder; this.deocdingErrorHandler = builder.deocdingErrorHandler; } public Decoder<K> getKeyDecoder() { return keyDecoder; } public Decoder<V> getValueDecoder() { return valueDecoder; } public Action3<K, V, Throwable> getDeocdingErrorHandler() { return deocdingErrorHandler; } public static class Builder<K, V> { private String host; private int port; private String name; private Decoder<K> keyDecoder; private Decoder<V> valueDecoder; private Map<String, String> subscribeParameters = new HashMap<>(); private int subscribeAttempts = 3; private Action3<K, V, Throwable> deocdingErrorHandler = new Action3<K, V, Throwable>() { @Override public void call(K key, V value, Throwable t2) { t2.printStackTrace(); } }; private boolean suppressDecodingErrors = false; private Action0 connectionDisconnectCallback = new Action0() { @Override public void call() {} }; private PublishSubject<Integer> closeTrigger = PublishSubject.create(); public Builder() {} public Builder(Builder<K, V> config) { this.host = config.host; this.port = config.port; this.name = config.name; this.keyDecoder = config.keyDecoder; this.valueDecoder = config.valueDecoder; this.subscribeParameters.putAll(config.subscribeParameters); this.subscribeAttempts = config.subscribeAttempts; this.deocdingErrorHandler = config.deocdingErrorHandler; this.suppressDecodingErrors = config.suppressDecodingErrors; } public Builder<K, V> host(String host) { this.host = host; return this; } public Builder<K, V> port(int port) { this.port = port; return this; } public Builder<K, V> closeTrigger(PublishSubject<Integer> closeTrigger) { this.closeTrigger = closeTrigger; return this; } public Builder<K, V> connectionDisconnectCallback(Action0 connectionDisconnectCallback) { this.connectionDisconnectCallback = connectionDisconnectCallback; return this; } public Builder<K, V> deocdingErrorHandler(Action3<K, V, Throwable> handler, boolean suppressDecodingErrors) { this.deocdingErrorHandler = handler; this.suppressDecodingErrors = suppressDecodingErrors; return this; } public Builder<K, V> name(String name) { this.name = name; this.subscribeParameters.put("groupId", name);//used with modern server for routing return this; } public Builder<K, V> slotId(String slotId) { this.subscribeParameters.put("slotId", slotId); return this; } public Builder<K, V> keyDecoder(Decoder<K> keyDecoder) { this.keyDecoder = keyDecoder; return this; } public Builder<K, V> valueDecoder(Decoder<V> valueDecoder) { this.valueDecoder = valueDecoder; return this; } public Builder<K, V> subscribeParameters(Map<String, String> subscribeParameters) { this.subscribeParameters.putAll(subscribeParameters); return this; } public Builder<K, V> subscribeAttempts(int subscribeAttempts) { this.subscribeAttempts = subscribeAttempts; return this; } public ConnectToGroupedObservable<K, V> build() { return new ConnectToGroupedObservable<K, V>(this); } } }
8,795
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/BatchedRxEventPipelineConfigurator.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 io.reactivex.mantis.remote.observable; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import mantis.io.reactivex.netty.pipeline.PipelineConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BatchedRxEventPipelineConfigurator implements PipelineConfigurator<RemoteRxEvent, List<RemoteRxEvent>> { private static final Logger logger = LoggerFactory.getLogger(BatchedRxEventPipelineConfigurator.class); private static final byte PROTOCOL_VERSION = 1; @SuppressWarnings("unchecked") static Map<String, String> fromBytesToMap(byte[] bytes) { Map<String, String> map = null; ByteArrayInputStream bis = null; ObjectInput in = null; try { bis = new ByteArrayInputStream(bytes); in = new ObjectInputStream(bis); map = (Map<String, String>) in.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } finally { try { if (bis != null) {bis.close();} if (in != null) {in.close();} } catch (IOException e) { throw new RuntimeException(e); } } return map; } static byte[] fromMapToBytes(Map<String, String> map) { ByteArrayOutputStream baos = null; ObjectOutput out = null; try { baos = new ByteArrayOutputStream(); out = new ObjectOutputStream(baos); out.writeObject(map); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (out != null) {out.close();} if (baos != null) {baos.close();} } catch (IOException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } } return baos.toByteArray(); } @Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast(new ChannelDuplexHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean handled = false; if (ByteBuf.class.isAssignableFrom(msg.getClass())) { ByteBuf byteBuf = (ByteBuf) msg; if (byteBuf.isReadable()) { int protocolVersion = byteBuf.readByte(); if (protocolVersion != PROTOCOL_VERSION) { throw new RuntimeException("Unsupported protocol version: " + protocolVersion); } int observableNameLength = byteBuf.readByte(); String observableName = null; if (observableNameLength > 0) { // read name byte[] observableNameBytes = new byte[observableNameLength]; byteBuf.readBytes(observableNameBytes); observableName = new String(observableNameBytes, Charset.forName("UTF-8")); } while (byteBuf.isReadable()) { int lengthOfEvent = byteBuf.readInt(); int operation = byteBuf.readByte(); RemoteRxEvent.Type type = null; Map<String, String> subscribeParams = null; byte[] valueData = null; if (operation == 1) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: next"); // } type = RemoteRxEvent.Type.next; valueData = new byte[lengthOfEvent - 1]; //subtract op code byteBuf.readBytes(valueData); } else if (operation == 2) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: error"); // } type = RemoteRxEvent.Type.error; valueData = new byte[lengthOfEvent - 1]; byteBuf.readBytes(valueData); } else if (operation == 3) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: completed"); // } type = RemoteRxEvent.Type.completed; } else if (operation == 4) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: subscribed"); // } type = RemoteRxEvent.Type.subscribed; // read subscribe parameters int subscribeParamsLength = byteBuf.readInt(); if (subscribeParamsLength > 0) { // read byte into map byte[] subscribeParamsBytes = new byte[subscribeParamsLength]; byteBuf.readBytes(subscribeParamsBytes); subscribeParams = fromBytesToMap(subscribeParamsBytes); } } else if (operation == 5) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: unsubscribed"); // } type = RemoteRxEvent.Type.unsubscribed; } else if (operation == 6) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: heartbeat"); // } } else if (operation == 7) { // if(logger.isDebugEnabled()) { // logger.debug("READ request for RemoteRxEvent: nonDataError"); // } type = RemoteRxEvent.Type.nonDataError; valueData = new byte[lengthOfEvent - 1]; byteBuf.readBytes(valueData); } else { throw new RuntimeException("operation: " + operation + " not support."); } // don't send heartbeats through pipeline if (operation != 6) { ctx.fireChannelRead(new RemoteRxEvent(observableName, type, valueData, subscribeParams)); } } handled = true; byteBuf.release(); } } if (!handled) { super.channelRead(ctx, msg); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof List) { @SuppressWarnings("unchecked") List<RemoteRxEvent> batch = (List<RemoteRxEvent>) msg; ByteBuf buf = ctx.alloc().buffer(); writeHeader(buf, batch.get(0).getName()); for (RemoteRxEvent event : batch) { writeBytesIntoBuf(event, buf); } super.write(ctx, buf, promise); super.flush(ctx); } else { super.write(ctx, msg, promise); } } }); } private void writeHeader(ByteBuf buf, String name) { buf.writeByte(PROTOCOL_VERSION); String observableName = name; if (observableName != null && !observableName.isEmpty()) { // write length int nameLength = observableName.length(); if (nameLength < 127) { buf.writeByte(nameLength); buf.writeBytes(observableName.getBytes()); } else { throw new RuntimeException("observableName " + observableName + " exceeds max limit of 127 characters"); } } else { // no name provided, write 0 bytes for name length buf.writeByte(0); } } private void writeBytesIntoBuf(RemoteRxEvent event, ByteBuf buf) { if (event.getType() == RemoteRxEvent.Type.next) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: next"); // } byte[] data = event.getData(); buf.writeInt(1 + data.length); // length, add additional byte for opcode buf.writeByte(1); // opcode buf.writeBytes(data); } else if (event.getType() == RemoteRxEvent.Type.error) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: error"); // } byte[] data = event.getData(); buf.writeInt(1 + data.length); // length, add additional byte for opcode buf.writeByte(2); //opcode buf.writeBytes(data); } else if (event.getType() == RemoteRxEvent.Type.completed) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: completed"); // } buf.writeInt(1); // length buf.writeByte(3); // opcode } else if (event.getType() == RemoteRxEvent.Type.subscribed) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: subscribed"); // } Map<String, String> subscribeParameters = event.getSubscribeParameters(); if (subscribeParameters != null && !subscribeParameters.isEmpty()) { byte[] subscribeBytes = fromMapToBytes(subscribeParameters); buf.writeInt(1 + 4 + subscribeBytes.length); // op code, subscribe bytes length, subscribe bytes buf.writeByte(4); buf.writeInt(subscribeBytes.length); buf.writeBytes(subscribeBytes); } else { buf.writeInt(2); //length buf.writeByte(4); //opcode buf.writeInt(0); // no data } } else if (event.getType() == RemoteRxEvent.Type.unsubscribed) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: unsubscribed"); // } buf.writeInt(1); // length buf.writeByte(5); //opcode } else if (event.getType() == RemoteRxEvent.Type.heartbeat) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: hearbeat"); // } buf.writeInt(1); // length buf.writeByte(6); //opcode } else if (event.getType() == RemoteRxEvent.Type.nonDataError) { // if(logger.isDebugEnabled()) { // logger.debug("WRITE request for RemoteRxEvent: nonDataError"); // } buf.writeInt(1); // length buf.writeByte(7); //opcode buf.writeBytes(event.getData()); } } }
8,796
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/RxMetrics.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.metrics.Counter; import io.mantisrx.common.metrics.Metrics; public class RxMetrics { private Metrics metrics; private Counter next; private Counter nextFailure; private Counter error; private Counter errorFailure; private Counter complete; private Counter completeFailure; private Counter subscribe; private Counter unsubscribe; public RxMetrics() { metrics = new Metrics.Builder() .name("RemoteObservableMetrics") .addCounter("onNext") .addCounter("onNextFailure") .addCounter("onError") .addCounter("onErrorFailure") .addCounter("onComplete") .addCounter("onCompleteFailure") .addCounter("subscribe") .addCounter("unsubscribe") .build(); next = metrics.getCounter("onNext"); nextFailure = metrics.getCounter("onNextFailure"); error = metrics.getCounter("onError"); errorFailure = metrics.getCounter("onErrorFailure"); complete = metrics.getCounter("onComplete"); completeFailure = metrics.getCounter("onCompleteFailure"); subscribe = metrics.getCounter("subscribe"); unsubscribe = metrics.getCounter("unsubscribe"); } public Metrics getCountersAndGauges() { return metrics; } public void incrementNextFailureCount() { nextFailure.increment(); } public void incrementNextFailureCount(long numFailed) { nextFailure.increment(numFailed); } public void incrementNextCount() { next.increment(); } public void incrementNextCount(long numOnNext) { next.increment(numOnNext); } public void incrementErrorCount() { error.increment(); } public void incrementErrorFailureCount() { errorFailure.increment(); } public void incrementCompletedCount() { complete.increment(); } public void incrementCompletedFailureCount() { completeFailure.increment(); } public void incrementSubscribedCount() { subscribe.increment(); } public void incrementUnsubscribedCount() { unsubscribe.increment(); } public long getOnNextRollingCount() { return next.rateValue(); } public long getOnNextCount() { return next.value(); } public long getOnNextFailureCount() { return nextFailure.value(); } public long getOnNextRollingFailureCount() { return nextFailure.rateValue(); } public long getOnErrorRollingCount() { return error.rateValue(); } public long getOnErrorCount() { return error.value(); } public long getOnErrorFailureCount() { return errorFailure.value(); } public long getOnErrorRollingFailureCount() { return errorFailure.rateValue(); } public long getOnCompletedRollingCount() { return complete.rateValue(); } public long getOnCompletedRollingFailureCount() { return completeFailure.rateValue(); } public long getOnCompletedCount() { return complete.value(); } public long getOnCompletedFailureCount() { return completeFailure.value(); } public long getSubscribedCount() { return subscribe.value(); } public long getUnsubscribedCount() { return unsubscribe.value(); } }
8,797
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/ConnectToObservable.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.codec.Decoder; import java.util.HashMap; import java.util.Map; import rx.functions.Action0; import rx.functions.Action2; import rx.subjects.PublishSubject; public class ConnectToObservable<T> extends ConnectToConfig { private Decoder<T> decoder; private Action2<T, Throwable> deocdingErrorHandler; ConnectToObservable(Builder<T> builder) { super(builder.host, builder.port, builder.name, builder.subscribeParameters, builder.subscribeRetryAttempts, builder.suppressDecodingErrors, builder.connectionDisconnectCallback, builder.closeTrigger); this.decoder = builder.decoder; this.deocdingErrorHandler = builder.deocdingErrorHandler; } public Decoder<T> getDecoder() { return decoder; } public Action2<T, Throwable> getDeocdingErrorHandler() { return deocdingErrorHandler; } public static class Builder<T> { private String host; private int port; private String name; private Decoder<T> decoder; private Map<String, String> subscribeParameters = new HashMap<>(); private int subscribeRetryAttempts = 3; private Action2<T, Throwable> deocdingErrorHandler = new Action2<T, Throwable>() { @Override public void call(T t1, Throwable t2) { t2.printStackTrace(); } }; private boolean suppressDecodingErrors = false; private Action0 connectionDisconnectCallback = new Action0() { @Override public void call() {} }; private PublishSubject<Integer> closeTrigger = PublishSubject.create(); public Builder() {} public Builder(Builder<T> config) { this.host = config.host; this.port = config.port; this.name = config.name; this.decoder = config.decoder; this.subscribeParameters.putAll(config.subscribeParameters); this.subscribeRetryAttempts = config.subscribeRetryAttempts; this.deocdingErrorHandler = config.deocdingErrorHandler; this.suppressDecodingErrors = config.suppressDecodingErrors; } public Builder<T> host(String host) { this.host = host; return this; } public Builder<T> port(int port) { this.port = port; return this; } public Builder<T> closeTrigger(PublishSubject<Integer> closeTrigger) { this.closeTrigger = closeTrigger; return this; } public Builder<T> connectionDisconnectCallback(Action0 connectionDisconnectCallback) { this.connectionDisconnectCallback = connectionDisconnectCallback; return this; } public Builder<T> deocdingErrorHandler(Action2<T, Throwable> handler, boolean suppressDecodingErrors) { this.deocdingErrorHandler = handler; this.suppressDecodingErrors = suppressDecodingErrors; return this; } public Builder<T> name(String name) { this.name = name; this.subscribeParameters.put("groupId", name); //used with modern server for routing return this; } public Builder<T> slotId(String slotId) { this.subscribeParameters.put("slotId", slotId); return this; } public Builder<T> decoder(Decoder<T> decoder) { this.decoder = decoder; return this; } public Builder<T> subscribeParameters(Map<String, String> subscribeParameters) { this.subscribeParameters.putAll(subscribeParameters); return this; } public Builder<T> subscribeAttempts(int subscribeAttempts) { this.subscribeRetryAttempts = subscribeAttempts; return this; } public ConnectToObservable<T> build() { return new ConnectToObservable<T>(this); } } }
8,798
0
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote
Create_ds/mantis/mantis-remote-observable/src/main/java/io/reactivex/mantis/remote/observable/WriteBytesObserver.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 io.reactivex.mantis.remote.observable; import io.mantisrx.common.network.WritableEndpoint; import io.reactivex.mantis.remote.observable.slotting.SlottingStrategy; import java.util.List; import mantis.io.reactivex.netty.channel.ObservableConnection; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; public class WriteBytesObserver<T> extends SafeWriter implements Action1<List<RemoteRxEvent>> { private final ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection; private final MutableReference<Subscription> subReference; private final RxMetrics serverMetrics; private final SlottingStrategy<T> slottingStrategy; private final WritableEndpoint<T> endpoint; public WriteBytesObserver( ObservableConnection<RemoteRxEvent, List<RemoteRxEvent>> connection, MutableReference<Subscription> subReference, RxMetrics serverMetrics, SlottingStrategy<T> slottingStrategy, WritableEndpoint<T> endpoint) { this.connection = connection; this.subReference = subReference; this.serverMetrics = serverMetrics; this.slottingStrategy = slottingStrategy; this.endpoint = endpoint; } @Override public void call(final List<RemoteRxEvent> events) { if (!safeWrite(connection, events, subReference, // successful write callback new Action0() { @Override public void call() { serverMetrics.incrementNextCount(events.size()); } }, // failed write callback new Action1<Throwable>() { @Override public void call(Throwable t1) { serverMetrics.incrementNextFailureCount(events.size()); logger.warn("Failed to write onNext event to remote observable: " + endpoint + "" + " at address: " + connection.getChannel().remoteAddress() + " reason: " + t1.getMessage() + " force unsubscribe", t1); // TODO add callback here to notify when complete even fails subReference.getValue().unsubscribe(); } }, slottingStrategy, endpoint )) { // check if connection is closed if (connection.isCloseIssued()) { slottingStrategy.removeConnection(endpoint); } serverMetrics.incrementNextFailureCount(); } ; } }
8,799