-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (88 loc) · 2.02 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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func main() {
// check args
args := os.Args
if len(args) != 2 {
fmt.Println("Usage: bridge-cni [output-conf-path]")
os.Exit(1)
}
// lookup the node name
nodeName, found := os.LookupEnv("NODE_NAME")
if !found {
fmt.Printf("Env var NODE_NAME is not defined\n")
os.Exit(1)
}
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
log.Panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Panic(err.Error())
}
// get the node object
node, err := clientset.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
if errors.IsNotFound(err) {
fmt.Printf("Node %s not found\n", nodeName)
} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
fmt.Printf("Error getting node %s: %v\n", nodeName, statusError.ErrStatus.Message)
os.Exit(1)
} else if err != nil {
panic(err.Error())
}
// extract the pod CIDR
podCidr := node.Spec.PodCIDR
if len(podCidr) == 0 {
log.Panicf("PodCIDR is empty for node %s", nodeName)
}
// generate the CNI config
conf := NetConfList{
CNIVersion: "1.0.0",
Name: "cbr0",
Plugins: []*PluginConf{
{
Type: "bridge",
IsDefaultGateway: true,
IPAM: IPAM{
Type: "host-local",
Subnet: podCidr,
},
},
},
}
confJson, err := json.MarshalIndent(conf, "", " ")
if err != nil {
panic(err.Error())
}
// open a writer for the desired output path
outputPath := args[1]
var output io.Writer
if outputPath == "-" {
output = os.Stdout
} else {
var err error
output, err = os.OpenFile(outputPath, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
panic(err.Error())
}
}
// write the json to the desired output
_, err = output.Write(confJson)
if err != nil {
panic(err.Error())
}
}