Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: b3lbctl apply -f instances.yaml command #33 #61

Merged
merged 1 commit into from
Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@
"tenant",
"localhost:8090"
]
},
{
"name": "b3lbctl apply instances",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "cmd/b3lbctl/main.go",
"args": [
"apply",
"-f",
"/home/codespace/.b3lb/instances.yml"
]
}
]
}
7 changes: 7 additions & 0 deletions internal/mock/admin_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ var (
GetTenantFunc func(hostname string) (*b3lbadmin.Tenant, error)
// DeleteTenantFunc is the function that will be called whtne the admin mock is used
DeleteTenantFunc func(hostname string) error
// ApplyFunc is the function that will be called when the admin mock is used
ApplyFunc func(kind string, resource *interface{}) error
)

// InitAdminMock init admin.API object with an empty AdminMock struct
Expand Down Expand Up @@ -81,3 +83,8 @@ func (a *AdminMock) GetTenant(hostname string) (*b3lbadmin.Tenant, error) {
func (a *AdminMock) DeleteTenant(hostname string) error {
return DeleteTenantFunc(hostname)
}

// Apply is a mock implementation that apply a resource
func (a *AdminMock) Apply(kind string, resource *interface{}) error {
return ApplyFunc(kind, resource)
}
28 changes: 28 additions & 0 deletions pkg/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type Admin interface {
GetTenants() (*b3lbadmin.TenantList, error)
GetTenant(hostname string) (*b3lbadmin.Tenant, error)
DeleteTenant(hostname string) error
Apply(king string, resource *interface{}) error
}

// DefaultAdmin is the default admin api struct. It an empty struct
Expand Down Expand Up @@ -242,3 +243,30 @@ func (a *DefaultAdmin) DeleteTenant(hostname string) error {

return nil
}

// Apply applies a resource to b3lb cluster
func (a *DefaultAdmin) Apply(kind string, resource *interface{}) error {
var url string

if kind == "InstanceList" {
url = fmt.Sprintf("%s/admin/api/instances", *config.B3LB)
} else {
url = fmt.Sprintf("%s/admin/api/tenants", *config.B3LB)
}

b, err := json.Marshal(resource)
if err != nil {
return err
}

resp, err := restclient.PostWithHeaders(url, authorization(), b)
if err != nil {
return err
}

if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("b3lb returns a %d status instead of %d", resp.StatusCode, http.StatusCreated)
}

return nil
}
90 changes: 90 additions & 0 deletions pkg/admin/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"testing"

"github.com/SLedunois/b3lb/v2/pkg/admin"
b3lbadmin "github.com/SLedunois/b3lb/v2/pkg/admin"
"github.com/SLedunois/b3lb/v2/pkg/api"
"github.com/SLedunois/b3lb/v2/pkg/balancer"
Expand Down Expand Up @@ -624,3 +625,92 @@ func TestDeleteTenant(t *testing.T) {
})
}
}

func TestApply(t *testing.T) {
initTests()

var kind string
var resource interface{}

tests := []test{
{
name: "an error returned by restclient while applying InstanceList should be returned",
mock: func() {
resource = &admin.InstanceList{
Kind: "InstanceList",
Instances: map[string]string{},
}
kind = "InstanceList"
restclient.RestClientMockDoFunc = func(req *http.Request) (*http.Response, error) {
return nil, errors.New("rest error")
}
},
validator: func(t *testing.T, value interface{}, err error) {
assert.NotNil(t, err)
},
},
{
name: "an error returned by restclient while applying Tenant should be returned",
mock: func() {
resource = &admin.Tenant{
Kind: "Tenant",
Spec: map[string]string{},
Instances: []string{},
}
kind = "Tenant"
restclient.RestClientMockDoFunc = func(req *http.Request) (*http.Response, error) {
return nil, errors.New("rest error")
}
},
validator: func(t *testing.T, value interface{}, err error) {
assert.NotNil(t, err)
},
},
{
name: "an http status != 201 - Created should return an error",
mock: func() {
resource = &admin.Tenant{
Kind: "Tenant",
Spec: map[string]string{},
Instances: []string{},
}
kind = "Tenant"
restclient.RestClientMockDoFunc = func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusInternalServerError,
}, nil
}
},
validator: func(t *testing.T, value interface{}, err error) {
assert.NotNil(t, err)
},
},
{
name: "a valid request should return no error",
mock: func() {
resource = &admin.Tenant{
Kind: "Tenant",
Spec: map[string]string{},
Instances: []string{},
}
kind = "Tenant"
restclient.RestClientMockDoFunc = func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusCreated,
}, nil
}
},
validator: func(t *testing.T, value interface{}, err error) {
assert.Nil(t, err)
},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
test.mock()
err := API.Apply(kind, &resource)
test.validator(t, nil, err)
})
}
}
92 changes: 92 additions & 0 deletions pkg/cmd/apply/apply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package apply

import (
"fmt"
"io/ioutil"
"os"

"github.com/SLedunois/b3lbctl/pkg/admin"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)

