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-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/TaskStatusUpdateHandler.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.client; import io.mantisrx.server.core.Status; /** * TaskStatusUpdateHandler is responsible for handling updates to task statuses as the task is being run. */ public interface TaskStatusUpdateHandler { void onStatusUpdate(Status status); /** * Creates a task status update handler that keeps the mantis master up to date on the task's progress. * @param gateway gateway that needs to kept upto date. * @return created instance of TaskStatusUpdateHandler */ static TaskStatusUpdateHandler forReportingToGateway(MantisMasterGateway gateway) { return new TaskStatusUpdateHandlerImpl(gateway); } }
8,200
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/ResourceLeaderConnection.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.client; /** * ResourceLeaderConnection helps create a connection with the leader resource. You create a connection using the * register method and on subsequent changes to the leader resource, the listener gets notified so that the caller * can perform appropriate actions as necessary. * * @param <ResourceT> type of the resource being connected to. */ public interface ResourceLeaderConnection<ResourceT> { ResourceT getCurrent(); void register(ResourceLeaderChangeListener<ResourceT> changeListener); interface ResourceLeaderChangeListener<ResourceT> { void onResourceLeaderChanged(ResourceT previousResourceLeader, ResourceT newResourceLeader); } }
8,201
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/HttpUtility.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.server.master.client; 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 io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import java.nio.charset.Charset; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import mantis.io.reactivex.netty.client.RxClient; import mantis.io.reactivex.netty.pipeline.PipelineConfigurator; import mantis.io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; import mantis.io.reactivex.netty.protocol.http.client.HttpClient; import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest; import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; /* package */ class HttpUtility { private static final Logger logger = LoggerFactory.getLogger(HttpUtility.class); private static final long GET_TIMEOUT_SECS = 30; private static final int MAX_REDIRECTS = 10; static Observable<String> getGetResponse(String host, int port, String uri) { return new CompositeHttpClientBuilder<ByteBuf, ByteBuf>() .appendPipelineConfigurator( new PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>>() { @Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast("introspecting-handler", new ChannelDuplexHandler() { private String uri = "<undefined>"; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; uri = request.getUri(); logger.info("Sending request on channel id: " + ctx.channel().toString() + ", request URI: " + uri); } super.write(ctx, msg, promise); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { logger.info("Received response on channel id: " + ctx.channel().toString() + ", request URI: " + uri); } super.channelRead(ctx, msg); } }); try { int maxContentLength = 10 * 1024 * 1024; // Ten megabytes pipeline.replace(HttpObjectAggregator.class, "http-object-aggregator", new HttpObjectAggregator(maxContentLength)); } catch (NoSuchElementException ex) { logger.error("HttpObjectAggregator did not exist in this pipeline. Error: {}", ex.getMessage(), ex); } catch (IllegalArgumentException ex) { logger.error("ChannelHandler named http-object-aggregator already existed in this" + " pipeline. Error: {}", ex.getMessage(), ex); } catch (Throwable t) { logger.error("Unknown error adding HttpObjectAggregator to Master Client " + "Pipeline. Error: {}", t.getMessage(), t); } } }) .build() .submit(new RxClient.ServerInfo(host, port), HttpClientRequest.createGet(uri), new HttpClient.HttpClientConfig.Builder().setFollowRedirect(true).followRedirect(MAX_REDIRECTS).build()) .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> response) { return response.getContent(); } }) .map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf o) { return o.toString(Charset.defaultCharset()); } }) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.warn("Error: " + throwable.getMessage(), throwable); } }) .timeout(GET_TIMEOUT_SECS, TimeUnit.SECONDS); } }
8,202
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/NoSuchJobException.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.server.master.client; public class NoSuchJobException extends Exception { public NoSuchJobException(String jobId) { super(jobId + " doesn't exist"); } public NoSuchJobException(String jobId, Throwable t) { super(jobId + " doesn't exist", t); } }
8,203
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/ResubmitJobWorkerRequest.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.server.master.client; 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 ResubmitJobWorkerRequest { @JsonProperty("JobId") private final String jobId; @JsonProperty("user") private final String user; @JsonProperty("workerNumber") private final int workerNumber; @JsonProperty("reason") private final String reason; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public ResubmitJobWorkerRequest(final String jobId, final String user, final int workerNumber, final String reason) { this.jobId = jobId; this.user = user; this.workerNumber = workerNumber; this.reason = reason; } public String getJobId() { return jobId; } public String getUser() { return user; } public int getWorkerNumber() { return workerNumber; } public String getReason() { return reason; } @Override public String toString() { return "ResubmitJobWorkerRequest{" + "jobId='" + jobId + '\'' + ", user='" + user + '\'' + ", workerNumber=" + workerNumber + ", reason='" + reason + '\'' + '}'; } }
8,204
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/JobSubmitResponse.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.server.master.client; public class JobSubmitResponse { private final String jobId; private final boolean failed; private final String errorMessage; public JobSubmitResponse(String jobId, boolean failed, String errorMessage) { this.jobId = jobId; this.failed = failed; this.errorMessage = errorMessage; } public String getJobId() { return jobId; } public boolean isFailed() { return failed; } public String getErrorMessage() { return errorMessage; } }
8,205
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/TestGetMasterMonitor.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.server.master.client; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.master.MasterDescription; import io.mantisrx.server.core.master.MasterMonitor; import io.mantisrx.server.core.zookeeper.CuratorService; import io.mantisrx.server.master.client.config.StaticPropertiesConfigurationFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import rx.functions.Action1; import rx.functions.Func1; public class TestGetMasterMonitor { @Argument(alias = "p", description = "Specify a configuration file", required = true) private static String propFile = ""; public static void main(String[] args) { try { Args.parse(TestGetMasterMonitor.class, args); } catch (IllegalArgumentException e) { Args.usage(TestGetMasterMonitor.class); System.exit(1); } Properties properties = new Properties(); System.out.println("propfile=" + propFile); try (InputStream inputStream = new FileInputStream(propFile)) { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } final AtomicInteger counter = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(5); StaticPropertiesConfigurationFactory configurationFactory = new StaticPropertiesConfigurationFactory(properties); CoreConfiguration config = configurationFactory.getConfig(); final CuratorService curatorService = new CuratorService(config); MasterMonitor masterMonitor = curatorService.getMasterMonitor(); masterMonitor.getMasterObservable() .filter(new Func1<MasterDescription, Boolean>() { @Override public Boolean call(MasterDescription masterDescription) { return masterDescription != null; } }) .doOnNext(new Action1<MasterDescription>() { @Override public void call(MasterDescription masterDescription) { System.out.println(counter.incrementAndGet() + ": Got new master: " + masterDescription.toString()); latch.countDown(); } }) .subscribe(); curatorService.start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }
8,206
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/MantisClientException.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.server.master.client; public class MantisClientException extends Exception { public MantisClientException(String message) { super(message); } public MantisClientException(String message, Throwable cause) { super(message, cause); } public MantisClientException(Throwable cause) { super(cause); } }
8,207
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/MantisMasterClientApi.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.server.master.client; import static org.asynchttpclient.Dsl.asyncHttpClient; import static org.asynchttpclient.Dsl.post; import com.spotify.futures.CompletableFutures; import io.mantisrx.common.Ack; import io.mantisrx.common.Label; import io.mantisrx.common.network.Endpoint; import io.mantisrx.runtime.JobSla; import io.mantisrx.runtime.MantisJobDefinition; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.runtime.WorkerMigrationConfig; import io.mantisrx.runtime.codec.JsonCodec; import io.mantisrx.runtime.descriptor.DeploymentStrategy; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.server.core.JobAssignmentResult; import io.mantisrx.server.core.JobSchedulingInfo; import io.mantisrx.server.core.NamedJobInfo; import io.mantisrx.server.core.PostJobStatusRequest; import io.mantisrx.server.core.Status; import io.mantisrx.server.core.master.MasterDescription; import io.mantisrx.server.core.master.MasterMonitor; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException; import io.mantisrx.shaded.com.fasterxml.jackson.core.type.TypeReference; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpStatusClass; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.reactivex.mantis.remote.observable.ConnectToObservable; import io.reactivex.mantis.remote.observable.DynamicConnectionSet; import io.reactivex.mantis.remote.observable.ToDeltaEndpointInjector; import io.reactivex.mantis.remote.observable.reconciliator.Reconciliator; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import mantis.io.reactivex.netty.RxNetty; import mantis.io.reactivex.netty.channel.ObservableConnection; import mantis.io.reactivex.netty.pipeline.PipelineConfigurators; import mantis.io.reactivex.netty.protocol.http.client.HttpClient; import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest; import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse; import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent; import mantis.io.reactivex.netty.protocol.http.websocket.WebSocketClient; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.RequestBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; /** * */ public class MantisMasterClientApi implements MantisMasterGateway { static final String ConnectTimeoutSecsPropertyName = "MantisClientConnectTimeoutSecs"; private static final ObjectMapper objectMapper; private static final Logger logger = LoggerFactory.getLogger(MantisMasterClientApi.class); private static final String JOB_METADATA_FIELD = "jobMetadata"; private static final String STAGE_MEDATA_LIST_FIELD = "stageMetadataList"; private static final String STAGE_NUM_FIELD = "stageNum"; private static final String NUM_STAGES_FIELD = "numStages"; private static final int MAX_REDIRECTS = 10; private static final String API_JOBS_LIST_PATH = "/api/jobs/list"; private static final String API_JOBS_LIST_MATCHING_PATH = "/api/jobs/list/matching"; private static final String API_JOB_SUBMIT_PATH = "/api/submit"; private static final String API_JOB_NAME_CREATE = "/api/namedjob/create"; private static final String API_JOB_NAME_UPDATE = "/api/namedjob/update"; private static final String API_JOB_NAME_LIST = "/api/namedjob/list"; private static final String API_JOB_KILL = "/api/jobs/kill"; private static final String API_JOB_STAGE_SCALE = "/api/jobs/scaleStage"; private static final String API_JOB_RESUBMIT_WORKER = "/api/jobs/resubmitWorker"; // Retry attempts before giving up in connection to master // each attempt waits attempt amount of time, 10=55 seconds private static final int SUBSCRIBE_ATTEMPTS_TO_MASTER = 100; private static final int MAX_RANDOM_WAIT_RETRY_SEC = 10; // The following timeout should be what's in master configuration's mantis.scheduling.info.observable.heartbeat.interval.secs private static final long MASTER_SCHED_INFO_HEARTBEAT_INTERVAL_SECS = 120; static { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.registerModule(new Jdk8Module()); } final String DEFAULT_RESPONSE = "NO_RESPONSE_FROM_MASTER"; private final long GET_TIMEOUT_SECS = 30; private final Observable<Endpoint> masterEndpoint; private final int subscribeAttemptsToMaster; private final Func1<Observable<? extends Throwable>, Observable<?>> retryLogic = attempts -> attempts .zipWith(Observable.range(1, Integer.MAX_VALUE), (Func2<Throwable, Integer, Integer>) (t1, integer) -> integer) .flatMap((Func1<Integer, Observable<?>>) integer -> { long delay = 2 * (integer > 10 ? 10 : integer); logger.info(": retrying conx after sleeping for " + delay + " secs"); return Observable.timer(delay, TimeUnit.SECONDS); }); private final Func1<Observable<? extends Void>, Observable<?>> repeatLogic = attempts -> attempts .zipWith(Observable.range(1, Integer.MAX_VALUE), (Func2<Void, Integer, Integer>) (t1, integer) -> integer) .flatMap((Func1<Integer, Observable<?>>) integer -> { long delay = 2 * (integer > 10 ? 10 : integer); logger.warn("On Complete received! : repeating conx after sleeping for " + delay + " secs"); return Observable.timer(delay, TimeUnit.SECONDS); }); private MasterMonitor masterMonitor; /** * * @param masterMonitor */ public MantisMasterClientApi(MasterMonitor masterMonitor) { this.masterMonitor = masterMonitor; masterEndpoint = masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .map(description -> { logger.info("New Mantis Master notification, host: " + description.getHostname() + "," + " swapping out client API connection to new master."); return new Endpoint(description.getHostname(), description.getApiPortV2()); }); apiClient = asyncHttpClient(); int a = SUBSCRIBE_ATTEMPTS_TO_MASTER; final String p = System.getProperty(ConnectTimeoutSecsPropertyName); if (p != null) { try { long t = Long.parseLong(p); a = Math.max(1, (int) Math.sqrt(2.0 * t)); // timeout = SUM(1 + 2 + ... + N) =~ (N^2)/2 } catch (NumberFormatException e) { logger.warn("Invalid number for connectTimeoutSecs: " + p); } } subscribeAttemptsToMaster = Integer.MAX_VALUE; } private String toUri(MasterDescription md, String path) { return "http://" + md.getHostname() + ":" + md.getApiPort() + path; } /** * * @param name * @param version * @param parameters * @param jobSla * @param schedulingInfo * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final SchedulingInfo schedulingInfo) { return submitJob(name, version, parameters, jobSla, 0L, schedulingInfo, WorkerMigrationConfig.DEFAULT); } /** * * @param name * @param version * @param parameters * @param jobSla * @param subscriptionTimeoutSecs * @param schedulingInfo * @param migrationConfig * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final WorkerMigrationConfig migrationConfig) { return submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, false, migrationConfig); } /** * * @param name * @param version * @param parameters * @param jobSla * @param subscriptionTimeoutSecs * @param schedulingInfo * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo) { return submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, false, WorkerMigrationConfig.DEFAULT); } /** * * @param name * @param version * @param parameters * @param jobSla * @param subscriptionTimeoutSecs * @param schedulingInfo * @param readyForJobMaster * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final boolean readyForJobMaster) { return submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, readyForJobMaster, WorkerMigrationConfig.DEFAULT); } /** * * @param name * @param version * @param parameters * @param jobSla * @param subscriptionTimeoutSecs * @param schedulingInfo * @param readyForJobMaster * @param migrationConfig * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final boolean readyForJobMaster, final WorkerMigrationConfig migrationConfig) { return submitJob(name, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, readyForJobMaster, migrationConfig, new LinkedList<>()); } /** * * @param name * @param version * @param parameters * @param jobSla * @param subscriptionTimeoutSecs * @param schedulingInfo * @param readyForJobMaster * @param migrationConfig * @param labels * @return */ public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final boolean readyForJobMaster, final WorkerMigrationConfig migrationConfig, final List<Label> labels) { try { String jobDef = getJobDefinitionString(name, null, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, readyForJobMaster, migrationConfig, labels, null); return submitJob(jobDef); } catch (MalformedURLException | JsonProcessingException e) { return Observable.error(e); } } public Observable<JobSubmitResponse> submitJob(final String name, final String version, final List<Parameter> parameters, final JobSla jobSla, final long subscriptionTimeoutSecs, final SchedulingInfo schedulingInfo, final boolean readyForJobMaster, final WorkerMigrationConfig migrationConfig, final List<Label> labels, final DeploymentStrategy deploymentStrategy) { try { String jobDef = getJobDefinitionString(name, null, version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, readyForJobMaster, migrationConfig, labels, deploymentStrategy); return submitJob(jobDef); } catch (MalformedURLException | JsonProcessingException e) { return Observable.error(e); } } /** * * @param submitJobRequestJson * @return */ public Observable<JobSubmitResponse> submitJob(final String submitJobRequestJson) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .switchMap((Func1<MasterDescription, Observable<JobSubmitResponse>>) masterDescription -> { String uri = "http://" + masterDescription.getHostname() + ":" + masterDescription.getApiPort() + API_JOB_SUBMIT_PATH; logger.info("Doing POST on " + uri); try { return getPostResponse(uri, submitJobRequestJson) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.empty(); }) .map(s -> new JobSubmitResponse(s, false, null)); } catch (Exception e) { return Observable.error(e); } }); } private String getJobDefinitionString(String name, String jobUrl, String version, List<Parameter> parameters, JobSla jobSla, long subscriptionTimeoutSecs, SchedulingInfo schedulingInfo, boolean readyForJobMaster, final WorkerMigrationConfig migrationConfig, final List<Label> labels, final DeploymentStrategy deploymentStrategy) throws JsonProcessingException, MalformedURLException { MantisJobDefinition jobDefinition = new MantisJobDefinition(name, System.getProperty("user.name"), jobUrl == null ? null : new URL(jobUrl), version, parameters, jobSla, subscriptionTimeoutSecs, schedulingInfo, 0, 0, null, null, readyForJobMaster, migrationConfig, labels, deploymentStrategy); return objectMapper.writeValueAsString(jobDefinition); } public Observable<Void> killJob(final String jobId) { return killJob(jobId, "Unknown", "User requested"); } /** * * @param jobId * @param user * @param reason * @return */ public Observable<Void> killJob(final String jobId, final String user, final String reason) { return masterMonitor.getMasterObservable() .filter(md -> md != null) .switchMap((Func1<MasterDescription, Observable<Void>>) md -> { Map<String, String> content = new HashMap<>(); content.put("JobId", jobId); content.put("user", user); content.put("reason", reason); try { return getPostResponse(toUri(md, API_JOB_KILL), objectMapper.writeValueAsString(content)) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.empty(); }) .map(s -> { logger.info(s); return null; }); } catch (JsonProcessingException e) { return Observable.error(e); } }); } /** * * @param jobId * @param stageNum * @param numWorkers * @param reason * @return */ public Observable<Boolean> scaleJobStage(final String jobId, final int stageNum, final int numWorkers, final String reason) { return masterMonitor .getMasterObservable() .filter(md -> md != null) .take(1) .flatMap((Func1<MasterDescription, Observable<Boolean>>) md -> { final StageScaleRequest stageScaleRequest = new StageScaleRequest(jobId, stageNum, numWorkers, reason); try { return submitPostRequest(toUri(md, API_JOB_STAGE_SCALE), objectMapper.writeValueAsString(stageScaleRequest)) .map(s -> { logger.info("POST to scale stage returned status: {}", s); return s.codeClass().equals(HttpStatusClass.SUCCESS); }); } catch (JsonProcessingException e) { logger.error("failed to serialize stage scale request {} to json", stageScaleRequest); return Observable.error(e); } }); } /** * * @param jobId * @param user * @param workerNum * @param reason * @return */ public Observable<Boolean> resubmitJobWorker(final String jobId, final String user, final int workerNum, final String reason) { return masterMonitor.getMasterObservable() .filter(md -> md != null) .take(1) .flatMap((Func1<MasterDescription, Observable<Boolean>>) md -> { final ResubmitJobWorkerRequest resubmitJobWorkerRequest = new ResubmitJobWorkerRequest(jobId, user, workerNum, reason); logger.info("sending request to resubmit worker {} for jobId {}", workerNum, jobId); try { return submitPostRequest(toUri(md, API_JOB_RESUBMIT_WORKER), objectMapper.writeValueAsString(resubmitJobWorkerRequest)) .map(s -> { logger.info("POST to resubmit worker {} returned status: {}", workerNum, s); return s.codeClass().equals(HttpStatusClass.SUCCESS); }); } catch (JsonProcessingException e) { logger.error("failed to serialize resubmit job worker request {} to json", resubmitJobWorkerRequest); return Observable.error(e); } }); } private Observable<HttpResponseStatus> submitPostRequest(String uri, String postContent) { logger.info("sending POST request to {} content {}", uri, postContent); return RxNetty .createHttpRequest( HttpClientRequest.createPost(uri) .withContent(postContent), new HttpClient.HttpClientConfig.Builder() .build()) .map(b -> b.getStatus()); } private Observable<String> getPostResponse(String uri, String postContent) { logger.info("sending POST request to {} content {}", uri, postContent); return RxNetty .createHttpRequest( HttpClientRequest.createPost(uri) .withContent(postContent), new HttpClient.HttpClientConfig.Builder() .build()) .flatMap((Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>) b -> b.getContent()) .map(o -> o.toString(Charset.defaultCharset())); } /** * * @param jobName * @return */ public Observable<Boolean> namedJobExists(final String jobName) { return masterMonitor.getMasterObservable() .filter(md -> md != null) .switchMap((Func1<MasterDescription, Observable<Boolean>>) masterDescription -> { String uri = API_JOB_NAME_LIST + "/" + jobName; logger.info("Calling GET on " + uri); return HttpUtility.getGetResponse(masterDescription.getHostname(), masterDescription.getApiPort(), uri) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.error(throwable); }) .map(response -> { logger.debug("Job cluster response: " + response); JSONArray jsonArray = new JSONArray(response); return jsonArray.length() > 0; }) .retryWhen(retryLogic) ; }) .retryWhen(retryLogic) ; } /** * * @param jobId * @return */ public Observable<Integer> getSinkStageNum(final String jobId) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .switchMap(masterDescription -> { String uri = API_JOBS_LIST_PATH + "/" + jobId; logger.info("Calling GET on " + uri); return HttpUtility.getGetResponse(masterDescription.getHostname(), masterDescription.getApiPort(), uri) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.error(throwable); }) .flatMap(response -> { try { logger.info("Got response for job info on " + jobId); Integer sinkStage = getSinkStageNumFromJsonResponse(jobId, response); if (sinkStage < 0) { logger.warn("Job " + jobId + " not found"); return Observable.error(new Exception("Job " + jobId + " not found, response: " + response)); } return Observable.just(sinkStage); } catch (MasterClientException e) { logger.warn("Can't get sink stage info for " + jobId + ": " + e.getMessage()); return Observable.error(new Exception("Can't get sink stage info for " + jobId + ": " + e.getMessage(), e)); } }) .retryWhen(retryLogic) ; }); } /** * * @param jobName * @param state * @return */ // returns json array of job metadata public Observable<String> getJobsOfNamedJob(final String jobName, final MantisJobState.MetaState state) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .switchMap(masterDescription -> { String uri = API_JOBS_LIST_MATCHING_PATH + "/" + jobName; if (state != null) uri = uri + "?jobState=" + state; logger.info("Calling GET on " + uri); return HttpUtility.getGetResponse(masterDescription.getHostname(), masterDescription.getApiPort(), uri) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.empty(); }); }) .retryWhen(retryLogic) ; } /** * Checks the existence of a jobId by calling GET on the Master * for /api/jobs/list/_jobId_ and ensuring the response is not an error. * * @param jobId The id of the Mantis job. * @return A boolean indicating whether the job id exists or not. */ public Observable<Boolean> jobIdExists(final String jobId) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .switchMap(masterDescription -> { String uri = API_JOBS_LIST_PATH + "/" + jobId; logger.info("Calling GET on " + uri); return HttpUtility.getGetResponse(masterDescription.getHostname(), masterDescription.getApiPort(), uri) .onErrorResumeNext(throwable -> { logger.warn("Can't connect to master: {}", throwable.getMessage(), throwable); return Observable.empty(); }); }) .retryWhen(retryLogic) .map(payload -> !payloadIsError(payload)); } /** * Checks wether a master response is of the form <code>{"error": "message"}</code> * @param payload A string representation of the payload returned by Master GET /api/jobs/list/_jobId_ * @return A boolean indicating true if this payload represents an error. */ private boolean payloadIsError(String payload) { try { Map<String, String> decoded = objectMapper.readValue(payload, new TypeReference<Map<String, String>>() {}); return decoded.get("error") != null; } catch(Exception ex) { // No op } return false; } private Integer getSinkStageNumFromJsonResponse(String jobId, String response) throws MasterClientException { final String throwMessage = "Can't parse json response for job " + jobId; if (response == null) { logger.warn("Null info response from master for job " + jobId); throw new MasterClientException(throwMessage); } try { JSONObject jsonObject = new JSONObject(response); JSONObject jobMetadata = jsonObject.optJSONObject(JOB_METADATA_FIELD); if (jobMetadata == null) { logger.warn("Didn't find meta data for job " + jobId + " in json (" + response + ")"); return -1; } String state = jobMetadata.optString("state"); if (state == null) { throw new MasterClientException("Can't read job state in response (" + response + ")"); } if (MantisJobState.isTerminalState(MantisJobState.valueOf(state))) { logger.info("Can't get sink stage of job in state " + MantisJobState.valueOf(state)); return -1; } int lastStage = 0; JSONArray stages = jsonObject.optJSONArray(STAGE_MEDATA_LIST_FIELD); if (stages == null) { logger.warn("Didn't find stages metadata for job " + jobId + " in json: " + response); throw new MasterClientException(throwMessage); } for (int i = 0; i < stages.length(); i++) { final JSONObject s = stages.getJSONObject(i); final int n = s.optInt(STAGE_NUM_FIELD, 0); lastStage = Math.max(lastStage, n); } if (lastStage == 0) { logger.warn("Didn't find " + STAGE_NUM_FIELD + " field in stage metadata json (" + response + ")"); throw new MasterClientException(throwMessage); } logger.info("Got sink stage number for job " + jobId + ": " + lastStage); return lastStage; } catch (JSONException e) { logger.error("Error parsing info for job " + jobId + " from json data (" + response + "): " + e.getMessage()); throw new MasterClientException(throwMessage); } } private HttpClient<ByteBuf, ServerSentEvent> getRxnettySseClient(String hostname, int port) { return RxNetty.<ByteBuf, ServerSentEvent>newHttpClientBuilder(hostname, port) .pipelineConfigurator(PipelineConfigurators.clientSseConfigurator()) //.enableWireLogging(LogLevel.ERROR) .withNoConnectionPooling().build(); } private WebSocketClient<TextWebSocketFrame, TextWebSocketFrame> getRxnettyWebSocketClient(String host, int port, String uri) { logger.debug("Creating websocket client for " + host + ":" + port + " uri " + uri + " ..."); return RxNetty.<TextWebSocketFrame, TextWebSocketFrame>newWebSocketClientBuilder(host, port) .withWebSocketURI(uri) // .withWebSocketVersion(WebSocketVersion.V13) .build(); } /** * * @param jobId * @return */ public Observable<String> getJobStatusObservable(final String jobId) { return masterMonitor.getMasterObservable() .filter((md) -> md != null) .retryWhen(retryLogic) .switchMap((md) -> getRxnettyWebSocketClient(md.getHostname(), md.getConsolePort(), "ws://" + md.getHostname() + ":" + md.getApiPort() + "/job/status/" + jobId) .connect() .flatMap((ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> connection) -> connection.getInput() .map((TextWebSocketFrame webSocketFrame) -> webSocketFrame.text()))) .onErrorResumeNext(Observable.empty()); } /** * * @param jobId * @return */ public Observable<JobSchedulingInfo> schedulingChanges(final String jobId) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .retryWhen(retryLogic) .switchMap((Func1<MasterDescription, Observable<JobSchedulingInfo>>) masterDescription -> getRxnettySseClient( masterDescription.getHostname(), masterDescription.getSchedInfoPort()) .submit(HttpClientRequest.createGet("/assignmentresults/" + jobId + "?sendHB=true")) .flatMap((Func1<HttpClientResponse<ServerSentEvent>, Observable<JobSchedulingInfo>>) response -> { if (!HttpResponseStatus.OK.equals(response.getStatus())) { return Observable.error(new Exception(response.getStatus().reasonPhrase())); } return response.getContent() .map(event -> { try { return objectMapper.readValue(event.contentAsString(), JobSchedulingInfo.class); } catch (IOException e) { throw new RuntimeException("Invalid schedInfo json: " + e.getMessage(), e); } }) .timeout(3 * MASTER_SCHED_INFO_HEARTBEAT_INTERVAL_SECS, TimeUnit.SECONDS) .filter(schedulingInfo -> schedulingInfo != null && !JobSchedulingInfo.HB_JobId.equals(schedulingInfo.getJobId())) .distinctUntilChanged() ; })) .repeatWhen(repeatLogic) .retryWhen(retryLogic) ; } /** * * @param jobName * @return */ public Observable<NamedJobInfo> namedJobInfo(final String jobName) { return masterMonitor.getMasterObservable() .filter(masterDescription -> masterDescription != null) .retryWhen(retryLogic) .switchMap((Func1<MasterDescription, Observable<NamedJobInfo>>) masterDescription -> getRxnettySseClient(masterDescription.getHostname(), masterDescription.getSchedInfoPort()) .submit(HttpClientRequest.createGet("/namedjobs/" + jobName + "?sendHB=true")) .flatMap((Func1<HttpClientResponse<ServerSentEvent>, Observable<NamedJobInfo>>) response -> { if (!HttpResponseStatus.OK.equals(response.getStatus())) return Observable.error(new Exception(response.getStatus().reasonPhrase())); return response.getContent() .map(event -> { try { return objectMapper.readValue(event.contentAsString(), NamedJobInfo.class); } catch (IOException e) { throw new RuntimeException("Invalid namedJobInfo json: " + e.getMessage(), e); } }) .timeout(3 * MASTER_SCHED_INFO_HEARTBEAT_INTERVAL_SECS, TimeUnit.SECONDS) .filter(namedJobInfo -> namedJobInfo != null && !JobSchedulingInfo.HB_JobId.equals(namedJobInfo.getName())) ; })) .repeatWhen(repeatLogic) .retryWhen(retryLogic) ; } /** * * @param jobId * @return */ public Observable<JobAssignmentResult> assignmentResults(String jobId) { ConnectToObservable.Builder<JobAssignmentResult> connectionBuilder = new ConnectToObservable.Builder<JobAssignmentResult>() .subscribeAttempts(subscribeAttemptsToMaster) .name("/v1/api/master/assignmentresults") .decoder(new JsonCodec<JobAssignmentResult>(JobAssignmentResult.class)); if (jobId != null && !jobId.isEmpty()) { Map<String, String> subscriptionParams = new HashMap<>(); subscriptionParams.put("jobId", jobId); connectionBuilder = connectionBuilder.subscribeParameters(subscriptionParams); } Observable<List<Endpoint>> changes = masterEndpoint .map(t1 -> { List<Endpoint> list = new ArrayList<>(1); list.add(t1); return list; }); Reconciliator<JobAssignmentResult> reconciliator = new Reconciliator.Builder<JobAssignmentResult>() .name("master-jobAssignmentResults") .connectionSet(DynamicConnectionSet.create(connectionBuilder, MAX_RANDOM_WAIT_RETRY_SEC)) .injector(new ToDeltaEndpointInjector(changes)) .build(); return Observable.merge(reconciliator.observables()); } private final AsyncHttpClient apiClient; /** * Implementation of updateStatus that updates the status of the worker on the mantis-master. * @param status status that contains all the information about the worker such as the WorkerId, * State of the worker, etc... * @return Acknowledgement if the update was received by the mantis-master leader. */ @Override public CompletableFuture<Ack> updateStatus(Status status) { try { final String statusUpdate = objectMapper.writeValueAsString( new PostJobStatusRequest(status.getJobId(), status)); final RequestBuilder requestBuilder = post(masterMonitor.getLatestMaster().getFullApiStatusUri()) .setBody(statusUpdate); return apiClient .executeRequest(requestBuilder) .toCompletableFuture() .thenCompose(response -> { if (response.getStatusCode() == 200) { return CompletableFuture.completedFuture(Ack.getInstance()); } else { return CompletableFutures.exceptionallyCompletedFuture( new Exception(response.getResponseBody())); } }); } catch (Exception e) { return CompletableFutures.exceptionallyCompletedFuture(e); } } }
8,208
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/config/ConfigurationFactory.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.server.master.client.config; import io.mantisrx.server.core.CoreConfiguration; public interface ConfigurationFactory { CoreConfiguration getConfig(); }
8,209
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/config/PluginCoercible.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.client.config; import io.mantisrx.shaded.org.apache.curator.shaded.com.google.common.base.Preconditions; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Properties; import lombok.RequiredArgsConstructor; import org.apache.flink.util.ExceptionUtils; import org.skife.config.Coercer; import org.skife.config.Coercible; /** * Coorcible that converts a value to a class object. The value represents the class object that needs to be * initialized. The mechanism for initializing the class object is as follows: * 1. The class, as represented by the value, is searched for a static method with the signature * static T valueOf(Properties properties) * 2. The method is called with all the properties that the configuration is aware of. * * <pre> * Example usage: * interface Configuration { * @Config("mantis.taskexecutor.metrics.collector") * @Default("io.mantisrx.server.worker.mesos.MesosMetricsCollector") * MetricsCollector getUsageSupplier(); * } * * class MesosMetricsCollector { * public static MesosMetricsCollector valueOf(Properties properties) { * } * } * </pre> * * @param <T> type of the object that the value needs to return */ @RequiredArgsConstructor public class PluginCoercible<T> implements Coercible<T> { private final Class<T> tClass; private final Properties properties; @SuppressWarnings("unchecked") public Coercer<T> accept(final Class<?> type) { if (tClass.isAssignableFrom(type)) { return value -> { try { Class<?> derivedType = Class.forName(value); Method candidate = derivedType.getMethod("valueOf", Properties.class); // Method must be 'static valueOf(Properties)' and return the type in question. Preconditions.checkArgument(Modifier.isStatic(candidate.getModifiers())); Preconditions.checkArgument(type.isAssignableFrom(candidate.getReturnType())); return (T) candidate.invoke(null, properties); } catch (Exception e) { ExceptionUtils.rethrow(e); return null; } }; } else { return null; } } }
8,210
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/config/StaticPropertiesConfigurationFactory.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.server.master.client.config; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.MetricsCoercer; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; public class StaticPropertiesConfigurationFactory implements ConfigurationFactory { private final ConfigurationObjectFactory delegate; private final CoreConfiguration config; public StaticPropertiesConfigurationFactory(Properties props) { delegate = new ConfigurationObjectFactory(props); delegate.addCoercible(new MetricsCoercer(props)); // delegate.addCoercible(new MantisPropertiesCoercer(props)); config = delegate.build(CoreConfiguration.class); } @Override public CoreConfiguration getConfig() { return config; } @Override public String toString() { return "StaticPropertiesConfigurationFactory{" + "delegate=" + delegate + ", config=" + config + '}'; } }
8,211
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic/plugin/DiagnosticMessageType.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.server.master.client.diagnostic.plugin; /** an enumeration of different types of diagnostic messages */ public enum DiagnosticMessageType { }
8,212
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic/plugin/DiagnosticMessage.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.server.master.client.diagnostic.plugin; import java.util.Map; /** struct for recording messages */ public class DiagnosticMessage { public static class Builder { private final DiagnosticMessageType messageType; private Throwable error; private String description; private Map<String, String> tags; private Builder(final DiagnosticMessageType messageType) { this.messageType = messageType; } public Builder withError(final Throwable error) { this.error = error; return this; } public Builder withDescription(final String description) { this.description = description; return this; } public Builder withTags(final Map<String, String> tags) { this.tags = tags; return this; } public DiagnosticMessage build() { return new DiagnosticMessage(this); } } private DiagnosticMessage(final Builder builder) { this.messageType = builder.messageType; this.error = builder.error; this.description = builder.description; this.tags = builder.tags; } /** used to construct a diagnostic message with the standard Java builder pattern */ public static Builder builder(final DiagnosticMessageType messageType) { return new Builder(messageType); } /** the message type of the diagnostic message */ public DiagnosticMessageType getMessageType() { return messageType; } /** if an exception is part of the diagnostic message, the exception. Otherwise null */ public Throwable getError() { return error; } /** if the message has descriptive tags, the tags. Otherwise null */ public Map<String, String> getTags() { return tags; } /** if there is descriptive text, like a log message associated with the log message, the text. Otherwise null */ public String getDescription() { return description; } @Override public String toString() { return "DiagnosticMessage [messageType=" + messageType + ", error=" + error + ", tags=" + tags + ", description=" + description + "]"; } private final DiagnosticMessageType messageType; private final Throwable error; private final Map<String, String> tags; private final String description; }
8,213
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic
Create_ds/mantis/mantis-control-plane/mantis-control-plane-client/src/main/java/io/mantisrx/server/master/client/diagnostic/plugin/DiagnosticPlugin.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.server.master.client.diagnostic.plugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.observers.SerializedObserver; import rx.subjects.PublishSubject; /** mechanism for listening for diagnostic messages. You can record a message, and callers can subscribe to the observable to take action on the messages. * This is a simple singleton pattern class */ public class DiagnosticPlugin { private static final Logger logger = LoggerFactory.getLogger(DiagnosticPlugin.class); private final PublishSubject<DiagnosticMessage> messagePublisher = PublishSubject.create(); private final SerializedObserver<DiagnosticMessage> messagePublisherSerialized = new SerializedObserver<>(messagePublisher); private DiagnosticPlugin() { } /** * Record a message for diagnostic purposes. Serialized order is enforced. * @param message the message to record */ public void record(final DiagnosticMessage message) { if (message != null) { messagePublisherSerialized.onNext(message); } else { logger.error("RECORDING_NULL_MESSAGE_PROHBIITED"); } } /** * Return an observable that calling program can process using standard rx idioms. * @param maxBackPressureBuffer - maximum number of messages to permit before back pressure exceeeded. * @return an observable for processing */ public Observable<DiagnosticMessage> getDiagnosticObservable(final int maxBackPressureBuffer) { return messagePublisher.onBackpressureBuffer(maxBackPressureBuffer); } /** the singleton instance of the diagnostic plugin */ public static final DiagnosticPlugin INSTANCE = new DiagnosticPlugin(); }
8,214
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/WorkerHostTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.shaded.com.google.common.collect.ImmutableList; import org.junit.Test; public class WorkerHostTest { @Test public void testEquals() { WorkerHost w1 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w2 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w3 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7005); assertTrue(w1.equals(w2)); assertFalse(w1.equals(w3)); } }
8,215
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/TimeBufferedWorkerOutlierTest.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.server.core; import static org.junit.Assert.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Test; public class TimeBufferedWorkerOutlierTest { @Test public void testOutlier() throws Exception { long bufferSec = 1; CountDownLatch latch = new CountDownLatch(1); TimeBufferedWorkerOutlier outlier = new TimeBufferedWorkerOutlier(600, bufferSec, index -> { if (index == 0) { latch.countDown(); } }); for (int i = 0; i < 16; i++) { // Add multiple data points within the buffer period. for (int j = 0; j < 3; j++) { outlier.addDataPoint(0, 5, 2); outlier.addDataPoint(1, 5, 2); } assertFalse(latch.await(bufferSec * 1500, TimeUnit.MILLISECONDS)); } outlier.addDataPoint(0, 15, 2); assertFalse(latch.await(bufferSec * 1500, TimeUnit.MILLISECONDS)); // Additional data points with higher value. Need to have > 70% of 20 outliers to trigger. for (int i = 0; i < 14; i++) { for (int j = 0; j < 3; j++) { outlier.addDataPoint(0, 6, 2); } assertFalse(latch.await(bufferSec * 1500, TimeUnit.MILLISECONDS)); } outlier.addDataPoint(0, 18, 2); assertFalse(latch.await(bufferSec * 1500, TimeUnit.MILLISECONDS)); outlier.addDataPoint(0, 18, 2); assertTrue(latch.await(bufferSec * 1500, TimeUnit.MILLISECONDS)); } }
8,216
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/WorkerOutlierTest.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.server.core; import static org.junit.Assert.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Test; public class WorkerOutlierTest { @Test public void testOutlier() throws Exception { CountDownLatch latch = new CountDownLatch(1); WorkerOutlier outlier = new WorkerOutlier(600, index -> { if (index == 0) { latch.countDown(); } }); for (int i = 0; i < 16; i++) { outlier.addDataPoint(0, 5, 2); outlier.addDataPoint(1, 5, 2); assertEquals(1, latch.getCount()); } outlier.addDataPoint(0, 5, 2); assertFalse(latch.await(1, TimeUnit.SECONDS)); // Additional data points with higher value. Need to have > 70% of 20 outliers to trigger. for (int i = 0; i < 14; i++) { outlier.addDataPoint(0, 6, 2); assertEquals(1, latch.getCount()); } outlier.addDataPoint(0, 6, 2); assertTrue(latch.await(1, TimeUnit.SECONDS)); } @Test public void testOutlierMultipleWorkers() throws Exception { CountDownLatch latch = new CountDownLatch(1); WorkerOutlier outlier = new WorkerOutlier(600, index -> { if (index == 0) { latch.countDown(); } }); for (int i = 0; i < 16; i++) { outlier.addDataPoint(0, 6, 4); outlier.addDataPoint(1, 6, 4); outlier.addDataPoint(2, 5, 4); outlier.addDataPoint(3, 5, 4); assertEquals(1, latch.getCount()); } outlier.addDataPoint(0, 6, 4); assertFalse(latch.await(1, TimeUnit.SECONDS)); // Additional data points with higher value. Need to have > 70% of 20 outliers to trigger. for (int i = 0; i < 14; i++) { outlier.addDataPoint(0, 8, 4); assertEquals(1, latch.getCount()); } outlier.addDataPoint(0, 8, 4); assertTrue(latch.await(1, TimeUnit.SECONDS)); } }
8,217
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/WorkerAssignmentsTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.shaded.com.google.common.collect.ImmutableList; import io.mantisrx.shaded.com.google.common.collect.ImmutableMap; import org.junit.Test; public class WorkerAssignmentsTest { @Test public void testEquals() { WorkerHost w1 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w2 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w3 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7005); WorkerAssignments a1 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w1)); WorkerAssignments a2 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w2)); WorkerAssignments a3 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w3)); assertTrue(a1.equals(a2)); assertFalse(a1.equals(a3)); } }
8,218
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/ExecuteStageRequestTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.mantisrx.common.JsonSerializer; import io.mantisrx.common.WorkerPorts; import io.mantisrx.runtime.MachineDefinition; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.shaded.com.google.common.collect.ImmutableList; import io.mantisrx.shaded.com.google.common.collect.Lists; import java.net.URL; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Before; import org.junit.Test; public class ExecuteStageRequestTest { private ExecuteStageRequest example1; private ExecuteStageRequest example2; private final JsonSerializer serializer = new JsonSerializer(); @Before public void setup() throws Exception { example1 = new ExecuteStageRequest("jobName", "jobId-0", 0, 1, new URL("http://datamesh/whatever"), 1, 1, ImmutableList.of(1, 2, 3, 4, 5), 100L, 1, ImmutableList.of(new Parameter("name", "value")), new SchedulingInfo.Builder().numberOfStages(1) .singleWorkerStageWithConstraints(new MachineDefinition(1, 10, 10, 10, 2), Lists.newArrayList(), Lists.newArrayList()).build(), MantisJobDurationType.Perpetual, 0, 1000L, 1L, new WorkerPorts(2, 3, 4, 5, 6), java.util.Optional.of("className"), "user1"); example2 = new ExecuteStageRequest("jobName", "jobId-0", 0, 1, new URL("http://datamesh/whatever"), 1, 1, ImmutableList.of(1, 2, 3, 4, 5), 100L, 1, ImmutableList.of(new Parameter("name", "value")), new SchedulingInfo.Builder().numberOfStages(1) .singleWorkerStageWithConstraints(new MachineDefinition(1, 10, 10, 10, 2), Lists.newArrayList(), Lists.newArrayList()).build(), MantisJobDurationType.Perpetual, 0, 1000L, 1L, new WorkerPorts(2, 3, 4, 5, 6), java.util.Optional.empty(), "user1"); } @Test public void testSerialization() throws Exception { byte[] serializedBytes = SerializationUtils.serialize(example1); assertTrue(serializedBytes.length > 0); } @Test public void testIfExecuteStageRequestIsSerializableAndDeserializableFromJackson() throws Exception { String json = serializer.toJson(example1); assertEquals(StringUtils.deleteWhitespace("{\n" + " \"jobName\": \"jobName\",\n" + " \"workerIndex\": 0,\n" + " \"workerNumber\": 1,\n" + " \"jobJarUrl\": \"http://datamesh/whatever\",\n" + " \"stage\": 1,\n" + " \"totalNumStages\": 1,\n" + " \"ports\":\n" + " [\n" + " 1,\n" + " 2,\n" + " 3,\n" + " 4,\n" + " 5\n" + " ],\n" + " \"timeoutToReportStart\": 100,\n" + " \"metricsPort\": 1,\n" + " \"parameters\":\n" + " [\n" + " {\n" + " \"name\": \"name\",\n" + " \"value\": \"value\"\n" + " }\n" + " ],\n" + " \"schedulingInfo\":\n" + " {\n" + " \"stages\":\n" + " {\n" + " \"1\":\n" + " {\n" + " \"numberOfInstances\": 1,\n" + " \"machineDefinition\":\n" + " {\n" + " \"cpuCores\": 1.0,\n" + " \"memoryMB\": 10.0,\n" + " \"networkMbps\": 10.0,\n" + " \"diskMB\": 10.0,\n" + " \"numPorts\": 2\n" + " },\n" + " \"hardConstraints\":\n" + " [],\n" + " \"softConstraints\":\n" + " [],\n" + " \"scalingPolicy\": null,\n" + " \"scalable\": false\n" + " }\n" + " }\n" + " },\n" + " \"durationType\": \"Perpetual\",\n" + " \"heartbeatIntervalSecs\": 20,\n" + " \"subscriptionTimeoutSecs\": 1000,\n" + " \"minRuntimeSecs\": 1,\n" + " \"workerPorts\":\n" + " {\n" + " \"metricsPort\": 2,\n" + " \"debugPort\": 3,\n" + " \"consolePort\": 4,\n" + " \"customPort\": 5,\n" + " \"ports\":\n" + " [\n" + " 6\n" + " ],\n" + " \"sinkPort\": 6\n" + " },\n" + " \"nameOfJobProviderClass\": \"className\",\n" + " \"user\": \"user1\",\n" + " \"hasJobMaster\": false,\n" + " \"jobId\": \"jobId-0\",\n" + " \"workerId\":\n" + " {\n" + " \"jobCluster\": \"jobId\",\n" + " \"jobId\": \"jobId-0\",\n" + " \"workerIndex\": 0,\n" + " \"workerNum\": 1\n" + " }\n" + "}"), json); ExecuteStageRequest deserialized = serializer.fromJSON(json, ExecuteStageRequest.class); assertEquals(example1, deserialized); } @Test public void testIfExecuteStageRequestIsSerializableAndDeserializableFromJacksonWhenJobProviderClassIsEmpty() throws Exception { String json = serializer.toJson(example2); assertEquals(StringUtils.deleteWhitespace("{\n" + " \"jobName\": \"jobName\",\n" + " \"workerIndex\": 0,\n" + " \"workerNumber\": 1,\n" + " \"jobJarUrl\": \"http://datamesh/whatever\",\n" + " \"stage\": 1,\n" + " \"totalNumStages\": 1,\n" + " \"ports\":\n" + " [\n" + " 1,\n" + " 2,\n" + " 3,\n" + " 4,\n" + " 5\n" + " ],\n" + " \"timeoutToReportStart\": 100,\n" + " \"metricsPort\": 1,\n" + " \"parameters\":\n" + " [\n" + " {\n" + " \"name\": \"name\",\n" + " \"value\": \"value\"\n" + " }\n" + " ],\n" + " \"schedulingInfo\":\n" + " {\n" + " \"stages\":\n" + " {\n" + " \"1\":\n" + " {\n" + " \"numberOfInstances\": 1,\n" + " \"machineDefinition\":\n" + " {\n" + " \"cpuCores\": 1.0,\n" + " \"memoryMB\": 10.0,\n" + " \"networkMbps\": 10.0,\n" + " \"diskMB\": 10.0,\n" + " \"numPorts\": 2\n" + " },\n" + " \"hardConstraints\":\n" + " [],\n" + " \"softConstraints\":\n" + " [],\n" + " \"scalingPolicy\": null,\n" + " \"scalable\": false\n" + " }\n" + " }\n" + " },\n" + " \"durationType\": \"Perpetual\",\n" + " \"heartbeatIntervalSecs\": 20,\n" + " \"subscriptionTimeoutSecs\": 1000,\n" + " \"minRuntimeSecs\": 1,\n" + " \"workerPorts\":\n" + " {\n" + " \"metricsPort\": 2,\n" + " \"debugPort\": 3,\n" + " \"consolePort\": 4,\n" + " \"customPort\": 5,\n" + " \"ports\":\n" + " [\n" + " 6\n" + " ],\n" + " \"sinkPort\": 6\n" + " },\n" + " \"nameOfJobProviderClass\": null,\n" + " \"user\": \"user1\",\n" + " \"hasJobMaster\": false,\n" + " \"jobId\": \"jobId-0\",\n" + " \"workerId\":\n" + " {\n" + " \"jobCluster\": \"jobId\",\n" + " \"jobId\": \"jobId-0\",\n" + " \"workerIndex\": 0,\n" + " \"workerNum\": 1\n" + " }\n" + "}"), json); ExecuteStageRequest deserialized = serializer.fromJSON(json, ExecuteStageRequest.class); assertEquals(example2, deserialized); } }
8,219
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/JobSchedulingInfoTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.shaded.com.google.common.collect.ImmutableList; import io.mantisrx.shaded.com.google.common.collect.ImmutableMap; import org.junit.Test; public class JobSchedulingInfoTest { @Test public void testEquals() { WorkerHost w1 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w2 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7004); WorkerHost w3 = new WorkerHost("localhost", 1, ImmutableList.of(7001, 7002), MantisJobState.Accepted, 2, 7003, 7005); WorkerAssignments a1 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w1)); WorkerAssignments a2 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w2)); WorkerAssignments a3 = new WorkerAssignments(1, 1, ImmutableMap.of(0, w3)); JobSchedulingInfo s1 = new JobSchedulingInfo("job-1", ImmutableMap.of(1, a1)); JobSchedulingInfo s2 = new JobSchedulingInfo("job-1", ImmutableMap.of(1, a2)); JobSchedulingInfo s3 = new JobSchedulingInfo("job-1", ImmutableMap.of(1, a3)); assertTrue(s1.equals(s2)); assertFalse(s1.equals(s3)); } }
8,220
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/domain/WorkerIdTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.domain; import static org.junit.Assert.assertEquals; import io.mantisrx.common.JsonSerializer; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; public class WorkerIdTest { private final JsonSerializer serializer = new JsonSerializer(); @Test public void testSerializationAndDeserialization() throws Exception { WorkerId workerId = WorkerId.fromId("late-sine-function-tutorial-1-worker-0-1").get(); String s = serializer.toJson(workerId); assertEquals(s, "{\"jobCluster\":\"late-sine-function-tutorial\",\"jobId\":\"late-sine-function-tutorial-1\",\"workerIndex\":0,\"workerNum\":1}"); WorkerId actual = serializer.fromJSON(s, WorkerId.class); assertEquals(workerId, actual); } @Test public void testIfWorkerIdIsSerializableUsingJava() throws Exception { WorkerId workerId = WorkerId.fromId("late-sine-function-tutorial-1-worker-0-1").get(); byte[] serialized = SerializationUtils.serialize(workerId); assertEquals(workerId, SerializationUtils.deserialize(serialized)); } }
8,221
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/core/domain/JobMetadataTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.core.domain; import static org.junit.Assert.assertEquals; import io.mantisrx.runtime.MachineDefinition; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.shaded.com.google.common.collect.Lists; import java.net.URL; import org.junit.Test; public class JobMetadataTest { @Test public void testGetJobArtifact() throws Exception { MachineDefinition machineDefinition = new MachineDefinition(1.0, 1.0, 1.0, 1.0, 3); SchedulingInfo schedulingInfo = new SchedulingInfo.Builder() .numberOfStages(1) .singleWorkerStageWithConstraints(machineDefinition, Lists.newArrayList(), Lists.newArrayList()).build(); JobMetadata jobMetadata = new JobMetadata( "testId", new URL("http://artifact.zip"),1,"testUser",schedulingInfo, Lists.newArrayList(),0,10, 0); assertEquals(jobMetadata.getJobArtifact(), ArtifactID.of("artifact.zip")); } }
8,222
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/master/resourcecluster/TaskExecutorRegistrationTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.mantisrx.common.JsonSerializer; import io.mantisrx.shaded.com.google.common.collect.ImmutableMap; import org.junit.Test; public class TaskExecutorRegistrationTest { private final JsonSerializer serializer = new JsonSerializer(); @Test public void testTaskExecutorRegistrationDeserialization() throws Exception { String str = "{\n" + " \"taskExecutorID\":\n" + " {\n" + " \"resourceId\": \"25400d92-96ed-40b9-9843-a6e7e248db52\"\n" + " },\n" + " \"clusterID\":\n" + " {\n" + " \"resourceID\": \"mantistaskexecutor\"\n" + " },\n" + " \"taskExecutorAddress\": \"akka.tcp://flink@100.118.114.30:5050/user/rpc/worker_0\",\n" + " \"hostname\": \"localhost\",\n" + " \"workerPorts\":\n" + " {\n" + " \"metricsPort\": 5051,\n" + " \"debugPort\": 5052,\n" + " \"consolePort\": 5053,\n" + " \"customPort\": 5054,\n" + " \"ports\":\n" + " [\n" + " 5055,\n" + " 5051,\n" + " 5052,\n" + " 5053,\n" + " 5054\n" + " ],\n" + " \"sinkPort\": 5055,\n" + " \"numberOfPorts\": 5,\n" + " \"valid\": true\n" + " },\n" + " \"machineDefinition\":\n" + " {\n" + " \"cpuCores\": 4.0,\n" + " \"memoryMB\": 17179869184,\n" + " \"networkMbps\": 128.0,\n" + " \"diskMB\": 88969576448,\n" + " \"numPorts\": 5\n" + " }\n" + "}"; final TaskExecutorRegistration registration = serializer.fromJSON(str, TaskExecutorRegistration.class); assertEquals(ImmutableMap.of(), registration.getTaskExecutorAttributes()); final TaskExecutorRegistration deserialized = serializer.fromJSON(serializer.toJson(registration), TaskExecutorRegistration.class); assertEquals(registration, deserialized); } @Test public void testDeserializationForV2() throws Exception { String str = "{\n" + " \"taskExecutorID\":\n" + " {\n" + " \"resourceId\": \"25400d92-96ed-40b9-9843-a6e7e248db52\"\n" + " },\n" + " \"clusterID\":\n" + " {\n" + " \"resourceID\": \"mantistaskexecutor\"\n" + " },\n" + " \"taskExecutorAddress\": \"akka.tcp://flink@100.118.114.30:5050/user/rpc/worker_0\",\n" + " \"hostname\": \"localhost\",\n" + " \"workerPorts\":\n" + " {\n" + " \"metricsPort\": 5051,\n" + " \"debugPort\": 5052,\n" + " \"consolePort\": 5053,\n" + " \"customPort\": 5054,\n" + " \"ports\":\n" + " [\n" + " 5055,\n" + " 5051,\n" + " 5052,\n" + " 5053,\n" + " 5054\n" + " ],\n" + " \"sinkPort\": 5055,\n" + " \"numberOfPorts\": 5,\n" + " \"valid\": true\n" + " },\n" + " \"machineDefinition\":\n" + " {\n" + " \"cpuCores\": 4.0,\n" + " \"memoryMB\": 17179869184,\n" + " \"networkMbps\": 128.0,\n" + " \"diskMB\": 88969576448,\n" + " \"numPorts\": 5\n" + " },\n" + " \"taskExecutorAttributes\": {\n" + " \t\"attribute1\": \"attributeValue1\",\n" + " \t\"attribute2\": \"AttributeValue2\",\n" + " \t\"attribute3\": \"attributeValue3\"\n" + " }\n" + "}"; final TaskExecutorRegistration registration = serializer.fromJSON(str, TaskExecutorRegistration.class); assertEquals(ImmutableMap.of("attribute1", "attributeValue1", "attribute2", "AttributeValue2", "attribute3", "attributeValue3"), registration.getTaskExecutorAttributes()); final TaskExecutorRegistration deserialized = serializer.fromJSON(serializer.toJson(registration), TaskExecutorRegistration.class); assertEquals(registration, deserialized); assertTrue(registration.containsAttributes(ImmutableMap.of("ATTribute2", "AttributevAlue2"))); assertTrue(registration.containsAttributes(ImmutableMap.of( "ATTribute2", "AttributevAlue2", "attribute1", "attributevalue1"))); } @Test public void testSerialization() throws Exception { String expected = "{\n" + " \"taskExecutorID\":\n" + " {\n" + " \"resourceId\": \"25400d92-96ed-40b9-9843-a6e7e248db52\"\n" + " },\n" + " \"clusterID\":\n" + " {\n" + " \"resourceID\": \"mantistaskexecutor\"\n" + " },\n" + " \"taskExecutorAddress\": \"akka.tcp://flink@100.118.114.30:5050/user/rpc/worker_0\",\n" + " \"hostname\": \"localhost\",\n" + " \"workerPorts\":\n" + " {\n" + " \"metricsPort\": 5051,\n" + " \"debugPort\": 5052,\n" + " \"consolePort\": 5053,\n" + " \"customPort\": 5054,\n" + " \"ports\":\n" + " [\n" + " 5055" + " ],\n" + " \"sinkPort\": 5055\n" + " },\n" + " \"machineDefinition\":\n" + " {\n" + " \"cpuCores\": 4.0,\n" + " \"memoryMB\": 1.7179869184E10,\n" + " \"networkMbps\": 128.0,\n" + " \"diskMB\": 8.8969576448E10,\n" + " \"numPorts\": 5\n" + " },\n" + " \"taskExecutorAttributes\":\n" + " {}\n" + "}"; final TaskExecutorRegistration registration = serializer.fromJSON(expected, TaskExecutorRegistration.class); assertEquals(expected.replaceAll("[\\n\\s]+", ""), serializer.toJson(registration)); } }
8,223
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/test/java/io/mantisrx/server/master/resourcecluster/TaskExecutorHeartbeatTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import static org.junit.Assert.assertEquals; import io.mantisrx.common.JsonSerializer; import org.junit.Test; public class TaskExecutorHeartbeatTest { private final JsonSerializer serializer = new JsonSerializer(); @Test public void testHeartbeat() throws Exception { TaskExecutorHeartbeat heartbeat = new TaskExecutorHeartbeat( TaskExecutorID.generate(), ClusterID.of("cluster"), TaskExecutorReport.available()); String encoded = serializer.toJson(heartbeat); assertEquals(serializer.fromJSON(encoded, TaskExecutorHeartbeat.class), heartbeat); } }
8,224
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/testFixtures/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/testFixtures/java/io/mantisrx/server/core/TestingRpcService.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import static org.apache.flink.util.Preconditions.checkNotNull; import java.io.Serializable; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.apache.flink.configuration.Configuration; import org.apache.flink.runtime.rpc.FencedRpcGateway; import org.apache.flink.runtime.rpc.RpcEndpoint; import org.apache.flink.runtime.rpc.RpcGateway; import org.apache.flink.runtime.rpc.RpcServer; import org.apache.flink.runtime.rpc.RpcService; import org.apache.flink.runtime.rpc.RpcSystem; import org.apache.flink.runtime.rpc.akka.AkkaRpcSystem; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.util.concurrent.ScheduledExecutor; /** * Copied from <a href="https://github.com/apache/flink/blob/master/flink-runtime/src/test/java/org/apache/flink/runtime/rpc/TestingRpcService.java">flink</a>. * * An RPC Service implementation for testing. This RPC service acts as a replacement for the regular * RPC service for cases where tests need to return prepared mock gateways instead of proper RPC * gateways. * * <p>The TestingRpcService can be used for example in the following fashion, using <i>Mockito</i> * for mocks and verification: * * <pre>{@code * TestingRpcService rpc = new TestingRpcService(); * * ResourceManagerGateway testGateway = mock(ResourceManagerGateway.class); * rpc.registerGateway("myAddress", testGateway); * * MyComponentToTest component = new MyComponentToTest(); * component.triggerSomethingThatCallsTheGateway(); * * verify(testGateway, timeout(1000)).theTestMethod(any(UUID.class), anyString()); * }</pre> */ public class TestingRpcService implements RpcService { // load RpcSystem once to save initialization costs // this is safe because it is state-less private static final RpcSystem RPC_SYSTEM_SINGLETON = new AkkaRpcSystem(); private static final Function<RpcGateway, CompletableFuture<RpcGateway>> DEFAULT_RPC_GATEWAY_FUTURE_FUNCTION = CompletableFuture::completedFuture; /** * Map of pre-registered connections. */ private final ConcurrentHashMap<String, RpcGateway> registeredConnections; private volatile Function<RpcGateway, CompletableFuture<RpcGateway>> rpcGatewayFutureFunction = DEFAULT_RPC_GATEWAY_FUTURE_FUNCTION; private final RpcService backingRpcService; /** * Creates a new {@code TestingRpcService}, using the given configuration. */ public TestingRpcService() { try { this.backingRpcService = RPC_SYSTEM_SINGLETON.localServiceBuilder(new Configuration()).createAndStart(); } catch (Exception e) { throw new RuntimeException(e); } this.registeredConnections = new ConcurrentHashMap<>(); } // ------------------------------------------------------------------------ @Override public CompletableFuture<Void> stopService() { final CompletableFuture<Void> terminationFuture = backingRpcService.stopService(); terminationFuture.whenComplete( (Void ignored, Throwable throwable) -> { registeredConnections.clear(); }); return terminationFuture; } // ------------------------------------------------------------------------ // connections // ------------------------------------------------------------------------ public void registerGateway(String address, RpcGateway gateway) { checkNotNull(address); checkNotNull(gateway); if (registeredConnections.putIfAbsent(address, gateway) != null) { throw new IllegalStateException("a gateway is already registered under " + address); } } public void unregisterGateway(String address) { checkNotNull(address); if (registeredConnections.remove(address) == null) { throw new IllegalStateException("no gateway is registered under " + address); } } @SuppressWarnings("unchecked") private <C extends RpcGateway> CompletableFuture<C> getRpcGatewayFuture(C gateway) { return (CompletableFuture<C>) rpcGatewayFutureFunction.apply(gateway); } @Override public <C extends RpcGateway> CompletableFuture<C> connect(String address, Class<C> clazz) { RpcGateway gateway = registeredConnections.get(address); if (gateway != null) { if (clazz.isAssignableFrom(gateway.getClass())) { @SuppressWarnings("unchecked") C typedGateway = (C) gateway; return getRpcGatewayFuture(typedGateway); } else { return FutureUtils.completedExceptionally( new Exception( "Gateway registered under " + address + " is not of type " + clazz)); } } else { return backingRpcService.connect(address, clazz); } } @Override public <F extends Serializable, C extends FencedRpcGateway<F>> CompletableFuture<C> connect( String address, F fencingToken, Class<C> clazz) { RpcGateway gateway = registeredConnections.get(address); if (gateway != null) { if (clazz.isAssignableFrom(gateway.getClass())) { @SuppressWarnings("unchecked") C typedGateway = (C) gateway; return getRpcGatewayFuture(typedGateway); } else { return FutureUtils.completedExceptionally( new Exception( "Gateway registered under " + address + " is not of type " + clazz)); } } else { return backingRpcService.connect(address, fencingToken, clazz); } } public void clearGateways() { registeredConnections.clear(); } public void resetRpcGatewayFutureFunction() { rpcGatewayFutureFunction = DEFAULT_RPC_GATEWAY_FUTURE_FUNCTION; } public void setRpcGatewayFutureFunction( Function<RpcGateway, CompletableFuture<RpcGateway>> rpcGatewayFutureFunction) { this.rpcGatewayFutureFunction = rpcGatewayFutureFunction; } // ------------------------------------------------------------------------ // simple wrappers // ------------------------------------------------------------------------ @Override public String getAddress() { return backingRpcService.getAddress(); } @Override public int getPort() { return backingRpcService.getPort(); } @Override public <C extends RpcEndpoint & RpcGateway> RpcServer startServer(C rpcEndpoint) { return backingRpcService.startServer(rpcEndpoint); } @Override public <F extends Serializable> RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken) { return backingRpcService.fenceRpcServer(rpcServer, fencingToken); } @Override public void stopServer(RpcServer selfGateway) { backingRpcService.stopServer(selfGateway); } @Override public CompletableFuture<Void> getTerminationFuture() { return backingRpcService.getTerminationFuture(); } @Override public ScheduledExecutor getScheduledExecutor() { return backingRpcService.getScheduledExecutor(); } @Override public ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit) { return backingRpcService.scheduleRunnable(runnable, delay, unit); } @Override public void execute(Runnable runnable) { backingRpcService.execute(runnable); } @Override public <T> CompletableFuture<T> execute(Callable<T> callable) { return backingRpcService.execute(callable); } }
8,225
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/Configurations.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.Properties; import org.skife.config.ConfigurationObjectFactory; public class Configurations { public static <T> T frmProperties(Properties properties, Class<T> tClass) { ConfigurationObjectFactory configurationObjectFactory = new ConfigurationObjectFactory( properties); configurationObjectFactory.addCoercible(new MetricsCoercer(properties)); return configurationObjectFactory.build(tClass); } }
8,226
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/NamedJobInfo.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.server.core; import io.mantisrx.runtime.codec.JsonType; 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 NamedJobInfo implements JsonType { private final String name; private final String jobId; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public NamedJobInfo(@JsonProperty("name") String name, @JsonProperty("jobId") String jobId) { this.name = name; this.jobId = jobId; } public String getName() { return name; } public String getJobId() { return jobId; } }
8,227
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/JobCompletedReason.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.server.core; /** * Enum for the various types of Job Completions. */ public enum JobCompletedReason { /** * Job completed normally due to SLA enforcement or runtime limit. */ Normal, /** * Job completed due to an abnormal condition. */ Error, /** * Does not apply to Jobs. */ Lost, /** * Job was explicitly killed. */ Killed, /** * Unused. */ Relaunched }
8,228
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/Status.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.server.core; import io.mantisrx.common.JsonSerializer; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.server.core.domain.WorkerId; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import java.util.Optional; import lombok.extern.slf4j.Slf4j; @Slf4j public class Status { @JsonIgnore private static final JsonSerializer jsonSerializer = new JsonSerializer(); @JsonIgnore private final Optional<WorkerId> workerId; private final String jobId; private int stageNum; private int workerIndex; private final int workerNumber; private String hostname = null; private final TYPE type; private final String message; private final long timestamp; private final MantisJobState state; private JobCompletedReason reason = JobCompletedReason.Normal; private List<Payload> payloads; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Status(@JsonProperty("jobId") String jobId, @JsonProperty("stageNum") int stageNum, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("type") TYPE type, @JsonProperty("message") String message, @JsonProperty("state") MantisJobState state) { this(jobId, stageNum, workerIndex, workerNumber, type, message, state, System.currentTimeMillis()); } public Status(String jobId, int stageNum, int workerIndex, int workerNumber, TYPE type, String message, MantisJobState state, long ts) { this.jobId = jobId; this.stageNum = stageNum; this.workerIndex = workerIndex; this.workerNumber = workerNumber; if (workerIndex >= 0 && workerNumber >= 0) { this.workerId = Optional.of(new WorkerId(jobId, workerIndex, workerNumber)); } else { this.workerId = Optional.empty(); } this.type = type; this.message = message; this.state = state; timestamp = ts; this.payloads = new ArrayList<>(); } public String getJobId() { return jobId; } public int getStageNum() { return stageNum; } public void setStageNum(int stageNum) { this.stageNum = stageNum; } public int getWorkerIndex() { return workerIndex; } public void setWorkerIndex(int workerIndex) { this.workerIndex = workerIndex; } public int getWorkerNumber() { return workerNumber; } public Optional<WorkerId> getWorkerId() { return workerId; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public TYPE getType() { return type; } public String getMessage() { return message; } public MantisJobState getState() { return state; } public JobCompletedReason getReason() { return reason; } public void setReason(JobCompletedReason reason) { this.reason = reason; } public List<Payload> getPayloads() { return payloads; } public void setPayloads(List<Payload> payloads) { this.payloads = payloads; } public long getTimestamp() { return timestamp; } @Override public String toString() { try { return jsonSerializer.toJson(this); } catch (Exception e) { log.error("Failed to serialize status", e); return "Error getting string for status on job " + jobId; } } public enum TYPE { ERROR, WARN, INFO, DEBUG, HEARTBEAT } public static class Payload { private final String type; private final String data; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Payload(@JsonProperty("type") String type, @JsonProperty("data") String data) { this.type = type; this.data = data; } public String getType() { return type; } public String getData() { return data; } } }
8,229
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/ExecuteStageRequest.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.server.core; import io.mantisrx.common.WorkerPorts; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import io.mantisrx.server.core.domain.WorkerId; 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.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; /** * ExecuteStageRequest represents the data structure that defines the StageTask workload a given worker needs to run. * The data structure is sent over the wire using java serialization when the server requests a given task executor to * perform a certain stage task. */ @Slf4j @Getter @ToString @EqualsAndHashCode public class ExecuteStageRequest implements Serializable { //todo: refactor into ConfigurationProvider or something equivalent and drive from there! public static final long DEFAULT_HEARTBEAT_INTERVAL_SECS = 20; private static final long serialVersionUID = 1L; // indicates whether this is stage 0 or not. stage 0 runs the autoscaler for the mantis job. private final boolean hasJobMaster; // interval in seconds between worker heartbeats private final long heartbeatIntervalSecs; // subscription threshold for when a sink should be considered inactive so that ephemeral jobs producing the sink // can be shutdown. private final long subscriptionTimeoutSecs; private final long minRuntimeSecs; private final WorkerPorts workerPorts; private final String jobName; // jobId represents the instance of the job. private final String jobId; // index of the worker in that stage private final int workerIndex; // rolling counter of workers for that stage private final int workerNumber; private final URL jobJarUrl; // index of the stage private final int stage; private final int totalNumStages; private final int metricsPort; private final List<Integer> ports = new ArrayList<>(); private final long timeoutToReportStart; private final List<Parameter> parameters; private final SchedulingInfo schedulingInfo; private final MantisJobDurationType durationType; // class name that provides the job provider. @Nullable private final String nameOfJobProviderClass; private final String user; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public ExecuteStageRequest( @JsonProperty("jobName") String jobName, @JsonProperty("jobID") String jobId, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("jobJarUrl") URL jobJarUrl, @JsonProperty("stage") int stage, @JsonProperty("totalNumStages") int totalNumStages, @JsonProperty("ports") List<Integer> ports, @JsonProperty("timeoutToReportStart") long timeoutToReportStart, @JsonProperty("metricsPort") int metricsPort, @JsonProperty("parameters") List<Parameter> parameters, @JsonProperty("schedulingInfo") SchedulingInfo schedulingInfo, @JsonProperty("durationType") MantisJobDurationType durationType, @JsonProperty("heartbeatIntervalSecs") long heartbeatIntervalSecs, @JsonProperty("subscriptionTimeoutSecs") long subscriptionTimeoutSecs, @JsonProperty("minRuntimeSecs") long minRuntimeSecs, @JsonProperty("workerPorts") WorkerPorts workerPorts, @JsonProperty("nameOfJobProviderClass") Optional<String> nameOfJobProviderClass, @JsonProperty("user") String user) { this.jobName = jobName; this.jobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.jobJarUrl = jobJarUrl; this.stage = stage; this.totalNumStages = totalNumStages; this.nameOfJobProviderClass = nameOfJobProviderClass.orElse(null); this.user = user; this.ports.addAll(ports); this.metricsPort = metricsPort; this.timeoutToReportStart = timeoutToReportStart; if (parameters != null) { this.parameters = parameters; } else { this.parameters = new LinkedList<>(); } this.schedulingInfo = schedulingInfo; this.durationType = durationType; this.heartbeatIntervalSecs = (heartbeatIntervalSecs > 0) ? heartbeatIntervalSecs : DEFAULT_HEARTBEAT_INTERVAL_SECS; log.info("heartbeat interval {}, using {}", heartbeatIntervalSecs, this.heartbeatIntervalSecs); this.hasJobMaster = schedulingInfo != null && schedulingInfo.forStage(0) != null; this.subscriptionTimeoutSecs = subscriptionTimeoutSecs; this.minRuntimeSecs = minRuntimeSecs; this.workerPorts = workerPorts; } public boolean getHasJobMaster() { return hasJobMaster; } public java.util.Optional<String> getNameOfJobProviderClass() { return java.util.Optional.ofNullable(nameOfJobProviderClass); } public WorkerId getWorkerId() { return new WorkerId(jobId, workerIndex, workerNumber); } }
8,230
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/WorkerHost.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.server.core; import io.mantisrx.runtime.MantisJobState; 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.List; import lombok.EqualsAndHashCode; @EqualsAndHashCode public class WorkerHost { private final MantisJobState state; private final int workerNumber; private final int workerIndex; private final String host; private final List<Integer> port; private final int metricsPort; private final int customPort; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public WorkerHost(@JsonProperty("host") String host, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("port") List<Integer> port, @JsonProperty("state") MantisJobState state, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("metricsPort") int metricsPort, @JsonProperty("customPort") int customPort) { this.host = host; this.workerIndex = workerIndex; this.port = port; this.state = state; this.workerNumber = workerNumber; this.metricsPort = metricsPort; this.customPort = customPort; } public int getWorkerNumber() { return workerNumber; } public MantisJobState getState() { return state; } public String getHost() { return host; } public List<Integer> getPort() { return port; } public int getWorkerIndex() { return workerIndex; } public int getMetricsPort() { return metricsPort; } public int getCustomPort() { return customPort; } @Override public String toString() { return "WorkerHost [state=" + state + ", workerIndex=" + workerIndex + ", host=" + host + ", port=" + port + "]"; } }
8,231
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/CoreConfiguration.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.server.core; import io.mantisrx.common.metrics.MetricsPublisher; import org.skife.config.Config; import org.skife.config.Default; /** * The configurations declared in this interface should be the ones that are shared by both worker and master (and * potentially other sub-projects). */ public interface CoreConfiguration { @Config("mantis.zookeeper.connectionTimeMs") @Default("10000") int getZkConnectionTimeoutMs(); @Config("mantis.zookeeper.connection.retrySleepMs") @Default("500") int getZkConnectionRetrySleepMs(); @Config("mantis.zookeeper.connection.retryCount") @Default("5") int getZkConnectionMaxRetries(); @Config("mantis.zookeeper.connectString") @Default("localhost:2181") String getZkConnectionString(); @Config("mantis.zookeeper.leader.announcement.path") @Default("/leader") String getLeaderAnnouncementPath(); @Config("mantis.zookeeper.root") String getZkRoot(); @Config("mantis.localmode") @Default("true") boolean isLocalMode(); @Config("mantis.metricsPublisher.class") @Default("io.mantisrx.common.metrics.MetricsPublisherNoOp") MetricsPublisher getMetricsPublisher(); @Config("mantis.metricsPublisher.publishFrequencyInSeconds") @Default("15") int getMetricsPublisherFrequencyInSeconds(); @Config("mantis.asyncHttpClient.maxConnectionsPerHost") @Default("2") int getAsyncHttpClientMaxConnectionsPerHost(); @Config("mantis.asyncHttpClient.connectionTimeoutMs") @Default("10000") int getAsyncHttpClientConnectionTimeoutMs(); @Config("mantis.asyncHttpClient.requestTimeoutMs") @Default("10000") int getAsyncHttpClientRequestTimeoutMs(); @Config("mantis.asyncHttpClient.readTimeoutMs") @Default("10000") int getAsyncHttpClientReadTimeoutMs(); }
8,232
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/CleanupOnCloseRpcSystem.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.core; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.file.Path; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.classloading.ComponentClassLoader; import org.apache.flink.runtime.rpc.AddressResolution; import org.apache.flink.runtime.rpc.RpcSystem; import org.apache.flink.util.FileUtils; import org.apache.flink.util.Preconditions; /** An {@link RpcSystem} wrapper that cleans up resources after the RPC system has been closed. */ @Slf4j class CleanupOnCloseRpcSystem implements RpcSystem { private final RpcSystem rpcSystem; private final ComponentClassLoader pluginLoader; @Nullable private final Path tempDirectory; public CleanupOnCloseRpcSystem( RpcSystem rpcSystem, ComponentClassLoader pluginLoader, @Nullable Path tempDirectory) { this.rpcSystem = Preconditions.checkNotNull(rpcSystem); this.pluginLoader = Preconditions.checkNotNull(pluginLoader); this.tempDirectory = tempDirectory; } @Override public void close() { log.info("Closing MantisAkkaRpcSystemLoader."); rpcSystem.close(); try { pluginLoader.close(); } catch (Exception e) { log.warn("Could not close RpcSystem classloader.", e); } if (tempDirectory != null) { try { FileUtils.deleteFileOrDirectory(tempDirectory.toFile()); } catch (Exception e) { log.warn("Could not delete temporary rpc system file {}.", tempDirectory, e); } } } @Override public RpcServiceBuilder localServiceBuilder(Configuration config) { return rpcSystem.localServiceBuilder(config); } @Override public RpcServiceBuilder remoteServiceBuilder( Configuration configuration, @Nullable String externalAddress, String externalPortRange) { return rpcSystem.remoteServiceBuilder(configuration, externalAddress, externalPortRange); } @Override public String getRpcUrl( String hostname, int port, String endpointName, AddressResolution addressResolution, Configuration config) throws UnknownHostException { return rpcSystem.getRpcUrl(hostname, port, endpointName, addressResolution, config); } @Override public InetSocketAddress getInetSocketAddressFromRpcUrl(String url) throws Exception { return rpcSystem.getInetSocketAddressFromRpcUrl(url); } @Override public long getMaximumMessageSizeInBytes(Configuration config) { return rpcSystem.getMaximumMessageSizeInBytes(config); } }
8,233
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/WrappedExecuteStageRequest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import rx.subjects.PublishSubject; public class WrappedExecuteStageRequest { private PublishSubject<Boolean> requestSubject; private ExecuteStageRequest request; public WrappedExecuteStageRequest(PublishSubject<Boolean> subject, ExecuteStageRequest request) { this.requestSubject = subject; this.request = request; } public PublishSubject<Boolean> getRequestSubject() { return requestSubject; } public ExecuteStageRequest getRequest() { return request; } @Override public String toString() { return "WrappedExecuteStageRequest{" + "requestSubject=" + requestSubject + ", request=" + request + '}'; } }
8,234
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/PostJobStatusRequest.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.server.core; 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 PostJobStatusRequest { private String jobId; private Status status; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public PostJobStatusRequest(@JsonProperty("jobId") String jobId, @JsonProperty("status") Status status) { this.jobId = jobId; this.status = status; } public String getJobId() { return jobId; } public Status getStatus() { return status; } }
8,235
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/MantisAkkaRpcSystemLoader.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ServiceLoader; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.CoreOptions; import org.apache.flink.core.classloading.ComponentClassLoader; import org.apache.flink.runtime.rpc.RpcSystem; import org.apache.flink.runtime.rpc.RpcSystemLoader; import org.apache.flink.util.IOUtils; /** * RpcSystemLoader for mantis task executor and other services that need to expose an RPC API. * This particular implementation uses the akka RPC implementation under the hood. */ @Slf4j public class MantisAkkaRpcSystemLoader implements RpcSystemLoader { private static final RpcSystem INSTANCE = createRpcSystem(); public static RpcSystem getInstance() { return INSTANCE; } @Override public RpcSystem loadRpcSystem(Configuration config) { return INSTANCE; } private static RpcSystem createRpcSystem() { try { final ClassLoader flinkClassLoader = RpcSystem.class.getClassLoader(); final Path tmpDirectory = Paths.get(System.getProperty("java.io.tmpdir") + "/flink-rpc-akka-jar"); Files.createDirectories(tmpDirectory); try { // Best-effort cleanup directory in case some other jobs has failed abruptly FileUtils.cleanDirectory(tmpDirectory.toFile()); } catch (Exception e) { log.warn("Could not cleanup flink-rpc-akka jar directory {}.", tmpDirectory, e); } final Path tempFile = Files.createFile( tmpDirectory.resolve("flink-rpc-akka_" + UUID.randomUUID() + ".jar")); final InputStream resourceStream = flinkClassLoader.getResourceAsStream("flink-rpc-akka.jar"); if (resourceStream == null) { throw new RuntimeException( "Akka RPC system could not be found. If this happened while running a test in the IDE," + "run the process-resources phase on flink-rpc/flink-rpc-akka-loader via maven."); } IOUtils.copyBytes(resourceStream, Files.newOutputStream(tempFile)); // The following classloader loads all classes from the submodule jar, except for explicitly white-listed packages. // // <p>To ensure that classes from the submodule are always loaded through the submodule classloader // (and thus from the submodule jar), even if the classes are also on the classpath (e.g., during // tests), all classes from the "org.apache.flink" package are loaded child-first. // // <p>Classes related to mantis-specific or logging are loaded parent-first. // // <p>All other classes can only be loaded if they are either available in the submodule jar or the // bootstrap/app classloader (i.e., provided by the JDK). final ComponentClassLoader componentClassLoader = new ComponentClassLoader( new URL[] {tempFile.toUri().toURL()}, flinkClassLoader, // Dependencies which are needed by logic inside flink-rpc-akka (ie AkkaRpcService/System) which // are external to flink-rpc-akka itself (like ExecuteStageRequest in mantis-control-plane). CoreOptions.parseParentFirstLoaderPatterns( "org.slf4j;org.apache.log4j;org.apache.logging;org.apache.commons.logging;ch.qos.logback;io.mantisrx.server.worker;io.mantisrx.server.core;io.mantisrx", ""), new String[] {"org.apache.flink"}); return new CleanupOnCloseRpcSystem( ServiceLoader.load(RpcSystem.class, componentClassLoader).iterator().next(), componentClassLoader, tempFile); } catch (IOException e) { throw new RuntimeException("Could not initialize RPC system.", e); } } }
8,236
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/StatusPayloads.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.server.core; 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 StatusPayloads { public enum Type { SubscriptionState, IncomingDataDrop, ResourceUsage } public static class DataDropCounts { private final long onNextCount; private final long droppedCount; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public DataDropCounts(@JsonProperty("onNextCount") long onNextCount, @JsonProperty("droppedCount") long droppedCount) { this.onNextCount = onNextCount; this.droppedCount = droppedCount; } public long getOnNextCount() { return onNextCount; } public long getDroppedCount() { return droppedCount; } } public static class ResourceUsage { private final double cpuLimit; private final double cpuUsageCurrent; private final double cpuUsagePeak; private final double memLimit; private final double memCacheCurrent; private final double memCachePeak; private final double totMemUsageCurrent; private final double totMemUsagePeak; private final double nwBytesCurrent; private final double nwBytesPeak; @JsonCreator public ResourceUsage(@JsonProperty("cpuLimit") double cpuLimit, @JsonProperty("cpuUsageCurrent") double cpuUsageCurrent, @JsonProperty("cpuUsagePeak") double cpuUsagePeak, @JsonProperty("memLimit") double memLimit, @JsonProperty("memCacheCurrent") double memCacheCurrent, @JsonProperty("memCachePeak") double memCachePeak, @JsonProperty("totMemUsageCurrent") double totMemUsageCurrent, @JsonProperty("totMemUsagePeak") double totMemUsagePeak, @JsonProperty("nwBytesCurrent") double nwBytesCurrent, @JsonProperty("nwBytesPeak") double nwBytesPeak) { this.cpuLimit = cpuLimit; this.cpuUsageCurrent = cpuUsageCurrent; this.cpuUsagePeak = cpuUsagePeak; this.memLimit = memLimit; this.memCacheCurrent = memCacheCurrent; this.memCachePeak = memCachePeak; this.totMemUsageCurrent = totMemUsageCurrent; this.totMemUsagePeak = totMemUsagePeak; this.nwBytesCurrent = nwBytesCurrent; this.nwBytesPeak = nwBytesPeak; } public double getCpuLimit() { return cpuLimit; } public double getCpuUsageCurrent() { return cpuUsageCurrent; } public double getCpuUsagePeak() { return cpuUsagePeak; } public double getMemLimit() { return memLimit; } public double getMemCacheCurrent() { return memCacheCurrent; } public double getMemCachePeak() { return memCachePeak; } public double getTotMemUsageCurrent() { return totMemUsageCurrent; } public double getTotMemUsagePeak() { return totMemUsagePeak; } public double getNwBytesCurrent() { return nwBytesCurrent; } public double getNwBytesPeak() { return nwBytesPeak; } @Override public String toString() { return "cpuLimit=" + cpuLimit + ", cpuUsageCurrent=" + cpuUsageCurrent + ", cpuUsagePeak=" + cpuUsagePeak + ", memLimit=" + memLimit + ", memCacheCurrent=" + memCacheCurrent + ", memCachePeak=" + memCachePeak + ", totMemUsageCurrent=" + totMemUsageCurrent + ", totMemUsagePeak=" + totMemUsagePeak + ", nwBytesCurrent=" + nwBytesCurrent + ", nwBytesPeak=" + nwBytesPeak; } } }
8,237
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/JobSchedulingInfo.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.server.core; import io.mantisrx.runtime.codec.JsonType; 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; import lombok.EqualsAndHashCode; @EqualsAndHashCode public class JobSchedulingInfo implements JsonType { public static final String HB_JobId = "HB_JobId"; public static final String SendHBParam = "sendHB"; private String jobId; private Map<Integer, WorkerAssignments> workerAssignments; // index by stage num @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobSchedulingInfo(@JsonProperty("jobId") String jobId, @JsonProperty("workerAssignments") Map<Integer, WorkerAssignments> workerAssignments) { this.jobId = jobId; this.workerAssignments = workerAssignments; } public String getJobId() { return jobId; } public Map<Integer, WorkerAssignments> getWorkerAssignments() { return workerAssignments; } @Override public String toString() { return "SchedulingChange [jobId=" + jobId + ", workerAssignments=" + workerAssignments + "]"; } }
8,238
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/Service.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.server.core; public interface Service { void start(); void shutdown(); void enterActiveMode(); }
8,239
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/WorkerTopologyInfo.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.server.core; import io.mantisrx.runtime.descriptor.StageSchedulingInfo; import java.util.HashMap; import java.util.Map; public class WorkerTopologyInfo { private static final String MANTIS_JOB_NAME = "MANTIS_JOB_NAME"; private static final String MANTIS_JOB_ID = "MANTIS_JOB_ID"; private static final String MANTIS_WORKER_INDEX = "MANTIS_WORKER_INDEX"; private static final String MANTIS_WORKER_NUMBER = "MANTIS_WORKER_NUMBER"; private static final String MANTIS_WORKER_STAGE_NUMBER = "MANTIS_WORKER_STAGE_NUMBER"; private static final String MANTIS_NUM_STAGES = "MANTIS_NUM_STAGES"; private static final String MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS = "MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS"; private static final String MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS = "MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS"; private static final String MANTIS_METRICS_PORT = "MANTIS_METRICS_PORT"; private static final String MANTIS_WORKER_CUSTOM_PORT = "MANTIS_WORKER_CUSTOM_PORT"; public static class Data { private String jobName; private String JobId; private int workerIndex; private int workerNumber; private int stageNumber; private int numStages; private int prevStageInitialNumWorkers = -1; private int nextStageInitialNumWorkers = -1; private int metricsPort; public Data(String jobName, String jobId, int workerIndex, int workerNumber, int stageNumber, int numStages) { this.jobName = jobName; JobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.stageNumber = stageNumber; this.numStages = numStages; } public Data(String jobName, String jobId, int workerIndex, int workerNumber, int stageNumber, int numStages, int prevStageInitialNumWorkers, int nextStageInitialNumWorkers, int metricsPort) { this.jobName = jobName; JobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.stageNumber = stageNumber; this.numStages = numStages; this.prevStageInitialNumWorkers = prevStageInitialNumWorkers; this.nextStageInitialNumWorkers = nextStageInitialNumWorkers; this.metricsPort = metricsPort; } public String getJobName() { return jobName; } public String getJobId() { return JobId; } public int getWorkerIndex() { return workerIndex; } public int getWorkerNumber() { return workerNumber; } public int getStageNumber() { return stageNumber; } public int getNumStages() { return numStages; } public int getPrevStageInitialNumWorkers() { return prevStageInitialNumWorkers; } public int getNextStageInitialNumWorkers() { return nextStageInitialNumWorkers; } public int getMetricsPort() { return metricsPort; } } public static class Writer { private final Map<String, String> envVars; public Writer(ExecuteStageRequest request) { envVars = new HashMap<>(); envVars.put(MANTIS_JOB_NAME, request.getJobName()); envVars.put(MANTIS_JOB_ID, request.getJobId()); envVars.put(MANTIS_WORKER_INDEX, request.getWorkerIndex() + ""); envVars.put(MANTIS_WORKER_NUMBER, request.getWorkerNumber() + ""); envVars.put(MANTIS_WORKER_STAGE_NUMBER, request.getStage() + ""); envVars.put(MANTIS_NUM_STAGES, request.getTotalNumStages() + ""); final int totalNumWorkerStages = request.getTotalNumStages() - (request.getHasJobMaster() ? 1 : 0); if (totalNumWorkerStages > 1 && request.getStage() > 1) { StageSchedulingInfo prevStage = request.getSchedulingInfo().forStage(request.getStage() - 1); envVars.put(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS, prevStage.getNumberOfInstances() + ""); if (totalNumWorkerStages > request.getStage()) { StageSchedulingInfo nextStage = request.getSchedulingInfo().forStage( request.getStage() + 1); envVars.put(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS, nextStage.getNumberOfInstances() + ""); } } envVars.put(MANTIS_METRICS_PORT, request.getMetricsPort() + ""); envVars.put(MANTIS_WORKER_CUSTOM_PORT, request.getWorkerPorts().getCustomPort() + ""); } public Map<String, String> getEnvVars() { return envVars; } } public static class Reader { private static Data data; static { data = new Data( System.getenv(MANTIS_JOB_NAME), System.getenv(MANTIS_JOB_ID), System.getenv(MANTIS_WORKER_INDEX) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_INDEX)), System.getenv(MANTIS_WORKER_NUMBER) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_NUMBER)), System.getenv(MANTIS_WORKER_STAGE_NUMBER) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_STAGE_NUMBER)), System.getenv(MANTIS_NUM_STAGES) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_NUM_STAGES)), System.getenv(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS)), System.getenv(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS)), System.getenv(MANTIS_METRICS_PORT) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_METRICS_PORT)) ); } public static Data getData() { return data; } } }
8,240
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/WorkerAssignments.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.server.core; 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; import lombok.EqualsAndHashCode; @EqualsAndHashCode public class WorkerAssignments { private int stage; private int numWorkers; private int activeWorkers; private Map<Integer, WorkerHost> hosts; // lookup by workerNumber @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public WorkerAssignments(@JsonProperty("stage") Integer stage, @JsonProperty("numWorkers") Integer numWorkers, @JsonProperty("hosts") Map<Integer, WorkerHost> hosts) { this.stage = stage; this.numWorkers = numWorkers; this.hosts = hosts; } public int getStage() { return stage; } public int getNumWorkers() { return numWorkers; } public void setNumWorkers(int numWorkers) { this.numWorkers = numWorkers; } public int getActiveWorkers() { return activeWorkers; } public void setActiveWorkers(int activeWorkers) { this.activeWorkers = activeWorkers; } public Map<Integer, WorkerHost> getHosts() { return hosts; } @Override public String toString() { return "WorkerAssignments [stage=" + stage + ", numWorkers=" + numWorkers + ", hosts=" + hosts + "]"; } }
8,241
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/WorkerOutlier.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.server.core; import io.mantisrx.server.core.stats.SimpleStats; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; import rx.functions.Action1; import rx.observers.SerializedObserver; import rx.subjects.PublishSubject; public class WorkerOutlier { private static final Logger logger = LoggerFactory.getLogger(WorkerOutlier.class); private final PublishSubject<DataPoint> subject = PublishSubject.create(); private final Observer<DataPoint> observer = new SerializedObserver<>(subject); private final long cooldownSecs; private final Action1<Integer> outlierTrigger; private long lastTriggeredAt = 0L; private long minDataPoints = 16; private long maxDataPoints = 20; public WorkerOutlier(long cooldownSecs, Action1<Integer> outlierTrigger) { this.cooldownSecs = cooldownSecs; if (outlierTrigger == null) throw new NullPointerException("outlierTrigger is null"); this.outlierTrigger = outlierTrigger; start(); } private void start() { logger.info("Starting Worker outlier detector"); final Map<Integer, Double> values = new HashMap<>(); final Map<Integer, List<Boolean>> isOutlierMap = new HashMap<>(); subject .doOnNext(new Action1<DataPoint>() { @Override public void call(DataPoint dataPoint) { values.put(dataPoint.index, dataPoint.value); final int currSize = values.size(); if (currSize > dataPoint.numWorkers) { for (int i = dataPoint.numWorkers; i < currSize; i++) { values.remove(i); isOutlierMap.remove(i); } } SimpleStats simpleStats = new SimpleStats(values.values()); List<Boolean> booleans = isOutlierMap.get(dataPoint.index); if (booleans == null) { booleans = new ArrayList<>(); isOutlierMap.put(dataPoint.index, booleans); } if (booleans.size() >= maxDataPoints) // for now hard code to 20 items booleans.remove(0); booleans.add(dataPoint.value > simpleStats.getOutlierThreshold()); if ((System.currentTimeMillis() - lastTriggeredAt) > cooldownSecs * 1000) { if (booleans.size() > minDataPoints) { int total = 0; int outlierCnt = 0; for (boolean b : booleans) { total++; if (b) outlierCnt++; } if (outlierCnt > (Math.round((double) total * 0.7))) { // again, hardcode for now outlierTrigger.call(dataPoint.index); lastTriggeredAt = System.currentTimeMillis(); booleans.clear(); } } } } }) .subscribe(); } public void addDataPoint(int workerIndex, double value, int numWorkers) { observer.onNext(new DataPoint(workerIndex, value, numWorkers)); } public void completed() { observer.onCompleted(); } private static class DataPoint { private final int index; private final double value; private final int numWorkers; private DataPoint(int index, double value, int numWorkers) { this.index = index; this.value = value; this.numWorkers = numWorkers; } } }
8,242
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/CacheJobArtifactsRequest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.core; 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.io.Serializable; import java.net.URI; import java.util.List; import lombok.NonNull; import lombok.Value; @Value public class CacheJobArtifactsRequest implements Serializable { private static final long serialVersionUID = 1L; @NonNull final List<URI> artifacts; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public CacheJobArtifactsRequest(@JsonProperty("artifacts") List<URI> artifacts) { this.artifacts = artifacts; } }
8,243
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/BaseService.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.server.core; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Action0; public abstract class BaseService implements Service { private static AtomicInteger SERVICES_COUNTER = new AtomicInteger(0); private final boolean awaitsActiveMode; private final ActiveMode activeMode = new ActiveMode(); private final int myServiceCount; private BaseService predecessor = null; protected BaseService() { this(false); } protected BaseService(boolean awaitsActiveMode) { this.awaitsActiveMode = awaitsActiveMode; if (!this.awaitsActiveMode) { activeMode.isInited.set(true); } myServiceCount = SERVICES_COUNTER.getAndIncrement(); } @Override public abstract void start(); /** * If this is set to await active mode, then, asynchronously (in a new thread) waits for entering active mode * and then calls the action parameter. It then also waits for any predecessor to be initialized before setting this * as initialized. * If this is set to not await active mode, then it just sets this as initialized and returns. * * @param onActive Action to call after waiting for entering active mode. */ protected void awaitActiveModeAndStart(Action0 onActive) { activeMode.waitAndStart(onActive, predecessor); } protected boolean getIsInited() { return activeMode.getIsInited() && (predecessor == null || predecessor.getIsInited()); } @Override public void enterActiveMode() { activeMode.enterActiveMode(); } @Override public void shutdown() { } public void addPredecessor(BaseService service) { this.predecessor = service; } public int getMyServiceCount() { return myServiceCount; } public class ActiveMode { private final AtomicBoolean isLeaderMode = new AtomicBoolean(false); private final AtomicBoolean isInited = new AtomicBoolean(false); Logger logger = LoggerFactory.getLogger(ActiveMode.class); public boolean getIsInited() { return isInited.get(); } private void awaitLeaderMode() { while (!isLeaderMode.get()) { synchronized (isLeaderMode) { try { isLeaderMode.wait(10000); } catch (InterruptedException e) { logger.info("Interrupted waiting for leaderModeLatch"); Thread.currentThread().interrupt(); } } } } public void waitAndStart(final Action0 onActive, final BaseService predecessor) { logger.info(myServiceCount + ": Setting up thread to wait for entering leader mode"); Runnable runnable = new Runnable() { @Override public void run() { awaitLeaderMode(); logger.info(myServiceCount + ": done waiting for leader mode"); if (predecessor != null) { predecessor.activeMode.awaitInit(); } logger.info(myServiceCount + ": done waiting for predecessor init"); if (onActive != null) { onActive.call(); } synchronized (isInited) { isInited.set(true); isInited.notify(); } } }; Thread thr = new Thread(runnable, "BaseService-LeaderModeWaitThread-" + myServiceCount); thr.setDaemon(true); thr.start(); } private void awaitInit() { while (!isInited.get()) { synchronized (isInited) { try { isInited.wait(5000); } catch (InterruptedException e) { logger.info("Interrupted waiting for predecessor init"); Thread.currentThread().interrupt(); } } } if (predecessor != null) { predecessor.activeMode.awaitInit(); } } public void enterActiveMode() { logger.info(myServiceCount + ": Entering leader mode"); synchronized (isLeaderMode) { isLeaderMode.set(true); isLeaderMode.notify(); } } } public static BaseService wrap(io.mantisrx.shaded.com.google.common.util.concurrent.Service service) { return new BaseService() { @Override public void start() { } @Override public void enterActiveMode() { service.startAsync().awaitRunning(); super.enterActiveMode(); } @Override public void shutdown() { service.stopAsync().awaitTerminated(); super.shutdown(); } }; } }
8,244
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/MetricsCoercer.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.server.core; import io.mantisrx.common.metrics.MetricsPublisher; import java.util.Map.Entry; import java.util.Properties; import org.skife.config.Coercer; import org.skife.config.Coercible; public class MetricsCoercer implements Coercible<MetricsPublisher> { private Properties props; public MetricsCoercer(Properties props) { this.props = props; } @Override public Coercer<MetricsPublisher> accept(Class<?> clazz) { if (MetricsPublisher.class.isAssignableFrom(clazz)) { return new Coercer<MetricsPublisher>() { @Override public MetricsPublisher coerce(String className) { try { // get properties for publisher Properties publishProperties = new Properties(); String configPrefix = (String) props.get("mantis.metricsPublisher.config.prefix"); if (configPrefix != null && configPrefix.length() > 0) { for (Entry<Object, Object> entry : props.entrySet()) { if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith(configPrefix)) { publishProperties.put(entry.getKey(), entry.getValue()); } } } return (MetricsPublisher) Class.forName(className).getConstructor(Properties.class) .newInstance(publishProperties); } catch (Exception e) { throw new IllegalArgumentException( String.format( "The value %s is not a valid class name for %s implementation. ", className, MetricsPublisher.class.getName() ), e); } } }; } return null; } }
8,245
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/TimeBufferedWorkerOutlier.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.server.core; import java.util.HashMap; import java.util.Map; import rx.functions.Action1; /** * Worker outlier detector that buffers events based on time before determining outliers. This is used for high volume * metrics such as sourcejob drops. Volume may have high variation over time, buffering by time will eliminate the variant. */ public class TimeBufferedWorkerOutlier extends WorkerOutlier { private Map<Integer, CumulatedValue> workerValues = new HashMap<>(); private long bufferedSecs; public TimeBufferedWorkerOutlier(long cooldownSecs, long bufferedSecs, Action1<Integer> outlierTrigger) { super(cooldownSecs, outlierTrigger); this.bufferedSecs = bufferedSecs; } @Override public void addDataPoint(int workerIndex, double value, int numWorkers) { CumulatedValue cumulatedValue; synchronized (workerValues) { cumulatedValue = workerValues.get(workerIndex); if (cumulatedValue == null) { cumulatedValue = new CumulatedValue(); workerValues.put(workerIndex, cumulatedValue); } } double dataPoint = -1; synchronized (cumulatedValue) { if (System.currentTimeMillis() - cumulatedValue.startTs > bufferedSecs * 1000) { dataPoint = cumulatedValue.value; cumulatedValue.reset(); } cumulatedValue.increment(value); } if (dataPoint != -1) { super.addDataPoint(workerIndex, dataPoint, numWorkers); } } public static class CumulatedValue { private long startTs = System.currentTimeMillis(); private double value = 0; public void increment(double incr) { value += incr; } public void reset() { startTs = System.currentTimeMillis(); value = 0; } } }
8,246
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/JobAssignmentResult.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.server.core; import io.mantisrx.runtime.codec.JsonType; 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.List; public class JobAssignmentResult implements JsonType { private final String jobId; private final List<Failure> failures; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobAssignmentResult(@JsonProperty("jobId") String jobId, @JsonProperty("failures") List<Failure> failures) { this.jobId = jobId; this.failures = failures; } private static boolean failuresIdentical(List<Failure> first, List<Failure> second) { if (first == null) { return second == null; } if (second == null) return false; if (first.size() != second.size()) return false; int item = 0; for (Failure f : first) { boolean found = false; for (int fi = 0; fi < second.size() && !found; fi++) { if (f.isIdentical(second.get(fi))) found = true; } if (!found) return false; } return true; } public String getJobId() { return jobId; } public List<Failure> getFailures() { return failures; } public boolean isIdentical(JobAssignmentResult that) { if (that == null) return false; if (this == that) return true; if (!jobId.equals(that.jobId)) return false; return failuresIdentical(failures, that.failures); } public static class Failure { private int workerNumber; private String type; private double asking; private double used; private double available; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Failure(@JsonProperty("workerNumber") int workerNumber, @JsonProperty("type") String type, @JsonProperty("asking") double asking, @JsonProperty("used") double used, @JsonProperty("available") double available) { this.workerNumber = workerNumber; this.type = type; this.asking = asking; this.used = used; this.available = available; } public int getWorkerNumber() { return workerNumber; } public String getType() { return type; } public double getAsking() { return asking; } public double getUsed() { return used; } public double getAvailable() { return available; } private boolean isIdentical(Failure that) { if (that == null) return false; return workerNumber == that.workerNumber && type.equals(that.type) && asking == that.asking && used == that.used && available == that.available; } } }
8,247
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/metrics/MetricsFactory.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.metrics; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.ExecuteStageRequest; import io.mantisrx.server.core.stats.MetricStringConstants; import java.util.HashMap; import java.util.Map; public class MetricsFactory { /** * Returns a metrics server, publishing metrics every 1 second * * @param request request for which the metrics need to be published * @return MetricsServerService server */ public static MetricsServerService newMetricsServer(CoreConfiguration configuration, ExecuteStageRequest request) { // todo(sundaram): get rid of the dependency on the metrics port defined at the ExecuteStageRequest level // because that's a configuration of the task manager rather than the request. return new MetricsServerService(request.getMetricsPort(), 1, getCommonTags(request)); } public static MetricsPublisherService newMetricsPublisher(CoreConfiguration config, ExecuteStageRequest request) { return new MetricsPublisherService(config.getMetricsPublisher(), config.getMetricsPublisherFrequencyInSeconds(), getCommonTags(request)); } public static Map<String, String> getCommonTags(ExecuteStageRequest request) { // provide common tags to metrics publishing service Map<String, String> commonTags = new HashMap<>(); commonTags.put(MetricStringConstants.MANTIS_WORKER_NUM, Integer.toString(request.getWorkerNumber())); commonTags.put(MetricStringConstants.MANTIS_STAGE_NUM, Integer.toString(request.getStage())); commonTags.put(MetricStringConstants.MANTIS_WORKER_INDEX, Integer.toString(request.getWorkerIndex())); commonTags.put(MetricStringConstants.MANTIS_JOB_NAME, request.getJobName()); commonTags.put(MetricStringConstants.MANTIS_JOB_ID, request.getJobId()); // adding the following for mesos metrics back compat commonTags.put(MetricStringConstants.MANTIS_WORKER_NUMBER, Integer.toString(request.getWorkerNumber())); commonTags.put(MetricStringConstants.MANTIS_WORKER_STAGE_NUMBER, Integer.toString(request.getStage())); return commonTags; } }
8,248
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/metrics/MetricsPublisherService.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.server.core.metrics; import io.mantisrx.common.metrics.MetricsPublisher; import io.mantisrx.server.core.Service; import java.util.HashMap; import java.util.Map; public class MetricsPublisherService implements Service { private MetricsPublisher publisher; private int publishFrequency; private Map<String, String> commonTags = new HashMap<>(); public MetricsPublisherService(MetricsPublisher publisher, int publishFrequency, Map<String, String> commonTags) { this.publisher = publisher; this.publishFrequency = publishFrequency; this.commonTags.putAll(commonTags); } public MetricsPublisherService(MetricsPublisher publisher, int publishFrequency) { this(publisher, publishFrequency, new HashMap<String, String>()); } @Override public void start() { publisher.start(publishFrequency, commonTags); } @Override public void shutdown() { publisher.shutdown(); } @Override public void enterActiveMode() {} }
8,249
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/metrics/MetricsServerService.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.server.core.metrics; import io.mantisrx.common.metrics.MetricsServer; import io.mantisrx.server.core.Service; import java.util.Map; public class MetricsServerService implements Service { private MetricsServer server; public MetricsServerService(final int port, final int publishRateInSeconds, final Map<String, String> tags) { server = new MetricsServer(port, publishRateInSeconds, tags); } @Override public void start() { server.start(); } @Override public void shutdown() { server.shutdown(); } @Override public void enterActiveMode() {} }
8,250
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/utils/StatusConstants.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.core.utils; public class StatusConstants { public static final String STATUS_MESSAGE_FORMAT = "stage %s worker index=%s number=%s %s"; }
8,251
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/zookeeper/CuratorService.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.server.core.zookeeper; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.server.core.BaseService; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.Service; import io.mantisrx.server.core.master.MasterMonitor; import io.mantisrx.server.core.master.ZookeeperMasterMonitor; import io.mantisrx.shaded.com.google.common.util.concurrent.MoreExecutors; import io.mantisrx.shaded.org.apache.curator.framework.CuratorFramework; import io.mantisrx.shaded.org.apache.curator.framework.CuratorFrameworkFactory; import io.mantisrx.shaded.org.apache.curator.framework.imps.GzipCompressionProvider; import io.mantisrx.shaded.org.apache.curator.framework.state.ConnectionState; import io.mantisrx.shaded.org.apache.curator.framework.state.ConnectionStateListener; import io.mantisrx.shaded.org.apache.curator.retry.ExponentialBackoffRetry; import io.mantisrx.shaded.org.apache.curator.utils.ZKPaths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This {@link Service} implementation is responsible for managing the lifecycle of a {@link io.mantisrx.shaded.org.apache.curator.framework.CuratorFramework} * instance. */ public class CuratorService extends BaseService { private static final Logger LOG = LoggerFactory.getLogger(CuratorService.class); private static final String isConnectedGaugeName = "isConnected"; private final CuratorFramework curator; private final ZookeeperMasterMonitor masterMonitor; private final Gauge isConnectedGauge; public CuratorService(CoreConfiguration configs) { super(false); Metrics m = new Metrics.Builder() .name(CuratorService.class.getCanonicalName()) .addGauge(isConnectedGaugeName) .build(); m = MetricsRegistry.getInstance().registerAndGet(m); isConnectedGauge = m.getGauge(isConnectedGaugeName); curator = CuratorFrameworkFactory.builder() .compressionProvider(new GzipCompressionProvider()) .connectionTimeoutMs(configs.getZkConnectionTimeoutMs()) .retryPolicy(new ExponentialBackoffRetry(configs.getZkConnectionRetrySleepMs(), configs.getZkConnectionMaxRetries())) .connectString(configs.getZkConnectionString()) .build(); masterMonitor = new ZookeeperMasterMonitor( curator, ZKPaths.makePath(configs.getZkRoot(), configs.getLeaderAnnouncementPath())); } private void setupCuratorListener() { LOG.info("Setting up curator state change listener"); curator.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState.isConnected()) { LOG.info("Curator connected"); isConnectedGauge.set(1L); } else { // ToDo: determine if it is safe to restart our service instead of committing suicide LOG.error("Curator connection lost"); isConnectedGauge.set(0L); } } }, MoreExecutors.newDirectExecutorService()); } @Override public void start() { try { isConnectedGauge.set(0L); setupCuratorListener(); curator.start(); masterMonitor.startAsync().awaitRunning(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void shutdown() { try { masterMonitor.stopAsync().awaitTerminated(); curator.close(); } catch (Exception e) { // A shutdown failure should not affect the subsequent shutdowns, so // we just warn here LOG.warn("Failed to shut down the curator service: " + e.getMessage(), e); } } public CuratorFramework getCurator() { return curator; } public MasterMonitor getMasterMonitor() { return masterMonitor; } }
8,252
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/json/DefaultObjectMapper.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.server.core.json; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonFactory; import io.mantisrx.shaded.com.fasterxml.jackson.core.Version; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.MapperFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.SerializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.module.SimpleModule; import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module; public class DefaultObjectMapper extends ObjectMapper { private static DefaultObjectMapper INSTANCE = new DefaultObjectMapper(); private DefaultObjectMapper() { this(null); } public DefaultObjectMapper(JsonFactory factory) { super(factory); SimpleModule serializerModule = new SimpleModule("Mantis Default JSON Serializer", new Version(1, 0, 0, null)); registerModule(serializerModule); configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); configure(MapperFeature.AUTO_DETECT_GETTERS, false); configure(MapperFeature.AUTO_DETECT_FIELDS, false); registerModule(new Jdk8Module()); } public static DefaultObjectMapper getInstance() { return INSTANCE; } }
8,253
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/master/MasterMonitor.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.server.core.master; import javax.annotation.Nullable; import rx.Observable; public interface MasterMonitor { Observable<MasterDescription> getMasterObservable(); /** * Returns the latest master if there's one. If there has been no master in recently history, * then this return null. * * @return Latest description of the master */ @Nullable MasterDescription getLatestMaster(); }
8,254
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/master/ZookeeperMasterMonitor.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.server.core.master; import io.mantisrx.common.JsonSerializer; import io.mantisrx.server.core.json.DefaultObjectMapper; import io.mantisrx.shaded.com.google.common.base.Preconditions; import io.mantisrx.shaded.com.google.common.util.concurrent.AbstractIdleService; import io.mantisrx.shaded.org.apache.curator.framework.CuratorFramework; import io.mantisrx.shaded.org.apache.curator.framework.api.BackgroundCallback; import io.mantisrx.shaded.org.apache.curator.framework.api.CuratorEvent; import io.mantisrx.shaded.org.apache.curator.framework.recipes.cache.NodeCache; import io.mantisrx.shaded.org.apache.curator.framework.recipes.cache.NodeCacheListener; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.subjects.BehaviorSubject; /** * A monitor that monitors the status of Mantis masters. */ public class ZookeeperMasterMonitor extends AbstractIdleService implements MasterMonitor { private static final Logger logger = LoggerFactory.getLogger(ZookeeperMasterMonitor.class); private final CuratorFramework curator; private final String masterPath; private final BehaviorSubject<MasterDescription> masterSubject; private final AtomicReference<MasterDescription> latestMaster = new AtomicReference<>(); private final NodeCache nodeMonitor; private final JsonSerializer jsonSerializer; public ZookeeperMasterMonitor(CuratorFramework curator, String masterPath) { this.curator = curator; this.masterPath = masterPath; this.masterSubject = BehaviorSubject.create(); this.nodeMonitor = new NodeCache(curator, masterPath); this.jsonSerializer = new JsonSerializer(); } @Override public void startUp() throws Exception { nodeMonitor.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { retrieveMaster(); } }); nodeMonitor.start(true); onMasterNodeUpdated(nodeMonitor.getCurrentData() == null ? null : nodeMonitor.getCurrentData().getData()); logger.info("The ZK master monitor has started"); } private void onMasterNodeUpdated(@Nullable byte[] data) throws Exception { if (data != null) { logger.info("value was {}", new String(data)); MasterDescription description = DefaultObjectMapper.getInstance().readValue(data, MasterDescription.class); logger.info("new master description = {}", description); latestMaster.set(description); masterSubject.onNext(description); } else { logger.info("looks like there's no master at the moment"); } } private void retrieveMaster() { try { curator .sync() // sync with ZK before reading .inBackground( curator .getData() .inBackground(new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { onMasterNodeUpdated(event.getData()); } }) .forPath(masterPath) ) .forPath(masterPath); } catch (Exception e) { logger.error("Failed to retrieve updated master information: " + e.getMessage(), e); } } @Override public Observable<MasterDescription> getMasterObservable() { return masterSubject; } /** * * @return */ @Override @Nullable public MasterDescription getLatestMaster() { Preconditions.checkState(isRunning(), "ZookeeperMasterMonitor is currently not running but instead is at state %s", state()); return latestMaster.get(); } @Override public void shutDown() throws Exception { nodeMonitor.close(); logger.info("ZK master monitor is shut down"); } }
8,255
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/master/LocalMasterMonitor.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.server.core.master; import rx.Observable; /** * A {@code MasterMonitor} implementation that does not monitor anything. Use this * class for local testing. */ public class LocalMasterMonitor implements MasterMonitor { private final MasterDescription master; public LocalMasterMonitor(MasterDescription master) { this.master = master; } @Override public Observable<MasterDescription> getMasterObservable() { return Observable.just(master); } @Override public MasterDescription getLatestMaster() { return master; } }
8,256
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/master/MasterDescription.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.server.core.master; 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 lombok.EqualsAndHashCode; import lombok.ToString; /** * A JSON-serializable data transfer object for Mantis master descriptions. It's used to transfer * metadata between master and workers. */ @EqualsAndHashCode @ToString public class MasterDescription { public static final String JSON_PROP_HOSTNAME = "hostname"; public static final String JSON_PROP_HOST_IP = "hostIP"; public static final String JSON_PROP_API_PORT = "apiPort"; public static final String JSON_PROP_SCHED_INFO_PORT = "schedInfoPort"; public static final String JSON_PROP_API_PORT_V2 = "apiPortV2"; public static final String JSON_PROP_API_STATUS_URI = "apiStatusUri"; public static final String JSON_PROP_CONSOLE_PORT = "consolePort"; public static final String JSON_PROP_CREATE_TIME = "createTime"; private final String hostname; private final String hostIP; private final int apiPort; private final int schedInfoPort; private final int apiPortV2; private final String apiStatusUri; private final long createTime; private final int consolePort; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public MasterDescription( @JsonProperty(JSON_PROP_HOSTNAME) String hostname, @JsonProperty(JSON_PROP_HOST_IP) String hostIP, @JsonProperty(JSON_PROP_API_PORT) int apiPort, @JsonProperty(JSON_PROP_SCHED_INFO_PORT) int schedInfoPort, @JsonProperty(JSON_PROP_API_PORT_V2) int apiPortV2, @JsonProperty(JSON_PROP_API_STATUS_URI) String apiStatusUri, @JsonProperty(JSON_PROP_CONSOLE_PORT) int consolePort, @JsonProperty(JSON_PROP_CREATE_TIME) long createTime ) { this.hostname = hostname; this.hostIP = hostIP; this.apiPort = apiPort; this.schedInfoPort = schedInfoPort; this.apiPortV2 = apiPortV2; this.apiStatusUri = apiStatusUri; this.consolePort = consolePort; this.createTime = createTime; } @JsonProperty(JSON_PROP_HOSTNAME) public String getHostname() { return hostname; } @JsonProperty(JSON_PROP_HOST_IP) public String getHostIP() { return hostIP; } @JsonProperty(JSON_PROP_API_PORT) public int getApiPort() { return apiPort; } @JsonProperty(JSON_PROP_SCHED_INFO_PORT) public int getSchedInfoPort() { return schedInfoPort; } @JsonProperty(JSON_PROP_API_PORT_V2) public int getApiPortV2() { return apiPortV2; } @JsonProperty(JSON_PROP_API_STATUS_URI) public String getApiStatusUri() { return apiStatusUri; } @JsonProperty(JSON_PROP_CREATE_TIME) public long getCreateTime() { return createTime; } public String getFullApiStatusUri() { String uri = getApiStatusUri().trim(); if (uri.startsWith("/")) { uri = uri.substring(1); } return String.format("http://%s:%d/%s", getHostname(), getApiPort(), uri); } @JsonProperty(JSON_PROP_CONSOLE_PORT) public int getConsolePort() { return consolePort; } }
8,257
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/domain/JobArtifact.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.domain; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.time.Instant; import java.util.Map; import lombok.Builder; import lombok.Value; @Value @Builder @JsonIgnoreProperties(ignoreUnknown = true) public class JobArtifact { // Job artifact unique identifier @JsonProperty("artifactID") ArtifactID artifactID; // Job artifact name @JsonProperty("name") String name; // Job artifact version @JsonProperty("version") String version; // Job artifact creation timestamp @JsonProperty("createdAt") Instant createdAt; // Runtime Type Identification. For java potential values: spring-boot, guice @JsonProperty("runtimeType") String runtimeType; // Job artifact external dependencies // Example: {"mantis-runtime": "1.0.0"} @JsonProperty("dependencies") Map<String, String> dependencies; // Job entrypoint clas. @JsonProperty("entrypoint") String entrypoint; }
8,258
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/domain/ArtifactID.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.domain; import lombok.RequiredArgsConstructor; import lombok.Value; /** * Represents the job artifact that mantis can run. */ @RequiredArgsConstructor(staticName="of") @Value public class ArtifactID { String resourceID; }
8,259
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/domain/WorkerId.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.server.core.domain; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.shaded.org.apache.curator.shaded.com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkerId implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(WorkerId.class); private static final String DELIMITER = "-"; private static final String WORKER_DELIMITER = "-worker-"; private final String jobCluster; private final String jobId; private final int wIndex; private final int wNum; private final String id; public WorkerId(final String jobId, final int wIndex, final int wNum) { this(WorkerId.getJobClusterFromId(jobId), jobId, wIndex, wNum); } @JsonCreator public WorkerId(@JsonProperty("jobCluster") final String jobCluster, @JsonProperty("jobId") final String jobId, @JsonProperty("workerIndex") final int wIndex, @JsonProperty("workerNum") final int wNum) { this.jobCluster = jobCluster; this.jobId = jobId; this.wIndex = wIndex; this.wNum = wNum; this.id = new StringBuilder() .append(jobId) .append(WORKER_DELIMITER) .append(wIndex) .append('-') .append(wNum) .toString(); } private static String getJobClusterFromId(final String jobId) { final int jobClusterIdx = jobId.lastIndexOf(DELIMITER); if (jobClusterIdx > 0) { return jobId.substring(0, jobClusterIdx); } else { logger.error("Failed to get JobCluster name from Job ID {}", jobId); throw new IllegalArgumentException("Job ID is invalid " + jobId); } } /* Returns a valid WorkerId only if the passed 'id' string is well-formed. There are some instances in Master currently where we could get back index = -1 which would fail to get a valid WorkerId from String. */ public static Optional<WorkerId> fromId(final String id) { final int workerDelimIndex = id.indexOf(WORKER_DELIMITER); if (workerDelimIndex > 0) { final String jobId = id.substring(0, workerDelimIndex); final int jobClusterIdx = jobId.lastIndexOf(DELIMITER); if (jobClusterIdx > 0) { final String jobCluster = jobId.substring(0, jobClusterIdx); final String workerInfo = id.substring(workerDelimIndex + WORKER_DELIMITER.length()); final int delimiterIndex = workerInfo.indexOf(DELIMITER); if (delimiterIndex > 0) { try { final int wIndex = Integer.parseInt(workerInfo.substring(0, delimiterIndex)); final int wNum = Integer.parseInt(workerInfo.substring(delimiterIndex + 1)); return Optional.of(new WorkerId(jobCluster, jobId, wIndex, wNum)); } catch (NumberFormatException nfe) { logger.warn("failed to parse workerId from {}", id, nfe); } } } } logger.warn("failed to parse workerId from {}", id); return Optional.empty(); } @VisibleForTesting public static WorkerId fromIdUnsafe(String id) { return fromId(id).get(); } public String getJobCluster() { return jobCluster; } public String getJobId() { return jobId; } public int getWorkerIndex() { return wIndex; } public int getWorkerNum() { return wNum; } @JsonIgnore public String getId() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkerId workerId = (WorkerId) o; if (wIndex != workerId.wIndex) return false; if (wNum != workerId.wNum) return false; if (!jobCluster.equals(workerId.jobCluster)) return false; if (!jobId.equals(workerId.jobId)) return false; return id.equals(workerId.id); } @Override public int hashCode() { int result = jobCluster.hashCode(); result = 31 * result + jobId.hashCode(); result = 31 * result + wIndex; result = 31 * result + wNum; result = 31 * result + id.hashCode(); return result; } @Override public String toString() { return id; } }
8,260
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/domain/JobMetadata.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.server.core.domain; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; import java.net.URL; import java.util.List; import lombok.Getter; @Getter public class JobMetadata { private final String jobId; private final URL jobJarUrl; private final int totalStages; private final String user; private final SchedulingInfo schedulingInfo; private final List<Parameter> parameters; private final long subscriptionTimeoutSecs; private final long heartbeatIntervalSecs; private final long minRuntimeSecs; public JobMetadata(final String jobId, final URL jobJarUrl, final int totalStages, final String user, final SchedulingInfo schedulingInfo, final List<Parameter> parameters, final long subscriptionTimeoutSecs, final long heartbeatIntervalSecs, final long minRuntimeSecs) { this.jobId = jobId; this.jobJarUrl = jobJarUrl; this.totalStages = totalStages; this.user = user; this.schedulingInfo = schedulingInfo; this.parameters = parameters; this.subscriptionTimeoutSecs = subscriptionTimeoutSecs; this.heartbeatIntervalSecs = heartbeatIntervalSecs; this.minRuntimeSecs = minRuntimeSecs; } public ArtifactID getJobArtifact() { final String urlString = jobJarUrl.toString(); return ArtifactID.of(urlString.substring(urlString.lastIndexOf('/') + 1)); } }
8,261
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/stats/MetricStringConstants.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.server.core.stats; public class MetricStringConstants { public static final String METRIC_NAME_STR = "name"; public static final String MANTIS_JOB_NAME = "mantisJobName"; public static final String MANTIS_JOB_ID = "mantisJobId"; public static final String MANTIS_STAGE_NUM = "mantisStageNum"; public static final String MANTIS_WORKER_STAGE_NUMBER = "mantisWorkerStageNumber"; public static final String MANTIS_WORKER_INDEX = "mantisWorkerIndex"; public static final String MANTIS_WORKER_NUM = "mantisWorkerNum"; public static final String MANTIS_WORKER_NUMBER = "mantisWorkerNumber"; // Resource Usage metrics public static final String RESOURCE_USAGE_METRIC_GROUP = "ResourceUsage"; public static final String CPU_PCT_LIMIT = "cpuPctLimit"; public static final String CPU_PCT_USAGE_CURR = "cpuPctUsageCurr"; public static final String CPU_PCT_USAGE_PEAK = "cpuPctUsagePeak"; public static final String MEM_LIMIT = "memLimit"; public static final String CACHED_MEM_USAGE_CURR = "cachedMemUsageCurr"; public static final String CACHED_MEM_USAGE_PEAK = "cachedMemUsagePeak"; public static final String TOT_MEM_USAGE_CURR = "totMemUsageCurr"; public static final String TOT_MEM_USAGE_PEAK = "totMemUsagePeak"; public static final String NW_BYTES_LIMIT = "nwBytesLimit"; public static final String NW_BYTES_USAGE_CURR = "nwBytesUsageCurr"; public static final String NW_BYTES_USAGE_PEAK = "nwBytesUsagePeak"; // Data drop metrics public static final String DATA_DROP_METRIC_GROUP = "DataDrop"; public static final String DROP_COUNT = "dropCount"; public static final String ON_NEXT_COUNT = "onNextCount"; public static final String DROP_PERCENT = "dropPercent"; // Kafka lag metric public static final String KAFKA_CONSUMER_FETCH_MGR_METRIC_GROUP = "consumer-fetch-manager-metrics"; public static final String KAFKA_LAG = "records-lag-max"; public static final String KAFKA_PROCESSED = "records-consumed-rate"; // RPS Metrics public static final String WORKER_STAGE_INNER_INPUT = "worker_stage_inner_input"; public static final String ON_NEXT_GAUGE = "onNextGauge"; private MetricStringConstants() {} }
8,262
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/stats/UsageDataStats.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.server.core.stats; import io.mantisrx.runtime.descriptor.StageScalingPolicy; import java.util.ArrayDeque; public class UsageDataStats { private final int capacity; private final ArrayDeque<Double> data; private final double highThreshold; private final double lowThreshold; private double sum = 0.0; private int countAboveHighThreshold = 0; private int countBelowLowThreshold = 0; private StageScalingPolicy.RollingCount rollingCount = new StageScalingPolicy.RollingCount(1, 1); public UsageDataStats(double highThreshold, double lowThreshold, StageScalingPolicy.RollingCount rollingCount) { this.capacity = rollingCount.getOf(); data = new ArrayDeque<>(capacity); this.highThreshold = highThreshold; this.lowThreshold = lowThreshold; this.rollingCount = rollingCount; } public void add(double d) { if (data.size() >= capacity) { final Double removed = data.removeFirst(); sum -= removed; if (removed > highThreshold) countAboveHighThreshold--; if (removed < lowThreshold && lowThreshold > 0.0) { // disable scaleDown for lowThreshold <= 0 countBelowLowThreshold--; } } data.addLast(d); sum += d; if (d > highThreshold) countAboveHighThreshold++; if (d < lowThreshold && lowThreshold > 0.0) { // disable scaleDown for lowThreshold <= 0 countBelowLowThreshold++; } } public int getCapacity() { return capacity; } public double getAverage() { return sum / data.size(); } public int getCountAboveHighThreshold() { return countAboveHighThreshold; } public int getCountBelowLowThreshold() { return countBelowLowThreshold; } public int getSize() { return data.size(); } public boolean getHighThreshTriggered() { return data.size() >= rollingCount.getCount() && countAboveHighThreshold >= rollingCount.getCount(); } public boolean getLowThreshTriggered() { return data.size() >= rollingCount.getCount() && countBelowLowThreshold >= rollingCount.getCount(); } public String getCurrentHighCount() { return countAboveHighThreshold + " of " + data.size(); } public String getCurrentLowCount() { return countBelowLowThreshold + " of " + data.size(); } }
8,263
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/core/stats/SimpleStats.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.server.core.stats; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; // Simple stats to figure out outlier threshold, specifically for low number of data points. // This is meant for finding out outliers greater than most of the data, not outliers that are smaller. // We make special cases as needed. public class SimpleStats { private final int maxDataPoints; private final ArrayList<Double> dataPoints; public SimpleStats(int maxDataPoints) { this.maxDataPoints = maxDataPoints; dataPoints = new ArrayList<>(); } public SimpleStats(Collection<Double> data) { this.maxDataPoints = data.size(); dataPoints = new ArrayList<>(data); } public static void main(String[] args) { SimpleStats simpleStats = new SimpleStats(5); simpleStats.add(4.0); for (int i = 1; i < 4; i++) simpleStats.add(0.0); simpleStats.add(10.0); System.out.println(String.format("thresh=%8.2f", simpleStats.getOutlierThreshold())); } public void add(double d) { if (dataPoints.size() == maxDataPoints) dataPoints.remove(0); dataPoints.add(d); } public double getOutlierThreshold() { if (dataPoints.size() <= 2) return twoPointsResults(); Double[] data = dataPoints.toArray(new Double[0]); Arrays.sort(data); // special case when the highest item is the major contributor of the total double total = 0.0; for (double d : data) total += d; if (data[data.length - 1] / total > 0.75) return data[data.length - 2]; if (dataPoints.size() == 3) return threePointsResults(data); if (dataPoints.size() == 4) return fourPointsResults(data); double q1 = data[(int) Math.round((double) data.length / 4.0)]; double q3 = data[(int) Math.floor((double) data.length * 3.0 / 4.0)]; return getThresh(q1, q3); } private double fourPointsResults(Double[] data) { return getThresh(data[1], data[2]); } private double getThresh(double q1, double q3) { return q3 + q3 - q1; } private double threePointsResults(Double[] data) { double q1 = (data[0] + data[1]) / 2.0; double q3 = (data[1] + data[2]) / 2.0; return getThresh(q1, q3); } private double twoPointsResults() { return dataPoints.isEmpty() ? 0.0 : dataPoints.get(0) == 0.0 ? 0.0 : dataPoints.get(dataPoints.size() - 1); } public boolean isSufficientData() { return dataPoints.size() > 3; } @Override public String toString() { return "SimpleStats{" + "maxDataPoints=" + maxDataPoints + ", dataPoints=" + dataPoints + '}'; } }
8,264
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorStatusChange.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import lombok.Value; /** * Data structure representing task executor's state changes. */ @Value public class TaskExecutorStatusChange { TaskExecutorID taskExecutorID; ClusterID clusterID; TaskExecutorReport taskExecutorReport; }
8,265
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorHeartbeat.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import lombok.Value; @Value public class TaskExecutorHeartbeat { TaskExecutorID taskExecutorID; ClusterID clusterID; TaskExecutorReport taskExecutorReport; }
8,266
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/ContainerSkuID.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import lombok.RequiredArgsConstructor; import lombok.Value; /** * Represents the container sku ID that the task executor's host container belongs to. */ @RequiredArgsConstructor(staticName="of") @Value public class ContainerSkuID { String resourceID; }
8,267
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/RequestThrottledException.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.master.resourcecluster; /** * This exception will be thrown when the request is throttled. */ public class RequestThrottledException extends Exception { public RequestThrottledException(String msg) { super(msg); } }
8,268
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/PagedActiveJobOverview.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import java.util.List; import lombok.Value; @Value public class PagedActiveJobOverview { List<String> activeJobs; int endPosition; }
8,269
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorDisconnection.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import lombok.Value; /** * Datastructure representing the task executor that needs to be disconnected from the resource cluster. */ @Value public class TaskExecutorDisconnection { TaskExecutorID taskExecutorID; ClusterID clusterID; }
8,270
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/ResourceClusters.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import java.util.Set; import java.util.concurrent.CompletableFuture; /** * ResourceClusters is a factory class for getting and managing individual resource clusters. */ public interface ResourceClusters { ResourceCluster getClusterFor(ClusterID clusterID); CompletableFuture<Set<ClusterID>> listActiveClusters(); }
8,271
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorRegistration.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import io.mantisrx.common.WorkerConstants; import io.mantisrx.common.WorkerPorts; import io.mantisrx.runtime.MachineDefinition; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.shaded.com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.Optional; import lombok.AccessLevel; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.ToString; import lombok.experimental.FieldDefaults; /** * Data structure used at the time of registration by the task executor. * Different fields help identify the task executor in different dimensions. */ @Builder @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @Getter @ToString @EqualsAndHashCode public class TaskExecutorRegistration { @NonNull TaskExecutorID taskExecutorID; @NonNull ClusterID clusterID; // RPC address that's used to talk to the task executor @NonNull String taskExecutorAddress; // host name of the task executor @NonNull String hostname; // ports used by the task executor for various purposes. @NonNull WorkerPorts workerPorts; // machine information identifies the cpu/mem/disk/network resources of the task executor. @NonNull MachineDefinition machineDefinition; /** custom attributes describing the task executor * [Note] all keys/values need to be save as lower-case to avoid mismatch. * TODO make this field non-null once no back-compat required. **/ Map<String, String> taskExecutorAttributes; @JsonCreator public TaskExecutorRegistration( @JsonProperty("taskExecutorID") TaskExecutorID taskExecutorID, @JsonProperty("clusterID") ClusterID clusterID, @JsonProperty("taskExecutorAddress") String taskExecutorAddress, @JsonProperty("hostname") String hostname, @JsonProperty("workerPorts") WorkerPorts workerPorts, @JsonProperty("machineDefinition") MachineDefinition machineDefinition, @JsonProperty("taskExecutorAttributes") Map<String, String> taskExecutorAttributes) { this.taskExecutorID = taskExecutorID; this.clusterID = clusterID; this.taskExecutorAddress = taskExecutorAddress; this.hostname = hostname; this.workerPorts = workerPorts; this.machineDefinition = machineDefinition; this.taskExecutorAttributes = (taskExecutorAttributes == null) ? ImmutableMap.of() : taskExecutorAttributes; } /** * Check if all given attributes have a match in taskExecutorAttributes. * [Note] all keys/values in taskExecutorAttributes are lower-case and * requiredAttributes will be evaluated case-insensitive. */ public boolean containsAttributes(Map<String, String> requiredAttributes) { for (Map.Entry<String, String> kv : requiredAttributes.entrySet()) { String k = kv.getKey().toLowerCase(); if (this.taskExecutorAttributes.containsKey(k) && this.taskExecutorAttributes.get(k).equalsIgnoreCase(kv.getValue())) { continue; } // handle back compat on case-sensitive registrations. if (this.taskExecutorAttributes.containsKey(kv.getKey()) && this.taskExecutorAttributes.get(kv.getKey()).equalsIgnoreCase(kv.getValue())) { continue; } return false; } return true; } @JsonIgnore public Optional<ContainerSkuID> getTaskExecutorContainerDefinitionId() { // handle back compat on key case insensitivity. String containerDefIdLower = WorkerConstants.WORKER_CONTAINER_DEFINITION_ID.toLowerCase(); if (this.taskExecutorAttributes.containsKey(containerDefIdLower)) { return Optional.ofNullable(ContainerSkuID.of(this.getTaskExecutorAttributes().get(containerDefIdLower))); } if (this.taskExecutorAttributes.containsKey(WorkerConstants.WORKER_CONTAINER_DEFINITION_ID)) { return Optional.ofNullable( ContainerSkuID.of( this.getTaskExecutorAttributes().get(WorkerConstants.WORKER_CONTAINER_DEFINITION_ID))); } return Optional.empty(); } @JsonIgnore public Optional<String> getAttributeByKey(String attributeKey) { if (this.taskExecutorAttributes.containsKey(attributeKey.toLowerCase())) { return Optional.ofNullable(this.getTaskExecutorAttributes().get(attributeKey.toLowerCase())); } if (this.taskExecutorAttributes.containsKey(attributeKey)) { return Optional.ofNullable(this.getTaskExecutorAttributes().get(attributeKey)); } return Optional.empty(); } }
8,272
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorAllocationRequest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.server.master.resourcecluster; import io.mantisrx.runtime.MachineDefinition; import io.mantisrx.server.core.domain.JobMetadata; import io.mantisrx.server.core.domain.WorkerId; import lombok.AllArgsConstructor; import lombok.Value; @Value @AllArgsConstructor(staticName = "of") public class TaskExecutorAllocationRequest { WorkerId workerId; MachineDefinition machineDefinition; JobMetadata jobMetadata; int stageNum; }
8,273
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorID.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import java.util.UUID; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.Value; /** * ID of the task executor. Reason this is wrapped inside a type is to have strong typing when dealing * with different types of IDs within the system. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) @Value public class TaskExecutorID { String resourceId; public static TaskExecutorID generate() { return new TaskExecutorID(UUID.randomUUID().toString()); } public static TaskExecutorID of(String resourceId) { return new TaskExecutorID(resourceId); } }
8,274
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/ResourceCluster.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import io.mantisrx.common.Ack; import io.mantisrx.server.core.domain.ArtifactID; import io.mantisrx.server.core.domain.WorkerId; import io.mantisrx.server.worker.TaskExecutorGateway; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import javax.annotation.Nullable; import lombok.Value; /** * Abstraction to deal with all interactions with the resource cluster such as * 1). listing the set of task executors registered * 2). listing the set of task executors available * 3). listing the set of task executors busy * 4). get the current state of a task executor * 5). get the current state of the system * 6). assign a task executor for a given worker */ public interface ResourceCluster extends ResourceClusterGateway { /** * Get the name of the resource cluster * * @return name of the resource cluster */ String getName(); /** * API that gets invoked when the resource cluster migrates from one machine to another and needs to be initialized. * * @param taskExecutorID taskExecutorID that was originally running the worker * @param workerId workerID of the task that being run on the task executor * @return Ack when the initialization is done */ CompletableFuture<Ack> initializeTaskExecutor(TaskExecutorID taskExecutorID, WorkerId workerId); default CompletableFuture<List<TaskExecutorID>> getRegisteredTaskExecutors() { return getRegisteredTaskExecutors(Collections.emptyMap()); } /** * Get the registered set of task executors * @param attributes attributes to filter out the set of task executors to be considered for registration. * @return the list of task executor IDs */ CompletableFuture<List<TaskExecutorID>> getRegisteredTaskExecutors(Map<String, String> attributes); default CompletableFuture<List<TaskExecutorID>> getAvailableTaskExecutors() { return getAvailableTaskExecutors(Collections.emptyMap()); } /** * Get the available set of task executors * * @param attributes attributes to filter out the set of task executors to be considered for availability. * @return the list of task executor IDs */ CompletableFuture<List<TaskExecutorID>> getAvailableTaskExecutors(Map<String, String> attributes); default CompletableFuture<List<TaskExecutorID>> getBusyTaskExecutors() { return getBusyTaskExecutors(Collections.emptyMap()); } CompletableFuture<List<TaskExecutorID>> getBusyTaskExecutors(Map<String, String> attributes); default CompletableFuture<List<TaskExecutorID>> getUnregisteredTaskExecutors() { return getUnregisteredTaskExecutors(Collections.emptyMap()); } CompletableFuture<List<TaskExecutorID>> getUnregisteredTaskExecutors(Map<String, String> attributes); CompletableFuture<ResourceOverview> resourceOverview(); CompletableFuture<Ack> addNewJobArtifactsToCache(ClusterID clusterID, List<ArtifactID> artifacts); CompletableFuture<Ack> removeJobArtifactsToCache(List<ArtifactID> artifacts); CompletableFuture<List<ArtifactID>> getJobArtifactsToCache(); /** * Can throw {@link NoResourceAvailableException} wrapped within the CompletableFuture in case there * are no task executors. * * @param machineDefinition machine definition that's requested for the worker * @param workerId worker id of the task that's going to run on the node. * @return task executor assigned for the particular task. */ CompletableFuture<TaskExecutorID> getTaskExecutorFor( TaskExecutorAllocationRequest allocationRequest); /** * Returns the Gateway instance to talk to the task executor. If unable to make connection with * the task executor, then a ConnectionFailedException is thrown wrapped inside the future. * * @param taskExecutorID executor for which the gateway is requested * @return gateway corresponding to the executor wrapped inside a future. */ CompletableFuture<TaskExecutorGateway> getTaskExecutorGateway(TaskExecutorID taskExecutorID); CompletableFuture<TaskExecutorRegistration> getTaskExecutorInfo(String hostName); /** * Gets the task executor's ID that's currently either running or is assigned for the given * workerId * * @param workerId workerId whose current task executor is needed * @return TaskExecutorID */ CompletableFuture<TaskExecutorID> getTaskExecutorAssignedFor(WorkerId workerId); CompletableFuture<TaskExecutorRegistration> getTaskExecutorInfo(TaskExecutorID taskExecutorID); CompletableFuture<TaskExecutorStatus> getTaskExecutorState(TaskExecutorID taskExecutorID); /** * Trigger a request to this resource cluster's ResourceClusterScalerActor to refresh the local scale rule set. */ CompletableFuture<Ack> refreshClusterScalerRuleSet(); /** * Disables task executors that match the passed set of attributes * * @param attributes attributes that need to be present in the task executor's set of * attributes. * @param expiry instant at which the request can be marked as complete. this is important * because we cannot be constantly checking if new task executors match the * disabled criteria or not. * @return a future that completes when the underlying operation is registered by the system */ CompletableFuture<Ack> disableTaskExecutorsFor(Map<String, String> attributes, Instant expiry, Optional<TaskExecutorID> taskExecutorID); /** * Enables/Disables scaler for a given skuID of a given clusterID * * @param skuID skuID whom scaler will be enabled/disabled. * @param enabled whether the scaler will be enabled/disabled. * @return a future that completes when the underlying operation is registered by the system */ CompletableFuture<Ack> setScalerStatus(ClusterID clusterID, ContainerSkuID skuID, Boolean enabled, Long expirationDurationInSeconds); /** * Get a paged result of all active jobs associated with this resource cluster. * * @param startingIndex Starting index for the paged list of all the active jobs. * @param pageSize Max size of returned paged list. * @return PagedActiveJobOverview instance. */ CompletableFuture<PagedActiveJobOverview> getActiveJobOverview( Optional<Integer> startingIndex, Optional<Integer> pageSize); /** * Gets the task executors to worker mapping for the given resource cluster * * @return a future mapping task executor IDs to the work they are doing */ CompletableFuture<Map<TaskExecutorID, WorkerId>> getTaskExecutorWorkerMapping(); /** * Gets the task executors to worker mapping for all task executors in the resource cluster that * match the filtering criteria as represented by the attributes. * * @param attributes filtering criteria * @return a future mapping task executor IDs to the work they are doing */ CompletableFuture<Map<TaskExecutorID, WorkerId>> getTaskExecutorWorkerMapping( Map<String, String> attributes); class NoResourceAvailableException extends Exception { public NoResourceAvailableException(String message) { super(message); } } /** * Exception thrown to indicate unable to make a connection */ static class ConnectionFailedException extends Exception { private static final long serialVersionUID = 1L; public ConnectionFailedException(Throwable cause) { super(cause); } } @Value class ResourceOverview { long numRegisteredTaskExecutors; long numAvailableTaskExecutors; long numOccupiedTaskExecutors; long numAssignedTaskExecutors; long numDisabledTaskExecutors; } @Value class TaskExecutorStatus { TaskExecutorRegistration registration; boolean registered; boolean runningTask; boolean assignedTask; boolean disabled; @Nullable WorkerId workerId; long lastHeartbeatInMs; } /** * Exception when asked {@link TaskExecutorID} cannot be found in control plane. */ static class TaskExecutorNotFoundException extends Exception { private static final long serialVersionUID = 2913026730940135991L; public TaskExecutorNotFoundException(TaskExecutorID taskExecutorID) { super("TaskExecutor " + taskExecutorID + " not found"); } } }
8,275
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/ClusterID.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import lombok.RequiredArgsConstructor; import lombok.Value; /** * Represents the cluster that the task executor belongs to. */ @RequiredArgsConstructor(staticName="of") @Value public class ClusterID { String resourceID; }
8,276
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/ResourceClusterGateway.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import io.mantisrx.common.Ack; import java.util.concurrent.CompletableFuture; /** * Gateway for performing all actions corresponding to the resource cluster from the task executor. */ public interface ResourceClusterGateway { /** * triggered at the start of a task executor or when the task executor has lost connection to the resource cluster * previously */ CompletableFuture<Ack> registerTaskExecutor(TaskExecutorRegistration registration); /** * Triggered when the task executor needs to send a heartbeat every epoch after registration. * Absence of a heartbeat from the task executor implies loss of the task executor or a network partition. */ CompletableFuture<Ack> heartBeatFromTaskExecutor(TaskExecutorHeartbeat heartbeat); /** * Triggered whenever the task executor gets occupied with a worker request or is available to do some work */ CompletableFuture<Ack> notifyTaskExecutorStatusChange(TaskExecutorStatusChange taskExecutorStatusChange); /** * Triggered by the task executor when it's about to shut itself down. */ CompletableFuture<Ack> disconnectTaskExecutor(TaskExecutorDisconnection taskExecutorDisconnection); /** * Exception thrown by the resource cluster whenever anyone of the state transitions of the task executor are invalid. * Note that the exception generally gets wrapped inside {@link java.util.concurrent.CompletionException}. */ class InvalidStateTransitionException extends Exception { public InvalidStateTransitionException(String message) { super(message); } } }
8,277
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/master/resourcecluster/TaskExecutorReport.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.master.resourcecluster; import io.mantisrx.server.core.domain.WorkerId; import io.mantisrx.server.master.resourcecluster.TaskExecutorReport.Available; import io.mantisrx.server.master.resourcecluster.TaskExecutorReport.Occupied; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonSubTypes; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonSubTypes.Type; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonTypeInfo; import lombok.Value; /** * Current state of the task executor. This is a union of two possible states. * 1. Available when the task executor is capable of taking some work. * 2. Occupied when the task executor is already doing some work. */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = Available.class, name = "available"), @Type(value = Occupied.class, name = "occupied") }) public interface TaskExecutorReport { @Value class Available implements TaskExecutorReport {} @Value class Occupied implements TaskExecutorReport { WorkerId workerId; } static Available available() { return new Available(); } static Occupied occupied(WorkerId workerId) { return new Occupied(workerId); } }
8,278
0
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server
Create_ds/mantis/mantis-control-plane/mantis-control-plane-core/src/main/java/io/mantisrx/server/worker/TaskExecutorGateway.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.worker; import io.mantisrx.common.Ack; import io.mantisrx.server.core.CacheJobArtifactsRequest; import io.mantisrx.server.core.ExecuteStageRequest; import io.mantisrx.server.core.domain.WorkerId; import java.util.concurrent.CompletableFuture; import org.apache.flink.runtime.rpc.RpcGateway; /** * Gateway to talk to the task executor running on the mantis-agent. */ public interface TaskExecutorGateway extends RpcGateway { /** * submit a new task to be run on the task executor. The definition of the task is represented by * {@link ExecuteStageRequest}. * * @param request Task that needs to be run on the executor. * @return Ack to indicate that the gateway was able to receive the task. * @throws TaskAlreadyRunningException wrapped inside {@link java.util.concurrent.CompletionException} * in case there's already an existing task that's running on the task executor. */ CompletableFuture<Ack> submitTask(ExecuteStageRequest request); /** * instruct the task executor on which job artifacts to cache in order to speed up job initialization time. * * @param request List of job artifacts that need to be cached. * @return Ack in any case (this task is best effort). */ CompletableFuture<Ack> cacheJobArtifacts(CacheJobArtifactsRequest request); /** * cancel the currently running task and get rid of all of the associated resources. * * @param workerId of the task that needs to be cancelled. * @return Ack to indicate that the gateway was able to receive the request and the worker ID represents the currently * running task. * @throws TaskNotFoundException wrapped inside a {@link java.util.concurrent.CompletionException} in case * workerId is not running on the executor. */ CompletableFuture<Ack> cancelTask(WorkerId workerId); /** * request a thread dump on the worker to see what threads are running on it. * * @return thread dump in the string format. */ CompletableFuture<String> requestThreadDump(); CompletableFuture<Boolean> isRegistered(); class TaskAlreadyRunningException extends Exception { private static final long serialVersionUID = 1L; private final WorkerId currentlyRunningWorkerTask; public TaskAlreadyRunningException(WorkerId workerId) { this(workerId, null); } public TaskAlreadyRunningException(WorkerId workerId, Throwable cause) { super(cause); this.currentlyRunningWorkerTask = workerId; } } class TaskNotFoundException extends Exception { private static final long serialVersionUID = 1L; public TaskNotFoundException(WorkerId workerId) { this(workerId, null); } public TaskNotFoundException(WorkerId workerId, Throwable cause) { super(String.format("Task %s not found", workerId.toString()), cause); } } }
8,279
0
Create_ds/mantis/mantis-publish/mantis-publish-netty-guice/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty-guice/src/test/java/io/mantisrx/publish/netty/guice/LocalMantisPublishTester.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.publish.netty.guice; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.spectator.nflx.SpectatorModule; import io.mantisrx.publish.api.EventPublisher; import org.junit.jupiter.api.Test; public class LocalMantisPublishTester { @Test public void injectionTest() { try { Injector injector = Guice.createInjector(new ArchaiusModule(), new MantisRealtimeEventsPublishModule(), new SpectatorModule()); EventPublisher publisher = injector.getInstance(EventPublisher.class); /// FOR local testing uncomment // for(int i=0; i<100; i++) { // Map<String,Object> event = new HashMap<>(); // event.put("id",i); // CompletionStage<PublishStatus> sendStatus = publisher.publish("requestEventStream", new Event(event)); // sendStatus.whenCompleteAsync((status, throwable) -> { // System.out.println("Send status => " + status); // }); // Thread.sleep(1000); // } assertNotNull(publisher); } catch(Exception e) { fail(); } } }
8,280
0
Create_ds/mantis/mantis-publish/mantis-publish-netty-guice/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty-guice/src/main/java/io/mantisrx/publish/netty/guice/MantisRealtimeEventsPublishModule.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.publish.netty.guice; import com.google.inject.AbstractModule; import com.netflix.archaius.api.PropertyRepository; import com.netflix.spectator.api.Registry; import com.netflix.spectator.ipc.http.HttpClient; import io.mantisrx.publish.DefaultSubscriptionTracker; import io.mantisrx.publish.EventChannel; import io.mantisrx.publish.EventTransmitter; import io.mantisrx.publish.MrePublishClientInitializer; import io.mantisrx.publish.StreamManager; import io.mantisrx.publish.SubscriptionTracker; import io.mantisrx.publish.Tee; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.config.MrePublishConfiguration; import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration; import io.mantisrx.publish.internal.discovery.MantisJobDiscovery; import io.mantisrx.publish.netty.pipeline.HttpEventChannel; import io.mantisrx.publish.netty.pipeline.HttpEventChannelManager; import io.mantisrx.publish.netty.transmitters.ChoiceOfTwoEventTransmitter; import io.mantisrx.publish.providers.EventPublisherProvider; import io.mantisrx.publish.providers.MantisJobDiscoveryProvider; import io.mantisrx.publish.providers.MrePublishClientInitializerProvider; import io.mantisrx.publish.providers.StreamManagerProvider; import io.mantisrx.publish.providers.TeeProvider; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; public class MantisRealtimeEventsPublishModule extends AbstractModule { @Singleton private static class EventTransmitterProvider implements Provider<EventTransmitter> { private final MrePublishConfiguration configuration; private final Registry registry; private final MantisJobDiscovery jobDiscovery; @Inject public EventTransmitterProvider( MrePublishConfiguration configuration, Registry registry, MantisJobDiscovery jobDiscovery) { this.configuration = configuration; this.registry = registry; this.jobDiscovery = jobDiscovery; } @Override public EventTransmitter get() { HttpEventChannelManager channelManager = new HttpEventChannelManager(registry, configuration); EventChannel eventChannel = new HttpEventChannel(registry, channelManager); return new ChoiceOfTwoEventTransmitter(configuration, registry, jobDiscovery, eventChannel); } } @Singleton private static class SubscriptionTrackerProvider implements Provider<SubscriptionTracker> { private final MrePublishConfiguration configuration; private final Registry registry; private final StreamManager streamManager; private final MantisJobDiscovery jobDiscovery; @Inject public SubscriptionTrackerProvider( MrePublishConfiguration configuration, Registry registry, StreamManager streamManager, MantisJobDiscovery jobDiscovery) { this.configuration = configuration; this.registry = registry; this.streamManager = streamManager; this.jobDiscovery = jobDiscovery; } @Override public SubscriptionTracker get() { return new DefaultSubscriptionTracker( configuration, registry, jobDiscovery, streamManager, HttpClient.create(registry)); } } @Singleton private static class MrePublishConfigProvider implements Provider<MrePublishConfiguration> { private final PropertyRepository propertyRepository; @Inject public MrePublishConfigProvider(PropertyRepository propertyRepository) { this.propertyRepository = propertyRepository; } @Override public MrePublishConfiguration get() { return new SampleArchaiusMrePublishConfiguration(propertyRepository); } } @Override protected void configure() { bind(MrePublishConfiguration.class).toProvider(MrePublishConfigProvider.class).asEagerSingleton(); bind(StreamManager.class).toProvider(StreamManagerProvider.class).asEagerSingleton(); bind(EventPublisher.class).toProvider(EventPublisherProvider.class).asEagerSingleton(); bind(MantisJobDiscovery.class).toProvider(MantisJobDiscoveryProvider.class).asEagerSingleton(); bind(EventTransmitter.class).toProvider(EventTransmitterProvider.class).asEagerSingleton(); bind(Tee.class).toProvider(TeeProvider.class).asEagerSingleton(); bind(SubscriptionTracker.class).toProvider(SubscriptionTrackerProvider.class).asEagerSingleton(); bind(MrePublishClientInitializer.class).toProvider(MrePublishClientInitializerProvider.class).asEagerSingleton(); } }
8,281
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/LocalMrePublishClientInitializer.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.publish.netty; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.api.PropertyRepository; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.ipc.http.HttpClient; import io.mantisrx.discovery.proto.JobDiscoveryInfo; import io.mantisrx.discovery.proto.MantisWorker; import io.mantisrx.discovery.proto.StageWorkers; import io.mantisrx.publish.DefaultSubscriptionTracker; import io.mantisrx.publish.EventChannel; import io.mantisrx.publish.EventTransmitter; import io.mantisrx.publish.MantisEventPublisher; import io.mantisrx.publish.MrePublishClientInitializer; import io.mantisrx.publish.StreamManager; import io.mantisrx.publish.SubscriptionTracker; import io.mantisrx.publish.Tee; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.api.EventPublisher; import io.mantisrx.publish.api.StreamType; import io.mantisrx.publish.config.MrePublishConfiguration; import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration; import io.mantisrx.publish.internal.discovery.MantisJobDiscovery; import io.mantisrx.publish.netty.pipeline.HttpEventChannel; import io.mantisrx.publish.netty.pipeline.HttpEventChannelManager; import io.mantisrx.publish.netty.transmitters.ChoiceOfTwoEventTransmitter; import io.netty.util.ResourceLeakDetector; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class LocalMrePublishClientInitializer { private static final Map<String, String> streamJobClusterMap = Collections.singletonMap(StreamType.DEFAULT_EVENT_STREAM, "StartPlayLogBlobSource2-4"); private static MrePublishConfiguration testConfig() { DefaultSettableConfig settableConfig = new DefaultSettableConfig(); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.DEFAULT_EVENT_STREAM, streamJobClusterMap.get(StreamType.DEFAULT_EVENT_STREAM)); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_REFRESH_INTERVAL_SEC_PROP, 5); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP, 5); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_HOSTNAME_PROP, "127.0.0.1"); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_PORT_PROP, 9090); settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.CHANNEL_GZIP_ENABLED_PROP, true); PropertyRepository propertyRepository = DefaultPropertyFactory.from(settableConfig); return new SampleArchaiusMrePublishConfiguration(propertyRepository); } private static MantisJobDiscovery createJobDiscovery() { MantisJobDiscovery jobDiscovery = mock(MantisJobDiscovery.class); when(jobDiscovery.getCurrentJobWorkers(anyString())) .thenReturn( Optional.of(new JobDiscoveryInfo( "cluster", "id", Collections.singletonMap( 1, new StageWorkers( "cluster", "id", 1, Collections.singletonList( new MantisWorker("127.0.0.1", 9090) ) ) ) ) ) ); return jobDiscovery; } public static void main(String[] args) throws InterruptedException { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); MrePublishConfiguration mrePublishConfiguration = testConfig(); Registry registry = new DefaultRegistry(); HttpClient httpClient = HttpClient.create(registry); MantisJobDiscovery jobDiscovery = createJobDiscovery(); StreamManager streamManager = new StreamManager(registry, mrePublishConfiguration); MantisEventPublisher mantisEventPublisher = new MantisEventPublisher(mrePublishConfiguration, streamManager); SubscriptionTracker subscriptionsTracker = new DefaultSubscriptionTracker(mrePublishConfiguration, registry, jobDiscovery, streamManager, httpClient); HttpEventChannelManager channelManager = new HttpEventChannelManager(registry, mrePublishConfiguration); EventChannel eventChannel = new HttpEventChannel(registry, channelManager); EventTransmitter transmitter = new ChoiceOfTwoEventTransmitter(mrePublishConfiguration, registry, jobDiscovery, eventChannel); Tee tee = mock(Tee.class); doNothing().when(tee).tee(anyString(), any(Event.class)); MrePublishClientInitializer mreClient = new MrePublishClientInitializer( mrePublishConfiguration, registry, streamManager, mantisEventPublisher, subscriptionsTracker, transmitter, tee); mreClient.start(); EventPublisher eventPublisher = mreClient.getEventPublisher(); // Periodically publish a test event final Event event = new Event(); final CountDownLatch latch = new CountDownLatch(1000); event.set("testKey", "testValue"); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "EventPublisherTest")); ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(() -> { eventPublisher.publish(event); latch.countDown(); }, 1, 1, TimeUnit.SECONDS); latch.await(); if (!scheduledFuture.isCancelled()) { scheduledFuture.cancel(true); } mreClient.stop(); } }
8,282
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/pipeline/HttpEventChannelTest.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.publish.netty.pipeline; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import io.mantisrx.discovery.proto.MantisWorker; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.netty.proto.MantisEvent; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import java.net.InetSocketAddress; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HttpEventChannelTest { private static MantisWorker mantisWorker; private HttpEventChannelManager channelManager; private HttpEventChannel eventChannel; private Channel channel; @BeforeAll static void setupAll() { mantisWorker = new MantisWorker("127.0.0.1", 9090); } @BeforeEach void setup() { Registry registry = new DefaultRegistry(); channelManager = mock(HttpEventChannelManager.class); channel = mock(Channel.class); when(channel.writeAndFlush(any(MantisEvent.class))).thenReturn(mock(ChannelFuture.class)); when(channel.write(any(MantisEvent.class))).thenReturn(mock(ChannelFuture.class)); when(channelManager.findOrCreate(any(InetSocketAddress.class))).thenReturn(channel); eventChannel = new HttpEventChannel(registry, channelManager); } @Test void shouldWriteOverActiveAndWritableChannel() { when(channel.isActive()).thenReturn(true); when(channel.isWritable()).thenReturn(true); when(channel.bytesBeforeUnwritable()).thenReturn(10L); eventChannel.send(mantisWorker, new Event()); verify(channel, times(1)).writeAndFlush(any(MantisEvent.class)); } @Test void shouldNotWriteOverInactiveChannel() { when(channel.isActive()).thenReturn(false); when(channel.isWritable()).thenReturn(true); eventChannel.send(mantisWorker, new Event()); verify(channel, times(0)).writeAndFlush(any(MantisEvent.class)); } @Test void shouldNotWriteOverActiveAndUnwritableChannel() { when(channel.isActive()).thenReturn(true); when(channel.isWritable()).thenReturn(false); eventChannel.send(mantisWorker, new Event()); verify(channel, times(0)).writeAndFlush(any(MantisEvent.class)); } }
8,283
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/pipeline/GzipEncoderTest.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.publish.netty.pipeline; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.netflix.spectator.api.DefaultRegistry; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class GzipEncoderTest { private ChannelHandlerContext ctx; private GzipEncoder encoder; private List<Object> out; @BeforeEach void setup() { ctx = mock(ChannelHandlerContext.class); when(ctx.alloc()).thenReturn(ByteBufAllocator.DEFAULT); out = new ArrayList<>(); encoder = new GzipEncoder(new DefaultRegistry()); } @AfterEach void teardown() { out.clear(); ctx.alloc().buffer().release(); } @Test void shouldCompressFullHttpRequest() throws IOException { FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "http://127.0.0.1:9090"); request.content().writeBytes(new byte[1024]); int uncompressedSize = request.content().readableBytes(); encoder.encode(ctx, request, out); assertFalse(out.isEmpty()); FullHttpRequest result = (FullHttpRequest) out.get(0); int compressedSize = result.content().readableBytes(); assertTrue(uncompressedSize > compressedSize); byte[] b = new byte[result.content().readableBytes()]; result.content().readBytes(b); // Check first byte is from valid magic byte from GZIP header. assertEquals((byte) 0x8b1f, b[0]); } }
8,284
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/pipeline/MantisEventAggregatorTest.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.publish.netty.pipeline; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.netflix.spectator.api.DefaultRegistry; import io.mantisrx.publish.netty.proto.MantisEvent; import io.mantisrx.publish.netty.proto.MantisEventEnvelope; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import java.io.IOException; import java.net.InetSocketAddress; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MantisEventAggregatorTest { private Clock clock; private ChannelHandlerContext ctx; private MantisEventAggregator aggregator; @BeforeEach void setup() { ctx = mock(ChannelHandlerContext.class); clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); aggregator = new MantisEventAggregator(new DefaultRegistry(), clock, true, 50, 10); Channel channel = mock(Channel.class); when(ctx.channel()).thenReturn(channel); ChannelPromise promise = mock(ChannelPromise.class); when(ctx.channel().voidPromise()).thenReturn(promise); when(ctx.channel().remoteAddress()).thenReturn(new InetSocketAddress("127.0.0.1", 9090)); when(ctx.alloc()).thenReturn(mock(PooledByteBufAllocator.class)); when(ctx.alloc().directBuffer()).thenReturn(mock(ByteBuf.class)); when(ctx.writeAndFlush(any(FullHttpRequest.class))).thenReturn(mock(ChannelFuture.class)); } @Test void shouldBuildValidHeaders() throws IOException { MantisEventEnvelope envelope = new MantisEventEnvelope(clock.millis(), "origin", new ArrayList<>()); envelope.addEvent(new MantisEvent(1, "v")); FullHttpRequest request = aggregator.buildRequest(ctx, envelope); HttpHeaders expectedHeaders = new DefaultHttpHeaders(); expectedHeaders.add(HttpHeaderNames.ACCEPT, HttpHeaderValues.APPLICATION_JSON); expectedHeaders.add(HttpHeaderNames.ORIGIN, "localhost"); request.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); expectedHeaders.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); // Netty wraps and overrides String#equals type with its own StringEntry. for (int i = 0; i < expectedHeaders.entries().size(); i++) { assertEquals( expectedHeaders.entries().get(i).getKey(), request.headers().entries().get(i).getKey()); assertEquals( expectedHeaders.entries().get(i).getValue(), request.headers().entries().get(i).getValue()); } } @Test void shouldForwardMessageAboveSizeThreshold() { MantisEvent event = new MantisEvent(1, "12345"); aggregator.write(ctx, event, ctx.channel().voidPromise()); aggregator.write(ctx, event, ctx.channel().voidPromise()); // message1 + message2 > 10 Bytes; forwards message1, clear state, and add message2. verify(ctx, times(1)).writeAndFlush(any(FullHttpRequest.class)); } @Test void shouldBatchMessagesBelowSizeThreshold() { MantisEvent event = new MantisEvent(1, "12345"); aggregator.write(ctx, event, ctx.channel().voidPromise()); // message1 < 10 Bytes; hold until size threshold (or timeout) reached. // Also forwards the original promise. verify(ctx, times(0)).write(any(FullHttpRequest.class), any()); } @Test void shouldForwardUnacceptedMessage() { aggregator.write(ctx, new byte[1], ctx.channel().voidPromise()); verify(ctx, times(1)).write(any(), any()); } @Test void shouldForwardOversizedMessages() { MantisEvent event = new MantisEvent(1, Arrays.toString(new byte[11])); // message1 > 10 Bytes; don't propagate an exception to the caller (so we don't // close the connection), but instead warn. aggregator.write(ctx, event, ctx.channel().voidPromise()); verify(ctx, times(1)).writeAndFlush(any(FullHttpRequest.class)); } }
8,285
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/pipeline/HttpEventChannelInitializerTest.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.publish.netty.pipeline; import static org.mockito.Mockito.mock; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import io.mantisrx.publish.config.MrePublishConfiguration; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HttpEventChannelInitializerTest { private Channel channel; private HttpEventChannelInitializer initializer; @BeforeEach void setup() { Registry registry = new DefaultRegistry(); MrePublishConfiguration config = mock(MrePublishConfiguration.class); channel = new EmbeddedChannel(); initializer = new HttpEventChannelInitializer(registry, config, mock(EventLoopGroup.class)); } @Test void shouldInitializeChannelPipelineWithExpectedHandlers() { List<String> expected = Arrays.asList( "LoggingHandler#0", "http-client-codec", "gzip-encoder", "http-object-aggregator", "write-timeout-handler", "mantis-event-aggregator", "idle-channel-handler", "event-channel-handler", "DefaultChannelPipeline$TailContext#0"); initializer.initChannel(channel); Assertions.assertTrue(expected.containsAll(channel.pipeline().names())); } }
8,286
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/pipeline/MantisMessageSizeEstimatorTest.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.publish.netty.pipeline; import static org.junit.jupiter.api.Assertions.assertEquals; import io.mantisrx.publish.netty.proto.MantisEvent; import io.mantisrx.publish.proto.MantisServerSubscription; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.MessageSizeEstimator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class MantisMessageSizeEstimatorTest { private MessageSizeEstimator estimator; private MessageSizeEstimator.Handle handle; @BeforeEach void setup() { estimator = MantisMessageSizeEstimator.DEFAULT; handle = estimator.newHandle(); } @Test void shouldReturnSizeForMantisMessage() { MantisEvent event = new MantisEvent(1, "v"); assertEquals(5, handle.size(event)); } @Test void shouldReturnSizeForNettyByteBuf() { ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); buf.writeByte(1); assertEquals(1, buf.readableBytes()); buf.release(); } @Test void shouldReturnUnknownSizeForUnsupportedObject() { MantisServerSubscription subscription = Mockito.mock(MantisServerSubscription.class); // Delegate to Netty's default handle which returns 8 for unknown size // since our handle (nor Netty's) knows how to estimate a MantisServerSubscription object. assertEquals(8, handle.size(subscription)); } }
8,287
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/proto/MantisEnvelopeTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.publish.netty.proto; import static org.junit.jupiter.api.Assertions.fail; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectReader; import org.junit.jupiter.api.Test; public class MantisEnvelopeTest { @Test public void deserTest() { String data = "{\"ts\":1571174446676,\"originServer\":\"origin\",\"eventList\":[{\"id\":1,\"data\":\"{\\\"mantisStream\\\":\\\"defaultStream\\\",\\\"matched-clients\\\":[\\\"MantisPushRequestEvents_PushRequestEventSourceJobLocal-1_nj3\\\"],\\\"id\\\":44,\\\"type\\\":\\\"EVENT\\\"}\"}]}"; final ObjectMapper mapper = new ObjectMapper(); ObjectReader mantisEventEnvelopeReader = mapper.readerFor(MantisEventEnvelope.class); try { MantisEventEnvelope envelope = mantisEventEnvelopeReader.readValue(data); System.out.println("Envelope=>" + envelope); } catch (JsonProcessingException e) { e.printStackTrace(); fail(); } } }
8,288
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/test/java/io/mantisrx/publish/netty/transmitters/ChoiceOfTwoWorkerPoolTest.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.publish.netty.transmitters; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import io.mantisrx.discovery.proto.MantisWorker; import io.mantisrx.publish.EventChannel; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.config.MrePublishConfiguration; import io.mantisrx.publish.internal.exceptions.NonRetryableException; import io.mantisrx.publish.internal.exceptions.RetryableException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ChoiceOfTwoWorkerPoolTest { private ChoiceOfTwoWorkerPool workerPool; private MrePublishConfiguration config; private Registry registry; @BeforeEach void setUp() { config = mock(MrePublishConfiguration.class); when(config.getWorkerPoolRefreshIntervalSec()).thenReturn(-1); registry = new NoopRegistry(); when(config.getWorkerPoolCapacity()).thenReturn(2); when(config.getWorkerPoolWorkerErrorQuota()).thenReturn(2); workerPool = new ChoiceOfTwoWorkerPool(config, registry, mock(EventChannel.class)); } @AfterEach void tearDown() { } @Test void shouldRefreshEmptyPool() { List<MantisWorker> freshWorkers = Collections.singletonList(mock(MantisWorker.class)); workerPool.refresh(freshWorkers); assertEquals(1, workerPool.size()); } @Test void shouldRefreshPoolOnNonexistentWorker() { MantisWorker nonExistentWorker = mock(MantisWorker.class); when(nonExistentWorker.getHost()).thenReturn("1.1.1.1"); MantisWorker newWorker = mock(MantisWorker.class); when(newWorker.getHost()).thenReturn("1.1.1.2"); List<MantisWorker> freshWorkers = Collections.singletonList(nonExistentWorker); workerPool.refresh(freshWorkers); assertEquals(1, workerPool.size()); freshWorkers = Collections.singletonList(newWorker); workerPool.refresh(freshWorkers); assertEquals(1, workerPool.size()); assertEquals(newWorker, workerPool.getRandomWorker()); } @Test void shouldForceRefreshFullPool() { when(config.getWorkerPoolCapacity()).thenReturn(1); when(config.getWorkerPoolWorkerErrorQuota()).thenReturn(1); workerPool = new ChoiceOfTwoWorkerPool(config, registry, mock(EventChannel.class)); MantisWorker worker = mock(MantisWorker.class); List<MantisWorker> freshWorkers = Collections.singletonList(worker); workerPool.refresh(freshWorkers); workerPool.refresh(freshWorkers, true); assertEquals(0, workerPool.getWorkerErrors(worker)); } @Test void shouldNotRefreshFullAndHealthyPool() throws NonRetryableException { when(config.getWorkerPoolCapacity()).thenReturn(1); when(config.getWorkerPoolWorkerErrorQuota()).thenReturn(1); workerPool = new ChoiceOfTwoWorkerPool(config, registry, mock(EventChannel.class)); MantisWorker worker = mock(MantisWorker.class); List<MantisWorker> freshWorkers = Collections.singletonList(worker); CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(new RetryableException("expected test exception")); workerPool.refresh(freshWorkers); CompletableFuture<Void> future = workerPool.record(mock(Event.class), (w, e) -> completableFuture); future.whenComplete((v, t) -> { // Fresh workers haven't changed (i.e., haven't scaled up or down) and workers in the pool aren't blacklisted. workerPool.refresh(freshWorkers); // Check to see if the same worker, with the same number of errors still exists. assertEquals(1, workerPool.getWorkerErrors(worker)); }); } @Test void shouldGetRandomWorkerFromPool() { List<MantisWorker> freshWorkers = Collections.singletonList(mock(MantisWorker.class)); workerPool.refresh(freshWorkers); assertNotNull(workerPool.getRandomWorker()); freshWorkers = Arrays.asList(mock(MantisWorker.class), mock(MantisWorker.class)); workerPool.refresh(freshWorkers); assertNotNull(workerPool.getRandomWorker()); } @Test void shouldNotGetRandomWorkerFromEmptyPool() { assertNull(workerPool.getRandomWorker()); } @Test void shouldNotRecordOnEmptyPool() { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.complete(null); assertThrows( NonRetryableException.class, () -> workerPool.record(mock(Event.class), (w, e) -> completableFuture)); } @Test void shouldRecordOnHealthyPool() { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.complete(null); List<MantisWorker> freshWorkers = Collections.singletonList(mock(MantisWorker.class)); workerPool.refresh(freshWorkers); Assertions.assertDoesNotThrow(() -> workerPool.record(mock(Event.class), (w, e) -> completableFuture).get()); } @Test void shouldRecordAndIncrementError() throws NonRetryableException { MantisWorker worker = mock(MantisWorker.class); List<MantisWorker> freshWorkers = Collections.singletonList(worker); CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(new RetryableException("expected test exception")); workerPool.refresh(freshWorkers); CompletableFuture<Void> future = workerPool.record(mock(Event.class), (w, e) -> completableFuture); future.whenComplete((v, t) -> assertEquals(1, workerPool.getWorkerErrors(worker))); } @Test void shouldRecordAndImmediatelyBlacklist() throws NonRetryableException { when(config.getWorkerPoolCapacity()).thenReturn(1); when(config.getWorkerPoolWorkerErrorQuota()).thenReturn(1); workerPool = new ChoiceOfTwoWorkerPool(config, registry, mock(EventChannel.class)); MantisWorker worker = mock(MantisWorker.class); List<MantisWorker> freshWorkers = Collections.singletonList(worker); CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(new RetryableException("expected test exception")); workerPool.refresh(freshWorkers); CompletableFuture<Void> future = workerPool.record(mock(Event.class), (w, e) -> completableFuture); future.whenComplete((v, t) -> { assertEquals(1, workerPool.size()); assertFalse(workerPool.isBlacklisted(worker)); }); future = workerPool.record(mock(Event.class), (w, e) -> completableFuture); future.whenComplete((v, t) -> assertEquals(0, workerPool.size())); } }
8,289
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/HttpEventChannelInitializer.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.publish.netty.pipeline; import com.netflix.spectator.api.Registry; import io.mantisrx.publish.config.MrePublishConfiguration; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import java.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class HttpEventChannelInitializer extends ChannelInitializer<Channel> { private static final Logger LOG = LoggerFactory.getLogger(HttpEventChannel.class); private final Registry registry; private final boolean gzipEnabled; private final long flushIntervalMs; private final int flushIntervalBytes; private final int idleTimeoutSeconds; private final int httpChunkSize; private final int writeTimeoutSeconds; private final EventLoopGroup encoderEventLoopGroup; HttpEventChannelInitializer( Registry registry, MrePublishConfiguration config, EventLoopGroup encoderEventLoopGroup) { this.registry = registry; this.gzipEnabled = config.getGzipEnabled(); this.idleTimeoutSeconds = config.getIdleTimeoutSeconds(); this.httpChunkSize = config.getHttpChunkSize(); this.writeTimeoutSeconds = config.getWriteTimeoutSeconds(); this.flushIntervalMs = config.getFlushIntervalMs(); this.flushIntervalBytes = config.getFlushIntervalBytes(); this.encoderEventLoopGroup = encoderEventLoopGroup; } @Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast( new LoggingHandler()); pipeline.addLast("http-client-codec", new HttpClientCodec()); if (gzipEnabled) { pipeline.addLast(encoderEventLoopGroup, "gzip-encoder", new GzipEncoder(registry)); } pipeline.addLast("http-object-aggregator", new HttpObjectAggregator(httpChunkSize)); pipeline.addLast("write-timeout-handler", new WriteTimeoutHandler(writeTimeoutSeconds)); pipeline.addLast("mantis-event-aggregator", new MantisEventAggregator( registry, Clock.systemUTC(), gzipEnabled, flushIntervalMs, flushIntervalBytes)); pipeline.addLast("idle-channel-handler", new IdleStateHandler(0, idleTimeoutSeconds, 0)); pipeline.addLast("event-channel-handler", new HttpEventChannelHandler(registry)); LOG.debug("initializing channel with pipeline: {}", pipeline.toMap()); } }
8,290
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/MantisMessageSizeEstimator.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.publish.netty.pipeline; import io.mantisrx.publish.netty.proto.MantisEvent; import io.netty.channel.DefaultMessageSizeEstimator; import io.netty.channel.MessageSizeEstimator; import io.netty.channel.WriteBufferWaterMark; import io.netty.handler.codec.MessageToMessageEncoder; /** * This class implements Netty's {@link MessageSizeEstimator} interface so it can be used by * a {@link MessageToMessageEncoder} to estimate the size of an object. This makes {@link MantisEvent}s compatible * with checking against Netty's {@link WriteBufferWaterMark}. Netty otherwise doesn't know how to estimate the * size of objects unfamiliar objects. */ final class MantisMessageSizeEstimator implements MessageSizeEstimator { /** * Return the default implementation which returns {@code 8} for unknown messages. */ static final MessageSizeEstimator DEFAULT = new MantisMessageSizeEstimator(); private static final DefaultMessageSizeEstimator.Handle NETTY_DEFAULT_HANDLE = new DefaultMessageSizeEstimator(8).newHandle(); private final Handle handle; /** * Create a new instance. */ private MantisMessageSizeEstimator() { handle = new HandleImpl(); } @Override public Handle newHandle() { return handle; } private static final class HandleImpl implements Handle { @Override public int size(Object msg) { if (msg instanceof MantisEvent) { return ((MantisEvent) msg).size(); } return NETTY_DEFAULT_HANDLE.size(msg); } } }
8,291
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/GzipEncoder.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.publish.netty.pipeline; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import io.netty.handler.codec.http.FullHttpRequest; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; class GzipEncoder extends MessageToMessageEncoder<FullHttpRequest> { private final Registry registry; private final Timer encodeTime; GzipEncoder(Registry registry) { this.registry = registry; this.encodeTime = SpectatorUtils.buildAndRegisterTimer( registry, "encodeTime", "channel", HttpEventChannel.CHANNEL_TYPE, "encoder", "gzip"); } @Override protected void encode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) { final long start = registry.clock().wallTime(); ByteBuf buf = ctx.alloc().directBuffer(); try ( ByteBufOutputStream bbos = new ByteBufOutputStream(buf); GZIPOutputStream gos = new GZIPOutputStream(bbos) ) { msg.content().readBytes(gos, msg.content().readableBytes()); gos.finish(); FullHttpRequest message = msg.replace(buf.retain()); out.add(message); } catch (Exception e) { ctx.fireExceptionCaught(new IOException("error encoding message", e)); } finally { buf.release(); } final long end = registry.clock().wallTime(); encodeTime.record(end - start, TimeUnit.MILLISECONDS); } }
8,292
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/MantisEventAggregator.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.publish.netty.pipeline; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.spectator.impl.AtomicDouble; import io.mantisrx.publish.internal.exceptions.RetryableException; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.mantisrx.publish.netty.proto.MantisEvent; import io.mantisrx.publish.netty.proto.MantisEventEnvelope; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectWriter; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; import java.time.Clock; import java.util.ArrayList; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Aggregates {@link MantisEvent}s for a configurable amount of time or size. After either time or size threshold * is met, this class will batch up the events into a {@link MantisEventEnvelope} and set that as a HTTP request * body, specifically within {@link FullHttpRequest#content()} as a {@link ByteBuf}. */ class MantisEventAggregator extends ChannelOutboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(MantisEventAggregator.class); private final Clock clock; private final Timer batchFlushTime; private final Counter droppedBatches; private final Counter flushSuccess; private final Counter flushFailure; private final AtomicDouble batchSize; private final ObjectWriter objectWriter; private final boolean compress; private ScheduledFuture<?> writerTimeout; private long flushIntervalMs; private int flushIntervalBytes; private MantisEventEnvelope currentMessage; private int currentMessageSize; /** * Creates a new instance. */ MantisEventAggregator(Registry registry, Clock clock, boolean compress, long flushIntervalMs, int flushIntervalBytes) { this.clock = clock; this.batchFlushTime = SpectatorUtils.buildAndRegisterTimer( registry, "batchFlushTime", "channel", HttpEventChannel.CHANNEL_TYPE); this.droppedBatches = SpectatorUtils.buildAndRegisterCounter( registry, "droppedBatches", "channel", HttpEventChannel.CHANNEL_TYPE); this.flushSuccess = SpectatorUtils.buildAndRegisterCounter( registry, "flushSuccess", "channel", HttpEventChannel.CHANNEL_TYPE); this.flushFailure = SpectatorUtils.buildAndRegisterCounter( registry, "flushFailure", "channel", HttpEventChannel.CHANNEL_TYPE); this.batchSize = SpectatorUtils.buildAndRegisterGauge( registry, "batchSize", "channel", HttpEventChannel.CHANNEL_TYPE); this.flushIntervalMs = flushIntervalMs; this.flushIntervalBytes = flushIntervalBytes; this.compress = compress; this.objectWriter = new ObjectMapper().writer(); this.currentMessage = new MantisEventEnvelope( clock.millis(), "origin", // TODO: Get origin from context. new ArrayList<>()); } private boolean acceptOutboundMessage(Object msg) { return msg instanceof MantisEvent; } /** * Writes a message into an internal buffer and returns a promise. * <p> * If it's not time to write a batch, then return a {@code successful} promise. * If it's time to write a batch, then return the promise resulting from the batch write operation, * which could be {@code successful} or {@code failure}. */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (acceptOutboundMessage(msg)) { MantisEvent event = (MantisEvent) msg; int eventSize = event.size(); if (currentMessageSize + eventSize > flushIntervalBytes) { writeBatch(ctx, promise); } else { promise.setSuccess(); } currentMessage.addEvent(event); currentMessageSize += event.size(); } else { ctx.write(msg, promise); } } @Override public void handlerAdded(ChannelHandlerContext ctx) { writerTimeout = ctx.executor() .scheduleAtFixedRate( new WriterTimeoutTask(ctx), flushIntervalMs, flushIntervalMs, TimeUnit.MILLISECONDS); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (writerTimeout != null) { writerTimeout.cancel(false); writerTimeout = null; } } /** * Aggregates {@link MantisEvent}s into a {@link MantisEventEnvelope} and packages it up into a * {@link FullHttpRequest} to be sent to the next channel handler in the pipeline. * <p> * This method will set the status of the promise based on the * result of the {@link ChannelHandlerContext#writeAndFlush(Object)} operation. */ void writeBatch(ChannelHandlerContext ctx, ChannelPromise promise) { try { FullHttpRequest request = buildRequest(ctx, currentMessage); int eventListSize = currentMessage.getEventList().size(); batchSize.set((double) eventListSize); final long start = clock.millis(); ctx.writeAndFlush(request).addListener(future -> { final long end = clock.millis(); batchFlushTime.record(end - start, TimeUnit.MILLISECONDS); if (future.isSuccess()) { promise.setSuccess(); flushSuccess.increment(); } else { promise.setFailure(new RetryableException(future.cause().getMessage())); flushFailure.increment(); } }); } catch (IOException e) { LOG.debug("unable to serialize batch", e); droppedBatches.increment(); ctx.fireExceptionCaught(e); } finally { currentMessage = new MantisEventEnvelope( clock.millis(), "origin", // TODO: Get origin from context. new ArrayList<>()); currentMessageSize = 0; } } /** * Returns a {@link FullHttpRequest} with headers, body, and event timestamp set. */ FullHttpRequest buildRequest(ChannelHandlerContext ctx, MantisEventEnvelope event) throws IOException { InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); String urlString = "http://" + address.getHostString() + ':' + address.getPort() + "/api/v1/events"; URI uri = URI.create(urlString); FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), ctx.alloc().directBuffer()); request.headers().add(HttpHeaderNames.ACCEPT, HttpHeaderValues.APPLICATION_JSON); request.headers().add(HttpHeaderNames.ORIGIN, "localhost"); if (compress) { request.headers().add(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP); } request.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); event.setTs(clock.millis()); try (OutputStream bbos = new ByteBufOutputStream(request.content())) { objectWriter.writeValue(bbos, event); } return request; } private class WriterTimeoutTask implements Runnable { private final ChannelHandlerContext ctx; WriterTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() { if (!ctx.channel().isActive()) { LOG.debug("channel not active"); return; } if (ctx.channel().isWritable() && currentMessage != null && currentMessageSize != 0) { writeBatch(ctx, ctx.channel().newPromise()); } } } }
8,293
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/HttpEventChannel.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.publish.netty.pipeline; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import io.mantisrx.discovery.proto.MantisWorker; import io.mantisrx.publish.EventChannel; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.internal.exceptions.NonRetryableException; import io.mantisrx.publish.internal.exceptions.RetryableException; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.mantisrx.publish.netty.proto.MantisEvent; import io.netty.channel.Channel; import io.netty.util.concurrent.Future; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An {@link EventChannel} backed by Netty. All I/O operations are asynchronous. */ public class HttpEventChannel implements EventChannel { /** * Defines Netty as an {@link EventChannel} channel type. */ public static final String CHANNEL_TYPE = "netty"; private static final Logger LOG = LoggerFactory.getLogger(HttpEventChannel.class); private final Registry registry; private final Counter writeSuccess; private final Counter writeFailure; private final Counter nettyChannelDropped; private final Timer nettyWriteTime; private final HttpEventChannelManager channelManager; /** * Creates an instance. */ public HttpEventChannel( Registry registry, HttpEventChannelManager channelManager) { this.registry = registry; this.writeSuccess = SpectatorUtils.buildAndRegisterCounter( this.registry, "writeSuccess", "channel", CHANNEL_TYPE); this.writeFailure = SpectatorUtils.buildAndRegisterCounter( this.registry, "writeFailure", "channel", CHANNEL_TYPE); this.nettyChannelDropped = SpectatorUtils.buildAndRegisterCounter( this.registry, "mantisEventsDropped", "channel", CHANNEL_TYPE, "reason", "nettyBufferFull"); this.nettyWriteTime = SpectatorUtils.buildAndRegisterTimer( this.registry, "writeTime", "channel", CHANNEL_TYPE); this.channelManager = channelManager; } /** * Writes an event over the network via {@code POST} request, typically to a Mantis Source Job worker instance. * * @param worker a {@link MantisWorker} representing remote host. * @param event the output to write over the network. * * @return a {@link Future<Void>} which could indicate a Success or Retryable/NonRetryable exception. */ @Override public CompletableFuture<Void> send(MantisWorker worker, Event event) { InetSocketAddress address = worker.toInetSocketAddress(); Channel channel = channelManager.findOrCreate(address); CompletableFuture<Void> future = new CompletableFuture<>(); if (channel.isActive()) { if (channel.isWritable()) { LOG.debug("channel is writable: {} bytes remaining", channel.bytesBeforeUnwritable()); final long nettyStart = registry.clock().wallTime(); // TODO: Channel#setAttribute(future), complete (or exceptionally) in HttpEventChannelHandler. MantisEvent mantisEvent = new MantisEvent(1, event.toJsonString()); channel.writeAndFlush(mantisEvent).addListener(f -> { if (f.isSuccess()) { writeSuccess.increment(); future.complete(null); } else { LOG.debug("failed to send event over netty channel", f.cause()); writeFailure.increment(); future.completeExceptionally(new RetryableException(f.cause().getMessage())); } }); final long nettyEnd = registry.clock().wallTime(); nettyWriteTime.record(nettyEnd - nettyStart, TimeUnit.MILLISECONDS); } else { LOG.debug("channel not writable: {} bytes before writable", channel.bytesBeforeWritable()); nettyChannelDropped.increment(); future.completeExceptionally( new RetryableException("channel not writable: " + channel.bytesBeforeWritable() + " bytes before writable")); } } else { future.completeExceptionally(new NonRetryableException("channel not active")); } return future; } /** * Returns the buffer size as a percentage utilization of the channel's internal transport. For example, see * {@link HttpEventChannel} which uses a Netty {@link Channel} for its underlying transport which will return the * underlying Netty Channel NIO buffer size. * <p> * An {@link EventChannel} may have many underlying connections which implement the same transport. For example, * the {@link HttpEventChannel} may have many Netty {@link Channel}s to connect to external hosts. Each of these * Netty Channels will have their own buffers. * * @param worker a {@link MantisWorker} which is used to query for the buffer size of a specific internal transport. */ @Override public double bufferSize(MantisWorker worker) { InetSocketAddress address = worker.toInetSocketAddress(); Channel channel = channelManager.findOrCreate(address); return channel.bytesBeforeUnwritable() / channel.config().getWriteBufferHighWaterMark(); } @Override public void close(MantisWorker worker) { InetSocketAddress address = worker.toInetSocketAddress(); channelManager.close(address); } }
8,294
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/HttpEventChannelHandler.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.publish.netty.pipeline; import static io.netty.channel.ChannelHandler.Sharable; import static java.nio.charset.StandardCharsets.UTF_8; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import io.mantisrx.publish.internal.exceptions.NonRetryableException; import io.mantisrx.publish.internal.exceptions.RetryableException; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.MessageToMessageEncoder; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpStatusClass; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles incoming responses for sending an event via {@code POST} request. * <p> * This class propagates {@code 4xx} errors as {@link NonRetryableException}s and {@code 5xx} errors as * {@link RetryableException}s. * <p> * For runtime exceptions, such as ones thrown by a {@link MessageToMessageEncoder} or * {@link ChannelOutboundHandlerAdapter}, or Netty user events, such as an {@link IdleStateEvent}, * this class will explicitly close the connection. */ @Sharable class HttpEventChannelHandler extends SimpleChannelInboundHandler<FullHttpResponse> { private static final Logger LOG = LoggerFactory.getLogger(HttpEventChannelHandler.class); private final Counter droppedBatches; /** * Creates a new instance. */ HttpEventChannelHandler(Registry registry) { this.droppedBatches = SpectatorUtils.buildAndRegisterCounter( registry, "droppedBatches", "channel", HttpEventChannel.CHANNEL_TYPE); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) { HttpStatusClass status = msg.status().codeClass(); if (status != HttpStatusClass.SUCCESS) { droppedBatches.increment(); } if (LOG.isDebugEnabled()) { LOG.debug("got http response. status: {}, headers: {}, message: {}", msg.status().codeAsText(), msg.headers().entries().toString(), msg.content().toString(UTF_8)); } } /** * Handles user events for inbound and outbound events of the channel pipeline. * <p> * This method handles the following events: * <p> * 1. {@link IdleStateEvent}s if no data has been written for some time. */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof IdleStateEvent) { LOG.warn("closing idle channel"); ctx.channel().close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { LOG.debug("caught exception from handler", cause); droppedBatches.increment(); if (!(cause instanceof RetryableException || cause instanceof NonRetryableException)) { ctx.channel().close(); } } }
8,295
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/pipeline/HttpEventChannelManager.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.publish.netty.pipeline; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.impl.AtomicDouble; import io.mantisrx.publish.config.MrePublishConfiguration; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; import io.netty.channel.WriteBufferWaterMark; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages a cache of Netty {@link Channel}s. It configures and creates channels, * adds event listeners to channels, and returns them to the caller when queried for by address. * Channels are associated with a single {@link EventLoopGroup}. */ public class HttpEventChannelManager { private static final Logger LOG = LoggerFactory.getLogger(HttpEventChannel.class); private final Counter connectionSuccess; private final Counter connectionFailure; private final AtomicDouble liveConnections; private final AtomicDouble nettyChannelBufferSize; private final int lowWriteBufferWatermark; private final int highWriteBufferWatermark; private final EventLoopGroup eventLoopGroup; private final EventLoopGroup encoderEventLoopGroup; private final Bootstrap bootstrap; private final ConcurrentMap<String, Channel> channels; /** * Creates a new instance. */ public HttpEventChannelManager( Registry registry, MrePublishConfiguration config) { this.connectionSuccess = SpectatorUtils.buildAndRegisterCounter( registry, "connectionSuccess", "channel", HttpEventChannel.CHANNEL_TYPE); this.connectionFailure = SpectatorUtils.buildAndRegisterCounter( registry, "connectionFailure", "channel", HttpEventChannel.CHANNEL_TYPE); this.liveConnections = SpectatorUtils.buildAndRegisterGauge( registry, "liveConnections", "channel", HttpEventChannel.CHANNEL_TYPE); this.nettyChannelBufferSize = SpectatorUtils.buildAndRegisterGauge( registry, "bufferSize", "channel", HttpEventChannel.CHANNEL_TYPE); this.lowWriteBufferWatermark = config.getLowWriteBufferWatermark(); this.highWriteBufferWatermark = config.getHighWriteBufferWatermark(); this.eventLoopGroup = new NioEventLoopGroup(config.getIoThreads()); boolean gzipEnabled = config.getGzipEnabled(); if (gzipEnabled) { this.encoderEventLoopGroup = new DefaultEventLoopGroup(config.getCompressionThreads()); } else { this.encoderEventLoopGroup = null; } this.bootstrap = new Bootstrap() .group(this.eventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, MantisMessageSizeEstimator.DEFAULT) .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( lowWriteBufferWatermark, highWriteBufferWatermark)) .handler(new HttpEventChannelInitializer( registry, config, encoderEventLoopGroup)); this.channels = new ConcurrentHashMap<>(); Runtime.getRuntime().addShutdownHook(new Thread(this.eventLoopGroup::shutdownGracefully)); } /** * Returns an existing channel or creates and caches a new channel. * <p> * The newly-cached channel may not be operational as creation is asynchronous. * <p> * Since the connect operation is asynchronous, callers must: * <p> * 1. check the channel's state before writing * 2. invalidate the cache on connection closed/refused exceptions in the supplied future. * <p> * This method registers a {@link ChannelFutureListener} to listen for {@link Channel#close()} events. * On a {@code close()} event, this channel manager instance will deregister the closed Netty channel * by removing it from its {@link HttpEventChannelManager#channels} cache. */ Channel findOrCreate(InetSocketAddress address) { Channel channel = find(address); if (channel == null) { LOG.debug("creating new channel for {}", address); ChannelFuture channelFuture = bootstrap.connect(address); channel = channelFuture.channel(); channels.put(getHostPortString(address), channel); // Add listener to handle connection closed events, which could happen on exceptions. channel.closeFuture().addListener(future -> { LOG.debug("closing channel for {}", address); channels.remove(getHostPortString(address)); liveConnections.set((double) channels.size()); }); // Add listener to handle the result of the connection event. channelFuture.addListener(future -> { if (future.isSuccess()) { LOG.debug("connection success for {}", address); connectionSuccess.increment(); liveConnections.set((double) channels.size()); } else { LOG.debug("failed to connect to {}", address); connectionFailure.increment(); } }); } nettyChannelBufferSize.set(highWriteBufferWatermark - channel.bytesBeforeUnwritable()); return channel; } private Channel find(InetSocketAddress address) { return channels.get(getHostPortString(address)); } /** * Request to close the Netty channel at the given address. * <p> * Note that we don't need to explicitly remove the channel from the * {@link HttpEventChannelManager#channels} cache because it adds a {@link ChannelFutureListener} * upon {@link Channel} creation (in {@link HttpEventChannelManager#findOrCreate(InetSocketAddress)}) * to listen for {@link Channel#close()} events. On a {@code close()} event, * the channel will be removed from the cache. */ void close(InetSocketAddress address) { Channel channel = find(address); if (channel != null) { channel.close(); } } private String getHostPortString(InetSocketAddress address) { return address.getHostString() + ':' + address.getPort(); } }
8,296
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/proto/MantisEvent.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.publish.netty.proto; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; public class MantisEvent { private final int id; private final String data; @JsonCreator public MantisEvent(@JsonProperty("id") int id, @JsonProperty("data") String data) { this.id = id; this.data = data; } public int getId() { return id; } public String getData() { return data; } /** * Estimate the size (in Bytes) of this object using the size of its fields. */ public int size() { return Integer.BYTES // id + data.getBytes().length; // data } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MantisEvent that = (MantisEvent) o; return getId() == that.getId() && Objects.equals(getData(), that.getData()); } @Override public int hashCode() { return Objects.hash(getId(), getData()); } @Override public String toString() { return "MantisEvent{" + "id=" + id + ", data='" + data + '\'' + '}'; } }
8,297
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/proto/MantisEventEnvelope.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.publish.netty.proto; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class MantisEventEnvelope { private String originServer; private List<MantisEvent> eventList; private long ts; /** * For JSON serde */ public MantisEventEnvelope() { } @JsonCreator public MantisEventEnvelope(@JsonProperty("ts") long ts, @JsonProperty("originServer") String originServer, @JsonProperty("events") List<MantisEvent> eventList) { this.ts = ts; this.originServer = originServer; this.eventList = eventList; } public long getTs() { return ts; } public void setTs(long ts) { this.ts = ts; } public String getOriginServer() { return originServer; } public List<MantisEvent> getEventList() { return eventList; } public void addEvent(MantisEvent event) { eventList.add(event); } @Override public String toString() { return "MantisEventEnvelope{" + "originServer='" + originServer + '\'' + ", eventList=" + eventList + ", ts=" + ts + '}'; } }
8,298
0
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty
Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/transmitters/RoundRobinEventTransmitter.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.publish.netty.transmitters; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import io.mantisrx.discovery.proto.JobDiscoveryInfo; import io.mantisrx.discovery.proto.MantisWorker; import io.mantisrx.publish.EventChannel; import io.mantisrx.publish.EventTransmitter; import io.mantisrx.publish.api.Event; import io.mantisrx.publish.config.MrePublishConfiguration; import io.mantisrx.publish.internal.discovery.MantisJobDiscovery; import io.mantisrx.publish.internal.metrics.SpectatorUtils; import io.mantisrx.publish.netty.pipeline.HttpEventChannel; import java.util.List; import java.util.Optional; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RoundRobinEventTransmitter implements EventTransmitter { private static final Logger LOG = LoggerFactory.getLogger(RoundRobinEventTransmitter.class); private final MrePublishConfiguration configuration; private static volatile int nextWorkerIdx = 0; private final Registry registry; private final Timer channelSendTime; private final MantisJobDiscovery jobDiscovery; private final EventChannel eventChannel; private final Counter noWorkersDroppedCount; private final Counter noDiscoveryDroppedCount; public RoundRobinEventTransmitter(MrePublishConfiguration config, Registry registry, MantisJobDiscovery jobDiscovery, EventChannel eventChannel) { this.configuration = config; this.registry = registry; this.channelSendTime = SpectatorUtils.buildAndRegisterTimer( registry, "sendTime", "channel", HttpEventChannel.CHANNEL_TYPE); this.noWorkersDroppedCount = SpectatorUtils.buildAndRegisterCounter(registry, "mantisEventsDropped", "reason", "noWorkers"); this.noDiscoveryDroppedCount = SpectatorUtils.buildAndRegisterCounter(registry, "mantisEventsDropped", "reason", "noDiscoveryInfo"); this.jobDiscovery = jobDiscovery; this.eventChannel = eventChannel; } @Override public void send(Event event, String stream) { String app = configuration.appName(); String jobCluster = jobDiscovery.getJobCluster(app, stream); Optional<JobDiscoveryInfo> jobDiscoveryInfo = jobDiscovery.getCurrentJobWorkers(jobCluster); if (jobDiscoveryInfo.isPresent()) { List<MantisWorker> workers = jobDiscoveryInfo.get().getIngestStageWorkers().getWorkers(); int numWorkers = workers.size(); if (numWorkers > 0) { MantisWorker nextWorker = workers.get(Integer.remainderUnsigned(nextWorkerIdx++, numWorkers)); final long start = registry.clock().wallTime(); // TODO: propagate feedback - check for Retryable or NonRetryable Exception. Future<Void> future = eventChannel.send(nextWorker, event); final long end = registry.clock().wallTime(); channelSendTime.record(end - start, TimeUnit.MILLISECONDS); } else { LOG.trace("No workers for job cluster {}, dropping event", jobCluster); noWorkersDroppedCount.increment(); } } else { LOG.trace("No job discovery info for job cluster {}, dropping event", jobCluster); noDiscoveryDroppedCount.increment(); } } }
8,299