code improvements & delete task endpoint

This commit is contained in:
Marcel 2021-11-02 20:58:59 +01:00
parent 6752454838
commit 06172b34cd
29 changed files with 256 additions and 24 deletions

View File

@ -17,6 +17,10 @@ public class ApplyForTaskController {
this.applyForTaskUseCase = applyForTaskUseCase;
}
/**
* Checks if task is available for the requesting executor.
* @return a task or null if no task found
**/
@PostMapping(path = "/task/apply", consumes = {"application/json"})
public Task applyForTask(@RequestBody ExecutorInfo executorInfo) {
@ -24,6 +28,5 @@ public class ApplyForTaskController {
executorInfo.getExecutorURI());
return applyForTaskUseCase.applyForTask(command);
}
}

View File

@ -0,0 +1,35 @@
package ch.unisg.assignment.assignment.adapter.in.web;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ch.unisg.assignment.assignment.application.port.in.DeleteTaskCommand;
import ch.unisg.assignment.assignment.application.port.in.DeleteTaskUseCase;
import ch.unisg.assignment.assignment.domain.Task;
@RestController
public class DeleteTaskController {
private final DeleteTaskUseCase deleteTaskUseCase;
public DeleteTaskController(DeleteTaskUseCase deleteTaskUseCase) {
this.deleteTaskUseCase = deleteTaskUseCase;
}
/**
* Controller to delete a task
* @return 200 OK, 409 Conflict
**/
@DeleteMapping(path = "/task", consumes = {"application/task+json"})
public ResponseEntity<Void> applyForTask(@RequestBody Task task) {
DeleteTaskCommand command = new DeleteTaskCommand(task.getTaskID(), task.getTaskType());
if (deleteTaskUseCase.deleteTask(command)) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
}

View File

@ -18,7 +18,11 @@ public class NewTaskController {
this.newTaskUseCase = newTaskUseCase;
}
@PostMapping(path = "/task", consumes = {"application/json"})
/**
* Controller which handles the new task event from the tasklist
* @return 201 Create or 409 Conflict
**/
@PostMapping(path = "/task", consumes = {"application/task+json"})
public ResponseEntity<Void> newTaskController(@RequestBody Task task) {
NewTaskCommand command = new NewTaskCommand(task.getTaskID(), task.getTaskType());

View File

@ -19,6 +19,10 @@ public class TaskCompletedController {
this.taskCompletedUseCase = taskCompletedUseCase;
}
/**
* Controller which handles the task completed event from executors
* @return 200 OK
**/
@PostMapping(path = "/task/completed", consumes = {"application/json"})
public ResponseEntity<Void> addNewTaskTaskToTaskList(@RequestBody Task task) {

View File

@ -11,6 +11,10 @@ import ch.unisg.common.exception.InvalidExecutorURIException;
@ControllerAdvice
public class WebControllerExceptionHandler {
/**
* Handles error of type InvalidExecutorURIException
* @return 404 Bad Request
**/
@ExceptionHandler(InvalidExecutorURIException.class)
public ResponseEntity<ErrorResponse> handleException(InvalidExecutorURIException e){

View File

@ -24,6 +24,11 @@ public class GetAllExecutorInExecutorPoolByTypeAdapter implements GetAllExecutor
@Value("${executor-pool.url}")
private String server;
/**
* Requests all executor of the give type from the executor-pool and cheks if there is one
* avaialable of this type.
* @return Whether an executor exist or not
**/
@Override
public boolean doesExecutorTypeExist(ExecutorType type) {

View File

@ -27,6 +27,10 @@ public class PublishNewTaskEventAdapter implements NewTaskEventPort {
Logger logger = Logger.getLogger(PublishNewTaskEventAdapter.class.getName());
/**
* Informs executors about the availability of a new task.
* @return void
**/
@Override
public void publishNewTaskEvent(NewTaskEvent event) {

View File

@ -25,6 +25,10 @@ public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort {
Logger logger = Logger.getLogger(PublishTaskAssignedEventAdapter.class.getName());
/**
* Informs the task service about the assignment of the task.
* @return void
**/
@Override
public void publishTaskAssignedEvent(TaskAssignedEvent event) {

View File

@ -25,6 +25,10 @@ public class PublishTaskCompletedEventAdapter implements TaskCompletedEventPort
Logger logger = Logger.getLogger(PublishTaskCompletedEventAdapter.class.getName());
/**
* Informs the task service about the completion of the task.
* @return void
**/
@Override
public void publishTaskCompleted(TaskCompletedEvent event) {

View File

@ -0,0 +1,24 @@
package ch.unisg.assignment.assignment.application.port.in;
import javax.validation.constraints.NotNull;
import ch.unisg.assignment.assignment.domain.valueobject.ExecutorType;
import ch.unisg.common.validation.SelfValidating;
import lombok.EqualsAndHashCode;
import lombok.Value;
@Value
@EqualsAndHashCode(callSuper=false)
public class DeleteTaskCommand extends SelfValidating<ApplyForTaskCommand> {
@NotNull
private final String taskId;
@NotNull
private final ExecutorType taskType;
public DeleteTaskCommand(String taskId, ExecutorType taskType) {
this.taskId = taskId;
this.taskType = taskType;
this.validateSelf();
}
}

View File

@ -0,0 +1,5 @@
package ch.unisg.assignment.assignment.application.port.in;
public interface DeleteTaskUseCase {
boolean deleteTask(DeleteTaskCommand deleteTaskCommand);
}

View File

@ -3,6 +3,10 @@ package ch.unisg.assignment.assignment.application.port.out;
import ch.unisg.assignment.assignment.domain.valueobject.ExecutorType;
public interface GetAllExecutorInExecutorPoolByTypePort {
/**
* Checks if a executor with the given type exist in our executor pool
* @return boolean
**/
boolean doesExecutorTypeExist(ExecutorType type);
}

View File

@ -3,5 +3,9 @@ package ch.unisg.assignment.assignment.application.port.out;
import ch.unisg.assignment.assignment.domain.event.NewTaskEvent;
public interface NewTaskEventPort {
/**
* Publishes the new task event.
* @return void
**/
void publishNewTaskEvent(NewTaskEvent event);
}

View File

@ -3,5 +3,9 @@ package ch.unisg.assignment.assignment.application.port.out;
import ch.unisg.assignment.assignment.domain.event.TaskAssignedEvent;
public interface TaskAssignedEventPort {
/**
* Publishes the task assigned event.
* @return void
**/
void publishTaskAssignedEvent(TaskAssignedEvent taskAssignedEvent);
}

View File

@ -3,5 +3,9 @@ package ch.unisg.assignment.assignment.application.port.out;
import ch.unisg.assignment.assignment.domain.event.TaskCompletedEvent;
public interface TaskCompletedEventPort {
/**
* Publishes the task completed event.
* @return void
**/
void publishTaskCompleted(TaskCompletedEvent event);
}

View File

@ -19,6 +19,11 @@ public class ApplyForTaskService implements ApplyForTaskUseCase {
private final TaskAssignedEventPort taskAssignedEventPort;
/**
* Checks if a task is available and assignes it to the executor. If task got assigned a task
* assigned event gets published.
* @return assigned task or null if no task is found
**/
@Override
public Task applyForTask(ApplyForTaskCommand command) {
Task task = Roster.getInstance().assignTaskToExecutor(command.getTaskType(),

View File

@ -0,0 +1,27 @@
package ch.unisg.assignment.assignment.application.service;
import javax.transaction.Transactional;
import org.springframework.stereotype.Component;
import ch.unisg.assignment.assignment.application.port.in.DeleteTaskCommand;
import ch.unisg.assignment.assignment.application.port.in.DeleteTaskUseCase;
import ch.unisg.assignment.assignment.domain.Roster;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Component
@Transactional
public class DeleteTaskService implements DeleteTaskUseCase {
/**
* Check if task can get deleted
* @return if task can get deleted
**/
@Override
public boolean deleteTask(DeleteTaskCommand command) {
Roster roster = Roster.getInstance();
return roster.deleteTask(command.getTaskId(), command.getTaskType());
}
}

View File

@ -21,18 +21,22 @@ public class NewTaskService implements NewTaskUseCase {
private final NewTaskEventPort newTaskEventPort;
private final GetAllExecutorInExecutorPoolByTypePort getAllExecutorInExecutorPoolByTypePort;
/**
* Checks if we can execute the give task, if yes the task gets added to the task queue and return true.
* If the task can not be executed by an internal or auction house executor, the method return false.
* @return boolean
**/
@Override
public boolean addNewTaskToQueue(NewTaskCommand command) {
if (!getAllExecutorInExecutorPoolByTypePort.doesExecutorTypeExist(command.getTaskType())) {
return false;
}
// if (!getAllExecutorInExecutorPoolByTypePort.doesExecutorTypeExist(command.getTaskType())) {
// return false;
// }
Task task = new Task(command.getTaskID(), command.getTaskType());
Roster.getInstance().addTaskToQueue(task);
// TODO this event should be in the roster function xyz
NewTaskEvent newTaskEvent = new NewTaskEvent(task.getTaskType());
newTaskEventPort.publishNewTaskEvent(newTaskEvent);

View File

@ -18,6 +18,10 @@ public class TaskCompletedService implements TaskCompletedUseCase {
private final TaskCompletedEventPort taskCompletedEventPort;
/**
* Completes the task in the roster and publishes a task completed event.
* @return void
**/
@Override
public void taskCompleted(TaskCompletedCommand command) {

View File

@ -3,6 +3,8 @@ package ch.unisg.assignment.assignment.domain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import ch.unisg.assignment.assignment.domain.valueobject.ExecutorType;
import ch.unisg.common.valueobject.ExecutorURI;
@ -11,25 +13,41 @@ public class Roster {
private static final Roster roster = new Roster();
// Queues which hold all the tasks which need to be assigned | Will be replaced by message queue later
private HashMap<String, ArrayList<Task>> queues = new HashMap<>();
// Roster witch holds information about which executor is assigned to a task
private HashMap<String, RosterItem> rosterMap = new HashMap<>();
Logger logger = Logger.getLogger(Roster.class.getName());
public static Roster getInstance() {
return roster;
}
private Roster() {}
/**
* Adds a task to the task queue.
* @return void
* @see Task
**/
public void addTaskToQueue(Task task) {
if (queues.containsKey(task.getTaskType().getValue())) {
queues.get(task.getTaskType().getValue()).add(task);
} else {
queues.put(task.getTaskType().getValue(), new ArrayList<>(Arrays.asList(task)));
}
logger.log(Level.INFO, "Added task with id {0} to queue", task.getTaskID());
}
/**
* Checks if a task of this type is in a queue and if so assignes it to the executor.
* @return assigned task or null if no task is found
* @see Task
**/
public Task assignTaskToExecutor(ExecutorType taskType, ExecutorURI executorURI) {
// TODO I don't think we need this if
if (!queues.containsKey(taskType.getValue())) {
return null;
}
@ -45,8 +63,24 @@ public class Roster {
return task;
}
/**
* Removed a task from the roster after if got completed
* @return void
* @see Task
* @see Roster
**/
public void taskCompleted(String taskID) {
rosterMap.remove(taskID);
logger.log(Level.INFO, "Task {0} completed", taskID);
}
/**
* Deletes a task if it is still in the queue.
* @return Whether the task got deleted or not
**/
public boolean deleteTask(String taskID, ExecutorType taskType) {
logger.log(Level.INFO, "Try to delete task with id {0}", taskID);
return queues.get(taskType.getValue()).removeIf(task -> task.getTaskID().equalsIgnoreCase(taskID));
}
}

View File

@ -8,11 +8,16 @@ public class ExecutorURI {
private String value;
public ExecutorURI(String uri) throws InvalidExecutorURIException {
if (uri.equalsIgnoreCase("localhost") ||
uri.matches("^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)(\\.(?!$)|$)){4}$")) {
this.value = uri;
} else {
String ip = uri.split(":")[0];
int port = Integer.parseInt(uri.split(":")[1]);
// Check if valid ip4
if (!ip.equalsIgnoreCase("localhost") &&
!uri.matches("^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)(\\.(?!$)|$)){4}$")) {
throw new InvalidExecutorURIException();
// Check if valid port
} else if (port < 1024 || port > 65535) {
throw new InvalidExecutorURIException();
}
this.value = uri;
}
}

View File

@ -19,7 +19,11 @@ public class TaskAvailableController {
this.taskAvailableUseCase = taskAvailableUseCase;
}
@GetMapping(path = "/newtask/{taskType}")
/**
* Controller for notification about new events.
* @return 200 OK
**/
@GetMapping(path = "/newtask/{taskType}", consumes = { "application/json" })
public ResponseEntity<String> retrieveTaskFromTaskList(@PathVariable("taskType") String taskType) {
if (ExecutorType.contains(taskType.toUpperCase())) {

View File

@ -21,6 +21,10 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
Logger logger = Logger.getLogger(ExecutionFinishedEventAdapter.class.getName());
/**
* Publishes the execution finished event
* @return void
**/
@Override
public void publishExecutionFinishedEvent(ExecutionFinishedEvent event) {
@ -46,7 +50,7 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
System.out.println("Finish execution event sent with result:" + event.getResult());
logger.log(Level.INFO, "Finish execution event sent with result: {}", event.getResult());
}

View File

@ -28,6 +28,11 @@ public class GetAssignmentAdapter implements GetAssignmentPort {
Logger logger = Logger.getLogger(GetAssignmentAdapter.class.getName());
/**
* Requests a new task assignment
* @return the assigned task
* @see Task
**/
@Override
public Task getAssignment(ExecutorType executorType, ExecutorURI executorURI) {
@ -44,7 +49,9 @@ public class GetAssignmentAdapter implements GetAssignmentPort {
.build();
try {
logger.info("Sending getAssignment Request");
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
logger.log(Level.INFO, "getAssignment request result:\n {}", response.body());
if (response.body().equals("")) {
return null;
}

View File

@ -27,6 +27,10 @@ public class NotifyExecutorPoolAdapter implements NotifyExecutorPoolPort {
Logger logger = Logger.getLogger(NotifyExecutorPoolAdapter.class.getName());
/**
* Notifies the executor-pool about the startup of this executor
* @return if the notification was successful
**/
@Override
public boolean notifyExecutorPool(ExecutorURI executorURI, ExecutorType executorType) {

View File

@ -15,6 +15,6 @@ public class TaskAvailableService implements TaskAvailableUseCase {
@Override
public void newTaskAvailable(TaskAvailableCommand command) {
// Placeholder so spring can create a bean
// Placeholder so spring can create a bean, implementation of this function is inside the executors
}
}

View File

@ -1,5 +1,7 @@
package ch.unisg.executorbase.executor.domain;
import java.util.logging.Logger;
import ch.unisg.common.exception.InvalidExecutorURIException;
import ch.unisg.common.valueobject.ExecutorURI;
import ch.unisg.executorbase.executor.adapter.out.web.ExecutionFinishedEventAdapter;
@ -23,25 +25,28 @@ public abstract class ExecutorBase {
private ExecutorStatus status;
// TODO Violation of the Dependency Inversion Principle?, but we havn't really got a better solutions to send a http request / access a service from a domain model
// TODO I guess we can implement the execution as a service but there still is the problem with the startup request.
// TODO I guess we can somehow autowire this but I don't know why it's not working :D
private final NotifyExecutorPoolPort notifyExecutorPoolPort = new NotifyExecutorPoolAdapter();
private final NotifyExecutorPoolService notifyExecutorPoolService = new NotifyExecutorPoolService(notifyExecutorPoolPort);
private final GetAssignmentPort getAssignmentPort = new GetAssignmentAdapter();
private final ExecutionFinishedEventPort executionFinishedEventPort = new ExecutionFinishedEventAdapter();
public ExecutorBase(ExecutorType executorType) {
System.out.println("Starting Executor");
Logger logger = Logger.getLogger(ExecutorBase.class.getName());
protected ExecutorBase(ExecutorType executorType) {
logger.info("Starting Executor");
this.status = ExecutorStatus.STARTING_UP;
this.executorType = executorType;
// TODO set this automaticly
try {
this.executorURI = new ExecutorURI("localhost:8084");
} catch (InvalidExecutorURIException e) {
// Shutdown system if ip or port is not valid
// Shutdown system if the executorURI is not valid
System.exit(1);
}
this.executorType = executorType;
this.status = ExecutorStatus.STARTING_UP;
// Notify executor-pool about existence. If executor-pools response is successfull start with getting an assignment, else shut down executor.
if(!notifyExecutorPoolService.notifyExecutorPool(this.executorURI, this.executorType)) {
System.exit(0);
} else {
@ -50,6 +55,10 @@ public abstract class ExecutorBase {
}
}
/**
* Requests a new task from the task queue
* @return void
**/
public void getAssignment() {
Task newTask = getAssignmentPort.getAssignment(this.getExecutorType(), this.getExecutorURI());
if (newTask != null) {
@ -59,19 +68,28 @@ public abstract class ExecutorBase {
}
}
/**
* Start the execution of a task
* @return void
**/
private void executeTask(Task task) {
System.out.println("Starting execution");
logger.info("Starting execution");
this.status = ExecutorStatus.EXECUTING;
task.setResult(execution());
// TODO implement logic if execution was not successful
executionFinishedEventPort.publishExecutionFinishedEvent(
new ExecutionFinishedEvent(task.getTaskID(), task.getResult(), "SUCCESS"));
System.out.println("Finish execution");
logger.info("Finish execution");
getAssignment();
}
/**
* Implementation of the actual execution method of an executor
* @return the execution result
**/
protected abstract String execution();
}

View File

@ -1,7 +1,7 @@
package ch.unisg.executorbase.executor.domain;
public enum ExecutorStatus {
STARTING_UP,
EXECUTING,
IDLING,
STARTING_UP, // Executor is starting
EXECUTING, // Executor is currently executing a task
IDLING, // Executor has no tasks left and is waiting for new instructions
}

View File

@ -3,6 +3,10 @@ package ch.unisg.executorbase.executor.domain;
public enum ExecutorType {
ADDITION, ROBOT;
/**
* Checks if the give executor type exists.
* @return Wheter the given executor type exists
**/
public static boolean contains(String test) {
for (ExecutorType x : ExecutorType.values()) {