Skip to content

Add template tooltips/kira pilot #2308

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 17 commits into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
76 changes: 71 additions & 5 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"golang.org/x/mod/semver"
"golang.org/x/oauth2"
xgithub "golang.org/x/oauth2/github"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"google.golang.org/api/idtoken"
"google.golang.org/api/option"
Expand Down Expand Up @@ -169,8 +170,9 @@ func server() *cobra.Command {
}

var (
tunnelErrChan <-chan error
ctxTunnel, closeTunnel = context.WithCancel(cmd.Context())
devTunnel = (*devtunnel.Tunnel)(nil)
devTunnelErrChan = make(<-chan error, 1)
)
defer closeTunnel()

Expand All @@ -197,14 +199,37 @@ func server() *cobra.Command {
}
}
if err == nil {
accessURL, tunnelErrChan, err = devtunnel.New(ctxTunnel, localURL)
devTunnel, devTunnelErrChan, err = devtunnel.New(ctxTunnel, logger.Named("devtunnel"))
if err != nil {
return xerrors.Errorf("create tunnel: %w", err)
}
accessURL = devTunnel.URL
}
_, _ = fmt.Fprintln(cmd.ErrOrStderr())
}

// Warn the user if the access URL appears to be a loopback address.
isLocal, err := isLocalURL(cmd.Context(), accessURL)
if isLocal || err != nil {
var reason string
if isLocal {
reason = "appears to be a loopback address"
} else {
reason = "could not be resolved"
}
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), cliui.Styles.Wrap.Render(
cliui.Styles.Warn.Render("Warning:")+" The current access URL:")+"\n\n")
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), " "+cliui.Styles.Field.Render(accessURL)+"\n\n")
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), cliui.Styles.Wrap.Render(
reason+". Provisioned workspaces are unlikely to be able to "+
"connect to Coder. Please consider changing your "+
"access URL using the --access-url option, or directly "+
"specifying access URLs on templates.",
)+"\n\n")
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "For more information, see "+
"https://github.com/coder/coder/issues/1528\n\n")
}

validator, err := idtoken.NewValidator(cmd.Context(), option.WithoutAuthentication())
if err != nil {
return err
Expand Down Expand Up @@ -329,7 +354,27 @@ func server() *cobra.Command {
return shutdownConnsCtx
},
}
errCh <- server.Serve(listener)

wg := errgroup.Group{}
wg.Go(func() error {
// Make sure to close the tunnel listener if we exit so the
// errgroup doesn't wait forever!
if dev && tunnel {
defer devTunnel.Listener.Close()
}

return server.Serve(listener)
})

if dev && tunnel {
wg.Go(func() error {
defer listener.Close()

return server.Serve(devTunnel.Listener)
})
}

errCh <- wg.Wait()
}()

config := createConfig(cmd)
Expand Down Expand Up @@ -395,7 +440,7 @@ func server() *cobra.Command {
case <-cmd.Context().Done():
coderAPI.Close()
return cmd.Context().Err()
case err := <-tunnelErrChan:
case err := <-devTunnelErrChan:
if err != nil {
return err
}
Expand Down Expand Up @@ -458,7 +503,7 @@ func server() *cobra.Command {
if dev && tunnel {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), cliui.Styles.Prompt.String()+"Waiting for dev tunnel to close...\n")
closeTunnel()
<-tunnelErrChan
<-devTunnelErrChan
}

_, _ = fmt.Fprintf(cmd.OutOrStdout(), cliui.Styles.Prompt.String()+"Waiting for WebSocket connections to close...\n")
Expand Down Expand Up @@ -805,3 +850,24 @@ func serveHandler(ctx context.Context, logger slog.Logger, handler http.Handler,

return func() { _ = srv.Close() }
}

