-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdo.php
More file actions
2862 lines (2336 loc) · 114 KB
/
do.php
File metadata and controls
2862 lines (2336 loc) · 114 KB
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
<?php
// DigitalOcean command-line shell for managing droplets.
// (C) 2019 CubicleSoft. All Rights Reserved.
if (!isset($_SERVER["argc"]) || !$_SERVER["argc"])
{
echo "This file is intended to be run from the command-line.";
exit();
}
// Temporary root.
$rootpath = str_replace("\\", "/", dirname(__FILE__));
require_once $rootpath . "/support/cli.php";
require_once $rootpath . "/support/sdk_digitalocean.php";
// Process the command-line options.
$options = array(
"shortmap" => array(
"c" => "config",
"d" => "debug",
"s" => "suppressoutput",
"?" => "help"
),
"rules" => array(
"config" => array("arg" => true),
"debug" => array("arg" => false),
"suppressoutput" => array("arg" => false),
"help" => array("arg" => false)
),
"allow_opts_after_param" => false
);
$args = CLI::ParseCommandLine($options);
if (isset($args["opts"]["help"]))
{
echo "DigitalOcean management command-line tool\n";
echo "Purpose: Expose the DigitalOcean API to the command-line. Also verifies correct SDK functionality.\n";
echo "\n";
echo "This tool is question/answer enabled. Just running it will provide a guided interface. It can also be run entirely from the command-line if you know all the answers.\n";
echo "\n";
echo "Syntax: " . $args["file"] . " [options] [apigroup api [apioptions]]\n";
echo "Options:\n";
echo "\t-c Specify a configuration file to use. If it doesn't exist, it will be created. Default is config.dat.\n";
echo "\t-d Enable raw API debug mode. Dumps the raw data sent and received on the wire.\n";
echo "\t-s Suppress most output. Useful for capturing JSON output.\n";
echo "\n";
echo "Examples:\n";
echo "\tphp " . $args["file"] . "\n";
echo "\tphp " . $args["file"] . " droplets create -name test\n";
echo "\tphp " . $args["file"] . " -c altconfig.dat -s account get-info\n";
exit();
}
function SaveConfig($configfile, $config)
{
file_put_contents($configfile, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
chmod($configfile, 0660);
}
$suppressoutput = (isset($args["opts"]["suppressoutput"]) && $args["opts"]["suppressoutput"]);
// Get the API group.
$configfile = (isset($args["opts"]["config"]) ? $args["opts"]["config"] : $rootpath . "/config.dat");
if (!file_exists($configfile))
{
$apigroups = array(
"setup" => "Configure the tool",
"metadata-droplet" => "Droplet metadata"
);
$default = "setup";
}
else
{
$apigroups = array(
"account" => "Account",
"actions" => "Actions",
"volumes" => "Volumes (Block storage)",
"volume-actions" => "Volume actions (Block storage)",
"cdn-endpoints" => "Content Delivery Network (CDN) endpoints",
"certificates" => "Certificates (SSL/TLS)",
"database-clusters" => "Database clusters",
"database-replicas" => "Database read-only replicas",
"database-users" => "Database users",
"databases" => "Databases in a database cluster",
"database-pools" => "Database connection pools",
"domains" => "Domains (DNS)",
"domain-records" => "Domain records (DNS)",
"droplets" => "Droplets",
"droplet-actions" => "Droplet actions",
"firewalls" => "Firewalls",
"images" => "Images",
"image-actions" => "Image actions",
"load-balancers" => "Load balancers",
"projects" => "Projects",
"project-resources" => "Project resources",
"snapshots" => "Snapshots",
"ssh-keys" => "SSH keys",
"regions" => "Regions",
"sizes" => "Sizes",
"floating-ips" => "Floating IPs",
"floating-ip-actions" => "Floating IP actions",
"tags" => "Tags",
"oauth" => "OAuth",
"metadata-droplet" => "Droplet metadata"
);
$default = false;
}
$apigroup = CLI::GetLimitedUserInputWithArgs($args, false, "API group", $default, "Available API groups:", $apigroups, true, $suppressoutput);
// Get the API.
switch ($apigroup)
{
case "account": $apis = array("get-info" => "Get account information"); break;
case "actions": $apis = array("list" => "List actions", "get-info" => "Get information about an action", "wait" => "Wait for an action to complete"); break;
case "volumes": $apis = array("list" => "List Block Storage volumes", "create" => "Create a Block Storage volume", "get-info" => "Get information about a Block Storage volume", "snapshots" => "List all Block Storage volume snapshots", "snapshot" => "Create a Block Storage volume snapshot", "delete" => "Delete a Block Storage volume"); break;
case "volume-actions": $apis = array("attach" => "Attach a Block Storage volume to a Droplet", "detach" => "Detach a Block Storage volume from a Droplet", "resize" => "Enlarge a Block Storage volume"); break;
case "cdn-endpoints": $apis = array("list" => "List CDN endpoints", "create" => "Create a CDN endpoint", "update" => "Update a CDN endpoint", "get-info" => "Get information about a CDN endpoint", "purge" => "Purge CDN endpoint cache", "delete" => "Delete a CDN endpoint"); break;
case "certificates": $apis = array("list" => "List registered SSL certificates", "create" => "Create/Upload a SSL certificate", "get-info" => "Get information about a SSL certificate", "delete" => "Delete a SSL certificate"); break;
case "database-clusters": $apis = array("list" => "List database clusters", "create" => "Create a database cluster", "resize" => "Resize a database cluster", "migrate" => "Migrate a database cluster to another region", "maintenance" => "Configure the automatic maintenance window for a database cluster", "backups" => "List available backups for a database cluster", "restore" => "Restore from a backup into a new database cluster", "get-info" => "Get information about a database cluster", "delete" => "Delete a database cluster and all associated databases, tables, and users"); break;
case "database-replicas": $apis = array("list" => "List read-only database replicas", "create" => "Create a read-only database replica", "get-info" => "Get information about a read-only database replica", "delete" => "Delete a read-only database replica"); break;
case "database-users": $apis = array("list" => "List database users", "create" => "Create a database user", "get-info" => "Get information about a database user", "delete" => "Delete a database user"); break;
case "databases": $apis = array("list" => "List databases", "create" => "Create a database", "get-info" => "Get information about a database", "delete" => "Delete a database"); break;
case "database-pools": $apis = array("list" => "List database connection pools", "create" => "Create a database connection pool", "get-info" => "Get information about a database connection pool", "delete" => "Delete a database connection pool"); break;
case "domains": $apis = array("list" => "List registered domains (DNS)", "create" => "Create a domain (TLD)", "get-info" => "Get information about a domain", "delete" => "Delete a domain and all domain records"); break;
case "domain-records": $apis = array("list" => "List DNS records for a domain", "create" => "Create a domain record (A, AAAA, etc.)", "update" => "Update a domain record", "get-info" => "Get information about a domain record", "delete" => "Delete a domain record"); break;
case "droplets": $apis = array("list" => "List Droplets", "create" => "Create a new Droplet", "get-info" => "Get information about a Droplet", "kernels" => "List all available kernels for a Droplet", "snapshots" => "List all Droplet snapshots", "backups" => "List all Droplet backups", "actions" => "List Droplet actions", "delete" => "Delete a single Droplet", "delete-by-tag" => "Delete all Droplets with a specific tag", "neighbors" => "List neighbors for a Droplet", "all-neighbors" => "List all neighbors for all Droplets"); break;
case "droplet-actions": $apis = array("enable-backups" => "Enable backups", "disable-backups" => "Disable backups", "reboot" => "Reboot (gentle)", "power-cycle" => "Power cycle (hard reset)", "shutdown" => "Shutdown (gentle)", "power-off" => "Power off (forced shutdown)", "power-on" => "Power on", "restore" => "Restore from a backup image", "password-reset" => "Password reset", "resize" => "Resize Droplet", "rebuild" => "Recreate/Rebuild Droplet with a specific image", "rename" => "Rename", "change-kernel" => "Change Droplet kernel", "enable-ipv6" => "Enable IPv6 support", "enable-private-networking" => "Enable Shared Private Networking", "snapshot" => "Create a snapshot image"); break;
case "firewalls": $apis = array("list" => "List firewalls", "create" => "Create a firewall", "update" => "Update a firewall", "add-tag" => "Adds a tag to a firewall", "remove-tag" => "Removes a tag from a firewall", "add-droplet" => "Adds a Droplet to a firewall", "remove-droplet" => "Removes a Droplet from a firewall", "get-info" => "Get information about a firewall", "delete" => "Delete a firewall"); break;
case "images": $apis = array("list" => "List images (snapshots, backups, etc.)", "create" => "Create a custom image", "actions" => "List image actions", "rename" => "Rename image", "delete" => "Delete image", "get-info" => "Get information about an image"); break;
case "image-actions": $apis = array("transfer" => "Transfer/Copy an image to another region", "convert" => "Convert a backup to a snapshot"); break;
case "load-balancers": $apis = array("list" => "List load balancers", "create" => "Create a load balancer", "update" => "Update a load balancer", "add-forwarding-rule" => "Adds a forwarding rule to a load balancer", "remove-forwarding-rule" => "Removes a forwarding rule from a load balancer", "add-droplet" => "Adds a Droplet to a load balancer", "remove-droplet" => "Removes a Droplet from a load balancer", "get-info" => "Get information about a load balancer", "delete" => "Delete a load balancer"); break;
case "projects": $apis = array("list" => "List projects", "create" => "Create a project", "update" => "Update a project", "get-info" => "Get information about a project"); break;
case "project-resources": $apis = array("list" => "List resources", "assign" => "Assign a resource to a project"); break;
case "snapshots": $apis = array("list" => "List snapshots", "get-info" => "Get information about a snapshot", "delete" => "Delete a snapshot"); break;
case "ssh-keys": $apis = array("list" => "List SSH public keys in DigitalOcean account", "create" => "Add a SSH public key to your account", "get-info" => "Get information about a SSH public key", "rename" => "Rename a SSH public key", "delete" => "Remove a SSH public key from your account"); break;
case "regions": $apis = array("list" => "List all regions"); break;
case "sizes": $apis = array("list" => "List all Droplet sizes"); break;
case "floating-ips": $apis = array("list" => "List your Floating IPs", "create" => "Create a new Floating IP", "get-info" => "Get information about a Floating IP", "actions" => "List Floating IP actions", "delete" => "Delete a Floating IP"); break;
case "floating-ip-actions": $apis = array("assign" => "Assign a Floating IP to a Droplet", "unassign" => "Unassign a Floating IP"); break;
case "tags": $apis = array("list" => "List tags and associated resources", "create" => "Create a tag", "get-info" => "Get information about a tag", "attach" => "Attach a tag to one or more resources", "detach" => "Detach one or more resources from a tag", "delete" => "Delete a tag"); break;
case "oauth": $apis = array("revoke" => "Self-revoke API access"); break;
case "metadata-droplet": $apis = array("get-info" => "Get information about the Droplet (see Metadata API and Cloud Config tutorials)"); break;
}
if ($apigroup !== "setup") $api = CLI::GetLimitedUserInputWithArgs($args, false, "API", false, "Available APIs:", $apis, true, $suppressoutput);
function DisplayResult($result, $wait = true, $defaultwait = 5, $initwait = array())
{
global $do;
if (is_array($result) && isset($result["success"]) && isset($result["actions"]) && $result["success"] && $wait)
{
foreach ($result["actions"] as $num => $action)
{
$result["actions"][$num]["result"] = $do->WaitForActionCompletion($action["id"], $defaultwait, $initwait, "ActionWaitHandler");
}
}
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
exit();
}
$do = new DigitalOcean();
if (isset($args["opts"]["debug"]) && $args["opts"]["debug"]) $do->SetDebug(true);
if ($apigroup === "metadata-droplet")
{
if (!$suppressoutput) echo "The metadata API is intended to be used from the droplet itself.\n";
if ($api === "get-info") DisplayResult($do->MetadataDropletGetInfo());
}
// Load the configuration file.
if (!file_exists($configfile))
{
echo "\n\n---------------------\n\nThe configuration file '" . $configfile . "' does not exist. Entering interactive configuration mode.\n\n";
$tokentypes = array(
"application" => "Standard DigitalOcation OAuth2 application login.",
"personal" => "A permanent access token you manually set up in your DigitalOcean account."
);
$mode = CLI::GetLimitedUserInputWithArgs($args, false, "Access token type", "application", "Available access token types:", $tokentypes);
$config = array();
if ($mode === "application")
{
echo "\n";
$result = $do->InteractiveLogin();
if (!$result["success"]) CLI::DisplayError("An error occurred while performing the interactive login.", $result);
$config["access_tokens"] = $do->GetAccessTokens();
}
else
{
$config["access_tokens"] = $do->GetAccessTokens();
$config["access_tokens"]["bearertoken"] = CLI::GetUserInputWithArgs($args, false, "Personal Access Token (from API -> Tokens)", false);
if ($config["access_tokens"]["bearertoken"] === "") CLI::DisplayError("Personal Access Token was not supplied.");
}
SaveConfig($configfile, $config);
echo "\n";
echo "Configuration file written to '" . $configfile . "'.\n\n";
}
$config = json_decode(file_get_contents($configfile), true);
if (!is_array($config)) CLI::DisplayError("The configuration file '" . $configfile . "' is corrupt. Try deleting the configuration file and running the command again.");
$do->SetAccessTokens($config["access_tokens"]);
// Callback function for saving updated tokens.
function SaveAccessTokens($do)
{
global $configfile, $config;
$config["access_tokens"] = $do->GetAccessTokens();
SaveConfig($configfile, $config);
}
$do->AddAccessTokensUpdatedNotify("SaveAccessTokens");
function ActionWaitHandler($first, $result, $opts)
{
if ($first) fwrite(STDERR, "Waiting for action '" . $result["action"]["id"] . "' to complete...");
else if ($result["action"]["status"] === "completed") fwrite(STDERR, "\n");
else fwrite(STDERR, ".");
}
function GetVolumeID()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id"))
{
$id = CLI::GetUserInputWithArgs($args, "id", "Volume ID", false, "", $suppressoutput);
$result = $do->VolumesGetInfo($id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->VolumesList();
if (!$result["success"]) DisplayResult($result);
$volumes = array();
$volumes2 = array();
foreach ($result["data"] as $volume)
{
$volumes[$volume["id"]] = $volume["region"]["slug"] . ", " . $volume["name"] . ", " . $volume["size_gigabytes"] . " GB";
$volumes2[$volume["id"]] = $volume;
}
if (!count($volumes)) CLI::DisplayError("No Block Storage volumes have been created. Try creating your first Block Storage volume with the API: volumes create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Volume ID", false, "Available Block Storage volumes:", $volumes, true, $suppressoutput);
unset($result["data"]);
$result["volume"] = $volumes2[$id];
}
return $result;
}
function GetVolumeSnapshotID($volumeid)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "snapshot")) $id = CLI::GetUserInputWithArgs($args, "snapshot", "Snapshot ID", false, "", $suppressoutput);
else
{
$result = $do->VolumesSnapshotsList($volumeid);
if (!$result["success"]) DisplayResult($result);
$snapshots = array();
foreach ($result["data"] as $snapshot)
{
$snapshots[$snapshot["id"]] = $snapshot["name"] . ", " . $snapshot["size_gigabytes"] . " GB (" . implode(", ", $snapshot["regions"]) . ")";
}
if (!count($snapshots)) CLI::DisplayError("No Block Storage volume snapshots have been created. Try creating your first Block Storage volume snapshot with the API: volumes snapshot");
$id = CLI::GetLimitedUserInputWithArgs($args, "snapshot", "Snapshot ID", false, "Available Block Storage volume snapshots:", $snapshots, true, $suppressoutput);
}
return $id;
}
function GetCDNEndpointID()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id")) $id = CLI::GetUserInputWithArgs($args, "id", "CDN endpoint ID", false, "", $suppressoutput);
else
{
$result = $do->CDNEndpointsList();
if (!$result["success"]) DisplayResult($result);
$cdns = array();
foreach ($result["data"] as $cdn)
{
$cdns[$cdn["id"]] = $cdn["origin"] . ($cdn["custom_domain"] !== "" ? " (" . $cdn["custom_domain"] . ")" : "");
}
if (!count($cdns)) CLI::DisplayError("No CDN endpoints have been created. Try creating your first CDN endpoint with the API: cdn-endpoints create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "CDN endpoint ID", false, "Available CDN endpoints:", $cdns, true, $suppressoutput);
}
return $id;
}
function GetCertificateID($default = false, $certificates = array())
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id")) $id = CLI::GetUserInputWithArgs($args, "id", "Certificate ID", $default, "", $suppressoutput);
else
{
$result = $do->CertificatesList();
if (!$result["success"]) DisplayResult($result);
foreach ($result["data"] as $certificate)
{
$certificates[$certificate["id"]] = $certificate["name"] . " (" . implode(", ", $certificate["dns_names"]) . ")";
}
if (!count($certificates)) CLI::DisplayError("No SSL certificates have been created. Try creating your first SSL certificate with the API: certificates create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Certificate ID", $default, "Available SSL certificates:", $certificates, true, $suppressoutput);
}
return $id;
}
function GetDatabaseClusterID()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id")) $id = CLI::GetUserInputWithArgs($args, "id", "Database cluster ID", false, "", $suppressoutput);
else
{
$result = $do->DatabaseClustersList();
if (!$result["success"]) DisplayResult($result);
$clusters = array();
foreach ($result["data"] as $cluster)
{
$clusters[$cluster["id"]] = $cluster["name"];
}
if (!count($clusters)) CLI::DisplayError("No database clusters have been created. Try creating your first database cluster with the API: database-clusters create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Database cluster ID", false, "Available database clusters:", $clusters, true, $suppressoutput);
}
return $id;
}
function GetDatabaseUsername($id)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "name")) $name = CLI::GetUserInputWithArgs($args, "name", "Database username", false, "", $suppressoutput);
else
{
$result = $do->DatabaseUsersList($id);
if (!$result["success"]) DisplayResult($result);
$users = array();
foreach ($result["data"] as $user)
{
$users[$user["name"]] = $user["name"] . " (" . $user["role"] . ")";
}
if (!count($users)) CLI::DisplayError("No database users have been created. Try creating your first database user with the API: database-users create");
$name = CLI::GetLimitedUserInputWithArgs($args, "name", "Database username", false, "Available database users:", $users, true, $suppressoutput);
}
return $name;
}
function GetDatabaseName($id)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "name")) $name = CLI::GetUserInputWithArgs($args, "name", "Database name", false, "", $suppressoutput);
else
{
$result = $do->DatabasesList($id);
if (!$result["success"]) DisplayResult($result);
$databases = array();
foreach ($result["data"] as $db)
{
$databases[$db["name"]] = $db["name"];
}
if (!count($databases)) CLI::DisplayError("No databases have been created. Try creating your first database with the API: database create");
$name = CLI::GetLimitedUserInputWithArgs($args, "name", "Database", false, "Available databases:", $databases, true, $suppressoutput);
}
return $name;
}
function GetDatabasePoolName($id)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "name")) $name = CLI::GetUserInputWithArgs($args, "name", "Database connection pool", false, "", $suppressoutput);
else
{
$result = $do->DatabasePoolsList($id);
if (!$result["success"]) DisplayResult($result);
$pools = array();
foreach ($result["data"] as $pool)
{
$pools[$pool["name"]] = $pool["mode"] . ", " . $pool["size"] . " max connections, " . $pool["db"] . ", " . $pool["user"];
}
if (!count($pools)) CLI::DisplayError("No database connection pools have been created. Try creating your first database connection pool with the API: database-pools create");
$name = CLI::GetLimitedUserInputWithArgs($args, "name", "Database connection pool", false, "Available database connection pools:", $pools, true, $suppressoutput);
}
return $name;
}
function GetDomainName($arg)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, $arg)) $domainname = CLI::GetUserInputWithArgs($args, $arg, "Domain name (TLD, no subdomains)", false, "", $suppressoutput);
else
{
$result = $do->DomainsList();
if (!$result["success"]) DisplayResult($result);
$domainnames = array();
foreach ($result["data"] as $domain) $domainnames[] = $domain["name"];
if (!count($domainnames)) CLI::DisplayError("No domains have been created. Try creating your first domain with the API: domains create");
$domainname = CLI::GetLimitedUserInputWithArgs($args, $arg, "Domain name (TLD, no subdomains)", false, "Available domain names:", $domainnames, true, $suppressoutput);
$domainname = $domainnames[$domainname];
}
return $domainname;
}
function GetDomainNameRecord($domainname)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id"))
{
$id = CLI::GetUserInputWithArgs($args, "id", "Domain record ID", false, "", $suppressoutput);
$result = $do->DomainRecordsGetInfo($domainname, $id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->DomainRecordsList($domainname);
if (!$result["success"]) DisplayResult($result);
$ids = array();
$ids2 = array();
foreach ($result["data"] as $record)
{
$ids[$record["id"]] = $record["type"] . " | " . $record["name"] . " | " . $record["data"] . (isset($record["priority"]) ? " | " . $record["priority"] : "") . (isset($record["port"]) ? " | " . $record["port"] : "") . (isset($record["weight"]) ? " | " . $record["weight"] : "");
$ids2[$record["id"]] = $record;
}
if (!count($ids)) CLI::DisplayError("No domain records have been created. Try creating your first domain record with the API: domain-records create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Domain record ID", false, "Available domain records:", $ids, true, $suppressoutput);
unset($result["data"]);
$result["record"] = $ids2[$id];
}
return $result;
}
function GetDropletSize($info = "")
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "size"))
{
$size = CLI::GetUserInputWithArgs($args, "size", "Droplet size", false, $info, $suppressoutput);
$disksize = false;
}
else
{
$result = $do->SizesList();
if (!$result["success"]) DisplayResult($result);
$sizes = array();
$sizes2 = array();
foreach ($result["data"] as $size)
{
if ($size["available"]) $sizes[$size["slug"]] = $size["memory"] . "MB RAM, " . $size["vcpus"] . ($size["vcpus"] == 1 ? " vCore, " : " vCores, ") . $size["disk"] . "GB disk, " . $size["transfer"] . "TB transfer\n\t\$" . $size["price_monthly"] . " USD/month OR \$" . $size["price_hourly"] . " USD/hour\n";
$sizes2[$size["slug"]] = $size;
}
if (!count($sizes)) CLI::DisplayError("No Droplet sizes are available. Is your account in good standing and does your account have a valid credit card on file?");
$size = CLI::GetLimitedUserInputWithArgs($args, "size", "Droplet size", false, ($info !== "" ? $info . " " : "") . "Available Droplet sizes:", $sizes, true, $suppressoutput);
$disksize = $sizes2[$size]["disk"];
}
return array("size" => $size, "disksize" => $disksize);
}
function GetDropletRegion($question, $size, $backups, $ipv6, $privatenetwork, $storage, $userdata)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "region")) $region = CLI::GetUserInputWithArgs($args, "region", $question, false, "", $suppressoutput);
else
{
$result = $do->RegionsList();
if (!$result["success"]) DisplayResult($result);
$regions = array();
foreach ($result["data"] as $region)
{
if ($region["available"] && ($size === false || in_array($size, $region["sizes"])) && (!$backups || in_array("backups", $region["features"])) && (!$ipv6 || in_array("ipv6", $region["features"])) && (!$privatenetwork || in_array("private_networking", $region["features"])) && (!$storage || in_array("storage", $region["features"])) && ($userdata === "" || in_array("metadata", $region["features"])))
{
$regions[$region["slug"]] = $region["name"];
}
}
if (!count($regions)) CLI::DisplayError("No suitable regions are available. Is your account in good standing and does your account have a valid credit card on file?");
$region = CLI::GetLimitedUserInputWithArgs($args, "region", $question, false, "Available regions:", $regions, true, $suppressoutput);
}
return $region;
}
function GetDropletImage($question, $defaultval, $disksize, $region, $useronly = false, $matchtype = false)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "image"))
{
$image = CLI::GetUserInputWithArgs($args, "image", $question, false, "", $suppressoutput);
$result = $do->ImagesGetInfo($image);
if (!$result["success"] || ($useronly && $image["public"])) DisplayResult($result);
$result["id"] = $image;
}
else
{
$images = array();
$imagemap = array();
if ($useronly) $extras = array("?private=true" => "private");
else $extras = array("?type=distribution" => "distribution", "?type=application" => "application", "?private=true" => "private");
foreach ($extras as $extra => $type)
{
$result = $do->ImagesList(true, $extra);
if (!$result["success"]) DisplayResult($result);
$images2 = array();
foreach ($result["data"] as $image)
{
if (($disksize === false || $disksize <= $image["min_disk_size"]) && ($region === false || in_array($region, $image["regions"])) && ($matchtype === false || $image["type"] === $matchtype))
{
$images2[(isset($image["slug"]) ? $image["slug"] : $image["id"])] = ((int)$image["name"] > 0 ? $image["distribution"] . " " . $image["name"] : $image["name"] . " " . $image["distribution"]) . "\n\t" . (isset($image["size_gigabytes"]) ? $image["size_gigabytes"] : "Under " . $image["min_disk_size"]) . "GB, " . $image["type"] . ", " . ($image["public"] ? "public, " . $type : "private") . "\n";
$imagemap[(isset($image["slug"]) ? $image["slug"] : $image["id"])] = $image;
}
}
ksort($images2);
foreach ($images2 as $id => $disp) $images[$id] = $disp;
}
if (!count($images)) CLI::DisplayError($useronly ? ($matchtype === "backup" ? "No backups are available." : "No user-created backups or snapshots are available.") : "No images are available. Is your account in good standing and does your account have a valid credit card on file?");
$image = CLI::GetLimitedUserInputWithArgs($args, "image", $question, ($defaultval !== false && isset($images[$defaultval]) ? $defaultval : false), "Available images:", $images, true, $suppressoutput);
unset($result["data"]);
$result["image"] = $imagemap[$image];
$result["id"] = $image;
}
return $result;
}
function GetDropletID($tagname = "", $region = false, $allowedids = false)
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id"))
{
$id = CLI::GetUserInputWithArgs($args, "id", "Droplet ID", false, "", $suppressoutput);
$result = $do->DropletsGetInfo($id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->DropletsList(true, ($tagname !== "" ? "?tag_name=" . urlencode($tagname) : ""));
if (!$result["success"]) DisplayResult($result);
$ids = array();
$ids2 = array();
foreach ($result["data"] as $droplet)
{
if ($region !== false && $region !== $droplet["region"]["slug"]) continue;
if ($allowedids !== false && !in_array($droplet["id"], $allowedids)) continue;
$ids[$droplet["id"]] = $droplet["name"] . " - " . $droplet["status"] . ($droplet["locked"] ? " (locked)" : "") . "\n\t" . $droplet["memory"] . "MB RAM, " . $droplet["vcpus"] . ($droplet["vcpus"] == 1 ? " vCore, " : " vCores, ") . $droplet["disk"] . "GB disk\n";
$ids2[$droplet["id"]] = $droplet;
}
if (!count($ids)) CLI::DisplayError("No droplets have been created" . ($region !== false ? " in the '" . $region . "' region. Try creating a droplet with the API: droplets create" : ". Try creating your first droplet with the API: droplets create"));
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Droplet ID", false, "Available Droplets:", $ids, true, $suppressoutput);
unset($result["data"]);
$result["droplet"] = $ids2[$id];
}
return $result;
}
function GetFirewallID()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id"))
{
$id = CLI::GetUserInputWithArgs($args, "id", "Firewall ID", false, "", $suppressoutput);
$result = $do->FirewallsGetInfo($id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->FirewallsList();
if (!$result["success"]) DisplayResult($result);
$ids = array();
$ids2 = array();
foreach ($result["data"] as $firewall)
{
$opts = array();
if (count($firewall["inbound_rules"]) == 1) $opts[] = "1 inbound rule";
else if (count($firewall["inbound_rules"]) == 0) $opts[] = "No inbound rules";
else $opts[] = count($firewall["inbound_rules"]) . " inbound rules";
if (count($firewall["outbound_rules"]) == 1) $opts[] = "1 outbound rule";
else if (count($firewall["outbound_rules"]) == 0) $opts[] = "No outbound rules";
else $opts[] = count($firewall["outbound_rules"]) . " outbound rules";
if (count($firewall["droplet_ids"]) == 1) $opts[] = "1 Droplet";
else if (count($firewall["droplet_ids"]) == 0) $opts[] = "No Droplets";
else $opts[] = count($firewall["droplet_ids"]) . " Droplets";
if (count($firewall["tags"]) == 1) $opts[] = "1 tag";
else if (count($firewall["tags"]) == 0) $opts[] = "No tags";
else $opts[] = count($firewall["tags"]) . " tags";
if (count($firewall["pending_changes"]) == 1) $opts[] = "1 pending change";
else if (count($firewall["pending_changes"]) != 0) $opts[] = count($firewall["pending_changes"]) . " pending changes";
$ids[$firewall["id"]] = $firewall["name"] . ", " . $firewall["status"] . " (" . implode(", ", $opts) . ")";
$ids2[$firewall["id"]] = $firewall;
}
if (!count($ids)) CLI::DisplayError("No firewalls have been created. Try creating your first firewall with the API: firewalls create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Firewall ID", false, "Available Firewalls:", $ids, true, $suppressoutput);
unset($result["data"]);
$result["firewall"] = $ids2[$id];
}
return $result;
}
function GetLoadBalancerID()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id"))
{
$id = CLI::GetUserInputWithArgs($args, "id", "Load balancer ID", false, "", $suppressoutput);
$result = $do->LoadBalancersGetInfo($id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->LoadBalancersList();
if (!$result["success"]) DisplayResult($result);
$ids = array();
$ids2 = array();
foreach ($result["data"] as $loadbalancer)
{
$ids[$loadbalancer["id"]] = $loadbalancer["name"] . ", " . $loadbalancer["ip"] . ", " . $loadbalancer["region"]["name"] . ", " . $loadbalancer["status"] . " (" . ($loadbalancer["tag"] !== "" ? $loadbalancer["tag"] : count($loadbalancer["droplet_ids"]) . " Droplets") . ")";
$ids2[$loadbalancer["id"]] = $loadbalancer;
}
if (!count($ids)) CLI::DisplayError("No load balancers have been created. Try creating your first load balancer with the API: load-balancers create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", "Load balancer ID", false, "Available load balancers:", $ids, true, $suppressoutput);
unset($result["data"]);
$result["load_balancer"] = $ids2[$id];
}
return $result;
}
function GetFloatingIPAddr()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "ipaddr"))
{
$ipaddr = CLI::GetUserInputWithArgs($args, "ipaddr", "Floating IP address", false, "", $suppressoutput);
$result = $do->FloatingIPsGetInfo($ipaddr);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->FloatingIPsList();
if (!$result["success"]) DisplayResult($result);
$ipaddrs = array();
$ipaddrs2 = array();
foreach ($result["data"] as $ipaddr)
{
$info = array();
if (isset($ipaddr["region"])) $info[] = $ipaddr["region"]["name"];
if (isset($ipaddr["droplet"])) $info[] = $ipaddr["droplet"]["name"] . " (" . $ipaddr["droplet"]["id"] . ")";
$ipaddrs[$ipaddr["ip"]] = implode(", ", $info);
$ipaddrs2[$ipaddr["ip"]] = $ipaddr;
}
if (!count($ipaddrs)) CLI::DisplayError("No Floating IPs have been created. Try creating your first Floating IP with the API: floating-ips create");
$ipaddr = CLI::GetLimitedUserInputWithArgs($args, "ipaddr", "Floating IP address", false, "Available Floating IPs:", $ipaddrs, true, $suppressoutput);
unset($result["data"]);
$result["ipaddr"] = $ipaddrs2[$ipaddr];
}
return $result;
}
function GetProjectID($question = "Project ID")
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "id")) $id = CLI::GetUserInputWithArgs($args, "id", $question, false, "", $suppressoutput);
else
{
$result = $do->ProjectsList();
if (!$result["success"]) DisplayResult($result);
$projects = array();
$default = false;
foreach ($result["data"] as $project)
{
$projects[$project["id"]] = $project["name"] . ($project["is_default"] ? " (default)" : "");
if ($project["is_default"]) $default = $project["id"];
}
if (!count($projects)) CLI::DisplayError("No Projects have been created. Try creating your first Project with the API: projects create");
$id = CLI::GetLimitedUserInputWithArgs($args, "id", $question, $default, "Available Projects:", $projects, true, $suppressoutput);
}
return $id;
}
function GetSSHKey()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "sshkey"))
{
$id = CLI::GetUserInputWithArgs($args, "sshkey", "SSH key ID", false, "", $suppressoutput);
$result = $do->SSHKeysGetInfo($id);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->SSHKeysList();
if (!$result["success"]) DisplayResult($result);
$ids = array();
$ids2 = array();
foreach ($result["data"] as $sshkey)
{
$ids[$sshkey["id"]] = $sshkey["name"] . " | " . $sshkey["fingerprint"];
$ids2[$sshkey["id"]] = $sshkey;
}
if (!count($ids)) CLI::DisplayError("No SSH keys have been created/registered. Try creating/registering your first SSH key with the API: ssh-keys create");
$id = CLI::GetLimitedUserInputWithArgs($args, "sshkey", "SSH key ID", false, "Available SSH keys:", $ids, true, $suppressoutput);
unset($result["data"]);
$result["ssh_key"] = $ids2[$id];
}
return $result;
}
function GetTagName()
{
global $suppressoutput, $args, $do;
if ($suppressoutput || CLI::CanGetUserInputWithArgs($args, "tag"))
{
$tagname = CLI::GetUserInputWithArgs($args, "tag", "Tag name", false, "", $suppressoutput);
$result = $do->TagsGetInfo($tagname);
if (!$result["success"]) DisplayResult($result);
}
else
{
$result = $do->TagsList();
if (!$result["success"]) DisplayResult($result);
$tags = array();
$tags2 = array();
foreach ($result["data"] as $tag)
{
$resources = array();
foreach ($tag["resources"] as $type => $resourceinfo)
{
if ($resourceinfo["count"] > 0) $resources[] = $resourceinfo["count"] . " " . $type;
}
if (!count($resources)) $resources[] = "No resources associated with this tag";
$tags[$tag["name"]] = implode(", ", $resources);
$tags2[$tag["name"]] = $tag;
}
if (!count($tags)) CLI::DisplayError("No tags have been created. Try creating your first tag with the API: tags create");
$tagname = CLI::GetLimitedUserInputWithArgs($args, "tag", "Tag name", false, "Available tags:", $tags, true, $suppressoutput);
unset($result["data"]);
$result["tag"] = $tags2[$tagname];
}
return $result;
}
function ReinitArgs($newargs)
{
global $args;
// Process the parameters.
$options = array(
"shortmap" => array(
"?" => "help"
),
"rules" => array(
)
);
foreach ($newargs as $arg) $options["rules"][$arg] = array("arg" => true, "multiple" => true);
$options["rules"]["help"] = array("arg" => false);
$args = CLI::ParseCommandLine($options, array_merge(array(""), $args["params"]));
if (isset($args["opts"]["help"])) DisplayResult(array("success" => true, "options" => array_keys($options["rules"])));
}
if ($apigroup === "account")
{
// Account.
if ($api === "get-info") DisplayResult($do->AccountGetInfo());
}
else if ($apigroup === "actions")
{
// Actions.
if ($api === "list")
{
ReinitArgs(array("pages"));
$numpages = (int)CLI::GetUserInputWithArgs($args, "pages", "Number of pages to retrieve", "1", "", $suppressoutput);
DisplayResult($do->ActionsList($numpages));
}
else if ($api === "get-info")
{
ReinitArgs(array("id"));
$id = CLI::GetUserInputWithArgs($args, "id", "Action ID", false, "", $suppressoutput);
DisplayResult($do->ActionsGetInfo($id));
}
else if ($api === "wait")
{
ReinitArgs(array("id", "wait"));
$id = CLI::GetUserInputWithArgs($args, "id", "Action ID", false, "", $suppressoutput);
$wait = (int)CLI::GetUserInputWithArgs($args, "wait", "Wait in seconds", false, "", $suppressoutput);
if ($wait < 1) $wait = 1;
DisplayResult($do->WaitForActionCompletion($id, $wait, array(), "ActionWaitHandler"));
}
}
else if ($apigroup === "volumes")
{
// Volumes.
if ($api === "list") DisplayResult($do->VolumesList());
else if ($api === "create")
{
ReinitArgs(array("name", "desc", "size", "mode", "region", "id", "snapshot", "fstype", "fslabel"));
$name = CLI::GetUserInputWithArgs($args, "name", "Block Storage volume name", false, "", $suppressoutput);
$desc = CLI::GetUserInputWithArgs($args, "desc", "Description", "", "", $suppressoutput);
$size = (int)CLI::GetUserInputWithArgs($args, "size", "Size (in GB)", "1", "DigitalOcean Block Storage is approximately \$0.10 USD/month per GB.", $suppressoutput);
if ($size < 1) $size = 1;
$modes = array(
"region" => "New Block Storage volume by region",
"snapshot" => "Block Storage volume snapshot"
);
$mode = CLI::GetLimitedUserInputWithArgs($args, "mode", "Mode", "region", "Available volume creation modes:", $modes, true, $suppressoutput);
$volumeopts = array();
if ($mode === "region")
{
// Get supported Droplet region.
$region = GetDropletRegion("Block Storage region", false, false, false, false, true, "");
$volumeopts["region"] = $region;
}
else
{
$result = GetVolumeID();
$id = $result["volume"]["id"];
$snapshotid = GetVolumeSnapshotID($id);
$volumeopts["snapshot_id"] = $snapshotid;
}
// Note: Attaching pre-formatted volumes to Droplets created before April 26, 2018 is not recommended.
$fstypes = array(
"" => "Unformatted",
"ext4" => "ext4",
"xfs" => "xfs"
);
$fstype = CLI::GetLimitedUserInputWithArgs($args, "fstype", "Filesystem type", "", "Available filesystem types:", $fstypes, true, $suppressoutput);
$volumeopts["filesystem_type"] = $fstype;
if ($fstype !== "")
{
$fslabel = CLI::GetUserInputWithArgs($args, "fslabel", "Filesystem label", "", "Labels for ext4 may contain 16 characters while xfs may contain 12 characters.", $suppressoutput);
$volumeopts["filesystem_label"] = $fslabel;
}
DisplayResult($do->VolumesCreate($name, $desc, $size, $volumeopts));
}
else
{
ReinitArgs(array("id", "name"));
$result = GetVolumeID();
$id = $result["volume"]["id"];
if ($api === "get-info") DisplayResult($result);
else if ($api === "snapshots") DisplayResult($do->VolumesSnapshotsList($id));
else if ($api === "snapshot")
{
$name = CLI::GetUserInputWithArgs($args, "name", "Snapshot name", false, "", $suppressoutput);
DisplayResult($do->VolumeSnapshotCreate($id, $name));
}
else if ($api === "delete") DisplayResult($do->VolumesDelete($id));
}
}
else if ($apigroup === "volume-actions")
{
ReinitArgs(array("id", "size", "wait"));
$result = GetVolumeID();
$id = $result["volume"]["id"];
$region = $result["volume"]["region"]["slug"];
$defaultwait = 5;
$initwait = array();
$actionvalues = array();
$actionvalues["region"] = $region;
if ($api === "attach" || $api === "detach")
{
$result = GetDropletID("", $region, ($api === "detach" ? $result["volume"]["droplet_ids"] : false));
$actionvalues["droplet_id"] = $result["droplet"]["id"];
}
else if ($api === "resize")
{
$size = (int)CLI::GetUserInputWithArgs($args, "size", "New size (in GB)", (string)($result["volume"]["size_gigabytes"] + 1), "For the next question, Block Storage volumes can only increase in size. DigitalOcean Block Storage is approximately \$0.10 USD/month per GB.", $suppressoutput);
if ($size <= $result["volume"]["size_gigabytes"]) CLI::DisplayError("Size specified is smaller than " . ($result["volume"]["size_gigabytes"] + 1) . " GB.");
$actionvalues["size_gigabytes"] = $size;
}
// Wait for action completion.
$wait = CLI::GetYesNoUserInputWithArgs($args, "wait", "Wait for completion", "Y", "The next question involves whether or not to wait for the Block Storage volume action to complete. If you don't want to wait, you can use the 'action' ID that is returned to wait later on for completion of the task.", $suppressoutput);
DisplayResult($do->VolumeActionsByID($id, $api, $actionvalues), $wait, $defaultwait, $initwait);
}
else if ($apigroup === "cdn-endpoints")
{
// Content Delivery Network (CDN) endpoints.
if ($api === "list") DisplayResult($do->CDNEndpointsList());
else if ($api === "create" || $api === "update")
{
ReinitArgs(array("origin", "ttl", "id", "customdomain"));
if ($api === "create") $origin = CLI::GetUserInputWithArgs($args, "origin", "Origin domain", false, "The next question asks for the fully qualified domain name (FQDN) for the origin server which the provides the content for the CDN.", $suppressoutput);
else
{
$id = GetCDNEndpointID();