forked from domodwyer/mgo
-
Notifications
You must be signed in to change notification settings - Fork 230
/
session.go
5656 lines (5215 loc) · 175 KB
/
session.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
// mgo - MongoDB driver for Go
//
// Copyright (c) 2010-2012 - Gustavo Niemeyer <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package mgo
import (
"crypto/md5"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"errors"
"fmt"
"math"
"net"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/globalsign/mgo/bson"
)
// Mode read preference mode. See Eventual, Monotonic and Strong for details
//
// Relevant documentation on read preference modes:
//
// http://docs.mongodb.org/manual/reference/read-preference/
//
type Mode int
const (
// Primary mode is default mode. All operations read from the current replica set primary.
Primary Mode = 2
// PrimaryPreferred mode: read from the primary if available. Read from the secondary otherwise.
PrimaryPreferred Mode = 3
// Secondary mode: read from one of the nearest secondary members of the replica set.
Secondary Mode = 4
// SecondaryPreferred mode: read from one of the nearest secondaries if available. Read from primary otherwise.
SecondaryPreferred Mode = 5
// Nearest mode: read from one of the nearest members, irrespective of it being primary or secondary.
Nearest Mode = 6
// Eventual mode is specific to mgo, and is same as Nearest, but may change servers between reads.
Eventual Mode = 0
// Monotonic mode is specifc to mgo, and is same as SecondaryPreferred before first write. Same as Primary after first write.
Monotonic Mode = 1
// Strong mode is specific to mgo, and is same as Primary.
Strong Mode = 2
// DefaultConnectionPoolLimit defines the default maximum number of
// connections in the connection pool.
//
// To override this value set DialInfo.PoolLimit.
DefaultConnectionPoolLimit = 4096
zeroDuration = time.Duration(0)
)
// mgo.v3: Drop Strong mode, suffix all modes with "Mode".
// When changing the Session type, check if newSession and copySession
// need to be updated too.
// Session represents a communication session with the database.
//
// All Session methods are concurrency-safe and may be called from multiple
// goroutines. In all session modes but Eventual, using the session from
// multiple goroutines will cause them to share the same underlying socket.
// See the documentation on Session.SetMode for more details.
type Session struct {
defaultdb string
sourcedb string
syncTimeout time.Duration
consistency Mode
creds []Credential
dialCred *Credential
safeOp *queryOp
mgoCluster *mongoCluster
slaveSocket *mongoSocket
masterSocket *mongoSocket
m sync.RWMutex
queryConfig query
bypassValidation bool
slaveOk bool
dialInfo *DialInfo
}
// Database holds collections of documents
//
// Relevant documentation:
//
// https://docs.mongodb.com/manual/core/databases-and-collections/#databases
//
type Database struct {
Session *Session
Name string
}
// Collection stores documents
//
// Relevant documentation:
//
// https://docs.mongodb.com/manual/core/databases-and-collections/#collections
//
type Collection struct {
Database *Database
Name string // "collection"
FullName string // "db.collection"
}
// Query keeps info on the query.
type Query struct {
m sync.Mutex
session *Session
query // Enables default settings in session.
}
type query struct {
op queryOp
prefetch float64
limit int32
}
type getLastError struct {
CmdName int `bson:"getLastError,omitempty"`
W interface{} `bson:"w,omitempty"`
WTimeout int `bson:"wtimeout,omitempty"`
FSync bool `bson:"fsync,omitempty"`
J bool `bson:"j,omitempty"`
}
// Iter stores informations about a Cursor
//
// Relevant documentation:
//
// https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/
//
type Iter struct {
m sync.Mutex
gotReply sync.Cond
session *Session
server *mongoServer
docData queue
err error
op getMoreOp
prefetch float64
docsToReceive int
docsBeforeMore int
timeout time.Duration
limit int32
timedout bool
isFindCmd bool
isChangeStream bool
maxTimeMS int64
}
var (
// ErrNotFound error returned when a document could not be found
ErrNotFound = errors.New("not found")
// ErrCursor error returned when trying to retrieve documents from
// an invalid cursor
ErrCursor = errors.New("invalid cursor")
)
const (
defaultPrefetch = 0.25
maxUpsertRetries = 5
)
// Dial establishes a new session to the cluster identified by the given seed
// server(s). The session will enable communication with all of the servers in
// the cluster, so the seed servers are used only to find out about the cluster
// topology.
//
// Dial will timeout after 10 seconds if a server isn't reached. The returned
// session will timeout operations after one minute by default if servers aren't
// available. To customize the timeout, see DialWithTimeout, SetSyncTimeout, and
// DialInfo Read/WriteTimeout.
//
// This method is generally called just once for a given cluster. Further
// sessions to the same cluster are then established using the New or Copy
// methods on the obtained session. This will make them share the underlying
// cluster, and manage the pool of connections appropriately.
//
// Once the session is not useful anymore, Close must be called to release the
// resources appropriately.
//
// The seed servers must be provided in the following format:
//
// [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]
//
// For example, it may be as simple as:
//
// localhost
//
// Or more involved like:
//
// mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb
//
// If the port number is not provided for a server, it defaults to 27017.
//
// The username and password provided in the URL will be used to authenticate
// into the database named after the slash at the end of the host names, or into
// the "admin" database if none is provided. The authentication information
// will persist in sessions obtained through the New method as well.
//
// The following connection options are supported after the question mark:
//
// connect=direct
//
// Disables the automatic replica set server discovery logic, and
// forces the use of servers provided only (even if secondaries).
// Note that to talk to a secondary the consistency requirements
// must be relaxed to Monotonic or Eventual via SetMode.
//
//
// connect=replicaSet
//
// Discover replica sets automatically. Default connection behavior.
//
//
// replicaSet=<setname>
//
// If specified will prevent the obtained session from communicating
// with any server which is not part of a replica set with the given name.
// The default is to communicate with any server specified or discovered
// via the servers contacted.
//
//
// authSource=<db>
//
// Informs the database used to establish credentials and privileges
// with a MongoDB server. Defaults to the database name provided via
// the URL path, and "admin" if that's unset.
//
//
// authMechanism=<mechanism>
//
// Defines the protocol for credential negotiation. Defaults to "MONGODB-CR",
// which is the default username/password challenge-response mechanism.
//
//
// gssapiServiceName=<name>
//
// Defines the service name to use when authenticating with the GSSAPI
// mechanism. Defaults to "mongodb".
//
//
// maxPoolSize=<limit>
//
// Defines the per-server socket pool limit. Defaults to 4096.
// See Session.SetPoolLimit for details.
//
// minPoolSize=<limit>
//
// Defines the per-server socket pool minium size. Defaults to 0.
//
// maxIdleTimeMS=<millisecond>
//
// The maximum number of milliseconds that a connection can remain idle in the pool
// before being removed and closed. If maxIdleTimeMS is 0, connections will never be
// closed due to inactivity.
//
// appName=<appName>
//
// The identifier of this client application. This parameter is used to
// annotate logs / profiler output and cannot exceed 128 bytes.
//
// ssl=<true|false>
//
// true: Initiate the connection with TLS/SSL.
// false: Initiate the connection without TLS/SSL.
// The default value is false.
//
// Relevant documentation:
//
// http://docs.mongodb.org/manual/reference/connection-string/
//
func Dial(url string) (*Session, error) {
session, err := DialWithTimeout(url, 10*time.Second)
if err == nil {
session.SetSyncTimeout(1 * time.Minute)
session.SetSocketTimeout(1 * time.Minute)
}
return session, err
}
// DialWithTimeout works like Dial, but uses timeout as the amount of time to
// wait for a server to respond when first connecting and also on follow up
// operations in the session. If timeout is zero, the call may block
// forever waiting for a connection to be made.
//
// See SetSyncTimeout for customizing the timeout for the session.
func DialWithTimeout(url string, timeout time.Duration) (*Session, error) {
info, err := ParseURL(url)
if err != nil {
return nil, err
}
info.Timeout = timeout
return DialWithInfo(info)
}
// ParseURL parses a MongoDB URL as accepted by the Dial function and returns
// a value suitable for providing into DialWithInfo.
//
// See Dial for more details on the format of url.
func ParseURL(url string) (*DialInfo, error) {
uinfo, err := extractURL(url)
if err != nil {
return nil, err
}
ssl := false
direct := false
mechanism := ""
service := ""
source := ""
setName := ""
poolLimit := 0
appName := ""
readPreferenceMode := Primary
var readPreferenceTagSets []bson.D
minPoolSize := 0
maxIdleTimeMS := 0
safe := Safe{}
for _, opt := range uinfo.options {
switch opt.key {
case "ssl":
if v, err := strconv.ParseBool(opt.value); err == nil && v {
ssl = true
}
case "authSource":
source = opt.value
case "authMechanism":
mechanism = opt.value
case "gssapiServiceName":
service = opt.value
case "replicaSet":
setName = opt.value
case "w":
safe.WMode = opt.value
case "j":
journal, err := strconv.ParseBool(opt.value)
if err != nil {
return nil, errors.New("bad value for j: " + opt.value)
}
safe.J = journal
case "wtimeoutMS":
timeout, err := strconv.Atoi(opt.value)
if err != nil {
return nil, errors.New("bad value for wtimeoutMS: " + opt.value)
}
if timeout < 0 {
return nil, errors.New("bad value (negative) for wtimeoutMS: " + opt.value)
}
safe.WTimeout = timeout
case "maxPoolSize":
poolLimit, err = strconv.Atoi(opt.value)
if err != nil {
return nil, errors.New("bad value for maxPoolSize: " + opt.value)
}
case "appName":
if len(opt.value) > 128 {
return nil, errors.New("appName too long, must be < 128 bytes: " + opt.value)
}
appName = opt.value
case "readPreference":
switch opt.value {
case "nearest":
readPreferenceMode = Nearest
case "primary":
readPreferenceMode = Primary
case "primaryPreferred":
readPreferenceMode = PrimaryPreferred
case "secondary":
readPreferenceMode = Secondary
case "secondaryPreferred":
readPreferenceMode = SecondaryPreferred
default:
return nil, errors.New("bad value for readPreference: " + opt.value)
}
case "readPreferenceTags":
tags := strings.Split(opt.value, ",")
var doc bson.D
for _, tag := range tags {
kvp := strings.Split(tag, ":")
if len(kvp) != 2 {
return nil, errors.New("bad value for readPreferenceTags: " + opt.value)
}
doc = append(doc, bson.DocElem{Name: strings.TrimSpace(kvp[0]), Value: strings.TrimSpace(kvp[1])})
}
readPreferenceTagSets = append(readPreferenceTagSets, doc)
case "minPoolSize":
minPoolSize, err = strconv.Atoi(opt.value)
if err != nil {
return nil, errors.New("bad value for minPoolSize: " + opt.value)
}
if minPoolSize < 0 {
return nil, errors.New("bad value (negative) for minPoolSize: " + opt.value)
}
case "maxIdleTimeMS":
maxIdleTimeMS, err = strconv.Atoi(opt.value)
if err != nil {
return nil, errors.New("bad value for maxIdleTimeMS: " + opt.value)
}
if maxIdleTimeMS < 0 {
return nil, errors.New("bad value (negative) for maxIdleTimeMS: " + opt.value)
}
case "connect":
if opt.value == "direct" {
direct = true
break
}
if opt.value == "replicaSet" {
break
}
fallthrough
default:
return nil, errors.New("unsupported connection URL option: " + opt.key + "=" + opt.value)
}
}
if readPreferenceMode == Primary && len(readPreferenceTagSets) > 0 {
return nil, errors.New("readPreferenceTagSet may not be specified when readPreference is primary")
}
info := DialInfo{
Addrs: uinfo.addrs,
Direct: direct,
Database: uinfo.db,
Username: uinfo.user,
Password: uinfo.pass,
Mechanism: mechanism,
Service: service,
Source: source,
PoolLimit: poolLimit,
AppName: appName,
ReadPreference: &ReadPreference{
Mode: readPreferenceMode,
TagSets: readPreferenceTagSets,
},
Safe: safe,
ReplicaSetName: setName,
MinPoolSize: minPoolSize,
MaxIdleTimeMS: maxIdleTimeMS,
}
if ssl && info.DialServer == nil {
// Set DialServer only if nil, we don't want to override user's settings.
info.DialServer = func(addr *ServerAddr) (net.Conn, error) {
conn, err := tls.Dial("tcp", addr.String(), &tls.Config{})
return conn, err
}
}
return &info, nil
}
// DialInfo holds options for establishing a session with a MongoDB cluster.
// To use a URL, see the Dial function.
type DialInfo struct {
// Addrs holds the addresses for the seed servers.
Addrs []string
// Timeout is the amount of time to wait for a server to respond when
// first connecting and on follow up operations in the session. If
// timeout is zero, the call may block forever waiting for a connection
// to be established. Timeout does not affect logic in DialServer.
Timeout time.Duration
// Database is the default database name used when the Session.DB method
// is called with an empty name, and is also used during the initial
// authentication if Source is unset.
Database string
// ReplicaSetName, if specified, will prevent the obtained session from
// communicating with any server which is not part of a replica set
// with the given name. The default is to communicate with any server
// specified or discovered via the servers contacted.
ReplicaSetName string
// Source is the database used to establish credentials and privileges
// with a MongoDB server. Defaults to the value of Database, if that is
// set, or "admin" otherwise.
Source string
// Service defines the service name to use when authenticating with the GSSAPI
// mechanism. Defaults to "mongodb".
Service string
// ServiceHost defines which hostname to use when authenticating
// with the GSSAPI mechanism. If not specified, defaults to the MongoDB
// server's address.
ServiceHost string
// Mechanism defines the protocol for credential negotiation.
// Defaults to "MONGODB-CR".
Mechanism string
// Username and Password inform the credentials for the initial authentication
// done on the database defined by the Source field. See Session.Login.
Username string
Password string
// PoolLimit defines the per-server socket pool limit. Defaults to
// DefaultConnectionPoolLimit. See Session.SetPoolLimit for details.
PoolLimit int
// PoolTimeout defines max time to wait for a connection to become available
// if the pool limit is reached. Defaults to zero, which means forever. See
// Session.SetPoolTimeout for details
PoolTimeout time.Duration
// ReadTimeout defines the maximum duration to wait for a response to be
// read from MongoDB.
//
// This effectively limits the maximum query execution time. If a MongoDB
// query duration exceeds this timeout, the caller will receive a timeout,
// however MongoDB will continue processing the query. This duration must be
// large enough to allow MongoDB to execute the query, and the response be
// received over the network connection.
//
// Only limits the network read - does not include unmarshalling /
// processing of the response. Defaults to DialInfo.Timeout. If 0, no
// timeout is set.
ReadTimeout time.Duration
// WriteTimeout defines the maximum duration of a write to MongoDB over the
// network connection.
//
// This is can usually be low unless writing large documents, or over a high
// latency link. Only limits network write time - does not include
// marshalling/processing the request. Defaults to DialInfo.Timeout. If 0,
// no timeout is set.
WriteTimeout time.Duration
// The identifier of the client application which ran the operation.
AppName string
// ReadPreference defines the manner in which servers are chosen. See
// Session.SetMode and Session.SelectServers.
ReadPreference *ReadPreference
// Safe mostly defines write options, though there is RMode. See Session.SetSafe
Safe Safe
// FailFast will cause connection and query attempts to fail faster when
// the server is unavailable, instead of retrying until the configured
// timeout period. Note that an unavailable server may silently drop
// packets instead of rejecting them, in which case it's impossible to
// distinguish it from a slow server, so the timeout stays relevant.
FailFast bool
// Direct informs whether to establish connections only with the
// specified seed servers, or to obtain information for the whole
// cluster and establish connections with further servers too.
Direct bool
// MinPoolSize defines The minimum number of connections in the connection pool.
// Defaults to 0.
MinPoolSize int
// The maximum number of milliseconds that a connection can remain idle in the pool
// before being removed and closed.
MaxIdleTimeMS int
// DialServer optionally specifies the dial function for establishing
// connections with the MongoDB servers.
DialServer func(addr *ServerAddr) (net.Conn, error)
// WARNING: This field is obsolete. See DialServer above.
Dial func(addr net.Addr) (net.Conn, error)
}
// Copy returns a deep-copy of i.
func (i *DialInfo) Copy() *DialInfo {
var readPreference *ReadPreference
if i.ReadPreference != nil {
readPreference = &ReadPreference{
Mode: i.ReadPreference.Mode,
}
readPreference.TagSets = make([]bson.D, len(i.ReadPreference.TagSets))
copy(readPreference.TagSets, i.ReadPreference.TagSets)
}
info := &DialInfo{
Timeout: i.Timeout,
Database: i.Database,
ReplicaSetName: i.ReplicaSetName,
Source: i.Source,
Service: i.Service,
ServiceHost: i.ServiceHost,
Mechanism: i.Mechanism,
Username: i.Username,
Password: i.Password,
PoolLimit: i.PoolLimit,
PoolTimeout: i.PoolTimeout,
ReadTimeout: i.ReadTimeout,
WriteTimeout: i.WriteTimeout,
AppName: i.AppName,
ReadPreference: readPreference,
FailFast: i.FailFast,
Direct: i.Direct,
MinPoolSize: i.MinPoolSize,
MaxIdleTimeMS: i.MaxIdleTimeMS,
DialServer: i.DialServer,
Dial: i.Dial,
}
info.Addrs = make([]string, len(i.Addrs))
copy(info.Addrs, i.Addrs)
return info
}
// readTimeout returns the configured read timeout, or i.Timeout if it's not set
func (i *DialInfo) readTimeout() time.Duration {
if i.ReadTimeout == zeroDuration {
return i.Timeout
}
return i.ReadTimeout
}
// writeTimeout returns the configured write timeout, or i.Timeout if it's not
// set
func (i *DialInfo) writeTimeout() time.Duration {
if i.WriteTimeout == zeroDuration {
return i.Timeout
}
return i.WriteTimeout
}
// roundTripTimeout returns the total time allocated for a single network read
// and write.
func (i *DialInfo) roundTripTimeout() time.Duration {
return i.readTimeout() + i.writeTimeout()
}
// poolLimit returns the configured connection pool size, or
// DefaultConnectionPoolLimit.
func (i *DialInfo) poolLimit() int {
if i.PoolLimit == 0 {
return DefaultConnectionPoolLimit
}
return i.PoolLimit
}
// ReadPreference defines the manner in which servers are chosen.
type ReadPreference struct {
// Mode determines the consistency of results. See Session.SetMode.
Mode Mode
// TagSets indicates which servers are allowed to be used. See Session.SelectServers.
TagSets []bson.D
}
// mgo.v3: Drop DialInfo.Dial.
// ServerAddr represents the address for establishing a connection to an
// individual MongoDB server.
type ServerAddr struct {
str string
tcp *net.TCPAddr
}
// String returns the address that was provided for the server before resolution.
func (addr *ServerAddr) String() string {
return addr.str
}
// TCPAddr returns the resolved TCP address for the server.
func (addr *ServerAddr) TCPAddr() *net.TCPAddr {
return addr.tcp
}
// DialWithInfo establishes a new session to the cluster identified by info.
func DialWithInfo(dialInfo *DialInfo) (*Session, error) {
info := dialInfo.Copy()
info.PoolLimit = info.poolLimit()
info.ReadTimeout = info.readTimeout()
info.WriteTimeout = info.writeTimeout()
addrs := make([]string, len(info.Addrs))
for i, addr := range info.Addrs {
p := strings.LastIndexAny(addr, "]:")
if p == -1 || addr[p] != ':' {
// XXX This is untested. The test suite doesn't use the standard port.
addr += ":27017"
}
addrs[i] = addr
}
cluster := newCluster(addrs, info)
session := newSession(Eventual, cluster, info)
session.defaultdb = info.Database
if session.defaultdb == "" {
session.defaultdb = "test"
}
session.sourcedb = info.Source
if session.sourcedb == "" {
session.sourcedb = info.Database
if session.sourcedb == "" {
session.sourcedb = "admin"
}
}
if info.Username != "" {
source := session.sourcedb
if info.Source == "" &&
(info.Mechanism == "GSSAPI" || info.Mechanism == "PLAIN" || info.Mechanism == "MONGODB-X509") {
source = "$external"
}
session.dialCred = &Credential{
Username: info.Username,
Password: info.Password,
Mechanism: info.Mechanism,
Service: info.Service,
ServiceHost: info.ServiceHost,
Source: source,
}
session.creds = []Credential{*session.dialCred}
}
cluster.Release()
// People get confused when we return a session that is not actually
// established to any servers yet (e.g. what if url was wrong). So,
// ping the server to ensure there's someone there, and abort if it
// fails.
if err := session.Ping(); err != nil {
session.Close()
return nil, err
}
session.SetSafe(&info.Safe)
if info.ReadPreference != nil {
session.SelectServers(info.ReadPreference.TagSets...)
session.SetMode(info.ReadPreference.Mode, true)
} else {
session.SetMode(Strong, true)
}
session.dialInfo = info
return session, nil
}
func isOptSep(c rune) bool {
return c == ';' || c == '&'
}
type urlInfo struct {
addrs []string
user string
pass string
db string
options []urlInfoOption
}
type urlInfoOption struct {
key string
value string
}
func extractURL(s string) (*urlInfo, error) {
s = strings.TrimPrefix(s, "mongodb://")
info := &urlInfo{options: []urlInfoOption{}}
if c := strings.Index(s, "?"); c != -1 {
for _, pair := range strings.FieldsFunc(s[c+1:], isOptSep) {
l := strings.SplitN(pair, "=", 2)
if len(l) != 2 || l[0] == "" || l[1] == "" {
return nil, errors.New("connection option must be key=value: " + pair)
}
info.options = append(info.options, urlInfoOption{key: l[0], value: l[1]})
}
s = s[:c]
}
if c := strings.Index(s, "@"); c != -1 {
pair := strings.SplitN(s[:c], ":", 2)
if len(pair) > 2 || pair[0] == "" {
return nil, errors.New("credentials must be provided as user:pass@host")
}
var err error
info.user, err = url.QueryUnescape(pair[0])
if err != nil {
return nil, fmt.Errorf("cannot unescape username in URL: %q", pair[0])
}
if len(pair) > 1 {
info.pass, err = url.QueryUnescape(pair[1])
if err != nil {
return nil, fmt.Errorf("cannot unescape password in URL")
}
}
s = s[c+1:]
}
if c := strings.Index(s, "/"); c != -1 {
info.db = s[c+1:]
s = s[:c]
}
info.addrs = strings.Split(s, ",")
return info, nil
}
func newSession(consistency Mode, cluster *mongoCluster, info *DialInfo) (session *Session) {
cluster.Acquire()
session = &Session{
mgoCluster: cluster,
syncTimeout: info.Timeout,
dialInfo: info,
}
debugf("New session %p on cluster %p", session, cluster)
session.SetMode(consistency, true)
session.SetSafe(&Safe{})
session.queryConfig.prefetch = defaultPrefetch
return session
}
func copySession(session *Session, keepCreds bool) (s *Session) {
cluster := session.cluster()
cluster.Acquire()
if session.masterSocket != nil {
session.masterSocket.Acquire()
}
if session.slaveSocket != nil {
session.slaveSocket.Acquire()
}
var creds []Credential
if keepCreds {
creds = make([]Credential, len(session.creds))
copy(creds, session.creds)
} else if session.dialCred != nil {
creds = []Credential{*session.dialCred}
}
scopy := Session{
defaultdb: session.defaultdb,
sourcedb: session.sourcedb,
syncTimeout: session.syncTimeout,
consistency: session.consistency,
creds: creds,
dialCred: session.dialCred,
safeOp: session.safeOp,
mgoCluster: session.mgoCluster,
slaveSocket: session.slaveSocket,
masterSocket: session.masterSocket,
m: sync.RWMutex{},
queryConfig: session.queryConfig,
bypassValidation: session.bypassValidation,
slaveOk: session.slaveOk,
dialInfo: session.dialInfo,
}
s = &scopy
debugf("New session %p on cluster %p (copy from %p)", s, cluster, session)
return s
}
// LiveServers returns a list of server addresses which are
// currently known to be alive.
func (s *Session) LiveServers() (addrs []string) {
s.m.RLock()
addrs = s.cluster().LiveServers()
s.m.RUnlock()
return addrs
}
// DB returns a value representing the named database. If name
// is empty, the database name provided in the dialed URL is
// used instead. If that is also empty, "test" is used as a
// fallback in a way equivalent to the mongo shell.
//
// Creating this value is a very lightweight operation, and
// involves no network communication.
func (s *Session) DB(name string) *Database {
if name == "" {
name = s.defaultdb
}
return &Database{s, name}
}
// C returns a value representing the named collection.
//
// Creating this value is a very lightweight operation, and
// involves no network communication.
func (db *Database) C(name string) *Collection {
return &Collection{db, name, db.Name + "." + name}
}
// CreateView creates a view as the result of the applying the specified
// aggregation pipeline to the source collection or view. Views act as
// read-only collections, and are computed on demand during read operations.
// MongoDB executes read operations on views as part of the underlying aggregation pipeline.
//
// For example:
//
// db := session.DB("mydb")
// db.CreateView("myview", "mycoll", []bson.M{{"$match": bson.M{"c": 1}}}, nil)
// view := db.C("myview")
//
// Relevant documentation:
//
// https://docs.mongodb.com/manual/core/views/
// https://docs.mongodb.com/manual/reference/method/db.createView/
//
func (db *Database) CreateView(view string, source string, pipeline interface{}, collation *Collation) error {
command := bson.D{{Name: "create", Value: view}, {Name: "viewOn", Value: source}, {Name: "pipeline", Value: pipeline}}
if collation != nil {
command = append(command, bson.DocElem{Name: "collation", Value: collation})
}
return db.Run(command, nil)
}
// With returns a copy of db that uses session s.
func (db *Database) With(s *Session) *Database {
newdb := *db
newdb.Session = s
return &newdb
}
// With returns a copy of c that uses session s.
func (c *Collection) With(s *Session) *Collection {
newdb := *c.Database
newdb.Session = s
newc := *c
newc.Database = &newdb
return &newc
}
// GridFS returns a GridFS value representing collections in db that
// follow the standard GridFS specification.
// The provided prefix (sometimes known as root) will determine which
// collections to use, and is usually set to "fs" when there is a
// single GridFS in the database.
//
// See the GridFS Create, Open, and OpenId methods for more details.
//
// Relevant documentation:
//
// http://www.mongodb.org/display/DOCS/GridFS
// http://www.mongodb.org/display/DOCS/GridFS+Tools
// http://www.mongodb.org/display/DOCS/GridFS+Specification
//
func (db *Database) GridFS(prefix string) *GridFS {
return newGridFS(db, prefix)
}
// Run issues the provided command on the db database and unmarshals
// its result in the respective argument. The cmd argument may be either
// a string with the command name itself, in which case an empty document of
// the form bson.M{cmd: 1} will be used, or it may be a full command document.
//
// Note that MongoDB considers the first marshalled key as the command
// name, so when providing a command with options, it's important to
// use an ordering-preserving document, such as a struct value or an
// instance of bson.D. For instance:
//
// db.Run(bson.D{{"create", "mycollection"}, {"size", 1024}})
//
// For privilleged commands typically run on the "admin" database, see
// the Run method in the Session type.
//
// Relevant documentation:
//
// http://www.mongodb.org/display/DOCS/Commands
// http://www.mongodb.org/display/DOCS/List+of+Database+CommandSkips
//
func (db *Database) Run(cmd interface{}, result interface{}) error {
socket, err := db.Session.acquireSocket(true)
if err != nil {
return err
}
defer socket.Release()
// This is an optimized form of db.C("$cmd").Find(cmd).One(result).
return db.run(socket, cmd, result)
}