From eae5c34e40615446472347399742f65af5b723e2 Mon Sep 17 00:00:00 2001 From: guoxudong Date: Wed, 15 Jan 2020 10:30:37 +0800 Subject: [PATCH] add cli command server status --- cli/cmd/cmd.go | 1 + cli/cmd/server_status.go | 58 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 cli/cmd/server_status.go diff --git a/cli/cmd/cmd.go b/cli/cmd/cmd.go index 54cd07e0..a2a2def3 100644 --- a/cli/cmd/cmd.go +++ b/cli/cmd/cmd.go @@ -60,6 +60,7 @@ func CmdInit() *baseCommand { baseCmd.AddCommand(serverCommand) serverCommand.AddCommand(&StartServerCommand{}) serverCommand.AddCommand(&StopServerCommand{}) + serverCommand.AddCommand(&StatusServerCommand{}) return baseCmd } diff --git a/cli/cmd/server_status.go b/cli/cmd/server_status.go new file mode 100644 index 00000000..d7bc907f --- /dev/null +++ b/cli/cmd/server_status.go @@ -0,0 +1,58 @@ +package cmd + +import ( + "context" + "fmt" + "strings" + + "github.com/chaosblade-io/chaosblade-spec-go/channel" + "github.com/chaosblade-io/chaosblade-spec-go/spec" + "github.com/spf13/cobra" +) + +type StatusServerCommand struct { + baseCommand +} + +func (ssc *StatusServerCommand) Init() { + ssc.command = &cobra.Command{ + Use: "status", + Short: "Prints out the status of blade server", + Long: "Prints out the status of blade server", + Aliases: []string{"s"}, + RunE: func(cmd *cobra.Command, args []string) error { + return ssc.run(cmd, args) + }, + Example: statusServerExample(), + } +} + +func (ssc *StatusServerCommand) run(cmd *cobra.Command, args []string) error { + // check if the process named `blade server --start` exists or not + pids, err := channel.GetPidsByProcessName(startServerKey, context.TODO()) + if err != nil { + return spec.ReturnFail(spec.Code[spec.ServerError], err.Error()) + } + if len(pids) != 0 { + data := map[string]string{ + "status": "up", + "port": "", + } + response := channel.NewLocalChannel().Run(context.TODO(), "ps", fmt.Sprintf("-p %s | grep port", strings.Join(pids, " "))) + fmtStrs := strings.Split(strings.Replace(fmt.Sprintf("%v", response.Result), "\n", "", -1), " ") + for i, p := range fmtStrs { + if p == "--port" { + data["port"] = fmtStrs[i+1] + } + } + response = spec.ReturnSuccess(data) + ssc.command.Println(response.Print()) + } else { + return spec.ReturnFail(spec.Code[spec.ServerError], "down") + } + return nil +} + +func statusServerExample() string { + return `blade server status` +}