1 package dst.ass3.elastic.impl;
3 import com.github.dockerjava.api.DockerClient;
4 import com.github.dockerjava.api.command.CreateContainerResponse;
5 import com.github.dockerjava.api.command.InspectContainerResponse;
6 import com.github.dockerjava.api.exception.NotFoundException;
7 import com.github.dockerjava.api.model.Container;
8 import com.github.dockerjava.core.DefaultDockerClientConfig;
9 import com.github.dockerjava.core.DockerClientBuilder;
10 import com.github.dockerjava.core.DockerClientConfig;
11 import dst.ass3.elastic.ContainerException;
12 import dst.ass3.elastic.ContainerInfo;
13 import dst.ass3.elastic.ContainerNotFoundException;
14 import dst.ass3.elastic.IContainerService;
15 import dst.ass3.messaging.RequestType;
17 import java.util.ArrayList;
18 import java.util.List;
20 public class ContainerService implements IContainerService {
21 final static DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost("tcp://192.168.99.99:2375").build();
24 public List<ContainerInfo> listContainers() throws ContainerException {
25 DockerClient docker = DockerClientBuilder.getInstance(config).build();
27 ArrayList<ContainerInfo> ret = new ArrayList<>();
28 for (Container c : docker.listContainersCmd().exec()) {
29 ContainerInfo ci = new ContainerInfo();
30 ci.setContainerId(c.getId());
31 ci.setImage(c.getImage());
33 ci.setWorkerType(RequestType.valueOf((c.getCommand().split(" "))[2].toUpperCase()));
40 public void stopContainer(String containerId) throws ContainerException {
41 DockerClient docker = DockerClientBuilder.getInstance(config).build();
43 docker.stopContainerCmd(containerId).exec();
44 docker.removeContainerCmd(containerId).exec();
45 } catch (NotFoundException e) {
46 throw new ContainerNotFoundException(e);
51 public ContainerInfo startWorker(RequestType type) throws ContainerException {
52 DockerClient docker = DockerClientBuilder.getInstance(config).build();
54 CreateContainerResponse container = docker.createContainerCmd("dst/ass3-worker").withCmd(type.toString().toLowerCase()).exec();
55 docker.startContainerCmd(container.getId()).exec();
57 ContainerInfo ci = new ContainerInfo();
58 ci.setWorkerType(type);
59 ci.setImage("dst/ass3-worker");
60 ci.setContainerId(container.getId());
62 InspectContainerResponse inspect = docker.inspectContainerCmd(container.getId()).exec();
65 ci.setRunning(inspect.getState().getRunning());
66 } catch (NullPointerException e) {