Created
January 30, 2018 16:35
-
-
Save gustavofranke/f1da5acda134d7f37c782373886d8773 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "com.spotify" % "docker-client" % "8.10.+" % Test | |
import com.spotify.docker.client.messages.{ContainerConfig, ContainerCreation, HostConfig, PortBinding} | |
import com.spotify.docker.client.{DefaultDockerClient, DockerClient} | |
import scala.collection.JavaConverters._ | |
import scala.util.Try | |
case class DockerServiceWrapper(image: String, hostPortForward: Int, env: List[String] = Nil) { | |
private lazy val docker: DockerClient = { | |
val dc = DefaultDockerClient.fromEnv().build() | |
dc.pull(image) | |
dc | |
} | |
private lazy val hostConfig: HostConfig = HostConfig.builder().portBindings( | |
Map( | |
hostPortForward.toString -> List(PortBinding.of("0.0.0.0", hostPortForward)).asJava | |
).asJava | |
).build() | |
private lazy val containerConfig: ContainerConfig = ContainerConfig.builder() | |
.exposedPorts(hostPortForward.toString) | |
.env(env.asJava) | |
.hostConfig(hostConfig) | |
.image(image) | |
.build() | |
private lazy val containerCreation: ContainerCreation = docker.createContainer(containerConfig) | |
private lazy val containerId: String = containerCreation.id() | |
/** | |
* Starts the kinesis container. | |
* | |
* @return Unit wrapped in Try. | |
* | |
*/ | |
def start: Try[Unit] = { | |
Try(docker.startContainer(containerId)) | |
} | |
/** | |
* Stops the kinesis container. | |
* | |
* @param secondsToWaitBeforeKill the number of seconds to wait before force killing the container. | |
* @return Unit wrapped in Try. | |
*/ | |
def stop(secondsToWaitBeforeKill: Int = 5): Try[Unit] = { | |
Try(docker.stopContainer(containerId, secondsToWaitBeforeKill)) | |
} | |
/** | |
* Removes the container from the host. Will stop the container first. | |
* | |
* @return Unit wrapped in Try. | |
*/ | |
def remove: Try[Unit] = { | |
Try{ stop(); docker.removeContainer(containerId) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment