-
Notifications
You must be signed in to change notification settings - Fork 400
/
Copy pathdatabases.go
2800 lines (2308 loc) · 108 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"
"strconv"
"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, MongoDB, Kafka and Opensearch database services.",
GroupID: manageResourcesGroup,
},
}
clusterDetails := `
- The database ID, in UUID format
- The name you gave the database cluster
- The database engine. Possible values: ` + "`redis`, `pg`, `mysql` , `mongodb`, `kafka`, `opensearch`" + `
- The engine version, such as ` + "`14`" + ` for PostgreSQL version 14
- The number of nodes in the database cluster
- The region the database cluster resides in, such as ` + "`sfo2`, " + "`nyc1`" + `
- The current status of the database cluster, such as ` + "`online`" + `
- The size of the machine running the database instance, such as ` + "`db-s-1vcpu-1gb`" + `)`
cmdDatabaseList := CmdBuilder(cmd, RunDatabaseList, "list", "List your database clusters", `Retrieves a list of database clusters and their following details:`+clusterDetails, Writer, aliasOpt("ls"), displayerType(&displayers.Databases{}))
cmdDatabaseList.Example = `The following example lists all database associated with your account and uses the ` + "`" + `--format` + "`" + ` flag to return only the ID, engine, and engine version of each database: doctl databases list --format ID,Engine,Version`
cmdDatabaseGet := CmdBuilder(cmd, RunDatabaseGet, "get <database-cluster-id>", "Get details for a database cluster", `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{}))
cmdDatabaseGet.Example = `The following example retrieves the details for a database cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + ` and uses the ` + "`" + `--format` + "`" + ` flag to return only the database's ID, engine, and engine version: doctl databases get f81d4fae-7dec-11d0-a765-00a0c91e6bf6`
cmdDatabaseGetCA := CmdBuilder(cmd, RunDatabaseGetCA, "get-ca <database-cluster-id>", "Provides the CA certificate for a DigitalOcean database", `Retrieves a database certificate`, Writer, aliasOpt("gc"), displayerType(&displayers.DatabaseCA{}))
cmdDatabaseGetCA.Example = `Retrieves the database certificate for the cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + `: doctl databases get-ca f81d4fae-7dec-11d0-a765-00a0c91e6bf6
With the ` + "`" + `-o json flag` + "`" + `, the certificate to connect to the database is base64 encoded. To decode it: ` + "`" + `doctl databases get-ca <database-cluster-id> -o json | jq -r .certificate | base64 --decode` + "`"
nodeSizeDetails := "The size of the nodes in the database cluster, for example `db-s-1vcpu-1gb` indicates 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 1-3. In addition to the primary node, up to two standby nodes may be added for high availability."
storageSizeMiBDetails := "The amount of disk space allocated to the cluster. Applicable for PostgreSQL and MySQL clusters. Each plan size has a default value but can be increased in increments up to a maximum amount. For ranges, visit: https://www.digitalocean.com/pricing/managed-databases"
cmdDatabaseCreate := CmdBuilder(cmd, RunDatabaseCreate, "create <name>", "Create a database cluster", `Creates a database cluster with the specified name.
You can customize the configuration using the listed flags, all of which are optional. Without any flags set, the command creates a single-node, single-CPU PostgreSQL database cluster.`, Writer,
aliasOpt("c"))
AddIntFlag(cmdDatabaseCreate, doctl.ArgDatabaseNumNodes, "", defaultDatabaseNodeCount, nodeNumberDetails)
AddStringFlag(cmdDatabaseCreate, doctl.ArgRegionSlug, "", defaultDatabaseRegion, "The data center region where the database cluster resides, such as `nyc1` or `sfo2`.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgSizeSlug, "", defaultDatabaseNodeSize, nodeSizeDetails)
AddIntFlag(cmdDatabaseCreate, doctl.ArgDatabaseStorageSizeMib, "", 0, storageSizeMiBDetails)
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseEngine, "", defaultDatabaseEngine, "The database's engine. Possible values are: `pg`, `mysql`, `redis`, `mongodb`, `kafka` and `opensearch`.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgVersion, "", "", "The database engine's version, such as 14 for PostgreSQL version 14.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgPrivateNetworkUUID, "", "", "The UUID of a VPC to create the database cluster in. The command uses the region's default VPC if excluded.")
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseRestoreFromClusterName, "", "", "The name of an existing database cluster to restore from.")
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 is used if excluded.")
AddBoolFlag(cmdDatabaseCreate, doctl.ArgCommandWait, "", false, "A boolean value that specifies whether to wait for the database cluster to be provisioned before returning control to the terminal.")
AddStringSliceFlag(cmdDatabaseCreate, doctl.ArgTag, "", nil, "A comma-separated list of tags to apply to the database cluster.")
cmdDatabaseCreate.Example = `The following example creates a database cluster named ` + "`" + `example-database` + "`" + ` in the ` + "`" + `nyc1` + "`" + ` region with a single 1 GB node: doctl databases create example-database --region nyc1 --size db-s-1vcpu-1gb --num-nodes 1`
cmdDatabaseDelete := CmdBuilder(cmd, RunDatabaseDelete, "delete <database-cluster-id>", "Delete a database cluster", `Deletes the database cluster with the specified ID.
To retrieve a list of your database clusters and their IDs, use `+"`"+`doctl databases list`+"`"+`.`, Writer,
aliasOpt("rm"))
AddBoolFlag(cmdDatabaseDelete, doctl.ArgForce, doctl.ArgShortForce, false, "Delete the database cluster without a confirmation prompt")
cmdDatabaseDelete.Example = `The following example deletes the database cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + `: doctl databases delete f81d4fae-7dec-11d0-a765-00a0c91e6bf6`
cmdDatabaseGetConn := CmdBuilder(cmd, RunDatabaseConnectionGet, "connection <database-cluster-id>", "Retrieve connection details for a database cluster", `Retrieves the following connection details for a database cluster:
- A 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 value indicating if the connection should be made over SSL
While you can use these connection details, you can manually update the connection string's parameters to change how you connect to the database, such using a private hostname, custom username, or a different database.`, Writer,
aliasOpt("conn"), displayerType(&displayers.DatabaseConnection{}))
AddBoolFlag(cmdDatabaseGetConn, doctl.ArgDatabasePrivateConnectionBool, "", false, "Returns connection details that use the database's VPC network connection.")
cmdDatabaseGetConn.Example = `The following example retrieves the connection details for a database cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + `: doctl databases connection f81d4fae-7dec-11d0-a765-00a0c91e6bf6`
cmdDatabaseListBackups := CmdBuilder(cmd, RunDatabaseBackupsList, "backups <database-cluster-id>", "List database cluster backups", `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 created.`, Writer,
aliasOpt("bu"), displayerType(&displayers.DatabaseBackups{}))
cmdDatabaseListBackups.Example = `The following example retrieves a list of backups for a database cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + `: doctl databases backups f81d4fae-7dec-11d0-a765-00a0c91e6bf6`
cmdDatabaseResize := CmdBuilder(cmd, RunDatabaseResize, "resize <database-cluster-id>", "Resize a database cluster", `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.
For PostgreSQL and MySQL clusters, you can also provide a disk size in MiB to scale the storage up to 15 TB, depending on your plan. You cannot reduce the storage size of a cluster.`, Writer,
aliasOpt("rs"))
AddIntFlag(cmdDatabaseResize, doctl.ArgDatabaseNumNodes, "", 0, nodeNumberDetails, requiredOpt())
AddStringFlag(cmdDatabaseResize, doctl.ArgSizeSlug, "", "", nodeSizeDetails, requiredOpt())
AddIntFlag(cmdDatabaseResize, doctl.ArgDatabaseStorageSizeMib, "", 0, storageSizeMiBDetails)
AddBoolFlag(cmdDatabaseResize, doctl.ArgCommandWait, "", false,
"Boolean that specifies whether to wait for the resize to complete before returning control to the terminal")
cmdDatabaseResize.Example = `The following example resizes a PostgreSQL or MySQL database to have two nodes, 16 vCPUs, 64 GB of memory, and 2048 GiB of storage space: doctl databases resize ca9f591d-9999-5555-a0ef-1c02d1d1e352 --num-nodes 2 --size db-s-16vcpu-64gb --storage-size-mib 2048000 --wait true`
cmdDatabaseMigrate := CmdBuilder(cmd, RunDatabaseMigrate, "migrate <database-cluster-id>", "Migrate a database cluster to a new region", `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, such as `sfo2` or `nyc3`.", requiredOpt())
AddStringFlag(cmdDatabaseMigrate, doctl.ArgPrivateNetworkUUID, "", "", "The UUID of a VPC network to create the database cluster in. The command uses the region's default VPC network if not specified.")
AddBoolFlag(cmdDatabaseMigrate, doctl.ArgCommandWait, "", false, "A boolean value that specifies whether to wait for the database migration to complete before returning control to the terminal.")
cmdDatabaseFork := CmdBuilder(cmd, RunDatabaseFork, "fork <name>", "Create a new database cluster by forking an existing database cluster.", `Creates a new database cluster from an existing cluster. The forked database contains all of the data from the original database at the time the fork is created.`, 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 is used if excluded.")
AddBoolFlag(cmdDatabaseFork, doctl.ArgCommandWait, "", false, "A boolean that specifies whether to wait for a database to complete before returning control to the terminal")
cmdDatabaseFork.Example = `The following example forks a database cluster with the ID ` + "`" + `f81d4fae-7dec-11d0-a765-00a0c91e6bf6` + "`" + ` to create a new database cluster. The command also uses the ` + "`" + `--restore-from-timestamp` + "`" + ` flag to specifically fork the database from a cluster backup that was created on 2023 November 7: doctl databases fork new-db-cluster --restore-from-cluster-id f81d4fae-7dec-11d0-a765-00a0c91e6bf6 --restore-from-timestamp 2023-11-07 12:34:56 +0000 UTC`
cmd.AddCommand(databaseReplica())
cmd.AddCommand(databaseMaintenanceWindow())
cmd.AddCommand(databaseUser())
cmd.AddCommand(databaseDB())
cmd.AddCommand(databasePool())
cmd.AddCommand(sqlMode())
cmd.AddCommand(databaseFirewalls())
cmd.AddCommand(databaseOptions())
cmd.AddCommand(databaseConfiguration())
cmd.AddCommand(databaseTopic())
cmd.AddCommand(databaseEvents())
cmd.AddCommand(databaseIndex())
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)
}
// RunDatabaseGetCA returns a CA certificate for a database
func RunDatabaseGetCA(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
dbCA, err := c.Databases().GetCA(id)
if err != nil {
return err
}
return displayDatabaseCA(c, dbCA)
}
// 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
tags, err := c.Doit.GetStringSlice(c.NS, doctl.ArgTag)
if err != nil {
return nil, err
}
r.Tags = tags
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
storageSizeMibInt, err := c.Doit.GetInt(c.NS, doctl.ArgDatabaseStorageSizeMib)
if err != nil {
return nil, err
}
r.StorageSizeMib = uint64(storageSizeMibInt)
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]
private, err := c.Doit.GetBool(c.NS, doctl.ArgDatabasePrivateConnectionBool)
if err != nil {
return err
}
connInfo, err := c.Databases().GetConnection(id, private)
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]
dbs := c.Databases()
r, err := buildDatabaseResizeRequestFromArgs(c)
if err != nil {
return err
}
// Resize the database
err = dbs.Resize(id, r)
if err != nil {
return err
}
// Check if the --wait flag was passed
wait, err := c.Doit.GetBool(c.NS, doctl.ArgCommandWait)
if err != nil {
return err
}
if wait {
notice("Database resizing is in progress, waiting for database to be online")
err := waitForDatabaseReady(dbs, id)
if err != nil {
return fmt.Errorf(
"database couldn't enter the `online` state after resizing: %v",
err,
)
}
notice("Database resized successfully")
}
return nil
}
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
storageSizeMibInt, err := c.Doit.GetInt(c.NS, doctl.ArgDatabaseStorageSizeMib)
if err != nil {
return nil, err
}
r.StorageSizeMib = uint64(storageSizeMibInt)
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
}
dbs := c.Databases()
err = dbs.Migrate(id, r)
if err != nil {
return err
}
wait, err := c.Doit.GetBool(c.NS, doctl.ArgCommandWait)
if err != nil {
return err
}
if wait {
notice("Database migration is in progress, waiting for database to be online")
err := waitForDatabaseReady(dbs, id)
if err != nil {
return fmt.Errorf(
"database couldn't enter the `online` state after migration: %v",
err,
)
}
notice("Database migrated successfully")
}
return nil
}
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.
To install an update outside of a maintenance window, use the ` + "`" + `doctl databases maintenance-window install` + "`" + ` command.`,
},
}
cmdMaintenanceGet := CmdBuilder(cmd, RunDatabaseMaintenanceGet, "get <database-cluster-id>",
"Retrieve details about a database cluster's maintenance windows", `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, such as "16:00"
- A boolean representing whether maintenance updates are currently pending
To see a list of your databases and their IDs, run `+"`"+`doctl databases list`+"`"+`.`, Writer, aliasOpt("g"),
displayerType(&displayers.DatabaseMaintenanceWindow{}))
cmdMaintenanceGet.Example = `The following example retrieves the maintenance window for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + `: doctl databases maintenance-window ca9f591d-f38h-5555-a0ef-1c02d1d1e35`
cmdDatabaseCreate := CmdBuilder(cmd, RunDatabaseMaintenanceUpdate,
"update <database-cluster-id>", "Update the maintenance window for a database cluster", `Updates 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.
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, for example: 'tuesday')", requiredOpt())
AddStringFlag(cmdDatabaseCreate, doctl.ArgDatabaseMaintenanceHour, "", "",
"The hour when maintenance updates are applied, in UTC 24-hour format. Example: '16:00')", requiredOpt())
cmdDatabaseCreate.Example = `The following example updates the maintenance window for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + `: doctl databases maintenance-window update ca9f591d-f38h-5555-a0ef-1c02d1d1e35 --day tuesday --hour 16:00`
cmdDatabaseInstallUpdate := CmdBuilder(cmd, RunDatabaseInstallUpdate, "install <database-cluster-id>", "Start installation of updates immediately", "Starts the installation of updates for the specified database cluster immediately outside of a maintenance window.", Writer, aliasOpt("i"))
cmdDatabaseInstallUpdate.Example = `The following example starts installation of updates for your databases with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + `: doctl databases maintenance-window install ca9f591d-f38h-5555-a0ef-1c02d1d1e35`
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)
}
// RunDatabaseInstallUpdate starts installation of updates
func RunDatabaseInstallUpdate(c *CmdConfig) error {
if len(c.Args) == 0 {
return doctl.NewMissingArgsErr(c.NS)
}
id := c.Args[0]
return c.Databases().InstallUpdate(id)
}
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.`,
},
}
databaseKafkaACLsTxt := `A comma-separated list of kafka ACL rules, in ` + "`" + `topic:permission` + "`" + ` format.`
databaseOpenSearchACLsTxt := `A comma-separated list of OpenSearch ACL rules, in ` + "`" + `index:permission` + "`" + ` format.`
userDetailsDesc := `
- The username for the user
- The password for the user
- The user's role, either "primary" or "normal"
Primary user accounts are created by DigitalOcean at database cluster creation time and can't be deleted. You can create additional users with a "normal" role. Both have administrative privileges on the database cluster.
To retrieve a list of your databases and their IDs, call ` + "`" + `doctl databases list` + "`" + `.`
cmdDatabaseUserList := CmdBuilder(cmd, RunDatabaseUserList, "list <database-cluster-id>", "Retrieve list of database users",
`Retrieves a list of users for the specified database with the following details:`+userDetailsDesc, Writer, aliasOpt("ls"), displayerType(&displayers.DatabaseUsers{}))
cmdDatabaseUserList.Example = `The following example retrieves a list of users for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + ` and uses the ` + "`" + `--format flag` + "`" + ` to return only the name and role for each each user: doctl databases user list ca9f591d-f38h-5555-a0ef-1c02d1d1e35 --format Name,Role`
cmdDatabaseUserGet := CmdBuilder(cmd, RunDatabaseUserGet, "get <database-cluster-id> <user-name>",
"Retrieve details about a database user", `Retrieves the following details about the specified user:`+userDetailsDesc+`
To retrieve a list of database users for a database cluster, call `+"`"+`doctl databases user list <database-cluster-id>`+"`"+`.`, Writer, aliasOpt("g"),
displayerType(&displayers.DatabaseUsers{}))
cmdDatabaseUserGet.Example = `The following example retrieves the details for the user with the username ` + "`" + `example-user` + "`" + ` for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + ` and uses the ` + "`" + `--format` + "`" + ` flag to return only the user's name and role: doctl databases user get ca9f591d-f38h-5555-a0ef-1c02d1d1e35 example-user --format Name,Role`
cmdDatabaseUserCreate := CmdBuilder(cmd, RunDatabaseUserCreate, "create <database-cluster-id> <user-name>",
"Create a database user", `Creates a new user for a database. New users are given a role of `+"`"+`normal`+"`"+` and are 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, "", "",
"Sets authorization plugin for a MySQL user. Possible values: `caching_sha2_password` or `mysql_native_password`")
AddStringSliceFlag(cmdDatabaseUserCreate, doctl.ArgDatabaseUserKafkaACLs, "", []string{}, databaseKafkaACLsTxt)
AddStringSliceFlag(cmdDatabaseUserCreate, doctl.ArgDatabaseUserOpenSearchACLs, "", []string{}, databaseOpenSearchACLsTxt)
cmdDatabaseUserCreate.Example = `The following example creates a new user with the username ` + "`" + `example-user` + "`" + ` for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + `: doctl databases user create ca9f591d-f38h-5555-a0ef-1c02d1d1e35 example-user`
cmdDatabaseUserResetAuth := CmdBuilder(cmd, RunDatabaseUserResetAuth, "reset <database-cluster-id> <user-name> <new-auth-mode>",
"Resets a user's auth", "Resets the auth password or the MySQL authorization plugin for a given user and returns the user's new credentials. When resetting MySQL auth, valid values for `<new-auth-mode>` are `caching_sha2_password` and `mysql_native_password`.", Writer, aliasOpt("rs"))
cmdDatabaseUserResetAuth.Example = `The following example resets the auth plugin for the user with the username ` + "`" + `example-user` + "`" + ` for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + ` to ` + "`" + `mysql_native_password` + "`" + `: doctl databases user reset ca9f591d-f38h-5555-a0ef-1c02d1d1e35 example-user mysql_native_password`
cmdDatabaseUserDelete := CmdBuilder(cmd, RunDatabaseUserDelete,
"delete <database-cluster-id> <user-id>", "Delete a database user", `Deletes the specified database user.
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")
cmdDatabaseUserDelete.Example = `The following example deletes the user with the username ` + "`" + `example-user` + "`" + ` for a database cluster with the ID ` + "`" + `ca9f591d-f38h-5555-a0ef-1c02d1d1e35` + "`" + `: doctl databases user delete ca9f591d-f38h-5555-a0ef-1c02d1d1e35 example-user`
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,
}
}
kafkaAcls, err := buildDatabaseCreateKafkaUserACls(c)
if err != nil {
return err
}
if len(kafkaAcls) != 0 {
req.Settings = &godo.DatabaseUserSettings{
ACL: kafkaAcls,
}
}
openSearchACLs, err := buildDatabaseCreateOpenSearchUserACLs(c)
if err != nil {
return err
}
if len(openSearchACLs) != 0 {
req.Settings = &godo.DatabaseUserSettings{
OpenSearchACL: openSearchACLs,
}
}
user, err := c.Databases().CreateUser(databaseID, req)
if err != nil {
return err
}
return displayDatabaseUsers(c, *user)
}
func buildDatabaseCreateKafkaUserACls(c *CmdConfig) (kafkaACls []*godo.KafkaACL, err error) {
acls, err := c.Doit.GetStringSlice(c.NS, doctl.ArgDatabaseUserKafkaACLs)
if err != nil {
return nil, err
}
for _, acl := range acls {
pair := strings.SplitN(acl, ":", 2)
if len(pair) != 2 {
return nil, fmt.Errorf("unexpected input value [%v], must be a topic:permission pair", pair)
}
kafkaACl := new(godo.KafkaACL)
kafkaACl.Topic = pair[0]
kafkaACl.Permission = pair[1]
kafkaACls = append(kafkaACls, kafkaACl)
}
return kafkaACls, nil
}
func buildDatabaseCreateOpenSearchUserACLs(c *CmdConfig) (openSearchACLs []*godo.OpenSearchACL, err error) {
acls, err := c.Doit.GetStringSlice(c.NS, doctl.ArgDatabaseUserOpenSearchACLs)
if err != nil {
return nil, err
}
for _, acl := range acls {
pair := strings.SplitN(acl, ":", 2)
if len(pair) != 2 {
return nil, fmt.Errorf("unexpected input value [%v], must be a index:permission pair", pair)
}
openSearchACL := new(godo.OpenSearchACL)
openSearchACL.Index = pair[0]
openSearchACL.Permission = pair[1]
openSearchACLs = append(openSearchACLs, openSearchACL)
}
return openSearchACLs, nil
}
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 displayDatabaseCA(c *CmdConfig, dbCA *do.DatabaseCA) error {
item := &displayers.DatabaseCA{DatabaseCA: *dbCA}
return c.Display(item)
}