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/containerManager.go | 74 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/containerManager.go (limited to 'src/containerManager.go') diff --git a/src/containerManager.go b/src/containerManager.go new file mode 100644 index 0000000..0c25ae9 --- /dev/null +++ b/src/containerManager.go @@ -0,0 +1,74 @@ +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 + } + } +} + +// 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 "" +} -- cgit 1.4.1