Browse Source

add network create,get and list

Anish Mukherjee 2 years ago
parent
commit
6a493b951a

+ 1 - 2
cli/cmd/context/set.go

@@ -44,8 +44,7 @@ var contextSetCmd = &cobra.Command{
 }
 
 func init() {
-	contextSetCmd.Flags().StringVar(&endpoint, FlagEndpoint, "", "Endpoint of the API Server (Required)")
-	contextSetCmd.MarkFlagRequired(FlagEndpoint)
+	contextSetCmd.Flags().StringVar(&endpoint, FlagEndpoint, "", "Endpoint of the API Server")
 	contextSetCmd.Flags().StringVar(&username, FlagUsername, "", "Username")
 	contextSetCmd.Flags().StringVar(&password, FlagPassword, "", "Password")
 	contextSetCmd.MarkFlagsRequiredTogether(FlagUsername, FlagPassword)

+ 12 - 5
cli/cmd/network/create.go

@@ -1,8 +1,9 @@
 package network
 
 import (
-	"fmt"
-	"os"
+	"encoding/json"
+	"io/ioutil"
+	"log"
 
 	"github.com/gravitl/netmaker/cli/functions"
 	"github.com/gravitl/netmaker/models"
@@ -11,14 +12,20 @@ import (
 
 // networkCreateCmd represents the networkCreate command
 var networkCreateCmd = &cobra.Command{
-	Use:   "create [network_definition.json]",
+	Use:   "create [/path/to/network_definition.json]",
 	Short: "Create a Network",
 	Long:  `Create a Network`,
 	Args:  cobra.ExactArgs(1),
 	Run: func(cmd *cobra.Command, args []string) {
+		content, err := ioutil.ReadFile(args[0])
+		if err != nil {
+			log.Fatal("Error when opening file: ", err)
+		}
 		network := &models.Network{}
-		resp := functions.CreateNetwork(network)
-		fmt.Fprintf(os.Stdout, "Response from `NetworksApi.CreateNetwork`: %v\n", resp)
+		if err := json.Unmarshal(content, network); err != nil {
+			log.Fatal(err)
+		}
+		functions.PrettyPrint(functions.CreateNetwork(network))
 	},
 }
 

+ 21 - 0
cli/cmd/network/get.go

@@ -0,0 +1,21 @@
+package network
+
+import (
+	"github.com/gravitl/netmaker/cli/functions"
+	"github.com/spf13/cobra"
+)
+
+// networkGetCmd represents the networkCreate command
+var networkGetCmd = &cobra.Command{
+	Use:   "get [NAME]",
+	Short: "Get a Network",
+	Long:  `Get a Network`,
+	Args:  cobra.ExactArgs(1),
+	Run: func(cmd *cobra.Command, args []string) {
+		functions.PrettyPrint(functions.GetNetwork(args[0]))
+	},
+}
+
+func init() {
+	rootCmd.AddCommand(networkGetCmd)
+}

+ 33 - 0
cli/cmd/network/list.go

@@ -0,0 +1,33 @@
+package network
+
+import (
+	"os"
+	"time"
+
+	"github.com/gravitl/netmaker/cli/functions"
+	"github.com/olekukonko/tablewriter"
+	"github.com/spf13/cobra"
+)
+
+// networkListCmd represents the networkCreate command
+var networkListCmd = &cobra.Command{
+	Use:   "list",
+	Short: "List all Networks",
+	Long:  `List all Networks`,
+	Args:  cobra.NoArgs,
+	Run: func(cmd *cobra.Command, args []string) {
+		networks := functions.GetNetworks()
+		table := tablewriter.NewWriter(os.Stdout)
+		table.SetHeader([]string{"NetId", "Address Range (IPv4)", "Address Range (IPv6)", "Network Last Modified", "Nodes Last Modified"})
+		for _, n := range *networks {
+			networkLastModified := time.Unix(n.NetworkLastModified, 0).Format(time.RFC3339)
+			nodesLastModified := time.Unix(n.NodesLastModified, 0).Format(time.RFC3339)
+			table.Append([]string{n.NetID, n.AddressRange, n.AddressRange6, networkLastModified, nodesLastModified})
+		}
+		table.Render()
+	},
+}
+
+func init() {
+	rootCmd.AddCommand(networkListCmd)
+}

+ 5 - 5
cli/config/config.go

@@ -11,11 +11,11 @@ import (
 )
 
 type Context struct {
-	Endpoint  string
-	Username  string
-	Password  string
-	MasterKey string
-	Current   bool `yaml:"current,omitempty"`
+	Endpoint  string `yaml:"endpoint"`
+	Username  string `yaml:"username,omitempty"`
+	Password  string `yaml:"password,omitempty"`
+	MasterKey string `yaml:"masterkey,omitempty"`
+	Current   bool   `yaml:"current,omitempty"`
 }
 
 var (

+ 0 - 12
cli/functions/auth.go

@@ -1,12 +0,0 @@
-package functions
-
-import (
-	"net/http"
-
-	"github.com/gravitl/netmaker/models"
-)
-
-func LoginWithUserAndPassword(username, password string) *models.SuccessResponse {
-	authParams := &models.UserAuthParams{UserName: username, Password: password}
-	return Request[models.SuccessResponse](http.MethodPost, "/api/users/adm/authenticate", authParams)
-}

+ 47 - 9
cli/functions/http_client.go

@@ -3,38 +3,76 @@ package functions
 import (
 	"bytes"
 	"encoding/json"
-	"io/ioutil"
+	"io"
 	"log"
 	"net/http"
+
+	"github.com/gravitl/netmaker/cli/config"
+	"github.com/gravitl/netmaker/models"
 )
 
-func Request[T any](method, route string, payload any) *T {
-	requestURL := "http://localhost:3000"
+func getAuthToken(ctx config.Context) string {
+	authParams := &models.UserAuthParams{UserName: ctx.Username, Password: ctx.Password}
+	payload, err := json.Marshal(authParams)
+	if err != nil {
+		log.Fatal(err)
+	}
+	res, err := http.Post(ctx.Endpoint+"/api/users/adm/authenticate", "application/json", bytes.NewReader(payload))
+	if err != nil {
+		log.Fatal(err)
+	}
+	resBodyBytes, err := io.ReadAll(res.Body)
+	if err != nil {
+		log.Fatalf("Client could not read response body: %s", err)
+	}
+	if res.StatusCode != http.StatusOK {
+		log.Fatalf("Error response: %s", string(resBodyBytes))
+	}
+	body := new(models.SuccessResponse)
+	if err := json.Unmarshal(resBodyBytes, body); err != nil {
+		log.Fatalf("Error unmarshalling JSON: %s", err)
+	}
+	return body.Response.(map[string]any)["AuthToken"].(string)
+}
+
+func request[T any](method, route string, payload any) *T {
 	var (
+		ctx = config.GetCurrentContext()
 		req *http.Request
 		err error
 	)
 	if payload == nil {
-		req, err = http.NewRequest(method, requestURL+route, nil)
+		req, err = http.NewRequest(method, ctx.Endpoint+route, nil)
+		if err != nil {
+			log.Fatalf("Client could not create request: %s", err)
+		}
 	} else {
 		payloadBytes, jsonErr := json.Marshal(payload)
 		if jsonErr != nil {
 			log.Fatalf("Error in request JSON marshalling: %s", err)
 		}
-		req, err = http.NewRequest(method, requestURL+route, bytes.NewReader(payloadBytes))
+		req, err = http.NewRequest(method, ctx.Endpoint+route, bytes.NewReader(payloadBytes))
+		if err != nil {
+			log.Fatalf("Client could not create request: %s", err)
+		}
+		req.Header.Set("Content-Type", "application/json")
 	}
-	if err != nil {
-		log.Fatalf("Client could not create request: %s", err)
+	if ctx.MasterKey != "" {
+		req.Header.Set("Authorization", "Bearer "+ctx.MasterKey)
+	} else {
+		req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx))
 	}
 	res, err := http.DefaultClient.Do(req)
 	if err != nil {
 		log.Fatalf("Client error making http request: %s", err)
 	}
-
-	resBodyBytes, err := ioutil.ReadAll(res.Body)
+	resBodyBytes, err := io.ReadAll(res.Body)
 	if err != nil {
 		log.Fatalf("Client could not read response body: %s", err)
 	}
+	if res.StatusCode != http.StatusOK {
+		log.Fatalf("Error response: %s", string(resBodyBytes))
+	}
 	body := new(T)
 	if err := json.Unmarshal(resBodyBytes, body); err != nil {
 		log.Fatalf("Error unmarshalling JSON: %s", err)

+ 13 - 3
cli/functions/network.go

@@ -8,10 +8,20 @@ import (
 
 // CreateNetwork - creates a network
 func CreateNetwork(payload *models.Network) *models.Network {
-	return Request[models.Network](http.MethodPost, "/api/networks", payload)
+	return request[models.Network](http.MethodPost, "/api/networks", payload)
+}
+
+// UpdateNetwork - updates a network
+func UpdateNetwork(name string, payload *models.Network) *models.Network {
+	return request[models.Network](http.MethodPut, "/api/networks/"+name, payload)
 }
 
 // GetNetworks - fetch all networks
-func GetNetworks() *models.Network {
-	return Request[models.Network](http.MethodGet, "/api/networks", nil)
+func GetNetworks() *[]models.Network {
+	return request[[]models.Network](http.MethodGet, "/api/networks", nil)
+}
+
+// GetNetwork - fetch a single network
+func GetNetwork(name string) *models.Network {
+	return request[models.Network](http.MethodGet, "/api/networks/"+name, nil)
 }

+ 15 - 0
cli/functions/pretty_print.go

@@ -0,0 +1,15 @@
+package functions
+
+import (
+	"encoding/json"
+	"fmt"
+	"log"
+)
+
+func PrettyPrint(data any) {
+	body, err := json.MarshalIndent(data, "", "  ")
+	if err != nil {
+		log.Fatal(err)
+	}
+	fmt.Println(string(body))
+}

+ 30 - 0
cli/samples/network.json

@@ -0,0 +1,30 @@
+{
+    "addressrange": "10.120.130.0/24",
+    "addressrange6": "",
+    "netid": "test3",
+    "defaultlistenport": 51821,
+    "nodelimit": 999999999,
+    "defaultpostup": "",
+    "defaultpostdown": "",
+    "defaultkeepalive": 20,
+    "accesskeys": [],
+    "allowmanualsignup": "no",
+    "islocal": "no",
+    "isipv4": "yes",
+    "isipv6": "no",
+    "ispointtosite": "no",
+    "localrange": "",
+    "defaultudpholepunch": "yes",
+    "defaultextclientdns": "",
+    "defaultmtu": 1280,
+    "defaultacl": "yes",
+    "prosettings": {
+      "defaultaccesslevel": 3,
+      "defaultusernodelimit": 0,
+      "defaultuserclientlimit": 0,
+      "allowedusers": [],
+      "allowedgroups": [
+        "*"
+      ]
+    }
+  }