Skip to content

Commit a44070e

Browse files
authored
feat(scaletest): allow scaletests to run using the host credentials (#7075)
1 parent 2585249 commit a44070e

File tree

6 files changed

+93
-54
lines changed

6 files changed

+93
-54
lines changed

cli/scaletest.go

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ func (r *RootCmd) scaletestCleanup() *clibase.Cmd {
471471
}
472472

473473
cliui.Errorf(inv.Stderr, "Found %d scaletest users\n", len(users))
474-
if len(workspaces) != 0 {
474+
if len(users) != 0 {
475475
cliui.Infof(inv.Stdout, "Deleting scaletest users..."+"\n")
476476
harness := harness.NewTestHarness(cleanupStrategy.toStrategy(), harness.ConcurrentExecutionStrategy{})
477477

@@ -535,6 +535,8 @@ func (r *RootCmd) scaletestCreateWorkspaces() *clibase.Cmd {
535535
connectInterval time.Duration
536536
connectTimeout time.Duration
537537

538+
useHostUser bool
539+
538540
tracingFlags = &scaletestTracingFlags{}
539541
strategy = &scaletestStrategyFlags{}
540542
cleanupStrategy = &scaletestStrategyFlags{cleanup: true}
@@ -693,35 +695,37 @@ func (r *RootCmd) scaletestCreateWorkspaces() *clibase.Cmd {
693695
const name = "workspacebuild"
694696
id := strconv.Itoa(i)
695697

696-
username, email, err := newScaleTestUser(id)
697-
if err != nil {
698-
return xerrors.Errorf("create scaletest username and email: %w", err)
699-
}
700-
workspaceName, err := newScaleTestWorkspace(id)
701-
if err != nil {
702-
return xerrors.Errorf("create scaletest workspace name: %w", err)
703-
}
704-
705698
config := createworkspaces.Config{
706699
User: createworkspaces.UserConfig{
707700
// TODO: configurable org
708701
OrganizationID: me.OrganizationIDs[0],
709-
Username: username,
710-
Email: email,
711702
},
712703
Workspace: workspacebuild.Config{
713704
OrganizationID: me.OrganizationIDs[0],
714705
// UserID is set by the test automatically.
715706
Request: codersdk.CreateWorkspaceRequest{
716707
TemplateID: tpl.ID,
717-
Name: workspaceName,
718708
ParameterValues: params,
719709
},
720710
NoWaitForAgents: noWaitForAgents,
721711
},
722712
NoCleanup: noCleanup,
723713
}
724714

715+
if useHostUser {
716+
config.User.SessionToken = client.SessionToken()
717+
} else {
718+
config.User.Username, config.User.Email, err = newScaleTestUser(id)
719+
if err != nil {
720+
return xerrors.Errorf("create scaletest username and email: %w", err)
721+
}
722+
}
723+
724+
config.Workspace.Request.Name, err = newScaleTestWorkspace(id)
725+
if err != nil {
726+
return xerrors.Errorf("create scaletest workspace name: %w", err)
727+
}
728+
725729
if runCommand != "" {
726730
config.ReconnectingPTY = &reconnectingpty.Config{
727731
// AgentID is set by the test automatically.
@@ -927,6 +931,13 @@ func (r *RootCmd) scaletestCreateWorkspaces() *clibase.Cmd {
927931
Description: "Timeout for each request to the --connect-url.",
928932
Value: clibase.DurationOf(&connectTimeout),
929933
},
934+
{
935+
Flag: "use-host-login",
936+
Env: "CODER_SCALETEST_USE_HOST_LOGIN",
937+
Default: "false",
938+
Description: "Use the use logged in on the host machine, instead of creating users.",
939+
Value: clibase.BoolOf(&useHostUser),
940+
},
930941
}
931942

932943
tracingFlags.attach(&cmd.Options)
@@ -1009,9 +1020,6 @@ func isScaleTestUser(user codersdk.User) bool {
10091020
}
10101021

10111022
func isScaleTestWorkspace(workspace codersdk.Workspace) bool {
1012-
if !strings.HasPrefix(workspace.OwnerName, "scaletest-") {
1013-
return false
1014-
}
1015-
1016-
return strings.HasPrefix(workspace.Name, "scaletest-")
1023+
return strings.HasPrefix(workspace.OwnerName, "scaletest-") ||
1024+
strings.HasPrefix(workspace.Name, "scaletest-")
10171025
}

cli/testdata/coder_scaletest_create-workspaces_--help.golden

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,5 +116,8 @@ It is recommended that all rate limits are disabled on the server before running
116116
if the server is configured with the exact same tracing configuration
117117
as the client.
118118

119+
--use-host-login bool, $CODER_SCALETEST_USE_HOST_LOGIN (default: false)
120+
Use the use logged in on the host machine, instead of creating users.
121+
119122
---
120123
Run `coder --help` for a list of global options.

coderd/provisionerdserver/provisionerdserver.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -490,14 +490,14 @@ func (server *Server) UpdateJob(ctx context.Context, request *proto.UpdateJobReq
490490
slog.F("stage", log.Stage),
491491
slog.F("output", log.Output))
492492
}
493-
//nolint:gocritic // Provisionerd has specific authz rules.
494-
logs, err := server.Database.InsertProvisionerJobLogs(dbauthz.AsProvisionerd(context.Background()), insertParams)
493+
494+
logs, err := server.Database.InsertProvisionerJobLogs(ctx, insertParams)
495495
if err != nil {
496496
server.Logger.Error(ctx, "failed to insert job logs", slog.F("job_id", parsedID), slog.Error(err))
497497
return nil, xerrors.Errorf("insert job logs: %w", err)
498498
}
499-
// Publish by the lowest log ID inserted so the
500-
// log stream will fetch everything from that point.
499+
// Publish by the lowest log ID inserted so the log stream will fetch
500+
// everything from that point.
501501
lowestID := logs[0].ID
502502
server.Logger.Debug(ctx, "inserted job logs", slog.F("job_id", parsedID))
503503
data, err := json.Marshal(ProvisionerJobLogsNotifyMessage{

docs/cli/scaletest_create-workspaces.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,13 @@ Enables trace exporting to Honeycomb.io using the provided API key.
282282
| Environment | <code>$CODER_SCALETEST_TRACE_PROPAGATE</code> |
283283

284284
Enables trace propagation to the Coder backend, which will be used to correlate server-side spans with client-side spans. Only enable this if the server is configured with the exact same tracing configuration as the client.
285+
286+
### --use-host-login
287+
288+
| | |
289+
| ----------- | -------------------------------------------- |
290+
| Type | <code>bool</code> |
291+
| Environment | <code>$CODER_SCALETEST_USE_HOST_LOGIN</code> |
292+
| Default | <code>false</code> |
293+
294+
Use the use logged in on the host machine, instead of creating users.

scaletest/createworkspaces/config.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ type UserConfig struct {
1717
Username string `json:"username"`
1818
// Email is the email of the new user.
1919
Email string `json:"email"`
20+
// SessionToken is the session token of an already existing user. If set, no
21+
// user will be created.
22+
SessionToken string `json:"session_token"`
2023
}
2124

2225
func (c UserConfig) Validate() error {

scaletest/createworkspaces/run.go

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -52,44 +52,59 @@ func (r *Runner) Run(ctx context.Context, id string, logs io.Writer) error {
5252
r.client.Logger = logger
5353
r.client.LogBodies = true
5454

55-
_, _ = fmt.Fprintln(logs, "Generating user password...")
56-
password, err := cryptorand.String(16)
57-
if err != nil {
58-
return xerrors.Errorf("generate random password for user: %w", err)
55+
var (
56+
client = r.client
57+
user codersdk.User
58+
err error
59+
)
60+
if r.cfg.User.SessionToken != "" {
61+
_, _ = fmt.Fprintln(logs, "Using existing user session token:")
62+
user, err = client.User(ctx, "me")
63+
if err != nil {
64+
return xerrors.Errorf("generate random password for user: %w", err)
65+
}
66+
} else {
67+
_, _ = fmt.Fprintln(logs, "Generating user password...")
68+
password, err := cryptorand.String(16)
69+
if err != nil {
70+
return xerrors.Errorf("generate random password for user: %w", err)
71+
}
72+
73+
_, _ = fmt.Fprintln(logs, "Creating user:")
74+
75+
user, err := r.client.CreateUser(ctx, codersdk.CreateUserRequest{
76+
OrganizationID: r.cfg.User.OrganizationID,
77+
Username: r.cfg.User.Username,
78+
Email: r.cfg.User.Email,
79+
Password: password,
80+
})
81+
if err != nil {
82+
return xerrors.Errorf("create user: %w", err)
83+
}
84+
r.userID = user.ID
85+
86+
_, _ = fmt.Fprintln(logs, "\nLogging in as new user...")
87+
client = codersdk.New(r.client.URL)
88+
loginRes, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
89+
Email: r.cfg.User.Email,
90+
Password: password,
91+
})
92+
if err != nil {
93+
return xerrors.Errorf("login as new user: %w", err)
94+
}
95+
client.SetSessionToken(loginRes.SessionToken)
5996
}
6097

61-
_, _ = fmt.Fprintln(logs, "Creating user:")
6298
_, _ = fmt.Fprintf(logs, "\tOrg ID: %s\n", r.cfg.User.OrganizationID.String())
63-
_, _ = fmt.Fprintf(logs, "\tUsername: %s\n", r.cfg.User.Username)
64-
_, _ = fmt.Fprintf(logs, "\tEmail: %s\n", r.cfg.User.Email)
99+
_, _ = fmt.Fprintf(logs, "\tUsername: %s\n", user.Username)
100+
_, _ = fmt.Fprintf(logs, "\tEmail: %s\n", user.Email)
65101
_, _ = fmt.Fprintf(logs, "\tPassword: ****************\n")
66-
user, err := r.client.CreateUser(ctx, codersdk.CreateUserRequest{
67-
OrganizationID: r.cfg.User.OrganizationID,
68-
Username: r.cfg.User.Username,
69-
Email: r.cfg.User.Email,
70-
Password: password,
71-
})
72-
if err != nil {
73-
return xerrors.Errorf("create user: %w", err)
74-
}
75-
r.userID = user.ID
76-
77-
_, _ = fmt.Fprintln(logs, "\nLogging in as new user...")
78-
userClient := codersdk.New(r.client.URL)
79-
loginRes, err := userClient.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
80-
Email: r.cfg.User.Email,
81-
Password: password,
82-
})
83-
if err != nil {
84-
return xerrors.Errorf("login as new user: %w", err)
85-
}
86-
userClient.SetSessionToken(loginRes.SessionToken)
87102

88103
_, _ = fmt.Fprintln(logs, "\nCreating workspace...")
89104
workspaceBuildConfig := r.cfg.Workspace
90105
workspaceBuildConfig.OrganizationID = r.cfg.User.OrganizationID
91106
workspaceBuildConfig.UserID = user.ID.String()
92-
r.workspacebuildRunner = workspacebuild.NewRunner(userClient, workspaceBuildConfig)
107+
r.workspacebuildRunner = workspacebuild.NewRunner(client, workspaceBuildConfig)
93108
err = r.workspacebuildRunner.Run(ctx, id, logs)
94109
if err != nil {
95110
return xerrors.Errorf("create workspace: %w", err)
@@ -104,7 +119,7 @@ func (r *Runner) Run(ctx context.Context, id string, logs io.Writer) error {
104119
if err != nil {
105120
return xerrors.Errorf("get workspace ID: %w", err)
106121
}
107-
workspace, err := userClient.Workspace(ctx, workspaceID)
122+
workspace, err := client.Workspace(ctx, workspaceID)
108123
if err != nil {
109124
return xerrors.Errorf("get workspace %q: %w", workspaceID.String(), err)
110125
}
@@ -128,7 +143,7 @@ resourceLoop:
128143
reconnectingPTYConfig := *r.cfg.ReconnectingPTY
129144
reconnectingPTYConfig.AgentID = agent.ID
130145

131-
reconnectingPTYRunner := reconnectingpty.NewRunner(userClient, reconnectingPTYConfig)
146+
reconnectingPTYRunner := reconnectingpty.NewRunner(client, reconnectingPTYConfig)
132147
err := reconnectingPTYRunner.Run(egCtx, id, logs)
133148
if err != nil {
134149
return xerrors.Errorf("run reconnecting pty: %w", err)
@@ -142,7 +157,7 @@ resourceLoop:
142157
agentConnConfig := *r.cfg.AgentConn
143158
agentConnConfig.AgentID = agent.ID
144159

145-
agentConnRunner := agentconn.NewRunner(userClient, agentConnConfig)
160+
agentConnRunner := agentconn.NewRunner(client, agentConnConfig)
146161
err := agentConnRunner.Run(egCtx, id, logs)
147162
if err != nil {
148163
return xerrors.Errorf("run agent connection: %w", err)

0 commit comments

Comments
 (0)