-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
305 lines (259 loc) · 7.93 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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright 2018 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"fmt"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/020"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/containernetworking/cni/pkg/version"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
"net"
"os"
"strings"
log "github.com/sirupsen/logrus"
)
// The top-level network config - IPAM plugins are passed the full configuration
// of the calling plugin, not just the IPAM section.
type Net struct {
Name string `json:"name"`
CNIVersion string `json:"cniVersion"`
IPAM *IPAMConfig `json:"ipam"`
}
type IPAMConfig struct {
Name string
Type string `json:"type"`
Routes []*types.Route `json:"routes"`
Addresses []Address `json:"addresses,omitempty"`
DNS types.DNS `json:"dns"`
}
type IPAMEnvArgs struct {
types.CommonArgs
IP types.UnmarshallableString `json:"ip,omitempty"`
GATEWAY types.UnmarshallableString `json:"gateway,omitempty"`
}
type Address struct {
AddressStr string `json:"address"`
Gateway net.IP `json:"gateway,omitempty"`
Address net.IPNet
Version string
}
const static_ipv4_annotation = "static-ipam.ipv4"
func init() {
log.SetFormatter(&log.TextFormatter{})
file, err := os.OpenFile("/tmp/static-ipam.log", os.O_CREATE|os.O_WRONLY, 0666)
if err == nil {
log.SetOutput(file)
} else {
log.SetOutput(os.Stdout)
}
log.SetLevel(log.DebugLevel)
}
func main() {
skel.PluginMain(cmdAdd, cmdCheck, cmdDel, version.All, bv.BuildString("static-ipam"))
}
func loadNetConf(bytes []byte) (*types.NetConf, string, error) {
n := &types.NetConf{}
if err := json.Unmarshal(bytes, n); err != nil {
return nil, "", fmt.Errorf("failed to load netconf: %v", err)
}
return n, n.CNIVersion, nil
}
func cmdCheck(args *skel.CmdArgs) error {
ipamConf, _, err := LoadIPAMConfig(args.StdinData, args.Args)
if err != nil {
return err
}
// Get PrevResult from stdin... store in RawPrevResult
n, _, err := loadNetConf(args.StdinData)
if err != nil {
return err
}
// Parse previous result.
if n.RawPrevResult == nil {
return fmt.Errorf("Required prevResult missing")
}
if err := version.ParsePrevResult(n); err != nil {
return err
}
result, err := current.NewResultFromResult(n.PrevResult)
if err != nil {
return err
}
// Each configured IP should be found in result.IPs
for _, rangeset := range ipamConf.Addresses {
for _, ips := range result.IPs {
// Ensure values are what we expect
if rangeset.Address.IP.Equal(ips.Address.IP) {
if rangeset.Gateway == nil {
break
} else if rangeset.Gateway.Equal(ips.Gateway) {
break
}
return fmt.Errorf("static: Failed to match addr %v on interface %v", ips.Address.IP, args.IfName)
}
}
}
return nil
}
// canonicalizeIP makes sure a provided ip is in standard form
func canonicalizeIP(ip *net.IP) error {
if ip.To4() != nil {
*ip = ip.To4()
return nil
} else if ip.To16() != nil {
*ip = ip.To16()
return nil
}
return fmt.Errorf("IP %s not v4 nor v6", *ip)
}
// LoadIPAMConfig creates IPAMConfig using json encoded configuration provided
// as `bytes`. At the moment values provided in envArgs are ignored so there
// is no possibility to overload the json configuration using envArgs
func LoadIPAMConfig(bytes []byte, envArgs string) (*IPAMConfig, string, error) {
n := Net{}
if err := json.Unmarshal(bytes, &n); err != nil {
return nil, "", err
}
if n.IPAM == nil {
return nil, "", fmt.Errorf("IPAM config missing 'ipam' key")
}
// Validate all ranges
numV4 := 0
numV6 := 0
for i := range n.IPAM.Addresses {
ip, addr, err := net.ParseCIDR(n.IPAM.Addresses[i].AddressStr)
if err != nil {
return nil, "", fmt.Errorf("invalid CIDR %s: %s", n.IPAM.Addresses[i].AddressStr, err)
}
n.IPAM.Addresses[i].Address = *addr
n.IPAM.Addresses[i].Address.IP = ip
if err := canonicalizeIP(&n.IPAM.Addresses[i].Address.IP); err != nil {
return nil, "", fmt.Errorf("invalid address %d: %s", i, err)
}
if n.IPAM.Addresses[i].Address.IP.To4() != nil {
n.IPAM.Addresses[i].Version = "4"
numV4++
} else {
n.IPAM.Addresses[i].Version = "6"
numV6++
}
}
if envArgs != "" {
e := IPAMEnvArgs{}
err := types.LoadArgs(envArgs, &e)
if err != nil {
return nil, "", err
}
if e.IP != "" {
for _, item := range strings.Split(string(e.IP), ",") {
ipstr := strings.TrimSpace(item)
ip, subnet, err := net.ParseCIDR(ipstr)
if err != nil {
return nil, "", fmt.Errorf("invalid CIDR %s: %s", ipstr, err)
}
addr := Address{Address: net.IPNet{IP: ip, Mask: subnet.Mask}}
if addr.Address.IP.To4() != nil {
addr.Version = "4"
numV4++
} else {
addr.Version = "6"
numV6++
}
n.IPAM.Addresses = append(n.IPAM.Addresses, addr)
}
}
if e.GATEWAY != "" {
for _, item := range strings.Split(string(e.GATEWAY), ",") {
gwip := net.ParseIP(strings.TrimSpace(item))
if gwip == nil {
return nil, "", fmt.Errorf("invalid gateway address: %s", item)
}
for i := range n.IPAM.Addresses {
if n.IPAM.Addresses[i].Address.Contains(gwip) {
n.IPAM.Addresses[i].Gateway = gwip
}
}
}
}
}
// CNI spec 0.2.0 and below supported only one v4 and v6 address
if numV4 > 1 || numV6 > 1 {
for _, v := range types020.SupportedVersions {
if n.CNIVersion == v {
return nil, "", fmt.Errorf("CNI version %v does not support more than 1 address per family", n.CNIVersion)
}
}
}
// Copy net name into IPAM so not to drag Net struct around
n.IPAM.Name = n.Name
return n.IPAM, n.CNIVersion, nil
}
func cmdAdd(args *skel.CmdArgs) error {
ipamConf, confVersion, err := LoadIPAMConfig(args.StdinData, args.Args)
if err != nil {
return err
}
podIpv4, err := LoadIPFromPodAnnotation(args.Args)
if err != nil {
log.Errorf("load ip error %v", err)
}
log.Infof("load ip from k8s pod annotation %s", podIpv4)
result := ¤t.Result{}
result.DNS = ipamConf.DNS
result.Routes = ipamConf.Routes
result.IPs = populateResultIPs(podIpv4, ipamConf.Addresses)
log.Infof("cni ipam result %+v", result)
return types.PrintResult(result, confVersion)
}
func populateResultIPs(ipv4 string, addresses []Address) []*current.IPConfig {
var ips []*current.IPConfig
for _, v := range addresses {
address := v.Address.IP
if strings.Compare("4", v.Version) == 0 && len(ipv4) > 0 {
address = net.ParseIP(ipv4)
}
log.Infof("version %s, use ip %s", v.Version, address.String())
ips = append(ips, ¤t.IPConfig{
Version: v.Version,
Address: net.IPNet{
IP: address,
Mask: v.Address.Mask,
},
Gateway: v.Gateway})
}
return ips
}
func LoadIPFromPodAnnotation(args string) (string, error) {
log.Debugf("read args.args ==> %s", args)
k8sArgs := K8sArgs{}
if err := types.LoadArgs(args, &k8sArgs); err != nil {
log.Errorf("read k8s args error %v", err)
return "", err
}
client, err := NewClient()
if err != nil {
log.Errorf("create k8s client error %v", err)
return "", err
}
annotations, err := GetPodInfo(client, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))
log.Infof("pod %s annotations %+v", string(k8sArgs.K8S_POD_NAME), annotations)
return annotations[static_ipv4_annotation], nil
}
func cmdDel(args *skel.CmdArgs) error {
// Nothing required because of no resource allocation in static plugin.
return nil
}