Skip to content

Commit

Permalink
Merge pull request #16 from mateimicu/testing-internal
Browse files Browse the repository at this point in the history
  • Loading branch information
mateimicu committed May 9, 2020
2 parents 633751f + b2f2f59 commit 040d9fc
Show file tree
Hide file tree
Showing 25 changed files with 1,214 additions and 391 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ linters-settings:
settings:
mnd:
# TODO(mmicu): exclude this when golangci-lint will include v2.0.0 of go-mnd
exclude: argument
excludes: argument
11 changes: 6 additions & 5 deletions cmd/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ package cmd
import (
"fmt"

"github.com/mateimicu/kdiscover/internal"
"github.com/mateimicu/kdiscover/internal/aws"
"github.com/mateimicu/kdiscover/internal/kubeconfig"
"github.com/spf13/cobra"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -37,13 +38,13 @@ func newAWSCommand() *cobra.Command {
"partitions": awsPartitions,
}).Debug("Search regions for partitions")

awsRegions = internal.GetRegions(awsPartitions)
awsRegions = aws.GetRegions(awsPartitions)

if len(awsRegions) == 0 {
log.WithFields(log.Fields{
"partitions": awsPartitions,
}).Error("Can't find regions for partitions")
return fmt.Errorf("Can't find regions for partitions %v", awsPartitions)
return fmt.Errorf("can't find regions for partitions %v", awsPartitions)
}

