/
create.go
495 lines (428 loc) · 12.4 KB
/
create.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package main
import (
"context"
"fmt"
"strconv"
"time"
"github.com/go-openapi/strfmt"
"github.com/juju/ansiterm"
"github.com/manifoldco/go-manifold"
"github.com/manifoldco/go-manifold/idtype"
"github.com/urfave/cli"
"github.com/manifoldco/manifold-cli/api"
"github.com/manifoldco/manifold-cli/clients"
"github.com/manifoldco/manifold-cli/color"
"github.com/manifoldco/manifold-cli/config"
"github.com/manifoldco/manifold-cli/data/catalog"
"github.com/manifoldco/manifold-cli/errs"
"github.com/manifoldco/manifold-cli/middleware"
"github.com/manifoldco/manifold-cli/prompts"
"github.com/manifoldco/manifold-cli/session"
"github.com/manifoldco/manifold-cli/generated/billing/client/profile"
cModels "github.com/manifoldco/manifold-cli/generated/catalog/models"
mModels "github.com/manifoldco/manifold-cli/generated/marketplace/models"
provisioning "github.com/manifoldco/manifold-cli/generated/provisioning/client"
"github.com/manifoldco/manifold-cli/generated/provisioning/client/operation"
pModels "github.com/manifoldco/manifold-cli/generated/provisioning/models"
)
func init() {
createCmd := cli.Command{
Name: "create",
ArgsUsage: "[resource-name]",
Usage: "Create a new resource",
Category: "RESOURCES",
Action: middleware.Chain(middleware.LoadDirPrefs, middleware.EnsureSession,
middleware.LoadTeamPrefs, create),
Flags: append(teamFlags, []cli.Flag{
projectFlag(),
planFlag(),
regionFlag(),
cli.StringFlag{
Name: "product",
Usage: "Create a resource for this product",
},
cli.BoolFlag{
Name: "custom, c",
Usage: "Create a custom resource, for holding custom configuration",
},
skipFlag(),
}...),
}
cmds = append(cmds, createCmd)
}
func create(cliCtx *cli.Context) error {
ctx := context.Background()
if err := maxOptionalArgsLength(cliCtx, 1); err != nil {
return err
}
teamID, err := validateTeamID(cliCtx)
if err != nil {
return err
}
dontWait := cliCtx.Bool("no-wait")
projectName, err := validateName(cliCtx, "project")
if err != nil {
return err
}
planName, err := validateName(cliCtx, "plan")
if err != nil {
return err
}
productName, err := validateName(cliCtx, "product")
if err != nil {
return err
}
regionName, err := validateName(cliCtx, "region")
if err != nil {
return err
}
custom := cliCtx.Bool("custom")
if custom && (planName != "" || productName != "" || regionName != "") {
return errs.NewUsageExitError(cliCtx, cli.NewExitError(
"You cannot specify product options for a custom resource", -1,
))
}
cfg, err := config.Load()
if err != nil {
return cli.NewExitError("Could not load config: "+err.Error(), -1)
}
s, err := session.Retrieve(ctx, cfg)
if err != nil {
return cli.NewExitError("Could not retrieve session: "+err.Error(), -1)
}
client, err := api.New(api.Catalog, api.Marketplace, api.Provisioning)
if err != nil {
return err
}
catalog, err := catalog.New(ctx, client.Catalog)
if err != nil {
return cli.NewExitError("Failed to fetch catalog data: "+err.Error(), -1)
}
var product *cModels.Product
var plan *cModels.Plan
var region *cModels.Region
if !custom {
products := catalog.Products()
productIdx, _, err := prompts.SelectProduct(products, productName)
if err != nil {
return prompts.HandleSelectError(err, "Could not select product.")
}
if planName != "" {
plan, err = catalog.FetchPlanByLabel(ctx, products[productIdx].ID, planName)
if err != nil {
return prompts.HandleSelectError(err, "Plan does not exist.")
}
_, _, err = prompts.SelectPlan([]*cModels.Plan{plan}, planName)
if err != nil {
return prompts.HandleSelectError(err, "Could not select plan.")
}
} else {
selectedPlan, err := selectPlanForCreate(ctx, teamID, catalog.Plans(), products[productIdx].ID, planName)
if err != nil {
switch err {
case errAbortSelectPlan:
return err
default:
return prompts.HandleSelectError(err, "Could not select plan.")
}
}
plan = selectedPlan
}
regions := filterRegionsForPlan(catalog.Regions(), plan.Body.Regions)
regionIdx, _, err := prompts.SelectRegion(regions)
if err != nil {
return prompts.HandleSelectError(err, "Could not select region.")
}
product = products[productIdx]
region = regions[regionIdx]
}
projects, err := clients.FetchProjects(ctx, client.Marketplace, teamID)
if err != nil {
return cli.NewExitError("Failed to fetch projects list: "+err.Error(), -1)
}
var project *mModels.Project
if len(projects) > 0 {
pidx, _, err := prompts.SelectProject(projects, projectName, true, true)
if err != nil {
return prompts.HandleSelectError(err, "Could not select project.")
}
if pidx > -1 {
project = projects[pidx]
}
}
descriptor := "a custom resource"
if !custom {
descriptor = "an instance of " + string(product.Body.Name)
}
resourceID, err := manifold.NewID(idtype.Resource)
if err != nil {
return cli.NewExitError("Could not create resource: "+err.Error(), -1)
}
prefix := manifold.Label("custom")
if product != nil {
prefix = product.Body.Label
}
resourceName, err := promptNameForResource(cliCtx, &resourceID, prefix)
if err != nil {
return err
}
resourceTitle := resourceName
spin := prompts.NewSpinner(fmt.Sprintf("Creating %s", descriptor))
if !dontWait {
spin.Start()
defer spin.Stop()
}
op, err := createResource(ctx, cfg, &resourceID, teamID, s, client.Provisioning,
custom, product, plan, region, project, resourceName, resourceTitle, dontWait)
if err != nil {
return cli.NewExitError("Could not create resource: "+err.Error(), -1)
}
provision := op.Body.(*pModels.Provision)
if !dontWait {
spin.Stop()
fmt.Printf("An instance named \"%s\" has been created!\n", *provision.Name)
return nil
}
if custom {
fmt.Printf("\nA custom resource named \"%s\" is being created!\n", *provision.Name)
} else {
fmt.Printf("\nAn instance of %s named \"%s\" is being created!\n",
product.Body.Name, *provision.Name)
}
return nil
}
var errAbortSelectPlan = cli.NewExitError("Resource creation aborted.", -1)
func selectPlanForCreate(ctx context.Context, teamID *manifold.ID, plans []*cModels.Plan, product manifold.ID, planName string) (*cModels.Plan, error) {
filteredPlans := filterPlansByProductID(plans, product)
planIdx, _, err := prompts.SelectPlan(filteredPlans, planName)
if err != nil {
return nil, prompts.HandleSelectError(err, "Could not select plan.")
}
plan := filteredPlans[planIdx]
// If the plan is not free, check if they have a billing profile
if (*plan.Body.Cost) > 0 {
_, err := retrieveBillingProfile(ctx)
if err != nil {
switch err.(type) {
case *profile.GetProfilesIDNotFound:
fmt.Println("")
fmt.Println(color.Color(ansiterm.White, "You chose a plan which is not free and have not added your billing details."))
fmt.Println("What would you like to do?")
// No billing information on file, ask how they wish to proceed
action, err := prompts.SelectBillingProfileAction()
if err != nil {
return nil, err
}
switch action {
case "Add credit card":
userID, userIDErr := loadUserID(ctx)
if userIDErr != nil && userIDErr != errUserActionAsTeam {
return nil, userIDErr
}
// Prompt the user to add their payment information
err := createNewBillingProfile(ctx, userID, teamID)
if err != nil {
return nil, err
}
case "Select different plan":
return selectPlanForCreate(ctx, teamID, plans, product, planName)
default:
return nil, errAbortSelectPlan
}
default:
return nil, cli.NewExitError("Failed to retrieve billing profile: "+err.Error(), -1)
}
}
}
return plan, nil
}
func createResource(ctx context.Context, cfg *config.Config, resourceID, teamID *manifold.ID, s session.Session,
pClient *provisioning.Provisioning, custom bool, product *cModels.Product, plan *cModels.Plan,
region *cModels.Region, project *mModels.Project, resourceName, resourceTitle string, dontWait bool) (*pModels.Operation, error) {
ID, err := manifold.NewID(idtype.Operation)
if err != nil {
return nil, err
}
var planID, productID, regionID *manifold.ID
source := "custom"
if !custom {
planID = &plan.ID
productID = &product.ID
regionID = ®ion.ID
source = "catalog"
}
var projectID *manifold.ID
if project != nil {
projectID = &project.ID
}
// TODO: Generate a label from the name if name provided..?
// TODO: Expose the Operation primitive from the core marketplace code base into
// go-manifold so we can use it here.
typeStr := "operation"
version := int64(1)
state := "provision"
curTime := strfmt.DateTime(time.Now())
op := &pModels.Operation{
ID: ID,
Type: &typeStr,
Version: &version,
Body: &pModels.Provision{
ResourceID: *resourceID,
Label: &resourceName,
Name: &resourceTitle,
Source: &source,
PlanID: planID,
ProductID: productID,
RegionID: regionID,
State: &state,
ProjectID: projectID,
},
}
op.Body.SetCreatedAt(&curTime)
op.Body.SetUpdatedAt(&curTime)
if teamID == nil {
if !s.IsUser() {
return nil, errUserActionAsTeam
}
op.Body.SetUserID(&s.User().ID)
} else {
op.Body.SetTeamID(teamID)
}
p := operation.NewPutOperationsIDParamsWithContext(ctx)
p.SetBody(op)
p.SetID(ID.String())
res, err := pClient.Operation.PutOperationsID(p, nil)
if err != nil {
switch e := err.(type) {
case *operation.PutOperationsIDBadRequest:
return nil, e.Payload
case *operation.PutOperationsIDUnauthorized:
return nil, e.Payload
case *operation.PutOperationsIDNotFound:
return nil, e.Payload
case *operation.PutOperationsIDConflict:
return nil, e.Payload
case *operation.PutOperationsIDInternalServerError:
return nil, errs.ErrSomethingWentHorriblyWrong
default:
return nil, err
}
}
if dontWait {
return res.Payload, nil
}
return waitForOp(ctx, pClient, res.Payload)
}
func waitForOp(ctx context.Context, pClient *provisioning.Provisioning, op *pModels.Operation) (*pModels.Operation, error) {
checkOp := func() (*pModels.Operation, error) {
p := operation.NewGetOperationsIDParams()
p.SetContext(ctx)
p.SetID(op.ID.String())
res, err := pClient.Operation.GetOperationsID(p, nil)
if err != nil {
switch e := err.(type) {
case *operation.GetOperationsIDBadRequest:
return nil, e.Payload
case *operation.GetOperationsIDUnauthorized:
return nil, e.Payload
case *operation.GetOperationsIDNotFound:
return nil, e.Payload
case *operation.GetOperationsIDInternalServerError:
return nil, e.Payload
default:
return nil, err
}
}
return res.Payload, nil
}
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
<-ticker.C
op, err := checkOp()
if err != nil {
return nil, err
}
switch provision := op.Body.(type) {
case *pModels.Provision:
switch *provision.State {
case "done":
return op, nil
case "error":
return nil, fmt.Errorf("Error completing provision")
default:
continue
}
case *pModels.Resize:
switch *provision.State {
case "done":
return op, nil
case "error":
return nil, fmt.Errorf("Error completing resize")
default:
continue
}
case *pModels.Deprovision:
switch *provision.State {
case "done":
return op, nil
case "error":
return nil, fmt.Errorf("Error completing delete")
default:
continue
}
case *pModels.Move:
switch *provision.State {
case "done":
return op, nil
case "error":
return nil, fmt.Errorf("Error completing move")
}
case *pModels.ProjectDelete:
switch *provision.State {
case "done":
return op, nil
case "error":
return nil, fmt.Errorf("Error completing project delete")
}
default:
return nil, fmt.Errorf("Unknown provision operation")
}
}
}
func filterPlansByProductID(plans []*cModels.Plan, productID manifold.ID) []*cModels.Plan {
out := make([]*cModels.Plan, 0, len(plans))
for _, p := range plans {
if p.Body.ProductID == productID {
out = append(out, p)
}
}
return out
}
func filterRegionsForPlan(regions []*cModels.Region, regionIDs []manifold.ID) []*cModels.Region {
out := make([]*cModels.Region, 0, len(regionIDs))
idx := make(map[manifold.ID]bool)
for _, r := range regionIDs {
idx[r] = true
}
for _, r := range regions {
_, ok := idx[r.ID]
if ok {
out = append(out, r)
}
}
return out
}
func toPrice(cost int64) string {
s := strconv.Itoa(int(cost))
if len(s) == 0 {
return "0.00"
}
if len(s) == 1 {
return "0.0" + s
}
if len(s) == 2 {
return "0." + s
}
return s[:len(s)-2] + "." + s[len(s)-2:]
}