From 0b3290f270985dccf485a76f18d9c654e82c5814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nagy=20K=C3=A1roly=20G=C3=A1briel?= Date: Tue, 29 Aug 2023 19:37:01 +0300 Subject: [PATCH] jpictl: introduce `gateway` command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nagy Károly Gábriel --- cmd/jpictl/gateway.go | 82 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 8 deletions(-) diff --git a/cmd/jpictl/gateway.go b/cmd/jpictl/gateway.go index 1428e17..1004db3 100644 --- a/cmd/jpictl/gateway.go +++ b/cmd/jpictl/gateway.go @@ -1,6 +1,12 @@ package main import ( + "bytes" + "fmt" + "os" + "strconv" + "strings" + "git.jpi.io/amery/jpictl/pkg/zones" "github.com/spf13/cobra" ) @@ -31,8 +37,19 @@ var gatewaySetCmd = &cobra.Command{ }, } -func gatewaySet(_ zones.ZoneIterator, _ string) error { - return nil +func gatewaySet(zi zones.ZoneIterator, gw string) error { + var err error + zi.ForEachZone(func(z *zones.Zone) bool { + for _, m := range z.Machines { + if m.Name == gw { + z.SetGateway(m.ID, true) + return true + } + } + err = fmt.Errorf("machine %s not found", gw) + return false + }) + return err } // gateway unset @@ -56,8 +73,20 @@ var gatewayUnsetCmd = &cobra.Command{ }, } -func gatewayUnset(_ zones.ZoneIterator, _ string) error { - return nil +func gatewayUnset(zi zones.ZoneIterator, ngw string) error { + var err error + zi.ForEachZone(func(z *zones.Zone) bool { + for _, m := range z.Machines { + if m.Name == ngw && m.IsGateway() { + z.SetGateway(m.ID, false) + m.RemoveWireguardConfig(0) + return true + } + } + err = fmt.Errorf("machine %s not found", ngw) + return false + }) + return err } // gateway list @@ -85,12 +114,49 @@ var gatewayListCmd = &cobra.Command{ }, } -func gatewayListAll(_ zones.ZoneIterator) error { - return nil +func gatewayListAll(zi zones.ZoneIterator) error { + var b bytes.Buffer + var err error + zi.ForEachZone(func(z *zones.Zone) bool { + b.WriteString(z.Name + ":") + var sIDs []string + ids, num := z.GatewayIDs() + if num == 0 { + err = fmt.Errorf("no gateway in zone %s", z.Name) + return false + } + for _, i := range ids { + sIDs = append(sIDs, strconv.Itoa(i)) + } + b.WriteString(strings.Join(sIDs, ", ")) + b.WriteString("\n") + _, err = b.WriteTo(os.Stdout) + return false + }) + return err } -func gatewayList(_ zones.ZoneIterator, _ string) error { - return nil +func gatewayList(zi zones.ZoneIterator, m string) error { + var b bytes.Buffer + var err error + zi.ForEachZone(func(z *zones.Zone) bool { + if z.Name == m { + b.WriteString(z.Name + ":") + ids, num := z.GatewayIDs() + if num == 0 { + err = fmt.Errorf("no gateway in zone %s", z.Name) + return true + } + + b.WriteString(fmt.Sprint(ids)) + b.WriteString("\n") + _, err = b.WriteTo(os.Stdout) + return true + } + err = fmt.Errorf("zone %s not found", m) + return false + }) + return err } func init() {