Sfoglia il codice sorgente

fix+simplify wg0 logic

reid 2 anni fa
parent
commit
cec761a084
8 ha cambiato i file con 69 aggiunte e 75 eliminazioni
  1. 3 3
      config/config.go
  2. 4 4
      config/wireguard.go
  3. 10 10
      docker/docker.go
  4. 11 11
      docker/minio.go
  5. 12 12
      docker/netdata.go
  6. 2 2
      docker/urbit.go
  7. 25 31
      docker/wireguard.go
  8. 2 2
      structs/structs.go

+ 3 - 3
config/config.go

@@ -71,14 +71,14 @@ func init() {
 		// generate and insert wireguard keys
 		wgPriv, wgPub, err := WgKeyGen()
 		if err != nil {
-			logger.Error(fmt.Sprintf("%v",err))
+			logger.Error(fmt.Sprintf("%v", err))
 		} else {
 			err = UpdateConf(map[string]interface{}{
-				"Pubkey": wgPub,
+				"Pubkey":  wgPub,
 				"Privkey": wgPriv,
 			})
 			if err != nil {
-				logger.Error(fmt.Sprintf("%v",err))
+				logger.Error(fmt.Sprintf("%v", err))
 			}
 		}
 	}

+ 4 - 4
config/wireguard.go

@@ -1,14 +1,14 @@
 package config
 
 import (
-	"fmt"
-	"encoding/json"
 	"encoding/base64"
+	"encoding/json"
+	"fmt"
 	"goseg/defaults"
 	"goseg/structs"
 	"os"
 	"path/filepath"
-	
+
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
 )
 
@@ -79,4 +79,4 @@ func WgKeyGen() (privateKeyStr string, publicKeyStr string, err error) {
 	// derive pubkey and use startram encoding
 	publicKey := base64.StdEncoding.EncodeToString([]byte(privateKey.PublicKey().String() + "\n"))
 	return privateKey.String(), publicKey, nil
-}
+}

+ 10 - 10
docker/docker.go

