about summary refs log tree commit diff
path: root/src/container.go
blob: c06a9edd0faffa4422fb6609c50c8ee04349b1c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/network"
	"time"
)

type ChallengeContainer struct {
	Challenge *Challenge
	ContainerID string
	IP string
}

// 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 and Docker CLI connection
	setupContext()
	setupDockerCLI()

	// Set up container network
	if containerNetworkID == "" {
		id, err := setupNetwork(getChallengeNetworkName(), true)
		if (err != nil) {
			return "", "", err
		}
		containerNetworkID = id
	}

	// 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, &network.NetworkingConfig{
		EndpointsConfig: map[string]*network.EndpointSettings{
			getChallengeNetworkName(): {
				NetworkID: containerNetworkID,
			},
		},
	}, "")

	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.Networks[getChallengeNetworkName()].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)
}