This repository has been archived by the owner on Jan 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.go
119 lines (99 loc) · 2.48 KB
/
controller.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 controller
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/appc/cni/libcni"
)
type Controller struct {
PluginDir string
ConfigDir string
SandboxDirPath string
DaemonBaseURL string
cniConfig *libcni.CNIConfig
networkConfigs []*libcni.NetworkConfig
}
func (c *Controller) ensureInitialized() error {
if c.cniConfig == nil {
c.cniConfig = &libcni.CNIConfig{Path: []string{c.PluginDir}}
}
if c.networkConfigs == nil {
c.networkConfigs = []*libcni.NetworkConfig{}
err := filepath.Walk(c.ConfigDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".conf") {
return nil
}
conf, err := libcni.ConfFromFile(path)
if err != nil {
return fmt.Errorf("unable to load config from %s: %s", path, err)
}
c.networkConfigs = append(c.networkConfigs, conf)
log.Printf("loaded config %+v\n%s\n", conf.Network, string(conf.Bytes))
return nil
})
if err != nil {
return fmt.Errorf("error loading config: %s", err)
}
}
return nil
}
func (c *Controller) Up(namespacePath, handle, spec string) error {
err := c.ensureInitialized()
if err != nil {
return fmt.Errorf("failed to initialize controller: %s", err)
}
err = os.Setenv("DUCATI_OS_SANDBOX_REPO", c.SandboxDirPath)
if err != nil {
return err
}
err = os.Setenv("DAEMON_BASE_URL", c.DaemonBaseURL)
if err != nil {
return err
}
for i, networkConfig := range c.networkConfigs {
runtimeConfig := &libcni.RuntimeConf{
ContainerID: handle,
NetNS: namespacePath,
IfName: fmt.Sprintf("eth%d", i),
}
_, err = c.cniConfig.AddNetwork(networkConfig, runtimeConfig)
if err != nil {
return fmt.Errorf("add network failed: %s", err)
}
}
return nil
}
func (c *Controller) Down(namespacePath, handle string) error {
err := c.ensureInitialized()
if err != nil {
return fmt.Errorf("failed to initialize controller: %s", err)
}
err = os.Setenv("DUCATI_OS_SANDBOX_REPO", c.SandboxDirPath)
if err != nil {
return err
}
err = os.Setenv("DAEMON_BASE_URL", c.DaemonBaseURL)
if err != nil {
return err
}
for i, networkConfig := range c.networkConfigs {
runtimeConfig := &libcni.RuntimeConf{
ContainerID: handle,
NetNS: namespacePath,
IfName: fmt.Sprintf("eth%d", i),
}
err = c.cniConfig.DelNetwork(networkConfig, runtimeConfig)
if err != nil {
return fmt.Errorf("add network failed: %s", err)
}
}
return nil
}