// Cmd represents appl command type
type Cmd struct {
Command *cobra.Command
Flags *Flags
}

// NewCmd initialize a new Apply command
func NewCmd() *cobra.Command {
cmd := &Cmd{
Command: &cobra.Command{
Use: "apply -f [filepath]",
Short: "Apply a configuration to b3lb server using a file",
Long: "Apply a configuration to b3lb server using a file",
},
Flags: NewFlags(),
}

cmd.ApplyFlags()

cmd.Command.RunE = cmd.process

return cmd.Command
}

// ApplyFlags apply command flags to apply command
func (cmd *Cmd) ApplyFlags() {
cmd.Command.Flags().StringVarP(&cmd.Flags.FilePath, "file", "f", "", "resource file path")
cmd.Command.MarkFlagRequired("file")
}

func (cmd *Cmd) printApplyMessage(kind string, resource *interface{}) {
if kind == "InstanceList" {
cmd.Command.Println("InstanceList created")
}
}

func (cmd *Cmd) process(command *cobra.Command, args []string) error {
command.SilenceUsage = true
b, err := cmd.loadFile()
if err != nil {
return fmt.Errorf("unable to apply file. File loading fail: %s", err.Error())
}

kind, resource, err := toResource(b)
if err != nil {
return fmt.Errorf("unable to apply file. File is not a valid resource: %s", err.Error())
}

if err := yaml.Unmarshal(b, &resource); err != nil {
return fmt.Errorf("unable to apply file. Failed to unmarshal file content: %s", err.Error())
}

if err := admin.API.Apply(kind, &resource); err != nil {
return fmt.Errorf("unable to apply file. %s", err.Error())
}

cmd.printApplyMessage(kind, &resource)

return nil
}

func (cmd *Cmd) loadFile() ([]byte, error) {
file, err := os.Open(cmd.Flags.FilePath)
if err != nil {
return nil, err
}

defer func() {
if err := file.Close(); err != nil {
cmd.Command.Println(fmt.Sprintf("unable to close config file: %s", err))
}
}()

b, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}

return b, nil
}
81 changes: 81 additions & 0 deletions pkg/cmd/apply/apply_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package apply

import (
"bytes"
"errors"
"os"
"strings"
"testing"

"github.com/SLedunois/b3lb/v2/pkg/admin"
"github.com/SLedunois/b3lbctl/internal/mock"
"github.com/SLedunois/b3lbctl/internal/test"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)

func TestNewCmd(t *testing.T) {
mock.InitAdminMock()
tests := []test.CmdTest{
{
Name: "an error returned by file loader should be returned",
Args: []string{"-f", "/etc/dummy_folder/instances.yml"},
Mock: func() {},
Validator: func(t *testing.T, output *bytes.Buffer, err error) {
assert.NotNil(t, err)
},
},
{
Name: "an error return by admin apply method should be returned",
Args: []string{"-f", "/tmp/instances.yml"},
Mock: func() {
instances := &admin.InstanceList{
Kind: "InstanceList",
Instances: map[string]string{},
}

out, err := yaml.Marshal(instances)
if err != nil {
t.Fatal(err)
}

if err := os.WriteFile("/tmp/instances.yml", out, os.FileMode(0644)); err != nil {
t.Fatal(err)
}

mock.ApplyFunc = func(kind string, resource *interface{}) error {
return errors.New("admin error")
}
},
Validator: func(t *testing.T, output *bytes.Buffer, err error) {
assert.NotNil(t, err)
assert.Equal(t, "unable to apply file. admin error", err.Error())
},
},
{
Name: "applying an InstanceList file should print a valid `InstanceList created` message",
Args: []string{"-f", "/tmp/instances.yml"},
Mock: func() {
mock.ApplyFunc = func(kind string, resource *interface{}) error {
return nil
}
},
Validator: func(t *testing.T, output *bytes.Buffer, err error) {
assert.Nil(t, err)
assert.Equal(t, "InstanceList created", strings.TrimSpace(string(output.Bytes())))
},
},
}

for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
b := bytes.NewBufferString("")
cmd := NewCmd()
cmd.SetArgs(test.Args)
cmd.SetOut(b)
test.Mock()
err := cmd.Execute()
test.Validator(t, b, err)
})
}
}
6 changes: 6 additions & 0 deletions pkg/cmd/apply/definitions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package apply

// Resource is a resource object
type Resource struct {
Kind string `yaml:"kind"`
}
11 changes: 11 additions & 0 deletions pkg/cmd/apply/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package apply

// Flags contains all apply flags
type Flags struct {
FilePath string
}

// NewFlags initialize a new Flags struct
func NewFlags() *Flags {
return &Flags{}
}
15 changes: 15 additions & 0 deletions pkg/cmd/apply/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package apply

import (
"github.com/SLedunois/b3lb/v2/pkg/admin"
"gopkg.in/yaml.v3"
)

func toResource(in []byte) (string, interface{}, error) {
var resource *Resource
if err := yaml.Unmarshal(in, &resource); err != nil {
return "", nil, err
}

return "InstanceList", admin.InstanceList{}, nil
}
Loading