provider-k3s/main.go

116 lines
2.5 KiB
Go
Raw Normal View History

2022-08-08 15:55:32 +00:00
package main
import (
"bytes"
"fmt"
"github.com/c3os-io/c3os/sdk/clusterplugin"
yip "github.com/mudler/yip/pkg/schema"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"path/filepath"
2022-08-08 23:57:37 +00:00
kyaml "sigs.k8s.io/yaml"
2022-08-08 15:55:32 +00:00
)
const (
configurationPath = "/etc/rancher/k3s/config.d"
serverSystemName = "k3s"
agentSystemName = "k3s-agent"
)
type K3sConfig struct {
ClusterInit bool `yaml:"cluster-init"`
Token string `yaml:"token"`
Server string `yaml:"server"`
TLSSan []string `yaml:"tls-san"`
}
func clusterProvider(cluster clusterplugin.Cluster) yip.YipConfig {
k3sConfig := K3sConfig{
2022-08-08 23:57:37 +00:00
Token: cluster.ClusterToken,
Server: fmt.Sprintf("https://%s:6443", cluster.ControlPlaneHost),
2022-08-08 15:55:32 +00:00
TLSSan: []string{
cluster.ControlPlaneHost,
},
}
2022-08-08 23:57:37 +00:00
if cluster.Role == clusterplugin.RoleInit {
k3sConfig.ClusterInit = true
k3sConfig.Server = ""
}
2022-08-08 15:55:32 +00:00
systemName := serverSystemName
if cluster.Role == clusterplugin.RoleWorker {
systemName = agentSystemName
}
// ensure we always have a valid user config
if cluster.Options == "" {
cluster.Options = "{}"
}
var providerConfig bytes.Buffer
_ = yaml.NewEncoder(&providerConfig).Encode(&k3sConfig)
2022-08-08 23:57:37 +00:00
userOptions, _ := kyaml.YAMLToJSON([]byte(cluster.Options))
options, _ := kyaml.YAMLToJSON(providerConfig.Bytes())
2022-08-08 15:55:32 +00:00
cfg := yip.YipConfig{
Name: "K3s C3OS Cluster Provider",
Stages: map[string][]yip.Stage{
"boot.before": {
{
Name: "Install K3s Configuration Files",
Files: []yip.File{
{
Path: filepath.Join(configurationPath, "90_userdata.yaml"),
Permissions: 0400,
2022-08-08 23:57:37 +00:00
Content: string(userOptions),
2022-08-08 15:55:32 +00:00
},
{
Path: filepath.Join(configurationPath, "99_userdata.yaml"),
Permissions: 0400,
2022-08-08 23:57:37 +00:00
Content: string(options),
2022-08-08 15:55:32 +00:00
},
},
2022-08-08 23:57:37 +00:00
Commands: []string{
fmt.Sprintf("jq -rs 'reduce .[] as $item ({}; . * $item)' %s/*.yaml > /etc/rancher/k3s/config.yaml", configurationPath),
},
2022-08-08 15:55:32 +00:00
},
{
Name: "Enable OpenRC Services",
If: "[ -x /sbin/openrc-run ]",
Commands: []string{
fmt.Sprintf("rc-update add %s default >/dev/null", systemName),
},
},
{
Name: "Enable Systemd Services",
If: "[ -x /bin/systemctl ]",
Systemctl: yip.Systemctl{
Enable: []string{
systemName,
},
Start: []string{
systemName,
},
},
},
},
},
}
return cfg
}
func main() {
plugin := clusterplugin.ClusterPlugin{
Provider: clusterProvider,
}
if err := plugin.Run(); err != nil {
logrus.Fatal(err)
}
}