From f937087319c11cca5e5295d0183055b2e8f3a9de Mon Sep 17 00:00:00 2001 From: mustard Date: Wed, 1 Jun 2022 11:58:48 +0000 Subject: [PATCH 1/2] [gp-cli] move cmd files --- components/gitpod-cli/cmd/ports-list.go | 94 +++++++++++++ components/gitpod-cli/cmd/ports.go | 8 -- components/gitpod-cli/cmd/ports/ports-list.go | 86 ------------ components/gitpod-cli/cmd/tasks-attach.go | 125 ++++++++++++++++++ components/gitpod-cli/cmd/tasks-list.go | 59 +++++++++ components/gitpod-cli/cmd/tasks.go | 27 ---- .../gitpod-cli/cmd/tasks/tasks-attach.go | 107 --------------- components/gitpod-cli/cmd/tasks/tasks-list.go | 50 ------- 8 files changed, 278 insertions(+), 278 deletions(-) create mode 100644 components/gitpod-cli/cmd/ports-list.go delete mode 100644 components/gitpod-cli/cmd/ports/ports-list.go create mode 100644 components/gitpod-cli/cmd/tasks-attach.go create mode 100644 components/gitpod-cli/cmd/tasks-list.go delete mode 100644 components/gitpod-cli/cmd/tasks/tasks-attach.go delete mode 100644 components/gitpod-cli/cmd/tasks/tasks-list.go diff --git a/components/gitpod-cli/cmd/ports-list.go b/components/gitpod-cli/cmd/ports-list.go new file mode 100644 index 00000000000000..6d67914e23ff9f --- /dev/null +++ b/components/gitpod-cli/cmd/ports-list.go @@ -0,0 +1,94 @@ +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. +// Licensed under the GNU Affero General Public License (AGPL). +// See License-AGPL.txt in the project root for license information. + +package cmd + +import ( + "context" + "fmt" + "os" + "sort" + "time" + + "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" + "github.com/gitpod-io/gitpod/supervisor/api" + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" + + "github.com/olekukonko/tablewriter" +) + +var listPortsCmd = &cobra.Command{ + Use: "list", + Short: "Lists the workspace ports and their states.", + Run: func(*cobra.Command, []string) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + conn := supervisor.Dial() + client := api.NewStatusServiceClient(conn) + + ports, portsListError := supervisor.GetPortsList(ctx, client) + + if portsListError != nil { + log.WithError(portsListError).Error("Could not get the ports list.") + return + } + + if len(ports) == 0 { + fmt.Println("No ports detected.") + return + } + + sort.Slice(ports, func(i, j int) bool { + return int(ports[i].LocalPort) < int(ports[j].LocalPort) + }) + + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Port", "Status", "URL", "Name & Description"}) + table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) + table.SetCenterSeparator("|") + + for _, port := range ports { + status := "not served" + statusColor := tablewriter.FgHiBlackColor + if port.Exposed == nil && port.Tunneled == nil { + if port.AutoExposure == api.PortAutoExposure_failed { + status = "failed to expose" + statusColor = tablewriter.FgRedColor + } else { + status = "detecting..." + statusColor = tablewriter.FgYellowColor + } + } else if port.Served { + status = "open (" + port.Exposed.Visibility.String() + ")" + if port.Exposed.Visibility == api.PortVisibility_public { + statusColor = tablewriter.FgHiGreenColor + } else { + statusColor = tablewriter.FgHiCyanColor + } + } + + nameAndDescription := port.Name + if len(port.Description) > 0 { + if len(nameAndDescription) > 0 { + nameAndDescription = fmt.Sprint(nameAndDescription, ": ", port.Description) + } else { + nameAndDescription = port.Description + } + } + + table.Rich( + []string{fmt.Sprint(port.LocalPort), status, port.Exposed.Url, nameAndDescription}, + []tablewriter.Colors{{}, {statusColor}, {}, {}}, + ) + } + + table.Render() + }, +} + +func init() { + portsCmd.AddCommand(listPortsCmd) +} diff --git a/components/gitpod-cli/cmd/ports.go b/components/gitpod-cli/cmd/ports.go index 6086c1c01df954..ce370074f11b01 100644 --- a/components/gitpod-cli/cmd/ports.go +++ b/components/gitpod-cli/cmd/ports.go @@ -5,7 +5,6 @@ package cmd import ( - "github.com/gitpod-io/gitpod/gitpod-cli/cmd/ports" "github.com/spf13/cobra" ) @@ -19,13 +18,6 @@ var portsCmd = &cobra.Command{ }, } -var listPortsCmd = &cobra.Command{ - Use: "list", - Short: "Lists the workspace ports and their states.", - Run: ports.ListPortsCmd, -} - func init() { rootCmd.AddCommand(portsCmd) - portsCmd.AddCommand(listPortsCmd) } diff --git a/components/gitpod-cli/cmd/ports/ports-list.go b/components/gitpod-cli/cmd/ports/ports-list.go deleted file mode 100644 index 682f8c1fe3107b..00000000000000 --- a/components/gitpod-cli/cmd/ports/ports-list.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2022 Gitpod GmbH. All rights reserved. -// Licensed under the GNU Affero General Public License (AGPL). -// See License-AGPL.txt in the project root for license information. - -package ports - -import ( - "context" - "fmt" - "os" - "sort" - "time" - - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" - "github.com/gitpod-io/gitpod/supervisor/api" - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - - "github.com/olekukonko/tablewriter" -) - -func ListPortsCmd(*cobra.Command, []string) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - conn := supervisor.Dial() - client := api.NewStatusServiceClient(conn) - - ports, portsListError := supervisor.GetPortsList(ctx, client) - - if portsListError != nil { - log.WithError(portsListError).Error("Could not get the ports list.") - return - } - - if len(ports) == 0 { - fmt.Println("No ports detected.") - return - } - - sort.Slice(ports, func(i, j int) bool { - return int(ports[i].LocalPort) < int(ports[j].LocalPort) - }) - - table := tablewriter.NewWriter(os.Stdout) - table.SetHeader([]string{"Port", "Status", "URL", "Name & Description"}) - table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) - table.SetCenterSeparator("|") - - for _, port := range ports { - status := "not served" - statusColor := tablewriter.FgHiBlackColor - if port.Exposed == nil && port.Tunneled == nil { - if port.AutoExposure == api.PortAutoExposure_failed { - status = "failed to expose" - statusColor = tablewriter.FgRedColor - } else { - status = "detecting..." - statusColor = tablewriter.FgYellowColor - } - } else if port.Served { - status = "open (" + port.Exposed.Visibility.String() + ")" - if port.Exposed.Visibility == api.PortVisibility_public { - statusColor = tablewriter.FgHiGreenColor - } else { - statusColor = tablewriter.FgHiCyanColor - } - } - - nameAndDescription := port.Name - if len(port.Description) > 0 { - if len(nameAndDescription) > 0 { - nameAndDescription = fmt.Sprint(nameAndDescription, ": ", port.Description) - } else { - nameAndDescription = port.Description - } - } - - table.Rich( - []string{fmt.Sprint(port.LocalPort), status, port.Exposed.Url, nameAndDescription}, - []tablewriter.Colors{{}, {statusColor}, {}, {}}, - ) - } - - table.Render() -} diff --git a/components/gitpod-cli/cmd/tasks-attach.go b/components/gitpod-cli/cmd/tasks-attach.go new file mode 100644 index 00000000000000..55b32ef8a52c28 --- /dev/null +++ b/components/gitpod-cli/cmd/tasks-attach.go @@ -0,0 +1,125 @@ +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. +// Licensed under the GNU Affero General Public License (AGPL). +// See License-AGPL.txt in the project root for license information. + +package cmd + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" + "github.com/gitpod-io/gitpod/supervisor/api" + "github.com/manifoldco/promptui" + "github.com/spf13/cobra" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +var attachTaskCmdOpts struct { + Interactive bool + ForceResize bool +} + +// attachTaskCmd represents the attach task command +var attachTaskCmd = &cobra.Command{ + Use: "attach ", + Short: "Attach to a workspace task", + Args: cobra.MaximumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + var terminalAlias string + + conn := supervisor.Dial() + + if len(args) > 0 { + terminalAlias = args[0] + } else { + statusClient := api.NewStatusServiceClient(conn) + stateToFilter := api.TaskState(api.TaskState_value["running"]) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + tasks := supervisor.GetTasksListByState(ctx, statusClient, stateToFilter) + + if len(tasks) == 0 { + fmt.Println("There are no running tasks") + return + } + + var taskNames []string + var taskIndex int + + if len(tasks) == 1 { + taskIndex = 0 + } else { + + for _, task := range tasks { + taskNames = append(taskNames, task.Presentation.Name) + } + + prompt := promptui.Select{ + Label: "What task do you want attach to?", + Items: taskNames, + Templates: &promptui.SelectTemplates{ + Selected: "Attaching to task: {{ . }}", + }, + } + + selectedIndex, selectedValue, err := prompt.Run() + + if selectedValue == "" { + return + } + + if err != nil { + panic(err) + } + + taskIndex = selectedIndex + } + + terminalAlias = tasks[taskIndex].Terminal + } + + terminalClient := api.NewTerminalServiceClient(conn) + + terminal, err := terminalClient.Get(context.Background(), &api.GetTerminalRequest{Alias: terminalAlias}) + if err != nil { + if e, ok := status.FromError(err); ok { + switch e.Code() { + case codes.NotFound: + fmt.Println("Terminal is inactive:", terminalAlias) + default: + fmt.Println(e.Code(), e.Message()) + } + return + } else { + panic(err) + } + } + ppid := int64(os.Getppid()) + + if ppid == terminal.Pid { + fmt.Println("You are already in terminal:", terminalAlias) + return + } + + interactive, _ := cmd.Flags().GetBool("interactive") + forceResize, _ := cmd.Flags().GetBool("force-resize") + + supervisor.AttachToTerminal(context.Background(), terminalClient, terminalAlias, supervisor.AttachToTerminalOpts{ + ForceResize: forceResize, + Interactive: interactive, + }) + }, +} + +func init() { + tasksCmd.AddCommand(attachTaskCmd) + + attachTaskCmd.Flags().BoolVarP(&attachTaskCmdOpts.Interactive, "interactive", "i", true, "assume control over the terminal") + attachTaskCmd.Flags().BoolVarP(&attachTaskCmdOpts.ForceResize, "force-resize", "r", true, "force this terminal's size irregardless of other clients") +} diff --git a/components/gitpod-cli/cmd/tasks-list.go b/components/gitpod-cli/cmd/tasks-list.go new file mode 100644 index 00000000000000..4a7d09ff567c30 --- /dev/null +++ b/components/gitpod-cli/cmd/tasks-list.go @@ -0,0 +1,59 @@ +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. +// Licensed under the GNU Affero General Public License (AGPL). +// See License-AGPL.txt in the project root for license information. + +package cmd + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" + "github.com/gitpod-io/gitpod/supervisor/api" + "github.com/spf13/cobra" + + "github.com/olekukonko/tablewriter" +) + +// listTasksCmd represents the tasks list command +var listTasksCmd = &cobra.Command{ + Use: "list", + Short: "Lists the workspace tasks and their state", + Run: func(cmd *cobra.Command, args []string) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + conn := supervisor.Dial() + client := api.NewStatusServiceClient(conn) + + tasks := supervisor.GetTasksList(ctx, client) + + if len(tasks) == 0 { + fmt.Println("No tasks detected") + return + } + + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Terminal ID", "Name", "State"}) + table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) + table.SetCenterSeparator("|") + + mapStatusToColor := map[api.TaskState]int{ + 0: tablewriter.FgHiGreenColor, + 1: tablewriter.FgHiGreenColor, + 2: tablewriter.FgHiBlackColor, + } + + for _, task := range tasks { + table.Rich([]string{task.Terminal, task.Presentation.Name, task.State.String()}, []tablewriter.Colors{{}, {}, {mapStatusToColor[task.State]}}) + } + + table.Render() + }, +} + +func init() { + tasksCmd.AddCommand(listTasksCmd) +} diff --git a/components/gitpod-cli/cmd/tasks.go b/components/gitpod-cli/cmd/tasks.go index 5c2fe658696eca..135e6b3875324b 100644 --- a/components/gitpod-cli/cmd/tasks.go +++ b/components/gitpod-cli/cmd/tasks.go @@ -5,7 +5,6 @@ package cmd import ( - "github.com/gitpod-io/gitpod/gitpod-cli/cmd/tasks" "github.com/spf13/cobra" ) @@ -20,32 +19,6 @@ var tasksCmd = &cobra.Command{ }, } -var attachTaskCmdOpts struct { - Interactive bool - ForceResize bool -} - -// listTasksCmd represents the tasks list command -var listTasksCmd = &cobra.Command{ - Use: "list", - Short: "Lists the workspace tasks and their state", - Run: tasks.ListTasksCmd, -} - -// attachTaskCmd represents the attach task command -var attachTaskCmd = &cobra.Command{ - Use: "attach ", - Short: "Attach to a workspace task", - Args: cobra.MaximumNArgs(1), - Run: tasks.AttachTasksCmd, -} - func init() { rootCmd.AddCommand(tasksCmd) - - tasksCmd.AddCommand(listTasksCmd) - tasksCmd.AddCommand(attachTaskCmd) - - attachTaskCmd.Flags().BoolVarP(&attachTaskCmdOpts.Interactive, "interactive", "i", true, "assume control over the terminal") - attachTaskCmd.Flags().BoolVarP(&attachTaskCmdOpts.ForceResize, "force-resize", "r", true, "force this terminal's size irregardless of other clients") } diff --git a/components/gitpod-cli/cmd/tasks/tasks-attach.go b/components/gitpod-cli/cmd/tasks/tasks-attach.go deleted file mode 100644 index c951613dd51f1b..00000000000000 --- a/components/gitpod-cli/cmd/tasks/tasks-attach.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2022 Gitpod GmbH. All rights reserved. -// Licensed under the GNU Affero General Public License (AGPL). -// See License-AGPL.txt in the project root for license information. - -package tasks - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" - "github.com/gitpod-io/gitpod/supervisor/api" - "github.com/manifoldco/promptui" - "github.com/spf13/cobra" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func AttachTasksCmd(cmd *cobra.Command, args []string) { - var terminalAlias string - - conn := supervisor.Dial() - - if len(args) > 0 { - terminalAlias = args[0] - } else { - statusClient := api.NewStatusServiceClient(conn) - stateToFilter := api.TaskState(api.TaskState_value["running"]) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - tasks := supervisor.GetTasksListByState(ctx, statusClient, stateToFilter) - - if len(tasks) == 0 { - fmt.Println("There are no running tasks") - return - } - - var taskNames []string - var taskIndex int - - if len(tasks) == 1 { - taskIndex = 0 - } else { - - for _, task := range tasks { - taskNames = append(taskNames, task.Presentation.Name) - } - - prompt := promptui.Select{ - Label: "What task do you want attach to?", - Items: taskNames, - Templates: &promptui.SelectTemplates{ - Selected: "Attaching to task: {{ . }}", - }, - } - - selectedIndex, selectedValue, err := prompt.Run() - - if selectedValue == "" { - return - } - - if err != nil { - panic(err) - } - - taskIndex = selectedIndex - } - - terminalAlias = tasks[taskIndex].Terminal - } - - terminalClient := api.NewTerminalServiceClient(conn) - - terminal, err := terminalClient.Get(context.Background(), &api.GetTerminalRequest{Alias: terminalAlias}) - if err != nil { - if e, ok := status.FromError(err); ok { - switch e.Code() { - case codes.NotFound: - fmt.Println("Terminal is inactive:", terminalAlias) - default: - fmt.Println(e.Code(), e.Message()) - } - return - } else { - panic(err) - } - } - ppid := int64(os.Getppid()) - - if ppid == terminal.Pid { - fmt.Println("You are already in terminal:", terminalAlias) - return - } - - interactive, _ := cmd.Flags().GetBool("interactive") - forceResize, _ := cmd.Flags().GetBool("force-resize") - - supervisor.AttachToTerminal(context.Background(), terminalClient, terminalAlias, supervisor.AttachToTerminalOpts{ - ForceResize: forceResize, - Interactive: interactive, - }) -} diff --git a/components/gitpod-cli/cmd/tasks/tasks-list.go b/components/gitpod-cli/cmd/tasks/tasks-list.go deleted file mode 100644 index db95fccbef514b..00000000000000 --- a/components/gitpod-cli/cmd/tasks/tasks-list.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2022 Gitpod GmbH. All rights reserved. -// Licensed under the GNU Affero General Public License (AGPL). -// See License-AGPL.txt in the project root for license information. - -package tasks - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" - "github.com/gitpod-io/gitpod/supervisor/api" - "github.com/spf13/cobra" - - "github.com/olekukonko/tablewriter" -) - -func ListTasksCmd(cmd *cobra.Command, args []string) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - conn := supervisor.Dial() - client := api.NewStatusServiceClient(conn) - - tasks := supervisor.GetTasksList(ctx, client) - - if len(tasks) == 0 { - fmt.Println("No tasks detected") - return - } - - table := tablewriter.NewWriter(os.Stdout) - table.SetHeader([]string{"Terminal ID", "Name", "State"}) - table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) - table.SetCenterSeparator("|") - - mapStatusToColor := map[api.TaskState]int{ - 0: tablewriter.FgHiGreenColor, - 1: tablewriter.FgHiGreenColor, - 2: tablewriter.FgHiBlackColor, - } - - for _, task := range tasks { - table.Rich([]string{task.Terminal, task.Presentation.Name, task.State.String()}, []tablewriter.Colors{{}, {}, {mapStatusToColor[task.State]}}) - } - - table.Render() -} From be78308a4bcd466d38e41da2c7344da386ee24b7 Mon Sep 17 00:00:00 2001 From: mustard Date: Wed, 1 Jun 2022 12:21:25 +0000 Subject: [PATCH 2/2] [gp-cli] refactor cmd tasks and ports supervisor related func --- components/gitpod-cli/cmd/ports-list.go | 13 ++--- components/gitpod-cli/cmd/tasks-attach.go | 24 ++++---- components/gitpod-cli/cmd/tasks-list.go | 11 ++-- .../ports.go | 14 +++-- .../pkg/supervisor-helper/status-tasks.go | 43 ++++++++++++++ .../pkg/supervisor-helper/supervisor.go | 26 +++++++++ .../terminal-attach.go | 29 ++++++---- .../gitpod-cli/pkg/supervisor/status-tasks.go | 56 ------------------- .../gitpod-cli/pkg/supervisor/supervisor.go | 25 --------- 9 files changed, 122 insertions(+), 119 deletions(-) rename components/gitpod-cli/pkg/{supervisor => supervisor-helper}/ports.go (63%) create mode 100644 components/gitpod-cli/pkg/supervisor-helper/status-tasks.go create mode 100644 components/gitpod-cli/pkg/supervisor-helper/supervisor.go rename components/gitpod-cli/pkg/{supervisor => supervisor-helper}/terminal-attach.go (72%) delete mode 100644 components/gitpod-cli/pkg/supervisor/status-tasks.go delete mode 100644 components/gitpod-cli/pkg/supervisor/supervisor.go diff --git a/components/gitpod-cli/cmd/ports-list.go b/components/gitpod-cli/cmd/ports-list.go index 6d67914e23ff9f..2896dd3e1ec8c3 100644 --- a/components/gitpod-cli/cmd/ports-list.go +++ b/components/gitpod-cli/cmd/ports-list.go @@ -11,8 +11,8 @@ import ( "sort" "time" - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" - "github.com/gitpod-io/gitpod/supervisor/api" + supervisor_helper "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor-helper" + supervisor "github.com/gitpod-io/gitpod/supervisor/api" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -26,10 +26,7 @@ var listPortsCmd = &cobra.Command{ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - conn := supervisor.Dial() - client := api.NewStatusServiceClient(conn) - - ports, portsListError := supervisor.GetPortsList(ctx, client) + ports, portsListError := supervisor_helper.GetPortsList(ctx) if portsListError != nil { log.WithError(portsListError).Error("Could not get the ports list.") @@ -54,7 +51,7 @@ var listPortsCmd = &cobra.Command{ status := "not served" statusColor := tablewriter.FgHiBlackColor if port.Exposed == nil && port.Tunneled == nil { - if port.AutoExposure == api.PortAutoExposure_failed { + if port.AutoExposure == supervisor.PortAutoExposure_failed { status = "failed to expose" statusColor = tablewriter.FgRedColor } else { @@ -63,7 +60,7 @@ var listPortsCmd = &cobra.Command{ } } else if port.Served { status = "open (" + port.Exposed.Visibility.String() + ")" - if port.Exposed.Visibility == api.PortVisibility_public { + if port.Exposed.Visibility == supervisor.PortVisibility_public { statusColor = tablewriter.FgHiGreenColor } else { statusColor = tablewriter.FgHiCyanColor diff --git a/components/gitpod-cli/cmd/tasks-attach.go b/components/gitpod-cli/cmd/tasks-attach.go index 55b32ef8a52c28..0c1d7c066debf8 100644 --- a/components/gitpod-cli/cmd/tasks-attach.go +++ b/components/gitpod-cli/cmd/tasks-attach.go @@ -7,11 +7,12 @@ package cmd import ( "context" "fmt" + "log" "os" "time" - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" - "github.com/gitpod-io/gitpod/supervisor/api" + supervisor_helper "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor-helper" + supervisor "github.com/gitpod-io/gitpod/supervisor/api" "github.com/manifoldco/promptui" "github.com/spf13/cobra" "google.golang.org/grpc/codes" @@ -31,18 +32,16 @@ var attachTaskCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { var terminalAlias string - conn := supervisor.Dial() - if len(args) > 0 { terminalAlias = args[0] } else { - statusClient := api.NewStatusServiceClient(conn) - stateToFilter := api.TaskState(api.TaskState_value["running"]) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - tasks := supervisor.GetTasksListByState(ctx, statusClient, stateToFilter) + tasks, err := supervisor_helper.GetTasksListByState(ctx, supervisor.TaskState_running) + if err != nil { + log.Fatalf("cannot get task list: %s", err) + } if len(tasks) == 0 { fmt.Println("There are no running tasks") @@ -84,9 +83,12 @@ var attachTaskCmd = &cobra.Command{ terminalAlias = tasks[taskIndex].Terminal } - terminalClient := api.NewTerminalServiceClient(conn) + terminalClient, err := supervisor_helper.GetTerminalServiceClient(context.Background()) + if err != nil { + log.Fatalf("cannot get terminal service: %s", err) + } - terminal, err := terminalClient.Get(context.Background(), &api.GetTerminalRequest{Alias: terminalAlias}) + terminal, err := terminalClient.Get(context.Background(), &supervisor.GetTerminalRequest{Alias: terminalAlias}) if err != nil { if e, ok := status.FromError(err); ok { switch e.Code() { @@ -110,7 +112,7 @@ var attachTaskCmd = &cobra.Command{ interactive, _ := cmd.Flags().GetBool("interactive") forceResize, _ := cmd.Flags().GetBool("force-resize") - supervisor.AttachToTerminal(context.Background(), terminalClient, terminalAlias, supervisor.AttachToTerminalOpts{ + supervisor_helper.AttachToTerminal(context.Background(), terminalClient, terminalAlias, supervisor_helper.AttachToTerminalOpts{ ForceResize: forceResize, Interactive: interactive, }) diff --git a/components/gitpod-cli/cmd/tasks-list.go b/components/gitpod-cli/cmd/tasks-list.go index 4a7d09ff567c30..76db98f0f07396 100644 --- a/components/gitpod-cli/cmd/tasks-list.go +++ b/components/gitpod-cli/cmd/tasks-list.go @@ -7,10 +7,11 @@ package cmd import ( "context" "fmt" + "log" "os" "time" - "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor" + supervisor_helper "github.com/gitpod-io/gitpod/gitpod-cli/pkg/supervisor-helper" "github.com/gitpod-io/gitpod/supervisor/api" "github.com/spf13/cobra" @@ -25,10 +26,10 @@ var listTasksCmd = &cobra.Command{ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - conn := supervisor.Dial() - client := api.NewStatusServiceClient(conn) - - tasks := supervisor.GetTasksList(ctx, client) + tasks, err := supervisor_helper.GetTasksList(ctx) + if err != nil { + log.Fatalf("cannot get task list: %s", err) + } if len(tasks) == 0 { fmt.Println("No tasks detected") diff --git a/components/gitpod-cli/pkg/supervisor/ports.go b/components/gitpod-cli/pkg/supervisor-helper/ports.go similarity index 63% rename from components/gitpod-cli/pkg/supervisor/ports.go rename to components/gitpod-cli/pkg/supervisor-helper/ports.go index 56444fb633d5e7..3e787a99c7108f 100644 --- a/components/gitpod-cli/pkg/supervisor/ports.go +++ b/components/gitpod-cli/pkg/supervisor-helper/ports.go @@ -2,15 +2,21 @@ // Licensed under the GNU Affero General Public License (AGPL). // See License-AGPL.txt in the project root for license information. -package supervisor +package supervisor_helper import ( "context" - "github.com/gitpod-io/gitpod/supervisor/api" + + supervisor "github.com/gitpod-io/gitpod/supervisor/api" ) -func GetPortsList(ctx context.Context, client api.StatusServiceClient) ([]*api.PortsStatus, error) { - portsStatusClient, portsStatusClientError := client.PortsStatus(ctx, &api.PortsStatusRequest{Observe: false}) +func GetPortsList(ctx context.Context) ([]*supervisor.PortsStatus, error) { + conn, err := Dial(ctx) + if err != nil { + return nil, err + } + client := supervisor.NewStatusServiceClient(conn) + portsStatusClient, portsStatusClientError := client.PortsStatus(ctx, &supervisor.PortsStatusRequest{Observe: false}) if portsStatusClientError != nil { return nil, portsStatusClientError diff --git a/components/gitpod-cli/pkg/supervisor-helper/status-tasks.go b/components/gitpod-cli/pkg/supervisor-helper/status-tasks.go new file mode 100644 index 00000000000000..2c8f2d5465e005 --- /dev/null +++ b/components/gitpod-cli/pkg/supervisor-helper/status-tasks.go @@ -0,0 +1,43 @@ +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. +// Licensed under the GNU Affero General Public License (AGPL). +// See License-AGPL.txt in the project root for license information. + +package supervisor_helper + +import ( + "context" + + supervisor "github.com/gitpod-io/gitpod/supervisor/api" + "golang.org/x/xerrors" +) + +func GetTasksList(ctx context.Context) ([]*supervisor.TaskStatus, error) { + conn, err := Dial(ctx) + if err != nil { + return nil, err + } + client := supervisor.NewStatusServiceClient(conn) + respClient, err := client.TasksStatus(ctx, &supervisor.TasksStatusRequest{Observe: false}) + if err != nil { + return nil, xerrors.Errorf("failed get tasks status client: %w", err) + } + resp, err := respClient.Recv() + if err != nil { + return nil, xerrors.Errorf("failed receive data: %w", err) + } + return resp.GetTasks(), nil +} + +func GetTasksListByState(ctx context.Context, filterState supervisor.TaskState) ([]*supervisor.TaskStatus, error) { + tasks, err := GetTasksList(ctx) + if err != nil { + return nil, err + } + var filteredTasks []*supervisor.TaskStatus + for _, task := range tasks { + if task.State == filterState { + filteredTasks = append(filteredTasks, task) + } + } + return filteredTasks, nil +} diff --git a/components/gitpod-cli/pkg/supervisor-helper/supervisor.go b/components/gitpod-cli/pkg/supervisor-helper/supervisor.go new file mode 100644 index 00000000000000..9353e5851a4a5e --- /dev/null +++ b/components/gitpod-cli/pkg/supervisor-helper/supervisor.go @@ -0,0 +1,26 @@ +// Copyright (c) 2022 Gitpod GmbH. All rights reserved. +// Licensed under the GNU Affero General Public License (AGPL). +// See License-AGPL.txt in the project root for license information. + +package supervisor_helper + +import ( + "context" + "os" + + "golang.org/x/xerrors" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func Dial(ctx context.Context) (*grpc.ClientConn, error) { + supervisorAddr := os.Getenv("SUPERVISOR_ADDR") + if supervisorAddr == "" { + supervisorAddr = "localhost:22999" + } + supervisorConn, err := grpc.DialContext(ctx, supervisorAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + err = xerrors.Errorf("failed connecting to supervisor: %w", err) + } + return supervisorConn, err +} diff --git a/components/gitpod-cli/pkg/supervisor/terminal-attach.go b/components/gitpod-cli/pkg/supervisor-helper/terminal-attach.go similarity index 72% rename from components/gitpod-cli/pkg/supervisor/terminal-attach.go rename to components/gitpod-cli/pkg/supervisor-helper/terminal-attach.go index aee46f559922f5..be906d8344db2d 100644 --- a/components/gitpod-cli/pkg/supervisor/terminal-attach.go +++ b/components/gitpod-cli/pkg/supervisor-helper/terminal-attach.go @@ -2,7 +2,7 @@ // Licensed under the GNU Affero General Public License (AGPL). // See License-AGPL.txt in the project root for license information. -package supervisor +package supervisor_helper import ( "context" @@ -12,7 +12,7 @@ import ( "syscall" "github.com/creack/pty" - "github.com/gitpod-io/gitpod/supervisor/api" + supervisor "github.com/gitpod-io/gitpod/supervisor/api" log "github.com/sirupsen/logrus" "golang.org/x/term" ) @@ -23,9 +23,9 @@ type AttachToTerminalOpts struct { Token string } -func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, alias string, opts AttachToTerminalOpts) { +func AttachToTerminal(ctx context.Context, client supervisor.TerminalServiceClient, alias string, opts AttachToTerminalOpts) { // Copy to stdout/stderr - listen, err := client.Listen(ctx, &api.ListenTerminalRequest{ + listen, err := client.Listen(ctx, &supervisor.ListenTerminalRequest{ Alias: alias, }) if err != nil { @@ -50,7 +50,7 @@ func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, ali // Set stdin in raw mode. oldState, err := term.MakeRaw(int(os.Stdin.Fd())) if err != nil { - panic(err) + log.WithError(err).Fatal("cannot attach to terminal") } defer func() { _ = term.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort. @@ -66,9 +66,9 @@ func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, ali continue } - req := &api.SetTerminalSizeRequest{ + req := &supervisor.SetTerminalSizeRequest{ Alias: alias, - Size: &api.TerminalSize{ + Size: &supervisor.TerminalSize{ Cols: uint32(size.Cols), Rows: uint32(size.Rows), WidthPx: uint32(size.X), @@ -78,10 +78,10 @@ func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, ali var expectResize bool if opts.ForceResize { - req.Priority = &api.SetTerminalSizeRequest_Force{Force: true} + req.Priority = &supervisor.SetTerminalSizeRequest_Force{Force: true} expectResize = true } else if opts.Token != "" { - req.Priority = &api.SetTerminalSizeRequest_Token{Token: opts.Token} + req.Priority = &supervisor.SetTerminalSizeRequest_Token{Token: opts.Token} expectResize = true } @@ -100,7 +100,7 @@ func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, ali for { n, err := os.Stdin.Read(buf) if n > 0 { - _, serr := client.Write(ctx, &api.WriteTerminalRequest{Alias: alias, Stdin: buf[:n]}) + _, serr := client.Write(ctx, &supervisor.WriteTerminalRequest{Alias: alias, Stdin: buf[:n]}) if serr != nil { errchan <- err return @@ -127,3 +127,12 @@ func AttachToTerminal(ctx context.Context, client api.TerminalServiceClient, ali case <-stopch: } } + +func GetTerminalServiceClient(ctx context.Context) (supervisor.TerminalServiceClient, error) { + conn, err := Dial(ctx) + if err != nil { + return nil, err + } + terminalClient := supervisor.NewTerminalServiceClient(conn) + return terminalClient, nil +} diff --git a/components/gitpod-cli/pkg/supervisor/status-tasks.go b/components/gitpod-cli/pkg/supervisor/status-tasks.go deleted file mode 100644 index d989c1538fd185..00000000000000 --- a/components/gitpod-cli/pkg/supervisor/status-tasks.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2022 Gitpod GmbH. All rights reserved. -// Licensed under the GNU Affero General Public License (AGPL). -// See License-AGPL.txt in the project root for license information. - -package supervisor - -import ( - "context" - "io" - - "github.com/gitpod-io/gitpod/supervisor/api" - log "github.com/sirupsen/logrus" -) - -func GetTasksList(ctx context.Context, client api.StatusServiceClient) []*api.TaskStatus { - listen, err := client.TasksStatus(ctx, &api.TasksStatusRequest{Observe: false}) - if err != nil { - log.WithError(err).Error("Cannot list tasks") - } - - taskschan := make(chan []*api.TaskStatus) - - go func() { - for { - resp, err := listen.Recv() - if err != nil && err != io.EOF { - panic(err) - } - - chunk := resp.GetTasks() - - if chunk == nil { - close(taskschan) - break - } else { - taskschan <- chunk - } - } - }() - - return <-taskschan -} - -func GetTasksListByState(ctx context.Context, client api.StatusServiceClient, filterState api.TaskState) []*api.TaskStatus { - tasks := GetTasksList(ctx, client) - - var filteredTasks []*api.TaskStatus - - for _, task := range tasks { - if task.State == filterState { - filteredTasks = append(filteredTasks, task) - } - } - - return filteredTasks -} diff --git a/components/gitpod-cli/pkg/supervisor/supervisor.go b/components/gitpod-cli/pkg/supervisor/supervisor.go deleted file mode 100644 index e977dc4059e11e..00000000000000 --- a/components/gitpod-cli/pkg/supervisor/supervisor.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2022 Gitpod GmbH. All rights reserved. -// Licensed under the GNU Affero General Public License (AGPL). -// See License-AGPL.txt in the project root for license information. - -package supervisor - -import ( - "os" - - log "github.com/sirupsen/logrus" - "google.golang.org/grpc" -) - -func Dial() *grpc.ClientConn { - supervisorAddr := os.Getenv("SUPERVISOR_ADDR") - if supervisorAddr == "" { - supervisorAddr = "localhost:22999" - } - supervisorConn, err := grpc.Dial(supervisorAddr, grpc.WithInsecure()) - if err != nil { - log.WithError(err).Fatal("cannot connect to supervisor") - } - - return supervisorConn -}