Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
136 lines (121 loc) · 2.69 KB
/
Copy pathmain.go
File metadata and controls
136 lines (121 loc) · 2.69 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
type AllocationConfig struct {
Namespace string `json:"namespace"`
Pod string `json:"pod"`
Address string `json:"address"`
Gateway string `json:"gateway"`
}
type RouteConfig struct {
Dst string `json:"dst,omitempty"`
Gateway string `json:"gw,omitempty"`
}
type IpamConfig struct {
Allocations []AllocationConfig `json:"allocations"`
Gateway string `json:"gateway,omitempty"`
Routes []RouteConfig `json:"routes,omitempty"`
}
type Config struct {
Ipam IpamConfig `json:"ipam"`
}
type CNIIpConfig struct {
Address string `json:"address"`
Gateway string ` json:"gateway,omitempty"`
}
type CNIIpam struct {
CniVersion string `json:"cniVersion,omitempty"`
Ips []CNIIpConfig `json:"ips,omitempty"`
Routes []RouteConfig `json:"routes,omitempty"`
}
func main() {
command := os.Getenv("CNI_COMMAND")
if command == "VERSION" {
fmt.Println(`{
"cniVersion": "1.0.0",
"supportedVersions": [ "0.1.0", "0.2.0", "0.3.0", "0.3.1", "0.4.0", "1.0.0" ]
}`)
return
}
if command != "ADD" {
fmt.Println(`{"cniVersion": "1.0.0"}`)
return
}
args := os.Getenv("CNI_ARGS")
argss := strings.Split(args, ";")
var podName string
var namespace string
for _, a := range argss {
as := strings.Split(a, "=")
if len(as) != 2 {
continue
}
if as[0] == "K8S_POD_NAMESPACE" {
namespace = as[1]
}
if as[0] == "K8S_POD_NAME" {
podName = as[1]
}
}
si := bufio.NewReader(os.Stdin)
data, err := ioutil.ReadAll(si)
var config Config
err = json.Unmarshal(data, &config)
if err != nil {
out := `
{
"cniVersion": "1.0.0",
"code": 7,
"msg": "Invalid Configuration",
"details": "%s"
}
`
fmt.Printf(out, err.Error())
os.Exit(1)
}
ips := []CNIIpConfig{}
routes := config.Ipam.Routes
for _, c := range config.Ipam.Allocations {
if (c.Namespace == namespace) && (c.Pod == podName) {
addr := c.Address
gateway := config.Ipam.Gateway
if len(c.Gateway) > 0 {
gateway = c.Gateway
}
ips = append(ips, CNIIpConfig {
Address: addr,
Gateway: gateway,
})
}
}
if len(ips) == 0 {
out := `
{
"cniVersion": "1.0.0",
"code": 7,
"msg": "Invalid Configuration",
"details": "no ip configured for %s/%s"
}
`
fmt.Printf(out, namespace, podName)
os.Exit(1)
}
outStruct := CNIIpam {
CniVersion: "1.0.0",
Ips: ips,
Routes: routes,
}
out, err := json.Marshal(&outStruct)
if err != nil {
log.Println(err)
}
fmt.Println(string(out))
log.Printf(string(out))
}