// isLocalURL returns true if the hostname of the provided URL appears to
// resolve to a loopback address.
func isLocalURL(ctx context.Context, urlString string) (bool, error) {
parsedURL, err := url.Parse(urlString)
if err != nil {
return false, err
}
resolver := &net.Resolver{}
ips, err := resolver.LookupIPAddr(ctx, parsedURL.Hostname())
if err != nil {
return false, err
}

for _, ip := range ips {
if ip.IP.IsLoopback() {
return true, nil
}
}
return false, nil
}
29 changes: 29 additions & 0 deletions cli/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ func TestServer(t *testing.T) {
} else {
t.Error("expected password line output; got no match")
}

// Verify that we warned the user about the default access URL possibly not being what they want.
assert.Contains(t, buf.String(), "coder/coder/issues/1528")
})

// Duplicated test from "Development" above to test setting email/password via env.
Expand Down Expand Up @@ -163,6 +166,32 @@ func TestServer(t *testing.T) {
assert.Contains(t, buf.String(), fmt.Sprintf("password: %s", wantPassword), "expected output %q; got no match", wantPassword)
})

t.Run("NoWarningWithRemoteAccessURL", func(t *testing.T) {
t.Parallel()
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()

root, cfg := clitest.New(t, "server", "--dev", "--tunnel=false", "--address", ":0", "--access-url", "http://1.2.3.4:3000/")
var buf strings.Builder
errC := make(chan error)
root.SetOutput(&buf)
go func() {
errC <- root.ExecuteContext(ctx)
}()

// Just wait for startup
require.Eventually(t, func() bool {
var err error
_, err = cfg.URL().Read()
return err == nil
}, 15*time.Second, 25*time.Millisecond)

cancelFunc()
require.ErrorIs(t, <-errC, context.Canceled)

assert.NotContains(t, buf.String(), "coder/coder/issues/1528")
})

