Skip to content

Commit

Permalink
Added BGP Peer create, delete, get command
Browse files Browse the repository at this point in the history
  • Loading branch information
inhogog2 committed Jan 23, 2024
1 parent 9eb6a09 commit 3ecac9f
Show file tree
Hide file tree
Showing 9 changed files with 396 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Create - Service type external load-balancer, Vlan, Vxlan, Qos Policies,
createCmd.AddCommand(NewCreateMirrorCmd(restOptions))
createCmd.AddCommand(NewCreateFirewallCmd(restOptions))
createCmd.AddCommand(NewCreateEndPointCmd(restOptions))
createCmd.AddCommand(NewCreateBGPNeighborCmd(restOptions))

return createCmd
}
118 changes: 118 additions & 0 deletions cmd/create/create_bgpneighbor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright (c) 2022 NetLOX Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package create

import (
"context"
"errors"
"fmt"
"loxicmd/pkg/api"
"net"
"net/http"
"os"
"strconv"
"time"

"github.com/spf13/cobra"
)

type CreateBGPNeighborOptions struct {
SetMultiHtop bool
RemotePort uint8
}

func NewCreateBGPNeighborCmd(restOptions *api.RESTOptions) *cobra.Command {
o := CreateBGPNeighborOptions{}

var createBGPNeighborCmd = &cobra.Command{
Use: "bgpneighbor <PeerIP> <ASN> [--remotePort=<remoteBGPPort>] [--setMultiHtop]",
Short: "Create a BGP Neighbor",
Long: `Create a BGP Neighbor using LoxiLB.
ex) loxicmd create bgpneighbor 10.10.10.1 64512
`,
Aliases: []string{"bgpnei", "bgpneigh"},
PreRun: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
},
Run: func(cmd *cobra.Command, args []string) {
var BGPNeighborMod api.BGPNeighborMod
// Make BGPNeighborMod
if err := ReadCreateBGPNeighborOptions(&BGPNeighborMod, args); err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
}
// option
if o.RemotePort != 179 {
BGPNeighborMod.RemotePort = int(o.RemotePort)
}
if o.SetMultiHtop {
BGPNeighborMod.SetMultiHop = o.SetMultiHtop
}
resp, err := BGPNeighborAPICall(restOptions, BGPNeighborMod)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
PrintCreateResult(resp, *restOptions)
return
}

},
}
createBGPNeighborCmd.Flags().BoolVarP(&o.SetMultiHtop, "setMultiHtop", "", false, "Enable Multihop BGP in the load balancer")
createBGPNeighborCmd.Flags().Uint8VarP(&o.RemotePort, "remotePort", "", 179, "BGP Port number of the remote site")

return createBGPNeighborCmd
}

func ReadCreateBGPNeighborOptions(o *api.BGPNeighborMod, args []string) error {
if len(args) > 2 {
return errors.New("create BGPNeighbor command get so many args")
} else if len(args) <= 1 {
return errors.New("create BGPNeighbor need <RemoteAS> args")
}

if val := net.ParseIP(args[0]); val != nil {
o.IPaddress = args[0]
} else {
return fmt.Errorf("Peer IP '%s' is invalid format", args[0])
}

RemoteAs, err := strconv.Atoi(args[1])
if err != nil {
return err
}
o.RemoteAs = RemoteAs
return nil
}

func BGPNeighborAPICall(restOptions *api.RESTOptions, BGPNeighborModel api.BGPNeighborMod) (*http.Response, error) {
client := api.NewLoxiClient(restOptions)
ctx := context.TODO()
var cancel context.CancelFunc
if restOptions.Timeout > 0 {
ctx, cancel = context.WithTimeout(context.TODO(), time.Duration(restOptions.Timeout)*time.Second)
defer cancel()
}

return client.BGPNeighbor().Create(ctx, BGPNeighborModel)
}
2 changes: 2 additions & 0 deletions cmd/delete/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ Delete - Service type external load-balancer, Vlan, Vxlan, Qos Policies,
deleteCmd.AddCommand(NewDeleteMirrorCmd(restOptions))
deleteCmd.AddCommand(NewDeleteFirewallCmd(restOptions))
deleteCmd.AddCommand(NewDeleteEndPointCmd(restOptions))
deleteCmd.AddCommand(NewDeleteBGPNeighborCmd(restOptions))

deleteCmd.Flags().StringVarP(&NormalConfigFile, "file", "f", "", "Config file to apply as like K8s")
return deleteCmd
}
97 changes: 97 additions & 0 deletions cmd/delete/delete_bgpneighbor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2022 NetLOX Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package delete

import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"strconv"
"time"

"loxicmd/pkg/api"

"github.com/spf13/cobra"
)

func DeleteBGPNeighborValidation(args []string) error {
if len(args) > 3 {
fmt.Println("delete BGPNeighbor command get so many args")
} else if len(args) <= 1 {
return errors.New("delete IP Address need <MacAddress> <device> args")
}
if val := net.ParseIP(args[0]); val == nil {
return fmt.Errorf("Peer IP '%s' is invalid format", args[0])
}
if val, err := strconv.Atoi(args[1]); err != nil || val > 65535 || 0 > val {
return fmt.Errorf("RemoteAS '%s' is invalid format", args[1])
}
return nil
}