log.WithFields(log.Fields{
Expand All @@ -61,12 +62,12 @@ func newAWSCommand() *cobra.Command {
&awsPartitions,
"aws-partitions",
[]string{"aws"},
fmt.Sprintf("In what partitions to search for clusters. Supported %v", internal.AllowedParitions()))
fmt.Sprintf("In what partitions to search for clusters. Supported %v", aws.AllowedParitions()))

AWSCommand.PersistentFlags().StringVar(
&kubeconfigPath,
"kubeconfig-path",
internal.GetDefaultKubeconfigPath(),
kubeconfig.GetDefaultKubeconfigPath(),
"Path to the kubeconfig to work with")

AWSCommand.AddCommand(newListCommand(), newUpdateCommand())
Expand Down
47 changes: 34 additions & 13 deletions cmd/aws_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,45 @@ package cmd
import (
"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
"github.com/mateimicu/kdiscover/internal"
"github.com/mateimicu/kdiscover/internal/aws"
"github.com/mateimicu/kdiscover/internal/cluster"
"github.com/mateimicu/kdiscover/internal/kubeconfig"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

type clusterDescribe interface {
GetEndpoint() string
GetName() string
GetRegion() string
GetStatus() string
}

type exportable interface {
IsExported(kubeconfigPath string) bool
IsExported(cls kubeconfig.Endpointer) bool
}

func getExportedString(e exportable, cls kubeconfig.Endpointer) string {
if e.IsExported(cls) {
return "Yes"
}
return "No"
}

func getTable(clusters []internal.Cluster) string {
func convertToInterfaces(clusters []*cluster.Cluster) []clusterDescribe {
cls := make([]clusterDescribe, len(clusters))
for i, c := range clusters {
cls[i] = clusterDescribe(c)
}
return cls
}

func getTable(clusters []clusterDescribe, e exportable) string {
tw := table.NewWriter()
tw.AppendHeader(table.Row{"Cluster Name", "Region", "Status", "Exported Locally"})
rows := []table.Row{}
for _, cls := range clusters {
rows = append(rows, table.Row{cls.Name, cls.Region, cls.Status, getExportedString(&cls, kubeconfigPath)})
rows = append(rows, table.Row{cls.GetName(), cls.GetRegion(), cls.GetStatus(), getExportedString(e, cls)})
}
tw.AppendRows(rows)

Expand All @@ -42,22 +66,19 @@ func getTable(clusters []internal.Cluster) string {
return tw.Render()
}

func getExportedString(cls exportable, kubeconfigPath string) string {
if cls.IsExported(kubeconfigPath) {
return "Yes"
}
return "No"
}

func newListCommand() *cobra.Command {
listCommand := &cobra.Command{
Use: "list",
Short: "List all EKS Clusters",
RunE: func(cmd *cobra.Command, args []string) error {
remoteEKSClusters := internal.GetEKSClusters(awsRegions)
remoteEKSClusters := aws.GetEKSClusters(awsRegions)
log.Info(remoteEKSClusters)
k, err := kubeconfig.LoadKubeconfig(kubeconfigPath)
if err != nil {
return err
}

cmd.Println(getTable(remoteEKSClusters))
cmd.Println(getTable(convertToInterfaces(remoteEKSClusters), k))
return nil
},
}
Expand Down
28 changes: 11 additions & 17 deletions cmd/aws_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,29 @@ import (
"strings"
"testing"

"github.com/mateimicu/kdiscover/internal"
"github.com/mateimicu/kdiscover/internal/cluster"
"github.com/mateimicu/kdiscover/internal/kubeconfig"
)

func getMockClusters(c int) []internal.Cluster {
d := make([]internal.Cluster, 0, c)
for i := 0; i < c; i++ {
d = append(d, internal.Cluster{
Name: fmt.Sprintf("clucster-name-%v", i),
Region: fmt.Sprintf("clucster-region-%v", i),
Id: fmt.Sprintf("clucster-id-%v", i),
Status: fmt.Sprintf("clucster-status-%v", i),
})
}
return d
type mockExportable struct{}

func (mockExportable) IsExported(cls kubeconfig.Endpointer) bool {
return false
}

// Test if the number of clusters is corectly diplayed
func Test_getTable(t *testing.T) {
tts := []struct {
clusters []internal.Cluster
clusters []*cluster.Cluster
}{
{clusters: getMockClusters(0)},
{clusters: getMockClusters(1)},
{clusters: getMockClusters(3)},
{clusters: cluster.GetMockClusters(0)},
{clusters: cluster.GetMockClusters(1)},
{clusters: cluster.GetMockClusters(3)},
}
for _, tt := range tts {
testname := fmt.Sprintf("Clusters %v", tt.clusters)
t.Run(testname, func(t *testing.T) {
r := getTable(tt.clusters)
r := getTable(convertToInterfaces(tt.clusters), mockExportable{})
if !strings.Contains(r, fmt.Sprintf("%v", len(tt.clusters))) {
t.Errorf("Expected %v in output, but got %v", len(tt.clusters), r)
}
Expand Down
85 changes: 85 additions & 0 deletions cmd/aws_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Package cmd offers CLI functionality
package cmd

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"

"github.com/mateimicu/kdiscover/internal/aws"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
)

type testCase struct {
Cmd []string
Partitions []string
}

var cases []testCase = []testCase{
{[]string{"aws", "list"}, []string{"aws"}},
{[]string{"aws", "list"}, []string{"aws-cn"}},
{[]string{"aws", "list"}, []string{"aws-iso-b"}},
{[]string{"aws", "list"}, []string{"aws", "aws-cn"}},
{[]string{"aws", "list"}, []string{"aws-us-gov", "aws-iso", "aws-iso-b"}},
{[]string{"aws", "list"}, []string{"aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b"}},
{[]string{"aws", "update"}, []string{"aws"}},
{[]string{"aws", "update"}, []string{"aws-cn"}},
{[]string{"aws", "update"}, []string{"aws-iso-b"}},
{[]string{"aws", "update"}, []string{"aws", "aws-cn"}},
{[]string{"aws", "update"}, []string{"aws-us-gov", "aws-iso", "aws-iso-b"}},
{[]string{"aws", "update"}, []string{"aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b"}},
}

func TestQueryAllRegions(t *testing.T) {
for _, tt := range cases {
testname := fmt.Sprintf("command %v", tt.Partitions)
t.Run(testname, func(t *testing.T) {
dir, err := ioutil.TempDir("", ".kube")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)
kubeconfigPath := filepath.Join(dir, "kubeconfig")

cmd := NewRootCommand()
buf := new(strings.Builder)
cmd.SetOut(buf)
cmd.SetErr(buf)
log.SetOutput(ioutil.Discard)
defer func() { log.SetOutput(os.Stdout) }()
hook := test.NewGlobal()
defer hook.Reset()
args := append(tt.Cmd, []string{
"--log-level", "debug",
"--kubeconfig-path", kubeconfigPath,
"--aws-partitions", strings.Join(tt.Partitions, ","),
}...)

cmd.SetArgs(args)
err = cmd.Execute()
if err != nil {
t.Error(err.Error())
}

expectedLogs := make(map[string]bool)
for _, region := range aws.GetRegions(tt.Partitions) {
expectedLogs[region] = false
}
for _, e := range hook.AllEntries() {
if v, ok := e.Data["region"]; ok {
expectedLogs[fmt.Sprintf("%v", v)] = true
}
}

for k, v := range expectedLogs {
if !v {
t.Errorf("Could not find log for %v", k)
}
}
})
}
}
39 changes: 16 additions & 23 deletions cmd/aws_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
package cmd

import (
"bytes"
"fmt"
"html/template"
"io"
"os"
"path"
"path/filepath"

"github.com/mateimicu/kdiscover/internal"
"github.com/mateimicu/kdiscover/internal/aws"
"github.com/mateimicu/kdiscover/internal/kubeconfig"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -42,7 +41,7 @@ func newUpdateCommand() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
cmd.Println(cmd.Short)

remoteEKSClusters := internal.GetEKSClusters(awsRegions)
remoteEKSClusters := aws.GetEKSClusters(awsRegions)
log.Info(remoteEKSClusters)

cmd.Printf("Found %v clusters remote\n", len(remoteEKSClusters))
Expand All @@ -54,11 +53,22 @@ func newUpdateCommand() *cobra.Command {
}
cmd.Printf("Backup kubeconfig to %v\n", bName)
}

err := internal.UpdateKubeconfig(remoteEKSClusters, kubeconfigPath, contextName{templateValue: alias})
kubeconfig, err := kubeconfig.LoadKubeconfig(kubeconfigPath)
if err != nil {
return err
}

for _, cls := range remoteEKSClusters {
ctxName, err := cls.PrettyName(alias)
if err != nil {
log.WithFields(log.Fields{
"cluster": cls,
"error": err,
}).Info("Can't generate alias for the cluster")
continue
}
kubeconfig.AddCluster(cls, ctxName)
}
return nil
},
}
Expand All @@ -73,23 +83,6 @@ func newUpdateCommand() *cobra.Command {
return updateCommand
}

type contextName struct {
templateValue string
}

func (c contextName) GetContextName(cls internal.Cluster) (string, error) {
tmpl, err := template.New("context-name").Parse(c.templateValue)
if err != nil {
return "", err
}
var tpl bytes.Buffer
err = tmpl.Execute(&tpl, cls)
if err != nil {
return "", err
}
return tpl.String(), nil
}

func copy(src, dst string) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
Expand Down
12 changes: 8 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"io/ioutil"
"os"

"github.com/mateimicu/kdiscover/internal"
"github.com/mateimicu/kdiscover/internal/kubeconfig"
"github.com/spf13/cobra"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -48,7 +48,7 @@ It will try to upgrade the kube-config for each cluster.`,
return nil
}

return fmt.Errorf("Can't find logging level %v", logLevel)
return fmt.Errorf("can't find logging level %v", logLevel)
},

RunE: func(cmd *cobra.Command, args []string) error {
Expand All @@ -57,12 +57,16 @@ It will try to upgrade the kube-config for each cluster.`,
},
}

rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "none", fmt.Sprintf("Set logging lvl. Supported %v", getAllLogglingLevels()))
rootCmd.PersistentFlags().StringVar(
&logLevel,
"log-level",
"none",
fmt.Sprintf("Set logging lvl. Supported %v", getAllLogglingLevels()))

rootCmd.PersistentFlags().StringVar(
&kubeconfigPath,
"kubeconfig-path",
internal.GetDefaultKubeconfigPath(),
kubeconfig.GetDefaultKubeconfigPath(),
"Path to the kubeconfig to work with")

rootCmd.AddCommand(newAWSCommand())
Expand Down
Loading

0 comments on commit 040d9fc

Please sign in to comment.