t.Run("TLSBadVersion", func(t *testing.T) {
t.Parallel()
ctx, cancelFunc := context.WithCancel(context.Background())
Expand Down
9 changes: 7 additions & 2 deletions cli/templateinit.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,13 @@ func templateInit() *cobra.Command {
exampleNames := []string{}
exampleByName := map[string]examples.Example{}
for _, example := range exampleList {
exampleNames = append(exampleNames, example.Name)
exampleByName[example.Name] = example
name := fmt.Sprintf(
"%s\n%s\n",
cliui.Styles.Bold.Render(example.Name),
cliui.Styles.Wrap.Copy().PaddingLeft(6).Render(example.Description),
)
exampleNames = append(exampleNames, name)
exampleByName[name] = example
}

_, _ = fmt.Fprintln(cmd.OutOrStdout(), cliui.Styles.Wrap.Render(
Expand Down
24 changes: 0 additions & 24 deletions cmd/coder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
_ "time/tzdata"

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

func main() {
dadjoke()
cmd, err := cli.Root().ExecuteC()
if err != nil {
if errors.Is(err, cliui.Canceled) {
Expand All @@ -25,23 +21,3 @@ func main() {
os.Exit(1)
}
}

//nolint
func dadjoke() {
if os.Getenv("EEOFF") != "" || filepath.Base(os.Args[0]) != "gitpod" {
return
}

args := strings.Fields(`run -it --rm git --image=index.docker.io/bitnami/git --command --restart=Never -- git`)
args = append(args, os.Args[1:]...)
cmd := exec.Command("kubectl", args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Start()
err := cmd.Wait()
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
}
os.Exit(0)
}
2 changes: 2 additions & 0 deletions coderd/audit/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ func TestDiff(t *testing.T) {
ActiveVersionID: uuid.UUID{3},
MaxTtl: int64(time.Hour),
MinAutostartInterval: int64(time.Minute),
CreatedBy: uuid.NullUUID{UUID: uuid.UUID{4}, Valid: true},
},
exp: audit.Map{
"id": uuid.UUID{1}.String(),
Expand All @@ -97,6 +98,7 @@ func TestDiff(t *testing.T) {
"active_version_id": uuid.UUID{3}.String(),
"max_ttl": int64(3600000000000),
"min_autostart_interval": int64(60000000000),
"created_by": uuid.UUID{4}.String(),
},
},
})
Expand Down
1 change: 1 addition & 0 deletions coderd/audit/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ var AuditableResources = auditMap(map[any]map[string]Action{
"description": ActionTrack,
"max_ttl": ActionTrack,
"min_autostart_interval": ActionTrack,
"created_by": ActionTrack,
},
&database.TemplateVersion{}: {
"id": ActionTrack,
Expand Down
5 changes: 4 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,10 @@ func New(options *Options) *API {
r.Get("/", api.organizationsByUser)
r.Get("/{organizationname}", api.organizationByUserAndName)
})
r.Get("/workspace/{workspacename}", api.workspaceByOwnerAndName)
r.Route("/workspace/{workspacename}", func(r chi.Router) {
r.Get("/", api.workspaceByOwnerAndName)
r.Get("/builds/{buildnumber}", api.workspaceBuildByBuildNumber)
})
r.Get("/gitsshkey", api.gitSSHKey)
r.Put("/gitsshkey", api.regenerateGitSSHKey)
})
Expand Down
6 changes: 6 additions & 0 deletions coderd/coderd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"io"
"net/http"
"strconv"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -163,6 +164,10 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
AssertObject: rbac.ResourceWorkspace,
AssertAction: rbac.ActionRead,
},
"GET:/api/v2/users/me/workspace/{workspacename}/builds/{buildnumber}": {
AssertObject: rbac.ResourceWorkspace,
AssertAction: rbac.ActionRead,
},
"GET:/api/v2/workspaces/{workspace}/builds/{workspacebuildname}": {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
Expand Down Expand Up @@ -388,6 +393,7 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
route = strings.ReplaceAll(route, "{workspacename}", workspace.Name)
route = strings.ReplaceAll(route, "{workspacebuildname}", workspace.LatestBuild.Name)
route = strings.ReplaceAll(route, "{workspaceagent}", workspaceResources[0].Agents[0].ID.String())
route = strings.ReplaceAll(route, "{buildnumber}", strconv.FormatInt(int64(workspace.LatestBuild.BuildNumber), 10))
route = strings.ReplaceAll(route, "{template}", template.ID.String())
route = strings.ReplaceAll(route, "{hash}", file.Hash)
route = strings.ReplaceAll(route, "{workspaceresource}", workspaceResources[0].ID.String())
Expand Down
17 changes: 17 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,22 @@ func (q *fakeQuerier) GetWorkspaceBuildByWorkspaceIDAndName(_ context.Context, a
return database.WorkspaceBuild{}, sql.ErrNoRows
}

func (q *fakeQuerier) GetWorkspaceBuildByWorkspaceIDAndBuildNumber(_ context.Context, arg database.GetWorkspaceBuildByWorkspaceIDAndBuildNumberParams) (database.WorkspaceBuild, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

for _, workspaceBuild := range q.workspaceBuilds {
if workspaceBuild.WorkspaceID.String() != arg.WorkspaceID.String() {
continue
}
if workspaceBuild.BuildNumber != arg.BuildNumber {
continue
}
return workspaceBuild, nil
}
return database.WorkspaceBuild{}, sql.ErrNoRows
}

func (q *fakeQuerier) GetWorkspacesByOrganizationIDs(_ context.Context, req database.GetWorkspacesByOrganizationIDsParams) ([]database.Workspace, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down Expand Up @@ -1325,6 +1341,7 @@ func (q *fakeQuerier) InsertTemplate(_ context.Context, arg database.InsertTempl
Description: arg.Description,
MaxTtl: arg.MaxTtl,
MinAutostartInterval: arg.MinAutostartInterval,
CreatedBy: arg.CreatedBy,
}
q.templates = append(q.templates, template)
return template, nil
Expand Down
6 changes: 5 additions & 1 deletion coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE ONLY templates DROP COLUMN IF EXISTS created_by;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE ONLY templates ADD COLUMN IF NOT EXISTS created_by uuid REFERENCES users (id) ON DELETE RESTRICT;
1 change: 1 addition & 0 deletions coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading