about summary refs log tree commit diff
path: root/src/containerManager.go
blob: c8af5f9a99edf222aeff152d8ef293ed90e48390 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main

import (
	"errors"
	"sync"
)

var(
	containers = []*ChallengeContainer{}
	containerStartLock sync.Mutex
	containerStopLock sync.Mutex
)

// Checks if the given container name is already running
func isChallengeContainerRunning(name string) (bool) {
	for _, c := range containers {
		if c.Challenge.Name == name {
			return true
		}
	}

	return false
}

// Starts the given container. Thread-safe!
func startChallengeContainer(c Challenge) (*ChallengeContainer, error) {
	// Lock procedure to avoid race conditions
	containerStartLock.Lock()
	defer containerStartLock.Unlock()

	if(isChallengeContainerRunning(c.Name)) {
		return nil, errors.New("Container already running")
	}

	cc := ChallengeContainer{Challenge: &c}
	address, containerID, err := cc.startContainer()

	if err != nil {
		return nil, err
	}

	cc.IP = address
	cc.ContainerID = containerID

	// Add container to list
	containers = append(containers, &cc)

	return &cc, nil
}

// Stops the given container. Thread-safe!
func stopChallengeContainer(name string) {
	containerStopLock.Lock()
	defer containerStopLock.Unlock()

	for index, c := range containers {
		if c.Challenge.Name == name {
			c.stopContainer()
			containers = append(containers[:index], containers[index+1:]...)
			return
		}
	}
}

// Stops all containers. Thread-safe!
func stopAllChallengeContainers() {
	containerStopLock.Lock()
	defer containerStopLock.Unlock()

	for _, c := range containers {
		c.stopContainer()
	}
}

// Returns the address for the given container, if there is a container with this name running
func getAddressForChallengeContainer(container string) (address string) {
	for _, c := range containers {
		if c.Challenge.Container == container {
			return c.IP
		}
	}

	return ""
}