-
Notifications
You must be signed in to change notification settings - Fork 38
/
cmd_destroy.go
119 lines (98 loc) · 2.1 KB
/
cmd_destroy.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"fmt"
"os"
"sync"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/shared/api"
)
func cmdDestroy(c lxd.ContainerServer, args []string) error {
var wgBatch sync.WaitGroup
if os.Getuid() != 0 {
return fmt.Errorf("Container destruction must be run as root.")
}
// Load the simulation
routersMap, err := importFromLXD(c)
if err != nil {
return err
}
routers := []*Router{}
for _, v := range routersMap {
if v.Tier < 1 || v.Tier > 3 {
continue
}
routers = append(routers, v)
}
// Load the LXD container list
containers, err := c.GetContainers()
if err != nil {
return err
}
containersMap := map[string]api.Container{}
for _, ctn := range containers {
containersMap[ctn.Name] = ctn
}
// Helper function
deleteContainer := func(name string) {
defer wgBatch.Done()
ct, ok := containersMap[name]
if !ok {
logf("Failed to delete container: %s: Doesn't exist", ct.Name)
return
}
// Stop
if ct.IsActive() {
req := api.ContainerStatePut{
Action: "stop",
Timeout: -1,
Force: true,
}
op, err := c.UpdateContainerState(ct.Name, req, "")
if err != nil {
logf("Failed to delete container: %s: %s", ct.Name, err)
return
}
err = op.Wait()
if err != nil {
logf("Failed to delete container: %s: %s", ct.Name, err)
return
}
}
// Delete
op, err := c.DeleteContainer(ct.Name)
if err != nil {
logf("Failed to delete container: %s: %s", ct.Name, err)
return
}
err = op.Wait()
if err != nil {
logf("Failed to delete container: %s: %s", ct.Name, err)
return
}
}
// Delete all the containers
batch := 8
batches := len(routers) / batch
remainder := len(routers) % batch
current := 0
for i := 0; i < batches; i++ {
for j := 0; j < batch; j++ {
wgBatch.Add(1)
go deleteContainer(routers[current].Name)
current += 1
}
wgBatch.Wait()
}
for k := 0; k < remainder; k++ {
wgBatch.Add(1)
go deleteContainer(routers[current].Name)
current += 1
}
wgBatch.Wait()
// Destroy all the interfaces
err = networkDestroy(routersMap)
if err != nil {
return err
}
return nil
}