This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathclient.go
320 lines (281 loc) · 8.23 KB
/
client.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
package mongodb
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"time"
"github.com/compose/transporter/client"
"github.com/compose/transporter/log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
// DefaultURI is the default endpoint of MongoDB on the local machine.
// Primarily used when initializing a new Client without a specific URI.
DefaultURI = "mongodb://127.0.0.1:27017/test"
// DefaultSessionTimeout is the default timeout after which the
// session times out when unable to connect to the provided URI.
DefaultSessionTimeout = 10 * time.Second
// DefaultReadPreference when connecting to a mongo replica set.
DefaultReadPreference = mgo.Primary
// DefaultMaxWriteBatchSize when using the bulk interface
DefaultMaxWriteBatchSize = 1000
)
var (
// DefaultSafety is the default saftey mode used for the underlying session.
// These default settings are only good for local use as it makes not guarantees for writes.
DefaultSafety = mgo.Safe{}
_ client.Client = &Client{}
_ client.Closer = &Client{}
)
// OplogAccessError wraps the underlying error when access to the oplog fails.
type OplogAccessError struct {
reason string
}
func (e OplogAccessError) Error() string {
return fmt.Sprintf("oplog access failed, %s", e.reason)
}
// InvalidReadPreferenceError represents the error when an incorrect mongo read preference has been set.
type InvalidReadPreferenceError struct {
ReadPreference string
}
func (e InvalidReadPreferenceError) Error() string {
return fmt.Sprintf("Invalid Read Preference, %s", e.ReadPreference)
}
// ClientOptionFunc is a function that configures a Client.
// It is used in NewClient.
type ClientOptionFunc func(*Client) error
// Client represents a client to the underlying MongoDB source.
type Client struct {
uri string
safety mgo.Safe
tlsConfig *tls.Config
sessionTimeout time.Duration
tail bool
readPreference mgo.Mode
maxWriteBatchSize int
mgoSession *mgo.Session
}
// NewClient creates a new client to work with MongoDB.
//
// The caller can configure the new client by passing configuration options
// to the func.
//
// Example:
//
// client, err := NewClient(
// WithURI("mongodb://localhost:27017"),
// WithTimeout("30s"))
//
// If no URI is configured, it uses defaultURI by default.
//
// An error is also returned when some configuration option is invalid
func NewClient(options ...ClientOptionFunc) (*Client, error) {
// Set up the client
c := &Client{
uri: DefaultURI,
sessionTimeout: DefaultSessionTimeout,
safety: DefaultSafety,
tlsConfig: nil,
tail: false,
readPreference: DefaultReadPreference,
maxWriteBatchSize: DefaultMaxWriteBatchSize,
}
// Run the options on it
for _, option := range options {
if err := option(c); err != nil {
return nil, err
}
}
return c, nil
}
// WithURI defines the full connection string of the MongoDB database.
func WithURI(uri string) ClientOptionFunc {
return func(c *Client) error {
_, err := mgo.ParseURL(uri)
if err != nil {
return client.InvalidURIError{URI: uri, Err: err.Error()}
}
c.uri = uri
return nil
}
}
// WithTimeout overrides the DefaultSessionTimeout and should be parseable by time.ParseDuration
func WithTimeout(timeout string) ClientOptionFunc {
return func(c *Client) error {
if timeout == "" {
c.sessionTimeout = DefaultSessionTimeout
return nil
}
t, err := time.ParseDuration(timeout)
if err != nil {
return client.InvalidTimeoutError{Timeout: timeout}
}
c.sessionTimeout = t
return nil
}
}
// WithSSL configures the database connection to connect via TLS.
func WithSSL(ssl bool) ClientOptionFunc {
return func(c *Client) error {
if ssl {
tlsConfig := &tls.Config{InsecureSkipVerify: true}
tlsConfig.RootCAs = x509.NewCertPool()
c.tlsConfig = tlsConfig
}
return nil
}
}
// WithCACerts configures the RootCAs for the underlying TLS connection
func WithCACerts(certs []string) ClientOptionFunc {
return func(c *Client) error {
if len(certs) > 0 {
roots := x509.NewCertPool()
for _, cert := range certs {
if _, err := os.Stat(cert); err != nil {
return errors.New("Cert file not found")
}
c, err := ioutil.ReadFile(cert)
if err != nil {
return err
}
if ok := roots.AppendCertsFromPEM(c); !ok {
return client.ErrInvalidCert
}
}
if c.tlsConfig != nil {
c.tlsConfig.RootCAs = roots
} else {
c.tlsConfig = &tls.Config{RootCAs: roots}
}
c.tlsConfig.InsecureSkipVerify = false
}
return nil
}
}
// WithWriteConcern configures the write concern option for the session (Default: 0).
func WithWriteConcern(wc int) ClientOptionFunc {
return func(c *Client) error {
if wc > 0 {
c.safety.W = wc
}
return nil
}
}
// WithFsync configures whether the server will wait for Fsync to complete before returning
// a response (Default: false).
func WithFsync(fsync bool) ClientOptionFunc {
return func(c *Client) error {
c.safety.FSync = fsync
return nil
}
}
// WithTail set the flag to tell the Client whether or not access to the oplog will be
// needed (Default: false).
func WithTail(tail bool) ClientOptionFunc {
return func(c *Client) error {
c.tail = tail
return nil
}
}
// WithReadPreference sets the MongoDB read preference based on the provided string.
func WithReadPreference(readPreference string) ClientOptionFunc {
return func(c *Client) error {
if readPreference == "" {
c.readPreference = DefaultReadPreference
return nil
}
switch strings.ToLower(readPreference) {
case "primary":
c.readPreference = mgo.Primary
case "primarypreferred":
c.readPreference = mgo.PrimaryPreferred
case "secondary":
c.readPreference = mgo.Secondary
case "secondarypreferred":
c.readPreference = mgo.SecondaryPreferred
case "nearest":
c.readPreference = mgo.Nearest
default:
return InvalidReadPreferenceError{ReadPreference: readPreference}
}
return nil
}
}
// Connect tests the mongodb connection and initializes the mongo session
func (c *Client) Connect() (client.Session, error) {
if c.mgoSession == nil {
if err := c.initConnection(); err != nil {
return nil, err
}
}
return c.session(), nil
}
// Close satisfies the Closer interface and handles closing the initial mgo.Session.
func (c Client) Close() {
if c.mgoSession != nil {
c.mgoSession.Close()
}
}
func (c *Client) initConnection() error {
// we can ignore the error since all Client's will either use the DefaultURI or SetURI
dialInfo, _ := mgo.ParseURL(c.uri)
if c.tlsConfig != nil {
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
return tls.Dial("tcp", addr.String(), c.tlsConfig)
}
}
dialInfo.Timeout = c.sessionTimeout
mgoSession, err := mgo.DialWithInfo(dialInfo)
if err != nil {
return client.ConnectError{Reason: err.Error()}
}
// set some options on the session
// mgo logger _may_ be a bit too noisy but it'll be good to have for diagnosis
mgo.SetLogger(log.Base())
mgoSession.EnsureSafe(&c.safety)
mgoSession.SetBatch(100000)
mgoSession.SetPrefetch(0.5)
mgoSession.SetSocketTimeout(time.Hour)
mgoSession.SetMode(c.readPreference, true)
// Lets set the max batch size
var results bson.M
err = mgoSession.DB("").Run("isMaster", &results)
if err != nil {
return client.ConnectError{Reason: err.Error()}
}
c.maxWriteBatchSize = results["maxWriteBatchSize"].(int)
if c.tail {
log.With("uri", c.uri).Infoln("testing oplog access")
localColls, err := mgoSession.DB("local").CollectionNames()
if err != nil {
return OplogAccessError{"unable to list collections on local database"}
}
oplogFound := false
for _, c := range localColls {
if c == "oplog.rs" {
oplogFound = true
break
}
}
if !oplogFound {
return OplogAccessError{"database missing oplog.rs collection"}
}
if err := mgoSession.DB("local").C("oplog.rs").Find(bson.M{}).Limit(1).One(nil); err != nil {
return OplogAccessError{"not authorized for oplog.rs collection"}
}
log.Infoln("oplog access good")
}
c.mgoSession = mgoSession
return nil
}
// Session fulfills the client.Client interface by providing a copy of the main mgoSession
func (c *Client) session() client.Session {
sess := c.mgoSession.Copy()
return &Session{sess, c.maxWriteBatchSize}
}