-
Notifications
You must be signed in to change notification settings - Fork 229
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #474 from TheHive-Project/fix/DL-717/cortex-docker…
…-client [DL-717] Fix: cortex docker client
- Loading branch information
Showing
6 changed files
with
261 additions
and
98 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
package org.thp.cortex.util.docker | ||
|
||
import com.github.dockerjava.api.model._ | ||
import com.github.dockerjava.core.{DefaultDockerClientConfig, DockerClientConfig, DockerClientImpl} | ||
import com.github.dockerjava.transport.DockerHttpClient | ||
import com.github.dockerjava.zerodep.ZerodepDockerHttpClient | ||
import play.api.{Configuration, Logger} | ||
|
||
import java.nio.file.{Files, Path} | ||
import java.time.Duration | ||
import java.util.concurrent.{Executors, TimeUnit} | ||
import scala.concurrent.blocking | ||
import scala.concurrent.duration.FiniteDuration | ||
import scala.jdk.CollectionConverters._ | ||
import scala.util.Try | ||
|
||
class DockerClient(config: Configuration) { | ||
private lazy val logger: Logger = Logger(getClass.getName) | ||
private lazy val (dockerConf, httpClient) = getHttpClient | ||
private lazy val underlyingClient = DockerClientImpl.getInstance(dockerConf, httpClient) | ||
|
||
def execute(containerId: String): Try[Int] = | ||
Try { | ||
val startContainerCmd = underlyingClient.startContainerCmd(containerId) | ||
startContainerCmd.exec() | ||
val waitResult = underlyingClient | ||
.waitContainerCmd(containerId) | ||
.start() | ||
.awaitStatusCode() | ||
logger.info(s"container $containerId started and awaited with code: $waitResult") | ||
|
||
waitResult | ||
} | ||
|
||
def prepare(image: String, jobDirectory: Path, jobBaseDirectory: Path, dockerJobBaseDirectory: Path, timeout: FiniteDuration): Try[String] = Try { | ||
logger.info(s"image $image pull result: ${pullImage(image)}") | ||
val containerCmd = underlyingClient | ||
.createContainerCmd(image) | ||
.withHostConfig(configure(jobDirectory, jobBaseDirectory, dockerJobBaseDirectory)) | ||
if (Files.exists(jobDirectory.resolve("input").resolve("cacerts"))) | ||
containerCmd.withEnv(s"REQUESTS_CA_BUNDLE=/job/input/cacerts") | ||
val containerResponse = containerCmd.exec() | ||
logger.info( | ||
s"about to start container ${containerResponse.getId}\n" + | ||
s" timeout: ${timeout.toString}\n" + | ||
s" image : $image\n" + | ||
s" volumes : ${jobDirectory.toAbsolutePath}" | ||
) | ||
if (containerResponse.getWarnings.nonEmpty) logger.warn(s"${containerResponse.getWarnings.mkString(", ")}") | ||
scheduleContainerTimeout(containerResponse.getId, timeout) | ||
|
||
containerResponse.getId | ||
} | ||
|
||
private def configure(jobDirectory: Path, jobBaseDirectory: Path, dockerJobBaseDirectory: Path): HostConfig = { | ||
val hostConfigMut = HostConfig | ||
.newHostConfig() | ||
.withBinds( | ||
Seq( | ||
new Bind( | ||
dockerJobBaseDirectory.resolve(jobBaseDirectory.relativize(jobDirectory)).toAbsolutePath.toString, | ||
new Volume(s"/job"), | ||
AccessMode.rw | ||
) | ||
): _* | ||
) | ||
|
||
config.getOptional[Seq[String]]("docker.container.capAdd").map(_.map(Capability.valueOf)).foreach(hostConfigMut.withCapAdd(_: _*)) | ||
config.getOptional[Seq[String]]("docker.container.capDrop").map(_.map(Capability.valueOf)).foreach(hostConfigMut.withCapDrop(_: _*)) | ||
config.getOptional[String]("docker.container.cgroupParent").foreach(hostConfigMut.withCgroupParent) | ||
config.getOptional[Long]("docker.container.cpuPeriod").foreach(hostConfigMut.withCpuPeriod(_)) | ||
config.getOptional[Long]("docker.container.cpuQuota").foreach(hostConfigMut.withCpuQuota(_)) | ||
config.getOptional[Seq[String]]("docker.container.dns").map(_.asJava).foreach(hostConfigMut.withDns) | ||
config.getOptional[Seq[String]]("docker.container.dnsSearch").map(_.asJava).foreach(hostConfigMut.withDnsSearch) | ||
config.getOptional[Seq[String]]("docker.container.extraHosts").foreach(l => hostConfigMut.withExtraHosts(l: _*)) | ||
config.getOptional[Long]("docker.container.kernelMemory").foreach(hostConfigMut.withKernelMemory(_)) | ||
config.getOptional[Long]("docker.container.memoryReservation").foreach(hostConfigMut.withMemoryReservation(_)) | ||
config.getOptional[Long]("docker.container.memory").foreach(hostConfigMut.withMemory(_)) | ||
config.getOptional[Long]("docker.container.memorySwap").foreach(hostConfigMut.withMemorySwap(_)) | ||
config.getOptional[Long]("docker.container.memorySwappiness").foreach(hostConfigMut.withMemorySwappiness(_)) | ||
config.getOptional[String]("docker.container.networkMode").foreach(hostConfigMut.withNetworkMode) | ||
config.getOptional[Boolean]("docker.container.privileged").foreach(hostConfigMut.withPrivileged(_)) | ||
|
||
hostConfigMut | ||
} | ||
|
||
def info: Info = underlyingClient.infoCmd().exec() | ||
def pullImage(image: String): Boolean = blocking { | ||
val pullImageResultCbk = underlyingClient // Blocking | ||
.pullImageCmd(image) | ||
.start() | ||
.awaitCompletion() | ||
val timeout = config.get[FiniteDuration]("docker.pullImageTimeout") | ||
|
||
pullImageResultCbk.awaitCompletion(timeout.toMillis, TimeUnit.MILLISECONDS) | ||
} | ||
|
||
def clean(containerId: String): Try[Unit] = Try { | ||
underlyingClient | ||
.killContainerCmd(containerId) | ||
.exec() | ||
underlyingClient | ||
.removeContainerCmd(containerId) | ||
.withForce(true) | ||
.exec() | ||
logger.info(s"removed container $containerId") | ||
} | ||
|
||
def getLogs(containerId: String): Try[String] = Try { | ||
val stringBuilder = new StringBuilder() | ||
val callback = new DockerLogsStringBuilder(stringBuilder) | ||
underlyingClient | ||
.logContainerCmd(containerId) | ||
.withStdErr(true) | ||
.withStdOut(true) | ||
.withFollowStream(true) | ||
.withTailAll() | ||
.exec(callback) | ||
.awaitCompletion() | ||
|
||
callback.builder.toString | ||
} | ||
|
||
private def scheduleContainerTimeout(containerId: String, timeout: FiniteDuration) = | ||
Executors | ||
.newSingleThreadScheduledExecutor() | ||
.schedule( | ||
() => { | ||
logger.info(s"timeout $timeout reached, stopping container $containerId}") | ||
underlyingClient.removeContainerCmd(containerId).withForce(true).exec() | ||
}, | ||
timeout.length, | ||
timeout.unit | ||
) | ||
|
||
private def getHttpClient: (DockerClientConfig, DockerHttpClient) = { | ||
val dockerConf = getBaseConfig | ||
val dockerClient = new ZerodepDockerHttpClient.Builder() | ||
.dockerHost(dockerConf.getDockerHost) | ||
.sslConfig(dockerConf.getSSLConfig) | ||
.maxConnections(if (config.has("docker.httpClient.maxConnections")) config.get[Int]("docker.httpClient.maxConnections") else 100) | ||
.connectionTimeout( | ||
if (config.has("docker.httpClient.connectionTimeout")) Duration.ofMillis(config.get[Long]("docker.httpClient.connectionTimeout")) | ||
else Duration.ofSeconds(30) | ||
) | ||
.responseTimeout( | ||
if (config.has("docker.httpClient.responseTimeout")) Duration.ofMillis(config.get[Long]("docker.httpClient.responseTimeout")) | ||
else Duration.ofSeconds(45) | ||
) | ||
.build() | ||
|
||
(dockerConf, dockerClient) | ||
} | ||
|
||
private def getBaseConfig: DockerClientConfig = { | ||
val confBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder() | ||
config.getOptional[String]("docker.host").foreach(confBuilder.withDockerHost) | ||
config.getOptional[Boolean]("docker.tlsVerify").foreach(confBuilder.withDockerTlsVerify(_)) | ||
config.getOptional[String]("docker.certPath").foreach(confBuilder.withDockerCertPath) | ||
config.getOptional[String]("docker.registry.user").foreach(confBuilder.withRegistryUsername) | ||
config.getOptional[String]("docker.registry.password").foreach(confBuilder.withRegistryPassword) | ||
config.getOptional[String]("docker.registry.email").foreach(confBuilder.withRegistryEmail) | ||
config.getOptional[String]("docker.registry.url").foreach(confBuilder.withRegistryUrl) | ||
|
||
confBuilder.build() | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
app/org/thp/cortex/util/docker/DockerLogsStringBuilder.scala
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package org.thp.cortex.util.docker | ||
|
||
import com.github.dockerjava.api.async.ResultCallback | ||
import com.github.dockerjava.api.model.Frame | ||
|
||
class DockerLogsStringBuilder(var builder: StringBuilder) extends ResultCallback.Adapter[Frame] { | ||
override def onNext(item: Frame): Unit = { | ||
builder.append(new String(item.getPayload)) | ||
super.onNext(item) | ||
} | ||
} |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -219,4 +219,43 @@ responder { | |
# port = 3128 | ||
# } | ||
|
||
# Docker | ||
docker { | ||
host = "tcp://docker.somewhere.tld:2376" | ||
tlsVerify = false | ||
certPath = "/home/user/.docker" | ||
registry { | ||
user = "username" | ||
password = "pwdReg" | ||
email = "[email protected]" | ||
url = "https://www.docker-registry.com" | ||
} | ||
httpClient { | ||
maxConnections = 100 | ||
connectionTimeout = 30000 # millis | ||
responseTimeout = 45000 | ||
} | ||
container { | ||
capAdd = ["ALL"] | ||
capDrop = ["NET_ADMIN", "SYS_ADMIN"] | ||
cgroupParent = "m-executor-abcd" | ||
privileged = false | ||
|
||
dns = ["8.8.8.8", "9.9.9.9"] | ||
dnsSearch = ["dc1.example.com", "dc2.example.com"] | ||
extraHosts = ["somehost=162.242.195.82", "otherhost=50.31.209.229", "myhostv6=::1"] | ||
networkMode = "host" | ||
|
||
cpuPeriod = 100000 | ||
cpuQuota = 50000 | ||
kernelMemory = 2147483648 | ||
memoryReservation = 1024 | ||
memory = 4294967296 | ||
memorySwap = 1073741824 | ||
memorySwappiness = 0 | ||
} | ||
autoUpdate = false | ||
pullImageTimeout = 10 minutes | ||
} | ||
|
||
# It's the end my friend. Happy hunting! |
Oops, something went wrong.