func NewDeleteBGPNeighborCmd(restOptions *api.RESTOptions) *cobra.Command {

var deleteBGPNeighborCmd = &cobra.Command{
Use: "bgpneighbor <PeerIP> <RemoteAS>",
Short: "Delete a BGP Neighbor peer information",
Long: `Delete a BGP Neighbor peer information in the LoxiLB.`,
PreRun: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
},
Aliases: []string{"bgpnei", "bgpneigh"},
Run: func(cmd *cobra.Command, args []string) {
if err := DeleteBGPNeighborValidation(args); err != nil {
fmt.Println("not valid <PeerIP> or <RemoteAs>")
fmt.Println(err)
return
}
PeerIP := args[0]
RemoteAS := args[1]
client := api.NewLoxiClient(restOptions)
ctx := context.TODO()
var cancel context.CancelFunc
if restOptions.Timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, time.Duration(restOptions.Timeout)*time.Second)
defer cancel()
}
subResources := []string{
PeerIP,
}
qmap := map[string]string{}
qmap["remoteAs"] = fmt.Sprintf("%v", RemoteAS)
resp, err := client.BGPNeighbor().SubResources(subResources).Query(qmap).Delete(ctx)
if err != nil {
fmt.Printf("Error: Failed to delete BGPNeighbor : %s", PeerIP)
return
}
defer resp.Body.Close()
fmt.Printf("Debug: response.StatusCode: %d\n", resp.StatusCode)
if resp.StatusCode == http.StatusOK {
PrintDeleteResult(resp, *restOptions)
return
}

},
}

return deleteBGPNeighborCmd
}
1 change: 1 addition & 0 deletions cmd/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ func GetCmd(restOptions *api.RESTOptions) *cobra.Command {
GetCmd.AddCommand(NewGetVxlanCmd(restOptions))
GetCmd.AddCommand(NewGetEndPointCmd(restOptions))
GetCmd.AddCommand(NewGetLogLevelCmd(restOptions))
GetCmd.AddCommand(NewGetBGPNeighborCmd(restOptions))

return GetCmd
}
Expand Down
95 changes: 95 additions & 0 deletions cmd/get/get_bgpneighbor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 NetLOX Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package get

import (
"context"
"encoding/json"
"fmt"
"io"
"loxicmd/pkg/api"
"net/http"
"time"

"github.com/spf13/cobra"
)

func NewGetBGPNeighborCmd(restOptions *api.RESTOptions) *cobra.Command {
var GetBGPNeighborCmd = &cobra.Command{
Use: "bgpneighbor",
Short: "Get a BGP neighbor",
Long: `It shows BGP neighbor Information in the LoxiLB`,
Aliases: []string{"bgpnei", "bgpneigh"},
Run: func(cmd *cobra.Command, args []string) {
client := api.NewLoxiClient(restOptions)
ctx := context.TODO()
var cancel context.CancelFunc
if restOptions.Timeout > 0 {
ctx, cancel = context.WithTimeout(context.TODO(), time.Duration(restOptions.Timeout)*time.Second)
defer cancel()
}
resp, err := client.BGPNeighbor().SetUrl("/config/bgp/neigh/all").Get(ctx)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return
}
if resp.StatusCode == http.StatusOK {
PrintGetBGPNeighborResult(resp, *restOptions)
return
}

},
}

return GetBGPNeighborCmd
}

func PrintGetBGPNeighborResult(resp *http.Response, o api.RESTOptions) {
BGPNeighborresp := api.BGPNeighborModGet{}
var data [][]string
resultByte, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error: Failed to read HTTP response: (%s)\n", err.Error())
return
}

if err := json.Unmarshal(resultByte, &BGPNeighborresp); err != nil {
fmt.Printf("Error: Failed to unmarshal HTTP response: (%s)\n", err.Error())
return
}

// if json options enable, it print as a json format.
if o.PrintOption == "json" {
resultIndent, _ := json.MarshalIndent(BGPNeighborresp, "", " ")
fmt.Println(string(resultIndent))
return
}

BGPNeighborresp.Sort()

// Table Init
table := TableInit()

// Making BGPNeighbor data
for _, BGPNeighbor := range BGPNeighborresp.BGPAttr {

table.SetHeader(BGPNEIGHBOR_TITLE)
data = append(data, []string{BGPNeighbor.IPaddress, fmt.Sprintf("%d", BGPNeighbor.RemoteAs), BGPNeighbor.UpDownTime, BGPNeighbor.State})

}
// Rendering the BGPNeighbor data to table
TableShow(data, table)
}
1 change: 1 addition & 0 deletions cmd/get/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@ var (
FIREWALL_TITLE = []string{"Source IP", "destination IP", "min SPort", "max SPort", "min DPort", "max DPort", "protocol", "port Name", "preference", "Option"}
ENDPOINT_TITLE = []string{"Host", "Name", "ptype", "port", "duration", "retries", "minDelay", "avgDelay", "maxDelay", "State"}
PARAM_TITLE = []string{"Param Name", "Value"}
BGPNEIGHBOR_TITLE = []string{"Peer", "AS", "UP/Down", "State"}
)
Loading

0 comments on commit 3ecac9f

Please sign in to comment.