-
Notifications
You must be signed in to change notification settings - Fork 151
/
custom_instance.go
862 lines (768 loc) · 23.7 KB
/
custom_instance.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
package rdb
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path"
"reflect"
"runtime"
"strings"
"time"
"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/human"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/passwordgenerator"
"github.com/scaleway/scaleway-cli/v2/internal/terminal"
rdbSDK "github.com/scaleway/scaleway-sdk-go/api/rdb/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
instanceActionTimeout = 20 * time.Minute
errorMessagePublicEndpointNotFound = "public endpoint not found"
errorMessagePrivateEndpointNotFound = "private endpoint not found"
errorMessageEndpointNotFound = "any endpoint is associated on your instance"
)
var (
instanceStatusMarshalSpecs = human.EnumMarshalSpecs{
rdbSDK.InstanceStatusUnknown: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "unknown"},
rdbSDK.InstanceStatusReady: &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"},
rdbSDK.InstanceStatusProvisioning: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "provisioning"},
rdbSDK.InstanceStatusConfiguring: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "configuring"},
rdbSDK.InstanceStatusDeleting: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "deleting"},
rdbSDK.InstanceStatusError: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"},
rdbSDK.InstanceStatusAutohealing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "auto-healing"},
rdbSDK.InstanceStatusLocked: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "locked"},
rdbSDK.InstanceStatusInitializing: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "initialized"},
rdbSDK.InstanceStatusDiskFull: &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "disk_full"},
rdbSDK.InstanceStatusBackuping: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "backuping"},
}
)
type serverWaitRequest struct {
InstanceID string
Region scw.Region
Timeout time.Duration
}
type CreateInstanceResult struct {
*rdbSDK.Instance
Password string `json:"password"`
}
func createInstanceResultMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
instanceResult := i.(CreateInstanceResult)
opt.Sections = []*human.MarshalSection{
{
FieldName: "Endpoint",
},
{
FieldName: "Volume",
},
{
FieldName: "BackupSchedule",
},
{
FieldName: "Settings",
},
}
instanceStr, err := human.Marshal(instanceResult.Instance, opt)
if err != nil {
return "", err
}
return strings.Join([]string{
instanceStr,
terminal.Style("Password: ", color.Bold) + "\n" + instanceResult.Password,
}, "\n\n"), nil
}
func instanceMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
// To avoid recursion of human.Marshal we create a dummy type
type tmp rdbSDK.Instance
instance := tmp(i.(rdbSDK.Instance))
// Sections
opt.Sections = []*human.MarshalSection{
{
FieldName: "Endpoint",
},
{
FieldName: "Volume",
},
{
FieldName: "BackupSchedule",
},
{
FieldName: "Settings",
},
}
str, err := human.Marshal(instance, opt)
if err != nil {
return "", err
}
return str, nil
}
func backupScheduleMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
backupSchedule := i.(rdbSDK.BackupSchedule)
if opt.TableCell {
if backupSchedule.Disabled {
return "Disabled", nil
}
return "Enabled", nil
}
// To avoid recursion of human.Marshal we create a dummy type
type LocalBackupSchedule rdbSDK.BackupSchedule
type tmp struct {
LocalBackupSchedule
Frequency *scw.Duration `json:"frequency"`
Retention *scw.Duration `json:"retention"`
}
localBackupSchedule := tmp{
LocalBackupSchedule: LocalBackupSchedule(backupSchedule),
Frequency: &scw.Duration{
Seconds: int64(backupSchedule.Frequency) * 3600,
},
Retention: &scw.Duration{
Seconds: int64(backupSchedule.Retention) * 24 * 3600,
},
}
str, err := human.Marshal(localBackupSchedule, opt)
if err != nil {
return "", err
}
return str, nil
}
func instanceCloneBuilder(c *core.Command) *core.Command {
c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
return api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
InstanceID: respI.(*rdbSDK.Instance).ID,
Region: respI.(*rdbSDK.Instance).Region,
Timeout: scw.TimeDurationPtr(instanceActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
}
return c
}
// Caching ListNodeType response for shell completion
var completeListNodeTypeCache *rdbSDK.ListNodeTypesResponse
var completeListEngineCache *rdbSDK.ListDatabaseEnginesResponse
func autoCompleteNodeType(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions {
region := scw.Region("")
switch req := request.(type) {
case *rdbSDK.CreateInstanceRequest:
region = req.Region
case *rdbSDK.UpgradeInstanceRequest:
region = req.Region
}
suggestions := core.AutocompleteSuggestions(nil)
client := core.ExtractClient(ctx)
api := rdbSDK.NewAPI(client)
if completeListNodeTypeCache == nil {
res, err := api.ListNodeTypes(&rdbSDK.ListNodeTypesRequest{
Region: region,
}, scw.WithAllPages())
if err != nil {
return nil
}
completeListNodeTypeCache = res
}
for _, nodeType := range completeListNodeTypeCache.NodeTypes {
if strings.HasPrefix(nodeType.Name, prefix) {
suggestions = append(suggestions, nodeType.Name)
}
}
return suggestions
}
func autoCompleteDatabaseEngines(ctx context.Context, prefix string, request any) core.AutocompleteSuggestions {
req := request.(*rdbSDK.CreateInstanceRequest)
suggestion := core.AutocompleteSuggestions(nil)
client := core.ExtractClient(ctx)
api := rdbSDK.NewAPI(client)
if completeListEngineCache == nil {
res, err := api.ListDatabaseEngines(&rdbSDK.ListDatabaseEnginesRequest{
Region: req.Region,
}, scw.WithAllPages())
if err != nil {
return nil
}
completeListEngineCache = res
}
for _, engine := range completeListEngineCache.Engines {
if strings.HasPrefix(engine.Name, prefix) {
suggestion = append(suggestion, engine.Name)
}
}
return suggestion
}
func instanceCreateBuilder(c *core.Command) *core.Command {
type rdbCreateInstanceRequestCustom struct {
*rdbSDK.CreateInstanceRequest
InitEndpoints []*rdbEndpointSpecCustom `json:"init-endpoints"`
GeneratePassword bool
}
c.ArgSpecs.AddBefore("init-endpoints.{index}.private-network.private-network-id", &core.ArgSpec{
Name: "init-endpoints.{index}.load-balancer",
Short: "Will configure a load-balancer endpoint along with your private network endpoint if true",
Required: false,
Default: core.DefaultValueSetter("false"),
})
c.ArgSpecs.AddBefore("init-endpoints.{index}.private-network.private-network-id", &core.ArgSpec{
Name: "init-endpoints.{index}.private-network.enable-ipam",
Short: "Will configure your Private Network endpoint with Scaleway IPAM service if true",
Required: false,
Default: core.DefaultValueSetter("false"),
})
c.ArgSpecs.AddBefore("password", &core.ArgSpec{
Name: "generate-password",
Short: `Will generate a 21 character-length password that contains a mix of upper/lower case letters, numbers and special symbols`,
Required: false,
Deprecated: false,
Positional: false,
Default: core.DefaultValueSetter("true"),
})
c.ArgSpecs.GetByName("password").Required = false
c.ArgSpecs.GetByName("node-type").Default = core.DefaultValueSetter("DB-DEV-S")
c.ArgSpecs.GetByName("node-type").AutoCompleteFunc = autoCompleteNodeType
c.ArgSpecs.GetByName("engine").AutoCompleteFunc = autoCompleteDatabaseEngines
c.ArgsType = reflect.TypeOf(rdbCreateInstanceRequestCustom{})
c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
instance, err := api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
InstanceID: respI.(CreateInstanceResult).Instance.ID,
Region: respI.(CreateInstanceResult).Instance.Region,
Timeout: scw.TimeDurationPtr(instanceActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
if err != nil {
return nil, err
}
result := CreateInstanceResult{
Instance: instance,
Password: respI.(CreateInstanceResult).Password,
}
return result, nil
}
c.Run = func(ctx context.Context, argsI interface{}) (interface{}, error) {
client := core.ExtractClient(ctx)
api := rdbSDK.NewAPI(client)
customRequest := argsI.(*rdbCreateInstanceRequestCustom)
createInstanceRequest := customRequest.CreateInstanceRequest
var err error
createInstanceRequest.NodeType = strings.ToLower(createInstanceRequest.NodeType)
if customRequest.GeneratePassword && customRequest.Password == "" {
createInstanceRequest.Password, err = passwordgenerator.GeneratePassword(21, 1, 1, 1, 1)
if err != nil {
return nil, err
}
fmt.Printf("Your generated password is %s \n", createInstanceRequest.Password)
fmt.Printf("\n")
}
createInstanceRequest.InitEndpoints, err = endpointRequestFromCustom(customRequest.InitEndpoints)
if err != nil {
return nil, err
}
instance, err := api.CreateInstance(createInstanceRequest)
if err != nil {
return nil, err
}
result := CreateInstanceResult{
Instance: instance,
Password: createInstanceRequest.Password,
}
return result, nil
}
// Waiting for API to accept uppercase node-type
c.Interceptor = func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) {
args := argsI.(*rdbCreateInstanceRequestCustom)
args.NodeType = strings.ToLower(args.NodeType)
return runner(ctx, args)
}
return c
}
func instanceGetBuilder(c *core.Command) *core.Command {
c.Interceptor = func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) {
res, err := runner(ctx, argsI)
if err != nil {
return nil, err
}
instance := res.(*rdbSDK.Instance)
args := argsI.(*rdbSDK.GetInstanceRequest)
acls, err := rdbSDK.NewAPI(core.ExtractClient(ctx)).ListInstanceACLRules(&rdbSDK.ListInstanceACLRulesRequest{
Region: args.Region,
InstanceID: args.InstanceID,
}, scw.WithAllPages())
if err != nil {
return res, nil
}
return struct {
*rdbSDK.Instance
ACLs []*rdbSDK.ACLRule `json:"acls"`
}{
instance,
acls.Rules,
}, nil
}
c.View = &core.View{
Sections: []*core.ViewSection{
{
FieldName: "Endpoint",
Title: "Endpoint",
},
{
FieldName: "Volume",
Title: "Volume",
},
{
FieldName: "BackupSchedule",
Title: "Backup schedule",
},
{
FieldName: "Settings",
Title: "Settings",
HideIfEmpty: true,
},
{
FieldName: "ACLs",
Title: "ACLs",
HideIfEmpty: true,
},
},
}
return c
}
func instanceUpgradeBuilder(c *core.Command) *core.Command {
c.ArgSpecs.GetByName("node-type").AutoCompleteFunc = autoCompleteNodeType
c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
return api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
InstanceID: respI.(*rdbSDK.Instance).ID,
Region: respI.(*rdbSDK.Instance).Region,
Timeout: scw.TimeDurationPtr(instanceActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
}
return c
}
func instanceUpdateBuilder(_ *core.Command) *core.Command {
type rdbUpdateInstanceRequestCustom struct {
*rdbSDK.UpdateInstanceRequest
Settings []*rdbSDK.InstanceSetting
}
return &core.Command{
Short: `Update an instance`,
Long: `Update an instance.`,
Namespace: "rdb",
Resource: "instance",
Verb: "update",
ArgsType: reflect.TypeOf(rdbUpdateInstanceRequestCustom{}),
ArgSpecs: core.ArgSpecs{
{
Name: "backup-schedule-frequency",
Short: `In hours`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "backup-schedule-retention",
Short: `In days`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "is-backup-schedule-disabled",
Short: `Whether or not the backup schedule is disabled`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "name",
Short: `Name of the instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "instance-id",
Short: `UUID of the instance to update`,
Required: true,
Deprecated: false,
Positional: true,
},
{
Name: "tags.{index}",
Short: `Tags of a given instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "logs-policy.max-age-retention",
Short: `Max age (in day) of remote logs to keep on the database instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "logs-policy.total-disk-retention",
Short: `Max disk size of remote logs to keep on the database instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "backup-same-region",
Short: `Store logical backups in the same region as the database instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "settings.{index}.name",
Short: `Setting name of a given instance`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "settings.{index}.value",
Short: `Setting value of a given instance`,
Required: false,
Deprecated: false,
Positional: false,
},
core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw),
},
Run: func(ctx context.Context, args interface{}) (i interface{}, e error) {
customRequest := args.(*rdbUpdateInstanceRequestCustom)
updateInstanceRequest := customRequest.UpdateInstanceRequest
client := core.ExtractClient(ctx)
api := rdbSDK.NewAPI(client)
getResp, err := api.GetInstance(&rdbSDK.GetInstanceRequest{
Region: customRequest.Region,
InstanceID: customRequest.InstanceID,
})
if err != nil {
return nil, err
}
if customRequest.Settings != nil {
settings := getResp.Settings
changes := customRequest.Settings
for _, change := range changes {
matched := false
for _, setting := range settings {
if change.Name == setting.Name {
setting.Value = change.Value
matched = true
break
}
}
if !matched {
settings = append(settings, change)
}
}
_, err = api.SetInstanceSettings(&rdbSDK.SetInstanceSettingsRequest{
Region: updateInstanceRequest.Region,
InstanceID: updateInstanceRequest.InstanceID,
Settings: settings,
})
if err != nil {
return nil, err
}
}
updateInstanceResponse, err := api.UpdateInstance(updateInstanceRequest)
if err != nil {
return nil, err
}
return updateInstanceResponse, nil
},
WaitFunc: func(ctx context.Context, _, respI interface{}) (interface{}, error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
return api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
InstanceID: respI.(*rdbSDK.Instance).ID,
Region: respI.(*rdbSDK.Instance).Region,
Timeout: scw.TimeDurationPtr(instanceActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
},
Examples: []*core.Example{
{
Short: "Update instance name",
Raw: "scw rdb instance update 11111111-1111-1111-1111-111111111111 name=foo --wait",
},
{
Short: "Update instance tags",
Raw: "scw rdb instance update 11111111-1111-1111-1111-111111111111 tags.0=a --wait",
},
{
Short: "Set a timezone",
Raw: "scw rdb instance update 11111111-1111-1111-1111-111111111111 settings.0.name=timezone settings.0.value=UTC --wait",
},
},
}
}
func instanceDeleteBuilder(c *core.Command) *core.Command {
c.WaitFunc = func(ctx context.Context, _, respI interface{}) (interface{}, error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
instance, err := api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
InstanceID: respI.(*rdbSDK.Instance).ID,
Region: respI.(*rdbSDK.Instance).Region,
Timeout: scw.TimeDurationPtr(instanceActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
if err != nil {
// if we get a 404 here, it means the resource was successfully deleted
notFoundError := &scw.ResourceNotFoundError{}
responseError := &scw.ResponseError{}
if errors.As(err, &responseError) && responseError.StatusCode == http.StatusNotFound || errors.As(err, ¬FoundError) {
return instance, nil
}
return nil, err
}
return instance, nil
}
return c
}
func instanceWaitCommand() *core.Command {
return &core.Command{
Short: `Wait for an instance to reach a stable state`,
Long: `Wait for an instance to reach a stable state. This is similar to using --wait flag.`,
Namespace: "rdb",
Resource: "instance",
Verb: "wait",
Groups: []string{"workflow"},
ArgsType: reflect.TypeOf(serverWaitRequest{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
api := rdbSDK.NewAPI(core.ExtractClient(ctx))
return api.WaitForInstance(&rdbSDK.WaitForInstanceRequest{
Region: argsI.(*serverWaitRequest).Region,
InstanceID: argsI.(*serverWaitRequest).InstanceID,
Timeout: scw.TimeDurationPtr(argsI.(*serverWaitRequest).Timeout),
RetryInterval: core.DefaultRetryInterval,
})
},
ArgSpecs: core.ArgSpecs{
{
Name: "instance-id",
Short: `ID of the instance you want to wait for.`,
Required: true,
Positional: true,
},
core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms),
core.WaitTimeoutArgSpec(instanceActionTimeout),
},
Examples: []*core.Example{
{
Short: "Wait for an instance to reach a stable state",
ArgsJSON: `{"instance_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
type instanceConnectArgs struct {
Region scw.Region
PrivateNetwork bool
InstanceID string
Username string
Database *string
CliDB *string
}
type engineFamily string
const (
Unknown = engineFamily("Unknown")
PostgreSQL = engineFamily("PostgreSQL")
MySQL = engineFamily("MySQL")
postgreSQLHint = `
psql supports password file to avoid typing your password manually.
Learn more at: https://www.postgresql.org/docs/current/libpq-pgpass.html`
mySQLHint = `
mysql supports loading your password from a file to avoid typing them manually.
Learn more at: https://dev.mysql.com/doc/refman/8.0/en/option-files.html`
)
func passwordFileExist(ctx context.Context, family engineFamily) bool {
passwordFilePath := ""
switch family {
case PostgreSQL:
switch runtime.GOOS {
case "windows":
passwordFilePath = path.Join(core.ExtractUserHomeDir(ctx), core.ExtractEnv(ctx, "APPDATA"), "postgresql", "pgpass.conf")
default:
passwordFilePath = path.Join(core.ExtractUserHomeDir(ctx), ".pgpass")
}
case MySQL:
passwordFilePath = path.Join(core.ExtractUserHomeDir(ctx), ".my.cnf")
default:
return false
}
if passwordFilePath == "" {
return false
}
_, err := os.Stat(passwordFilePath)
return err == nil
}
func passwordFileHint(family engineFamily) string {
switch family {
case PostgreSQL:
return postgreSQLHint
case MySQL:
return mySQLHint
default:
return ""
}
}
func detectEngineFamily(instance *rdbSDK.Instance) (engineFamily, error) {
if instance == nil {
return Unknown, fmt.Errorf("instance engine is nil")
}
if strings.HasPrefix(instance.Engine, string(PostgreSQL)) {
return PostgreSQL, nil
}
if strings.HasPrefix(instance.Engine, string(MySQL)) {
return MySQL, nil
}
return Unknown, fmt.Errorf("unknown engine: %s", instance.Engine)
}
func getPublicEndpoint(endpoints []*rdbSDK.Endpoint) (*rdbSDK.Endpoint, error) {
for _, e := range endpoints {
if e.LoadBalancer != nil {
return e, nil
}
}
return nil, fmt.Errorf(errorMessagePublicEndpointNotFound)
}
func getPrivateEndpoint(endpoints []*rdbSDK.Endpoint) (*rdbSDK.Endpoint, error) {
for _, e := range endpoints {
if e.PrivateNetwork != nil {
return e, nil
}
}
return nil, fmt.Errorf(errorMessagePrivateEndpointNotFound)
}
func createConnectCommandLineArgs(endpoint *rdbSDK.Endpoint, family engineFamily, args *instanceConnectArgs) ([]string, error) {
database := "rdb"
if args.Database != nil {
database = *args.Database
}
switch family {
case PostgreSQL:
clidb := "psql"
if args.CliDB != nil {
clidb = *args.CliDB
}
// psql -h 51.159.25.206 --port 13917 -d rdb -U username
return []string{
clidb,
"--host", endpoint.IP.String(),
"--port", fmt.Sprintf("%d", endpoint.Port),
"--username", args.Username,
"--dbname", database,
}, nil
case MySQL:
clidb := "mysql"
if args.CliDB != nil {
clidb = *args.CliDB
}
// mysql -h 195.154.69.163 --port 12210 -p -u username
return []string{
clidb,
"--host", endpoint.IP.String(),
"--port", fmt.Sprintf("%d", endpoint.Port),
"--database", database,
"--user", args.Username,
}, nil
}
return nil, fmt.Errorf("unrecognize database engine: %s", family)
}
func instanceConnectCommand() *core.Command {
return &core.Command{
Namespace: "rdb",
Resource: "instance",
Verb: "connect",
Short: "Connect to an instance using locally installed CLI",
Long: "Connect to an instance using locally installed CLI such as psql or mysql.",
ArgsType: reflect.TypeOf(instanceConnectArgs{}),
ArgSpecs: core.ArgSpecs{
{
Name: "private-network",
Short: `Connect by the private network endpoint attached.`,
Required: false,
Default: core.DefaultValueSetter("false"),
},
{
Name: "instance-id",
Short: `UUID of the instance`,
Required: true,
Positional: true,
},
{
Name: "username",
Short: "Name of the user to connect with to the database",
Required: true,
},
{
Name: "database",
Short: "Name of the database",
Default: core.DefaultValueSetter("rdb"),
},
{
Name: "cli-db",
Short: "Command line tool to use, default to psql/mysql",
},
core.RegionArgSpec(scw.RegionFrPar, scw.RegionNlAms),
},
Run: func(ctx context.Context, argsI interface{}) (interface{}, error) {
args := argsI.(*instanceConnectArgs)
client := core.ExtractClient(ctx)
api := rdbSDK.NewAPI(client)
instance, err := api.GetInstance(&rdbSDK.GetInstanceRequest{
Region: args.Region,
InstanceID: args.InstanceID,
})
if err != nil {
return nil, err
}
engineFamily, err := detectEngineFamily(instance)
if err != nil {
return nil, err
}
if len(instance.Endpoints) == 0 {
return nil, fmt.Errorf(errorMessageEndpointNotFound)
}
var endpoint *rdbSDK.Endpoint
switch {
case args.PrivateNetwork:
endpoint, err = getPrivateEndpoint(instance.Endpoints)
if err != nil {
return nil, err
}
default:
endpoint, err = getPublicEndpoint(instance.Endpoints)
if err != nil {
return nil, err
}
}
cmdArgs, err := createConnectCommandLineArgs(endpoint, engineFamily, args)
if err != nil {
return nil, err
}
if !passwordFileExist(ctx, engineFamily) {
interactive.Println(passwordFileHint(engineFamily))
}
// Run command
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) //nolint:gosec
//cmd.Stdin = os.Stdin
core.ExtractLogger(ctx).Debugf("executing: %s\n", cmd.Args)
exitCode, err := core.ExecCmd(ctx, cmd)
if err != nil {
return nil, err
}
if exitCode != 0 {
return nil, &core.CliError{Empty: true, Code: exitCode}
}
return &core.SuccessResult{
Empty: true, // the program will output the success message
}, nil
},
}
}