forked from mongodb/vault-plugin-database-mongodbatlas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_producer.go
98 lines (75 loc) · 2.28 KB
/
connection_producer.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
package mongodbatlas
import (
"context"
"errors"
"sync"
"github.com/Sectorbob/mlab-ns2/gae/ns/digest"
"github.com/hashicorp/vault/sdk/database/helper/connutil"
"github.com/mitchellh/mapstructure"
"github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"
)
type mongoDBAtlasConnectionProducer struct {
PublicKey string `json:"public_key" structs:"public_key" mapstructure:"public_key"`
PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"`
ProjectID string `json:"project_id" structs:"project_id" mapstructure:"project_id"`
Initialized bool
RawConfig map[string]interface{}
Type string
client *mongodbatlas.Client
sync.Mutex
}
func (c *mongoDBAtlasConnectionProducer) Initialize(ctx context.Context, conf map[string]interface{}, verifyConnection bool) error {
_, err := c.Init(ctx, conf, verifyConnection)
return err
}
// Initialize parses connection configuration.
func (c *mongoDBAtlasConnectionProducer) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) {
c.Lock()
defer c.Unlock()
err := mapstructure.WeakDecode(conf, c)
if err != nil {
return nil, err
}
if len(c.PublicKey) == 0 {
return nil, errors.New("public Key is not set")
}
if len(c.PrivateKey) == 0 {
return nil, errors.New("private Key is not set")
}
c.RawConfig = conf
// Set initialized to true at this point since all fields are set,
// and the connection can be established at a later time.
c.Initialized = true
return conf, nil
}
func (c *mongoDBAtlasConnectionProducer) secretValues() map[string]interface{} {
return map[string]interface{}{
c.PrivateKey: "[private_key]",
}
}
// Close terminates the database connection.
func (c *mongoDBAtlasConnectionProducer) Close() error {
c.Lock()
defer c.Unlock()
c.client = nil
return nil
}
func (c *mongoDBAtlasConnectionProducer) Connection(_ context.Context) (interface{}, error) {
if !c.Initialized {
return nil, connutil.ErrNotInitialized
}
if c.client != nil {
return c.client, nil
}
transport := digest.NewTransport(c.PublicKey, c.PrivateKey)
cl, err := transport.Client()
if err != nil {
return nil, err
}
client, err := mongodbatlas.New(cl)
if err != nil {
return nil, err
}
c.client = client
return c.client, nil
}