-
Notifications
You must be signed in to change notification settings - Fork 0
/
containers.go
88 lines (63 loc) · 1.51 KB
/
containers.go
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
85
86
87
package main
import (
"os"
"bufio"
"fmt"
"log"
"os/exec"
)
var startedContainers = make(map[string]string)
func init() {
loadStartedContainers()
}
func loadStartedContainers() {
file, err := os.OpenFile(datafile, os.O_RDONLY, os.ModePerm)
if err != nil {
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
log.Println("found started container: " + text)
startedContainers[text] = text
}
if err := scanner.Err(); err != nil {
log.Println(err)
}
}
func saveStartedContainers(name string) {
removeDeadContainers()
startedContainers[name] = name
os.Remove(datafile)
file, err := os.Create(datafile)
if err != nil {
log.Println("cannot write data file: ", err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, v := range startedContainers {
log.Println("save started container:" + v)
fmt.Fprintln(writer, v)
}
writer.Flush()
}
func removeDeadContainers() {
// remove dead container ids off the record
for _, v := range startedContainers {
//docker inspect -f '{{.State.Running}}' v
out, err := exec.Command("docker", "-f", "{{.State.Running}}", v).CombinedOutput()
if err != nil {
delete(startedContainers, v)
log.Println("inspect error:", err)
log.Println("removeDeadContainers dead container: ", v)
continue
}
if string(out) != "true" {
delete(startedContainers, v)
log.Println("removeDeadContainers dead container: ", v)
}
}
log.Println("removeDeadContainers done ")
}