generated from brevdev/seed
-
Notifications
You must be signed in to change notification settings - Fork 10
/
start.go
387 lines (336 loc) · 12.2 KB
/
start.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Package start is for starting Brev workspaces
package start
import (
"fmt"
"strings"
"time"
"github.com/brevdev/brev-cli/pkg/cmd/completions"
"github.com/brevdev/brev-cli/pkg/config"
"github.com/brevdev/brev-cli/pkg/entity"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/brevdev/brev-cli/pkg/terminal"
"github.com/spf13/cobra"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
)
var (
startLong = "Start a Brev machine that's in a paused or off state or create one from a url"
startExample = `
brev start <existing_ws_name>
brev start <git url>
brev start <git url> --org myFancyOrg
`
)
type StartStore interface {
GetWorkspaces(organizationID string, options *store.GetWorkspacesOptions) ([]entity.Workspace, error)
GetActiveOrganizationOrDefault() (*entity.Organization, error)
GetCurrentUser() (*entity.User, error)
StartWorkspace(workspaceID string) (*entity.Workspace, error)
GetWorkspace(workspaceID string) (*entity.Workspace, error)
GetOrganizations(options *store.GetOrganizationsOptions) ([]entity.Organization, error)
CreateWorkspace(organizationID string, options *store.CreateWorkspacesOptions) (*entity.Workspace, error)
GetWorkspaceMetaData(workspaceID string) (*entity.WorkspaceMetaData, error)
}
func NewCmdStart(t *terminal.Terminal, loginStartStore StartStore, noLoginStartStore StartStore) *cobra.Command {
var org string
var name string
var detached bool
cmd := &cobra.Command{
Annotations: map[string]string{"workspace": ""},
Use: "start",
DisableFlagsInUseLine: true,
Short: "Start a workspace if it's stopped, or create one from url",
Long: startLong,
Example: startExample,
Args: cobra.ExactArgs(1),
ValidArgsFunction: completions.GetAllWorkspaceNameCompletionHandler(noLoginStartStore, t),
Run: func(cmd *cobra.Command, args []string) {
isURL := false
if strings.Contains(args[0], "https://") || strings.Contains(args[0], "git@") {
isURL = true
}
if isURL {
// CREATE A WORKSPACE
err := clone(t, args[0], org, loginStartStore, name)
if err != nil {
t.Vprint(t.Red(err.Error()))
}
} else {
// Start an existing one (either theirs or someone elses)
err := startWorkspace(args[0], loginStartStore, t, detached, name)
if err != nil {
t.Vprint(t.Red(err.Error()))
}
}
},
}
cmd.Flags().BoolVarP(&detached, "detached", "d", false, "run the command in the background instead of blocking the shell")
cmd.Flags().StringVarP(&name, "name", "n", "", "name your workspace when creating a new one")
cmd.Flags().StringVarP(&org, "org", "o", "", "organization (will override active org if creating a workspace)")
err := cmd.RegisterFlagCompletionFunc("org", completions.GetOrgsNameCompletionHandler(noLoginStartStore, t))
if err != nil {
t.Errprint(err, "cli err")
}
return cmd
}
func startWorkspace(workspaceName string, startStore StartStore, t *terminal.Terminal, detached bool, name string) error {
workspace, err := getWorkspaceFromNameOrID(workspaceName, startStore)
org, othererr := startStore.GetActiveOrganizationOrDefault()
if othererr != nil {
return breverrors.WrapAndTrace(othererr)
}
user, usererr := startStore.GetCurrentUser()
if usererr != nil {
return breverrors.WrapAndTrace(err)
}
if err != nil {
// This is not an error yet-- the user might be trying to join a team's workspace
if org == nil {
return fmt.Errorf("no orgs exist")
}
workspaces, othererr := startStore.GetWorkspaces(org.ID, &store.GetWorkspacesOptions{
Name: workspaceName,
})
if othererr != nil {
return breverrors.WrapAndTrace(othererr)
}
if len(workspaces) == 0 {
return fmt.Errorf("your team has no projects named %s", workspaceName)
}
othererr = joinProjectWithNewWorkspace(workspaces[0], t, org.ID, startStore, name, user)
if othererr != nil {
return breverrors.WrapAndTrace(othererr)
}
} else {
if workspace.Status == "RUNNING" {
t.Vprint(t.Yellow("Workspace is already running"))
return nil
}
// TODO: check the workspace isn't running first!!!
if len(name) > 0 {
t.Vprint("Existing workspace found. Name flag ignored.")
}
startedWorkspace, err := startStore.StartWorkspace(workspace.ID)
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Vprintf(t.Yellow("\nWorkspace %s is starting. \nNote: this can take about a minute. Run 'brev ls' to check status\n\n", startedWorkspace.Name))
// Don't poll and block the shell if detached flag is set
if detached {
return nil
}
err = pollUntil(t, workspace.ID, "RUNNING", startStore, true)
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Vprint(t.Green("\nYour workspace is ready!"))
workspaces, err := startStore.GetWorkspaces(org.ID, &store.GetWorkspacesOptions{UserID: user.ID})
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Vprintf(t.Green("\n\nConnect to your machine with:") +
t.Yellow("\n\tssh %s\n", startedWorkspace.GetLocalIdentifier(workspaces)))
}
return nil
}
// "https://github.com/brevdev/microservices-demo.git
// "https://github.com/brevdev/microservices-demo.git"
// "git@github.com:brevdev/microservices-demo.git"
func joinProjectWithNewWorkspace(templateWorkspace entity.Workspace, t *terminal.Terminal, orgID string, startStore StartStore, name string, user *entity.User) error {
clusterID := config.GlobalConfig.GetDefaultClusterID()
options := store.NewCreateWorkspacesOptions(clusterID, templateWorkspace.Name).WithGitRepo(templateWorkspace.GitRepo).WithWorkspaceClassID(templateWorkspace.WorkspaceClassID)
if len(name) > 0 {
options.Name = name
} else {
t.Vprintf("Name flag omitted, using auto generated name: %s", t.Green(options.Name))
}
t.Vprint("\nWorkspace is starting. " + t.Yellow("This can take up to 2 minutes the first time.\n"))
w, err := startStore.CreateWorkspace(orgID, options)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = pollUntil(t, w.ID, "RUNNING", startStore, true)
if err != nil {
return breverrors.WrapAndTrace(err)
}
workspaces, err := startStore.GetWorkspaces(orgID, &store.GetWorkspacesOptions{UserID: user.ID})
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Vprintf("\nConnect to your machine with:\n\tssh %s\n", w.GetLocalIdentifier(workspaces))
return nil
}
func clone(t *terminal.Terminal, url string, orgflag string, startStore StartStore, name string) error {
newWorkspace := MakeNewWorkspaceFromURL(url)
if len(name) > 0 {
newWorkspace.Name = name
} else {
t.Vprintf("Name flag omitted, using auto generated name: %s", t.Green(newWorkspace.Name))
}
var orgID string
if orgflag == "" {
activeorg, err := startStore.GetActiveOrganizationOrDefault()
if err != nil {
return breverrors.WrapAndTrace(err)
}
if activeorg == nil {
return fmt.Errorf("no org exist")
}
orgID = activeorg.ID
} else {
orgs, err := startStore.GetOrganizations(&store.GetOrganizationsOptions{Name: orgflag})
if err != nil {
return breverrors.WrapAndTrace(err)
}
if len(orgs) == 0 {
return fmt.Errorf("no org with name %s", orgflag)
} else if len(orgs) > 1 {
return fmt.Errorf("more than one org with name %s", orgflag)
}
orgID = orgs[0].ID
}
err := createWorkspace(t, newWorkspace, orgID, startStore)
if err != nil {
t.Vprint(t.Red(err.Error()))
}
return nil
}
type NewWorkspace struct {
Name string `json:"name"`
GitRepo string `json:"gitRepo"`
}
func MakeNewWorkspaceFromURL(url string) NewWorkspace {
if strings.Contains(url, "http") {
split := strings.Split(url, ".com/")
provider := strings.Split(split[0], "://")[1]
if strings.Contains(split[1], ".git") {
return NewWorkspace{
GitRepo: fmt.Sprintf("%s.com:%s", provider, split[1]),
Name: strings.Split(split[1], ".git")[0],
}
} else {
return NewWorkspace{
GitRepo: fmt.Sprintf("%s.com:%s.git", provider, split[1]),
Name: split[1],
}
}
} else {
split := strings.Split(url, ".com:")
provider := strings.Split(split[0], "@")[1]
return NewWorkspace{
GitRepo: fmt.Sprintf("%s.com:%s", provider, split[1]),
Name: strings.Split(split[1], ".git")[0],
}
}
}
func createWorkspace(t *terminal.Terminal, workspace NewWorkspace, orgID string, startStore StartStore) error {
t.Vprint("\nWorkspace is starting. " + t.Yellow("This can take up to 2 minutes the first time.\n"))
clusterID := config.GlobalConfig.GetDefaultClusterID()
options := store.NewCreateWorkspacesOptions(clusterID, workspace.Name).WithGitRepo(workspace.GitRepo)
w, err := startStore.CreateWorkspace(orgID, options)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = pollUntil(t, w.ID, "RUNNING", startStore, true)
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Vprint(t.Green("\nYour workspace is ready!"))
t.Vprintf(t.Green("\nSSH into your machine:\n\tssh %s\n", w.GetLocalIdentifier(nil)))
return nil
}
func pollUntil(t *terminal.Terminal, wsid string, state string, startStore StartStore, canSafelyExit bool) error {
s := t.NewSpinner()
isReady := false
if canSafelyExit {
t.Vprintf("You can safely ctrl+c to exit\n")
}
s.Suffix = " hang tight 🤙"
s.Start()
for !isReady {
time.Sleep(5 * time.Second)
ws, err := startStore.GetWorkspace(wsid)
if err != nil {
return breverrors.WrapAndTrace(err)
}
s.Suffix = " workspace is " + strings.ToLower(ws.Status)
if ws.Status == state {
s.Suffix = "Workspace is ready!"
s.Stop()
isReady = true
}
}
return nil
}
// NOTE: this function is copy/pasted in many places. If you modify it, modify it elsewhere.
// Reasoning: there wasn't a utils file so I didn't know where to put it
// + not sure how to pass a generic "store" object
func getWorkspaceFromNameOrID(nameOrID string, sstore StartStore) (*entity.WorkspaceWithMeta, error) {
// Get Active Org
org, err := sstore.GetActiveOrganizationOrDefault()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
if org == nil {
return nil, fmt.Errorf("no orgs exist")
}
// Get Current User
currentUser, err := sstore.GetCurrentUser()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
// Get Workspaces for User
var workspace *entity.Workspace // this will be the returned workspace
workspaces, err := sstore.GetWorkspaces(org.ID, &store.GetWorkspacesOptions{Name: nameOrID, UserID: currentUser.ID})
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
switch len(workspaces) {
case 0:
// In this case, check workspace by ID
wsbyid, othererr := sstore.GetWorkspace(nameOrID) // Note: workspaceName is ID in this case
if othererr != nil {
return nil, fmt.Errorf("no workspaces found with name or id %s", nameOrID)
}
if wsbyid != nil {
workspace = wsbyid
} else {
// Can this case happen?
return nil, fmt.Errorf("no workspaces found with name or id %s", nameOrID)
}
case 1:
workspace = &workspaces[0]
default:
return nil, fmt.Errorf("multiple workspaces found with name %s\n\nTry running the command by id instead of name:\n\tbrev command <id>", nameOrID)
}
if workspace == nil {
return nil, fmt.Errorf("no workspaces found with name or id %s", nameOrID)
}
// Get WorkspaceMetaData
workspaceMetaData, err := sstore.GetWorkspaceMetaData(workspace.ID)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return &entity.WorkspaceWithMeta{WorkspaceMetaData: *workspaceMetaData, Workspace: *workspace}, nil
}
// NADER IS SO FUCKING SORRY FOR DOING THIS TWICE BUT I HAVE NO CLUE WHERE THIS HELPER FUNCTION SHOULD GO SO ITS COPY/PASTED ELSEWHERE
// IF YOU MODIFY IT MODIFY IT EVERYWHERE OR PLEASE PUT IT IN ITS PROPER PLACE. thank you you're the best <3
func WorkspacesFromWorkspaceWithMeta(wwm []entity.WorkspaceWithMeta) []entity.Workspace {
var workspaces []entity.Workspace
for _, v := range wwm {
workspaces = append(workspaces, entity.Workspace{
ID: v.ID,
Name: v.Name,
WorkspaceGroupID: v.WorkspaceGroupID,
OrganizationID: v.OrganizationID,
WorkspaceClassID: v.WorkspaceClassID,
CreatedByUserID: v.CreatedByUserID,
DNS: v.DNS,
Status: v.Status,
Password: v.Password,
GitRepo: v.GitRepo,
Version: v.Version,
WorkspaceTemplate: v.WorkspaceTemplate,
})
}
return workspaces
}