add network create,get and list

This commit is contained in:
Anish Mukherjee
2022-11-18 17:42:40 +05:30
parent fa9b7643cb
commit 6a493b951a
10 changed files with 177 additions and 36 deletions

View File

@@ -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)

View File

@@ -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
cli/cmd/network/get.go Normal file
View File

@@ -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
cli/cmd/network/list.go Normal file
View File

@@ -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)
}

View File

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

View File

@@ -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)
}

View File

@@ -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 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)

View File

@@ -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)
}

View File

@@ -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
cli/samples/network.json Normal file
View File

@@ -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": [
"*"
]
}
}