k3s/pkg/agent/flannel/setup.go

104 lines
2.0 KiB
Go
Raw Normal View History

2019-01-01 08:23:01 +00:00
package flannel
import (
"context"
2019-01-09 16:54:15 +00:00
"path/filepath"
2019-01-01 08:23:01 +00:00
"strings"
"time"
2019-01-09 16:54:15 +00:00
"github.com/rancher/k3s/pkg/agent/util"
"github.com/rancher/k3s/pkg/daemons/config"
2019-01-01 08:23:01 +00:00
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
cniConf = `{
"name":"cbr0",
"cniVersion":"0.3.1",
"plugins":[
{
"type":"flannel",
"delegate":{
"forceAddress":true,
"isDefaultGateway":true
}
},
{
"type":"portmap",
"capabilities":{
"portMappings":true
}
}
]
}
`
netJson = `{
"Network": "%CIDR%",
"Backend": {
"Type": "vxlan"
}
}
`
)
2019-01-09 16:54:15 +00:00
func Prepare(ctx context.Context, config *config.Node) error {
if err := createCNIConf(config.AgentConfig.CNIConfDir); err != nil {
return err
}
return createFlannelConf(config)
}
func Run(ctx context.Context, config *config.Node) error {
2019-01-01 08:23:01 +00:00
nodeName := config.AgentConfig.NodeName
restConfig, err := clientcmd.BuildConfigFromFlags("", config.AgentConfig.KubeConfig)
if err != nil {
return err
}
client, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return err
}
for {
node, err := client.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
if err == nil && node.Spec.PodCIDR != "" {
break
}
if err == nil {
logrus.Infof("waiting for node %s CIDR not assigned yet", nodeName)
} else {
logrus.Infof("waiting for node %s: %v", nodeName, err)
}
time.Sleep(2 * time.Second)
}
2019-01-09 16:54:15 +00:00
go func() {
err := flannel(ctx, config.FlannelConf, config.AgentConfig.KubeConfig)
2019-02-28 00:56:21 +00:00
logrus.Fatalf("flannel exited: %v", err)
2019-01-09 16:54:15 +00:00
}()
2019-01-01 08:23:01 +00:00
2019-01-09 16:54:15 +00:00
return err
2019-01-01 08:23:01 +00:00
}
2019-01-09 16:54:15 +00:00
func createCNIConf(dir string) error {
if dir == "" {
return nil
}
p := filepath.Join(dir, "10-flannel.conflist")
return util.WriteFile(p, cniConf)
2019-01-01 08:23:01 +00:00
}
2019-01-09 16:54:15 +00:00
func createFlannelConf(config *config.Node) error {
if config.FlannelConf == "" {
return nil
}
return util.WriteFile(config.FlannelConf,
strings.Replace(netJson, "%CIDR%", config.AgentConfig.ClusterCIDR.String(), -1))
2019-01-01 08:23:01 +00:00
}