All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.digitalforge.dockermanager.DockerManager Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package org.digitalforge.dockermanager;

import java.io.Closeable;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.transport.DockerHttpClient;
import com.github.dockerjava.zerodep.ZerodepDockerHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DockerManager {

    private static final Logger log = LoggerFactory.getLogger(DockerManager.class);

    private final DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
    private final DockerHttpClient httpClient = new ZerodepDockerHttpClient.Builder().dockerHost(config.getDockerHost()).build();
    private final DockerClient client = DockerClientImpl.getInstance(config, httpClient);

    public void startContainer(String imageName, DockerContainerConfig dockerContainerConfig) throws Throwable {

        if(!imageExists(client,imageName)) {
            log.info("Pulling " + imageName + " ...");
            CountDownLatch pullLatch = new CountDownLatch(1);
            client.pullImageCmd(imageName).exec(new ResultCallback() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(PullResponseItem object) {
                    //System.out.print(object.getStatus() + "\t" + object.getId());
                    //if((object.getProgressDetail() != null) && (object.getProgressDetail().getTotal() != null)) {
                    //    System.out.println(" " + ((object.getProgressDetail().getCurrent() / (float)object.getProgressDetail().getTotal()) * 100) + "%" );
                    //}
                }

                @Override
                public void onError(Throwable throwable) {
                    log.error("Error pulling Docker image:", throwable);
                    pullLatch.countDown();
                }

                @Override
                public void onComplete() {
                    log.info("    done");
                    pullLatch.countDown();
                }

                @Override
                public void close() {

                }
            });
            pullLatch.await();
        }

        String containerId = findContainerIdByName(client, dockerContainerConfig.getName());
        if(containerId == null) {
            log.info("Creating container " + dockerContainerConfig.getName() + " ...");

            CreateContainerCmd cmd = client.createContainerCmd(imageName);

            cmd.withName(dockerContainerConfig.getName());

            if(dockerContainerConfig.getEnvironment() != null) {
                cmd.withEnv(dockerContainerConfig.getEnvironment());
            }

            if(dockerContainerConfig.getPortBindings() != null) {
                cmd.withHostConfig(new HostConfig().withPortBindings(dockerContainerConfig.getPortBindings().stream().map(b -> PortBinding.parse(b)).collect(Collectors.toList())));
            }

            containerId = cmd.exec().getId();

            log.info("    done");

        }

        if(!client.inspectContainerCmd(containerId).exec().getState().getRunning()) {
            log.info("Starting container " + dockerContainerConfig.getName() + " ...");
            client.startContainerCmd(containerId).exec();
            log.info("    done");
        }

    }

    private String findContainerIdByName(DockerClient client, String containerName) {

        List containers = client.listContainersCmd()
            .withNameFilter(List.of(containerName))
            .withShowAll(true)
            .exec();

        if(containers.isEmpty()) {
            return null;
        }

        return containers.get(0).getId();

    }

    private boolean imageExists(DockerClient client, String imageId) {

        try {
            client.inspectImageCmd(imageId).exec();
            return true;
        } catch(NotFoundException ex) {
            return false;
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy