/
example_databasetools_test.go
1140 lines (1037 loc) · 40.2 KB
/
example_databasetools_test.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 (c) 2016, 2018, 2024, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Examples for creating and validating Database Tools Connections with and without
// Database Tools Private Endpoint Reverse Connections. Examples include:
//
// Oracle:
// - ExampleCreateADBsConnectionWithPublicIp
// - ExampleCreateADBsConnectionWithPrivateEndpoint
//
// MySQL:
// - ExampleCreateMySqlConnectionWithPublicIp
// - ExampleCreateMySqlDbSystemConnectionWithPrivateEndpoint
//
// Starting the examples:
// - First, set environment variables accordingly (see comments below)
// - Run with go test
// go test ./example -run ^ExampleCreateADBsConnectionWithPublicIp$ -v
//
// Prerequisites and environment variables are noted in the comment preceding
// each Example*. All examples assume an OCI config with a [DEFAULT] profile
package example
import (
"archive/zip"
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/database"
"github.com/oracle/oci-go-sdk/v65/databasetools"
"github.com/oracle/oci-go-sdk/v65/example/helpers"
"github.com/oracle/oci-go-sdk/v65/keymanagement"
"github.com/oracle/oci-go-sdk/v65/mysql"
"github.com/oracle/oci-go-sdk/v65/vault"
)
// The config struct used here is an arbitrary collection of the information
// that the examples below require to function. It's helpful to understand the
// scope of the information used during the process of creating connections with
// the Database Tools service, but keep in mind that only certain bits are used
// depending on which SDK is being used. Furthermore, these are academic examples.
// Some liberties are taken with respect to error handling as the main focus is
// on demonstrating the SDK.
type config struct {
// populated by environment variables
DatabaseId *string // because the SDK expects pointers
VaultId *string
Username *string
Password *string
ConnectionString *string
Ctx context.Context
// populated by reading [home]/.oci/config
Provider common.ConfigurationProvider
// SDK clients populated at runtime
DBToolsClient databasetools.DatabaseToolsClient
VaultsClient vault.VaultsClient
KmsVaultsClient keymanagement.KmsVaultClient
DatabaseClient database.DatabaseClient
DbSystemClient mysql.DbSystemClient
// Resources used in various steps populated at runtime
VaultCompartmentId *string
VaultKeyId *string
WalletBase64 *string
TargetCompartmentId *string
EndpointServiceId *string
SubnetId *string
}
// Example Use Case: Existing ADB-S with public IP (no ACL)
//
// This example creates a Database Tools Connection to an Autonomous Database
// (ADB) on Shared Exadata Infrastructure, accessible by public IP. Note, since
// this connection will be against a public IP address, a Database Tools Private
// Endpoint Reverse Connection is not required.
//
// Prerequisites:
// - An existing ADB-S
// - An existing Vault for storage of secrets
// - A previously configured .oci/config file with a [DEFAULT] section
// - The following environment variables set:
// - OCI_DBS_OCID : The ocid for an ADB-s database
// - OCI_VAULT_OCID : The ocid for a vault (to store secrets)
// - OCI_DB_USER : The Oracle database user to connect with
// - OCI_DB_PASS : The Oracle database password to connect with
//
// High-level Steps:
//
// 1- Locate the Autonomous Database (ADB-S) by the provided OCID
// 2- Locate the Vault by the provided OCID
// 3- Download the wallet for the ADB-S
// 4- Store the secrets in the Vault (as base64 encoded strings)
// 5- Create a Database Tools connection
// 6- Validate the connection
//
// ... cleanup when done (delete the temporary secrets and connection)
//
// Client
// |
// |
// +----------------------+----------+
// | V |
// | +----------------+ |
// | | Database Tools | |
// | | Service | |
// | +----------------+ |
// | | |
// | Database | |
// | Tools | |
// | VCN | |
// +----------------------+----------+
// |
// |
// +--------------+ |
// | Customer | |
// | VCN | |
// +--------------+ |
// |
// |
// +----------------------+----------+
// | | |
// | V |
// | --------- |
// | / ABD-S \ |
// | \Public IP/ |
// | --------- |
// | |
// | ADB |
// | Shared |
// | VCN |
// +---------------------------------+
func ExampleCreateADBsConnectionWithPublicIp() {
// Parses environment variables, .oci/config, and sets up the SDK clients
cfg := newConfig()
// Ignoring errors for simplicity
walletSecretId, _ := createSecretInVault(cfg.WalletBase64, cfg)
passwdSecretId, _ := createSecretInVault(cfg.Password, cfg)
dbConnectionId, _ := createDatabaseToolsConnectionADBsPublicIp(walletSecretId, passwdSecretId, cfg)
if ok := validateDatabaseToolsConnectionOracle(dbConnectionId, cfg); ok {
log.Println("connection is valid")
}
// ... cleanup resources when finished, comment out the following delete
// calls to keep the resources created above.
if err := deleteConnection(dbConnectionId, cfg); err != nil {
log.Printf("error deleting connection: %v\n", err)
}
if err := deleteSecret(passwdSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
if err := deleteSecret(walletSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
fmt.Println("ExampleCreateADBsConnectionWithPublicIp complete")
// Output:
// ExampleCreateADBsConnectionWithPublicIp complete
}
// Example Use Case: Existing ADB-S with Private Endpoint
//
// This example creates a Database Tools Connection to a Autonomous Database (ADB-S)
// accessible by private endpoint (PE). Note, since this connection will be against
// a PE, a Database Tools Private Endpoint Reverse Connection is required. This
// example serves as an academic exercise of the SDK.
//
// Prerequisites:
// - An existing ADB-S with PE and network security group (i.e. ingress on 1522)
// - Available capacity (limits apply) to create a new Private Endpoint
// - An existing Vault for storage of secrets
// - A previously configured .oci/config file with a [DEFAULT] section
// - The following environment variables set:
// - OCI_DBS_OCID : The ocid for an ADB-s database
// - OCI_VAULT_OCID : The ocid for a vault (to store secrets)
// - OCI_DB_USER : The Oracle database user to connect with
// - OCI_DB_PASS : The Oracle database password to connect with
//
// High-level Steps:
//
// 1- Locate the Autonomous Database (ADB-S) by the provided OCID
// 2- Locate the Vault by the provided OCID
// 3- Download the wallet for the ADB-S
// 4- Store the secrets in the Vault (as base64 encoded strings)
// 5- Create a Database Tools Private Endpoint for a Reverse Connection to the Private Endpoint of the ADB-S
// 6- Create a Database Tools connection
// 7- Validate the connection
//
// ... cleanup when done (delete the temporary secrets, connection, and PE)
//
// Client
// |
// |
// +----------------------+----------+
// | V |
// | +----------------+ |
// | | Database Tools | |
// | | Service | |
// | +----------------+ |
// | | |
// | Database | |
// | Tools | |
// | VCN | |
// +----------------------+----------+
// |
// |
// +----------------------+----------+
// | | |
// | V |
// | +-----------+ |
// | | Database | |
// | | Tools | |
// | | Private | |
// | | Endpoint | |
// | | Reverse | |
// | | Connection| |
// | +-----------+ |
// | | |
// | V |
// | +-----------+ |
// | | ADB-S | |
// | | Private | |
// | | Endpoint | |
// | +-----------+ |
// | | |
// | Customer | |
// | VCN | |
// +----------------------+----------+
// |
// |
// +----------------------+----------+
// | | |
// | V |
// | --------- |
// | / ABD-S \ |
// | | Private | |
// | \ Endpoint/ |
// | --------- |
// | |
// | ADB |
// | Shared |
// | VCN |
// +---------------------------------+
func ExampleCreateADBsConnectionWithPrivateEndpoint() {
// Parses environment variables, .oci/config, and sets up the SDK clients
cfg := newConfig()
// Ignoring errors for simplicity
privateEndpointId, _ := createDbToolsPrivateEndpoint(cfg)
walletSecretId, _ := createSecretInVault(cfg.WalletBase64, cfg)
passwdSecretId, _ := createSecretInVault(cfg.Password, cfg)
dbConnectionId, _ := createDatabaseToolsConnectionADBs(walletSecretId, passwdSecretId, privateEndpointId, cfg)
if ok := validateDatabaseToolsConnectionOracle(dbConnectionId, cfg); ok {
log.Println("connection is valid")
}
// ... cleanup resources when finished, comment out the following delete
// calls to keep the resources created above.
if err := deleteConnection(dbConnectionId, cfg); err != nil {
log.Printf("error deleting connection: %v\n", err)
}
if err := deleteSecret(passwdSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
if err := deleteSecret(walletSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
if err := deletePrivateEndpoint(privateEndpointId, cfg); err != nil {
log.Printf("error deleting private endpoint: %v\n", err)
}
fmt.Println("ExampleCreateADBsConnectionWithPrivateEndpoint complete")
// Output:
// ExampleCreateADBsConnectionWithPrivateEndpoint complete
}
// Example Use Case: Existing MySQL database with public IP (customer-managed)
//
// This example creates a Database Tools Connection to a MySQL database
// accessible by public IP. Note, since this connection will be against a
// public IP address, a Database Tools Private Endpoint Reverse Connection
// is not required. Exposing a database directly to the Internet is not a
// recommended practice for security reasons. This example serves as an
// academic exercise of the SDK and proof of concept only.
//
// Prerequisites:
// - An existing MySQL database on a compute node, for example
// - Firewall or security list entries allowing TCP traffic to MySQL
// - An existing Vault for storage of secrets
// - A previously configured .oci/config file with a [DEFAULT] section
// - The following environment variables set:
// - OCI_VAULT_OCID : The ocid for a vault (to store secrets)
// - OCI_DB_USER : The MySQL database user to connect with
// - OCI_DB_PASS : The MySQL database password to connect with
// - OCI_CONN_STRING : The MySQL connection string, asin mysql://host:port
//
// High-level Steps:
//
// 1- Locate the Vault by the provided OCID
// 2- Store the secret in the Vault (as base64 encoded string)
// 3- Create a Database Tools Connection
// 4- Validate the connection
//
// ... cleanup when done (delete the temporary secret and connection)
//
// Client
// |
// |
// +----------------------+----------+
// | V |
// | +----------------+ |
// | | Database Tools | |
// | | Service | |
// | +----------------+ |
// | | |
// | Database | |
// | Tools | |
// | VCN | |
// +----------------------+----------+
// |
// |
// +----------------------+----------+
// | Compute | |
// | Node | |
// | | |
// | | |
// | V |
// | --------- |
// | / MySQL \ |
// | \Public IP/ |
// | --------- |
// | |
// +---------------------------------+
func ExampleCreateMySqlConnectionWithPublicIp() {
// Parses environment variables, .oci/config, and sets up the SDK clients
cfg := newConfig()
// Ignoring errors for simplicity
passwdSecretId, _ := createSecretInVault(cfg.Password, cfg)
dbConnectionId, _ := createDatabaseToolsConnectionMySqlPublicIp(passwdSecretId, cfg)
if ok := validateDatabaseToolsConnectionMySQL(dbConnectionId, cfg); ok {
log.Println("connection is valid")
}
// ... cleanup resources when finished, comment out the following delete
// calls to keep the resources created above.
if err := deleteConnection(dbConnectionId, cfg); err != nil {
log.Printf("error deleting connection: %v\n", err)
}
if err := deleteSecret(passwdSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
fmt.Println("ExampleCreateMySqlConnectionWithPublicIp complete")
// Output:
// ExampleCreateMySqlConnectionWithPublicIp complete
}
// Example Use Case: MySQL DB System with Database Tools Private Endpoint
//
// This example creates a Database Tools Connection to a MySQL DB System
// accessible by private IP. Note, since this connection will be against a
// private IP address, a Database Tools Private Endpoint Reverse Connection
// is required. This example serves as an academic exercise of the SDK.
//
// Prerequisites:
// - An existing MySQL DB System in a VCN and associated subnet
// - Available capacity (limits apply) to create a new Private Endpoint
// - An existing Vault for storage of secrets
// - A previously configured .oci/config file with a [DEFAULT] section
// - The following environment variables set:
// - OCI_DBS_OCID : The ocid for a MySQL DB System
// - OCI_VAULT_OCID : The ocid for a vault (to store secrets)
// - OCI_DB_USER : The MySQL database user to connect with
// - OCI_DB_PASS : The MySQL database password to connect with
//
// High-level Steps:
//
// 1- Locate the MySQL DB System by provided OCID
// 2- Locate the Vault by provided OCID
// 3- Store the secret in the Vault (as base64 encoded string)
// 4- Create a Database Tools Private Endpoint Reverse Connection
// 5- Create a Database Tools connection
// 6- Validate the connection
//
// ... cleanup when done (delete the temporary secret, connection, and PE)
//
// Client
// |
// |
// +----------------------+----------+
// | V |
// | +----------------+ |
// | | Database Tools | |
// | | Service | |
// | +----------------+ |
// | | |
// | Database | |
// | Tools | |
// | VCN | |
// +----------------------+----------+
// |
// |
// +----------------------+----------+
// | | |
// | V |
// | +-----------+ |
// | | Database | |
// | | Tools | |
// | | Private | |
// | | Endpoint | |
// | +-----------+ |
// | | |
// | | |
// | V |
// | --------- |
// | / MDS \ |
// | | Private | |
// | \ IP / |
// | --------- |
// | |
// | Customer |
// | VCN (jump host not required) |
// +---------------------------------+
func ExampleCreateMySqlDbSystemConnectionWithPrivateEndpoint() {
// Parses environment variables, .oci/config, and sets up the SDK clients
cfg := newConfig()
// Ignoring errors for simplicity
privateEndpointId, _ := createDbToolsPrivateEndpoint(cfg)
passwdSecretId, _ := createSecretInVault(cfg.Password, cfg)
dbConnectionId, _ := createDatabaseToolsConnectionMySql(passwdSecretId, privateEndpointId, cfg)
if ok := validateDatabaseToolsConnectionMySQL(dbConnectionId, cfg); ok {
log.Println("connection is valid")
}
// ... cleanup resources when finished, comment out the following delete
// calls to keep the resources created above.
if err := deleteConnection(dbConnectionId, cfg); err != nil {
log.Printf("error deleting connection: %v\n", err)
}
if err := deleteSecret(passwdSecretId, cfg); err != nil {
log.Printf("error deleting secret: %v\n", err)
}
if err := deletePrivateEndpoint(privateEndpointId, cfg); err != nil {
log.Printf("error deleting private endpoint: %v\n", err)
}
fmt.Println("ExampleCreateMySqlDbSystemConnectionWithPrivateEndpoint complete")
// Output:
// ExampleCreateMySqlDbSystemConnectionWithPrivateEndpoint complete
}
func deletePrivateEndpoint(id *string, cfg config) error {
if id == nil {
log.Println("=== Skipping delete since no private endpoint was found")
return nil
}
log.Printf("=== Deleting private endpoint: %+v\n", toString(id))
client := cfg.DBToolsClient
_, err := client.DeleteDatabaseToolsPrivateEndpoint(cfg.Ctx,
databasetools.DeleteDatabaseToolsPrivateEndpointRequest{
DatabaseToolsPrivateEndpointId: id,
})
if err != nil {
return err
}
err = waitForPrivateEndpoint(id, databasetools.LifecycleStateDeleted, cfg)
if err == nil {
log.Println("=== Private endpoint deleted")
}
return err
}
func deleteConnection(id *string, cfg config) error {
if id == nil {
log.Println("=== Skipping delete since no connection was found")
return nil
}
log.Printf("=== Deleting database tools connection: %+v\n", toString(id))
client := cfg.DBToolsClient
_, err := client.DeleteDatabaseToolsConnection(cfg.Ctx,
databasetools.DeleteDatabaseToolsConnectionRequest{
DatabaseToolsConnectionId: id,
})
if err != nil {
return err
}
err = waitForConnection(id, databasetools.LifecycleStateDeleted, cfg)
if err == nil {
log.Println("=== Connection deleted")
}
return err
}
func deleteSecret(id *string, cfg config) error {
if id == nil {
log.Println("=== Skipping delete since no secret was found")
return nil
}
log.Printf("=== Scheduling secret deletion: %+v\n", toString(id))
client := cfg.VaultsClient
_, err := client.ScheduleSecretDeletion(cfg.Ctx, vault.ScheduleSecretDeletionRequest{
SecretId: id,
ScheduleSecretDeletionDetails: vault.ScheduleSecretDeletionDetails{
TimeOfDeletion: &common.SDKTime{time.Now().UTC().Add(time.Hour * 48)},
},
})
if err != nil {
return err
}
err = waitForSecret(id, vault.SecretLifecycleStatePendingDeletion, cfg)
if err == nil {
log.Println("=== Secret deletion is scheduled")
}
return err
}
func validateDatabaseToolsConnectionOracle(id *string, cfg config) bool {
connectionDetailsType := databasetools.ValidateDatabaseToolsConnectionOracleDatabaseDetails{}
return validateDatabaseToolsConnection(id, connectionDetailsType, cfg)
}
func validateDatabaseToolsConnectionMySQL(id *string, cfg config) bool {
connectionDetailsType := databasetools.ValidateDatabaseToolsConnectionMySqlDetails{}
return validateDatabaseToolsConnection(id, connectionDetailsType, cfg)
}
// validateDatabaseToolsConnection is an example of how to validate a database tools
// connection. Note, the validateion details should be supplied for either Oracle
// or MySql connection type structs. (see above)
func validateDatabaseToolsConnection(id *string, connectionDetailsType databasetools.ValidateDatabaseToolsConnectionDetails, cfg config) bool {
if id == nil || connectionDetailsType == nil {
log.Println("=== Skipping validate (connection is nil)")
return false
}
log.Printf("=== Validating connection: %v\n", toString(id))
response, err := cfg.DBToolsClient.ValidateDatabaseToolsConnection(cfg.Ctx,
databasetools.ValidateDatabaseToolsConnectionRequest{
DatabaseToolsConnectionId: id,
ValidateDatabaseToolsConnectionDetails: connectionDetailsType,
})
if err != nil {
log.Printf("error validating connection: %v\n", err)
return false
}
if toString(response.GetCode()) != "OK" {
log.Printf("Validation response: %+v\n", response)
return false
}
return true
}
func createDatabaseToolsConnectionMySqlPublicIp(passwordSecretId *string, cfg config) (*string, error) {
return createDatabaseToolsConnectionMySql(passwordSecretId, nil, cfg)
}
// createDatabaseToolsConnectionMySql creates a database tools connection to a
// MySQL database. privateEndpointId can be nil, in which case the the
// connection should be for a database that can be reached by public IP.
func createDatabaseToolsConnectionMySql(passwordSecretId *string, privateEndpointId *string, cfg config) (*string, error) {
displayName := common.String("dbtools-temp-connection-" + helpers.GetRandomString(10))
if passwordSecretId == nil || cfg.TargetCompartmentId == nil || toString(cfg.ConnectionString) == "" || toString(cfg.Username) == "" {
return nil, errors.New("connection cannot be created due to missing details")
}
connectionDetails := databasetools.CreateDatabaseToolsConnectionMySqlDetails{
UserName: cfg.Username,
UserPassword: databasetools.DatabaseToolsUserPasswordSecretIdDetails{SecretId: passwordSecretId},
CompartmentId: cfg.TargetCompartmentId,
ConnectionString: cfg.ConnectionString,
DisplayName: displayName,
}
if privateEndpointId != nil {
connectionDetails.PrivateEndpointId = privateEndpointId
}
return createDatabaseToolsConnection(connectionDetails, cfg)
}
// createDatabaseToolsConnectionADBsPublicIp creates a database tools connection
// to an Autonomous Database without a private endpoint. For this to work the ADBs
// needs to be accessible by public IP address with mTLS connections.
func createDatabaseToolsConnectionADBsPublicIp(walletSecretId *string, passwordSecretId *string, cfg config) (*string, error) {
return createDatabaseToolsConnectionADBs(walletSecretId, passwordSecretId, nil, cfg)
}
// createDatabaseToolsConnectionADBs creates a database tools connection to an
// Autonomous Database. privateEndpointId can be nil, in which case the the
// connection should be for a database that can be reached by public IP.
func createDatabaseToolsConnectionADBs(walletSecretId *string, passwordSecretId *string, privateEndpointId *string, cfg config) (*string, error) {
displayName := common.String("dbtools-temp-connection-" + helpers.GetRandomString(10))
if walletSecretId == nil || passwordSecretId == nil || cfg.TargetCompartmentId == nil || toString(cfg.ConnectionString) == "" || toString(cfg.Username) == "" {
return nil, errors.New("connection cannot be created due to missing details")
}
keyStore := databasetools.DatabaseToolsKeyStoreDetails{
KeyStoreType: databasetools.KeyStoreTypeSso,
KeyStoreContent: databasetools.DatabaseToolsKeyStoreContentSecretIdDetails{
SecretId: walletSecretId,
},
}
connectionDetails := databasetools.CreateDatabaseToolsConnectionOracleDatabaseDetails{
KeyStores: []databasetools.DatabaseToolsKeyStoreDetails{keyStore},
UserName: cfg.Username,
UserPassword: databasetools.DatabaseToolsUserPasswordSecretIdDetails{SecretId: passwordSecretId},
CompartmentId: cfg.TargetCompartmentId,
ConnectionString: cfg.ConnectionString,
DisplayName: displayName,
}
if privateEndpointId != nil {
connectionDetails.PrivateEndpointId = privateEndpointId
}
return createDatabaseToolsConnection(connectionDetails, cfg)
}
// createDatabaseToolsConnection is an example of how to setup a database tools
// connection. Note, the connectionDetails should be supplied fpr either Oracle
// or MySql connection detail structs. (see above)
func createDatabaseToolsConnection(connectionDetails databasetools.CreateDatabaseToolsConnectionDetails, cfg config) (*string, error) {
client := cfg.DBToolsClient
log.Printf("=== Creating connection %s in compartment %s\n",
toString(connectionDetails.GetDisplayName()),
toString(connectionDetails.GetCompartmentId()))
log.Printf("Connection details provided: %+v\n", connectionDetails)
response, err := client.CreateDatabaseToolsConnection(cfg.Ctx,
databasetools.CreateDatabaseToolsConnectionRequest{
CreateDatabaseToolsConnectionDetails: connectionDetails,
})
if err != nil {
return nil, err
}
err = waitForConnection(response.GetId(), databasetools.LifecycleStateActive, cfg)
if err == nil {
log.Println("=== Connection is created")
}
return response.GetId(), err
}
// createDbToolsPrivateEndpoint is an example of how to setup a private endpoint
// using information gathered from an ADBs database (or a MySQL DB System). Given
// the appropriate tenancy and VCN details, a private endpoint can also be setup
// for Oracle or MySQL databases running on a compute node / subnet in a tenancy.
func createDbToolsPrivateEndpoint(cfg config) (*string, error) {
client := cfg.DBToolsClient
displayName := common.String("dbtools-temp-pe-" + helpers.GetRandomString(10))
if cfg.TargetCompartmentId == nil || cfg.EndpointServiceId == nil || cfg.SubnetId == nil {
return nil, errors.New("private endpoint cannot be created due to missing details")
}
log.Printf("=== Creating private endpoint %s with service %s\n", toString(displayName), toString(cfg.EndpointServiceId))
response, err := client.CreateDatabaseToolsPrivateEndpoint(cfg.Ctx,
databasetools.CreateDatabaseToolsPrivateEndpointRequest{
CreateDatabaseToolsPrivateEndpointDetails: databasetools.CreateDatabaseToolsPrivateEndpointDetails{
DisplayName: displayName,
CompartmentId: cfg.TargetCompartmentId,
EndpointServiceId: cfg.EndpointServiceId,
SubnetId: cfg.SubnetId,
},
})
if err != nil {
return nil, err
}
err = waitForPrivateEndpoint(response.Id, databasetools.LifecycleStateActive, cfg)
if err == nil {
log.Println("=== Private endpoint is created")
}
return response.Id, err
}
// createSecretInVault creates a secret in a vault within the target tenancy.
// Database Tools Connections do not store secrets directly. Only a reference
// (ocid) of the secret is stored with the connection. Database Tools calls out
// to the Key Management and Vaults services to use secrets.
func createSecretInVault(secretValue *string, cfg config) (*string, error) {
client := cfg.VaultsClient
displayName := common.String("dbtools-temp-secret-" + helpers.GetRandomString(10))
if secretValue == nil || cfg.VaultId == nil || cfg.VaultKeyId == nil || cfg.TargetCompartmentId == nil {
return nil, errors.New("secret cannot be created due to missing details")
}
log.Printf("=== Creating secret %s in vault %s\n", toString(displayName), toString(cfg.VaultId))
response, err := client.CreateSecret(cfg.Ctx, vault.CreateSecretRequest{
CreateSecretDetails: vault.CreateSecretDetails{
CompartmentId: cfg.TargetCompartmentId,
SecretContent: vault.Base64SecretContentDetails{
Content: secretValue,
},
SecretName: displayName,
VaultId: cfg.VaultId,
KeyId: cfg.VaultKeyId, // Documented as not mandatory, but is required
},
})
if err != nil {
return nil, err
}
err = waitForSecret(response.Secret.Id, vault.SecretLifecycleStateActive, cfg)
if err == nil {
log.Println("=== Secret is created")
}
return response.Secret.Id, err
}
// The process of creating or deleting a secret is asynchronous so if a secret
// is to be used after the creation starts, for example, wait for the lifecycle
// state to be ACTIVE.
func waitForSecret(secretId *string, targetState vault.SecretLifecycleStateEnum, cfg config) error {
client := cfg.VaultsClient
for {
secret, err := client.GetSecret(cfg.Ctx, vault.GetSecretRequest{
SecretId: secretId,
})
if err != nil {
return err
}
log.Printf("waitForSecret: lifecycle state = %v\n", secret.LifecycleState)
if secret.LifecycleState == targetState {
return nil
}
time.Sleep(5 * time.Second)
}
}
// The process of creating or deleting a connection is asynchronous so if a
// connection is to be used after the creation starts, for example, wait for the
// lifecycle state to be ACTIVE.
func waitForConnection(connectionId *string, targetState databasetools.LifecycleStateEnum, cfg config) error {
client := cfg.DBToolsClient
for {
connection, err := client.GetDatabaseToolsConnection(cfg.Ctx,
databasetools.GetDatabaseToolsConnectionRequest{
DatabaseToolsConnectionId: connectionId,
})
if err != nil {
return err
}
log.Printf("waitForConnection: lifecycle state = %v\n", connection.GetLifecycleState())
if connection.GetLifecycleState() == targetState {
return nil
}
time.Sleep(10 * time.Second)
}
}
// The process of creating or deleting a private endpoint is asynchronous so if
// a private endpoint is to be used after the creation starts, for example, wait
// for the lifecycle state to be ACTIVE.
func waitForPrivateEndpoint(endpointId *string, targetState databasetools.LifecycleStateEnum, cfg config) error {
client := cfg.DBToolsClient
for {
pe, err := client.GetDatabaseToolsPrivateEndpoint(cfg.Ctx,
databasetools.GetDatabaseToolsPrivateEndpointRequest{
DatabaseToolsPrivateEndpointId: endpointId,
})
if err != nil {
return err
}
log.Printf("waitForPrivateEndpoint: lifecycle state = %v\n", pe.LifecycleState)
if pe.LifecycleState == targetState {
return nil
}
time.Sleep(10 * time.Second)
}
}
// newConfig returns a collection of the environment variables and SDK clients
// used by the examples. These are stored in a config struct. Helper functions
// are attached to config to make the examples above a little less verbose but
// this is purely to help focus the examples and integration with services.
func newConfig() config {
cfg := config{
Ctx: context.Background(),
Provider: common.DefaultConfigProvider(),
DatabaseId: common.String(os.Getenv("OCI_DBS_OCID")),
VaultId: common.String(os.Getenv("OCI_VAULT_OCID")),
Username: common.String(os.Getenv("OCI_DB_USER")),
ConnectionString: common.String(os.Getenv("OCI_CONN_STRING")),
Password: common.String(
base64.StdEncoding.EncodeToString(
[]byte(os.Getenv("OCI_DB_PASS")))),
}
cfg.DBToolsClient = cfg.getDatabaseToolsClient()
cfg.VaultsClient = cfg.getVaultsClient()
cfg.KmsVaultsClient = cfg.getKmsVaultsClient()
cfg.DatabaseClient = cfg.getDatabaseClient()
cfg.DbSystemClient = cfg.getMySqlDbSystemClient()
// Things that need to be initialized AFTER the SDK clients
cfg.VaultCompartmentId = cfg.getVaultCompartmentId()
cfg.VaultKeyId = cfg.getVaultKeyId()
cfg.WalletBase64 = cfg.getADBsWalletAsBase64String()
cfg.TargetCompartmentId = cfg.getTargetCompartmentId()
cfg.EndpointServiceId = cfg.getEndpointServiceId() // depends on TargetCompartmentId
cfg.SubnetId = cfg.getDatabaseSubnetId()
cfg.ConnectionString = cfg.getConnectionString() // respects OCI_CONN_STRING if defined
return cfg
}
func (cfg config) getADBsWalletAsBase64String() *string {
client := cfg.DatabaseClient
id := cfg.DatabaseId
if !strings.Contains(toString(id), ".autonomousdatabase.") {
if toString(cfg.DatabaseId) != "" {
log.Printf("Database ID provided is not an Autonomous Database (no wallet to download): %s\n", toString(id))
}
return nil
}
response, err := client.GenerateAutonomousDatabaseWallet(cfg.Ctx,
database.GenerateAutonomousDatabaseWalletRequest{
AutonomousDatabaseId: id,
GenerateAutonomousDatabaseWalletDetails: database.GenerateAutonomousDatabaseWalletDetails{
Password: common.String("1StrongPassword###"),
GenerateType: "SINGLE",
},
})
if err != nil {
log.Printf("error generating ADBs wallet: %v\n", err)
response.Content.Close()
return nil
}
defer response.Content.Close()
zipFileBytes, err := ioutil.ReadAll(response.Content)
if err != nil {
log.Printf("error reading ADBs wallet zip: %v\n", err)
return nil
}
cwalletBytes, err := cfg.getFileFromZip(zipFileBytes, "cwallet.sso")
if err != nil {
log.Printf("error reading cwallet.sso from zip: %v\n", err)
return nil
}
return common.String(
base64.StdEncoding.EncodeToString(cwalletBytes))
}
func (cfg config) getEndpointServiceId() *string {
client := cfg.DBToolsClient
if cfg.TargetCompartmentId == nil {
log.Println("unable to get endpoint service (compartment id is nil)")
return nil
}
service, err := client.ListDatabaseToolsEndpointServices(cfg.Ctx,
databasetools.ListDatabaseToolsEndpointServicesRequest{
CompartmentId: cfg.TargetCompartmentId,
Name: common.String("DATABASE_TOOLS"),
})
if err != nil {
log.Printf("error getting endpoint service: %v\n", err)
return nil
}
if len(service.Items) > 0 {
return service.Items[0].Id
}
return nil
}
func (cfg config) getTargetCompartmentId() *string {
id := toString(cfg.DatabaseId)
if strings.Contains(id, ".mysqldbsystem.") {
db, err := cfg.getMySqlDbSystem()
if err != nil {
log.Printf("error getting MySQL DB system compartment: %v\n", err)
return nil
}
return db.CompartmentId
} else if strings.Contains(id, ".autonomousdatabase.") {
db, err := cfg.getADBsDatabase()
if err != nil {
log.Printf("error getting ADBs compartment: %v\n", err)
return nil
}
return db.CompartmentId
} else if id == "" {
tenancy, err := cfg.Provider.TenancyOCID()
if err != nil {
log.Printf("error getting root compartment from provider: %v\n", err)
return nil
}
return common.String(tenancy)
}
return nil
}
func (cfg config) getDatabaseSubnetId() *string {
id := toString(cfg.DatabaseId)
if strings.Contains(id, ".mysqldbsystem.") {
db, err := cfg.getMySqlDbSystem()
if err != nil {
log.Printf("error getting MySQL DB system subnet: %v\n", err)
return nil
}
return db.SubnetId
} else if strings.Contains(id, ".autonomousdatabase.") {
db, err := cfg.getADBsDatabase()
if err != nil {
log.Printf("error getting ADBs subnet: %v\n", err)
return nil
}
return db.SubnetId
} else {
return nil
}
}
func (cfg config) getConnectionString() (connectionString *string) {
log.Println("=== Getting database connection string")
if toString(cfg.ConnectionString) != "" {
connectionString = cfg.ConnectionString
} else {
id := toString(cfg.DatabaseId)
if strings.Contains(id, ".mysqldbsystem.") {
connectionString = cfg.getMySqlDbSystemConnectionString()
} else if strings.Contains(id, ".autonomousdatabase.") {
connectionString = cfg.getADBsConnectionString("low")
} else {
log.Println("Connection string is not defined")
}
}
return
}
func (cfg config) getMySqlDbSystemConnectionString() *string {
db, err := cfg.getMySqlDbSystem()
if err != nil {
log.Printf("error getting MySQL DB system connection string: %v\n", err)
return nil
}
for _, endpoint := range db.Endpoints {
if endpoint.Port != nil && endpoint.IpAddress != nil {
connectionString := fmt.Sprintf("mysql://%s:%d", *endpoint.IpAddress, *endpoint.Port)
return common.String(connectionString)
}
}
return nil
}
func (cfg config) getADBsConnectionString(suffix string) *string {
db, err := cfg.getADBsDatabase()
if err != nil {
log.Printf("error getting ADBs connection string: %v\n", err)
return nil
}
for _, c := range db.ConnectionStrings.Profiles {
if len(suffix) == 0 || strings.HasSuffix(toString(c.DisplayName), suffix) {
return c.Value
}
}
return nil
}
func (cfg config) getMySqlDbSystem() (*mysql.GetDbSystemResponse, error) {
client := cfg.DbSystemClient
id := cfg.DatabaseId
if !strings.Contains(toString(id), ".mysqldbsystem.") {
return nil, errors.New("database id provided is not a valid mysql db system " + toString(id))
}
db, err := client.GetDbSystem(cfg.Ctx, mysql.GetDbSystemRequest{