forked from percona/percona-backup-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
249 lines (222 loc) · 5.88 KB
/
db.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
package testutils
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/globalsign/mgo"
"github.com/pkg/errors"
)
func loadCaCertificate(caFile string) (*x509.CertPool, error) {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
certificates := x509.NewCertPool()
if ok := certificates.AppendCertsFromPEM(caCert); !ok {
return nil, errors.New("could not append x509 PEM certificate to pool")
}
return certificates, nil
}
func dialInfo(addrs []string, rs string) (*mgo.DialInfo, error) {
MongoDBSSLDir = "../docker/test/ssl"
MongoDBSSLPEMKeyFile = filepath.Join(MongoDBSSLDir, "client.pem")
MongoDBSSLCACertFile = filepath.Join(MongoDBSSLDir, "rootCA.crt")
di, err := newDialInfo(&mgo.DialInfo{
Addrs: addrs,
ReplicaSetName: rs,
Username: MongoDBUser,
Password: MongoDBPassword,
Timeout: MongoDBTimeout,
Direct: true,
})
if err != nil {
return nil, err
}
return di, nil
}
func validateConnection(conn *tls.Conn, tlsConfig *tls.Config, dnsName string) error {
if err := conn.Handshake(); err != nil {
conn.Close()
return err
}
opts := x509.VerifyOptions{
CurrentTime: time.Now(),
DNSName: dnsName,
Roots: tlsConfig.RootCAs,
Intermediates: x509.NewCertPool(),
}
certs := conn.ConnectionState().PeerCertificates
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
_, err := certs[0].Verify(opts)
if err != nil {
conn.Close()
return err
}
return nil
}
func newDialInfo(di *mgo.DialInfo) (*mgo.DialInfo, error) {
dialInfo := &mgo.DialInfo{
AppName: "mongodbtest",
Addrs: di.Addrs,
ReplicaSetName: di.ReplicaSetName,
Username: di.Username,
Password: di.Password,
Direct: true,
}
MongoDBSSLDir := filepath.Join(BaseDir(), "docker/test/ssl")
MongoDBSSLPEMKeyFile := filepath.Join(MongoDBSSLDir, "client.pem")
MongoDBSSLCACertFile := filepath.Join(MongoDBSSLDir, "rootCA.crt")
CertFile := MongoDBSSLPEMKeyFile
CAFile := MongoDBSSLCACertFile
if di.Timeout > 0 {
dialInfo.Timeout = di.Timeout
}
// return early if ssl is disabled
if CertFile == "" && CAFile == "" {
return dialInfo, nil
}
certFileExists := false
caFileExists := false
if _, err := os.Stat(CertFile); !os.IsNotExist(err) {
certFileExists = true
}
if _, err := os.Stat(CAFile); !os.IsNotExist(err) {
caFileExists = true
}
tlsConfig := &tls.Config{
InsecureSkipVerify: !certFileExists || !caFileExists,
}
if certFileExists {
certificates, err := tls.LoadX509KeyPair(CertFile, CertFile)
if err != nil {
return nil, fmt.Errorf("Cannot load key pair from '%s': %v", CertFile, err)
}
tlsConfig.Certificates = []tls.Certificate{certificates}
}
if caFileExists {
caCert, err := loadCaCertificate(CAFile)
if err != nil {
return nil, fmt.Errorf("Cannot load client CA from '%s': %s", CAFile, err)
}
tlsConfig.RootCAs = caCert
}
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
if err != nil {
return nil, err
}
if !tlsConfig.InsecureSkipVerify {
// TODO: find a way to allow .validateConnection() errors to be read
// from outside of this func
dnsName := strings.SplitN(addr.String(), ":", 2)[0]
if err := validateConnection(conn, tlsConfig, dnsName); err != nil {
return nil, err
}
}
return conn, err
}
return dialInfo, nil
}
func DialInfoForPort(rs, port string) (*mgo.DialInfo, error) {
di, err := dialInfo([]string{
MongoDBHost + ":" + port},
rs,
)
if err != nil {
return nil, errors.Wrap(err, ".DialInfoForPort() failed")
}
return di, nil
}
func PrimaryDialInfo(t *testing.T, rs string) *mgo.DialInfo {
di, err := dialInfo([]string{
GetMongoDBAddr(rs, "primary")},
rs,
)
if err != nil {
t.Fatalf(".PrimaryDialInfo() failed: %v", err.Error())
}
return di
}
func ReplsetDialInfo(t *testing.T, rs string) *mgo.DialInfo {
di, err := dialInfo(
GetMongoDBReplsetAddrs(rs),
rs,
)
if err != nil {
t.Fatalf(".ReplsetDialInfo() failed: %v", err.Error())
}
di.Direct = false
return di
}
func ConfigsvrReplsetDialInfo(t *testing.T) *mgo.DialInfo {
di, err := dialInfo(
GetMongoDBReplsetAddrs(MongoDBConfigsvrReplsetName),
MongoDBConfigsvrReplsetName,
)
if err != nil {
t.Fatalf(".ConfigsvrReplsetDialInfo() failed: %v", err.Error())
}
di.Direct = false
return di
}
func MongosDialInfo(t *testing.T) *mgo.DialInfo {
di, err := dialInfo([]string{MongoDBHost + ":" + MongoDBMongosPort}, "")
if err != nil {
t.Fatalf(".MongosDialInfo() failed: %v", err.Error())
}
return di
}
func CleanupDatabases(session *mgo.Session, ignore map[string][]string) error {
if ignore == nil {
ignore = map[string][]string{}
}
// Ensure we don't delete the system.users collection otherwise authentication will be broken
if _, ok := ignore["admin"]; !ok {
ignore["admin"] = []string{"system.users"}
} else {
ignore["admin"] = append(ignore["admin"], "system.users")
}
databases, err := session.DatabaseNames()
if err != nil {
return errors.Wrap(err, "cannot get DBs list to clean up the config server")
}
for _, dbName := range databases {
collections, err := session.DB(dbName).CollectionNames()
if err != nil {
return errors.Wrapf(err, "cannot list %s database collections to clean up config server", dbName)
}
for _, collection := range collections {
if skipCollection(dbName, collection, ignore) {
continue
}
if _, err := session.DB(dbName).C(collection).RemoveAll(nil); err != nil {
return errors.Wrapf(err, "cannot empty %s.%s collection", dbName, collection)
}
}
}
return nil
}
func skipCollection(db, col string, ignoreList map[string][]string) bool {
ignoreCols, ok := ignoreList[db]
if !ok {
return false
}
for _, c := range ignoreCols {
if c == col {
return true
}
}
return false
}