-
Notifications
You must be signed in to change notification settings - Fork 374
/
databases.go
1854 lines (1463 loc) · 63.3 KB
/
databases.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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2018 The Doctl Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package commands
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/digitalocean/doctl"
"github.com/digitalocean/doctl/commands/displayers"
"github.com/digitalocean/doctl/do"
"github.com/digitalocean/godo"
"github.com/spf13/cobra"
)
const (
defaultDatabaseNodeSize = "db-s-1vcpu-1gb"
defaultDatabaseNodeCount = 1
defaultDatabaseRegion = "nyc1"
defaultDatabaseEngine = "pg"
databaseListDetails = `
This command requires the ID of a database cluster, which you can retrieve by calling:
doctl databases list`
)
// Databases creates the databases command
func Databases() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "databases",
Aliases: []string{"db", "dbs", "d", "database"},
Short: "Display commands that manage databases",
Long: "The commands under `doctl databases` are for managing your MySQL, Redis, PostgreSQL, and MongoDB database services.",
},
}
clusterDetails := `
- The database ID, in UUID format
- The name you gave the database cluster
- The database engine (e.g. ` + "`redis`, `pg`, `mysql` , or `mongodb`" + `)
- The engine version (e.g. ` + "`14`" + ` for PostgreSQL version 14)
- The number of nodes in the database cluster
- The region the database cluster resides in (e.g. ` + "`sfo2`, " + "`nyc1`" + `)
- The current status of the database cluster (e.g. ` + "`online`" + `)
- The size of the machine running the database instance (e.g. ` + "`db-s-1vcpu-1gb`" + `)`
CmdBuilder(cmd, RunDatabaseList, "list", "List your database clusters", `This command lists the database clusters associated with your account. The following details are provided:`+clusterDetails, Writer, aliasOpt("ls"), displayerType(&displayers.Databases{}))
CmdBuilder(cmd, RunDatabaseGet, "get <database-id>", "Get details for a database cluster", `This command retrieves the following details about the specified database cluster: `+clusterDetails+`
- A connection string for the database cluster
- The date and time when the database cluster was created`+databaseListDetails, Writer, aliasOpt("g"), displayerType(&displayers.Databases{}))
nodeSizeDetails := "The size of the nodes in the database cluster, e.g. `db-s-1vcpu-1gb`` for a 1 CPU, 1GB node. For a list of available size slugs, visit: https://docs.digitalocean.com/reference/api/api-reference/#tag/Databases"
nodeNumberDetails := "The number of nodes in the database cluster. Valid values are are 1-3. In addition to the primary node, up to two standby nodes may be added for high availability."
cmdDatabaseCreate := CmdBuilder(cmd, RunDatabaseCreate, "create <name>", "Create a database cluster", `This command creates a database cluster with the specified name.
There are a number of flags that customize the configuration, all of which are optional. Without any flags set, a single-node, single-CPU PostgreSQL database cluster will be created.`, Writer,
aliasOpt("c"))
AddIntFlag(cmdDatabaseCreate, doctl.ArgDatabaseNumNodes, "", defaultDatabaseNodeCount, nodeNumberDetails)
AddStringFlag(cmdDatabaseCreate, doctl.ArgRegionSlug, "", defaultDatabaseRegion, "The region where the database cluster will be created, e.g. `nyc1` or `sfo2`")
AddStringFlag(cmdDatabaseCreate, doctl.ArgSizeSlug, "", defaultDatabaseNodeSize, nodeSizeDetails)
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseEngine, "", defaultDatabaseEngine, "The database engine to be used for the cluster. Possible values are: `pg` for PostgreSQL, `mysql`, `redis`, and `mongodb`.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgVersion, "", "", "The database engine version, e.g. 14 for PostgreSQL version 14")
AddStringFlag(cmdDatabaseCreate, doctl.ArgPrivateNetworkUUID, "", "", "The UUID of a VPC to create the database cluster in; the default VPC for the region will be used if excluded")
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseRestoreFromClusterName, "", "", "The name of an existing database cluster from which the backup will be restored.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseRestoreFromTimestamp, "", "", "The timestamp of an existing database cluster backup in UTC combined date and time format (2006-01-02 15:04:05 +0000 UTC). The most recent backup will be used if excluded.")
AddBoolFlag(cmdDatabaseCreate, doctl.ArgCommandWait, "", false, "Boolean that specifies whether to wait for a database to complete before returning control to the terminal")
cmdDatabaseDelete := CmdBuilder(cmd, RunDatabaseDelete, "delete <database-id>", "Delete a database cluster", `This command deletes the database cluster with the given ID.
To retrieve a list of your database clusters and their IDs, call `+"`"+`doctl databases list`+"`"+`.`, Writer,
aliasOpt("rm"))
AddBoolFlag(cmdDatabaseDelete, doctl.ArgForce, doctl.ArgShortForce, false, "Delete the database cluster without a confirmation prompt")
CmdBuilder(cmd, RunDatabaseConnectionGet, "connection <database-id>", "Retrieve connection details for a database cluster", `This command retrieves the following connection details for a database cluster:
- The connection string for the database cluster
- The default database name
- The fully-qualified domain name of the publicly-connectable host
- The port on which the database is listening for connections
- The default username
- The randomly-generated password for the default username
- A boolean indicating if the connection should be made over SSL
While these connection details will work, you may wish to use different connection details, such as the private hostname, a custom username, or a different database.`, Writer,
aliasOpt("conn"), displayerType(&displayers.DatabaseConnection{}))
CmdBuilder(cmd, RunDatabaseBackupsList, "backups <database-id>", "List database cluster backups", `This command retrieves a list of backups created for the specified database cluster.
The list contains the size in GB, and the date and time the backup was taken.`, Writer,
aliasOpt("bu"), displayerType(&displayers.DatabaseBackups{}))
cmdDatabaseResize := CmdBuilder(cmd, RunDatabaseResize, "resize <database-id>", "Resize a database cluster", `This command resizes the specified database cluster.
You must specify the desired number of nodes and size of the nodes. For example:
doctl databases resize ca9f591d-9999-5555-a0ef-1c02d1d1e352 --num-nodes 2 --size db-s-16vcpu-64gb
Database nodes cannot be resized to smaller sizes due to the risk of data loss.`, Writer,
aliasOpt("rs"))
AddIntFlag(cmdDatabaseResize, doctl.ArgDatabaseNumNodes, "", 0, nodeNumberDetails, requiredOpt())
AddStringFlag(cmdDatabaseResize, doctl.ArgSizeSlug, "", "", nodeSizeDetails, requiredOpt())
cmdDatabaseMigrate := CmdBuilder(cmd, RunDatabaseMigrate, "migrate <database-id>", "Migrate a database cluster to a new region", `This command migrates the specified database cluster to a new region`, Writer,
aliasOpt("m"))
AddStringFlag(cmdDatabaseMigrate, doctl.ArgRegionSlug, "", "", "The region to which the database cluster should be migrated, e.g. `sfo2` or `nyc3`.", requiredOpt())
AddStringFlag(cmdDatabaseMigrate, doctl.ArgPrivateNetworkUUID, "", "", "The UUID of a VPC to create the database cluster in; the default VPC for the region will be used if excluded")
cmdDatabaseFork := CmdBuilder(cmd, RunDatabaseFork, "fork <name>", "Create a new database cluster by forking an existing database cluster.", `This command forks a database cluster from an existing cluster. example:
doctl databases fork new_db_name --restore-from-cluster-id=original-cluster-id`, Writer, aliasOpt("f"))
AddStringFlag(cmdDatabaseFork, doctl.ArgDatabaseRestoreFromClusterID, "", "", "The ID of an existing database cluster from which the new database will be forked from", requiredOpt())
AddStringFlag(cmdDatabaseFork, doctl.ArgDatabaseRestoreFromTimestamp, "", "", "The timestamp of an existing database cluster backup in UTC combined date and time format (2006-01-02 15:04:05 +0000 UTC). The most recent backup will be used if excluded.")
AddBoolFlag(cmdDatabaseFork, doctl.ArgCommandWait, "", false, "Boolean that specifies whether to wait for a database to complete before returning control to the terminal.")
cmd.AddCommand(databaseReplica())
cmd.AddCommand(databaseMaintenanceWindow())
cmd.AddCommand(databaseUser())
cmd.AddCommand(databaseDB())
cmd.AddCommand(databasePool())
cmd.AddCommand(sqlMode())
cmd.AddCommand(databaseFirewalls())
cmd.AddCommand(databaseOptions())
return cmd
}
// Clusters
// RunDatabaseList returns a list of database clusters.
func RunDatabaseList(c *CmdConfig) error {
dbs, err := c.Databases().List()
if err != nil {
return err
}
return displayDatabases(c, true, dbs...)
}
// RunDatabaseGet returns an individual database cluster
func RunDatabaseGet(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
db, err := c.Databases().Get(id)
if err != nil {
return err
}
return displayDatabases(c, false, *db)
}
// RunDatabaseCreate creates a database cluster
func RunDatabaseCreate(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
r, err := buildDatabaseCreateRequestFromArgs(c)
if err != nil {
return err
}
dbs := c.Databases()
db, err := dbs.Create(r)
if err != nil {
return err
}
wait, err := c.Doit.GetBool(c.NS, doctl.ArgCommandWait)
if err != nil {
return err
}
if wait {
connection := db.Connection
dbs := c.Databases()
notice("Database creation is in progress, waiting for database to be online")
err := waitForDatabaseReady(dbs, db.ID)
if err != nil {
return fmt.Errorf(
"database couldn't enter the `online` state: %v",
err,
)
}
db, err = dbs.Get(db.ID)
if err != nil {
return fmt.Errorf(
"failed to retrieve the new database: %v",
err,
)
}
db.Connection = connection
}
notice("Database created")
return displayDatabases(c, false, *db)
}
func buildDatabaseCreateRequestFromArgs(c *CmdConfig) (*godo.DatabaseCreateRequest, error) {
r := &godo.DatabaseCreateRequest{Name: c.Args[0]}
region, err := c.Doit.GetString(c.NS, doctl.ArgRegionSlug)
if err != nil {
return nil, err
}
r.Region = region
numNodes, err := c.Doit.GetInt(c.NS, doctl.ArgDatabaseNumNodes)
if err != nil {
return nil, err
}
r.NumNodes = numNodes
size, err := c.Doit.GetString(c.NS, doctl.ArgSizeSlug)
if err != nil {
return nil, err
}
r.SizeSlug = size
engine, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseEngine)
if err != nil {
return nil, err
}
r.EngineSlug = engine
version, err := c.Doit.GetString(c.NS, doctl.ArgVersion)
if err != nil {
return nil, err
}
r.Version = version
privateNetworkUUID, err := c.Doit.GetString(c.NS, doctl.ArgPrivateNetworkUUID)
if err != nil {
return nil, err
}
r.PrivateNetworkUUID = privateNetworkUUID
restoreFromCluster, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseRestoreFromClusterName)
if err != nil {
return nil, err
}
if restoreFromCluster != "" {
backUpRestore := &godo.DatabaseBackupRestore{}
backUpRestore.DatabaseName = restoreFromCluster
// only set the restore-from-timestamp if restore-from-cluster is set.
restoreFromTimestamp, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseRestoreFromTimestamp)
if err != nil {
return nil, err
}
if restoreFromTimestamp != "" {
dateFormatted, err := convertUTCtoISO8601(restoreFromTimestamp)
if err != nil {
return nil, err
}
backUpRestore.BackupCreatedAt = dateFormatted
}
r.BackupRestore = backUpRestore
}
r.PrivateNetworkUUID = privateNetworkUUID
return r, nil
}
// RunDatabaseFork creates a database cluster by forking an existing cluster.
func RunDatabaseFork(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
r, err := buildDatabaseForkRequest(c)
if err != nil {
return err
}
dbs := c.Databases()
db, err := dbs.Create(r)
if err != nil {
return err
}
wait, err := c.Doit.GetBool(c.NS, doctl.ArgCommandWait)
if err != nil {
return err
}
if wait {
connection := db.Connection
dbs := c.Databases()
notice("Database forking is in progress, waiting for database to be online")
err := waitForDatabaseReady(dbs, db.ID)
if err != nil {
return fmt.Errorf(
"database couldn't enter the `online` state: %v",
err,
)
}
db, _ = dbs.Get(db.ID)
db.Connection = connection
}
notice("Database created")
return displayDatabases(c, false, *db)
}
func buildDatabaseForkRequest(c *CmdConfig) (*godo.DatabaseCreateRequest, error) {
r := &godo.DatabaseCreateRequest{Name: c.Args[0]}
existingDatabaseID, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseRestoreFromClusterID)
if err != nil {
return nil, err
}
existingDatabase, err := c.Databases().Get(existingDatabaseID)
if err != nil {
return nil, err
}
backUpRestore := &godo.DatabaseBackupRestore{}
backUpRestore.DatabaseName = existingDatabase.Name
restoreFromTimestamp, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseRestoreFromTimestamp)
if err != nil {
return nil, err
}
if restoreFromTimestamp != "" {
dateFormatted, err := convertUTCtoISO8601(restoreFromTimestamp)
if err != nil {
return nil, err
}
backUpRestore.BackupCreatedAt = dateFormatted
}
r.BackupRestore = backUpRestore
r.EngineSlug = existingDatabase.EngineSlug
r.NumNodes = existingDatabase.NumNodes
r.SizeSlug = existingDatabase.SizeSlug
r.Region = existingDatabase.RegionSlug
r.Version = existingDatabase.VersionSlug
r.PrivateNetworkUUID = existingDatabase.PrivateNetworkUUID
r.Tags = existingDatabase.Tags
r.ProjectID = existingDatabase.ProjectID
return r, nil
}
func convertUTCtoISO8601(restoreFromTimestamp string) (string, error) {
// accepts UTC time format from user (to match db list output) and converts it to ISO8601 for api parity.
date, error := time.Parse("2006-01-02 15:04:05 +0000 UTC", restoreFromTimestamp)
if error != nil {
return "", fmt.Errorf("Invalid format for --restore-from-timestamp. Must be in UTC format: 2006-01-02 15:04:05 +0000 UTC")
}
dateFormatted := date.Format(time.RFC3339)
return dateFormatted, nil
}
// RunDatabaseDelete deletes a database cluster
func RunDatabaseDelete(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
force, err := c.Doit.GetBool(c.NS, doctl.ArgForce)
if err != nil {
return err
}
if force || AskForConfirmDelete("database cluster", 1) == nil {
id := c.Args[0]
return c.Databases().Delete(id)
}
return errOperationAborted
}
func displayDatabases(c *CmdConfig, short bool, dbs ...do.Database) error {
item := &displayers.Databases{
Databases: do.Databases(dbs),
Short: short,
}
return c.Display(item)
}
// RunDatabaseConnectionGet gets database connection info
func RunDatabaseConnectionGet(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
connInfo, err := c.Databases().GetConnection(id)
if err != nil {
return err
}
return displayDatabaseConnection(c, *connInfo)
}
func displayDatabaseConnection(c *CmdConfig, conn do.DatabaseConnection) error {
item := &displayers.DatabaseConnection{DatabaseConnection: conn}
return c.Display(item)
}
// RunDatabaseBackupsList lists all the backups for a database cluster
func RunDatabaseBackupsList(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
backups, err := c.Databases().ListBackups(id)
if err != nil {
return err
}
return displayDatabaseBackups(c, backups)
}
func displayDatabaseBackups(c *CmdConfig, bu do.DatabaseBackups) error {
item := &displayers.DatabaseBackups{DatabaseBackups: bu}
return c.Display(item)
}
// RunDatabaseResize resizes a database cluster
func RunDatabaseResize(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
r, err := buildDatabaseResizeRequestFromArgs(c)
if err != nil {
return err
}
return c.Databases().Resize(id, r)
}
func buildDatabaseResizeRequestFromArgs(c *CmdConfig) (*godo.DatabaseResizeRequest, error) {
r := &godo.DatabaseResizeRequest{}
numNodes, err := c.Doit.GetInt(c.NS, doctl.ArgDatabaseNumNodes)
if err != nil {
return nil, err
}
r.NumNodes = numNodes
size, err := c.Doit.GetString(c.NS, doctl.ArgSizeSlug)
if err != nil {
return nil, err
}
r.SizeSlug = size
return r, nil
}
// RunDatabaseMigrate migrates a database cluster to a new region
func RunDatabaseMigrate(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
r, err := buildDatabaseMigrateRequestFromArgs(c)
if err != nil {
return err
}
return c.Databases().Migrate(id, r)
}
func buildDatabaseMigrateRequestFromArgs(c *CmdConfig) (*godo.DatabaseMigrateRequest, error) {
r := &godo.DatabaseMigrateRequest{}
region, err := c.Doit.GetString(c.NS, doctl.ArgRegionSlug)
if err != nil {
return nil, err
}
r.Region = region
privateNetworkUUID, err := c.Doit.GetString(c.NS, doctl.ArgPrivateNetworkUUID)
if err != nil {
return nil, err
}
r.PrivateNetworkUUID = privateNetworkUUID
return r, nil
}
func databaseMaintenanceWindow() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "maintenance-window",
Aliases: []string{"maintenance", "mw", "main"},
Short: "Display commands for scheduling automatic maintenance on your database cluster",
Long: `The ` + "`" + `doctl databases maintenance-window` + "`" + ` commands allow you to schedule, and check the schedule of, maintenance windows for your databases.
Maintenance windows are hour-long blocks of time during which DigitalOcean performs automatic maintenance on databases every week. During this time, health checks, security updates, version upgrades, and more are performed.`,
},
}
CmdBuilder(cmd, RunDatabaseMaintenanceGet, "get <database-id>",
"Retrieve details about a database cluster's maintenance windows", `This command retrieves the following information on currently-scheduled maintenance windows for the specified database cluster:
- The day of the week the maintenance window occurs
- The hour in UTC when maintenance updates will be applied, in 24 hour format (e.g. "16:00")
- A boolean representing whether maintence updates are currently pending
To see a list of your databases and their IDs, run `+"`"+`doctl databases list`+"`"+`.`, Writer, aliasOpt("g"),
displayerType(&displayers.DatabaseMaintenanceWindow{}))
cmdDatabaseCreate := CmdBuilder(cmd, RunDatabaseMaintenanceUpdate,
"update <database-id>", "Update the maintenance window for a database cluster", `This command allows you to update the maintenance window for the specified database cluster.
Maintenance windows are hour-long blocks of time during which DigitalOcean performs automatic maintenance on databases every week. During this time, health checks, security updates, version upgrades, and more are performed.
To change the maintenance window for your database cluster, specify a day of the week and an hour of that day during which you would prefer such maintenance would occur.
doctl databases maintenance-window ca9f591d-f38h-5555-a0ef-1c02d1d1e35 update --day tuesday --hour 16:00
To see a list of your databases and their IDs, run `+"`"+`doctl databases list`+"`"+`.`, Writer, aliasOpt("u"))
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseMaintenanceDay, "", "",
"The day of the week the maintenance window occurs (e.g. 'tuesday')", requiredOpt())
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseMaintenanceHour, "", "",
"The hour in UTC when maintenance updates will be applied, in 24 hour format (e.g. '16:00')", requiredOpt())
return cmd
}
// Database Maintenance Window
// RunDatabaseMaintenanceGet retrieves the maintenance window info for a database cluster
func RunDatabaseMaintenanceGet(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
window, err := c.Databases().GetMaintenance(id)
if err != nil {
return err
}
return displayDatabaseMaintenanceWindow(c, *window)
}
func displayDatabaseMaintenanceWindow(c *CmdConfig, mw do.DatabaseMaintenanceWindow) error {
item := &displayers.DatabaseMaintenanceWindow{DatabaseMaintenanceWindow: mw}
return c.Display(item)
}
// RunDatabaseMaintenanceUpdate updates the maintenance window info for a database cluster
func RunDatabaseMaintenanceUpdate(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
r, err := buildDatabaseUpdateMaintenanceRequestFromArgs(c)
if err != nil {
return err
}
return c.Databases().UpdateMaintenance(id, r)
}
func buildDatabaseUpdateMaintenanceRequestFromArgs(c *CmdConfig) (*godo.DatabaseUpdateMaintenanceRequest, error) {
r := &godo.DatabaseUpdateMaintenanceRequest{}
day, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseMaintenanceDay)
if err != nil {
return nil, err
}
r.Day = strings.ToLower(day)
hour, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseMaintenanceHour)
if err != nil {
return nil, err
}
r.Hour = hour
return r, nil
}
func databaseUser() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "user",
Aliases: []string{"u"},
Short: "Display commands for managing database users",
Long: `The commands under ` + "`" + `doctl databases user` + "`" + ` allow you to view details for, and create, database users.
Database user accounts are scoped to one database cluster, to which they have full admin access, and are given an automatically-generated password.`,
},
}
userDetailsDesc := `
- The username for the user
- The password for the user
- The user's role. The value will be either "primary" or "normal".
Primary user accounts are created by DigitalOcean at database cluster creation time and can't be deleted. Normal user accounts are created by you. Both have administrative privileges on the database cluster.
To retrieve a list of your databases and their IDs, call ` + "`" + `doctl databases list` + "`" + `.`
CmdBuilder(cmd, RunDatabaseUserList, "list <database-id>", "Retrieve list of database users",
`This command retrieves a list of users for the specified database with the following details:`+userDetailsDesc, Writer, aliasOpt("ls"), displayerType(&displayers.DatabaseUsers{}))
CmdBuilder(cmd, RunDatabaseUserGet, "get <database-id> <user-name>",
"Retrieve details about a database user", `This command retrieves the following details about the specified user:`+userDetailsDesc+`
To retrieve a list of database users for a database, call `+"`"+`doctl databases user list <database-id>`+"`"+`.`, Writer, aliasOpt("g"),
displayerType(&displayers.DatabaseUsers{}))
cmdDatabaseUserCreate := CmdBuilder(cmd, RunDatabaseUserCreate, "create <database-id> <user-name>",
"Create a database user", `This command creates a user with the username you specify, who will be granted access to the database cluster you specify.
The user will be created with the role set to `+"`"+`normal`+"`"+`, and given an automatically-generated password.
To retrieve a list of your databases and their IDs, call `+"`"+`doctl databases list`+"`"+`.`, Writer, aliasOpt("c"))
AddStringFlag(cmdDatabaseUserCreate, doctl.ArgDatabaseUserMySQLAuthPlugin, "", "",
"set auth mode for MySQL users")
CmdBuilder(cmd, RunDatabaseUserResetAuth, "reset <database-id> <user-name> <new-auth-mode>",
"Resets a user's auth", "This command resets the auth password or the MySQL auth plugin for a given user. It will return the new user credentials. When resetting MySQL auth, valid values for `<new-auth-mode>` are `caching_sha2_password` and `mysql_native_password`.", Writer, aliasOpt("rs"))
cmdDatabaseUserDelete := CmdBuilder(cmd, RunDatabaseUserDelete,
"delete <database-id> <user-id>", "Delete a database user", `This command deletes the user with the username you specify, whose account was given access to the database cluster you specify.
To retrieve a list of your databases and their IDs, call `+"`"+`doctl databases list`+"`"+`.`, Writer, aliasOpt("rm"))
AddBoolFlag(cmdDatabaseUserDelete, doctl.ArgForce, doctl.ArgShortForce, false, "Delete the user without a confirmation prompt")
return cmd
}
// Database Users
// RunDatabaseUserList retrieves a list of users for specific database cluster
func RunDatabaseUserList(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
users, err := c.Databases().ListUsers(id)
if err != nil {
return err
}
return displayDatabaseUsers(c, users...)
}
// RunDatabaseUserGet retrieves a database user for a specific database cluster
func RunDatabaseUserGet(c *CmdConfig) error {
if len(c.Args) < 2 {
return doctl.NewMissingArgsErr(c.NS)
}
databaseID := c.Args[0]
userID := c.Args[1]
user, err := c.Databases().GetUser(databaseID, userID)
if err != nil {
return err
}
return displayDatabaseUsers(c, *user)
}
// RunDatabaseUserCreate creates a database user for a database cluster
func RunDatabaseUserCreate(c *CmdConfig) error {
if len(c.Args) < 2 {
return doctl.NewMissingArgsErr(c.NS)
}
var (
databaseID = c.Args[0]
userName = c.Args[1]
)
req := &godo.DatabaseCreateUserRequest{Name: userName}
authMode, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseUserMySQLAuthPlugin)
if err != nil {
return err
}
if authMode != "" {
req.MySQLSettings = &godo.DatabaseMySQLUserSettings{
AuthPlugin: authMode,
}
}
user, err := c.Databases().CreateUser(databaseID, req)
if err != nil {
return err
}
return displayDatabaseUsers(c, *user)
}
func RunDatabaseUserResetAuth(c *CmdConfig) error {
if len(c.Args) < 2 {
return doctl.NewMissingArgsErr(c.NS)
}
var (
databaseID = c.Args[0]
userName = c.Args[1]
)
database, err := c.Databases().Get(databaseID)
if err != nil {
return err
}
var req *godo.DatabaseResetUserAuthRequest
if strings.ToLower(database.EngineSlug) == "mysql" {
if len(c.Args) < 3 {
return doctl.NewMissingArgsErr(c.NS)
}
authMode := c.Args[2]
req = &godo.DatabaseResetUserAuthRequest{
MySQLSettings: &godo.DatabaseMySQLUserSettings{
AuthPlugin: authMode,
},
}
} else {
req = &godo.DatabaseResetUserAuthRequest{}
}
user, err := c.Databases().ResetUserAuth(databaseID, userName, req)
if err != nil {
return err
}
return displayDatabaseUsers(c, *user)
}
// RunDatabaseUserDelete deletes a database user
func RunDatabaseUserDelete(c *CmdConfig) error {
if len(c.Args) < 2 {
return doctl.NewMissingArgsErr(c.NS)
}
force, err := c.Doit.GetBool(c.NS, doctl.ArgForce)
if err != nil {
return err
}
if force || AskForConfirmDelete("database user", 1) == nil {
databaseID := c.Args[0]
userID := c.Args[1]
return c.Databases().DeleteUser(databaseID, userID)
}
return errOperationAborted
}
func displayDatabaseUsers(c *CmdConfig, users ...do.DatabaseUser) error {
item := &displayers.DatabaseUsers{DatabaseUsers: users}
return c.Display(item)
}
func databaseOptions() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "options",
Aliases: []string{"o"},
Short: `Display available database options (regions, version, layouts, etc.) for all available database engines`,
Long: `The subcommands under ` + "`" + `doctl databases options` + "`" + ` enable the navigation of available options under each database engine`,
},
}
databaseOptionEngines := `
This command lists the available database engines:
- The key of the database engine. Possible values are: "pg" for PostgreSQL, "mysql"" for MySQL, "redis"" for Redis, and "mongodb" for MongoDB
`
databaseOptionRegions := `
- The region of the database engine.
`
databaseOptionVersions := `
- The version of the database engine.
`
databaseOptionSlugs := `
- The slug of the database engine. These are prefixed with "db" for basic nodes, "gd" for general purpose nodes, "sol" for storage optimized nodes, and "m" for memory optimized nodes
`
CmdBuilder(cmd, RunDatabaseEngineOptions, "engines", "Retrieves a list of the available database engines", databaseOptionEngines,
Writer, aliasOpt("eng"))
cmdRegionOptions := CmdBuilder(cmd, RunDatabaseRegionOptions, "regions", "Retrieves a list of the available regions for a given database engine", databaseOptionEngines+databaseOptionRegions,
Writer, aliasOpt("r"))
AddStringFlag(cmdRegionOptions, doctl.ArgDatabaseEngine, "",
"", "The database engine")
cmdVersionOptions := CmdBuilder(cmd, RunDatabaseVersionOptions, "versions", "Retrieves a list of the available versions for a given database engine", databaseOptionEngines+databaseOptionVersions,
Writer, aliasOpt("v"))
AddStringFlag(cmdVersionOptions, doctl.ArgDatabaseEngine, "",
"", "The database engine")
cmdSlugOptions := CmdBuilder(cmd, RunDatabaseSlugOptions, "slugs", "Retrieves a list of the available slugs for a given database engine", databaseOptionEngines+databaseOptionSlugs,
Writer, aliasOpt("s"))
AddStringFlag(cmdSlugOptions, doctl.ArgDatabaseEngine, "",
"", "The database engine", requiredOpt())
return cmd
}
// RunDatabaseEngineOptions retrieves a list of the available database engines
func RunDatabaseEngineOptions(c *CmdConfig) error {
options, err := c.Databases().ListOptions()
if err != nil {
return err
}
return displayDatabaseEngineOptions(c, options)
}
func displayDatabaseEngineOptions(c *CmdConfig, options *do.DatabaseOptions) error {
item := &displayers.DatabaseOptions{DatabaseOptions: *options}
return c.Display(item)
}
func displayDatabaseRegionOptions(c *CmdConfig, regions map[string][]string) error {
item := &displayers.DatabaseRegionOptions{RegionMap: regions}
return c.Display(item)
}
func displayDatabaseVersionOptions(c *CmdConfig, versions map[string][]string) error {
item := &displayers.DatabaseVersionOptions{VersionMap: versions}
return c.Display(item)
}
func displayDatabaseLayoutOptions(c *CmdConfig, layouts []godo.DatabaseLayout) error {
item := &displayers.DatabaseLayoutOptions{Layouts: layouts}
return c.Display(item)
}
// RunDatabaseRegionOptions retrieves a list of the available regions for a given database engine
func RunDatabaseRegionOptions(c *CmdConfig) error {
engine, _ := c.Doit.GetString(c.NS, doctl.ArgDatabaseEngine)
options, err := c.Databases().ListOptions()
if err != nil {
return err
}
regions := make(map[string][]string, 0)
switch engine {
case "mongodb":
regions["mongodb"] = options.MongoDBOptions.Regions
case "mysql":
regions["mysql"] = options.MySQLOptions.Regions
case "pg":
regions["pg"] = options.PostgresSQLOptions.Regions
case "redis":
regions["redis"] = options.RedisOptions.Regions
case "":
regions["mongodb"] = options.MongoDBOptions.Regions
regions["mysql"] = options.MySQLOptions.Regions
regions["pg"] = options.PostgresSQLOptions.Regions
regions["redis"] = options.RedisOptions.Regions
}
return displayDatabaseRegionOptions(c, regions)
}
// RunDatabaseVersionOptions retrieves a list of the available versions for a given database engine
func RunDatabaseVersionOptions(c *CmdConfig) error {
engine, _ := c.Doit.GetString(c.NS, doctl.ArgDatabaseEngine)
options, err := c.Databases().ListOptions()
if err != nil {
return err
}
versions := make(map[string][]string, 0)
switch engine {
case "mongodb":
versions["mongodb"] = options.MongoDBOptions.Versions
case "mysql":
versions["mysql"] = options.MySQLOptions.Versions
case "pg":
versions["pg"] = options.PostgresSQLOptions.Versions
case "redis":
versions["redis"] = options.RedisOptions.Versions
case "":
versions["mongodb"] = options.MongoDBOptions.Versions
versions["mysql"] = options.MySQLOptions.Versions
versions["pg"] = options.PostgresSQLOptions.Versions
versions["redis"] = options.RedisOptions.Versions
}
return displayDatabaseVersionOptions(c, versions)
}
// RunDatabaseSlugOptions retrieves a list of the available slugs for a given database engine
func RunDatabaseSlugOptions(c *CmdConfig) error {
engine, err := c.Doit.GetString(c.NS, doctl.ArgDatabaseEngine)
if err != nil {
return doctl.NewMissingArgsErr(c.NS)
}
options, err := c.Databases().ListOptions()
if err != nil {
return err
}
layouts := make([]godo.DatabaseLayout, 0)
switch engine {
case "mongodb":
layouts = options.MongoDBOptions.Layouts
case "mysql":
layouts = options.MySQLOptions.Layouts
case "pg":
layouts = options.PostgresSQLOptions.Layouts
case "redis":
layouts = options.RedisOptions.Layouts
}
return displayDatabaseLayoutOptions(c, layouts)
}
func databasePool() *Command {
cmd := &Command{
Command: &cobra.Command{
Use: "pool",
Aliases: []string{"p"},
Short: "Display commands for managing connection pools",
Long: `The subcommands under ` + "`" + `doctl databases pool` + "`" + ` are for managing connection pools for your database cluster.
A connection pool may be useful if your database:
- Typically handles a large number of idle connections,
- Has wide variability in the possible number of connections at any given time,
- Drops connections due to max connection limits, or
- Experiences performance issues due to high CPU usage.
Connection pools can be created and deleted with these commands, or you can simply retrieve information about them.`,
},
}
connectionPoolDetails := `
- The database user that the connection pool uses. When excluded, all connections to the database use the inbound user.
- The name of the connection pool
- The size of the connection pool, i.e. the number of connections that will be allocated
- The database within the cluster for which the connection pool is used
- The pool mode for the connection pool, which can be 'session', 'transaction', or 'statement'
- A connection string for the connection pool`
getPoolDetails := `
You can get a list of existing connection pools by calling:
doctl databases pool list
You can get a list of existing database clusters and their IDs by calling:
doctl databases list`
CmdBuilder(cmd, RunDatabasePoolList, "list <database-id>", "List connection pools for a database cluster", `This command lists the existing connection pools for the specified database. The following information will be returned:`+connectionPoolDetails,
Writer, aliasOpt("ls"), displayerType(&displayers.DatabasePools{}))
CmdBuilder(cmd, RunDatabasePoolGet, "get <database-id> <pool-name>",
"Retrieve information about a database connection pool", `This command retrieves the following information about the specified connection pool for the specified database cluster:`+connectionPoolDetails+getPoolDetails, Writer, aliasOpt("g"),
displayerType(&displayers.DatabasePools{}))
cmdDatabasePoolCreate := CmdBuilder(cmd, RunDatabasePoolCreate,
"create <database-id> <pool-name>", "Create a connection pool for a database", `This command creates a connection pool for the specified database cluster and gives it the specified name.
You must also use flags to specify the target database, pool size, and database user's username that will be used for the pool. An example call would be: