Skip to content

feat: Add config-ssh command #735

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

Merged
merged 2 commits into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"cSpell.words": [
"cliflag",
"cliui",
"coderd",
"coderdtest",
Expand Down
24 changes: 6 additions & 18 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (s *agent) init(ctx context.Context) {
Handler: func(session ssh.Session) {
err := s.handleSSHSession(session)
if err != nil {
s.options.Logger.Debug(ctx, "ssh session failed", slog.Error(err))
s.options.Logger.Warn(ctx, "ssh session failed", slog.Error(err))
_ = session.Exit(1)
return
}
Expand Down Expand Up @@ -177,12 +177,6 @@ func (s *agent) init(ctx context.Context) {
},
ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig {
return &gossh.ServerConfig{
Config: gossh.Config{
// "arcfour" is the fastest SSH cipher. We prioritize throughput
// over encryption here, because the WebRTC connection is already
// encrypted. If possible, we'd disable encryption entirely here.
Ciphers: []string{"arcfour"},
},
NoClientAuth: true,
}
},
Expand All @@ -198,14 +192,11 @@ func (*agent) handleSSHSession(session ssh.Session) error {
err error
)

username := session.User()
if username == "" {
currentUser, err := user.Current()
if err != nil {
return xerrors.Errorf("get current user: %w", err)
}
username = currentUser.Username
currentUser, err := user.Current()
if err != nil {
return xerrors.Errorf("get current user: %w", err)
}
username := currentUser.Username

// gliderlabs/ssh returns a command slice of zero
// when a shell is requested.
Expand Down Expand Up @@ -249,10 +240,7 @@ func (*agent) handleSSHSession(session ssh.Session) error {
}
go func() {
for win := range windowSize {
err := ptty.Resize(uint16(win.Width), uint16(win.Height))
if err != nil {
panic(err)
}
_ = ptty.Resize(uint16(win.Width), uint16(win.Height))
}
}()
go func() {
Expand Down
3 changes: 0 additions & 3 deletions agent/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ func (c *Conn) SSHClient() (*ssh.Client, error) {
return nil, xerrors.Errorf("ssh: %w", err)
}
sshConn, channels, requests, err := ssh.NewClientConn(netConn, "localhost:22", &ssh.ClientConfig{
Config: ssh.Config{
Ciphers: []string{"arcfour"},
},
// SSH host validation isn't helpful, because obtaining a peer
// connection already signifies user-intent to dial a workspace.
// #nosec
Expand Down
2 changes: 1 addition & 1 deletion agent/usershell/usershell_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ func Get(username string) (string, error) {
}
return parts[6], nil
}
return "", xerrors.New("user not found in /etc/passwd and $SHELL not set")
return "", xerrors.Errorf("user %q not found in /etc/passwd", username)
}
21 changes: 11 additions & 10 deletions cli/cliui/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package cliui
import (
"context"
"fmt"
"io"
"sync"
"time"

"github.com/briandowns/spinner"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/codersdk"
Expand All @@ -21,15 +21,15 @@ type AgentOptions struct {
}

// Agent displays a spinning indicator that waits for a workspace agent to connect.
func Agent(cmd *cobra.Command, opts AgentOptions) error {
func Agent(ctx context.Context, writer io.Writer, opts AgentOptions) error {
if opts.FetchInterval == 0 {
opts.FetchInterval = 500 * time.Millisecond
}
if opts.WarnInterval == 0 {
opts.WarnInterval = 30 * time.Second
}
var resourceMutex sync.Mutex
resource, err := opts.Fetch(cmd.Context())
resource, err := opts.Fetch(ctx)
if err != nil {
return xerrors.Errorf("fetch: %w", err)
}
Expand All @@ -40,7 +40,8 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
opts.WarnInterval = 0
}
spin := spinner.New(spinner.CharSets[78], 100*time.Millisecond, spinner.WithColor("fgHiGreen"))
spin.Writer = cmd.OutOrStdout()
spin.Writer = writer
spin.ForceOutput = true
spin.Suffix = " Waiting for connection from " + Styles.Field.Render(resource.Type+"."+resource.Name) + "..."
spin.Start()
defer spin.Stop()
Expand All @@ -51,7 +52,7 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
defer timer.Stop()
go func() {
select {
case <-cmd.Context().Done():
case <-ctx.Done():
return
case <-timer.C:
}
Expand All @@ -63,17 +64,17 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
}
// This saves the cursor position, then defers clearing from the cursor
// position to the end of the screen.
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "\033[s\r\033[2K%s\n\n", Styles.Paragraph.Render(Styles.Prompt.String()+message))
defer fmt.Fprintf(cmd.OutOrStdout(), "\033[u\033[J")
_, _ = fmt.Fprintf(writer, "\033[s\r\033[2K%s\n\n", Styles.Paragraph.Render(Styles.Prompt.String()+message))
defer fmt.Fprintf(writer, "\033[u\033[J")
}()
for {
select {
case <-cmd.Context().Done():
return cmd.Context().Err()
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
resourceMutex.Lock()
resource, err = opts.Fetch(cmd.Context())
resource, err = opts.Fetch(ctx)
if err != nil {
return xerrors.Errorf("fetch: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/cliui/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestAgent(t *testing.T) {
ptty := ptytest.New(t)
cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
err := cliui.Agent(cmd, cliui.AgentOptions{
err := cliui.Agent(cmd.Context(), cmd.OutOrStdout(), cliui.AgentOptions{
WorkspaceName: "example",
Fetch: func(ctx context.Context) (codersdk.WorkspaceResource, error) {
resource := codersdk.WorkspaceResource{
Expand Down
38 changes: 38 additions & 0 deletions cli/cliui/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cliui

import (
"fmt"
"io"
"strings"

"github.com/charmbracelet/lipgloss"
)

// cliMessage provides a human-readable message for CLI errors and messages.
type cliMessage struct {
Level string
Style lipgloss.Style
Header string
Lines []string
}

// String formats the CLI message for consumption by a human.
func (m cliMessage) String() string {
var str strings.Builder
_, _ = fmt.Fprintf(&str, "%s\r\n",
Styles.Bold.Render(m.Header))
for _, line := range m.Lines {
_, _ = fmt.Fprintf(&str, " %s %s\r\n", m.Style.Render("|"), line)
}
return str.String()
}

// Warn writes a log to the writer provided.
func Warn(wtr io.Writer, header string, lines ...string) {
_, _ = fmt.Fprint(wtr, cliMessage{
Level: "warning",
Style: Styles.Warn,
Header: header,
Lines: lines,
}.String())
}
24 changes: 12 additions & 12 deletions cli/cliui/provisionerjob.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@ package cliui
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"sync"
"time"

"github.com/google/uuid"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/coderd/database"
"github.com/coder/coder/codersdk"
)

func WorkspaceBuild(cmd *cobra.Command, client *codersdk.Client, build uuid.UUID, before time.Time) error {
return ProvisionerJob(cmd, ProvisionerJobOptions{
func WorkspaceBuild(ctx context.Context, writer io.Writer, client *codersdk.Client, build uuid.UUID, before time.Time) error {
return ProvisionerJob(ctx, writer, ProvisionerJobOptions{
Fetch: func() (codersdk.ProvisionerJob, error) {
build, err := client.WorkspaceBuild(cmd.Context(), build)
build, err := client.WorkspaceBuild(ctx, build)
return build.Job, err
},
Logs: func() (<-chan codersdk.ProvisionerJobLog, error) {
return client.WorkspaceBuildLogsAfter(cmd.Context(), build, before)
return client.WorkspaceBuildLogsAfter(ctx, build, before)
},
})
}
Expand All @@ -39,25 +39,25 @@ type ProvisionerJobOptions struct {
}

// ProvisionerJob renders a provisioner job with interactive cancellation.
func ProvisionerJob(cmd *cobra.Command, opts ProvisionerJobOptions) error {
func ProvisionerJob(ctx context.Context, writer io.Writer, opts ProvisionerJobOptions) error {
if opts.FetchInterval == 0 {
opts.FetchInterval = time.Second
}
ctx, cancelFunc := context.WithCancel(ctx)
defer cancelFunc()

var (
currentStage = "Queued"
currentStageStartedAt = time.Now().UTC()
didLogBetweenStage = false
ctx, cancelFunc = context.WithCancel(cmd.Context())

errChan = make(chan error, 1)
job codersdk.ProvisionerJob
jobMutex sync.Mutex
)
defer cancelFunc()

printStage := func() {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), Styles.Prompt.Render("⧗")+"%s\n", Styles.Field.Render(currentStage))
_, _ = fmt.Fprintf(writer, Styles.Prompt.Render("⧗")+"%s\n", Styles.Field.Render(currentStage))
}

updateStage := func(stage string, startedAt time.Time) {
Expand All @@ -70,7 +70,7 @@ func ProvisionerJob(cmd *cobra.Command, opts ProvisionerJobOptions) error {
if job.CompletedAt != nil && job.Status != codersdk.ProvisionerJobSucceeded {
mark = Styles.Crossmark
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), prefix+mark.String()+Styles.Placeholder.Render(" %s [%dms]")+"\n", currentStage, startedAt.Sub(currentStageStartedAt).Milliseconds())
_, _ = fmt.Fprintf(writer, prefix+mark.String()+Styles.Placeholder.Render(" %s [%dms]")+"\n", currentStage, startedAt.Sub(currentStageStartedAt).Milliseconds())
}
if stage == "" {
return
Expand Down Expand Up @@ -116,7 +116,7 @@ func ProvisionerJob(cmd *cobra.Command, opts ProvisionerJobOptions) error {
return
}
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "\033[2K\r\n"+Styles.FocusedPrompt.String()+Styles.Bold.Render("Gracefully canceling...")+"\n\n")
_, _ = fmt.Fprintf(writer, "\033[2K\r\n"+Styles.FocusedPrompt.String()+Styles.Bold.Render("Gracefully canceling...")+"\n\n")
err := opts.Cancel()
if err != nil {
errChan <- xerrors.Errorf("cancel: %w", err)
Expand Down Expand Up @@ -183,7 +183,7 @@ func ProvisionerJob(cmd *cobra.Command, opts ProvisionerJobOptions) error {
jobMutex.Unlock()
continue
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %s\n", Styles.Placeholder.Render(" "), output)
_, _ = fmt.Fprintf(writer, "%s %s\n", Styles.Placeholder.Render(" "), output)
didLogBetweenStage = true
jobMutex.Unlock()
}
Expand Down
2 changes: 1 addition & 1 deletion cli/cliui/provisionerjob_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func newProvisionerJob(t *testing.T) provisionerJobTest {
logs := make(chan codersdk.ProvisionerJobLog, 1)
cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
return cliui.ProvisionerJob(cmd, cliui.ProvisionerJobOptions{
return cliui.ProvisionerJob(cmd.Context(), cmd.OutOrStdout(), cliui.ProvisionerJobOptions{
FetchInterval: time.Millisecond,
Fetch: func() (codersdk.ProvisionerJob, error) {
jobLock.Lock()
Expand Down
Loading