Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ func (r *RootCmd) Core() []*clibase.Cmd {
r.resetPassword(),
r.state(),
r.templates(),
r.upgrade(),
r.users(),
r.tokens(),
r.version(defaultVersionInfo),
Expand Down Expand Up @@ -677,7 +678,7 @@ func (r *RootCmd) checkVersions(i *clibase.Invocation, client *codersdk.Client)
if runtime.GOOS == "windows" {
fmtWarningText += `download the server version from: https://github.com/coder/coder/releases/v%s`
} else {
fmtWarningText += `download the server version with: 'curl -L https://coder.com/install.sh | sh -s -- --version %s'`
fmtWarningText += `download the server version with: 'curl -L https://coder.com/install.sh | sh -s -- --version %s' or run 'coder upgrade'`
}

if !buildinfo.VersionsMatch(clientVersion, info.Version) {
Expand Down
2 changes: 2 additions & 0 deletions cli/testdata/coder_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Coder v0.0.0-devel — A tool for provisioning self-hosted development environme
tokens Manage personal access tokens
update Will update and start a given workspace if it is out of
date
upgrade Upgrade the Coder CLI to match the version of a
deployment.
users Manage users
version Show coder version

Expand Down
6 changes: 6 additions & 0 deletions cli/testdata/coder_upgrade_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Usage: coder upgrade [flags]

Upgrade the Coder CLI to match the version of a deployment.

---
Run `coder --help` for a list of global options.
122 changes: 122 additions & 0 deletions cli/upgrade.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package cli

import (
"fmt"
"net/http"
"net/url"
"os/exec"
"runtime"
"strings"

"golang.org/x/mod/semver"
"golang.org/x/xerrors"

"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)

func (r *RootCmd) upgrade() *clibase.Cmd {
var scriptURL string
cmd := &clibase.Cmd{
Use: "upgrade",
Short: "Upgrade the Coder CLI to match the version of a deployment.",
Options: clibase.OptionSet{
{
Flag: "install-script-url",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: We have some other flags introduced for tests that are named test.x (i.e. test.install-script-url). This way the purpose of the flag is more clear and won't collide with non-test flags.

Description: "Download URL of install script (useful for testing).",
Value: clibase.StringOf(&scriptURL),
Default: "https://coder.com/install.sh",
Hidden: true,
},
},
Handler: func(inv *clibase.Invocation) error {
var (
ctx = inv.Context()
serverURL = r.clientURL.String()
)

var err error
if serverURL == "" {
serverURL, err = r.createConfig().URL().Read()
if err != nil || strings.TrimSpace(serverURL) == "" {
_, _ = fmt.Fprintln(inv.Stderr, cliui.Styles.Error.Render(
"No deployment URL provided. You must either login using",
cliui.Styles.Code.Render("coder login"),
cliui.Styles.Error.Render("or specify a URL with the"),
cliui.Styles.Code.Render("--url"),
cliui.Styles.Error.Render("flag."),
))

return xerrors.Errorf("read config url: %w", err)
}
}

uri, err := url.Parse(serverURL)
if err != nil {
return xerrors.Errorf("parse url: %w", err)
}

client := codersdk.New(uri)
serverInfo, err := client.BuildInfo(ctx)
if err != nil {
return xerrors.Errorf("build info: %w", err)
}

version := semver.Canonical(serverInfo.Version)
version = strings.TrimSuffix(version, "-devel")
version = strings.TrimPrefix(version, "v")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check that this isn't 0.0.0 in case the server was built without Makefile?


if runtime.GOOS == "windows" {
_, _ = fmt.Fprintln(inv.Stdout,
cliui.Styles.Code.Render("coder upgrade "),
"is not currently supported on Windows.\n",
fmt.Sprintf("Download the installer at %s to upgrade your client.", cliui.Styles.Keyword.Render(windowsInstallerURL(version))),
)
return nil
}

_, _ = fmt.Fprintf(inv.Stdout, "Detected server version %q, downloading version %q from %s\n", serverInfo.Version, version, scriptURL)

req, err := http.NewRequestWithContext(ctx, http.MethodGet, scriptURL, nil)
if err != nil {
return xerrors.Errorf("new http request: %w", err)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return xerrors.Errorf("fetch install script: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return xerrors.Errorf("unexpected error code %d while fetching install script: %w", resp.StatusCode, err)
}

// nolint: gosec
cmd := exec.Command("sh", "-s", "--", "--version", version)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I notice we're not controlling where the binary will end up (path). If the idea is for the binary to update itself, it should replace itself in the same location. Otherwise we will most definitely end up placing multiple coder binaries on user filesystems which would be confusing.

This could be a flag (--binary-path) to allow the user to change it (default arg0).

This may or may not have "file is in use" ramifications on certain systems as long as the coder command is running, but probably not on Linux/macOS.

// TODO: should output print the script prior to executing it and require
// the user to confirm they want to run it?
cmd.Stdin = resp.Body
cmd.Stdout = inv.Stdout
cmd.Stderr = inv.Stderr
err = cmd.Run()
if err != nil {
return xerrors.Errorf("run install script: %w", err)
}

return nil
},
}

return cmd
}

func windowsInstallerURL(version string) string {
return fmt.Sprintf(
"https://github.com/coder/coder/releases/download/v%s/coder_%s_windows_%s_installer.exe",
version,
version,
runtime.GOARCH,
)
}
99 changes: 99 additions & 0 deletions cli/upgrade_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package cli_test

import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/pty/ptytest"
"github.com/coder/coder/testutil"
)

func TestUpgrade(t *testing.T) {
t.Parallel()

if runtime.GOOS == "windows" {
t.Skipf("Detected Windows OS, skipping upgrade tests")
return
}

// startFakeDeployment starts and returns a fake deployment
// that returns the specified version when the upgrade command
// requests build info.
startFakeDeployment := func(t *testing.T, version string) string {
t.Helper()
s := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(codersdk.BuildInfoResponse{
Version: version,
})
require.NoError(t, err)
},
),
)
t.Cleanup(s.Close)
return s.URL
}

// startFakeInstallServer starts and returns a fake server
// that returns the specified script that is used to "install"
// coder.
startFakeInstallServer := func(t *testing.T, script string) string {
t.Helper()
s := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(script))
require.NoError(t, err)
}),
)
t.Cleanup(s.Close)
return s.URL
}

