Skip to content
Snippets Groups Projects
Commit fd8895f9 authored by Martin Weise's avatar Martin Weise
Browse files

Revert "Merge branch '16-refactoring-backend-endpoints' into 'master'"

This reverts merge request !9
parent bdb79ac5
No related branches found
No related tags found
4 merge requests!23Sprint results,!18Merge Conflicts,!15Sprint ended, merge into master,!10Revert bdb79ac5
Showing
with 145 additions and 806 deletions
package at.tuwien; package at.tuwien.application;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication @SpringBootApplication
@EnableJpaAuditing @ComponentScan(basePackages = "at.tuwien")
@EnableOpenApi @EnableSwagger2
@EnableJpaRepositories(basePackages = {"at.tuwien.repository"})
@EntityScan(basePackages = {"at.tuwien.entity"})
public class FdaContainerManagingApplication { public class FdaContainerManagingApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -3,7 +3,7 @@ package at.tuwien.config; ...@@ -3,7 +3,7 @@ package at.tuwien.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.PathSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact; import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
...@@ -12,28 +12,29 @@ import springfox.documentation.spring.web.plugins.Docket; ...@@ -12,28 +12,29 @@ import springfox.documentation.spring.web.plugins.Docket;
import java.util.Collections; import java.util.Collections;
@Configuration @Configuration
@EnableOpenApi
public class SwaggerConfig { public class SwaggerConfig {
@Bean @Bean
public Docket databaseApi() { public Docket swaggerConfiguration() {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("container-api")
.apiInfo(apiInfo())
.select() .select()
.paths(PathSelectors.ant("/api/**")) .paths(PathSelectors.ant("/api/*"))
.build(); .apis(RequestHandlerSelectors.basePackage("at.tuwien.controller"))
.build()
.apiInfo(apiInfo());
} }
private ApiInfo apiInfo() { private ApiInfo apiInfo() {
return new ApiInfo("FDA-Container-Managing API", return new ApiInfo("FDA-Container-Managing API",
"Service that can manage Docker containers", "Service API for container managing",
"1.0", "1.0",
null, null,
new Contact("Martin Weise", "https://informatics.tuwien.ac.at/people/martin-weise", "martin.weise@tuwien.ac.at"), new Contact("Gökhan Dasdemir", "http://tuwien.at", "goekhan.dasdemir@tuwien.ac.at"),
"API license", "API license",
null, null,
Collections.emptyList()); Collections.emptyList());
} }
} }
package at.tuwien.controller;
import at.tuwien.dto.CreateDatabaseContainerDTO;
import at.tuwien.model.DatabaseContainer;
import at.tuwien.service.ContainerService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@RestController
@RequestMapping("/api")
public class DatabaseContainerController {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseContainerController.class);
private ContainerService service;
@Autowired
public DatabaseContainerController(ContainerService service) {
this.service = service;
}
@PostMapping("/createDatabaseContainer")
@ApiOperation("creating a new database container")
@ApiResponses({@ApiResponse(code = 201, message = "database container created")})
public Response createDatabaseContainer(@RequestBody CreateDatabaseContainerDTO dto) {
LOGGER.debug("creating new database container");
String containerId = service.createDatabaseContainer(dto);
return Response
.status(Response.Status.CREATED)
.entity("Database container with containerID: " + containerId + "successfully created and started!")
.type(MediaType.APPLICATION_JSON)
.build();
}
@GetMapping("/getDatabaseContainerByContainerID")
public DatabaseContainer getDatabaseContainerByContainerID(@RequestParam String containerID) {
LOGGER.debug("getting database container by containerID");
return service.getDatabaseContainerByContainerID(containerID);
/* return Response
.status(Response.Status.FOUND)
.entity(connectionDataForDB)
.type(MediaType.APPLICATION_JSON)
.build();*/
}
@GetMapping("/getCreatedDatabaseContainers")
public List<DatabaseContainer> getCreatedDatabaseContainers() {
LOGGER.debug("getting created database containers");
return service.findAllDatabaseContainers();
}
public void startContainer(String containerID) {
//TODO
}
public void stopContainer(String containerID) {
//TODO
}
public void deleteDatabaseContainer(String containerID) {
//TODO
}
}
package at.tuwien.endpoints;
import at.tuwien.api.dto.container.ContainerChangeDto;
import at.tuwien.api.dto.container.ContainerBriefDto;
import at.tuwien.api.dto.container.ContainerDto;
import at.tuwien.api.dto.container.ContainerCreateRequestDto;
import at.tuwien.entity.Container;
import at.tuwien.exception.ContainerNotFoundException;
import at.tuwien.exception.DockerClientException;
import at.tuwien.exception.ImageNotFoundException;
import at.tuwien.mapper.ContainerMapper;
import at.tuwien.service.ContainerService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import static at.tuwien.api.dto.container.ContainerActionTypeDto.*;
@Log4j2
@RestController
@RequestMapping("/api")
public class ContainerEndpoint {
private final ContainerService containerService;
private final ContainerMapper containerMapper;
@Autowired
public ContainerEndpoint(ContainerService containerService, ContainerMapper containerMapper) {
this.containerMapper = containerMapper;
this.containerService = containerService;
}
@GetMapping("/container")
@ApiOperation(value = "List all containers", notes = "Lists the containers in the metadata database.")
@ApiResponses({
@ApiResponse(code = 200, message = "All containers are listed."),
@ApiResponse(code = 401, message = "Not authorized to list all containers."),
})
public ResponseEntity<List<ContainerBriefDto>> findAll() {
final List<Container> containers = containerService.getAll();
return ResponseEntity.ok()
.body(containers.stream()
.map(containerMapper::containerToDatabaseContainerBriefDto)
.collect(Collectors.toList()));
}
@PostMapping("/container")
@ApiOperation(value = "Creates a new container", notes = "Creates a new container whose image is registered in the metadata database too.")
@ApiResponses({
@ApiResponse(code = 201, message = "Successfully created a new container."),
@ApiResponse(code = 400, message = "Malformed payload."),
@ApiResponse(code = 402, message = "Not authorized to create a container."),
})
public ResponseEntity<ContainerDto> create(@Valid @RequestBody ContainerCreateRequestDto data)
throws ImageNotFoundException {
final Container container = containerService.create(data);
return ResponseEntity.status(HttpStatus.CREATED)
.body(containerMapper.containerToContainerDto(container));
}
@GetMapping("/container/{id}")
@ApiOperation(value = "Get all informations about a container", notes = "Since we follow the REST-principle, this method provides more information than the findAll method.")
@ApiResponses({
@ApiResponse(code = 200, message = "Get information about container."),
@ApiResponse(code = 402, message = "Not authorized to get information about a container."),
@ApiResponse(code = 404, message = "No container found with this id in metadata database."),
})
public ResponseEntity<ContainerDto> findById(@NotNull @RequestParam String id) throws ContainerNotFoundException {
final Container container = containerService.getById(id);
return ResponseEntity.ok()
.body(containerMapper.containerToContainerDto(container));
}
@PutMapping("/container/{id}")
@ApiOperation(value = "Change the state of a container", notes = "The new state can only be one of START/STOP/REMOVE.")
@ApiResponses({
@ApiResponse(code = 201, message = "Changed the state of a container."),
@ApiResponse(code = 400, message = "Malformed payload."),
@ApiResponse(code = 402, message = "Not authorized to modify a container."),
@ApiResponse(code = 404, message = "No container found with this id in metadata database."),
})
public ResponseEntity<?> modify(@NotNull @RequestParam String id, @Valid @RequestBody ContainerChangeDto changeDto) throws ContainerNotFoundException, DockerClientException {
if (changeDto.getAction().equals(START) || changeDto.getAction().equals(STOP) || changeDto.getAction().equals(REMOVE)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.build();
}
if (changeDto.getAction().equals(START)) {
containerService.start(id);
} else if (changeDto.getAction().equals(STOP)) {
containerService.stop(id);
} else if (changeDto.getAction().equals(REMOVE)) {
containerService.remove(id);
}
return ResponseEntity.status(HttpStatus.ACCEPTED)
.build();
}
@DeleteMapping("/container/{id}")
@ApiOperation(value = "Delete a container")
@ApiResponses({
@ApiResponse(code = 200, message = "Deleted the container."),
@ApiResponse(code = 402, message = "Not authorized to delete a container."),
@ApiResponse(code = 404, message = "No container found with this id in metadata database."),
})
public ResponseEntity delete(@NotNull @RequestParam String id) throws ContainerNotFoundException, DockerClientException {
containerService.remove(id);
return ResponseEntity.status(HttpStatus.OK)
.build();
}
}
server.port=9091
spring.application.name=fda-container-managing
spring.main.banner-mode=off
spring.cloud.loadbalancer.ribbon.enabled=false
logging.level.root=warn
logging.level.at.=info
logging.pattern.console=%d %highlight(%-5level): %msg%n
eureka.instance.hostname=fda-discovery-server
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:9090/eureka/
\ No newline at end of file
spring:
main.banner-mode: off
datasource:
url: jdbc:postgresql://fda-metadata-db:5432/fda
driver-class-name: org.postgresql.Driver
username: postgres
password: postgres
jpa:
show-sql: true
database-platform: org.hibernate.dialect.PostgreSQLDialect
hibernate:
ddl-auto: update
application:
name: fda-container-managing
cloud:
loadbalancer.ribbon.enabled: false
server.port: 9091
logging:
pattern.console: "%d %highlight(%-5level) %msg%n"
level:
root: warn
at.: info
eureka:
instance.hostname: fda-discovery-server
client.serviceUrl.defaultZone: http://${eureka.instance.hostname}:9090/eureka/
\ No newline at end of file
spring.application.name=fda-container-managing
server.port=9091
eureka.client.serviceUrl.defaultZone=http://localhost:9090/eureka/
\ No newline at end of file
spring:
main.banner-mode: off
datasource:
url: jdbc:postgresql://localhost:5432/fda
driver-class-name: org.postgresql.Driver
username: postgres
password: postgres
jpa:
show-sql: true
database-platform: org.hibernate.dialect.PostgreSQLDialect
hibernate:
ddl-auto: update
application:
name: fda-database-managing
cloud:
loadbalancer.ribbon.enabled: false
server.port: 9092
logging:
pattern.console: "%d %highlight(%-5level) %msg%n"
level:
root: warn
at.: debug
eureka:
instance.hostname: fda-discovery-server
client.serviceUrl.defaultZone: http://${eureka.instance.hostname}:9090/eureka/
\ No newline at end of file
package at.tuwien;
import at.tuwien.entity.Architecture;
import at.tuwien.entity.Container;
import at.tuwien.entity.ContainerImage;
import org.springframework.test.context.TestPropertySource;
import java.math.BigInteger;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
@TestPropertySource(locations = "classpath:application.properties")
public abstract class BaseIntegrationTest {
public final String IMAGE_1_REPOSITORY = "postgres";
public final String IMAGE_1_TAG = "13-alpine";
public final String IMAGE_1_HASH = "83b40f2726e5";
public final Integer IMAGE_1_PORT = 5432;
public final BigInteger IMAGE_1_SIZE = new BigInteger("160000000");
public final Instant IMAGE_1_BUILT = Instant.now().minus(40, HOURS);
public final List<String> IMAGE_1_ENV = Arrays.asList("POSTGRES_USER=postgres", "POSTGRES_PASSWORD=postgres");
public final String IMAGE_2_REPOSITORY = "redis";
public final String IMAGE_2_TAG = "latest";
public final String IMAGE_2_HASH = "f877e80bb9ef";
public final Integer IMAGE_2_PORT = 6379;
public final BigInteger IMAGE_2_SIZE = new BigInteger("105000000");
public final Instant IMAGE_2_BUILT = Instant.now().minus(9, DAYS);
public final List<String> IMAGE_2_ENV = Arrays.asList();
// public final ContainerImage IMAGE_1 = ContainerImage.builder()
// .repository(IMAGE_1_REPOSITORY)
// .tag(IMAGE_1_TAG)
// .hash(IMAGE_1_HASH)
// .size(IMAGE_1_SIZE)
// .built(IMAGE_1_BUILT)
// .environment(IMAGE_1_ENV)
// .defaultPort(IMAGE_1_PORT)
// .architecture(Architecture.LINUX_AMD64)
// .build();
//
// public final ContainerImage IMAGE_2 = ContainerImage.builder()
// .repository(IMAGE_2_REPOSITORY)
// .tag(IMAGE_2_TAG)
// .hash(IMAGE_2_HASH)
// .size(IMAGE_2_SIZE)
// .built(IMAGE_2_BUILT)
// .environment(IMAGE_2_ENV)
// .defaultPort(IMAGE_2_PORT)
// .architecture(Architecture.LINUX_AMD64)
// .build();
//
// public final String CONTAINER_1_ID = "deadbeef";
// public final ContainerImage CONTAINER_1_IMAGE = IMAGE_1;
// public final String CONTAINER_1_NAME = "u01";
// public final String CONTAINER_1_DATABASE = "univie";
// public final String CONTAINER_1_IP = "231.145.98.83";
// public final Instant CONTAINER_1_CREATED = Instant.now().minus(1, HOURS);
//
// public final String CONTAINER_2_ID = "0ff1ce";
// public final ContainerImage CONTAINER_2_IMAGE = IMAGE_2;
// public final String CONTAINER_2_NAME = "t01";
// public final String CONTAINER_2_DATABASE = "tuw";
// public final String CONTAINER_2_IP = "233.145.99.83";
// public final Instant CONTAINER_2_CREATED = Instant.now().minus(1, HOURS);
//
// public final Container CONTAINER_1 = Container.builder()
// .containerId(CONTAINER_1_ID)
// .name(CONTAINER_1_NAME)
// .ipAddress(CONTAINER_1_IP)
// .image(CONTAINER_1_IMAGE)
// .containerId(CONTAINER_1_ID)
// .containerCreated(CONTAINER_1_CREATED)
// .build();
//
// public final Container CONTAINER_2 = Container.builder()
// .containerId(CONTAINER_2_ID)
// .name(CONTAINER_2_NAME)
// .ipAddress(CONTAINER_2_IP)
// .image(CONTAINER_2_IMAGE)
// .containerId(CONTAINER_2_ID)
// .containerCreated(CONTAINER_2_CREATED)
// .build();
}
package at.tuwien.endpoint;
import at.tuwien.BaseIntegrationTest;
import at.tuwien.repository.ContainerRepository;
import at.tuwien.repository.ImageRepository;
import at.tuwien.service.ContainerService;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class EndpointTest extends BaseIntegrationTest {
@MockBean
private ImageRepository imageRepository;
@MockBean
private ContainerRepository containerRepository;
@MockBean
private ContainerService containerService;
// @Test
// public void listAllDatabases_succeeds() {
// when(containerService.getAll())
// .thenReturn(List.of(CONTAINER_1, CONTAINER_2));
//
// final List<DatabaseContainer> response = containerService.getAll();
//
// assertEquals(2, response.size());
// assertEquals(CONTAINER_1_ID, response.get(0).getContainerId());
// assertEquals(CONTAINER_1_DATABASE, response.get(0).getDatabaseName());
// assertEquals(CONTAINER_1_NAME, response.get(0).getName());
// assertEquals(CONTAINER_1_IP, response.get(0).getIpAddress());
// assertEquals(CONTAINER_2_ID, response.get(1).getContainerId());
// assertEquals(CONTAINER_2_DATABASE, response.get(1).getDatabaseName());
// assertEquals(CONTAINER_2_NAME, response.get(1).getName());
// assertEquals(CONTAINER_2_IP, response.get(1).getIpAddress());
// }
//
// @Test
// public void create_succeeds() throws ImageNotFoundException {
// final ContainerCreateRequestDto request = ContainerCreateRequestDto.builder()
// .containerName(CONTAINER_1_NAME)
// .image(CONTAINER_1_IMAGE.dockerImageName())
// .databaseName(CONTAINER_1_DATABASE)
// .build();
// when(containerService.create(request))
// .thenReturn(CONTAINER_1);
//
// final DatabaseContainer response = containerService.create(request);
//
// assertNotNull(response);
// assertEquals(response, CONTAINER_1);
// assertEquals(response.getImage(), CONTAINER_1_IMAGE);
// }
//
// @Test
// public void create_fails() throws ImageNotFoundException {
// final DatabaseContainerCreateRequestDto request = DatabaseContainerCreateRequestDto.builder()
// .containerName(CONTAINER_1_NAME)
// .image(CONTAINER_1_IMAGE.dockerImageName())
// .databaseName(CONTAINER_1_DATABASE)
// .build();
// when(containerService.create(request))
// .thenReturn(CONTAINER_1);
// when(imageRepository.findByImage(IMAGE_1_REPOSITORY, IMAGE_1_TAG))
// .thenReturn(null);
// }
//
// @Test
// public void findById_succeeds() {
// //
// }
//
// @Test
// public void findById_fails() {
// //
// }
//
// @Test
// public void change_succeeds() {
// //
// }
//
// @Test
// public void change_fails() {
// //
// }
//
// @Test
// public void delete_succeeds() {
// //
// }
//
// @Test
// public void delete_fails() {
// //
// }
}
package at.tuwien.mapper;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.NetworkSettings;
import lombok.SneakyThrows;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Field;
import java.util.Map;
public abstract class BaseMappingTest {
@Configuration
@ComponentScan(basePackages = {"at.tuwien"})
public static class BaseMappingContext {
}
final String CONTAINER_ID = "deadbeef";
final String CONTAINER_NETWORK_IP = "154.234.88.15";
@SneakyThrows
final InspectContainerResponse mockInspectResponse() {
final InspectContainerResponse responseC = new InspectContainerResponse();
final Object response = responseC.getClass().getConstructor().newInstance();
final Field idField = responseC.getClass().getDeclaredField("id");
idField.setAccessible(true);
idField.set(response, CONTAINER_ID);
final Field networkSettingsField = responseC.getClass().getDeclaredField("networkSettings");
networkSettingsField.setAccessible(true);
// define the network and address
final ContainerNetwork networkC = new ContainerNetwork();
final Object network = networkC.getClass().getConstructor().newInstance();
final Field ipField = networkC.getClass().getDeclaredField("ipAddress");
ipField.setAccessible(true);
ipField.set(network, CONTAINER_NETWORK_IP);
final Map<String, ContainerNetwork> map = Map.of("bridge", (ContainerNetwork) network);
// add to network settings
final NetworkSettings settingsC = new NetworkSettings();
final Object settings = settingsC.getClass().getConstructor().newInstance();
final Field networksField = settingsC.getClass().getDeclaredField("networks");
networksField.setAccessible(true);
networksField.set(settings, map);
networkSettingsField.set(response, settings);
return (InspectContainerResponse) response;
}
}
package at.tuwien.mapper;
import com.github.dockerjava.api.command.InspectContainerResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class DatabaseContainerMappingTest extends BaseMappingTest {
// @Test
// public void inspectContainerResponseToDatabaseContainerMappingTest_succeeds() {
// final InspectContainerResponse response = mockInspectResponse();
//
// assertNotNull(response, "response must not be null");
// assertEquals(CONTAINER_ID, response.getId());
// assertNotNull(response.getNetworkSettings(), "networkSettings must not be null");
// assertNotNull(response.getNetworkSettings().getNetworks(), "networkSettings.networks must not be null");
// assertNotNull(response.getNetworkSettings().getNetworks().get("bridge"), "networkSettings.networks['bridge'] must not be null");
// assertNotNull(response.getNetworkSettings().getNetworks().get("bridge").getIpAddress(), "networkSettings.networks['bridge'].ipAddress must not be null");
// assertEquals(CONTAINER_NETWORK_IP, response.getNetworkSettings().getNetworks().get("bridge").getIpAddress());
// }
}
package at.tuwien.service;
import at.tuwien.BaseIntegrationTest;
import at.tuwien.api.dto.container.ContainerCreateRequestDto;
import at.tuwien.exception.ContainerNotFoundException;
import at.tuwien.exception.ImageNotFoundException;
import at.tuwien.repository.ContainerRepository;
import at.tuwien.repository.ImageRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.mockito.Mockito.when;
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class DockerIntegrationTest extends BaseIntegrationTest {
@MockBean
private ContainerRepository containerRepository;
@MockBean
private ImageRepository imageRepository;
@MockBean
private ContainerService containerService;
// @Test
// public void create_noImage_fails() {
// final ContainerCreateRequestDto containerDto = ContainerCreateRequestDto.builder().build();
//
// Assertions.assertThrows(ImageNotFoundException.class, () -> containerService.create(containerDto));
// }
//
// @Test
// public void create_imageNotFound_fails() {
// final ContainerCreateRequestDto containerDto = ContainerCreateRequestDto.builder().build();
// containerDto.setImage("postgres:latest");
//
// Assertions.assertThrows(ImageNotFoundException.class, () -> containerService.create(containerDto));
// }
//
// @Test
// public void stop_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.stop(CONTAINER_1_ID));
// }
//
// @Test
// public void remove_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.remove(CONTAINER_1_ID));
// }
//
// @Test
// public void start_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.start(CONTAINER_1_ID));
// }
}
package at.tuwien.service;
import at.tuwien.BaseIntegrationTest;
import at.tuwien.repository.ContainerRepository;
import at.tuwien.repository.ImageRepository;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.mockito.Mockito.mock;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ServiceTest extends BaseIntegrationTest {
@MockBean
private ContainerRepository containerRepository;
@MockBean
private ImageRepository imageRepository;
@Autowired
private ContainerService containerService;
// @Test
// public void getAllTest_succeeds() {
// when(containerRepository.findAll())
// .thenReturn(List.of(CONTAINER_1, CONTAINER_2));
//
// final List<DatabaseContainer> response = containerService.getAll();
// Assertions.assertEquals(2, response.size());
// Assertions.assertEquals(CONTAINER_1, response.get(0));
// Assertions.assertEquals(CONTAINER_2, response.get(1));
// }
//
// @Test
// public void getById_succeeds() throws ContainerNotFoundException {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
//
// final DatabaseContainer response = containerService.getById(CONTAINER_1_ID);
// Assertions.assertEquals(CONTAINER_1, response);
// }
//
// @Test
// public void getById_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.getById(CONTAINER_1_ID));
// }
//
// @Test
// public void create_noImage_fails() {
// final ContainerCreateRequestDto containerDto = ContainerCreateRequestDto.builder().build();
//
// Assertions.assertThrows(ImageNotFoundException.class, () -> containerService.create(containerDto));
// }
//
// @Test
// public void create_imageNotFound_fails() {
// final ContainerCreateRequestDto containerDto = ContainerCreateRequestDto.builder().build();
// containerDto.setImage("postgres:latest");
//
// Assertions.assertThrows(ImageNotFoundException.class, () -> containerService.create(containerDto));
// }
//
// @Test
// public void stop_dockerClient_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.stopContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotFoundException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.stop(CONTAINER_1_ID));
// }
//
// @Test
// public void stop_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.stop(CONTAINER_1_ID));
// }
//
// @Test
// public void stop_dockerClient2_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.stopContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotModifiedException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.stop(CONTAINER_1_ID));
// }
//
// @Test
// public void remove_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.remove(CONTAINER_1_ID));
// }
//
// @Test
// public void remove_dockerClient_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.removeContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotFoundException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.remove(CONTAINER_1_ID));
// }
//
// @Test
// public void remove_dockerClient2_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.removeContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotModifiedException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.remove(CONTAINER_1_ID));
// }
//
// @Test
// public void start_notFound_fails() {
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(null);
//
// Assertions.assertThrows(ContainerNotFoundException.class, () -> containerService.start(CONTAINER_1_ID));
// }
//
// @Test
// public void start_dockerClient_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.removeContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotFoundException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.start(CONTAINER_1_ID));
// }
//
// @Test
// public void start_dockerClient2_fails() {
// final DockerClient dockerClient = mock(DockerClient.class);
// when(containerRepository.findByContainerId(CONTAINER_1_ID))
// .thenReturn(CONTAINER_1);
// when(dockerClient.removeContainerCmd(CONTAINER_1_ID))
// .thenThrow(NotModifiedException.class);
//
// Assertions.assertThrows(DockerClientException.class, () -> containerService.start(CONTAINER_1_ID));
// }
}
# disable discovery
spring.cloud.discovery.enabled = false
# disable cloud config and config discovery
spring.cloud.config.discovery.enabled = false
spring.cloud.config.enabled = false
\ No newline at end of file
...@@ -2,54 +2,27 @@ ...@@ -2,54 +2,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent> <parent>
<artifactId>fda-container-managing-service</artifactId> <artifactId>fda-container-managing-service</artifactId>
<groupId>at.tuwien</groupId> <groupId>at.tuwien</groupId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>services</artifactId> <artifactId>services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fda-container-managing-service-services</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>at.tuwien</groupId> <groupId>at.tuwien</groupId>
<artifactId>api</artifactId> <artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>${project.version}</version>
</dependency> </dependency>
</dependencies>
<build> <dependency>
<plugins> <groupId>com.github.docker-java</groupId>
<plugin> <artifactId>docker-java</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>3.2.1</version>
<artifactId>maven-compiler-plugin</artifactId> </dependency>
<configuration> </dependencies>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<!-- keep this order https://stackoverflow.com/questions/47676369/mapstruct-and-lombok-not-working-together#answer-65021876 -->
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>
\ No newline at end of file
package at.tuwien.config; package at.tuwien.config;
import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.RestartPolicy;
import com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig; import org.apache.commons.lang.SystemUtils;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
public class DockerConfig { public class ContainerSpringConfig {
@Bean private final String localDockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375"
public HostConfig hostConfig() { : "unix:///var/run/docker.sock";
return HostConfig.newHostConfig()
.withRestartPolicy(RestartPolicy.alwaysRestart()); private final DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
} .withDockerHost(localDockerHost).build();
@Bean @Bean
public DockerClient dockerClientConfiguration(){ public DockerClient dockerClientConfiguration(){
final DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() return DockerClientBuilder.getInstance(config).build();
.withDockerHost("unix:///var/run/docker.sock")
.build();
return DockerClientBuilder.getInstance(config)
.build();
} }
} }
package at.tuwien.entity;
public enum Architecture {
LINUX_AMD64, LINUX_ARM64, LINUX_RISCV64, LINUX_PPC64LE, LINUX_S390X, LINUX_386, LINUX_ARM_V7, LINUX_ARM_V8
}
package at.tuwien.entity;
import lombok.*;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.Instant;
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@Id
@EqualsAndHashCode.Include
@ToString.Include
@GeneratedValue(generator = "sequence-per-entity")
@GenericGenerator(
name = "sequence-per-entity",
strategy = "enhanced-sequence",
parameters = @Parameter(name = "prefer_sequence_per_entity", value = "true")
)
private Long id;
@Column(nullable = false, updatable = false)
@CreatedDate
private Instant created;
@Column
@LastModifiedDate
private Instant lastModified;
}
\ No newline at end of file
package at.tuwien.entity;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import java.time.Instant;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@ToString(callSuper = true, onlyExplicitlyIncluded = true)
public class Container extends Auditable {
@Column(nullable = false)
private String containerId;
@Column(nullable = false)
private Instant containerCreated;
@Column(nullable = false)
private String name;
@OneToOne(optional = false)
private ContainerImage image;
@Transient
private String status;
@Column
private String ipAddress;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment