Skip to content

Commit

Permalink
mesheryctl - Group commands into categories
Browse files Browse the repository at this point in the history
  • Loading branch information
nitishm committed May 18, 2020
1 parent 9f4d8f9 commit 27dac1d
Show file tree
Hide file tree
Showing 15 changed files with 235 additions and 150 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@ Gemfile.lock
docs/Gemfile.lock

yarn.lock

**/_output
4 changes: 2 additions & 2 deletions mesheryctl/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ GCFLAGS :=
.PHONY: $(BINNAME_DARWIN)
$(BINNAME_DARWIN):
@echo
CGO_ENABLED=0 GOARCH=$(ARCH) GOOS=darwin GO111MODULE=on go build -ldflags='$(LDFLAGS)' -gcflags='$(GCFLAGS)' -o $(OUTDIR)/$(BINNAME_DARWIN) ./main.go
CGO_ENABLED=0 GOARCH=$(ARCH) GOOS=darwin GO111MODULE=on go build -ldflags='$(LDFLAGS)' -gcflags='$(GCFLAGS)' -o $(OUTDIR)/$(BINNAME_DARWIN) ./cmd/mesheryctl/main.go

.PHONY: $(BINNAME_LINUX)
$(BINNAME_LINUX):
@echo
CGO_ENABLED=0 GOARCH=$(ARCH) GOOS=linux GO111MODULE=on go build -ldflags='$(LDFLAGS)' -gcflags='$(GCFLAGS)' -o $(OUTDIR)/$(BINNAME_LINUX) ./main.go
CGO_ENABLED=0 GOARCH=$(ARCH) GOOS=linux GO111MODULE=on go build -ldflags='$(LDFLAGS)' -gcflags='$(GCFLAGS)' -o $(OUTDIR)/$(BINNAME_LINUX) ./cmd/mesheryctl/main.go

.PHONY: $(BINNAME_WINDOWS)
$(BINNAME_WINDOWS):
Expand Down
14 changes: 0 additions & 14 deletions mesheryctl/cmd/helpers.go

This file was deleted.

10 changes: 5 additions & 5 deletions mesheryctl/main.go → mesheryctl/cmd/mesheryctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
package main

import (
"github.com/layer5io/meshery/mesheryctl/cmd"
"github.com/layer5io/meshery/mesheryctl/internal/cli/root"
)

var version = "dev"
var commitsha = "SHA"

func main() {
cmd.BuildClient = version
cmd.BuildServer = version
cmd.CommitSHA = commitsha
cmd.Execute()
root.BuildClient = version
root.BuildServer = version
root.CommitSHA = commitsha
root.Execute()
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd
package perf

import (
"bytes"
Expand All @@ -24,6 +24,8 @@ import (
"os"
"time"

"github.com/layer5io/meshery/mesheryctl/pkg/utils"

"github.com/layer5io/meshery/models"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
Expand All @@ -32,6 +34,11 @@ import (
"github.com/spf13/cobra"
)

const (
mesheryAuthToken = "http://localhost:9081/api/gettoken"
mesheryURL = "http://localhost:9081/api/load-test-smps?"
)

var (
testURL = ""
testName = ""
Expand Down Expand Up @@ -122,7 +129,7 @@ func UpdateAuthDetails(filepath string) error {

client := &http.Client{}
resp, err := client.Do(req)
defer SafeClose(resp.Body)
defer utils.SafeClose(resp.Body)

if err != nil {
return err
Expand All @@ -136,14 +143,20 @@ func UpdateAuthDetails(filepath string) error {
return ioutil.WriteFile(filepath, data, os.ModePerm)
}

// perfCmd represents the Performance command
var perfCmd = &cobra.Command{
// PerfCmd represents the Performance command
var PerfCmd = &cobra.Command{
Use: "perf",
Short: "Performance Testing",
Long: `Performance Testing & Benchmarking using Meshery CLI.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Print(perfDetails)
return
}

//Check prerequisite
preReqCheck()
utils.PreReqCheck()

// Importing SMPS Configuration from the file
if filePath != "" {
Expand Down Expand Up @@ -237,7 +250,7 @@ var perfCmd = &cobra.Command{
log.Print("Initiating Performance test ...")
log.Printf(resp.Status)

defer SafeClose(resp.Body)
defer utils.SafeClose(resp.Body)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading body: %v", err.Error())
Expand All @@ -255,14 +268,13 @@ var perfCmd = &cobra.Command{
}

func init() {
perfCmd.Flags().StringVar(&testURL, "url", "", "(required) Endpoint URL to test")
perfCmd.Flags().StringVar(&testName, "name", "", "(optional) Name of the Test")
perfCmd.Flags().StringVar(&testMesh, "mesh", "", "(optional) Name of the Service Mesh")
perfCmd.Flags().StringVar(&qps, "qps", "0", "(optional) Queries per second")
perfCmd.Flags().StringVar(&concurrentRequests, "concurrent-requests", "1", "(optional) Number of Parallel Requests")
perfCmd.Flags().StringVar(&testDuration, "duration", "30s", "(optional) Length of test (e.g. 10s, 5m, 2h). For more, see https://golang.org/pkg/time/#ParseDuration")
perfCmd.Flags().StringVar(&tokenPath, "token", authConfigFile, "(optional) Path to meshery auth config")
perfCmd.Flags().StringVar(&loadGenerator, "load-generator", "fortio", "(optional) Load-Generator to be used (fortio/wrk2)")
perfCmd.Flags().StringVar(&filePath, "file", "", "(optional) file containing SMPS-compatible test configuration. For more, see https://github.com/layer5io/service-mesh-performance-specification")
rootCmd.AddCommand(perfCmd)
PerfCmd.Flags().StringVar(&testURL, "url", "", "(required) Endpoint URL to test")
PerfCmd.Flags().StringVar(&testName, "name", "", "(optional) Name of the Test")
PerfCmd.Flags().StringVar(&testMesh, "mesh", "", "(optional) Name of the Service Mesh")
PerfCmd.Flags().StringVar(&qps, "qps", "0", "(optional) Queries per second")
PerfCmd.Flags().StringVar(&concurrentRequests, "concurrent-requests", "1", "(optional) Number of Parallel Requests")
PerfCmd.Flags().StringVar(&testDuration, "duration", "30s", "(optional) Length of test (e.g. 10s, 5m, 2h). For more, see https://golang.org/pkg/time/#ParseDuration")
PerfCmd.Flags().StringVar(&tokenPath, "token", utils.AuthConfigFile, "(optional) Path to meshery auth config")
PerfCmd.Flags().StringVar(&loadGenerator, "load-generator", "fortio", "(optional) Load-Generator to be used (fortio/wrk2)")
PerfCmd.Flags().StringVar(&filePath, "file", "", "(optional) file containing SMPS-compatible test configuration. For more, see https://github.com/layer5io/service-mesh-performance-specification")
}
66 changes: 43 additions & 23 deletions mesheryctl/cmd/root.go → mesheryctl/internal/cli/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd
package root

import (
"errors"
"fmt"

"github.com/layer5io/meshery/mesheryctl/internal/cli/root/perf"
"github.com/layer5io/meshery/mesheryctl/internal/cli/root/system"

"github.com/layer5io/meshery/mesheryctl/pkg/utils"

log "github.com/sirupsen/logrus"

"github.com/spf13/cobra"
Expand All @@ -35,18 +41,14 @@ Usage:
mesheryctl [command]
Available Commands:
cleanup Clean up Meshery
help Help about any command
logs Print logs
perf Performance Management: testing and benchmarking
start Start Meshery
status Check Meshery status
stop Stop Meshery
update Pull new Meshery images from Docker Hub
perf Performance Testing
system System level actions
version Version of mesheryctl
Flags:
--config string config file (default location is: $HOME/.meshery/` + dockerComposeFile + `)
--config string config file (default location is: $HOME/.meshery/` + utils.DockerComposeFile + `)
-h, --help help for mesheryctl
-v, --version Version of mesheryctl
Expand All @@ -58,50 +60,68 @@ func (f *TerminalFormatter) Format(entry *log.Entry) ([]byte, error) {
return append([]byte(entry.Message), '\n'), nil
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
var (
availableSubcommands = []*cobra.Command{}
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "mesheryctl",
Short: "Meshery Command Line tool",
Long: `Meshery is the service mesh management plane, providing lifecycle, performance, and configuration management of service meshes and their workloads.`,
Args: cobra.MinimumNArgs(1),
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
b, _ := cmd.Flags().GetBool("version")
if b {
versionCmd.Run(nil, nil)
return
return nil
}
if len(args) == 0 {
log.Print(cmdDetails)

for _, subcommand := range availableSubcommands {
if args[0] == subcommand.Name() {
return nil
}
}

return errors.New("sub-command not found : " + "\"" + args[0] + "\"")
},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
// This is called by main.main(). It only needs to happen once to the RootCmd.
func Execute() {
//log formatter for improved UX
log.SetFormatter(new(TerminalFormatter))
if err := rootCmd.Execute(); err != nil {
if err := RootCmd.Execute(); err != nil {
log.Fatalf("fatal err %v", err)
}
}

func init() {
setFileLocation() //from vars.go
utils.SetFileLocation() //from vars.go
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default location is: "+dockerComposeFile+")")
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default location is: "+utils.DockerComposeFile+")")

// Preparing for an "edge" channel
// rootCmd.PersistentFlags().StringVar(&cfgFile, "edge", "", "flag to run Meshery as edge (one-time)")
// RootCmd.PersistentFlags().StringVar(&cfgFile, "edge", "", "flag to run Meshery as edge (one-time)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("version", "v", false, "Version flag")
RootCmd.Flags().BoolP("version", "v", false, "Version flag")

availableSubcommands = []*cobra.Command{
versionCmd,
system.SystemCmd,
perf.PerfCmd,
}

RootCmd.AddCommand(availableSubcommands...)
}

// initConfig reads in config file and ENV variables if set.
Expand All @@ -111,8 +131,8 @@ func initConfig() {
viper.SetConfigFile(cfgFile)
} else {
// Use default ".meshery" folder location.
viper.AddConfigPath(mesheryFolder)
log.Debug("initConfig: ", mesheryFolder)
viper.AddConfigPath(utils.MesheryFolder)
log.Debug("initConfig: ", utils.MesheryFolder)
viper.SetConfigName("config.yaml")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd
package system

import (
"github.com/layer5io/meshery/mesheryctl/pkg/utils"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
Expand All @@ -24,20 +25,17 @@ var cleanupCmd = &cobra.Command{
Use: "cleanup",
Short: "Cleanup Meshery's configuration",
Long: `Reset Meshery to it's default configuration.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
resetMesheryConfig()
},
}

func init() {
rootCmd.AddCommand(cleanupCmd)
}

// resets meshery config
func resetMesheryConfig() {
log.Info("Meshery resetting...")
if err := downloadFile(dockerComposeFile, fileURL); err != nil {
if err := utils.DownloadFile(utils.DockerComposeFile, fileURL); err != nil {
log.Fatal("Error while resetting:", err)
}
log.Info("Meshery config (" + dockerComposeFile + ") settings reset to defaults.")
log.Info("Meshery config (" + utils.DockerComposeFile + ") settings reset to defaults.")
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd
package system

import (
"bufio"
"fmt"
"os"
"os/exec"

"github.com/layer5io/meshery/mesheryctl/pkg/utils"

log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
Expand All @@ -29,21 +31,22 @@ var logsCmd = &cobra.Command{
Use: "logs",
Short: "Print logs",
Long: `Print history of Meshery's container logs and begin tailing them.`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
if ok := isMesheryRunning(); !ok {
if ok := utils.IsMesheryRunning(); !ok {
log.Error("No logs to show. Meshery is not running.")
return
}

log.Info("Starting Meshery logging...")

if _, err := os.Stat(dockerComposeFile); os.IsNotExist(err) {
if err := downloadFile(dockerComposeFile, fileURL); err != nil {
if _, err := os.Stat(utils.DockerComposeFile); os.IsNotExist(err) {
if err := utils.DownloadFile(utils.DockerComposeFile, fileURL); err != nil {
log.Fatal("start cmd: ", err)
}
}

cmdlog := exec.Command("docker-compose", "-f", dockerComposeFile, "logs", "-f")
cmdlog := exec.Command("docker-compose", "-f", utils.DockerComposeFile, "logs", "-f")
cmdReader, err := cmdlog.StdoutPipe()
if err != nil {
log.Fatal(err)
Expand All @@ -62,7 +65,3 @@ var logsCmd = &cobra.Command{
}
},
}

func init() {
rootCmd.AddCommand(logsCmd)
}
Loading

0 comments on commit 27dac1d

Please sign in to comment.