Skip to content

consolidate bind to single command #2

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 1 commit into from
Oct 7, 2020
Merged
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
28 changes: 2 additions & 26 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,9 @@ package client

import (
"net/url"

"go.coder.com/cloud-agent/internal/config"
)

type Client struct {
token string
baseURL *url.URL
}

func FromEnv() (*Client, error) {
token, err := config.SessionToken.Read()
if err != nil {
return nil, err
}

u, err := config.URL.Read()
if err != nil {
return nil, err
}

parsed, err := url.Parse(u)
if err != nil {
return nil, err
}

return &Client{
token: token,
baseURL: parsed,
}, nil
Token string
BaseURL *url.URL
}
4 changes: 2 additions & 2 deletions internal/client/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ func (c *Client) request(method, path string, body interface{}) (*http.Response,
return nil, xerrors.Errorf("marshal body: %w", err)
}

req, err := http.NewRequest(method, c.baseURL.String()+path, bytes.NewReader(b))
req, err := http.NewRequest(method, c.BaseURL.String()+path, bytes.NewReader(b))
if err != nil {
return nil, xerrors.Errorf("new request: %w", err)
}

req.Header.Set(sessionHeader, c.token)
req.Header.Set(sessionHeader, c.Token)

return http.DefaultClient.Do(req)
}
Expand Down
152 changes: 152 additions & 0 deletions internal/cmd/bind.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package cmd

import (
"context"
"net/url"
"os"
"regexp"
"strings"
"time"

"cdr.dev/slog/sloggers/sloghuman"
"github.com/spf13/pflag"
"golang.org/x/xerrors"

"go.coder.com/cli"
"go.coder.com/cloud-agent/internal/client"
"go.coder.com/cloud-agent/internal/config"
"go.coder.com/cloud-agent/internal/ideproxy"
"go.coder.com/flog"
)

var (
DefaultCloudURL = "https://cloud.coder.com"
)

var codeServerNameRx = regexp.MustCompile("^[a-z][a-z0-9_]{0,50}$")

type bindCmd struct {
cloudURL string
codeServerAddr string
}

func (c *bindCmd) Spec() cli.CommandSpec {
return cli.CommandSpec{
Name: "bind",
Usage: "[NAME]",
Desc: "Bind a server to Coder Cloud. A name will be generated from the hostname if one is not provided.",
}
}

func (c *bindCmd) RegisterFlags(fl *pflag.FlagSet) {
fl.StringVar(&c.cloudURL, "cloud-url", DefaultCloudURL, "The Coder Cloud URL to connect to.")
fl.StringVar(&c.codeServerAddr,
"code-server-addr",
"localhost:8080",
"The address of the code-server instance to proxy.",
)
}

func (c *bindCmd) Run(fl *pflag.FlagSet) {
var (
err error
ctx = context.Background()
)

name := fl.Arg(0)
if name == "" {
// Generate a name based on the hostname if one is not provided.
name, err = genServerName()
if err != nil {
flog.Fatal("Failed to generate server name: %v", err.Error())
}
}

if !codeServerNameRx.MatchString(name) {
flog.Fatal("Name must conform to regex %s", codeServerNameRx.String())
}

cloudURL, err := url.Parse(c.cloudURL)
if err != nil {
flog.Fatal("Invalid Cloud URL: %v", err.Error())
}

token, err := config.SessionToken.Read()
if xerrors.Is(err, os.ErrNotExist) {
token, err = login(cloudURL.String(), name)
}
if err != nil {
flog.Fatal("Failed to login: %v", err)
}

cli := client.Client{
Token: token,
BaseURL: cloudURL,
}

// Register the server with Coder Cloud. This is an idempotent
// operation.
cs, err := cli.RegisterCodeServer(name)
if err != nil {
flog.Fatal("Failed to register server: %v", err)
}

// Get the Access URL for the user.
url, err := cli.AccessURL(cs.ID)
if err != nil {
flog.Fatal("Failed to query server: %v", err)
}

agent := &ideproxy.Agent{
Log: sloghuman.Make(os.Stderr),
CodeServerID: cs.ID,
SessionToken: token,
CloudProxyURL: c.cloudURL,
CodeServerAddr: os.Getenv(c.codeServerAddr),
}

proxy := func() {
err = agent.Proxy(ctx)
if err != nil {
flog.Error("Connection to Coder-Cloud disrupted, re-establishing connection: %v", err.Error())
}
}

flog.Info("Proxying code-server to Coder Cloud, you can access your IDE at %v", url)

proxy()

// Avoid a super tight loop.
ticker := time.NewTicker(time.Second)
for range ticker.C {
proxy()
}
}

func login(url, serverName string) (string, error) {
token, err := client.Login(url, serverName)
if err != nil {
return "", xerrors.Errorf("unable to login: %w", err)
}

err = config.SessionToken.Write(token)
if err != nil {
return "", xerrors.Errorf("write session token to file: %w", err)
}

return token, nil
}

func genServerName() (string, error) {
hostname, err := os.Hostname()
if err != nil {
xerrors.Errorf("get hostname: %w", err)
}

hostname = strings.ToLower(hostname)

// Only use the first token.
hostname = strings.Split(hostname, ".")[0]
// '-' are not allowed, convert them to '_'.
return strings.Replace(hostname, "-", "_", -1), nil
}
3 changes: 1 addition & 2 deletions internal/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ func (c *rootCmd) Spec() cli.CommandSpec {

func (c *rootCmd) Subcommands() []cli.Command {
return []cli.Command{
&linkCmd{},
&proxyCmd{},
&bindCmd{},
&versionCmd{},
}
}
Expand Down
91 changes: 0 additions & 91 deletions internal/cmd/link.go

This file was deleted.

Loading