provider-kairos/internal/provider/vpn.go

112 lines
2.7 KiB
Go
Raw Normal View History

2022-08-10 16:55:20 +00:00
package provider
import (
"fmt"
"io/ioutil"
2022-08-10 16:55:20 +00:00
"os"
"path/filepath"
"strings"
"github.com/kairos-io/kairos/pkg/machine"
"github.com/kairos-io/kairos/pkg/machine/systemd"
"github.com/kairos-io/kairos/pkg/utils"
providerConfig "github.com/kairos-io/provider-kairos/internal/provider/config"
"github.com/kairos-io/provider-kairos/internal/services"
"gopkg.in/yaml.v3"
2022-08-10 16:55:20 +00:00
yip "github.com/mudler/yip/pkg/schema"
)
func SaveOEMCloudConfig(name string, yc yip.YipConfig) error {
dnsYAML, err := yaml.Marshal(yc)
if err != nil {
return err
}
return ioutil.WriteFile(filepath.Join("oem", fmt.Sprintf("100_%s.yaml", name)), dnsYAML, 0700)
}
2022-08-10 16:55:20 +00:00
func SetupVPN(instance, apiAddress, rootDir string, start bool, c *providerConfig.Config) error {
if c.Kairos == nil || c.Kairos.NetworkToken == "" {
2022-08-10 16:55:20 +00:00
return fmt.Errorf("no network token defined")
}
2022-08-12 07:51:59 +00:00
svc, err := services.EdgeVPN(instance, rootDir)
2022-08-10 16:55:20 +00:00
if err != nil {
return fmt.Errorf("could not create svc: %w", err)
}
apiAddress = strings.ReplaceAll(apiAddress, "https://", "")
apiAddress = strings.ReplaceAll(apiAddress, "http://", "")
vpnOpts := map[string]string{
"EDGEVPNTOKEN": c.Kairos.NetworkToken,
"API": "true",
"APILISTEN": apiAddress,
"DHCP": "true",
"DHCPLEASEDIR": "/usr/local/.kairos/lease",
2022-08-10 16:55:20 +00:00
}
// Override opts with user-supplied
for k, v := range c.VPN {
vpnOpts[k] = v
}
if c.Kairos.DNS {
2022-08-10 16:55:20 +00:00
vpnOpts["DNSADDRESS"] = "127.0.0.1:53"
vpnOpts["DNSFORWARD"] = "true"
dnsConfig := yip.YipConfig{
2022-08-10 16:55:20 +00:00
Name: "DNS Configuration",
Stages: map[string][]yip.Stage{
"initramfs": {
{
Files: []yip.File{{
Permissions: 0644,
Path: "/etc/systemd/resolved.conf", Content: `
[Resolve]
DNS=127.0.0.1`,
}},
},
{
Dns: yip.DNS{Nameservers: []string{"127.0.0.1"}}},
}},
}
dat, _ := yaml.Marshal(&dnsConfig)
_ = machine.ExecuteInlineCloudConfig(string(dat), "initramfs")
if !utils.IsOpenRCBased() {
svc, err := systemd.NewService(
systemd.WithName("systemd-resolved"),
)
if err == nil {
_ = svc.Restart()
}
}
if err := SaveOEMCloudConfig("vpn_dns", dnsConfig); err != nil {
2022-08-10 16:55:20 +00:00
return fmt.Errorf("could not create dns config: %w", err)
}
}
os.MkdirAll("/etc/systemd/system.conf.d/", 0600) //nolint:errcheck
// Setup edgevpn instance
err = utils.WriteEnv(filepath.Join(rootDir, "/etc/systemd/system.conf.d/edgevpn-kairos.env"), vpnOpts)
2022-08-10 16:55:20 +00:00
if err != nil {
return fmt.Errorf("could not create write env file: %w", err)
}
err = svc.WriteUnit()
if err != nil {
return fmt.Errorf("could not create write unit file: %w", err)
}
if start {
err = svc.Start()
if err != nil {
return fmt.Errorf("could not start svc: %w", err)
}
return svc.Enable()
}
return nil
}