/
main.go
107 lines (87 loc) · 2.68 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/cni/pkg/version"
)
type PluginConf struct {
types.NetConf
RuntimeConfig *struct {
} `json:"runtimeConfig,omitempty"`
RawPrevResult *map[string]interface{} `json:"prevResult"`
PrevResult *current.Result `json:"-"`
Debug bool `json:"debug"`
DebugDir string `json:"debugDir"`
}
func parseConfig(stdin []byte) (*PluginConf, error) {
conf := PluginConf{}
if err := json.Unmarshal(stdin, &conf); err != nil {
return nil, fmt.Errorf("failed to parse network configuration: %v", err)
}
if conf.RawPrevResult != nil {
resultBytes, err := json.Marshal(conf.RawPrevResult)
if err != nil {
return nil, fmt.Errorf("could not serialize prevResult: %v", err)
}
res, err := version.NewResult(conf.CNIVersion, resultBytes)
if err != nil {
return nil, fmt.Errorf("could not parse prevResult: %v", err)
}
conf.RawPrevResult = nil
conf.PrevResult, err = current.NewResultFromResult(res)
if err != nil {
return nil, fmt.Errorf("could not convert result to current version: %v", err)
}
}
if conf.Debug == true && conf.DebugDir == "" {
return nil, fmt.Errorf("debugDir must be specified")
}
return &conf, nil
}
func cniDebug(enabled bool, dir string, args *skel.CmdArgs, action string) {
if !enabled {
return
}
dFilePath := filepath.Join(dir, args.ContainerID, args.IfName)
if err := os.MkdirAll(dFilePath, 0770); err != nil {
panic("untested")
}
stdinFile := fmt.Sprintf("%s/%s_%v.json", dFilePath, action, time.Now().Unix())
if err := ioutil.WriteFile(stdinFile, args.StdinData, 0770); err != nil {
panic("untested")
}
netnsFile := fmt.Sprintf("%s/%s_%v.netns", dFilePath, action, time.Now().Unix())
if err := ioutil.WriteFile(netnsFile, []byte(args.Netns), 0770); err != nil {
panic("untested")
}
}
func cmdAdd(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData)
if err != nil {
return fmt.Errorf("failed to parse config: %v", err)
}
cniDebug(conf.Debug, conf.DebugDir, args, "add")
if conf.PrevResult == nil {
return types.PrintResult(¤t.Result{}, conf.CNIVersion)
}
return types.PrintResult(conf.PrevResult, conf.CNIVersion)
}
func cmdDel(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData)
if err != nil {
return fmt.Errorf("failed to parse config: %v", err)
}
_ = conf
cniDebug(conf.Debug, conf.DebugDir, args, "del")
return nil
}
func main() {
skel.PluginMain(cmdAdd, cmdDel, version.PluginSupports(version.Current()))
}