From 07294af77f4b088f67efafbeee79e7ddd0eeac84 Mon Sep 17 00:00:00 2001 From: maride Date: Tue, 21 Aug 2018 18:49:59 +0200 Subject: Feature: Start and stop challenge containers --- src/container.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/container.go (limited to 'src/container.go') diff --git a/src/container.go b/src/container.go new file mode 100644 index 0000000..73912bf --- /dev/null +++ b/src/container.go @@ -0,0 +1,70 @@ +package main + +import ( + "context" + "github.com/docker/docker/client" + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/api/types" + "fmt" + "time" +) + +type ChallengeContainer struct { + Challenge *Challenge + ContainerID string + IP string +} + +var ( + dockerCtx context.Context + dockerCli *client.Client +) + +// Starts the container and returns its address and containerID if successful +func (cc ChallengeContainer) startContainer() (address string, containerID string, err error) { + // Set up our context if there is none already set up + if dockerCtx == nil { + dockerCtx = context.Background() + } + + // Set up our Docker CLI connection if there is not already one + if dockerCli == nil { + dockerCli, err = client.NewEnvClient() + + if err != nil { + return "", "", err + } + } + + // Create container + resp, err := dockerCli.ContainerCreate(dockerCtx, &container.Config{ + Image: cc.Challenge.Container, + Env: []string{fmt.Sprintf("FLAG=%s", cc.Challenge.Flag)}, + Tty: false, + }, nil, nil, "") + + if err != nil { + return "", "", err + } + + // Start container + err = dockerCli.ContainerStart(dockerCtx, resp.ID, types.ContainerStartOptions{}) + if err != nil { + return "", "", err + } + + // Get IP Address of that container + inspectJSON, err := dockerCli.ContainerInspect(dockerCtx, resp.ID) + if err != nil { + return "", "", err + } + + // Return IP, Container ID and error + return inspectJSON.NetworkSettings.IPAddress, resp.ID,nil +} + +// Stops the container with a timeout of one second +func (cc ChallengeContainer) stopContainer() { + timeout := time.Second + dockerCli.ContainerStop(dockerCtx, cc.ContainerID, &timeout) +} -- cgit 1.4.1