@@ -120,7 +120,7 @@ func StartContainer(containerName string, containerType string) (structs.Contain
 	// host config for container
 	var hostConfig container.HostConfig
 	// switch on containerType to process containerConfig
-	switch containerType { 
+	switch containerType {
 	case "vere":
 		// containerConfig, HostConfig, err := urbitContainerConf(containerName)
 		_, err := urbitContainerConf(containerName)
@@ -132,7 +132,7 @@ func StartContainer(containerName string, containerType string) (structs.Contain
 		if err != nil {
 			return containerState, err
 		}
-	case "minio": 
+	case "minio":
 		_, _, err := minioContainerConf(containerName)
 		if err != nil {
 			return containerState, err
@@ -142,13 +142,13 @@ func StartContainer(containerName string, containerType string) (structs.Contain
 		if err != nil {
 			return containerState, err
 		}
-	// case "wireguard":
-	// 	_, err := wgContainerConf()
-	// 	if err != nil {
-	// 		return containerState, err
-	// 	}
+	case "wireguard":
+		_, _, err := wgContainerConf()
+		if err != nil {
+			return containerState, err
+		}
 	default:
-		errmsg := fmt.Errorf("Unrecognized container type %s",containerType)
+		errmsg := fmt.Errorf("Unrecognized container type %s", containerType)
 		return containerState, errmsg
 	}
 	ctx := context.Background()
@@ -267,8 +267,8 @@ func StartContainer(containerName string, containerType string) (structs.Contain
 		DesiredStatus: desiredStatus,                 // what the user sets
 		ActualStatus:  containerDetails.State.Status, // what the daemon reports
 		CreatedAt:     containerDetails.Created,      // this is a string
-		Config:		   containerConfig,				  // container.Config struct constructed above
-		Host:		   hostConfig,					  // host.Config struct constructed above
+		Config:        containerConfig,               // container.Config struct constructed above
+		Host:          hostConfig,                    // host.Config struct constructed above
 	}
 	return containerState, err
 }

+ 11 - 11
docker/minio.go

@@ -2,12 +2,12 @@ package docker
 
 import (
 	"fmt"
+	"github.com/docker/docker/api/types/container"
+	"github.com/docker/docker/api/types/mount"
 	"goseg/config"
 	"os"
-	"strings"
 	"path/filepath"
-	"github.com/docker/docker/api/types/container"
-	"github.com/docker/docker/api/types/mount"
+	"strings"
 )
 
 func LoadMC() error {
@@ -55,7 +55,7 @@ func LoadMinIOs() error {
 func minioContainerConf(containerName string) (container.Config, container.HostConfig, error) {
 	var containerConfig container.Config
 	var hostConfig container.HostConfig
-	shipName := strings.Split(containerName,"_")[1]
+	shipName := strings.Split(containerName, "_")[1]
 	err := config.LoadUrbitConfig(shipName)
 	if err != nil {
 		errmsg := fmt.Errorf("Error loading %s config: %v", shipName, err)
@@ -83,9 +83,9 @@ func minioContainerConf(containerName string) (container.Config, container.HostC
 		},
 	}
 	containerConfig = container.Config{
-		Image:      desiredImage,
-		Cmd:        []string{command},
-		Env:        environment,
+		Image: desiredImage,
+		Cmd:   []string{command},
+		Env:   environment,
 	}
 	// always on wg nw
 	hostConfig = container.HostConfig{
@@ -110,14 +110,14 @@ func mcContainerConf() (container.Config, container.HostConfig, error) {
 	desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
 	// construct the container config struct
 	containerConfig = container.Config{
-		Image:     desiredImage,
+		Image:      desiredImage,
 		Entrypoint: []string{"/bin/bash"},
-		Tty:       true,
-		OpenStdin: true,
+		Tty:        true,
+		OpenStdin:  true,
 	}
 	// always on wg nw
 	hostConfig = container.HostConfig{
 		NetworkMode: "container:wireguard",
 	}
 	return containerConfig, hostConfig, nil
-}
+}

+ 12 - 12
docker/netdata.go

@@ -2,11 +2,11 @@ package docker
 
 import (
 	"fmt"
+	"github.com/docker/docker/api/types/container"
+	"github.com/docker/go-connections/nat"
 	"goseg/config"
 	"os"
 	"path/filepath"
-	"github.com/docker/docker/api/types/container"
-	"github.com/docker/go-connections/nat"
 )
 
 func LoadNetdata() error {
@@ -48,17 +48,17 @@ func netdataContainerConf() (container.Config, container.HostConfig, error) {
 	desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
 	// construct the container config struct
 	containerConfig = container.Config{
-		Image:      desiredImage,
+		Image:        desiredImage,
 		ExposedPorts: nat.PortSet{"19999/tcp": struct{}{}},
 		Volumes: map[string]struct{}{
-			"/etc/netdata":            {},
-			"/var/lib/netdata":        {},
-			"/var/cache/netdata":      {},
-			"/host/etc/passwd":        {},
-			"/host/etc/group":         {},
-			"/host/proc":              {},
-			"/host/sys":               {},
-			"/host/etc/os-release":    {},
+			"/etc/netdata":         {},
+			"/var/lib/netdata":     {},
+			"/var/cache/netdata":   {},
+			"/host/etc/passwd":     {},
+			"/host/etc/group":      {},
+			"/host/proc":           {},
+			"/host/sys":            {},
+			"/host/etc/os-release": {},
 		},
 	}
 	hostConfig = container.HostConfig{
@@ -84,4 +84,4 @@ func netdataContainerConf() (container.Config, container.HostConfig, error) {
 		},
 	}
 	return containerConfig, hostConfig, nil
-}
+}

+ 2 - 2
docker/urbit.go

@@ -6,8 +6,8 @@ import (
 	"fmt"
 	"goseg/config"
 	"goseg/defaults"
-	"path/filepath"
 	"io/ioutil"
+	"path/filepath"
 
 	"github.com/docker/docker/api/types/container"
 )
@@ -97,7 +97,7 @@ func urbitContainerConf(containerName string) (container.Config, error) {
 	// finally construct the container config struct
 	containerConfig = container.Config{
 		Image:      desiredImage,
-		Entrypoint: []string{scriptPath, shipName, "--loom="+loomValue, "--dirname="+dirnameValue, "--http-port="+httpPort, "--ames-port="+amesPort},
+		Entrypoint: []string{scriptPath, shipName, "--loom=" + loomValue, "--dirname=" + dirnameValue, "--http-port=" + httpPort, "--ames-port=" + amesPort},
 	}
 	return containerConfig, nil
 }

+ 25 - 31
docker/wireguard.go

@@ -2,16 +2,16 @@ package docker
 
 import (
 	"context"
+	"encoding/base64"
 	"fmt"
+	"github.com/docker/docker/api/types"
+	"github.com/docker/docker/api/types/container"
+	"github.com/docker/docker/client"
 	"goseg/config"
 	"io/ioutil"
 	"os"
 	"path/filepath"
-	"encoding/base64"
 	"strings"
-	"github.com/docker/docker/api/types/container"
-	"github.com/docker/docker/client"
-	"github.com/docker/docker/api/types"
 	// "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
 )
 
@@ -54,10 +54,10 @@ func wgContainerConf() (container.Config, container.HostConfig, error) {
 	desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
 	// construct the container config struct
 	containerConfig = container.Config{
-		Image:     desiredImage,
+		Image:      desiredImage,
 		Entrypoint: []string{"/bin/bash"},
-		Tty:       true,
-		OpenStdin: true,
+		Tty:        true,
+		OpenStdin:  true,
 	}
 	// always on wg nw
 	hostConfig = container.HostConfig{
@@ -79,40 +79,34 @@ func buildWgConf() (string, error) {
 	return res, nil
 }
 
-// write wg config if it doesn't exist or doesn't match
 func writeWgConf() error {
-	volumeExists := true
-	// read existing and build current conf
+	newConf, err := buildWgConf()
+	if err != nil {
+		return err
+	}
 	filePath := filepath.Join(config.DockerDir, "settings", "wireguard", "_data", "wg0.conf")
 	existingConf, err := ioutil.ReadFile(filePath)
 	if err != nil {
-		volumeExists = false
+		// assume it doesn't exist, so write the current config
+		return writeWgConfToFile(filePath, newConf)
 	}
-	newConf, err := buildWgConf()
-	if err != nil {
-		return err
+	if string(existingConf) != newConf {
+		// If they differ, overwrite
+		return writeWgConfToFile(filePath, newConf)
 	}
-	ctx := context.Background()
-	cli, err := client.NewClientWithOpts(client.FromEnv)
+	return nil
+}
+
+func writeWgConfToFile(filePath string, content string) error {
+	err := ioutil.WriteFile(filePath, []byte(content), 0644)
 	if err != nil {
-		return err
+		return fmt.Errorf("Failed to write new WG config: %v", err)
 	}
-	_, err = cli.VolumeInspect(ctx, "wireguard")
+	// Copy to volume
+	err = copyFileToVolume(filePath, "/etc/wireguard/", "wireguard")
 	if err != nil {
-		volumeExists = false
+		return fmt.Errorf("Failed to copy WG config file to volume: %v", err)
 	}
-	// if theyre different, or if the volume doesnt exist, copy the new config to the volume
-	if string(existingConf) != newConf || !volumeExists {
-		err = ioutil.WriteFile("tmp/wg0.conf", []byte(newConf), 0644)
-		if err != nil {
-			return fmt.Errorf("Failed to write new WG config: %v", err)
-		}
-		// copy to volume
-		err = copyFileToVolume(filepath.Join("tmp","wg0.conf"), "/etc/wireguard/", "wireguard")
-		if err != nil {
-			return fmt.Errorf("Failed to copy WG config file to volume: %v", err)
-		}
-	}	
 	return nil
 }
 

+ 2 - 2
structs/structs.go

@@ -27,6 +27,6 @@ type ContainerState struct {
 	ActualNetwork  string // bridge/wireguard
 	DesiredNetwork string
 	CreatedAt      string
-	Config		   container.Config
-	Host		   container.HostConfig
+	Config         container.Config
+	Host           container.HostConfig
 }