t.Run("OK", func(t *testing.T) {
t.Parallel()

var (
serverVersion = "v1.2.3-devel+f72d8e95"
expectedVersion = "1.2.3"
script = fmt.Sprintf(`#!/usr/bin/env bash
echo "testing 123"
echo %s`, expectedVersion)
)

serverURL := startFakeDeployment(t, serverVersion)
installURL := startFakeInstallServer(t, script)

inv, _ := clitest.New(t, "upgrade", "--url", serverURL, "--install-script-url", installURL)
pty := ptytest.New(t).Attach(inv)

ctx := testutil.Context(t, testutil.WaitMedium)
errC := inv.WithContext(ctx).Run()
assert.NoError(t, errC)
Comment on lines +81 to +82

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
errC := inv.WithContext(ctx).Run()
assert.NoError(t, errC)
err := inv.WithContext(ctx).Run()
assert.NoError(t, err)

pty.ExpectMatch(fmt.Sprintf("Detected server version %q, downloading version %q from %s", serverVersion, expectedVersion, installURL))
pty.ExpectMatch("testing 123")
pty.ExpectMatch(expectedVersion)
})

t.Run("NoServerURL", func(t *testing.T) {
t.Parallel()

inv, _ := clitest.New(t, "upgrade")
pty := ptytest.New(t).Attach(inv)

ctx := testutil.Context(t, testutil.WaitMedium)
errC := inv.WithContext(ctx).Run()
assert.Error(t, errC)
Comment on lines +95 to +96

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
errC := inv.WithContext(ctx).Run()
assert.Error(t, errC)
err := inv.WithContext(ctx).Run()
assert.Error(t, err)

pty.ExpectMatch("No deployment URL provided. You must either login using")
})
}
1 change: 1 addition & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Coder — A tool for provisioning self-hosted development environments with Terr
| [<code>templates</code>](./cli/templates.md) | Manage templates |
| [<code>tokens</code>](./cli/tokens.md) | Manage personal access tokens |
| [<code>update</code>](./cli/update.md) | Will update and start a given workspace if it is out of date |
| [<code>upgrade</code>](./cli/upgrade.md) | Upgrade the Coder CLI to match the version of a deployment. |
| [<code>users</code>](./cli/users.md) | Manage users |
| [<code>version</code>](./cli/version.md) | Show coder version |

Expand Down
11 changes: 11 additions & 0 deletions docs/cli/upgrade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!-- DO NOT EDIT | GENERATED CONTENT -->

# upgrade

Upgrade the Coder CLI to match the version of a deployment.

## Usage

```console
coder upgrade [flags]
```
5 changes: 5 additions & 0 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,11 @@
"description": "Will update and start a given workspace if it is out of date",
"path": "cli/update.md"
},
{
"title": "upgrade",
"description": "Upgrade the Coder CLI to match the version of a deployment.",
"path": "cli/upgrade.md"
},
{
"title": "users",
"description": "Manage users",
Expand Down