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/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/File.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.model.TransferWay;
import java.util.Map;
@Data
@EqualsAndHashCode(callSuper = false)
@DataObject(generateConverter = true)
public class File extends Entity {
public static File NOT_FOUND = notFoundInstance(File.class);
private String userId;
private String originalName;
private String name;
private String displayName;
private FileType type;
private long size;
private FileTransferState transferState;
private boolean shared;
private boolean downloadable;
private boolean inSharedDisk;
private String hostIP;
private boolean deleted;
private Deleter deleter;
private long deletedTime;
private TransferWay transferWay;
private Map<String, String> transferInfo;
public File() {
}
public File(JsonObject json) {
FileConverter.fromJson(json, this);
}
public JsonObject toJson() {
JsonObject result = new JsonObject();
FileConverter.toJson(this, result);
return result;
}
public boolean transferred() {
return transferState == FileTransferState.SUCCESS;
}
}
| 6,800 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/Config.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@DataObject(generateConverter = true)
public class Config extends Entity {
public static Config NOT_FOUND = notFoundInstance(Config.class);
private String name;
private String value;
public Config() {
}
public Config(JsonObject json) {
ConfigConverter.fromJson(json, this);
}
public JsonObject toJson() {
JsonObject result = new JsonObject();
ConfigConverter.toJson(this, result);
return result;
}
}
| 6,801 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/GlobalLock.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@DataObject(generateConverter = true)
public class GlobalLock extends Entity {
public static GlobalLock NOT_FOUND = notFoundInstance(GlobalLock.class);
private String name;
public GlobalLock() {
}
public GlobalLock(JsonObject json) {
GlobalLockConverter.fromJson(json, this);
}
public JsonObject toJson() {
JsonObject result = new JsonObject();
GlobalLockConverter.toJson(this, result);
return result;
}
}
| 6,802 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/Entity.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity;
import lombok.Data;
import org.eclipse.jifa.common.JifaException;
import java.lang.reflect.Constructor;
@Data
public abstract class Entity {
private static long NOT_FOUND_RECORD_ID = -1;
private long id;
private long lastModifiedTime;
private long creationTime;
static <R extends Entity> R notFoundInstance(Class<R> clazz) {
try {
Constructor<R> constructor = clazz.getConstructor();
R record = constructor.newInstance();
record.setId(NOT_FOUND_RECORD_ID);
return record;
} catch (Throwable t) {
throw new JifaException(t);
}
}
public boolean found() {
return getId() != NOT_FOUND_RECORD_ID;
}
public boolean notFound() {
return !found();
}
}
| 6,803 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/package-info.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
@ModuleGen(groupPackage = "org.eclipse.jifa.master.entity", name = "Entity")
package org.eclipse.jifa.master.entity;
import io.vertx.codegen.annotations.ModuleGen; | 6,804 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/enums/JobType.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity.enums;
import org.eclipse.jifa.common.enums.FileType;
public enum JobType {
FILE_TRANSFER,
HEAP_DUMP_ANALYSIS,
GCLOG_ANALYSIS,
THREAD_DUMP_ANALYSIS;
public boolean isFileTransfer() {
return this == FILE_TRANSFER;
}
public String getTag() {
switch (this) {
case HEAP_DUMP_ANALYSIS:
return FileType.HEAP_DUMP.getTag();
case GCLOG_ANALYSIS:
return FileType.GC_LOG.getTag();
case THREAD_DUMP_ANALYSIS:
return FileType.THREAD_DUMP.getTag();
default:
throw new IllegalStateException();
}
}
}
| 6,805 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/enums/Deleter.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity.enums;
public enum Deleter {
USER,
ADMIN,
SYSTEM
}
| 6,806 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/entity/enums/JobState.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.entity.enums;
public enum JobState {
PENDING,
IN_PROGRESS,
FINISHED
}
| 6,807 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/Pattern.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
public enum Pattern {
DEFAULT,
K8S;
}
| 6,808 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/Factory.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
public class Factory {
public static WorkerScheduler create(Pattern pattern) {
switch (pattern) {
case K8S:
return new K8SWorkerScheduler();
case DEFAULT:
default:
return new DefaultWorkerScheduler();
}
}
}
| 6,809 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/Utils.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
/**
* Commonly used across master side
*/
public class Utils {
// TODO: current algorithm used isn't good enough
public static long calculateLoadFromSize(double size) {
double G = 1024 * 1024 * 1024;
long load = (long) Math.ceil(size / G) * 10;
load = Math.max(load, 10);
load = Math.min(load, 900);
return load;
}
// Roughly a reverse operation of calculateLoad
public static double calculateSizeFromLoad(long size) {
long estimateLoad = size;
estimateLoad = Math.max(10, estimateLoad);
return estimateLoad / 10.0;
}
}
| 6,810 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/WorkerClient.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
import io.reactivex.Single;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.MultiMap;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.core.http.HttpServerRequest;
import io.vertx.reactivex.ext.web.client.HttpRequest;
import io.vertx.reactivex.ext.web.client.HttpResponse;
import io.vertx.reactivex.ext.web.client.WebClient;
import io.vertx.reactivex.ext.web.multipart.MultipartForm;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Map;
import static org.eclipse.jifa.master.Constant.*;
public class WorkerClient {
private static final Logger LOGGER = LoggerFactory.getLogger(WorkerClient.class);
private static String USERNAME;
private static String PASSWORD;
private static int PORT;
private static WebClient client;
public static void init(JsonObject config, WebClient client) {
USERNAME = config.getString(Constant.USERNAME);
PASSWORD = config.getString(Constant.PASSWORD);
PORT = config.getInteger(Constant.PORT);
WorkerClient.client = client;
}
public static Single<HttpResponse<Buffer>> post(String hostIP, String uri, Map<String, String> params) {
return send(HttpMethod.POST, hostIP, PORT, uri, params);
}
public static Single<HttpResponse<Buffer>> post(String hostIP, String uri) {
return send(HttpMethod.POST, hostIP, PORT, uri, (MultiMap) null);
}
public static Single<HttpResponse<Buffer>> post(String hostIP, String uri, MultiMap params) {
return send(HttpMethod.POST, hostIP, PORT, uri, params);
}
public static Single<HttpResponse<Buffer>> get(String hostIP, String uri) {
return send(HttpMethod.GET, hostIP, PORT, uri, (MultiMap) null);
}
public static Single<HttpResponse<Buffer>> get(String hostIP, String uri, Map<String, String> params) {
return send(HttpMethod.GET, hostIP, PORT, uri, params);
}
public static Single<HttpResponse<Buffer>> get(String hostIP, String uri, MultiMap params) {
return send(HttpMethod.GET, hostIP, PORT, uri, params);
}
public static Single<HttpResponse<Buffer>> send(HttpServerRequest request, String hostIP) {
return send(request, hostIP, PORT);
}
public static Single<HttpResponse<Buffer>> send(HttpServerRequest request, String hostIP, int port) {
return send(request.method(), hostIP, port, request.uri(), request.params());
}
private static Single<HttpResponse<Buffer>> send(HttpMethod method, String hostIP, int port, String uri,
Map<String, String> params) {
return send(method, hostIP, port, uri, MultiMap.caseInsensitiveMultiMap().addAll(params));
}
private static Single<HttpResponse<Buffer>> send(HttpMethod method, String hostIP, int port, String uri,
MultiMap params) {
return send(request(method, hostIP, port, uri), method == HttpMethod.POST, params);
}
public static Single<HttpResponse<Buffer>> send(HttpRequest<Buffer> request, boolean post, MultiMap params) {
request.basicAuthentication(USERNAME, PASSWORD);
if (post) {
if (params == null) {
return request.rxSend();
}
return request.rxSendForm(params);
}
if (params != null) {
request.queryParams().addAll(params);
}
return request.rxSend();
}
public static Single<HttpResponse<Buffer>> uploadFile(String hostIp, File file, String name, FileType type) {
HttpRequest<Buffer> request = request(HttpMethod.POST, hostIp, PORT, uri(FILE_UPLOAD));
MultipartForm formDataParts = MultipartForm.create();
formDataParts.attribute("fileName", name)
.attribute("type", type.name())
.binaryFileUpload(file.getName(), file.getName(), file.getPath(), "application/octet-stream");
return request.rxSendMultipartForm(formDataParts);
}
private static HttpRequest<Buffer> request(HttpMethod method, String hostIP, int port, String uri) {
if (method == HttpMethod.GET) {
return client.get(port, hostIP, uri);
} else if (method == HttpMethod.POST) {
return client.post(port, hostIP, uri);
}
LOGGER.error("Unsupported worker http request method {}", method);
throw new IllegalArgumentException();
}
public static HttpRequest<Buffer> request(HttpMethod method, String hostIP, String uri) {
return request(method, hostIP, PORT, uri);
}
}
| 6,811 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/K8SWorkerScheduler.java | /********************************************************************************
* Copyright (c) 2021,2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.Config;
import io.reactivex.Completable;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.sql.SQLConnection;
import io.vertx.serviceproxy.ServiceException;
import org.apache.commons.codec.digest.DigestUtils;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.model.WorkerInfo;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.task.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.Constant.*;
import static org.eclipse.jifa.master.Constant.K8S_WORKER_PVC_NAME;
public class K8SWorkerScheduler implements WorkerScheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(K8SWorkerScheduler.class);
private static final String WORKER_PREFIX = "jifa-worker";
private static final String SPECIAL_WORKER_PREFIX = "jifa-special";
private static String NAMESPACE;
private static String WORKER_IMAGE;
private static CoreV1Api api;
private static long MINIMAL_MEM_REQ;
private static String MASTER_POD_NAME;
private static String WORKER_PVC_NAME;
private static V1Pod createWorker(String name, long requestMemSize) {
requestMemSize = Math.max(requestMemSize, MINIMAL_MEM_REQ);
V1Volume volume = new V1Volume();
volume.setName("dumpfile-volume");
volume.persistentVolumeClaim(new V1PersistentVolumeClaimVolumeSource().claimName(WORKER_PVC_NAME));
V1Pod npod;
npod = new V1PodBuilder()
.withNewMetadata()
.withName(name)
.withLabels(new HashMap<String, String>() {{
put("name", "jifa-worker");
}})
.endMetadata()
.withNewSpec()
.addNewContainer()
.withResources(
new V1ResourceRequirements()
.requests(Map.of("memory", new Quantity(String.valueOf(requestMemSize))))
)
.withName("my-jifa-worker")
.withImage(WORKER_IMAGE)
.withPorts(
new V1ContainerPort()
.containerPort(8102)
)
.withVolumeMounts(
new V1VolumeMount()
.mountPath("/root")
.name("dumpfile-volume")
)
.endContainer()
.withVolumes(volume)
.endSpec()
.build();
try {
npod = api.createNamespacedPod(NAMESPACE, npod, null, null, null);
} catch (ApiException e) {
e.printStackTrace();
}
return npod;
}
public static String getNormalWorkerPrefix() {
return WORKER_PREFIX;
}
public static String getSpecialWorkerPrefix() {
return SPECIAL_WORKER_PREFIX;
}
private static List<V1Pod> listWorker() {
List<V1Pod> pods = null;
try {
V1PodList list = api.listNamespacedPod(NAMESPACE, null, null, null, null, null, null, null, null, null);
pods = list.getItems();
} catch (ApiException e) {
e.printStackTrace();
}
return pods;
}
private static V1Pod removeWorker(String name) {
V1Pod npod = null;
try {
npod = api.deleteNamespacedPod(name, NAMESPACE, null, null, 0, null, null, null);
} catch (ApiException e) {
e.printStackTrace();
}
return npod;
}
@Override
public void initialize(Pivot pivot, Vertx vertx, JsonObject config) {
new RetiringTask(pivot, vertx);
new TransferJobResultFillingTask(pivot, vertx);
new PVCCleanupTask(pivot, vertx);
new StopAbnormalWorkerTask(pivot, vertx);
new FileSyncForK8STask(pivot, vertx);
// Order is important
ApiClient client;
try {
client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
api = new CoreV1Api();
JsonObject k8sConfig = config.getJsonObject(K8S_KEYWORD);
NAMESPACE = k8sConfig.getString(K8S_NAMESPACE);
WORKER_IMAGE = k8sConfig.getString(K8S_WORKER_IMAGE);
MINIMAL_MEM_REQ = k8sConfig.getLong(K8S_MINIMAL_MEM_REQ);
MASTER_POD_NAME = k8sConfig.getString(K8S_MASTER_POD_NAME);
WORKER_PVC_NAME = k8sConfig.getString(K8S_WORKER_PVC_NAME);
LOGGER.info("K8S Namespace: " + NAMESPACE + ", Image: " + WORKER_IMAGE + ", Minimal memory request:" +
MINIMAL_MEM_REQ);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Single<Worker> decide(Job job, SQLConnection conn) {
String name = buildWorkerName(job);
WorkerInfo workerInfo = getWorkerInfo(name);
if (workerInfo == null) {
Worker none = Worker.NOT_FOUND;
none.setHostName(name);
return Single.just(none);
} else {
String workerIp = getWorkerInfo(name).getIp();
Worker handmake = new Worker();
handmake.setHostIP(workerIp);
handmake.setHostName(name);
return Single.just(handmake);
}
}
@Override
public boolean supportPendingJob() {
return false;
}
private String buildWorkerName(Job job) {
String target = job.getTarget();
if (target.startsWith(SPECIAL_WORKER_PREFIX)) {
return target;
} else {
target = DigestUtils.md5Hex(job.getTarget().getBytes(StandardCharsets.UTF_8)).substring(0, 16);
return WORKER_PREFIX + "-" + target;
}
}
@Override
public Completable start(Job job) {
String name = buildWorkerName(job);
Map<String, String> config = new HashMap<>();
double fileSizeGb = Utils.calculateSizeFromLoad(job.getEstimatedLoad());
fileSizeGb *= 1.3; // occupy 130% memory of filesize
fileSizeGb = Math.min(fileSizeGb, 18.0); // limit to 18g
long fileSizeKb = (long) (fileSizeGb * 1024 * 1024 * 1024); // convert gb to kb
config.put("requestMemSize", Long.toString(fileSizeKb));
schedule(name, config);
String workerIp = getWorkerInfo(name).getIp();
if (workerIp == null) {
// Front-end would retry original request until worker pod has been started or
// timeout threshold reached.
return Completable.error(new ServiceException(ErrorCode.RETRY.ordinal(), job.getTarget()));
}
final String MSG_RETRY = "RETRY";
final String MSG_OK = "OK";
return WorkerClient.get(workerIp, uri(PING))
.flatMap(resp -> Single.just(MSG_OK))
.onErrorReturn(err -> {
if (err instanceof ConnectException) {
// ConnectionException is tolerable because it simply indicates worker is still
// starting
return MSG_RETRY;
} else if (err instanceof IOException) {
if (err.getMessage() != null && err.getMessage().contains("Connection reset by peer")) {
return MSG_RETRY;
}
}
return err.getMessage();
}).flatMapCompletable(msg -> {
if (msg.equals(MSG_OK)) {
return Completable.complete();
} else if (msg.equals(MSG_RETRY)) {
return Completable.error(new ServiceException(ErrorCode.RETRY.ordinal(), job.getTarget()));
} else {
return Completable.error(new JifaException("Can not start worker due to internal error: " + msg));
}
});
}
private void schedule(String id, Map<String, String> config) {
long requestMemSize = 0L;
String tmp = config.get("requestMemSize");
if (tmp != null) {
requestMemSize = Long.parseLong(tmp);
}
if (getWorkerInfo(id) != null) {
LOGGER.debug("Create worker {} but it already exists", id);
} else {
LOGGER.debug("Create worker {} [MemRequest: {}bytes]", id, requestMemSize);
createWorker(id, requestMemSize);
}
}
@Override
public Completable stop(Job job) {
return Completable.fromAction(() -> {
String id = buildWorkerName(job);
if (getWorkerInfo(id) == null) {
LOGGER.debug("Stop worker " + id + " but it does not exist");
} else {
LOGGER.debug("Stop worker " + id);
removeWorker(id);
}
});
}
@Override
public Completable stop(Worker worker) {
return Completable.fromAction(() -> {
String id = worker.getHostName();
if (getWorkerInfo(id) == null) {
LOGGER.debug("Stop worker " + id + " but it does not exist");
} else {
LOGGER.debug("Stop worker " + id);
removeWorker(id);
}
});
}
@Override
public Single<List<Worker>> list() {
List<V1Pod> pods = listWorker();
if (pods != null) {
List<Worker> workers = pods.stream().map(pod -> {
Worker w = new Worker();
w.setHostName(pod.getMetadata().getName());
w.setHostIP(pod.getStatus().getPodIP());
return w;
}).collect(Collectors.toList());
return Single.just(workers);
}
return Single.just(new ArrayList<>() {{
add(Worker.NOT_FOUND);
}});
}
private WorkerInfo getWorkerInfo(String id) {
V1Pod npod = null;
try {
npod = api.readNamespacedPod(id, NAMESPACE, null, null, null);
} catch (ApiException ignored) {
}
if (null != npod) {
WorkerInfo info = new WorkerInfo();
info.setName(id);
info.setIp(Objects.requireNonNull(npod.getStatus()).getPodIP());
return info;
} else {
return null;
}
}
} | 6,812 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/WorkerScheduler.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
import io.reactivex.Completable;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.sql.SQLConnection;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.service.impl.Pivot;
import java.util.List;
import java.util.Map;
public interface WorkerScheduler {
/**
* init the scheduler
*/
void initialize(Pivot pivot, Vertx vertx, JsonObject config);
/**
* @param job related job
* @param conn sql connection
* @return worker to run the job
*/
Single<Worker> decide(Job job, SQLConnection conn);
/**
* @return true is the scheduler supports pending job
*/
boolean supportPendingJob();
/**
* @param job start the worker by job
*/
Completable start(Job job);
/**
* stop the worker by job
*/
Completable stop(Job job);
/**
* stop the worker by Worker entity
*/
Completable stop(Worker worker);
/**
* List existing workers
*
* @return list of worker
*/
Single<List<Worker>>list();
}
| 6,813 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/support/DefaultWorkerScheduler.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.support;
import io.reactivex.Completable;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.sql.SQLConnection;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.task.DiskCleaningTask;
import org.eclipse.jifa.master.task.DiskUsageUpdatingTask;
import org.eclipse.jifa.master.task.FileSyncTask;
import org.eclipse.jifa.master.task.RetiringTask;
import org.eclipse.jifa.master.task.SchedulingTask;
import org.eclipse.jifa.master.task.TransferJobResultFillingTask;
import java.util.List;
import java.util.Map;
public class DefaultWorkerScheduler implements WorkerScheduler {
private Pivot pivot;
@Override
public void initialize(Pivot pivot, Vertx vertx, JsonObject configs) {
this.pivot = pivot;
if (pivot.isLeader()) {
new DiskCleaningTask(pivot, vertx);
new RetiringTask(pivot, vertx);
pivot.setSchedulingTask(new SchedulingTask(pivot, vertx));
new TransferJobResultFillingTask(pivot, vertx);
new DiskUsageUpdatingTask(pivot, vertx);
new FileSyncTask(pivot, vertx);
}
}
@Override
public Single<Worker> decide(Job job, SQLConnection conn) {
return pivot.decideWorker(conn, job);
}
@Override
public boolean supportPendingJob() {
return true;
}
@Override
public Completable start(Job job) {
return Completable.complete();
}
@Override
public Completable stop(Job job) {
return Completable.complete();
}
@Override
public Completable stop(Worker worker) {
throw new JifaException("Unimplemented");
}
@Override
public Single<List<Worker>> list() {
throw new JifaException("Unimplemented");
}
}
| 6,814 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/UserRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.JWTOptions;
import io.vertx.ext.auth.PubSecKeyOptions;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.http.Cookie;
import io.vertx.reactivex.ext.auth.jwt.JWTAuth;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import io.vertx.reactivex.ext.web.handler.JWTAuthHandler;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.vo.UserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class UserRoute implements Constant {
private static final Logger LOGGER = LoggerFactory.getLogger(UserRoute.class);
private static final String EXCLUDE_URI = String.join("|", HEALTH_CHECK, AUTH);
private static final String EXCLUDE_ROUTE_REGEX = "^(?!" + EXCLUDE_URI +"$).*";
private JWTAuth jwtAuth;
private JWTOptions jwtOptions;
void init(Vertx vertx, JsonObject config, Router apiRouter) {
// symmetric is not safe, but it's enough now...
PubSecKeyOptions pubSecKeyOptions = new PubSecKeyOptions();
pubSecKeyOptions.setAlgorithm(JWT_ALGORITHM_HS256)
.setBuffer(JWT_ALGORITHM_HS256_PUBLIC_KEY);
jwtAuth = JWTAuth.create(vertx, new JWTAuthOptions().addPubSecKey(pubSecKeyOptions));
jwtOptions = new JWTOptions();
jwtOptions.setSubject(JWT_SUBJECT).setIssuer(JWT_ISSUER).setExpiresInMinutes(JWT_EXPIRES_IN_MINUTES);
apiRouter.routeWithRegex(EXCLUDE_ROUTE_REGEX).handler(this::authWithCookie);
apiRouter.routeWithRegex(EXCLUDE_ROUTE_REGEX).handler(JWTAuthHandler.create(jwtAuth));
apiRouter.post().path(AUTH).handler(this::auth);
apiRouter.routeWithRegex(EXCLUDE_ROUTE_REGEX).handler(this::extractInfo);
apiRouter.get().path(USER_INFO).handler(this::userInfo);
}
private void authWithCookie(RoutingContext context) {
Cookie authCookie = context.request().getCookie(COOKIE_AUTHORIZATION);
if (!context.request().headers().contains(HEADER_AUTHORIZATION) && authCookie != null) {
context.request().headers().add(HEADER_AUTHORIZATION, HEADER_AUTHORIZATION_PREFIX + authCookie.getValue());
}
context.next();
}
private void auth(RoutingContext context) {
Single.just(context.request())
.flatMap(req -> {
String username = req.getParam("username");
String password = req.getParam("password");
if ("admin".equals(username) && "admin".equals(password)) {
return Single.just(new JsonObject()
.put(USER_ID_KEY, "12345")
.put(USER_NAME_KEY, "admin")
.put(Constant.USER_IS_ADMIN_KEY, true))
.map(userInfo -> jwtAuth.generateToken(userInfo, jwtOptions));
} else {
return Single.just("");
}
}).subscribe(token -> HTTPRespGuarder.ok(context, new UserToken(token)),
t -> HTTPRespGuarder.fail(context, t));
}
private void extractUserInfo(RoutingContext context) {
JsonObject principal = context.user().principal();
User user = new User(principal.getString(USER_ID_KEY), principal.getString(USER_NAME_KEY),
principal.getBoolean(USER_IS_ADMIN_KEY));
context.put(USER_INFO_KEY, user);
}
private void saveAuthorizationCookie(RoutingContext context) {
Cookie authCookie = context.getCookie(COOKIE_AUTHORIZATION);
String authHeader = context.request().getHeader(HEADER_AUTHORIZATION);
if (authHeader != null && authHeader.startsWith(HEADER_AUTHORIZATION_PREFIX)) {
// cookie can not have ' ', so we save substring here
authHeader = authHeader.substring(HEADER_AUTHORIZATION_PREFIX.length());
if (authCookie == null || !authHeader.equals(authCookie.getValue())) {
Cookie cookie = Cookie.cookie(COOKIE_AUTHORIZATION, authHeader);
cookie.setPath("/");
context.addCookie(cookie);
}
}
}
private void extractInfo(RoutingContext context) {
saveAuthorizationCookie(context);
extractUserInfo(context);
context.next();
}
private void userInfo(RoutingContext context) {
HTTPRespGuarder.ok(context, context.get(USER_INFO_KEY));
}
}
| 6,815 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/WorkerRoute.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiPredicate;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.http.HttpServerRequest;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import io.vertx.serviceproxy.ServiceException;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.service.ProxyDictionary;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.reactivex.SupportService;
import org.eclipse.jifa.master.service.reactivex.WorkerService;
import org.eclipse.jifa.master.support.K8SWorkerScheduler;
import java.util.concurrent.TimeUnit;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
class WorkerRoute extends BaseRoute {
private WorkerService workerService;
private SupportService supportService;
void init(Vertx vertx, JsonObject config, Router apiRouter) {
workerService = ProxyDictionary.lookup(WorkerService.class);
supportService = ProxyDictionary.lookup(SupportService.class);
apiRouter.get().path(Constant.QUERY_ALL_WORKERS).handler(this::queryAll);
apiRouter.post().path(Constant.WORKER_DISK_CLEANUP).handler(this::diskCleanup);
if (!Pivot.getInstance().isDefaultPattern()) {
assert Pivot.getInstance().getScheduler() instanceof K8SWorkerScheduler : "unexpected scheduler";
apiRouter.get().path(Constant.HEALTH_CHECK).handler(this::healthCheck);
}
}
private void queryAll(RoutingContext context) {
User user = context.get(Constant.USER_INFO_KEY);
ASSERT.isTrue(user.isAdmin(), ErrorCode.FORBIDDEN);
workerService.rxQueryAll()
.subscribe(
workers -> HTTPRespGuarder.ok(context, workers),
t -> HTTPRespGuarder.fail(context, t)
);
}
private void diskCleanup(RoutingContext context) {
User user = context.get(Constant.USER_INFO_KEY);
ASSERT.isTrue(user.isAdmin(), ErrorCode.FORBIDDEN);
HttpServerRequest request = context.request();
String hostIP = request.getParam("host_ip");
workerService.rxDiskCleanup(hostIP).subscribe(
() -> HTTPRespGuarder.ok(context, "ok"),
t -> HTTPRespGuarder.fail(context, t));
}
private void healthCheck(RoutingContext context) {
supportService.rxIsDBConnectivity()
.onErrorReturn(e -> Boolean.FALSE)
.subscribe(connectivity -> {
if (!connectivity) {
HTTPRespGuarder.fail(context, new JifaException("Can not connect to DB"));
} else {
supportService.rxStartDummyWorker()
.retry(
// Note, http request has its own timeout mechanism, and we can not re-send health check
// since liveliness probe is a one-shot test, it's safe to use stream retry API.
new RetryStartingWorker(30))
.andThen(supportService.rxStopDummyWorker())
.subscribe(() -> HTTPRespGuarder.ok(context, "SUCCESS"),
e -> HTTPRespGuarder.fail(context, new JifaException("Can not start testing worker due to " + e)));
}
}, e -> HTTPRespGuarder.fail(context, e));
}
private static class RetryStartingWorker implements BiPredicate<Integer, Throwable> {
private final int retryLimit;
public RetryStartingWorker(int retryLimit) {
this.retryLimit = retryLimit;
}
@Override
public boolean test(@NonNull Integer integer, @NonNull Throwable ex) throws Exception {
if (integer < retryLimit) {
if (ex instanceof ServiceException) {
ServiceException se = (ServiceException) ex;
int failureCode = se.failureCode();
if (failureCode == ErrorCode.RETRY.ordinal()) {
TimeUnit.SECONDS.sleep(1);
return true;
}
}
}
return false;
}
}
}
| 6,816 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/HttpServerVerticle.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.Single;
import io.vertx.core.Promise;
import io.vertx.reactivex.core.AbstractVerticle;
import io.vertx.reactivex.core.http.HttpServerResponse;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import io.vertx.reactivex.ext.web.client.WebClient;
import io.vertx.reactivex.ext.web.handler.BodyHandler;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpServerVerticle extends AbstractVerticle implements Constant {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpServerVerticle.class);
private WebClient client;
@Override
public void start(Promise<Void> startFuture) {
vertx.rxExecuteBlocking(future -> {
client = WebClient.create(vertx);
// base
Router router = Router.router(vertx);
router.errorHandler(Constant.HTTP_INTERNAL_SERVER_ERROR_STATUS_CODE, this::error);
router.errorHandler(Constant.HTTP_BAD_REQUEST_STATUS_CODE, this::error);
// jifa api
Router apiRouter = Router.router(vertx);
router.mountSubRouter(BASE, apiRouter);
apiRouter.post().handler(BodyHandler.create());
new UserRoute().init(vertx, config(), apiRouter);
new JobRoute().init(vertx, config(), apiRouter);
new AdminRoute().init(vertx, config(), apiRouter);
new WorkerRoute().init(vertx, config(), apiRouter);
new FileRoute().init(vertx, config(), apiRouter);
new AnalyzerRoute().init(vertx, config(), apiRouter);
Integer port = config().getInteger("port");
vertx.createHttpServer().requestHandler(router).rxListen(port).subscribe(s -> {
LOGGER.info("Master-Http-Server-Verticle started successfully, port is {}", port);
future.complete(Single.just(this));
}, future::fail);
}).subscribe(f -> startFuture.complete(), startFuture::fail);
}
void error(RoutingContext context) {
Throwable failure = context.failure();
HttpServerResponse response = context.response();
if (failure != null && !response.ended() && !response.closed()) {
HTTPRespGuarder.fail(context, failure);
}
}
}
| 6,817 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/FileRoute.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.Single;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.MultiMap;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.core.http.HttpServerRequest;
import io.vertx.reactivex.ext.web.FileUpload;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import io.vertx.reactivex.ext.web.client.HttpRequest;
import io.vertx.reactivex.ext.web.codec.BodyCodec;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.common.enums.ProgressState;
import org.eclipse.jifa.common.util.FileUtil;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.common.vo.FileInfo;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.common.vo.TransferProgress;
import org.eclipse.jifa.common.vo.TransferringFile;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.model.TransferWay;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.service.ProxyDictionary;
import org.eclipse.jifa.master.service.reactivex.FileService;
import org.eclipse.jifa.master.service.reactivex.JobService;
import org.eclipse.jifa.master.support.WorkerClient;
import org.eclipse.jifa.master.vo.ExtendedFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
class FileRoute extends BaseRoute implements Constant {
private static final Logger LOGGER = LoggerFactory.getLogger(FileRoute.class.getName());
private static String PUB_KEY = Constant.EMPTY_STRING;
static {
String path = System.getProperty("user.home") + java.io.File.separator + ".ssh" + java.io.File.separator +
"jifa-ssh-key.pub";
java.io.File file = new java.io.File(path);
if (file.exists()) {
PUB_KEY = FileUtil.content(file);
} else {
LOGGER.warn("SSH public key file {} doesn't exist", file.getAbsolutePath());
}
}
private FileService fileService;
private JobService jobService;
private static ExtendedFileInfo buildFileInfo(File file) {
ExtendedFileInfo info = new ExtendedFileInfo();
info.setOriginalName(file.getOriginalName());
info.setDisplayName(
StringUtils.isBlank(file.getDisplayName()) ? file.getOriginalName() : file.getDisplayName());
info.setName(file.getName());
info.setType(file.getType());
info.setSize(file.getSize());
info.setTransferState(file.getTransferState());
info.setShared(file.isShared());
info.setDownloadable(false);
info.setCreationTime(file.getCreationTime());
info.setUserId(file.getUserId());
return info;
}
void init(Vertx vertx, JsonObject config, Router apiRouter) {
fileService = ProxyDictionary.lookup(FileService.class);
jobService = ProxyDictionary.lookup(JobService.class);
apiRouter.get().path(FILES).handler(this::files);
apiRouter.get().path(FILE).handler(this::file);
apiRouter.post().path(FILE_DELETE).handler(this::delete);
apiRouter.post().path(TRANSFER_BY_URL).handler(context -> transfer(context, TransferWay.URL));
apiRouter.post().path(TRANSFER_BY_SCP).handler(context -> transfer(context, TransferWay.SCP));
apiRouter.post().path(TRANSFER_BY_OSS).handler(context -> transfer(context, TransferWay.OSS));
apiRouter.post().path(TRANSFER_BY_S3).handler(context -> transfer(context, TransferWay.S3));
apiRouter.get().path(TRANSFER_PROGRESS).handler(this::fileTransportProgress);
apiRouter.get().path(PUBLIC_KEY).handler(this::publicKey);
apiRouter.post().path(FILE_SET_SHARED).handler(this::setShared);
apiRouter.post().path(FILE_UNSET_SHARED).handler(this::unsetShared);
apiRouter.post().path(FILE_UPDATE_DISPLAY_NAME).handler(this::updateDisplayName);
apiRouter.post().path(UPLOAD_TO_OSS).handler(this::uploadToOSS);
apiRouter.get().path(UPLOAD_TO_OSS_PROGRESS).handler(this::uploadToOSSProgress);
apiRouter.get().path(DOWNLOAD).handler(this::download);
apiRouter.post().path(FILE_UPLOAD).handler(this::upload);
}
private void files(RoutingContext context) {
String userId = context.<User>get(USER_INFO_KEY).getId();
int page = Integer.parseInt(context.request().getParam(PAGE));
int pageSize = Integer.parseInt(context.request().getParam(PAGE_SIZE));
FileType type = FileType.valueOf(context.request().getParam(FILE_TYPE));
String expected = context.request().getParam("expectedFilename");
Single<Integer> countSingle = fileService.rxCount(userId, type, expected);
Single<List<File>> fileRecordSingle = fileService.rxFiles(userId, type, expected, page, pageSize);
Single.zip(countSingle, fileRecordSingle, (count, fileRecords) -> {
PageView<FileInfo> pv = new PageView<>();
pv.setTotalSize(count);
pv.setPage(page);
pv.setPageSize(pageSize);
pv.setData(fileRecords.stream().map(FileRoute::buildFileInfo).collect(Collectors.toList()));
return pv;
}).subscribe(pageView -> HTTPRespGuarder.ok(context, pageView), t -> HTTPRespGuarder.fail(context, t));
}
private void file(RoutingContext context) {
User user = context.get(USER_INFO_KEY);
String name = context.request().getParam("name");
fileService.rxFile(name)
.doOnSuccess(this::assertFileAvailable)
.doOnSuccess(file -> checkPermission(user, file))
.map(FileRoute::buildFileInfo)
.subscribe(fileView -> HTTPRespGuarder.ok(context, fileView),
throwable -> HTTPRespGuarder.fail(context, throwable));
}
private void delete(RoutingContext context) {
User user = context.get(USER_INFO_KEY);
String name = context.request().getParam("name");
fileService.rxFile(name)
.doOnSuccess(this::assertFileAvailable)
.doOnSuccess(file -> checkDeletePermission(user, file))
.doOnSuccess(file -> ASSERT.isTrue(file.getTransferState().isFinal()))
.flatMapCompletable(
file -> fileService.rxDeleteFile(name,
file.getUserId().equals(user.getId()) ?
Deleter.USER : Deleter.ADMIN))
.subscribe(() -> HTTPRespGuarder.ok(context),
t -> HTTPRespGuarder.fail(context, t));
}
private void transfer(RoutingContext context, TransferWay way) {
String userId = context.<User>get(USER_INFO_KEY).getId();
HttpServerRequest request = context.request();
String[] paths = way.getPathKeys();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.length; i++) {
sb.append(request.getParam(paths[i]));
if (i != paths.length - 1) {
sb.append("_");
}
}
String origin = extractOriginalName(sb.toString());
FileType type = FileType.valueOf(context.request().getParam("type"));
String name;
if (context.request().getParam("retry") != null) {
name = context.request().getParam("retry");
} else {
name = buildFileName(userId, origin);
}
request.params().add("fileName", name);
fileService.rxTransfer(userId, type, origin, name, way, convert(request.params()))
.ignoreElement()
.toSingleDefault(name)
.subscribe(n -> HTTPRespGuarder.ok(context, new TransferringFile(n)),
t -> HTTPRespGuarder.fail(context, t));
}
private void fileTransportProgress(RoutingContext context) {
String name = context.request().getParam("name");
User user = context.get(USER_INFO_KEY);
jobService.rxFindActive(JobType.FILE_TRANSFER, name).flatMap(job -> {
if (job.notFound()) {
return fileService.rxFile(name)
.doOnSuccess(this::assertFileAvailable)
.doOnSuccess(file -> checkPermission(user, file))
.flatMap(file -> Single.just(toProgress(file)));
}
checkPermission(user, job);
Single<TransferProgress> progressSingle =
WorkerClient.send(context.request(), job.getHostIP())
.doOnSuccess(resp -> ASSERT.isTrue(HTTP_GET_OK_STATUS_CODE == resp.statusCode(),
resp::bodyAsString))
.map(resp -> GSON.fromJson(resp.bodyAsString(), TransferProgress.class));
return progressSingle.flatMap(progress -> {
ProgressState state = progress.getState();
if (state.isFinal()) {
LOGGER.info("File transfer {} done, state is {}", name, progress.getState());
FileTransferState transferState = FileTransferState.fromProgressState(state);
return fileService.rxTransferDone(name, transferState, progress.getTotalSize())
.andThen(Single.just(progress));
}
return Single.just(progress);
});
}).subscribe(p -> HTTPRespGuarder.ok(context, p),
t -> HTTPRespGuarder.fail(context, t));
}
private void uploadToOSS(RoutingContext context) {
String name = context.request().getParam("srcName");
ASSERT.isTrue(StringUtils.isNotBlank(name), ErrorCode.ILLEGAL_ARGUMENT, "srcName mustn't be empty");
User user = context.get(USER_INFO_KEY);
fileService.rxFile(name)
.doOnSuccess(file -> assertFileAvailable(file))
.doOnSuccess(file -> checkPermission(user, file))
.doOnSuccess(file -> ASSERT.isTrue(file.transferred(), ErrorCode.NOT_TRANSFERRED))
.doOnSuccess(file -> context.request().params().add("type", file.getType().name()))
.flatMap(file -> WorkerClient.send(context.request(), file.getHostIP()))
.subscribe(resp -> HTTPRespGuarder.ok(context, resp.statusCode(), resp.bodyAsString()),
t -> HTTPRespGuarder.fail(context, t));
}
private void uploadToOSSProgress(RoutingContext context) {
String name = context.request().getParam("name");
ASSERT.isTrue(StringUtils.isNotBlank(name), ErrorCode.ILLEGAL_ARGUMENT, "name mustn't be empty");
User user = context.get(USER_INFO_KEY);
fileService.rxFile(name)
.doOnSuccess(file -> assertFileAvailable(file))
.doOnSuccess(file -> checkPermission(user, file))
.doOnSuccess(file -> ASSERT.isTrue(file.transferred(), ErrorCode.NOT_TRANSFERRED))
.flatMap(file -> WorkerClient.send(context.request(), file.getHostIP()))
.subscribe(resp -> HTTPRespGuarder.ok(context, resp.statusCode(), resp.bodyAsString()),
t -> HTTPRespGuarder.fail(context, t));
}
private void setShared(RoutingContext context) {
String name = context.request().getParam("name");
User user = context.get(USER_INFO_KEY);
fileService.rxFile(name)
.doOnSuccess(file -> ASSERT.isTrue(file.found(), ErrorCode.FILE_DOES_NOT_EXIST))
.doOnSuccess(file -> checkPermission(user, file))
.ignoreElement()
.andThen(fileService.rxSetShared(name))
.subscribe(() -> HTTPRespGuarder.ok(context),
t -> HTTPRespGuarder.fail(context, t));
}
private void updateDisplayName(RoutingContext context) {
String name = context.request().getParam("name");
String displayName = context.request().getParam("displayName");
User user = context.get(USER_INFO_KEY);
fileService.rxFile(name)
.doOnSuccess(file -> ASSERT.isTrue(file.found(), ErrorCode.FILE_DOES_NOT_EXIST))
.doOnSuccess(file -> checkPermission(user, file))
.ignoreElement()
.andThen(fileService.rxUpdateDisplayName(name, displayName))
.subscribe(() -> HTTPRespGuarder.ok(context),
t -> HTTPRespGuarder.fail(context, t));
}
private void publicKey(RoutingContext context) {
HTTPRespGuarder.ok(context, PUB_KEY);
}
private void unsetShared(RoutingContext context) {
HTTPRespGuarder.fail(context, new JifaException(ErrorCode.UNSUPPORTED_OPERATION));
}
private String extractOriginalName(String path) {
String name = path.substring(path.lastIndexOf(java.io.File.separatorChar) + 1);
if (name.contains("?")) {
name = name.substring(0, name.indexOf("?"));
}
name = name.replaceAll("[%\\\\& ]", "_");
if (name.length() == 0) {
name = System.currentTimeMillis() + "";
}
return name;
}
private Map<String, String> convert(MultiMap src) {
Map<String, String> target = new HashMap<>();
for (Map.Entry<String, String> entry : src) {
target.put(entry.getKey(), entry.getValue());
}
return target;
}
private TransferProgress toProgress(File file) {
FileTransferState transferState = file.getTransferState();
ASSERT.isTrue(transferState.isFinal(), ErrorCode.SANITY_CHECK);
TransferProgress progress = new TransferProgress();
progress.setState(transferState.toProgressState());
progress.setTotalSize(file.getSize());
if (transferState == FileTransferState.SUCCESS) {
progress.setPercent(1.0);
progress.setTransferredSize(file.getSize());
}
return progress;
}
private void download(RoutingContext context) {
String name = context.request().getParam("name");
User user = context.get(USER_INFO_KEY);
fileService.rxFile(name)
.doOnSuccess(file -> ASSERT.isTrue(file.found(), ErrorCode.FILE_DOES_NOT_EXIST))
.doOnSuccess(file -> checkPermission(user, file))
.flatMap(file -> {
context.response()
.putHeader(HEADER_CONTENT_LENGTH_KEY, String.valueOf(file.getSize()))
.putHeader(HEADER_CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
.putHeader(HEADER_CONTENT_TYPE_KEY, CONTENT_TYPE_FILE_FORM);
HttpRequest<Buffer> workerRequest = WorkerClient.request(context.request().method(), file.getHostIP(), context.request().uri());
workerRequest.as(BodyCodec.pipe(context.response()));
return WorkerClient.send(workerRequest, context.request().method() == HttpMethod.POST, null);
})
.subscribe(resp -> context.response().end(),
t -> HTTPRespGuarder.fail(context, t));
}
private void upload(RoutingContext context) {
FileUpload[] fileUploads = context.fileUploads().toArray(new FileUpload[0]);
if (fileUploads.length == 0) {
HTTPRespGuarder.ok(context);
return;
}
FileUpload file = fileUploads[0];
String userId = context.<User>get(USER_INFO_KEY).getId();
HttpServerRequest request = context.request();
String origin = file.fileName();
FileType type = FileType.valueOf(context.request().getParam("type"));
String name = buildFileName(userId, origin);
request.params().add("fileName", name);
fileService.rxTransfer(userId, type, origin, name, TransferWay.UPLOAD, convert(request.params()))
.flatMap(job -> WorkerClient.uploadFile(job.getHostIP(),
new java.io.File(file.uploadedFileName()),
name,
type))
.subscribe(resp -> {
FileTransferState state = resp.statusCode() == Constant.HTTP_POST_CREATED_STATUS ?
FileTransferState.SUCCESS : FileTransferState.ERROR;
fileService.rxTransferDone(name, state, file.size())
.subscribe(
() -> HTTPRespGuarder
.ok(context, resp.statusCode(), new TransferringFile(name)),
t -> HTTPRespGuarder.fail(context, t)
);
context.vertx().executeBlocking(
p -> {
for (FileUpload f : fileUploads) {
context.vertx().fileSystem().delete(f.uploadedFileName());
}
}
);
},
t -> HTTPRespGuarder.fail(context, t));
}
}
| 6,818 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/JobRoute.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.service.ProxyDictionary;
import org.eclipse.jifa.master.service.reactivex.JobService;
import org.eclipse.jifa.master.vo.PendingJob;
import org.eclipse.jifa.master.vo.PendingJobsResult;
import java.util.ArrayList;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
class JobRoute extends BaseRoute implements Constant {
private JobService jobService;
void init(Vertx vertx, JsonObject config, Router apiRouter) {
jobService = ProxyDictionary.lookup(JobService.class);
apiRouter.get().path(PENDING_JOBS).handler(this::frontPendingJobs);
}
private void frontPendingJobs(RoutingContext context) {
JobType type = JobType.valueOf(context.request().getParam("type"));
String target = context.request().getParam("target");
jobService.rxFindActive(type, target)
.doOnSuccess(this::assertJobExist)
.flatMap(job -> {
if (job.getState() == JobState.IN_PROGRESS) {
return Single.just(new PendingJobsResult(true));
}
ASSERT.isTrue(job.getState() == JobState.PENDING, ErrorCode.SANITY_CHECK);
return jobService.rxPendingJobsInFrontOf(job)
.map(fronts -> {
ArrayList<Job> jobs = new ArrayList<>(fronts);
jobs.add(job);
return jobs;
})
.map(fronts -> fronts.stream().map(PendingJob::new).collect(Collectors.toList()))
.map(PendingJobsResult::new);
})
.subscribe(result -> HTTPRespGuarder.ok(context, result),
t -> HTTPRespGuarder.fail(context, t));
}
}
| 6,819 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/AdminRoute.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.service.ProxyDictionary;
import org.eclipse.jifa.master.service.reactivex.AdminService;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
public class AdminRoute extends BaseRoute {
private AdminService adminService;
void init(Vertx vertx, JsonObject config, Router apiRouter) {
adminService = ProxyDictionary.lookup(AdminService.class);
apiRouter.post().path(Constant.ADD_ADMIN).handler(this::add);
apiRouter.get().path(Constant.QUERY_ALL_ADMIN).handler(this::queryAll);
}
private void add(RoutingContext context) {
User user = context.get(USER_INFO_KEY);
ASSERT.isTrue(user.isAdmin(), ErrorCode.FORBIDDEN);
String userId = context.request().getParam("userId");
adminService.rxAdd(userId)
.subscribe(() -> HTTPRespGuarder.ok(context),
t -> HTTPRespGuarder.fail(context, t));
}
private void queryAll(RoutingContext context) {
User user = context.get(USER_INFO_KEY);
ASSERT.isTrue(user.isAdmin(), ErrorCode.FORBIDDEN);
adminService.rxQueryAll()
.subscribe(admins -> HTTPRespGuarder.ok(context, admins),
t -> HTTPRespGuarder.fail(context, t));
}
}
| 6,820 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/BaseRoute.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import com.google.common.base.Strings;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.vo.PendingJob;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
class BaseRoute implements Constant {
static final String SEP = "-";
void assertFileAvailable(File file) {
ASSERT.isTrue(file.found(), ErrorCode.FILE_DOES_NOT_EXIST);
ASSERT.isTrue(!file.isDeleted(), ErrorCode.FILE_HAS_BEEN_DELETED);
}
void assertJobExist(Job job) {
ASSERT.isTrue(job.found(), ErrorCode.JOB_DOES_NOT_EXIST);
}
void checkPermission(User user, File file) {
ASSERT.isTrue(file.isShared() || file.getUserId().equals(user.getId()) || user.isAdmin(),
ErrorCode.FORBIDDEN);
}
void checkDeletePermission(User user, File file) {
ASSERT.isTrue(file.getUserId().equals(user.getId()) || user.isAdmin(), ErrorCode.FORBIDDEN);
}
void checkPermission(User user, Job job) {
ASSERT.isTrue(job.getUserId().equals(user.getId()) || user.isAdmin(), ErrorCode.FORBIDDEN);
}
void assertJobInProgress(Job job) {
ASSERT.isTrue(job.getState() != JobState.PENDING, ErrorCode.PENDING_JOB,
() -> GSON.toJson(new PendingJob(job)))
.isTrue(job.getState() == JobState.IN_PROGRESS, ErrorCode.SANITY_CHECK);
}
String buildFileName(String userId, String originalName) {
ASSERT.isTrue(!Strings.isNullOrEmpty(userId), ErrorCode.ILLEGAL_ARGUMENT);
ASSERT.isTrue(!Strings.isNullOrEmpty(originalName), ErrorCode.ILLEGAL_ARGUMENT);
return userId + SEP + System.currentTimeMillis() + SEP + originalName;
}
}
| 6,821 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/http/AnalyzerRoute.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.http;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.model.User;
import org.eclipse.jifa.master.service.ProxyDictionary;
import org.eclipse.jifa.master.service.reactivex.FileService;
import org.eclipse.jifa.master.service.reactivex.JobService;
import org.eclipse.jifa.master.support.Utils;
import org.eclipse.jifa.master.support.WorkerClient;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.master.entity.enums.JobType.*;
class AnalyzerRoute extends BaseRoute {
private JobService jobService;
private FileService fileService;
void init(Vertx vertx, JsonObject config, Router apiRouter) {
jobService = ProxyDictionary.lookup(JobService.class);
fileService = ProxyDictionary.lookup(FileService.class);
// heap dump
// Do not change the order !!
apiRouter.route().path(HEAP_DUMP_RELEASE).handler(context -> release(context, HEAP_DUMP_ANALYSIS));
apiRouter.route().path(HEAP_DUMP_COMMON).handler(context -> process(context, HEAP_DUMP_ANALYSIS));
// gclog
apiRouter.route().path(GCLOG_RELEASE).handler(context -> release(context, GCLOG_ANALYSIS));
apiRouter.route().path(GCLOG_COMMON).handler(context -> process(context, GCLOG_ANALYSIS));
// thread dump
apiRouter.route().path(THREAD_DUMP_RELEASE).handler(context -> release(context, THREAD_DUMP_ANALYSIS));
apiRouter.route().path(THREAD_DUMP_COMMON).handler(context -> process(context, THREAD_DUMP_ANALYSIS));
}
private Single<Job> findOrAllocate(User user, File file, JobType jobType) {
String target = file.getName();
return jobService.rxFindActive(jobType, target)
.flatMap(job -> job.found() ?
Single.just(job) :
jobService.rxAllocate(user.getId(), file.getHostIP(), jobType,
target, EMPTY_STRING, Utils.calculateLoadFromSize(file.getSize()), false)
);
}
private void release(RoutingContext context, JobType jobType) {
User user = context.get(Constant.USER_INFO_KEY);
String fileName = context.request().getParam("file");
fileService.rxFile(fileName)
.doOnSuccess(file -> assertFileAvailable(file))
.doOnSuccess(file -> checkPermission(user, file))
.flatMap(file -> jobService.rxFindActive(jobType, file.getName()))
.doOnSuccess(this::assertJobExist)
.doOnSuccess(job -> ASSERT.isTrue(job.getState() != JobState.PENDING,
ErrorCode.RELEASE_PENDING_JOB))
.ignoreElement()
.andThen(jobService.rxFinish(jobType, fileName))
.subscribe(() -> HTTPRespGuarder.ok(context),
t -> HTTPRespGuarder.fail(context, t));
}
private void process(RoutingContext context, JobType jobType) {
User user = context.get(Constant.USER_INFO_KEY);
context.request().params().add("userName", user.getName());
String fileName = context.request().getParam("file");
fileService.rxFile(fileName)
.doOnSuccess(file -> assertFileAvailable(file))
.doOnSuccess(file -> checkPermission(user, file))
.doOnSuccess(file -> ASSERT.isTrue(file.transferred(), ErrorCode.NOT_TRANSFERRED))
.flatMap(file -> findOrAllocate(user, file, jobType))
.doOnSuccess(this::assertJobInProgress)
.flatMap(job -> WorkerClient.send(context.request(), job.getHostIP()))
.subscribe(resp -> HTTPRespGuarder.ok(context, resp.statusCode(), resp.bodyAsString()),
t -> HTTPRespGuarder.fail(context, t));
}
}
| 6,822 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/TransferJobResultFillingTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Completable;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.JobHelper;
import java.time.Instant;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.ServiceAssertion.SERVICE_ASSERT;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
import static org.eclipse.jifa.master.service.sql.JobSQL.SELECT_TRANSFER_JOB_TO_FILLING_RESULT;
public class TransferJobResultFillingTask extends BaseTask {
private static final long MIN_TIMEOUT_THRESHOLD = 5 * 6000;
private long timeoutThreshold;
public TransferJobResultFillingTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "Transfer Job Result Filling Task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-TRANSFER-RESULT-FILLING-INTERVAL"));
}
@Override
public void doInit() {
timeoutThreshold = ConfigHelper.getLong(pivot.config("JOB-SMALL-TIMEOUT-THRESHOLD"));
// timeout threshold must be greater than or equal to 5 min
SERVICE_ASSERT.isTrue(timeoutThreshold >= MIN_TIMEOUT_THRESHOLD, ErrorCode.SANITY_CHECK);
}
@Override
public void doPeriodic() {
Instant instant = Instant.now().minusMillis(timeoutThreshold);
pivot.getDbClient().rxQueryWithParams(SELECT_TRANSFER_JOB_TO_FILLING_RESULT, ja(instant))
.map(result -> result.getRows().stream().map(JobHelper::fromDBRecord).collect(Collectors.toList()))
.doOnSuccess(jobs -> LOGGER.info("Found timeout file transfer jobs: {}", jobs.size()))
.map(jobs -> jobs.stream().map(pivot::processTimeoutTransferJob).collect(Collectors.toList()))
.flatMapCompletable(Completable::concat)
.subscribe(
this::end,
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
} | 6,823 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/StopAbnormalWorkerTask.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Single;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.JobHelper;
import org.eclipse.jifa.master.service.sql.JobSQL;
import org.eclipse.jifa.master.support.K8SWorkerScheduler;
import java.util.List;
import java.util.stream.Collectors;
public class StopAbnormalWorkerTask extends BaseTask {
public StopAbnormalWorkerTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "Stop Abnormal Worker Task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("TASK-STOP-ABNORMAL-WORKER"));
}
@Override
public void doInit() {
}
@Override
public void doPeriodic() {
pivot.getDbClient().rxQuery(JobSQL.SELECT_ALL_ACTIVE_JOBS)
.map(result -> result.getRows().stream().map(JobHelper::fromDBRecord).collect(Collectors.toList()))
.flatMap(jobs -> {
// Every active job has its own worker, they should never be stopped
List<String> activeWorkers = jobs.stream().map(job ->
pivot.getScheduler().decide(job, null).blockingGet().getHostName()
).collect(Collectors.toList());
// Find all live workers in cloud cluster
return pivot.getScheduler()
.list()
.flatMap(workers -> {
for (Worker worker : workers) {
// Only watch upon normal worker groups, any other special workers have their special lifecycle
if (worker.getHostName().startsWith(K8SWorkerScheduler.getNormalWorkerPrefix())) {
if (!activeWorkers.contains(worker.getHostName())) {
return pivot.getScheduler().stop(worker).toSingleDefault(worker);
}
}
}
return Single.just(Worker.NOT_FOUND);
});
})
.subscribe(n -> {
if (n != Worker.NOT_FOUND) {
LOGGER.info("Stopped abnormal worker {}/{}", n.getHostName(), n.getHostIP());
}
end();
},
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
}
| 6,824 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/BaseTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class BaseTask {
public static final Logger LOGGER = LoggerFactory.getLogger(BaseTask.class);
protected final Pivot pivot;
private final AtomicBoolean PROCESSING = new AtomicBoolean(false);
BaseTask(Pivot pivot, Vertx vertx) {
this.pivot = pivot;
init(vertx);
}
public abstract String name();
public abstract long interval();
void end() {
doEnd();
LOGGER.info("{} end", name());
PROCESSING.set(false);
}
public void doEnd() {
}
public void doInit() {
}
public abstract void doPeriodic();
private void init(Vertx vertx) {
try {
vertx.setPeriodic(interval(), this::periodic);
doInit();
LOGGER.info("Init {} successfully", name());
} catch (Throwable t) {
LOGGER.error("Init {} error", name(), t);
System.exit(-1);
}
}
private void periodic(Long ignored) {
if (PROCESSING.get() || !PROCESSING.compareAndSet(false, true)) {
return;
}
LOGGER.info("Start {}", name());
doPeriodic();
}
public void trigger() {
periodic(0L);
}
}
| 6,825 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/DiskUsageUpdatingTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.vertx.ext.sql.UpdateResult;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.common.vo.DiskUsage;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.WorkerHelper;
import org.eclipse.jifa.master.service.sql.WorkerSQL;
import org.eclipse.jifa.master.support.WorkerClient;
import java.util.List;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
import static org.eclipse.jifa.master.Constant.uri;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class DiskUsageUpdatingTask extends BaseTask {
public DiskUsageUpdatingTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "Worker disk usage updating task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-DISK-USAGE-UPDATING-PERIODIC"));
}
@Override
public void doPeriodic() {
getWorkers().flatMapObservable(
workerList -> Observable.fromIterable(workerList)
.flatMapSingle(
worker -> WorkerClient.get(worker.getHostIP(), uri(Constant.SYSTEM_DISK_USAGE))
.map(resp -> GSON.fromJson(resp.bodyAsString(), DiskUsage.class))
.flatMap(usage -> updateWorkerDiskUsage(worker.getHostIP(),
usage.getTotalSpaceInMb(),
usage.getUsedSpaceInMb()))
)
).ignoreElements().subscribe(this::end, t -> {
LOGGER.error("Execute {} error", name(), t);
end();
});
}
private Single<UpdateResult> updateWorkerDiskUsage(String hostIP, long totalSpaceInMb, long usedSpaceInMb) {
return pivot.getDbClient()
.rxUpdateWithParams(WorkerSQL.UPDATE_DISK_USAGE, ja(totalSpaceInMb, usedSpaceInMb, hostIP))
.doOnSuccess(updateResult -> ASSERT.isTrue(updateResult.getUpdated() == 1));
}
private Single<List<Worker>> getWorkers() {
return pivot.getDbClient()
.rxQuery(WorkerSQL.SELECT_ALL)
.map(records ->
records.getRows().stream().map(WorkerHelper::fromDBRecord).collect(Collectors.toList())
);
}
}
| 6,826 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/DiskCleaningTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.sql.ConfigSQL;
import org.eclipse.jifa.master.service.sql.FileSQL;
import org.eclipse.jifa.master.service.sql.WorkerSQL;
import java.util.List;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class DiskCleaningTask extends BaseTask {
public DiskCleaningTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
/**
* The logic is straightforward, assume we have a disk cleaning thread named D and
* a user thread named U, we can use CAS operation to handle both user requesting
* and system disk cleaning, the pseudocode is as follows:
* <code>
* void U(){
* if(atomic.cmpxchg(in_use,0,1){
* // using
* atomic.cmpxchg(in_use,1,0)
* }
* }
* <p>
* void D(){
* if(atomic.cmpxchg(in_use,0,2){
* // deleting
* atomic.cmpxchg(in_use,2,0);
* }
* }
* </code>
*/
private static Observable<Completable> markAndDeleteFiles(JDBCClient jdbcClient, Pivot pivot,
List<String> workerIpList) {
return Observable.fromIterable(workerIpList)
.flatMap(
workerIp -> jdbcClient.rxUpdateWithParams(FileSQL.UPDATE_AS_PENDING_DELETE_BY_HOST, ja(workerIp))
.ignoreElement()
.andThen(jdbcClient.rxQueryWithParams(FileSQL.SELECT_PENDING_DELETE_BY_HOST,
ja(workerIp))
.map(rs -> rs.getRows().stream()
.map(row -> row.getString("name"))
.collect(Collectors.toList()))
.flatMapCompletable(fileNames -> pivot
.deleteFile(Deleter.SYSTEM,
fileNames.toArray(new String[0])))
)
.toObservable()
);
}
@Override
public String name() {
return "Disk cleaning task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-DISK-CLEANUP-PERIODIC"));
}
@Override
public void doPeriodic() {
// Get high dick overload workers, for each of them, get all files which
// neither deleted nor used in that worker, finally, apply real disk cleanup
// action for every file in that list
isEnableDiskCleaning()
.subscribe(val -> getHighDiskOverloadWorkers()
.flatMapObservable(workerIpList -> markAndDeleteFiles(pivot.getDbClient(), pivot, workerIpList))
.ignoreElements()
.subscribe(
() -> {
LOGGER.info("Execute {} successfully ", name());
this.end();
},
t -> {
LOGGER.error("Execute {} error", name(), t);
this.end();
}
)
);
}
private Maybe<List<String>> getHighDiskOverloadWorkers() {
return pivot.getDbClient().rxQuery(WorkerSQL.SELECT_FOR_DISK_CLEANUP)
.map(rs -> rs.getRows().stream().map(jo -> jo.getString("host_ip")).collect(Collectors.toList()))
.filter(workers -> workers.size() > 0);
}
private Maybe<Long> isEnableDiskCleaning() {
return pivot.getDbClient()
.rxQueryWithParams(ConfigSQL.SELECT, ja("TASK-ENABLE-DISK-CLEANUP"))
.map(resultSet -> resultSet.getRows().get(0).getString("value"))
.map(Long::valueOf)
.filter(value -> value == 1);
}
}
| 6,827 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/RetiringTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Completable;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.JobHelper;
import java.time.Instant;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.ServiceAssertion.SERVICE_ASSERT;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
import static org.eclipse.jifa.master.service.sql.JobSQL.SELECT_TO_RETIRE;
public class RetiringTask extends BaseTask {
private static long MIN_TIMEOUT_THRESHOLD = 5 * 6000L;
private static long timeoutThreshold;
public RetiringTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "Retiring Task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-RETIRING-INTERVAL"));
}
@Override
public void doInit() {
timeoutThreshold = ConfigHelper.getLong(pivot.config("JOB-COMMON-TIMEOUT-THRESHOLD"));
// timeout threshold must be greater than or equal to 5 min
SERVICE_ASSERT.isTrue(timeoutThreshold >= MIN_TIMEOUT_THRESHOLD, ErrorCode.SANITY_CHECK);
}
@Override
public void doPeriodic() {
Instant instant = Instant.now().minusMillis(timeoutThreshold);
pivot.getDbClient().rxQueryWithParams(SELECT_TO_RETIRE, ja(instant))
.map(result -> result.getRows().stream().map(JobHelper::fromDBRecord).collect(Collectors.toList()))
.doOnSuccess(jobs -> LOGGER.info("Found timeout jobs: {}", jobs.size()))
.map(jobs -> jobs.stream().map(pivot::finish).collect(Collectors.toList()))
.flatMapCompletable(Completable::concat)
.subscribe(
this::end,
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
} | 6,828 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/FileSyncForK8STask.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Completable;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.apache.commons.io.FileUtils;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.FileHelper;
import org.eclipse.jifa.master.service.sql.FileSQL;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Clean up any stale files that does not record in database. The cleanup is
* exactly different from FileSyncTask, otherwise, they look like the same one.
*/
public class FileSyncForK8STask extends FileSyncTask {
// TODO: should reuse WorkerGlobal.WORKSPACE and related functionalities
private static final String WORKSPACE = Constant.DEFAULT_WORKSPACE;
public FileSyncForK8STask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
private static String dirPath(FileType type) {
return WORKSPACE + java.io.File.separator + type.getTag();
}
private static void delete(FileType type, String name) {
try {
java.io.File f = new java.io.File(dirPath(type) + java.io.File.separator + name);
if (f.isDirectory()) {
FileUtils.deleteDirectory(f);
}
} catch (IOException e) {
LOGGER.error("Delete file failed", e);
throw new JifaException(e);
}
}
@Override
public String name() {
return "File Sync For K8S Task";
}
@Override
public void doPeriodic() {
JDBCClient dbClient = pivot.getDbClient();
dbClient.rxQuery(FileSQL.SELECT_FILES_FOR_SYNC)
.map(ar -> ar.getRows().stream().map(FileHelper::fromDBRecord).collect(Collectors.toList()))
.flatMapCompletable(
files -> {
// Clean up any files that exist in workspace while not recorded in database
// Merely a mirror of FileSupport.sync
Map<FileType, List<String>> filesGroup = new HashMap<>(){{
for (FileType ft : FileType.values()) {
// In case no files returned
this.put(ft, new ArrayList<>());
}
}};
for (File fi : files) {
filesGroup.get(fi.getType()).add(fi.getName());
}
long lastModified = System.currentTimeMillis() - Constant.STALE_THRESHOLD;
for (FileType ft : filesGroup.keySet()) {
List<String> names = filesGroup.get(ft);
java.io.File[] listFiles = new java.io.File(dirPath(ft)).listFiles();
if (listFiles == null) {
continue;
}
for (java.io.File lf : listFiles) {
if (names.contains(lf.getName())) {
continue;
}
LOGGER.info("{} is not synchronized", lf.getName());
if (isCleanStale() && lf.lastModified() < lastModified) {
LOGGER.info("Delete stale file {}", lf.getName());
delete(ft, lf.getName());
}
}
}
return Completable.complete();
}
).andThen(processLongTransferJob())
.subscribe(this::end,
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
}
| 6,829 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/FileSyncTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.FileHelper;
import org.eclipse.jifa.master.service.impl.helper.WorkerHelper;
import org.eclipse.jifa.master.service.sql.FileSQL;
import org.eclipse.jifa.master.service.sql.JobSQL;
import org.eclipse.jifa.master.service.sql.WorkerSQL;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class FileSyncTask extends BaseTask {
private boolean cleanStale;
public FileSyncTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
public boolean isCleanStale() {
return cleanStale;
}
@Override
public String name() {
return "File Sync Task";
}
@Override
public long interval() {
// 1 hour
return 60 * 60 * 1000;
}
@Override
public void doInit() {
cleanStale = ConfigHelper.getBoolean(pivot.config("JOB-CLEAN-STALE-FILES"));
}
@Override
public void doPeriodic() {
pivot.getDbClient().rxQuery(WorkerSQL.SELECT_ALL)
.map(records -> records.getRows()
.stream()
.map(WorkerHelper::fromDBRecord)
.collect(Collectors.toList()))
.flatMapCompletable(workers ->
Observable.fromIterable(workers)
.flatMapCompletable(
worker -> pivot.syncFiles(worker, cleanStale)
.doOnError(t -> LOGGER.error(
"Failed to sync worker files for {} ", worker.getHostIP(), t))
.onErrorComplete()
)
).andThen(processLongTransferJob()).subscribe(this::end,
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
/**
* Mark files that takes too long time to upload and not recorded in active jobs as ERROR state
*/
protected Completable processLongTransferJob() {
JDBCClient dbClient = pivot.getDbClient();
return dbClient.rxQuery(FileSQL.SELECT_TIMEOUT_IN_PROGRESS_FILE)
.map(records -> records.getRows()
.stream()
.map(FileHelper::fromDBRecord)
.collect(Collectors.toList()))
.flatMapCompletable(
files ->
Observable.fromIterable(files)
.flatMapCompletable(
file -> dbClient.rxQueryWithParams(JobSQL.SELECT_TRANSFER_JOB_BY_NAME, ja(file.getName()))
.flatMapCompletable(
rs -> {
if (rs.getRows().size() > 0) {
return Completable.complete();
}
// set state to error if not associated job
return dbClient.rxUpdateWithParams(FileSQL.UPDATE_IN_PROGRESS_FILE_AS_ERROR_BY_NAME, ja(file.getName()))
.ignoreElement();
})
.doOnError(t -> LOGGER
.error("Failed to sync file transfer state for {}", file.getName(),
t))
.onErrorComplete())
);
}
}
| 6,830 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/SchedulingTask.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Single;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.JobHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.sql.JobSQL.SELECT_ALL_PENDING;
public class SchedulingTask extends BaseTask {
private int index;
private List<Job> pendingJobs = new ArrayList<>();
private Set<String> pinnedHostIPs = new HashSet<>();
public SchedulingTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "Scheduling Task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-SCHEDULING-INTERVAL"));
}
@Override
public void doPeriodic() {
pivot.getDbClient().rxQuery(SELECT_ALL_PENDING)
.map(
records -> records.getRows().stream().map(JobHelper::fromDBRecord).collect(Collectors.toList()))
.map(jobs -> {
pendingJobs.addAll(jobs);
LOGGER.info("Found pending jobs: {}", pendingJobs.size());
return pendingJobs.size() > 0;
})
.subscribe(hasPendingJobs -> {
if (hasPendingJobs) {
processNextPendingJob();
} else {
end();
}
}, t -> {
LOGGER.error("Execute {} error", name(), t);
end();
});
}
@Override
public void doEnd() {
index = 0;
pendingJobs.clear();
pinnedHostIPs.clear();
}
private void processNextPendingJob() {
if (index < pendingJobs.size()) {
processJob(pendingJobs.get(index++))
.subscribe(
next -> {
if (next) {
processNextPendingJob();
}
},
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
} else {
end();
}
}
private Single<Boolean> processJob(Job job) {
return job.getHostIP() == null ? processNoBindingJob(job) : processBindingJob(job);
}
private Single<Boolean> processNoBindingJob(Job job) {
return pivot.inTransactionAndLock(
conn -> pivot.selectMostIdleWorker(conn).flatMap(
worker -> {
long loadSum = worker.getCurrentLoad() + job.getEstimatedLoad();
if (loadSum > worker.getMaxLoad()) {
return Single.just(false);
}
String hostIP = worker.getHostIP();
job.setHostIP(hostIP);
return pivot.updatePendingJobToInProcess(conn, job)
.andThen(pivot.updateWorkerLoad(conn, hostIP, loadSum))
.toSingleDefault(true);
}
)
).doOnSuccess(e -> pivot.postInProgressJob(job).subscribe());
}
private Single<Boolean> processBindingJob(Job job) {
return pivot.inTransactionAndLock(
conn -> pivot.selectWorker(conn, job.getHostIP()).flatMap(
worker -> {
String hostIP = worker.getHostIP();
if (pinnedHostIPs.contains(hostIP)) {
return Single.just(true);
}
long loadSum = worker.getCurrentLoad() + job.getEstimatedLoad();
if (loadSum > worker.getMaxLoad()) {
LOGGER.info("Pin host: {}", hostIP);
pinnedHostIPs.add(hostIP);
return Single.just(true);
}
return pivot.updatePendingJobToInProcess(conn, job)
.andThen(pivot.updateWorkerLoad(conn, hostIP, loadSum))
.toSingleDefault(true);
}
)
).doOnSuccess(e -> pivot.postInProgressJob(job).subscribe());
}
} | 6,831 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/task/PVCCleanupTask.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.task;
import io.reactivex.Observable;
import io.vertx.reactivex.core.Vertx;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.helper.ConfigHelper;
import org.eclipse.jifa.master.service.impl.helper.FileHelper;
import org.eclipse.jifa.master.service.sql.FileSQL;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
/**
* Periodically clean up dump files that stored at k8s persistent volume claim.
*/
public class PVCCleanupTask extends BaseTask {
private static final String WORKSPACE = "/root/jifa_workspace";
public PVCCleanupTask(Pivot pivot, Vertx vertx) {
super(pivot, vertx);
}
@Override
public String name() {
return "PVC Cleanup Task";
}
@Override
public long interval() {
return ConfigHelper.getLong(pivot.config("JOB-DISK-CLEANUP-PERIODIC"));
}
@Override
public void doInit() {
}
@Override
public void doPeriodic() {
pivot.getDbClient().rxQuery(FileSQL.SELECT_DATED_FILES)
.map(result -> result.getRows().stream().map(FileHelper::fromDBRecord).collect(Collectors.toList()))
.doOnSuccess(files -> LOGGER.info("Found dated files for deletion: {}", files.size()))
.flatMapCompletable(files ->
Observable.fromIterable(files.stream().map(File::getName).collect(Collectors.toList()))
.flatMapCompletable(
fileName ->
pivot.getDbClient()
.rxUpdateWithParams(FileSQL.UPDATE_AS_PENDING_DELETE_BY_FILE_NAME, ja(fileName))
.ignoreElement()
.andThen(
pivot.getDbClient()
.rxQueryWithParams(FileSQL.SELECT_PENDING_DELETE_BY_FILE_NAME, ja(fileName))
.map(rs -> rs.getRows().stream().map(row -> row.getString("name")).collect(Collectors.toList()))
.flatMapCompletable(fileNames -> pivot
.deleteFile(Deleter.SYSTEM, fileNames.toArray(new String[0]))
.doOnComplete(()->LOGGER.info("Deleted {} files by {}", fileNames.size(), this.name()))
)
)
)
)
.subscribe(() -> {
this.end();
},
t -> {
LOGGER.error("Execute {} error", name(), t);
end();
}
);
}
} | 6,832 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/model/TransferWay.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.model;
import static org.eclipse.jifa.master.Constant.*;
public enum TransferWay {
URL(uri(TRANSFER_BY_URL), "url"),
SCP(uri(TRANSFER_BY_SCP), "path"),
OSS(uri(TRANSFER_BY_OSS), "objectName"),
S3(uri(TRANSFER_BY_S3), "objectName"),
UPLOAD(uri(FILE_UPLOAD), "");
private String[] pathKey;
private String uri;
TransferWay(String uri, String... pathKey) {
this.pathKey = pathKey;
this.uri = uri;
}
public String[] getPathKeys() {
return pathKey;
}
public String getUri() {
return uri;
}
}
| 6,833 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/model/User.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.model;
import lombok.Data;
@Data
public class User {
private String id;
private String name;
private boolean admin;
public User(String id, String name, boolean admin) {
this.id = id;
this.name = name;
this.admin = admin;
}
}
| 6,834 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/model/WorkerInfo.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.model;
import lombok.Data;
@Data
public class WorkerInfo {
private String name;
private String ip;
}
| 6,835 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/AdminService.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.master.entity.Admin;
import org.eclipse.jifa.master.service.impl.AdminServiceImpl;
import java.util.List;
@ProxyGen
@VertxGen
public interface AdminService {
@GenIgnore
static void create(Vertx vertx, JDBCClient dbClient) {
new ServiceBinder(vertx.getDelegate()).setAddress(AdminService.class.getSimpleName())
.register(AdminService.class, new AdminServiceImpl(dbClient));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(AdminService.class, new org.eclipse.jifa.master.service.reactivex.AdminService(
new AdminServiceVertxEBProxy(vertx.getDelegate(), AdminService.class.getSimpleName())));
}
void isAdmin(String userId, Handler<AsyncResult<Boolean>> handler);
void add(String userId, Handler<AsyncResult<Void>> handler);
void queryAll(Handler<AsyncResult<List<Admin>>> handler);
}
| 6,836 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/WorkerService.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.WorkerServiceImpl;
import java.util.List;
@ProxyGen
@VertxGen
public interface WorkerService {
@GenIgnore
static void create(Vertx vertx, JDBCClient dbClient, Pivot pivot) {
new ServiceBinder(vertx.getDelegate()).setAddress(WorkerService.class.getSimpleName())
.register(WorkerService.class, new WorkerServiceImpl(dbClient, pivot));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(WorkerService.class, new org.eclipse.jifa.master.service.reactivex.WorkerService(
new WorkerServiceVertxEBProxy(vertx.getDelegate(), WorkerService.class.getSimpleName())));
}
void queryAll(Handler<AsyncResult<List<Worker>>> handler);
void diskCleanup(String hostIP, Handler<AsyncResult<Void>> handler);
void selectMostIdleWorker(Handler<AsyncResult<Worker>> handler);
void selectWorkerByIP(String hostIp, Handler<AsyncResult<Worker>> handler);
}
| 6,837 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/JobService.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.service.impl.JobServiceImpl;
import org.eclipse.jifa.master.service.impl.Pivot;
import java.util.List;
@ProxyGen
@VertxGen
public interface JobService {
@GenIgnore
static void create(Vertx vertx, Pivot pivot, JDBCClient dbClient) {
new ServiceBinder(vertx.getDelegate())
.setAddress(JobService.class.getSimpleName())
.register(JobService.class, new JobServiceImpl(pivot, dbClient));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(JobService.class, new org.eclipse.jifa.master.service.reactivex.JobService(
new JobServiceVertxEBProxy(vertx.getDelegate(), JobService.class.getSimpleName())));
}
void findActive(JobType jobType, String target, Handler<AsyncResult<Job>> handler);
void pendingJobsInFrontOf(Job job, Handler<AsyncResult<List<Job>>> handler);
void allocate(String userId, String hostIP, JobType jobType, String target,
String attachment, long estimatedLoad,
boolean immediate,
Handler<AsyncResult<Job>> handler);
void finish(JobType type, String target, Handler<AsyncResult<Void>> handler);
}
| 6,838 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/ProxyDictionary.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
public class ProxyDictionary {
private static Map<String, Object> proxyMap = new ConcurrentHashMap<>();
static synchronized void add(Class<?> serviceInterface, Object proxy) {
proxyMap.put(serviceInterface.getSimpleName(), proxy);
}
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<?> key) {
Object proxy = proxyMap.get(key.getSimpleName());
ASSERT.notNull(proxy);
return (T) proxy;
}
}
| 6,839 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/ServiceAssertion.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.serviceproxy.ServiceException;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.util.Assertion;
public class ServiceAssertion extends Assertion {
public static final ServiceAssertion SERVICE_ASSERT = new ServiceAssertion();
@Override
protected void throwEx(ErrorCode errorCode, String message) {
throw new ServiceException(errorCode.ordinal(), message);
}
}
| 6,840 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/FileService.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.model.TransferWay;
import org.eclipse.jifa.master.service.impl.FileServiceImpl;
import org.eclipse.jifa.master.service.impl.Pivot;
import java.util.List;
import java.util.Map;
@ProxyGen
@VertxGen
public interface FileService {
@GenIgnore
static void create(Vertx vertx, Pivot pivot, JDBCClient dbClient) {
new ServiceBinder(vertx.getDelegate())
.setAddress(FileService.class.getSimpleName())
.register(FileService.class, new FileServiceImpl(pivot, dbClient));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(FileService.class, new org.eclipse.jifa.master.service.reactivex.FileService(
new FileServiceVertxEBProxy(vertx.getDelegate(), FileService.class.getSimpleName())));
}
void count(String userId, FileType type, String expectedFilename, Handler<AsyncResult<Integer>> handler);
void files(String userId, FileType type, String expectedFilename, int page, int pageSize,
Handler<AsyncResult<List<File>>> handler);
void file(String name, Handler<AsyncResult<File>> handler);
void deleteFile(String name, Deleter deleter, Handler<AsyncResult<Void>> handler);
void transfer(String userId, FileType type, String originalName, String name, TransferWay transferWay,
Map<String, String> transferInfo, Handler<AsyncResult<Job>> handler);
void transferDone(String name, FileTransferState transferState, long size,
Handler<AsyncResult<Void>> handler);
void setShared(String name, Handler<AsyncResult<Void>> handler);
void updateDisplayName(String name, String displayName, Handler<AsyncResult<Void>> handler);
}
| 6,841 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/ConfigService.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.master.service.impl.ConfigServiceImpl;
@ProxyGen
@VertxGen
public interface ConfigService {
@GenIgnore
static void create(Vertx vertx, JDBCClient dbClient) {
new ServiceBinder(vertx.getDelegate()).setAddress(ConfigService.class.getSimpleName())
.register(ConfigService.class, new ConfigServiceImpl(dbClient));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(ConfigService.class, new org.eclipse.jifa.master.service.reactivex.ConfigService(
new ConfigServiceVertxEBProxy(vertx.getDelegate(), ConfigService.class.getSimpleName())));
}
void getConfig(String configName, Handler<AsyncResult<String>> handler);
}
| 6,842 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/ServiceVerticle.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import com.alibaba.druid.pool.DruidDataSource;
import io.reactivex.Single;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.AbstractVerticle;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceVerticle extends AbstractVerticle implements Constant {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceVerticle.class);
@Override
public void start(Promise <Void> startFuture) {
vertx.rxExecuteBlocking(future -> {
// init Data source
DruidDataSource ds = new DruidDataSource();
JsonObject dbConfig = config().getJsonObject(DB_KEYWORD);
ds.setUrl(dbConfig.getString(DB_URL));
ds.setUsername(dbConfig.getString(DB_USERNAME));
ds.setPassword(dbConfig.getString(DB_PASSWORD));
ds.setDriverClassName(dbConfig.getString(DB_DRIVER_CLASS_NAME));
// create proxy first
AdminService.createProxy(vertx);
JobService.createProxy(vertx);
ConfigService.createProxy(vertx);
WorkerService.createProxy(vertx);
FileService.createProxy(vertx);
SupportService.createProxy(vertx);
LOGGER.info("Create service proxy done");
JDBCClient jdbcClient = new JDBCClient(io.vertx.ext.jdbc.JDBCClient.create(vertx.getDelegate(), ds));
Pivot pivot = Pivot.createInstance(vertx, jdbcClient, config());
JobService.create(vertx, pivot, jdbcClient);
FileService.create(vertx, pivot, jdbcClient);
ConfigService.create(vertx, jdbcClient);
AdminService.create(vertx, jdbcClient);
WorkerService.create(vertx, jdbcClient, pivot);
SupportService.create(vertx, jdbcClient, pivot);
LOGGER.info("Create service done");
future.complete(Single.just(this));
}).subscribe(f -> startFuture.complete(), startFuture::fail);
}
}
| 6,843 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/SupportService.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.serviceproxy.ServiceBinder;
import org.eclipse.jifa.master.service.impl.Pivot;
import org.eclipse.jifa.master.service.impl.SupportServiceImpl;
@ProxyGen
@VertxGen
public interface SupportService {
@GenIgnore
static void create(Vertx vertx, JDBCClient dbClient, Pivot pivot) {
new ServiceBinder(vertx.getDelegate())
.setIncludeDebugInfo(true)
.setAddress(SupportService.class.getSimpleName())
.register(SupportService.class, new SupportServiceImpl(dbClient, pivot));
}
@GenIgnore
static void createProxy(Vertx vertx) {
ProxyDictionary.add(SupportService.class, new org.eclipse.jifa.master.service.reactivex.SupportService(
new SupportServiceVertxEBProxy(vertx.getDelegate(), SupportService.class.getSimpleName())));
}
void isDBConnectivity(Handler<AsyncResult<Boolean>> handler);
void startDummyWorker(Handler<AsyncResult<Void>> handler);
void stopDummyWorker(Handler<AsyncResult<Void>> handler);
}
| 6,844 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/package-info.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
@ModuleGen(groupPackage = "org.eclipse.jifa.master.service", name = "Service")
package org.eclipse.jifa.master.service;
import io.vertx.codegen.annotations.ModuleGen; | 6,845 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/WorkerServiceImpl.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.CompletableHelper;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.service.WorkerService;
import org.eclipse.jifa.master.service.impl.helper.WorkerHelper;
import org.eclipse.jifa.master.service.sql.FileSQL;
import org.eclipse.jifa.master.service.sql.WorkerSQL;
import java.util.List;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class WorkerServiceImpl implements WorkerService, WorkerSQL {
private final JDBCClient dbClient;
private final Pivot pivot;
public WorkerServiceImpl(JDBCClient dbClient, Pivot pivot) {
this.dbClient = dbClient;
this.pivot = pivot;
}
@Override
public void queryAll(Handler<AsyncResult<List<Worker>>> handler) {
dbClient.rxQuery(WorkerSQL.SELECT_ALL)
.map(records -> records.getRows()
.stream()
.map(WorkerHelper::fromDBRecord)
.collect(Collectors.toList()))
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void diskCleanup(String hostIP, Handler<AsyncResult<Void>> handler) {
dbClient.rxUpdateWithParams(FileSQL.UPDATE_AS_PENDING_DELETE_BY_HOST, ja(hostIP))
.ignoreElement()
.andThen(dbClient.rxQueryWithParams(FileSQL.SELECT_PENDING_DELETE_BY_HOST, ja(hostIP))
.map(rs -> rs.getRows().stream().map(row -> row.getString("name"))
.collect(Collectors.toList()))
.flatMapCompletable(
fileNames -> pivot.deleteFile(Deleter.ADMIN, fileNames.toArray(new String[0])))
)
.subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void selectMostIdleWorker(Handler<AsyncResult<Worker>> handler) {
dbClient.rxGetConnection()
.flatMap(conn -> pivot.selectMostIdleWorker(conn).doOnTerminate(conn::close))
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void selectWorkerByIP(String hostIp, Handler<AsyncResult<Worker>> handler) {
dbClient.rxQueryWithParams(WorkerSQL.SELECT_BY_IP, ja(hostIp))
.map(ar -> {
if (ar.getRows().size() > 0) {
return WorkerHelper.fromDBRecord(ar.getRows().get(0));
}
return Worker.NOT_FOUND;
})
.subscribe(SingleHelper.toObserver(handler));
}
}
| 6,846 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/FileServiceImpl.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import com.google.common.base.Strings;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.reactivex.CompletableHelper;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.model.TransferWay;
import org.eclipse.jifa.master.service.FileService;
import org.eclipse.jifa.master.service.impl.helper.FileHelper;
import org.eclipse.jifa.master.service.impl.helper.SQLAssert;
import org.eclipse.jifa.master.service.sql.FileSQL;
import org.eclipse.jifa.master.service.sql.SQL;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
import static org.eclipse.jifa.master.service.sql.FileSQL.*;
public class FileServiceImpl implements FileService, Constant {
private static final long TRANSFER_JOB_LOAD = 5;
private final Pivot pivot;
private final JDBCClient dbClient;
public FileServiceImpl(Pivot pivot, JDBCClient dbClient) {
this.pivot = pivot;
this.dbClient = dbClient;
}
@Override
public void count(String userId, FileType type, String expectedFilename, Handler<AsyncResult<Integer>> handler) {
boolean fuzzy = !Strings.isNullOrEmpty(expectedFilename);
expectedFilename = "%" + expectedFilename + "%";
String sql = fuzzy ? COUNT_BY_USER_ID_AND_TYPE_AND_EXPECTED_NAME : COUNT_BY_USER_ID_AND_TYPE;
JsonArray params = fuzzy ? ja(userId, type, expectedFilename, expectedFilename) : ja(userId, type);
dbClient.rxQueryWithParams(sql, params)
.map(resultSet -> resultSet.getRows().get(0).getInteger(SQL.COUNT_NAME))
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void files(String userId, FileType type, String expectedFilename, int page, int pageSize,
Handler<AsyncResult<List<File>>> handler) {
boolean fuzzy = !Strings.isNullOrEmpty(expectedFilename);
expectedFilename = "%" + expectedFilename + "%";
String sql = fuzzy ? SELECT_BY_USER_ID_AND_TYPE_AND_EXPECTED_NAME : SELECT_BY_USER_ID_AND_TYPE;
JsonArray params = fuzzy ? ja(userId, type, expectedFilename, expectedFilename, (page - 1) * pageSize, pageSize)
: ja(userId, type, (page - 1) * pageSize, pageSize);
dbClient.rxQueryWithParams(sql, params)
.map(ar -> ar.getRows().stream().map(FileHelper::fromDBRecord).collect(Collectors.toList()))
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void file(String name, Handler<AsyncResult<File>> handler) {
dbClient.rxQueryWithParams(FileSQL.SELECT_FILE_BY_NAME, ja(name))
.map(ar -> {
if (ar.getRows().size() > 0) {
return FileHelper.fromDBRecord(ar.getRows().get(0));
}
return File.NOT_FOUND;
})
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void deleteFile(String name, Deleter deleter, Handler<AsyncResult<Void>> handler) {
pivot.deleteFile(deleter, name)
.subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void transfer(String userId, FileType type, String originalName, String name, TransferWay transferWay,
Map<String, String> transferInfo, Handler<AsyncResult<Job>> handler) {
File file = new File();
file.setUserId(userId);
file.setOriginalName(originalName);
file.setName(name);
file.setType(type);
file.setSize(0);
file.setTransferState(FileTransferState.IN_PROGRESS);
file.setTransferWay(transferWay);
file.setTransferInfo(transferInfo);
boolean immediate = false;
if (transferWay == TransferWay.OSS ||
(transferWay == TransferWay.SCP && !Boolean.parseBoolean(transferInfo.get("usePublicKey")))) {
immediate = true;
}
pivot.allocate(userId, null, JobType.FILE_TRANSFER, name, GSON.toJson(file), TRANSFER_JOB_LOAD,
immediate)
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void transferDone(String name, FileTransferState transferState, long size,
Handler<AsyncResult<Void>> handler) {
pivot.transferDone(name, transferState, size).subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void setShared(String name, Handler<AsyncResult<Void>> handler) {
dbClient.rxUpdateWithParams(FileSQL.SET_SHARED, ja(name))
.ignoreElement()
.subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void updateDisplayName(String name, String displayName, Handler<AsyncResult<Void>> handler) {
dbClient.rxUpdateWithParams(FileSQL.UPDATE_DISPLAY_NAME, ja(displayName, name))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement()
.subscribe(CompletableHelper.toObserver(handler));
}
}
| 6,847 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/JobServiceImpl.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.reactivex.Single;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.ext.sql.ResultSet;
import io.vertx.reactivex.CompletableHelper;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.service.JobService;
import org.eclipse.jifa.master.service.impl.helper.JobHelper;
import org.eclipse.jifa.master.service.impl.helper.SQLHelper;
import org.eclipse.jifa.master.service.sql.JobSQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class JobServiceImpl implements JobService, JobSQL, Constant {
private static final Logger LOGGER = LoggerFactory.getLogger(JobServiceImpl.class);
private final JDBCClient dbClient;
private final Pivot pivot;
public JobServiceImpl(Pivot pivot, JDBCClient dbClient) {
this.pivot = pivot;
this.dbClient = dbClient;
}
@Override
public void findActive(JobType jobType, String target, Handler<AsyncResult<Job>> handler) {
dbClient.rxQueryWithParams(SELECT_ACTIVE_BY_TYPE_AND_TARGET, ja(jobType, target))
.flatMap(resultSet -> {
if (resultSet.getNumRows() == 0) {
return Single.just(Job.NOT_FOUND);
}
Job job = JobHelper.fromDBRecord(resultSet.getRows().get(0));
if (job.getState() != JobState.IN_PROGRESS) {
return Single.just(job);
}
return dbClient.rxUpdateWithParams(UPDATE_ACCESS_TIME, ja(jobType, target))
.ignoreElement()
.toSingleDefault(job);
})
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void pendingJobsInFrontOf(Job job, Handler<AsyncResult<List<Job>>> handler) {
String hostIP = job.getHostIP();
Instant instant = Instant.ofEpochMilli(job.getCreationTime());
Single<ResultSet> single = hostIP == null ?
dbClient.rxQueryWithParams(SELECT_FRONT_PENDING, ja(instant)) :
dbClient.rxQueryWithParams(SELECT_FRONT_PENDING_BY_HOST_IP, ja(hostIP, instant));
single.map(records -> records.getRows().stream().map(JobHelper::fromDBRecord)
.filter(fontJob -> job.getId() != fontJob.getId())
.collect(Collectors.toList()))
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void allocate(String userId, String hostIP, JobType jobType, String target, String attachment,
long estimatedLoad, boolean immediate, Handler<AsyncResult<Job>> handler) {
pivot.allocate(userId, hostIP, jobType, target, attachment, estimatedLoad, immediate)
.subscribe(SingleHelper.toObserver(handler));
}
@Override
public void finish(JobType type, String target, Handler<AsyncResult<Void>> handler) {
dbClient.rxQueryWithParams(SELECT_ACTIVE_BY_TYPE_AND_TARGET, ja(type, target))
.map(SQLHelper::singleRow)
.map(JobHelper::fromDBRecord)
.flatMapCompletable(pivot::finish)
.subscribe(CompletableHelper.toObserver(handler));
}
}
| 6,848 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/ConfigServiceImpl.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.service.ConfigService;
import org.eclipse.jifa.master.service.sql.ConfigSQL;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class ConfigServiceImpl implements ConfigService {
private final JDBCClient dbClient;
public ConfigServiceImpl(JDBCClient dbClient) {
this.dbClient = dbClient;
}
@Override
public void getConfig(String configName, Handler<AsyncResult<String>> handler) {
dbClient.rxQueryWithParams(ConfigSQL.SELECT, ja(configName))
.map(resultSet -> resultSet.getRows().get(0).getString("value"))
.subscribe(SingleHelper.toObserver(handler));
}
}
| 6,849 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/Pivot.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.observables.GroupedObservable;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.sql.ResultSet;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.reactivex.ext.sql.SQLClientHelper;
import io.vertx.reactivex.ext.sql.SQLConnection;
import io.vertx.reactivex.ext.web.client.HttpResponse;
import org.apache.commons.io.FileUtils;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.ProgressState;
import org.eclipse.jifa.common.vo.TransferProgress;
import org.eclipse.jifa.master.Constant;
import org.eclipse.jifa.master.entity.File;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.Master;
import org.eclipse.jifa.master.entity.Worker;
import org.eclipse.jifa.master.entity.enums.Deleter;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.entity.enums.JobType;
import org.eclipse.jifa.master.model.TransferWay;
import org.eclipse.jifa.master.service.impl.helper.*;
import org.eclipse.jifa.master.service.sql.*;
import org.eclipse.jifa.master.support.Factory;
import org.eclipse.jifa.master.support.Pattern;
import org.eclipse.jifa.master.support.WorkerClient;
import org.eclipse.jifa.master.support.WorkerScheduler;
import org.eclipse.jifa.master.task.SchedulingTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
import static org.eclipse.jifa.master.Constant.LOCAL_HOST;
import static org.eclipse.jifa.master.Constant.uri;
import static org.eclipse.jifa.master.service.ServiceAssertion.SERVICE_ASSERT;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
import static org.eclipse.jifa.master.service.sql.JobSQL.*;
import static org.eclipse.jifa.master.support.WorkerClient.post;
public class Pivot {
private static final Logger LOGGER = LoggerFactory.getLogger(Pivot.class);
private static final String JOB_LOCK_KEY = "MASTER-JOB-LOCK";
private static final String SCHEDULER_PATTERN = "SCHEDULER-PATTERN";
private static final String PENDING_JOB_MAX_COUNT_KEY = "JOB-PENDING-MAX-COUNT";
private static final String NOTIFY_WORKER_ACTION_DELAY_KEY = "JOB-NOTIFY-WORKER-ACTION-DELAY";
private static final String TRIGGER_SCHEDULING_ACTION_DELAY = "JOB-TRIGGER-SCHEDULING-ACTION-DELAY";
private static Pivot SINGLETON;
private Master currentMaster;
private JDBCClient dbClient;
private Vertx vertx;
private int pendingJobMaxCount;
private long notifyWorkerActionDelay;
private long triggerSchedulingActionDelay;
private SchedulingTask schedulingTask;
private WorkerScheduler scheduler;
private boolean isDefaultPattern;
private Pivot() {
}
public WorkerScheduler getScheduler() {
return scheduler;
}
public static Pivot getInstance() {
return SINGLETON;
}
public static synchronized Pivot createInstance(Vertx vertx, JDBCClient dbClient, JsonObject config) {
if (SINGLETON != null) {
return SINGLETON;
}
Pivot jm = new Pivot();
try {
jm.dbClient = dbClient;
jm.vertx = vertx;
Pattern pattern = Pattern.valueOf(ConfigHelper.getString(jm.config(SCHEDULER_PATTERN)));
jm.isDefaultPattern = pattern == Pattern.DEFAULT;
jm.scheduler = Factory.create(pattern);
jm.pendingJobMaxCount = ConfigHelper.getInt(jm.config(PENDING_JOB_MAX_COUNT_KEY));
jm.notifyWorkerActionDelay = ConfigHelper.getLong(jm.config(NOTIFY_WORKER_ACTION_DELAY_KEY));
jm.triggerSchedulingActionDelay = ConfigHelper.getLong(jm.config(TRIGGER_SCHEDULING_ACTION_DELAY));
String ip =
org.eclipse.jifa.master.Master.DEV_MODE || pattern == Pattern.K8S ?
LOCAL_HOST :
InetAddress.getLocalHost().getHostAddress();
LOGGER.info("Current Master Host IP is {}", ip);
SQLConnection sqlConnection = dbClient.rxGetConnection().blockingGet();
jm.currentMaster = jm.selectMaster(sqlConnection, ip).doFinally(sqlConnection::close).blockingGet();
jm.scheduler.initialize(jm, vertx, config);
} catch (Throwable t) {
LOGGER.error("Init job service error", t);
System.exit(-1);
}
SINGLETON = jm;
return jm;
}
public boolean isLeader() {
return currentMaster.isLeader();
}
public boolean isDefaultPattern() {
return isDefaultPattern;
}
public void setSchedulingTask(SchedulingTask task) {
this.schedulingTask = task;
}
private static Job buildPendingJob(String userId, String hostIP, JobType jobType, String target,
String attachment, long estimatedLoad, boolean immediate) {
Job job = new Job();
job.setUserId(userId);
job.setType(jobType);
job.setTarget(target);
job.setState(JobState.PENDING);
job.setHostIP(hostIP);
job.setAttachment(attachment);
job.setEstimatedLoad(estimatedLoad);
job.setImmediate(immediate);
return job;
}
public JDBCClient getDbClient() {
return dbClient;
}
Single<Job> allocate(String userId, String hostIP, JobType jobType, String target,
String attachment, long estimatedLoad, boolean immediate) {
Job job = buildPendingJob(userId, hostIP, jobType, target, attachment, estimatedLoad, immediate);
return doAllocate(job);
}
private Single<Job> doAllocate(Job job) {
return scheduler.start(job)
.andThen(inTransactionAndLock(
conn -> checkPendingCont(conn, job)
.flatMap(pendingCount -> doAllocate(conn, job, pendingCount))
).flatMap(i -> postInProgressJob(job).andThen(Single.just(job))));
}
private Single<Job> doAllocate(SQLConnection conn, Job job, int pendingCount) {
job.setState(JobState.PENDING);
if (pendingCount > 0) {
return conn.rxUpdateWithParams(INSERT_ACTIVE, buildActiveParams(job)).map(i -> job);
}
return setFileUsed(conn, job).andThen(scheduler.decide(job, conn).flatMap(
worker -> {
if (scheduler.supportPendingJob()) {
String selectedHostIP = worker.getHostIP();
long loadSum = worker.getCurrentLoad() + job.getEstimatedLoad();
if (loadSum <= worker.getMaxLoad()) {
// new in progress job
job.setHostIP(selectedHostIP);
job.setState(JobState.IN_PROGRESS);
return insertActiveJob(conn, job)
.andThen(updateWorkerLoad(conn, selectedHostIP, loadSum))
.toSingleDefault(job);
}
SERVICE_ASSERT.isTrue(!job.isImmediate(), ErrorCode.IMMEDIATE_JOB);
return insertActiveJob(conn, job).toSingleDefault(job);
} else {
String selectedHostIP = worker.getHostIP();
// new in progress job
job.setHostIP(selectedHostIP);
job.setState(JobState.IN_PROGRESS);
return insertActiveJob(conn, job).toSingleDefault(job);
}
}
));
}
public Single<Boolean> isDBConnectivity() {
return dbClient.rxGetConnection()
.flatMap(conn -> selectTrue(conn).doOnTerminate(
() -> {
LOGGER.info("Close connection for DB connectivity test");
conn.close();
}))
.onErrorReturn(t -> {
t.printStackTrace();
return Boolean.FALSE;
});
}
private Map<String, String> buildQueryFileTransferProgressParams(File file) {
Map<String, String> map = new HashMap<>();
map.put("name", file.getName());
map.put("type", file.getType().name());
return map;
}
private Completable processTransferProgressResult(String name, HttpResponse resp) {
if (resp.statusCode() != Constant.HTTP_GET_OK_STATUS_CODE) {
LOGGER.warn("Query file transfer progress error : {}", resp.bodyAsString());
return Completable.complete();
}
TransferProgress progress = GSON.fromJson(resp.bodyAsString(), TransferProgress.class);
ProgressState state = progress.getState();
if (state.isFinal()) {
return transferDone(name, FileTransferState.fromProgressState(state), progress.getTotalSize());
}
return Completable.complete();
}
public Completable processTimeoutTransferJob(Job job) {
return dbClient.rxGetConnection()
.flatMapCompletable(conn ->
selectFileOrNotFount(conn, job.getTarget())
.flatMapCompletable(file -> {
if (file.found()) {
return scheduler.decide(job, conn)
.flatMapCompletable(worker -> {
if (worker == Worker.NOT_FOUND) {
// Job has been timeout, but there is no corresponding worker which indicated
// by Job's hostIP, this only happens in K8S mode, i.e. worker has been stopped
// due to some reasons but Job is still presented. We would update Job transferState
// as Error unconditionally.
return Completable.complete()
.doOnComplete(() -> SERVICE_ASSERT.isTrue(!isDefaultPattern, "Only happens in K8S Mode"))
.andThen(transferDone(job.getTarget(), FileTransferState.ERROR, 0));
} else {
return WorkerClient.get(job.getHostIP(), uri(Constant.TRANSFER_PROGRESS),
buildQueryFileTransferProgressParams(file))
.flatMapCompletable(
resp -> processTransferProgressResult(job.getTarget(), resp));
}
});
} else {
return finish(job);
}
})
.doOnTerminate(conn::close)
)
.doOnError((t) -> LOGGER.warn("Process time out transfer job {} error", job.getTarget(), t))
.onErrorComplete();
}
Completable transferDone(String name, FileTransferState transferState, long size) {
return dbClient.rxGetConnection()
.flatMap(conn -> selectActiveJob(conn, JobType.FILE_TRANSFER, name).doOnTerminate(conn::close))
.flatMapCompletable(
job -> finish(job, conn -> updateFileTransferResult(conn, job, name, transferState, size))
);
}
private HashMap<String, String> buildParams(File... files) {
@SuppressWarnings("rawtypes")
Map[] maps = new Map[files.length];
for (int i = 0; i < files.length; i++) {
Map<String, String> map = new HashMap<>();
map.put("name", files[i].getName());
map.put("type", files[i].getType().name());
maps[i] = map;
}
return new HashMap<>(1) {{
put("files", GSON.toJson(maps));
}};
}
private Completable batchDeleteFiles(SQLConnection conn, Deleter deleter,
GroupedObservable<String, File> groupedFiles) {
String hostIP = groupedFiles.getKey();
return groupedFiles
.toList()
.flatMapCompletable(files -> Observable.fromIterable(files)
.flatMapSingle(file -> selectActiveJob(conn, file.getName())
.doOnSuccess(jobs -> {
if (deleter != Deleter.SYSTEM) {
SERVICE_ASSERT
.isTrue(jobs.size() == 0, ErrorCode.FILE_IS_IN_USED);
}
})
)
.ignoreElements()
.andThen(
deleteFileRecords(conn, deleter, files.toArray(new File[0])))
.andThen(
isDefaultPattern ?
post(hostIP, uri(Constant.FILE_BATCH_DELETE),
buildParams(files.toArray(new File[0])))
.doOnSuccess(resp -> SERVICE_ASSERT
.isTrue(resp.statusCode() ==
Constant.HTTP_POST_CREATED_STATUS,
resp.bodyAsString())).ignoreElement()
:
Completable.fromAction(
() -> {
for (File file : files) {
// FIXME: consider adding delete files
// api in worker scheduler
// copy from pvc clean up task
java.io.File pf =
new java.io.File("/root/jifa_workspace" +
java.io.File.separator +
file.getType().getTag() +
java.io.File.separator +
file.getName());
FileUtils.deleteDirectory(pf);
}
}
)
)
);
}
public Completable deleteFile(Deleter deleter, String... fileNames) {
return dbClient.rxGetConnection()
.flatMapCompletable(
conn -> Observable.fromArray(fileNames)
.flatMapSingle(fileName -> selectFile(conn, fileName))
.groupBy(File::getHostIP)
.flatMapCompletable(
groupedFiles -> batchDeleteFiles(conn, deleter, groupedFiles))
.doOnTerminate(conn::close)
);
}
public Completable syncFiles(Worker w, boolean cleanStale) {
return dbClient.rxQueryWithParams(FileSQL.SELECT_FILES_FOR_SYNC, SQLHelper.ja(w.getHostIP()))
.map(ar -> ar.getRows().stream().map(FileHelper::fromDBRecord).collect(Collectors.toList()))
.flatMapCompletable(
files -> {
HashMap<String, String> params = buildParams(files.toArray(new File[0]));
params.put("cleanStale", String.valueOf(cleanStale));
return post(w.getHostIP(), uri(Constant.FILE_SYNC), params)
.ignoreElement();
}
);
}
public Completable finish(Job job) {
return finish(job, conn -> Completable.complete());
}
private Completable finish(Job job, Function<SQLConnection, Completable> post) {
return inTransactionAndLock(
conn -> scheduler.decide(job, conn)
.flatMapCompletable(worker -> {
if (isDefaultPattern()) {
return updateWorkerLoad(conn, worker.getHostIP(), worker.getCurrentLoad() - job.getEstimatedLoad());
} else {
return Completable.complete();
}
})
.andThen(insertHistoricalJob(conn, job))
// delete old job
.andThen(deleteActiveJob(conn, job))
.andThen(this.setFileUnused(conn, job))
.andThen(post.apply(conn))
.toSingleDefault(job)
).ignoreElement()
// notify worker
.andThen(this.notifyWorkerJobIsFinished(job))
// stop worker
.andThen(scheduler.stop(job))
// trigger scheduling
.andThen(this.triggerScheduling());
}
private Completable setFileUsed(SQLConnection conn, Job job) {
if (job.getType() != JobType.FILE_TRANSFER) {
return conn.rxUpdateWithParams(FileSQL.UPDATE_FILE_AS_USED, ja(job.getTarget()))
.doOnSuccess(
record -> SERVICE_ASSERT.isTrue(record.getUpdated() == 1,
"Operation " + job.getType().toString() +
" failure due to unknown error"))
.ignoreElement();
}
return Completable.complete();
}
private Completable setFileUnused(SQLConnection conn, Job job) {
if (job.getType() != JobType.FILE_TRANSFER) {
return conn.rxUpdateWithParams(FileSQL.UPDATE_FILE_AS_UNUSED, ja(job.getTarget()))
.doOnSuccess(
record -> SERVICE_ASSERT.isTrue(record.getUpdated() == 1,
"Operation " + job.getType().toString() +
" failure due to unknown error"))
.ignoreElement();
}
return Completable.complete();
}
public Completable postInProgressJob(Job job) {
switch (job.getType()) {
case FILE_TRANSFER:
File file = new File(new JsonObject(job.getAttachment()));
JsonArray params = new JsonArray();
params.add(file.getUserId());
params.add(file.getOriginalName());
params.add(file.getName());
params.add(file.getType());
params.add(0);
params.add(job.getHostIP());
params.add(FileTransferState.IN_PROGRESS);
// shared/downloadable/in shared disk/deleted
params.add(false).add(false).add(false).add(false);
params.add(0);
return inTransaction(
conn -> conn.rxUpdateWithParams(FileSQL.INSERT, params)
.doOnSuccess(SQLAssert::assertUpdated).ignoreElement()
.andThen(
// upload file need special process
file.getTransferWay() != TransferWay.UPLOAD ?
post(job.getHostIP(), file.getTransferWay().getUri(), file.getTransferInfo())
.doOnSuccess(resp -> SERVICE_ASSERT.isTrue(
resp.statusCode() == Constant.HTTP_POST_CREATED_STATUS,
resp.bodyAsString())).ignoreElement() :
Completable.complete()
).toSingleDefault(job))
.doOnError(e -> finish(job).subscribe()).ignoreElement();
default:
return Completable.complete();
}
}
private Completable notifyWorkerJobIsFinished(Job job) {
JobType type = job.getType();
String hostIP = job.getHostIP();
String target = job.getTarget();
return Completable.fromAction(() -> {
switch (type) {
case HEAP_DUMP_ANALYSIS:
case GCLOG_ANALYSIS:
case THREAD_DUMP_ANALYSIS:
vertx.setTimer(notifyWorkerActionDelay, ignored -> {
String url = "/jifa-api/" + type.getTag() + "/" + target + "/release";
Single<HttpResponse<Buffer>> post = post(job.getHostIP(), url);
post.subscribe(resp -> {
if (resp.statusCode() != Constant.HTTP_POST_CREATED_STATUS) {
LOGGER.error("Notify worker {} to release task error, result : {}",
hostIP, resp.bodyAsString());
}
},
t -> LOGGER.error("Notify worker {} to release task error", hostIP));
});
default:
}
});
}
private Completable triggerScheduling() {
if (scheduler.supportPendingJob()) {
return Completable
.fromAction(() -> {
if (currentMaster.leader) {
vertx.setTimer(triggerSchedulingActionDelay, ignored -> schedulingTask.trigger());
}
});
}
return Completable.complete();
}
public JsonObject config(String name) {
return SQLHelper.singleRow(dbClient.rxQueryWithParams(ConfigSQL.SELECT, ja(name)).blockingGet());
}
public <T> Single<T> inTransaction(Function<SQLConnection, Single<T>> sourceSupplier) {
return SQLClientHelper.inTransactionSingle(dbClient, sourceSupplier);
}
public <T> Single<T> inTransactionAndLock(Function<SQLConnection, Single<T>> sourceSupplier) {
return SQLClientHelper.inTransactionSingle(dbClient, conn ->
lock(conn).andThen(sourceSupplier.apply(conn))
);
}
private Completable lock(SQLConnection conn) {
return conn.rxQueryWithParams(GlobalLockSQL.LOCK, ja(JOB_LOCK_KEY))
.doOnSuccess(SQLAssert::assertSelected)
.ignoreElement();
}
private JsonArray buildFileParams(File file) {
return ja(file.getUserId(), file.getOriginalName(), file.getName(), file.getType(), file.getSize(),
file.getHostIP(), file.getTransferState(), file.isShared(), file.isDownloadable(),
file.isInSharedDisk(), file.isDeleted());
}
private JsonArray buildActiveParams(Job job) {
return ja(job.getUserId(), job.getType(), job.getState(), job.getTarget(), job.getHostIP(),
job.getState() == JobState.PENDING ? job.getAttachment() : null,
job.getEstimatedLoad(),
job.getType().isFileTransfer());
}
private JsonArray buildHistoricalParams(Job job) {
return ja(job.getUserId(), job.getType(), job.getTarget(), job.getHostIP(), job.getEstimatedLoad());
}
private Single<Integer> checkPendingCont(SQLConnection conn, Job job) {
if (scheduler.supportPendingJob()) {
Single<ResultSet> s = job.getHostIP() == null ?
conn.rxQuery(COUNT_ALL_PENDING) :
conn.rxQueryWithParams(COUNT_PENDING_BY_HOST_IP, ja(job.getHostIP()));
return s.map(SQLHelper::count)
.doOnSuccess((pending) -> SERVICE_ASSERT.isTrue(pending < pendingJobMaxCount,
ErrorCode.SERVER_TOO_BUSY));
}
return Single.just(0);
}
public Single<Worker> decideWorker(SQLConnection conn, Job job) {
return job.getHostIP() == null ? selectMostIdleWorker(conn) : selectWorker(conn, job.getHostIP());
}
private Single<Master> selectMaster(SQLConnection conn, String hostIP) {
return conn.rxQueryWithParams(MasterSQL.SELECT, ja(hostIP))
.map(SQLHelper::singleRow)
.map(MasterHelper::fromDBRecord);
}
public Single<Worker> selectMostIdleWorker(SQLConnection conn) {
return conn.rxQuery(WorkerSQL.SELECT_MOST_IDLE)
.map(SQLHelper::singleRow)
.map(WorkerHelper::fromDBRecord);
}
public Single<Worker> selectWorker(SQLConnection conn, String hostIP) {
return conn.rxQueryWithParams(WorkerSQL.SELECT_BY_IP, ja(hostIP))
.map(SQLHelper::singleRow)
.map(WorkerHelper::fromDBRecord);
}
public Completable updateWorkerLoad(SQLConnection conn, String hostIP, long load) {
SERVICE_ASSERT.isTrue(load >= 0, ErrorCode.SANITY_CHECK);
return conn.rxUpdateWithParams(WorkerSQL.UPDATE_LOAD, ja(load, hostIP))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
private Completable insertActiveJob(SQLConnection conn, Job job) {
return conn.rxUpdateWithParams(INSERT_ACTIVE, buildActiveParams(job))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
private Single<Boolean> selectTrue(SQLConnection conn) {
return conn.rxQuery(SQL.SELECT_TRUE)
.map(SQLHelper::singleRow)
.map(value -> value.getInteger("TRUE") == 1 ? Boolean.TRUE : Boolean.FALSE)
.onErrorReturn(e -> {
e.printStackTrace();
return Boolean.FALSE;
});
}
private Completable deleteActiveJob(SQLConnection conn, Job job) {
return conn.rxUpdateWithParams(DELETE_ACTIVE_BY_TYPE_AND_TARGET, ja(job.getType(), job.getTarget()))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
private Single<Job> selectActiveJob(SQLConnection conn, JobType jobType, String target) {
return conn.rxQueryWithParams(JobSQL.SELECT_ACTIVE_BY_TYPE_AND_TARGET, ja(jobType, target))
.map(SQLHelper::singleRow)
.map(JobHelper::fromDBRecord);
}
private Single<List<Job>> selectActiveJob(SQLConnection conn, String target) {
return conn.rxQueryWithParams(JobSQL.SELECT_ACTIVE_BY_TARGET, ja(target))
.map(records ->
records.getRows().stream().map(JobHelper::fromDBRecord).collect(Collectors.toList())
);
}
private Completable insertHistoricalJob(SQLConnection conn, Job job) {
return conn.rxUpdateWithParams(INSERT_HISTORICAL, buildHistoricalParams(job))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
public Completable updatePendingJobToInProcess(SQLConnection conn, Job job) {
JsonArray params = ja(job.getHostIP(), Instant.now(), job.getType(), job.getTarget());
return conn.rxUpdateWithParams(JobSQL.UPDATE_TO_IN_PROGRESS, params)
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
private Single<File> selectFile(SQLConnection conn, String name) {
return conn.rxQueryWithParams(FileSQL.SELECT_FILE_BY_NAME, ja(name))
.map(SQLHelper::singleRow)
.map(FileHelper::fromDBRecord);
}
private Single<File> selectFileOrNotFount(SQLConnection conn, String name) {
return conn.rxQueryWithParams(FileSQL.SELECT_FILE_BY_NAME, ja(name))
.map(res -> {
if (res.getNumRows() > 0) {
return FileHelper.fromDBRecord(SQLHelper.singleRow(res));
}
return File.NOT_FOUND;
});
}
private Completable deleteFileRecords(SQLConnection conn, Deleter deleter, File... files) {
return Observable.fromArray(files)
.flatMapCompletable(
file -> conn.rxUpdateWithParams(FileSQL.DELETE_FILE_BY_NAME, ja(deleter, file.getName()))
.doOnSuccess(SQLAssert::assertUpdated).ignoreElement());
}
private Completable updateFileTransferResult(SQLConnection conn, Job job, String name,
FileTransferState transferState,
long size) {
return conn.rxUpdateWithParams(FileSQL.UPDATE_TRANSFER_RESULT, ja(transferState, size, name))
// file record may not exist for some reason
// .doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement();
}
}
| 6,850 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/SupportServiceImpl.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.CompletableHelper;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.service.SupportService;
import org.eclipse.jifa.master.support.K8SWorkerScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SupportServiceImpl implements SupportService {
private static final Logger LOGGER = LoggerFactory.getLogger(SupportServiceImpl.class.getName());
private final Pivot pivot;
public SupportServiceImpl(JDBCClient dbClient, Pivot pivot) {
this.pivot = pivot;
}
@Override
public void isDBConnectivity(Handler<AsyncResult<Boolean>> handler) {
pivot.isDBConnectivity().subscribe(SingleHelper.toObserver(handler));
}
@Override
public void startDummyWorker(Handler<AsyncResult<Void>> handler) {
assert pivot.getScheduler() instanceof K8SWorkerScheduler : "unexpected call";
String testWorkerName = K8SWorkerScheduler.getSpecialWorkerPrefix() + "-health-test";
Job dummyJob = new Job();
dummyJob.setTarget(testWorkerName);
pivot.getScheduler().start(dummyJob).subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void stopDummyWorker(Handler<AsyncResult<Void>> handler) {
assert pivot.getScheduler() instanceof K8SWorkerScheduler : "unexpected call";
String testWorkerName = K8SWorkerScheduler.getSpecialWorkerPrefix() + "-health-test";
Job dummyJob = new Job();
dummyJob.setTarget(testWorkerName);
pivot.getScheduler().stop(dummyJob).subscribe(CompletableHelper.toObserver(handler));
}
}
| 6,851 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/AdminServiceImpl.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.reactivex.CompletableHelper;
import io.vertx.reactivex.SingleHelper;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import org.eclipse.jifa.master.entity.Admin;
import org.eclipse.jifa.master.service.AdminService;
import org.eclipse.jifa.master.service.impl.helper.AdminHelper;
import org.eclipse.jifa.master.service.impl.helper.SQLAssert;
import org.eclipse.jifa.master.service.sql.AdminSQL;
import java.util.List;
import java.util.stream.Collectors;
import static org.eclipse.jifa.master.service.impl.helper.SQLHelper.ja;
public class AdminServiceImpl implements AdminService {
private final JDBCClient dbClient;
public AdminServiceImpl(JDBCClient dbClient) {
this.dbClient = dbClient;
}
@Override
public void isAdmin(String userId, Handler<AsyncResult<Boolean>> resultHandler) {
dbClient.rxQueryWithParams(AdminSQL.SELECT_BY_USER_ID, ja(userId))
.map(resultSet -> resultSet.getNumRows() == 1)
.subscribe(SingleHelper.toObserver(resultHandler));
}
@Override
public void add(String userId, Handler<AsyncResult<Void>> handler) {
dbClient.rxUpdateWithParams(AdminSQL.INSERT, ja(userId))
.doOnSuccess(SQLAssert::assertUpdated)
.ignoreElement()
.subscribe(CompletableHelper.toObserver(handler));
}
@Override
public void queryAll(Handler<AsyncResult<List<Admin>>> handler) {
dbClient.rxQuery(AdminSQL.QUERY_ALL)
.map(records -> records.getRows().stream().map(AdminHelper::fromDBRecord).collect(Collectors.toList()))
.subscribe(SingleHelper.toObserver(handler));
}
}
| 6,852 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/FileHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.master.entity.File;
import java.time.Instant;
public class FileHelper {
public static File fromDBRecord(JsonObject jsonObject) {
File file = new File();
EntityHelper.fill(file, jsonObject);
file.setUserId(jsonObject.getString("user_id"));
file.setOriginalName(jsonObject.getString("original_name"));
file.setDisplayName(jsonObject.getString("display_name"));
file.setName(jsonObject.getString("name"));
file.setType(FileType.valueOf(jsonObject.getString("type")));
file.setSize(jsonObject.getLong("size"));
file.setHostIP(jsonObject.getString("host_ip"));
file.setTransferState(FileTransferState.valueOf(jsonObject.getString("transfer_state")));
file.setShared(jsonObject.getInteger("shared") == 1);
file.setDownloadable(jsonObject.getInteger("downloadable") == 1);
file.setInSharedDisk(jsonObject.getInteger("in_shared_disk") == 1);
file.setDeleted(jsonObject.getInteger("deleted") == 1);
Instant deletedTime = jsonObject.getInstant("deleted_time");
if (deletedTime != null) {
file.setDeletedTime(deletedTime.toEpochMilli());
}
return file;
}
}
| 6,853 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/WorkerHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.master.entity.Worker;
public class WorkerHelper {
public static Worker fromDBRecord(JsonObject jsonObject) {
Worker worker = new Worker();
EntityHelper.fill(worker, jsonObject);
worker.setHostIP(jsonObject.getString("host_ip"));
worker.setHostName(jsonObject.getString("host_name"));
worker.setCurrentLoad(jsonObject.getLong("current_load"));
worker.setMaxLoad(jsonObject.getLong("max_load"));
worker.setCpuCount(jsonObject.getLong("cpu_count"));
worker.setMemoryUsed(jsonObject.getLong("memory_used"));
worker.setMemoryTotal(jsonObject.getLong("memory_total"));
worker.setDiskUsed(jsonObject.getLong("disk_used"));
worker.setDiskTotal(jsonObject.getLong("disk_total"));
return worker;
}
}
| 6,854 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/EntityHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.master.entity.Entity;
class EntityHelper {
static void fill(Entity entity, JsonObject json) {
entity.setId(json.getLong("id"));
entity.setLastModifiedTime(json.getInstant("last_modified_time").toEpochMilli());
entity.setCreationTime(json.getInstant("creation_time").toEpochMilli());
}
}
| 6,855 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/MasterHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.master.entity.Master;
public class MasterHelper {
public static Master fromDBRecord(JsonObject jsonObject) {
Master master = new Master();
EntityHelper.fill(master, jsonObject);
master.setHostIP(jsonObject.getString("host_ip"));
master.setHostName(jsonObject.getString("host_name"));
master.setLeader(jsonObject.getInteger("leader") == 1);
return master;
}
}
| 6,856 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/SQLAssert.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.UpdateResult;
import org.eclipse.jifa.common.ErrorCode;
import static org.eclipse.jifa.master.service.ServiceAssertion.SERVICE_ASSERT;
public class SQLAssert {
public static void assertSelected(ResultSet resultSet) {
assertSelected(resultSet, 1);
}
public static void assertSelected(ResultSet result, int expected) {
SERVICE_ASSERT.isTrue(result.getNumRows() == expected, ErrorCode.SANITY_CHECK);
}
public static void assertUpdated(UpdateResult result) {
assertUpdated(result, 1);
}
public static void assertUpdated(UpdateResult result, int expected) {
SERVICE_ASSERT.isTrue(result.getUpdated() == expected, ErrorCode.SANITY_CHECK);
}
}
| 6,857 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/AdminHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.master.entity.Admin;
public class AdminHelper {
public static Admin fromDBRecord(JsonObject jsonObject) {
Admin job = new Admin();
EntityHelper.fill(job, jsonObject);
job.setUserId(jsonObject.getString("user_id"));
return job;
}
}
| 6,858 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/JobHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.master.entity.Job;
import org.eclipse.jifa.master.entity.enums.JobState;
import org.eclipse.jifa.master.entity.enums.JobType;
import java.time.Instant;
public class JobHelper {
public static Job fromDBRecord(JsonObject jsonObject) {
Job job = new Job();
EntityHelper.fill(job, jsonObject);
job.setUserId(jsonObject.getString("user_id"));
job.setType(JobType.valueOf(jsonObject.getString("type")));
job.setTarget(jsonObject.getString("target"));
job.setState(JobState.valueOf(jsonObject.getString("state")));
job.setHostIP(jsonObject.getString("host_ip"));
job.setEstimatedLoad(jsonObject.getLong("estimated_load"));
job.setAttachment(jsonObject.getString("attachment"));
Instant accessTime = jsonObject.getInstant("access_time");
if (accessTime != null) {
job.setAccessTime(accessTime.toEpochMilli());
}
return job;
}
}
| 6,859 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/SQLHelper.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.sql.ResultSet;
import org.eclipse.jifa.master.service.sql.SQL;
import java.time.Instant;
public class SQLHelper {
public static JsonObject singleRow(ResultSet resultSet) {
SQLAssert.assertSelected(resultSet);
return resultSet.getRows().get(0);
}
public static int count(ResultSet resultSet) {
SQLAssert.assertSelected(resultSet);
return resultSet.getRows().get(0).getInteger(SQL.COUNT_NAME);
}
public static JsonArray ja(String param) {
return new JsonArray().add(param);
}
public static JsonArray ja(String param1, String param2) {
return ja(param1).add(param2);
}
public static JsonArray ja(Instant param) {
return new JsonArray().add(param);
}
public static JsonArray ja(Object... params) {
JsonArray jsonArray = new JsonArray();
for (Object param : params) {
if (param instanceof JsonArray) {
jsonArray.addAll((JsonArray) param);
} else if (param instanceof Enum) {
jsonArray.add((Enum) param);
} else {
jsonArray.add(param);
}
}
return jsonArray;
}
}
| 6,860 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/impl/helper/ConfigHelper.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.impl.helper;
import io.vertx.core.json.JsonObject;
public class ConfigHelper {
public static int getInt(JsonObject json) {
return Integer.parseInt(json.getString("value"));
}
public static long getLong(JsonObject json) {
return Long.parseLong(json.getString("value"));
}
public static boolean getBoolean(JsonObject json) {
return Boolean.parseBoolean(json.getString("value"));
}
public static String getString(JsonObject json) {
return json.getString("value");
}
}
| 6,861 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/ConfigSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface ConfigSQL {
String SELECT = "SELECT * FROM config WHERE name = ?";
}
| 6,862 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/JobSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface JobSQL {
String COUNT_ALL_PENDING = "SELECT COUNT(*) FROM active_job WHERE state = 'PENDING'";
String COUNT_PENDING_BY_HOST_IP =
"SELECT COUNT(*) FROM active_job WHERE state = 'PENDING' AND (host_ip IS NULL or host_ip = ?)";
String SELECT_ALL_PENDING =
"SELECT * FROM active_job WHERE state = 'PENDING' ORDER BY creation_time ASC";
String INSERT_ACTIVE =
"INSERT INTO active_job(user_id, type, state, target, host_ip, attachment, estimated_load, keep_alive) VALUE" +
"(?, ?, ?, ?, ?, ?, ?, ?)";
String UPDATE_ACCESS_TIME = "UPDATE active_job SET access_time = now() WHERE type = ? AND target = ?";
String SELECT_ACTIVE_BY_TYPE_AND_TARGET = "SELECT * FROM active_job WHERE type = ? AND target = ?";
String SELECT_ACTIVE_BY_TARGET = "SELECT * FROM active_job WHERE target = ?";
String DELETE_ACTIVE_BY_TYPE_AND_TARGET = "DELETE FROM active_job WHERE type = ? AND target = ?";
String INSERT_HISTORICAL =
"INSERT INTO historical_job(user_id, type, target, host_ip, estimated_load) VALUE(?, ?, ?, ?, ?)";
String SELECT_FRONT_PENDING =
"SELECT * FROM active_job WHERE state = 'PENDING' AND creation_time < ? ORDER BY creation_time ASC";
String SELECT_FRONT_PENDING_BY_HOST_IP =
"SELECT * FROM active_job WHERE state = 'PENDING' AND (host_ip IS NULL or host_ip = ?) AND " +
"creation_time < ? ORDER BY creation_time ASC";
String SELECT_TO_RETIRE =
"SELECT * FROM active_job WHERE state = 'IN_PROGRESS' AND keep_alive = 0 AND access_time <= ?";
String SELECT_TRANSFER_JOB_TO_FILLING_RESULT =
"SELECT * FROM active_job WHERE state = 'IN_PROGRESS' AND type = 'FILE_TRANSFER' AND access_time <= ?";
String UPDATE_TO_IN_PROGRESS =
"UPDATE active_job SET state = 'IN_PROGRESS', host_ip = ?, access_time = ? WHERE type = ? AND target = ?";
String SELECT_ALL_ACTIVE_JOBS = "SELECT * FROM active_job";
String SELECT_TRANSFER_JOB_BY_NAME = "SELECT * FROM active_job WHERE type = 'FILE_TRANSFER' AND target = ?";
}
| 6,863 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/GlobalLockSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface GlobalLockSQL {
String LOCK = "SELECT * FROM global_lock WHERE name = ? FOR UPDATE";
}
| 6,864 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/WorkerSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface WorkerSQL {
String SELECT_MOST_IDLE =
"SELECT * FROM worker ORDER BY (max_load - current_load) DESC, last_modified_time ASC LIMIT 1";
String SELECT_BY_IP = "SELECT * FROM worker WHERE host_ip = ?";
String SELECT_ALL = "SELECT * FROM worker";
String UPDATE_LOAD = "UPDATE worker SET current_load = ? WHERE host_ip = ?";
String SELECT_FOR_DISK_CLEANUP =
"SELECT * FROM worker WHERE disk_total > 0 AND disk_used / disk_total >= 0.75 ORDER BY disk_used DESC LIMIT 20";
String UPDATE_DISK_USAGE = "UPDATE worker SET disk_total= ?, disk_used= ? WHERE host_ip = ?";
}
| 6,865 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/SQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface SQL {
String COUNT_NAME = "COUNT(*)";
String SELECT_TRUE = "SELECT TRUE";
}
| 6,866 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/MasterSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface MasterSQL {
String SELECT = "SELECT * FROM master where host_ip = ?";
}
| 6,867 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/AdminSQL.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface AdminSQL {
String SELECT_BY_USER_ID = "SELECT * FROM admin WHERE user_id = ?";
String INSERT = "INSERT INTO admin(user_id) VALUES(?)";
String QUERY_ALL = "SELECT * FROM admin";
}
| 6,868 |
0 | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service | Create_ds/eclipse-jifa/backend/master/src/main/java/org/eclipse/jifa/master/service/sql/FileSQL.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.master.service.sql;
public interface FileSQL {
String INSERT = "INSERT INTO file(user_id, original_name, name, type, size, host_ip, transfer_state, shared, " +
"downloadable, in_shared_disk, deleted, cas_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String SELECT_BY_USER_ID_AND_TYPE =
"SELECT * FROM file WHERE user_id = ? AND type = ? AND deleted = false ORDER BY creation_time DESC LIMIT ?, ?";
String COUNT_BY_USER_ID_AND_TYPE = "SELECT COUNT(*) FROM file WHERE user_id = ? AND type = ? AND deleted = false";
String SELECT_BY_USER_ID_AND_TYPE_AND_EXPECTED_NAME =
"SELECT * FROM file WHERE user_id = ? AND type = ? AND (name like ? OR display_name like ?) AND deleted = " +
"false ORDER BY creation_time DESC LIMIT ?, ?";
String COUNT_BY_USER_ID_AND_TYPE_AND_EXPECTED_NAME = "SELECT COUNT(*) FROM file WHERE user_id = ? AND type = ? " +
"AND (name like ? OR display_name like ?) AND deleted = false";
String SELECT_FILE_BY_NAME = "SELECT * FROM file WHERE name = ?";
String UPDATE_TRANSFER_RESULT = "UPDATE file SET transfer_state = ?, size = ? WHERE name = ?";
String SET_SHARED = "UPDATE file SET shared = 1 WHERE name = ?";
/**
* To simultaneously accept users' requests while doing disk cleaning task
* we can CAS cas_state field to handle these works, its values are as follow:
* <p>
* cas_state(0) - This file is not being using by users
* cas_state(1) - This file is currently being using by users
* cas_state(2) - This file will be deleted quickly
*/
String UPDATE_FILE_AS_USED =
"UPDATE file SET cas_state = 1 WHERE name = ? and deleted = false AND (cas_state = 0 OR cas_state = 1)";
String UPDATE_FILE_AS_UNUSED =
"UPDATE file SET cas_state = 0 WHERE name = ? and deleted = false AND (cas_state = 1 OR cas_state = 0)";
String UPDATE_AS_PENDING_DELETE_BY_HOST = "UPDATE file SET cas_state = 2 WHERE host_ip = ? AND deleted = false AND " +
"cas_state = 0 AND transfer_state != 'IN_PROGRESS' ORDER BY creation_time ASC LIMIT 10";
String UPDATE_AS_PENDING_DELETE_BY_FILE_NAME = "UPDATE file SET cas_state = 2 WHERE name = ? AND deleted = false AND " +
"cas_state = 0 AND transfer_state != 'IN_PROGRESS' ORDER BY creation_time ASC LIMIT 10";
String SELECT_PENDING_DELETE_BY_HOST = "SELECT * FROM file WHERE host_ip = ? AND cas_state = 2 AND deleted = false";
String SELECT_PENDING_DELETE_BY_FILE_NAME = "SELECT * FROM file WHERE name = ? AND cas_state = 2 AND deleted = false";
String DELETE_FILE_BY_NAME =
"UPDATE file SET deleted = true, deleter = ?, deleted_time = now(), cas_state = 0 WHERE name= ? AND deleted = false";
String UPDATE_DISPLAY_NAME = "UPDATE file SET display_name = ? WHERE name = ?";
String SELECT_FILES_FOR_SYNC =
"SELECT * FROM file WHERE host_ip = ? AND transfer_state = 'SUCCESS' AND deleted = false AND type != 'JINSIGHT'";
String SELECT_DATED_FILES =
"SELECT f.* FROM file f LEFT JOIN active_job aj ON f.name=aj.target " +
"WHERE aj.target is null and " +
"f.deleted=0 and " +
"f.cas_state=0 and " +
"f.transfer_state='SUCCESS' and " +
"f.last_modified_time < now() - interval 7 day " +
"LIMIT 50";
String SELECT_TIMEOUT_IN_PROGRESS_FILE = "SELECT * FROM file WHERE transfer_state = 'IN_PROGRESS' AND " +
"last_modified_time < now() - INTERVAL 1 day ";
String UPDATE_IN_PROGRESS_FILE_AS_ERROR_BY_NAME = "UPDATE file SET transfer_state = 'ERROR' WHERE name = ? and transfer_state = 'IN_PROGRESS'";
}
| 6,869 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/FakeHooks.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.common.JifaHooks;
import java.util.concurrent.atomic.AtomicInteger;
public class FakeHooks implements JifaHooks {
static AtomicInteger initTriggered = new AtomicInteger(0);
public FakeHooks() {
}
public static void reset() {
initTriggered.set(0);
}
public static int countInitTriggered() {
return initTriggered.get();
}
@Override
public void init(JsonObject config) {
initTriggered.incrementAndGet();
}
}
| 6,870 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/TestWorker.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@RunWith(VertxUnitRunner.class)
public class TestWorker {
private static Logger LOGGER = LoggerFactory.getLogger(TestWorker.class);
@Before
public void setup(TestContext context) throws Exception {
FakeHooks.reset();
}
@Test
public void testStartupBasicConfig(TestContext context) throws Exception {
Map<String, Object> cfg = new HashMap<>();
cfg.put("server.port", findRandomPort());
cfg.put("server.host", "127.0.0.1");
cfg.put("api.prefix", "/jifa-api");
Map<String, Object> auth = new HashMap<>();
auth.put("enabled", false);
cfg.put("basicAuth", auth);
Map<String, Object> cache = new HashMap<>();
cache.put("expireAfterAccess", 10);
cache.put("expireAfterAccessTimeUnit", "MINUTES");
cfg.put("cacheConfig", cache);
Async async = context.async();
Vertx vertx = Vertx.vertx();
CountDownLatch count = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(1);
Worker.setCount(count);
vertx.deployVerticle(Worker.class.getName(),
new DeploymentOptions().setConfig(new JsonObject(cfg)).setInstances(1),
res -> {
if (res.succeeded()) {
try {
count.await();
} catch (InterruptedException e) {
context.fail(e);
return;
}
vertx.undeploy(res.result(), res2 -> {
if (res2.succeeded()) {
done.countDown();
async.complete();
} else {
context.fail(res2.cause());
}
});
} else {
context.fail(res.cause());
}
});
done.await();
}
@Test
public void testStartWithHook(TestContext context) throws Exception {
Map<String, Object> cfg = new HashMap<>();
cfg.put("server.port", findRandomPort());
cfg.put("server.host", "127.0.0.1");
cfg.put("api.prefix", "/jifa-api");
Map<String, Object> auth = new HashMap<>();
auth.put("enabled", false);
cfg.put("basicAuth", auth);
cfg.put("hooks.className", FakeHooks.class.getName());
Map<String, Object> cache = new HashMap<>();
cache.put("expireAfterAccess", 10);
cache.put("expireAfterAccessTimeUnit", "MINUTES");
cfg.put("cacheConfig", cache);
Async async = context.async();
Vertx vertx = Vertx.vertx();
CountDownLatch count = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(1);
Worker.setCount(count);
vertx.deployVerticle(Worker.class.getName(),
new DeploymentOptions().setConfig(new JsonObject(cfg)).setInstances(1),
res -> {
if (res.succeeded()) {
try {
count.await();
} catch (InterruptedException e) {
context.fail(e);
return;
}
vertx.undeploy(res.result(), res2 -> {
if (res2.succeeded()) {
context.assertEquals(FakeHooks.countInitTriggered(), 1);
done.countDown();
async.complete();
} else {
context.fail(res2.cause());
}
});
} else {
context.fail(res.cause());
}
});
done.await();
}
@After
public void reset() {
Worker.resetCount();
}
int findRandomPort() throws IOException {
ServerSocket socket = new ServerSocket(0);
int port = socket.getLocalPort();
socket.close();
return port;
}
}
| 6,871 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/route/TestRoutes.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import com.google.common.io.Files;
import com.sun.management.HotSpotDiagnosticMXBean;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.apache.commons.io.FileUtils;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.worker.Worker;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.eclipse.jifa.worker.support.FileSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.management.ManagementFactory;
@RunWith(VertxUnitRunner.class)
public class TestRoutes {
private static Logger LOGGER = LoggerFactory.getLogger(TestRoutes.class);
@Before
public void setup(TestContext context) throws Exception {
// start worker
Worker.main(new String[]{});
// prepare heap dump file
HotSpotDiagnosticMXBean mxBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
String name = "test_dump_" + System.currentTimeMillis() + ".hprof";
Base.TEST_HEAP_DUMP_FILENAME = name;
mxBean.dumpHeap(name, false);
FileSupport.initInfoFile(FileType.HEAP_DUMP, name, name);
Files.move(new File(name), new File(FileSupport.filePath(FileType.HEAP_DUMP, name)));
FileSupport.updateTransferState(FileType.HEAP_DUMP, name, FileTransferState.SUCCESS);
}
@Test
public void testRoutes(TestContext context) throws Exception {
FileRouteSuite.test(context);
HeapDumpRouteSuite.test(context);
}
@After
public void tearDown(TestContext context) {
try {
System.out.println(context);
FileUtils.deleteDirectory(new File(WorkerGlobal.workspace()));
WorkerGlobal.VERTX.close(context.asyncAssertSuccess());
} catch (Throwable t) {
LOGGER.error("Error", t);
}
}
}
| 6,872 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/route/FileRouteSuite.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import com.google.gson.reflect.TypeToken;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.common.vo.FileInfo;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.worker.Worker;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
public class FileRouteSuite extends Base {
private static Logger LOGGER = LoggerFactory.getLogger(FileRouteSuite.class);
public static void test(TestContext context) {
Async async = context.async();
LOGGER.info("port = {}, host = {}, uri = {}", WorkerGlobal.PORT, WorkerGlobal.HOST, uri("/files"));
CLIENT.get(WorkerGlobal.PORT, WorkerGlobal.HOST, uri("/files"))
.addQueryParam("type", FileType.HEAP_DUMP.name())
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10")
.send(ar -> {
context.assertTrue(ar.succeeded(), ar.cause() != null ? ar.cause().getMessage() : "");
Type type = new TypeToken<PageView<FileInfo>>() {
}.getType();
PageView<FileInfo> view = GSON.fromJson(ar.result().bodyAsString(), type);
context.assertTrue(view.getData().size() > 0, ar.result().bodyAsString());
async.complete();
});
}
}
| 6,873 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/route/Base.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import io.vertx.core.Vertx;
import io.vertx.ext.web.client.WebClient;
import org.eclipse.jifa.worker.Constant;
import org.eclipse.jifa.worker.WorkerGlobal;
public class Base {
static WebClient CLIENT = WebClient.create(Vertx.vertx());
static String TEST_HEAP_DUMP_FILENAME;
public static String uri(String uri) {
return WorkerGlobal.stringConfig(Constant.ConfigKey.API_PREFIX) + uri;
}
}
| 6,874 |
0 | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/test/java/org/eclipse/jifa/worker/route/HeapDumpRouteSuite.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import com.google.gson.reflect.TypeToken;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import org.eclipse.jifa.common.enums.ProgressState;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.common.vo.Progress;
import org.eclipse.jifa.common.vo.Result;
import org.eclipse.jifa.hda.api.Model;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.eclipse.jifa.common.Constant.HTTP_GET_OK_STATUS_CODE;
import static org.eclipse.jifa.common.Constant.HTTP_POST_CREATED_STATUS_CODE;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
public class HeapDumpRouteSuite extends Base {
private static final Logger LOGGER = LoggerFactory.getLogger(HeapDumpRouteSuite.class);
static TestContext context;
public static void test(TestContext c) throws Exception {
context = c;
Holder holder = new Holder();
testGet("/isFirstAnalysis",
(PostProcessor) resp -> {
Type type = new TypeToken<Result<Boolean>>() {
}.getType();
Result<Boolean> result = GSON.fromJson(resp.bodyAsString(), type);
context.assertTrue(result.getResult(), resp.bodyAsString());
});
testPost("/analyze");
AtomicBoolean success = new AtomicBoolean();
while (!success.get()) {
testGet("/progressOfAnalysis",
(PostProcessor) resp -> {
Progress progress = GSON.fromJson(resp.bodyAsString(), Progress.class);
ProgressState state = progress.getState();
context.assertTrue(state == ProgressState.IN_PROGRESS || state == ProgressState.SUCCESS,
resp.bodyAsString());
if (state == ProgressState.SUCCESS) {
success.set(true);
}
});
Thread.sleep(200);
}
// overview
testGet("/details");
testGet("/biggestObjects");
// class loader
testGet("/classLoaderExplorer/summary");
testGet("/classLoaderExplorer/classLoader",
req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"),
resp -> {
Type type = new TypeToken<PageView<Model.ClassLoader.Item>>() {
}.getType();
PageView<Model.ClassLoader.Item> result = GSON.fromJson(resp.bodyAsString(), type);
holder.id = result.getData().get(0).getObjectId();
});
testGet("/classLoaderExplorer/children",
(PreProcessor) req -> req.addQueryParam("classLoaderId", String.valueOf(holder.id))
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
// class reference
testGet("/classReference/inbounds/class",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id)));
testGet("/classReference/outbounds/class",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id)));
// direct byte buffer
testGet("/directByteBuffer/summary");
testGet("/directByteBuffer/records",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
// dominator tree
testGet("/dominatorTree/roots",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("grouping", "NONE"));
testGet("/dominatorTree/children",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("pageSize", "10")
.addQueryParam("grouping", "NONE")
.addQueryParam("idPathInResultTree", "[" + holder.id + "]")
.addQueryParam("parentObjectId", String.valueOf(holder.id)));
// gc root
testGet("/GCRoots");
testGet("/GCRoots/classes",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10")
.addQueryParam("rootTypeIndex", "1"));
testGet("/GCRoots/class/objects",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10")
.addQueryParam("rootTypeIndex", "1")
.addQueryParam("classIndex", "1"));
// histogram
testGet("/histogram",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("groupingBy", "BY_CLASS"));
// inspector
testGet("/inspector/objectView",
req -> req.addQueryParam("objectId", String.valueOf(holder.id)),
resp -> {
Model.InspectorView view = GSON.fromJson(resp.bodyAsString(), Model.InspectorView.class);
holder.objectAddress = view.getObjectAddress();
});
testGet("/inspector/addressToId",
(PreProcessor) req -> req.addQueryParam("objectAddress", String.valueOf(holder.objectAddress)));
testGet("/inspector/value",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id)));
testGet("/inspector/fields",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id))
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
testGet("/inspector/staticFields",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id))
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
// leak report
testGet("/leak/report");
// object list
testGet("/outbounds",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id))
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
testGet("/inbounds",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id))
.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
// object
testGet("/object",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id)));
// oql
testGet("/oql",
(PreProcessor) req -> req.addQueryParam("oql", "select * from java.lang.String")
.addQueryParam("page", "1")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("pageSize", "10"));
// oql
testGet("/sql",
(PreProcessor) req -> req.addQueryParam("sql", "select * from java.lang.String")
.addQueryParam("page", "1")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("pageSize", "10"));
// path to gc roots
testGet("/pathToGCRoots",
(PreProcessor) req -> req.addQueryParam("origin", String.valueOf(holder.id))
.addQueryParam("skip", "0")
.addQueryParam("count", "10"));
// system property
testGet("/systemProperties");
// thread
testGet("/threadsSummary");
testGet("/threads",
req -> req.addQueryParam("page", "1")
.addQueryParam("sortBy", "id")
.addQueryParam("ascendingOrder", "true")
.addQueryParam("pageSize", "10"),
resp -> {
Type type = new TypeToken<PageView<Model.Thread.Item>>() {
}.getType();
PageView<Model.Thread.Item> result = GSON.fromJson(resp.bodyAsString(), type);
holder.id = result.getData().get(0).getObjectId();
}
);
testGet("/stackTrace",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id)));
testGet("/locals",
(PreProcessor) req -> req.addQueryParam("objectId", String.valueOf(holder.id))
.addQueryParam("depth", "1")
.addQueryParam("firstNonNativeFrame", "false"));
// unreachable objects
testGet("/unreachableObjects/summary");
testGet("/unreachableObjects/records",
(PreProcessor) req -> req.addQueryParam("page", "1")
.addQueryParam("pageSize", "10"));
}
static void testGet(String uri) {
testGet(uri, null, null);
}
static void testGet(String uri, PreProcessor processor) {
testGet(uri, processor, null);
}
static void testGet(String uri, PostProcessor postProcessor) {
testGet(uri, null, postProcessor);
}
static void testGet(String uri, PreProcessor processor, PostProcessor postProcessor) {
test(uri, HttpMethod.GET, processor, postProcessor);
}
static void testPost(String uri) {
test(uri, HttpMethod.POST, null, null);
}
static void test(String uri, HttpMethod method, PreProcessor processor, PostProcessor postProcessor) {
LOGGER.info("test {}", uri);
Async async = context.async();
LOGGER.info("method = {}, port = {}, host = {}, uri = {}", method, WorkerGlobal.PORT, WorkerGlobal.HOST,
uri("/heap-dump/" + TEST_HEAP_DUMP_FILENAME + uri));
HttpRequest<Buffer> request =
CLIENT.request(method, WorkerGlobal.PORT, WorkerGlobal.HOST,
uri("/heap-dump/" + TEST_HEAP_DUMP_FILENAME + uri));
if (processor != null) {
processor.process(request);
}
request.send(
ar -> {
context.assertTrue(ar.succeeded(), ar.cause() != null ? ar.cause().getMessage() : "");
LOGGER.debug("{}: {} - {}", uri, ar.result().statusCode(), ar.result().bodyAsString());
context.assertEquals(ar.result().statusCode(),
method == HttpMethod.GET ? HTTP_GET_OK_STATUS_CODE : HTTP_POST_CREATED_STATUS_CODE,
ar.result().bodyAsString());
if (postProcessor != null) {
postProcessor.process(ar.result());
}
LOGGER.info("{}: {}", uri, ar.result().bodyAsString());
async.complete();
}
);
async.awaitSuccess();
}
interface PreProcessor {
void process(HttpRequest<Buffer> request);
}
interface PostProcessor {
void process(HttpResponse<Buffer> resp);
}
static class Holder {
int id;
long objectAddress;
}
}
| 6,875 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/WorkerGlobal.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.eclipse.jifa.common.JifaHooks;
import org.eclipse.jifa.worker.support.FileSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
public class WorkerGlobal {
private static final Logger LOGGER = LoggerFactory.getLogger(Worker.class);
public static Vertx VERTX;
public static String HOST;
public static int PORT;
private static JsonObject CONFIG;
private static String WORKSPACE;
private static JifaHooks HOOKS;
private static boolean initialized;
static synchronized void reset() {
if (!initialized) {
return;
}
VERTX = null;
HOST = null;
PORT = 0;
CONFIG = null;
HOOKS = null;
initialized = false;
}
static synchronized void init(Vertx vertx, String host, int port, JsonObject config, JifaHooks hooks) {
if (initialized) {
return;
}
VERTX = vertx;
HOST = host;
PORT = port;
CONFIG = config;
HOOKS = hooks;
WORKSPACE = CONFIG.getString(Constant.ConfigKey.WORKSPACE, org.eclipse.jifa.common.Constant.DEFAULT_WORKSPACE);
LOGGER.debug("Workspace: {}", WORKSPACE);
File workspaceDir = new File(WORKSPACE);
if (workspaceDir.exists()) {
ASSERT.isTrue(workspaceDir.isDirectory(), "Workspace must be directory");
} else {
ASSERT.isTrue(workspaceDir.mkdirs(),
() -> "Can not create workspace: " + workspaceDir.getAbsolutePath());
}
FileSupport.init();
initialized = true;
}
public static String stringConfig(String key) {
return CONFIG.getString(key);
}
public static String stringConfig(String... keys) {
JsonObject o = CONFIG;
for (int i = 0; i < keys.length - 1; i++) {
o = o.getJsonObject(keys[i]);
}
return o.getString(keys[keys.length - 1]);
}
public static int intConfig(String... keys) {
JsonObject o = CONFIG;
for (int i = 0; i < keys.length - 1; i++) {
o = o.getJsonObject(keys[i]);
}
return o.getInteger(keys[keys.length - 1]);
}
public static boolean booleanConfig(String... keys) {
JsonObject o = CONFIG;
for (int i = 0; i < keys.length - 1; i++) {
o = o.getJsonObject(keys[i]);
}
if (o == null) {
return false;
}
return o.getBoolean(keys[keys.length - 1]);
}
public static String workspace() {
return WORKSPACE;
}
public static JifaHooks hooks() {
return HOOKS;
}
}
| 6,876 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/Constant.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker;
public interface Constant extends org.eclipse.jifa.common.Constant {
interface Misc {
String VERTX_CONFIG_PROP = "jifa.vertx.config";
String WORKER_CONFIG_PROP = "jifa.worker.config";
String DEFAULT_VERTX_CONFIG_FILE = "vertx-config.json";
String DEFAULT_WORKER_CONFIG_FILE = "worker-config.json";
String DEFAULT_HOST = "0.0.0.0";
String WEB_ROOT_KEY = "jifa.webroot";
}
interface Heap {
String TOTAL_SIZE_KEY = "totalSize";
String SHALLOW_HEAP_KEY = "shallowHeap";
String RETAINED_HEAP_KEY = "retainedHeap";
}
interface File {
String INFO_FILE_SUFFIX = "-info.json";
}
interface ConfigKey {
String BASIC_AUTH = "basicAuth";
String ENABLED = "enabled";
String WORKSPACE = "workspace";
String API_PREFIX = "api.prefix";
String SERVER_HOST_KEY = "server.host";
String SERVER_PORT_KEY = "server.port";
String USERNAME = "username";
String PASSWORD = "password";
String HOOKS_NAME_KEY = "hooks.className";
String SERVER_UPLOAD_DIR_KEY = "server.uploadDir";
}
interface CacheConfig {
String CACHE_CONFIG = "cacheConfig";
String EXPIRE_AFTER_ACCESS = "expireAfterAccess";
String EXPIRE_AFTER_ACCESS_TIME_UNIT = "expireAfterAccessTimeUnit";
}
}
| 6,877 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/Worker.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker;
import com.google.common.base.Strings;
import io.vertx.core.*;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.*;
import org.apache.commons.io.FileUtils;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.JifaHooks;
import org.eclipse.jifa.common.util.FileUtil;
import org.eclipse.jifa.worker.route.RouteFiller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import static org.eclipse.jifa.worker.Constant.ConfigKey.*;
import static org.eclipse.jifa.worker.Constant.Misc.*;
import static org.eclipse.jifa.worker.WorkerGlobal.stringConfig;
public class Worker extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(Worker.class);
private static CountDownLatch count = new CountDownLatch(Runtime.getRuntime().availableProcessors());
private static long startTime;
public static void main(String[] args) throws InterruptedException, IOException {
startTime = System.currentTimeMillis();
JsonObject vertxConfig = readConfig(VERTX_CONFIG_PROP, DEFAULT_VERTX_CONFIG_FILE);
Vertx vertx = Vertx.vertx(new VertxOptions(vertxConfig));
JsonObject jifaConfig = readConfig(WORKER_CONFIG_PROP, DEFAULT_WORKER_CONFIG_FILE);
jifaConfig.getJsonObject(BASIC_AUTH).put(ENABLED, false);
vertx.deployVerticle(Worker.class.getName(), new DeploymentOptions().setConfig(jifaConfig).setInstances(
Runtime.getRuntime().availableProcessors()));
count.await();
}
private static int randomPort() {
try {
ServerSocket socket = new ServerSocket(0);
int port = socket.getLocalPort();
socket.close();
return port;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static JsonObject readConfig(String key, String def) throws IOException {
// Read default config first
JsonObject config = new JsonObject(FileUtil.content(Worker.class.getClassLoader().getResourceAsStream(def)));
// Merge the config items if customized config file is set.
String v = System.getProperty(key);
if (!Strings.isNullOrEmpty(v)) {
JsonObject customConfig = new JsonObject(FileUtils.readFileToString(new File(v), Charset.defaultCharset()));
config.mergeIn(customConfig);
}
return config;
}
// test support
public static void setCount(CountDownLatch count) {
Worker.count = count;
}
public static void resetCount() {
count = new CountDownLatch(Runtime.getRuntime().availableProcessors());
}
@SuppressWarnings("unchecked")
JifaHooks findHooks() {
JifaHooks hook = null;
if (config().containsKey(HOOKS_NAME_KEY)) {
String className = config().getString(HOOKS_NAME_KEY);
try {
LOGGER.info("applying hooks: " + className);
Class<JifaHooks> clazz = (Class<JifaHooks>) Class.forName(className);
hook = clazz.getConstructor().newInstance();
hook.init(config());
} catch (ReflectiveOperationException e) {
LOGGER.warn("could not start hook class: " + className + ", due to error", e);
}
}
return hook != null ? hook : new JifaHooks.EmptyHooks();
}
private void setupBasicAuthHandler(Router router) {
AuthenticationHandler authHandler = BasicAuthHandler.create((authInfo, resultHandler) -> {
Promise<User> promise = Promise.promise();
if (stringConfig(BASIC_AUTH, USERNAME).equals(authInfo.getString(USERNAME)) &&
stringConfig(BASIC_AUTH, PASSWORD).equals(authInfo.getString(PASSWORD))) {
promise.complete(User.create(authInfo));
} else {
promise.fail(new JifaException("Illegal User"));
}
resultHandler.handle(promise.future());
});
router.route().handler(authHandler);
}
@Override
public void start() {
String host = config().containsKey(SERVER_HOST_KEY) ? config().getString(SERVER_HOST_KEY) : DEFAULT_HOST;
int port = config().containsKey(SERVER_PORT_KEY) ? config().getInteger(SERVER_PORT_KEY) : randomPort();
String staticRoot = System.getProperty(WEB_ROOT_KEY, "webroot");
String uploadDir =
config().containsKey(SERVER_UPLOAD_DIR_KEY) ? config().getString(SERVER_UPLOAD_DIR_KEY) : null;
JifaHooks hooks = findHooks();
vertx.executeBlocking(event -> {
WorkerGlobal.init(vertx, host, port, config(), hooks);
HttpServer server = vertx.createHttpServer(hooks.serverOptions(vertx));
Router router = Router.router(vertx);
// body handler always ends to be first so it can read the body
if (uploadDir == null) {
router.post().handler(BodyHandler.create());
} else {
router.post().handler(BodyHandler.create(uploadDir));
}
hooks.beforeRoutes(vertx, router);
File webRoot = new File(staticRoot);
if (webRoot.exists() && webRoot.isDirectory()) {
StaticHandler staticHandler = StaticHandler.create();
staticHandler.setAllowRootFileSystemAccess(true);
staticHandler.setWebRoot(staticRoot);
// non-api
String staticPattern = "^(?!" + WorkerGlobal.stringConfig(Constant.ConfigKey.API_PREFIX) + ").*$";
router.routeWithRegex(staticPattern)
.handler(staticHandler)
// route to "/" if not found
.handler(context -> context.reroute("/"));
}
// cors
router.route().handler(CorsHandler.create("*"));
// basic auth
if (WorkerGlobal.booleanConfig(BASIC_AUTH, Constant.ConfigKey.ENABLED)) {
setupBasicAuthHandler(router);
}
router.post().handler(BodyHandler.create());
new RouteFiller(router).fill();
hooks.afterRoutes(vertx, router);
server.requestHandler(router);
server.listen(port, host, ar -> {
if (ar.succeeded()) {
event.complete();
} else {
event.fail(ar.cause());
}
});
}, ar -> {
if (ar.succeeded()) {
LOGGER.info("Jifa-Worker startup successfully in {} ms, verticle count = {}, http server = {}:{}",
System.currentTimeMillis() - startTime,
Runtime.getRuntime().availableProcessors(),
WorkerGlobal.HOST,
WorkerGlobal.PORT);
count.countDown();
} else {
LOGGER.error("Failed to start Jifa' worker side", ar.cause());
System.exit(-1);
}
});
}
@Override
public void stop() {
WorkerGlobal.reset();
}
}
| 6,878 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/RouteFiller.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.worker.route.gclog.GCLogBaseRoute;
import org.eclipse.jifa.worker.Constant;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.eclipse.jifa.worker.route.heapdump.HeapBaseRoute;
import org.eclipse.jifa.worker.route.threaddump.ThreadDumpBaseRoute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RouteFiller {
private static final Logger LOGGER = LoggerFactory.getLogger(RouteFiller.class);
private Router router;
public RouteFiller(Router router) {
this.router = router;
}
public void fill() {
try {
register(FileRoute.class);
register(AnalysisRoute.class);
register(SystemRoute.class);
for (Class<? extends HeapBaseRoute> route : HeapBaseRoute.routes()) {
register(route);
}
for (Class<? extends GCLogBaseRoute> route: GCLogBaseRoute.routes()){
register(route);
}
for (Class<? extends ThreadDumpBaseRoute> route: ThreadDumpBaseRoute.routes()){
register(route);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private String[] buildPrefixes(Class<?> clazz) {
ArrayList<String> prefixes = new ArrayList<>();
buildPrefix(prefixes, "", clazz);
return prefixes.toArray(new String[0]);
}
private void buildPrefix(ArrayList<String> prefixes, String prevPrefix, Class<?> clazz) {
if (clazz == null) {
String rootPrefix = WorkerGlobal.stringConfig(Constant.ConfigKey.API_PREFIX);
prefixes.add(rootPrefix + prevPrefix);
return;
}
MappingPrefix anno = clazz.getDeclaredAnnotation(MappingPrefix.class);
if (anno == null) {
buildPrefix(prefixes, prevPrefix, clazz.getSuperclass());
} else {
for (int i = 0; i < anno.value().length; i++) {
buildPrefix(prefixes, anno.value()[i] + prevPrefix, clazz.getSuperclass());
}
}
}
private void register(Class<? extends BaseRoute> clazz) throws Exception {
Constructor<? extends BaseRoute> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
BaseRoute thisObject = constructor.newInstance();
String[] prefixes = buildPrefixes(clazz);
Method[] methods = clazz.getDeclaredMethods();
for (String prefix : prefixes) {
for (Method method : methods) {
registerMethodRoute(thisObject, prefix, method);
}
}
}
private void registerMethodRoute(BaseRoute thisObject, String prefix, Method method) {
RouteMeta meta = method.getAnnotation(RouteMeta.class);
if (meta == null) {
return;
}
String fullPath = prefix + meta.path();
Route route = router.route(meta.method().toVertx(), fullPath);
Arrays.stream(meta.contentType()).forEach(route::produces);
method.setAccessible(true);
LOGGER.debug("Route: path = {}, method = {}", fullPath, method.toGenericString());
route.blockingHandler(rc -> {
try {
// pre-process
if (meta.contentType().length > 0) {
rc.response().putHeader("content-type", String.join(";", meta.contentType()));
}
List<Object> arguments = new ArrayList<>();
Parameter[] params = method.getParameters();
for (Parameter param : params) {
if (!RouterAnnotationProcessor.processParamKey(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processParamMap(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processPagingRequest(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processHttpServletRequest(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processHttpServletResponse(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processPromise(arguments, rc, method, param) &&
!RouterAnnotationProcessor.processRoutingContext(arguments, rc, method, param)
) {
throw new JifaException(ErrorCode.ILLEGAL_ARGUMENT,
"Illegal parameter meta, method = " + method);
}
}
method.invoke(thisObject, arguments.toArray());
} catch (Throwable t) {
HTTPRespGuarder.fail(rc, t);
}
}, false);
}
}
| 6,879 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/MappingPrefix.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MappingPrefix {
String[] value() default "";
}
| 6,880 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/SystemRoute.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.vo.DiskUsage;
import org.eclipse.jifa.worker.support.FileSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("unused")
class SystemRoute extends BaseRoute {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemRoute.class);
@RouteMeta(path = "/system/diskUsage")
void diskUsage(Promise<DiskUsage> promise) {
// Should we cache it?
long totalSpaceInMb = FileSupport.getTotalDiskSpace();
long usedSpaceInMb = FileSupport.getUsedDiskSpace();
assert totalSpaceInMb >= usedSpaceInMb;
LOGGER.info("Disk total {}MB, used {}MB", totalSpaceInMb, usedSpaceInMb);
promise.complete(new DiskUsage(totalSpaceInMb, usedSpaceInMb));
}
@RouteMeta(path = "/system/ping")
void ping(Promise<Void> promise) {
promise.complete();
}
}
| 6,881 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/AnalysisRoute.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerRequest;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.common.util.FileUtil;
import org.eclipse.jifa.common.vo.Progress;
import org.eclipse.jifa.common.vo.Result;
import org.eclipse.jifa.worker.Constant;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.eclipse.jifa.worker.support.Analyzer;
import org.eclipse.jifa.worker.support.FileSupport;
import java.io.File;
import java.util.Map;
@MappingPrefix(
value = {
"/heap-dump/:file",
"/gc-log/:file",
"/thread-dump/:file"}
)
class AnalysisRoute extends BaseRoute {
private final Analyzer helper = Analyzer.getInstance();
// TODO: not good enough
private FileType typeOf(HttpServerRequest request) {
String uri = request.uri();
String apiPrefix = WorkerGlobal.stringConfig(Constant.ConfigKey.API_PREFIX);
int end = uri.indexOf("/", apiPrefix.length() + 1);
return FileType.getByTag(uri.substring(apiPrefix.length() + 1, end));
}
@RouteMeta(path = "/isFirstAnalysis")
void isFirstAnalysis(HttpServerRequest request, Promise<Result<Boolean>> promise, @ParamKey("file") String file) {
promise.complete(new Result<>(helper.isFirstAnalysis(typeOf(request), file)));
}
@RouteMeta(path = "/analyze", method = HttpMethod.POST)
void analyze(HttpServerRequest request, Promise<Void> promise, @ParamKey("file") String file,
@ParamMap(keys = {"keep_unreachable_objects", "strictness"},
mandatory = {false, false, false}) Map<String, String> options) {
helper.analyze(promise, typeOf(request), file, options);
}
@RouteMeta(path = "/progressOfAnalysis")
void poll(HttpServerRequest request, Promise<Progress> promise, @ParamKey("file") String file) {
promise.complete(helper.pollProgress(typeOf(request), file));
}
@RouteMeta(path = "/release", method = HttpMethod.POST)
void release(HttpServerRequest request, Promise<Void> promise, @ParamKey("file") String file) {
helper.release(file);
promise.complete();
}
@RouteMeta(path = "/clean", method = HttpMethod.POST)
void clean(HttpServerRequest request, Promise<Void> promise, @ParamKey("file") String file) {
helper.clean(typeOf(request), file);
promise.complete();
}
@RouteMeta(path = "/errorLog")
void failedLog(HttpServerRequest request, Promise<Result<String>> promise, @ParamKey("file") String file) {
promise.complete(new Result<>(FileUtil.content(new File(FileSupport.errorLogPath(typeOf(request), file)))));
}
}
| 6,882 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/ParamKey.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ParamKey {
String value();
boolean mandatory() default true;
}
| 6,883 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/RouterAnnotationProcessor.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import com.google.gson.Gson;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.gclog.diagnoser.AnalysisConfig;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
class RouterAnnotationProcessor {
private static Map<Class<?>, Function<String, ?>> converter = new HashMap<>();
static {
converter.put(String.class, s -> s);
converter.put(Integer.class, Integer::parseInt);
converter.put(int.class, Integer::parseInt);
converter.put(Long.class, Long::parseLong);
converter.put(long.class, Long::parseLong);
converter.put(Float.class, Float::parseFloat);
converter.put(float.class, Float::parseFloat);
converter.put(Double.class, Double::parseDouble);
converter.put(double.class, Double::parseDouble);
converter.put(Boolean.class, Boolean::parseBoolean);
converter.put(boolean.class, Boolean::parseBoolean);
converter.put(int[].class, s -> new Gson().fromJson(s, int[].class));
converter.put(String[].class, s -> new Gson().fromJson(s, String[].class));
converter.put(AnalysisConfig.class, s -> new Gson().fromJson(s, AnalysisConfig.class));
}
static boolean processParamKey(List<Object> arguments, RoutingContext context, Method method, Parameter param) {
// param key
ParamKey paramKey = param.getAnnotation(ParamKey.class);
if (paramKey != null) {
String value = context.request().getParam(paramKey.value());
ASSERT.isTrue(!paramKey.mandatory() || value != null, ErrorCode.ILLEGAL_ARGUMENT,
() -> "Miss request parameter, key = " + paramKey.value());
arguments.add(value != null ? convert(method, param, context.request().getParam(paramKey.value())) : null);
return true;
}
return false;
}
static boolean processParamMap(List<Object> arguments, RoutingContext context, Method method, Parameter param) {
ParamMap paramMap = param.getAnnotation(ParamMap.class);
if (paramMap != null) {
Map<String, String> map = new HashMap<>();
String[] keys = paramMap.keys();
boolean[] mandatory = paramMap.mandatory();
for (int j = 0; j < keys.length; j++) {
String key = keys[j];
String value = context.request().getParam(key);
ASSERT.isTrue(!mandatory[j] || value != null, ErrorCode.ILLEGAL_ARGUMENT,
() -> "Miss request parameter, key = " + key);
if (value != null) {
map.put(key, value);
}
}
arguments.add(map);
return true;
}
return false;
}
static boolean processPagingRequest(List<Object> arguments, RoutingContext context, Method method,
Parameter param) {
if (param.getType() == PagingRequest.class) {
int page;
int pageSize;
try {
page = Integer.parseInt(context.request().getParam("page"));
pageSize = Integer.parseInt(context.request().getParam("pageSize"));
ASSERT.isTrue(page >= 1 && pageSize >= 1, ErrorCode.ILLEGAL_ARGUMENT,
"must greater than 1");
} catch (Exception e) {
throw new JifaException(ErrorCode.ILLEGAL_ARGUMENT, "Paging parameter(page or pageSize) is illegal, " +
e.getMessage());
}
arguments.add(new PagingRequest(page, pageSize));
return true;
}
return false;
}
static boolean processHttpServletRequest(List<Object> arguments, RoutingContext context, Method method,
Parameter param) {
if (param.getType().equals(HttpServerRequest.class)) {
arguments.add(context.request());
return true;
}
return false;
}
static boolean processHttpServletResponse(List<Object> arguments, RoutingContext context, Method method,
Parameter param) {
if (param.getType().equals(HttpServerResponse.class)) {
arguments.add(context.response());
return true;
}
return false;
}
static boolean processPromise(List<Object> arguments, RoutingContext context, Method method, Parameter param) {
if (param.getType().equals(Promise.class)) {
arguments.add(newPromise(context));
return true;
}
return false;
}
static boolean processRoutingContext(List<Object> arguments, RoutingContext context, Method method,
Parameter param) {
if (param.getType().equals(RoutingContext.class)) {
arguments.add(context);
return true;
}
return false;
}
private static Object convert(Method m, Parameter p, String value) {
Class<?> type = p.getType();
Function<String, ?> f;
if (type.isEnum()) {
f = s -> {
for (Object e : type.getEnumConstants()) {
if (((Enum) e).name().equalsIgnoreCase(value)) {
return e;
}
}
throw new JifaException(ErrorCode.ILLEGAL_ARGUMENT,
"Illegal parameter value, parameter = " + p + ", value = " + value);
};
} else {
f = converter.get(type);
}
ASSERT.notNull(f, () -> "Unsupported parameter type, method = " + m + ", parameter = " + p);
return f.apply(value);
}
private static <T> Promise<T> newPromise(io.vertx.ext.web.RoutingContext rc) {
Promise<T> promise = Promise.promise();
promise.future().onComplete(
event -> {
if (event.succeeded()) {
HTTPRespGuarder.ok(rc, event.result());
} else {
HTTPRespGuarder.fail(rc, event.cause());
}
}
);
return promise;
}
} | 6,884 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/FileRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import org.apache.logging.log4j.util.Strings;
import org.eclipse.jifa.common.ErrorCode;
import org.eclipse.jifa.common.JifaException;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.common.enums.ProgressState;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.util.HTTPRespGuarder;
import org.eclipse.jifa.common.util.PageViewBuilder;
import org.eclipse.jifa.common.vo.FileInfo;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.common.vo.TransferProgress;
import org.eclipse.jifa.common.vo.TransferringFile;
import org.eclipse.jifa.worker.WorkerGlobal;
import org.eclipse.jifa.worker.support.FileSupport;
import org.eclipse.jifa.worker.support.TransferListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import static org.eclipse.jifa.common.Constant.*;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.common.util.GsonHolder.GSON;
class FileRoute extends BaseRoute {
private static final Logger LOGGER = LoggerFactory.getLogger(FileRoute.class);
@RouteMeta(path = "/files")
void list(Promise<PageView<FileInfo>> promise, @ParamKey("type") FileType type, PagingRequest paging) {
List<FileInfo> info = FileSupport.info(type);
info.sort((i1, i2) -> Long.compare(i2.getCreationTime(), i1.getCreationTime()));
promise.complete(PageViewBuilder.build(info, paging));
}
@RouteMeta(path = "/file")
void file(Promise<FileInfo> promise, @ParamKey("type") FileType type, @ParamKey("name") String name) {
promise.complete(FileSupport.info(type, name));
}
@RouteMeta(path = "/file/delete", method = HttpMethod.POST)
void delete(Promise<Void> promise, @ParamKey("type") FileType type, @ParamKey("name") String name) {
FileSupport.delete(type, name);
promise.complete();
}
@RouteMeta(path = "/publicKey")
void publicKeys(Promise<String> promise) {
if (FileSupport.PUB_KEYS.size() > 0) {
promise.complete(FileSupport.PUB_KEYS.get(0));
} else {
promise.complete(EMPTY_STRING);
}
}
private String decorateFileName(String fileName) {
return System.currentTimeMillis() + "-" + fileName;
}
private String extractFileName(String path) {
return path.substring(path.lastIndexOf(File.separatorChar) + 1);
}
@RouteMeta(path = "/file/transferByURL", method = HttpMethod.POST)
void transferByURL(Promise<TransferringFile> promise, @ParamKey("type") FileType fileType,
@ParamKey("url") String url, @ParamKey(value = "fileName", mandatory = false) String fileName) {
String originalName;
try {
originalName = extractFileName(new URL(url).getPath());
} catch (MalformedURLException e) {
LOGGER.warn("invalid url: {}", url);
throw new JifaException(ErrorCode.ILLEGAL_ARGUMENT, e);
}
fileName = Strings.isNotBlank(fileName) ? fileName : decorateFileName(originalName);
TransferListener listener = FileSupport.createTransferListener(fileType, originalName, fileName);
FileSupport.transferByURL(url, fileType, fileName, listener, promise);
}
@RouteMeta(path = "/file/transferByOSS", method = HttpMethod.POST)
void transferByOSS(Promise<TransferringFile> promise, @ParamKey("type") FileType fileType,
@ParamKey("endpoint") String endpoint, @ParamKey("accessKeyId") String accessKeyId,
@ParamKey("accessKeySecret") String accessKeySecret, @ParamKey("bucketName") String bucketName,
@ParamKey("objectName") String objectName,
@ParamKey(value = "fileName", mandatory = false) String fileName) {
String originalName = extractFileName(objectName);
fileName = Strings.isNotBlank(fileName) ? fileName : decorateFileName(originalName);
TransferListener listener = FileSupport.createTransferListener(fileType, originalName, fileName);
FileSupport.transferByOSS(endpoint, accessKeyId, accessKeySecret, bucketName, objectName,
fileType, fileName, listener, promise);
}
@RouteMeta(path = "/file/transferByS3", method = HttpMethod.POST)
void transferByS3(Promise<TransferringFile> promise, @ParamKey("type") FileType fileType,
@ParamKey("endpoint") String endpoint, @ParamKey("accessKey") String accessKey,
@ParamKey("keySecret") String keySecret, @ParamKey("bucketName") String bucketName,
@ParamKey("objectName") String objectName,
@ParamKey(value = "fileName", mandatory = false) String fileName) {
String originalName = extractFileName(objectName);
fileName = Strings.isNotBlank(fileName) ? fileName : decorateFileName(originalName);
TransferListener listener = FileSupport.createTransferListener(fileType, originalName, fileName);
FileSupport.transferByS3(endpoint, accessKey, keySecret, bucketName, objectName,
fileType, fileName, listener, promise);
}
@RouteMeta(path = "/file/transferBySCP", method = HttpMethod.POST)
void transferBySCP(Promise<TransferringFile> promise, @ParamKey("type") FileType fileType,
@ParamKey("hostname") String hostname, @ParamKey("path") String path,
@ParamKey("user") String user, @ParamKey("usePublicKey") boolean usePublicKey,
@ParamKey(value = "password", mandatory = false) String password,
@ParamKey(value = "fileName", mandatory = false) String fileName) {
if (!usePublicKey) {
ASSERT.isTrue(password != null && password.length() > 0,
"Must provide password if you don't use public key");
}
String originalName = extractFileName(path);
fileName = Strings.isNotBlank(fileName) ? fileName : decorateFileName(extractFileName(path));
TransferListener listener = FileSupport.createTransferListener(fileType, originalName, fileName);
// do transfer
if (usePublicKey) {
FileSupport.transferBySCP(user, hostname, path, fileType, fileName, listener, promise);
} else {
FileSupport.transferBySCP(user, password, hostname, path, fileType, fileName, listener, promise);
}
}
@RouteMeta(path = "/file/transferByFileSystem", method = HttpMethod.POST)
void transferByFileSystem(Promise<TransferringFile> promise, @ParamKey("type") FileType fileType,
@ParamKey("path") String path, @ParamKey("move") boolean move) {
File src = new File(path);
ASSERT.isTrue(src.exists() && !src.isDirectory(), "Illegal path");
String originalName = extractFileName(path);
String fileName = decorateFileName(originalName);
promise.complete(new TransferringFile(fileName));
TransferListener listener = FileSupport.createTransferListener(fileType, originalName, fileName);
listener.setTotalSize(src.length());
listener.updateState(ProgressState.IN_PROGRESS);
if (move) {
WorkerGlobal.VERTX.fileSystem().moveBlocking(path, FileSupport.filePath(fileType, fileName));
} else {
WorkerGlobal.VERTX.fileSystem().copyBlocking(path, FileSupport.filePath(fileType, fileName));
}
listener.setTransferredSize(listener.getTotalSize());
listener.updateState(ProgressState.SUCCESS);
}
@RouteMeta(path = "/file/transferProgress")
void transferProgress(Promise<TransferProgress> promise, @ParamKey("type") FileType type,
@ParamKey("name") String name) {
TransferListener listener = FileSupport.getTransferListener(name);
if (listener != null) {
TransferProgress progress = new TransferProgress();
progress.setTotalSize(listener.getTotalSize());
progress.setTransferredSize(listener.getTransferredSize());
progress.setMessage(listener.getErrorMsg());
if (listener.getTotalSize() > 0) {
progress.setPercent((double) listener.getTransferredSize() / (double) listener.getTotalSize());
}
progress.setState(listener.getState());
if (progress.getState() == ProgressState.SUCCESS || progress.getState() == ProgressState.ERROR) {
FileSupport.removeTransferListener(name);
}
promise.complete(progress);
} else {
FileInfo info = FileSupport.infoOrNull(type, name);
if (info == null) {
TransferProgress progress = new TransferProgress();
progress.setState(ProgressState.ERROR);
promise.complete(progress);
return;
}
if (info.getTransferState() == FileTransferState.IN_PROGRESS
|| info.getTransferState() == FileTransferState.NOT_STARTED) {
LOGGER.warn("Illegal file {} state", name);
info.setTransferState(FileTransferState.ERROR);
FileSupport.save(info);
}
TransferProgress progress = new TransferProgress();
progress.setState(info.getTransferState().toProgressState());
if (progress.getState() == ProgressState.SUCCESS) {
progress.setPercent(1.0);
progress.setTotalSize(info.getSize());
progress.setTransferredSize(info.getSize());
}
promise.complete(progress);
}
}
@RouteMeta(path = "/file/sync", method = HttpMethod.POST)
void sync(Promise<Void> promise, @ParamKey("files") String files, @ParamKey("cleanStale") boolean cleanStale) {
promise.complete();
FileInfo[] fileInfos = GSON.fromJson(files, FileInfo[].class);
FileSupport.sync(fileInfos, cleanStale);
}
@RouteMeta(path = "/file/upload", method = HttpMethod.POST)
void upload(RoutingContext context, @ParamKey("type") FileType type,
@ParamKey(value = "fileName", mandatory = false) String fileName) {
FileUpload[] uploads = context.fileUploads().toArray(new FileUpload[0]);
try {
if (uploads.length > 0) {
// only process the first file
FileUpload file = uploads[0];
if (fileName == null || fileName.isBlank()) {
fileName = decorateFileName(file.fileName());
}
TransferListener listener = FileSupport.createTransferListener(type, file.fileName(), fileName);
listener.updateState(ProgressState.IN_PROGRESS);
try {
context.vertx().fileSystem()
.moveBlocking(file.uploadedFileName(), FileSupport.filePath(type, fileName));
FileSupport.updateTransferState(type, fileName, FileTransferState.SUCCESS);
} finally {
FileSupport.removeTransferListener(fileName);
}
}
HTTPRespGuarder.ok(context);
} finally {
// remove other files
for (int i = 1; i < uploads.length; i++) {
context.vertx().fileSystem().deleteBlocking(uploads[i].uploadedFileName());
}
}
}
@RouteMeta(path = "/file/download", contentType = {CONTENT_TYPE_FILE_FORM})
void download(RoutingContext context, @ParamKey("type") FileType fileType, @ParamKey("name") String name) {
File file = new File(FileSupport.filePath(fileType, name));
ASSERT.isTrue(file.exists(), "File doesn't exist!");
HttpServerResponse response = context.response();
response.putHeader(HEADER_CONTENT_DISPOSITION, "attachment;filename=" + file.getName());
response.sendFile(file.getAbsolutePath(), event -> {
if (!response.ended()) {
response.end();
}
});
}
@RouteMeta(path = "/file/getOrGenInfo", method = HttpMethod.POST)
void getOrGenInfo(Promise<FileInfo> promise, @ParamKey("fileType") FileType fileType,
@ParamKey("filename") String name) {
promise.complete(FileSupport.getOrGenInfo(fileType, name));
}
@RouteMeta(path = "/file/batchDelete", method = HttpMethod.POST)
void batchDelete(Promise<Void> promise, @ParamKey("files") String files) {
promise.complete();
FileInfo[] fileInfos = GSON.fromJson(files, FileInfo[].class);
FileSupport.delete(fileInfos);
}
}
| 6,885 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/HttpMethod.java | /********************************************************************************
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
public enum HttpMethod {
GET(io.vertx.core.http.HttpMethod.GET),
POST(io.vertx.core.http.HttpMethod.POST);
private final io.vertx.core.http.HttpMethod method;
HttpMethod(io.vertx.core.http.HttpMethod method) {
this.method = method;
}
public io.vertx.core.http.HttpMethod toVertx() {
return method;
}
}
| 6,886 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/ParamMap.java | /********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.PARAMETER;
@Retention(RetentionPolicy.RUNTIME)
@Target(PARAMETER)
public @interface ParamMap {
String[] keys();
boolean[] mandatory();
}
| 6,887 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/BaseRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
public abstract class BaseRoute {
}
| 6,888 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/RouteMeta.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RouteMeta {
HttpMethod method() default HttpMethod.GET;
String path();
String[] contentType() default {"application/json; charset=utf-8"};
}
| 6,889 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/threaddump/ThreadDumpBaseRoute.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.threaddump;
import org.eclipse.jifa.worker.route.BaseRoute;
import org.eclipse.jifa.worker.route.MappingPrefix;
import java.util.ArrayList;
import java.util.List;
@MappingPrefix("/thread-dump/:file")
public class ThreadDumpBaseRoute extends BaseRoute {
private static List<Class<? extends ThreadDumpBaseRoute>> ROUTES = new ArrayList<>();
static {
ROUTES.add(ThreadDumpRoute.class);
}
public static List<Class<? extends ThreadDumpBaseRoute>> routes() {
return ROUTES;
}
}
| 6,890 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/threaddump/ThreadDumpRoute.java | /********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.threaddump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.tda.ThreadDumpAnalyzer;
import org.eclipse.jifa.tda.enums.MonitorState;
import org.eclipse.jifa.tda.enums.ThreadType;
import org.eclipse.jifa.tda.vo.Content;
import org.eclipse.jifa.tda.vo.Overview;
import org.eclipse.jifa.tda.vo.VFrame;
import org.eclipse.jifa.tda.vo.VMonitor;
import org.eclipse.jifa.tda.vo.VThread;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
import org.eclipse.jifa.worker.support.Analyzer;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ThreadDumpRoute extends ThreadDumpBaseRoute {
@RouteMeta(path = "/overview")
public void overview(Promise<Overview> promise, @ParamKey("file") String file) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.overview());
}
@RouteMeta(path = "/callSiteTree")
public void callSiteTree(Promise<PageView<VFrame>> promise,
@ParamKey("file") String file,
@ParamKey("parentId") int parentId,
PagingRequest paging) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.callSiteTree(parentId, paging));
}
@RouteMeta(path = "/threads")
public void threads(Promise<PageView<VThread>> promise,
@ParamKey("file") String file,
@ParamKey(value = "name", mandatory = false) String name,
@ParamKey(value = "type", mandatory = false) ThreadType type,
PagingRequest paging) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.threads(name, type, paging));
}
@RouteMeta(path = "/threadsOfGroup")
public void threadsOfGroup(Promise<PageView<VThread>> promise,
@ParamKey("file") String file,
@ParamKey(value = "groupName") String groupName,
PagingRequest paging) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.threadsOfGroup(groupName, paging));
}
@RouteMeta(path = "/rawContentOfThread")
public void rawContentOfThread(Promise<List<String>> promise,
@ParamKey("file") String file,
@ParamKey("id") int id) throws IOException {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.rawContentOfThread(id));
}
@RouteMeta(path = "/content")
public void content(Promise<Content> promise,
@ParamKey("file") String file,
@ParamKey("lineNo") int lineNo,
@ParamKey("lineLimit") int lineLimit) throws IOException {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.content(lineNo, lineLimit));
}
@RouteMeta(path = "/monitors")
public void monitors(Promise<PageView<VMonitor>> promise, @ParamKey("file") String file, PagingRequest paging) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.monitors(paging));
}
@RouteMeta(path = "/threadCountsByMonitor")
public void threadCountsByMonitor(Promise<Map<MonitorState, Integer>> promise, @ParamKey("file") String file,
@ParamKey("id") int id) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.threadCountsByMonitor(id));
}
@RouteMeta(path = "/threadsByMonitor")
public void threadsByMonitor(Promise<PageView<VThread>> promise, @ParamKey("file") String file,
@ParamKey("id") int id, @ParamKey("state") MonitorState state,
PagingRequest paging) {
ThreadDumpAnalyzer analyzer = Analyzer.threadDumpAnalyzerOf(file);
promise.complete(analyzer.threadsByMonitor(id, state, paging));
}
}
| 6,891 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/HeapBaseRoute.java | /********************************************************************************
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import org.eclipse.jifa.hda.api.HeapDumpAnalyzer;
import org.eclipse.jifa.common.listener.ProgressListener;
import org.eclipse.jifa.worker.route.BaseRoute;
import org.eclipse.jifa.worker.route.MappingPrefix;
import org.eclipse.jifa.worker.support.Analyzer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@MappingPrefix("/heap-dump/:file")
public class HeapBaseRoute extends BaseRoute {
private static final List<Class<? extends HeapBaseRoute>> ROUTES = new ArrayList<>();
static {
ROUTES.add(OverviewRoute.class);
ROUTES.add(ObjectRoute.class);
ROUTES.add(InspectorRoute.class);
ROUTES.add(DominatorTreeRoute.class);
ROUTES.add(HistogramRoute.class);
ROUTES.add(UnreachableObjectsRoute.class);
ROUTES.add(ClassLoaderRoute.class);
ROUTES.add(DuplicatedClassesRoute.class);
ROUTES.add(SystemPropertyRoute.class);
ROUTES.add(ThreadRoute.class);
ROUTES.add(ObjectListRoute.class);
ROUTES.add(ClassReferenceRoute.class);
ROUTES.add(OQLRoute.class);
ROUTES.add(CalciteSQLRoute.class);
ROUTES.add(DirectByteBufferRoute.class);
ROUTES.add(GCRootRoute.class);
ROUTES.add(PathToGCRootsRoute.class);
ROUTES.add(CompareRoute.class);
ROUTES.add(LeakRoute.class);
ROUTES.add(MergePathToGCRootsRoute.class);
ROUTES.add(StringsRoute.class);
}
public static List<Class<? extends HeapBaseRoute>> routes() {
return ROUTES;
}
public static HeapDumpAnalyzer analyzerOf(String dump) {
return Analyzer.getOrBuildHeapDumpAnalyzer(dump, Collections.emptyMap(), ProgressListener.NoOpProgressListener);
}
}
| 6,892 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/PathToGCRootsRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
import static org.eclipse.jifa.common.util.Assertion.ASSERT;
import static org.eclipse.jifa.hda.api.Model.GCRootPath;
class PathToGCRootsRoute extends HeapBaseRoute {
@RouteMeta(path = "/pathToGCRoots")
void path(Promise<GCRootPath.Item> promise, @ParamKey("file") String file, @ParamKey("origin") int origin,
@ParamKey("skip") int skip, @ParamKey("count") int count) {
ASSERT.isTrue(origin >= 0).isTrue(skip >= 0).isTrue(count > 0);
promise.complete(analyzerOf(file).getPathToGCRoots(origin, skip, count));
}
}
| 6,893 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/CompareRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.enums.FileTransferState;
import org.eclipse.jifa.common.enums.FileType;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.util.PageViewBuilder;
import org.eclipse.jifa.common.vo.FileInfo;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
import org.eclipse.jifa.worker.support.FileSupport;
import java.io.File;
import java.util.stream.Collectors;
import static org.eclipse.jifa.common.enums.FileType.HEAP_DUMP;
import static org.eclipse.jifa.hda.api.Model.Comparison;
class CompareRoute extends HeapBaseRoute {
@RouteMeta(path = "/compare/files")
void files(Promise<PageView<FileInfo>> promise, @ParamKey("file") String source,
@ParamKey(value = "expected", mandatory = false) String expected, PagingRequest pagingRequest) {
promise.complete(PageViewBuilder.build(FileSupport.info(FileType.HEAP_DUMP).stream().filter(
fileInfo -> !fileInfo.getName().equals(source) && fileInfo.getTransferState() == FileTransferState.SUCCESS)
.sorted((i1, i2) -> Long.compare(i2.getCreationTime(),
i1.getCreationTime()))
.collect(Collectors.toList()), pagingRequest));
}
@RouteMeta(path = "/compare/summary")
void summary(Promise<Comparison.Summary> promise, @ParamKey("file") String target,
@ParamKey("baseline") String baseline) {
promise.complete(HeapBaseRoute.analyzerOf(target)
.getSummaryOfComparison(new File(FileSupport.filePath(HEAP_DUMP, baseline)).toPath()));
}
@RouteMeta(path = "/compare/records")
void record(Promise<PageView<Comparison.Item>> promise, @ParamKey("file") String target,
@ParamKey("baseline") String baseline, PagingRequest pagingRequest) {
promise.complete(
analyzerOf(target).getItemsOfComparison(new File(FileSupport.filePath(HEAP_DUMP, baseline)).toPath(),
pagingRequest.getPage(), pagingRequest.getPageSize()));
}
}
| 6,894 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/InspectorRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.hda.api.Model;
import org.eclipse.jifa.worker.route.MappingPrefix;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
@MappingPrefix("/inspector")
class InspectorRoute extends HeapBaseRoute {
@RouteMeta(path = "/addressToId")
void addressToId(Promise<Integer> promise, @ParamKey("file") String file, @ParamKey("objectAddress") long address) {
promise.complete(analyzerOf(file).mapAddressToId(address));
}
@RouteMeta(path = "/value")
void value(Promise<String> promise, @ParamKey("file") String file, @ParamKey("objectId") int objectId) {
promise.complete(analyzerOf(file).getObjectValue(objectId));
}
@RouteMeta(path = "/objectView")
void objectView(Promise<Model.InspectorView> promise, @ParamKey("file") String file,
@ParamKey("objectId") int objectId) {
promise.complete(analyzerOf(file).getInspectorView(objectId));
}
@RouteMeta(path = "/fields")
void fields(Promise<PageView<Model.FieldView>> promise, @ParamKey("file") String file,
@ParamKey("objectId") int objectId, PagingRequest pagingRequest) {
promise.complete(analyzerOf(file).getFields(objectId,
pagingRequest.getPage(), pagingRequest.getPageSize()));
}
@RouteMeta(path = "/staticFields")
void staticFields(Promise<PageView<Model.FieldView>> promise, @ParamKey("file") String file,
@ParamKey("objectId") int objectId, PagingRequest pagingRequest) {
promise.complete(analyzerOf(file).getStaticFields(objectId, pagingRequest.getPage(),
pagingRequest.getPageSize()));
}
}
| 6,895 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/StringsRoute.java | /********************************************************************************
* Copyright (c) 2022, Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.hda.api.Model;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
class StringsRoute extends HeapBaseRoute {
@RouteMeta(path = "/findStrings")
void strings(Promise<PageView<Model.TheString.Item>> promise, @ParamKey("file") String file,
@ParamKey("pattern") String pattern, PagingRequest pagingRequest) {
promise.complete(analyzerOf(file).getStrings(pattern, pagingRequest.getPage(), pagingRequest.getPageSize()));
}
}
| 6,896 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/CalciteSQLRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.hda.api.Model;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
class CalciteSQLRoute extends HeapBaseRoute {
@RouteMeta(path = "/sql")
void calciteSql(Promise<Model.CalciteSQLResult> promise, @ParamKey("file") String file,
@ParamKey("sql") String oql, @ParamKey(value = "sortBy", mandatory = false) String sortBy,
@ParamKey(value = "ascendingOrder", mandatory = false) boolean ascendingOrder,
PagingRequest pagingRequest) {
promise.complete(analyzerOf(file).getCalciteSQLResult(oql, sortBy, ascendingOrder,
pagingRequest.getPage(),
pagingRequest.getPageSize()));
}
}
| 6,897 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/ClassReferenceRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.hda.api.Model;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
class ClassReferenceRoute extends HeapBaseRoute {
@RouteMeta(path = "/classReference/inbounds/class")
void inboundsClassInfo(Promise<Model.ClassReferrer.Item> promise, @ParamKey("file") String file,
@ParamKey("objectId") int objectId) {
promise.complete(analyzerOf(file).getInboundClassOfClassReference(objectId));
}
@RouteMeta(path = "/classReference/outbounds/class")
void outboundsClassInfo(Promise<Model.ClassReferrer.Item> promise, @ParamKey("file") String file,
@ParamKey("objectId") int objectId) {
promise.complete(analyzerOf(file).getOutboundClassOfClassReference(objectId));
}
@RouteMeta(path = "/classReference/inbounds/children")
void inboundsChildren(Promise<PageView<Model.ClassReferrer.Item>> promise, @ParamKey("file") String file,
PagingRequest pagingRequest,
@ParamKey("objectIds") int[] objectIds) {
promise.complete(analyzerOf(file).getInboundsOfClassReference(objectIds,
pagingRequest.getPage(),
pagingRequest.getPageSize()));
}
@RouteMeta(path = "/classReference/outbounds/children")
void outboundsChildren(Promise<PageView<Model.ClassReferrer.Item>> promise, @ParamKey("file") String file,
PagingRequest pagingRequest,
@ParamKey("objectIds") int[] objectIds) {
promise.complete(analyzerOf(file).getOutboundsOfClassReference(objectIds,
pagingRequest.getPage(),
pagingRequest.getPageSize()));
}
}
| 6,898 |
0 | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route | Create_ds/eclipse-jifa/backend/worker/src/main/java/org/eclipse/jifa/worker/route/heapdump/DirectByteBufferRoute.java | /********************************************************************************
* Copyright (c) 2020, 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.jifa.worker.route.heapdump;
import io.vertx.core.Promise;
import org.eclipse.jifa.common.request.PagingRequest;
import org.eclipse.jifa.common.vo.PageView;
import org.eclipse.jifa.worker.route.ParamKey;
import org.eclipse.jifa.worker.route.RouteMeta;
import static org.eclipse.jifa.hda.api.Model.DirectByteBuffer;
class DirectByteBufferRoute extends HeapBaseRoute {
@RouteMeta(path = "/directByteBuffer/summary")
void summary(Promise<DirectByteBuffer.Summary> promise, @ParamKey("file") String file) {
promise.complete(analyzerOf(file).getSummaryOfDirectByteBuffers());
}
@RouteMeta(path = "/directByteBuffer/records")
void record(Promise<PageView<DirectByteBuffer.Item>> promise, @ParamKey("file") String file,
PagingRequest pagingRequest) {
promise.complete(analyzerOf(file).getDirectByteBuffers(pagingRequest.getPage(),
pagingRequest.getPageSize()));
}
}
| 6,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.