-
Notifications
You must be signed in to change notification settings - Fork 11
/
session.go
5164 lines (4785 loc) · 154 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"
"encoding/hex"
"errors"
"fmt"
"math"
"net"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/mgo/v3/bson"
)
type Mode int
const (
// Relevant documentation on read preference modes:
//
// http://docs.mongodb.org/manual/reference/read-preference/
//
Primary Mode = 2 // Default mode. All operations read from the current replica set primary.
PrimaryPreferred Mode = 3 // Read from the primary if available. Read from the secondary otherwise.
Secondary Mode = 4 // Read from one of the nearest secondary members of the replica set.
SecondaryPreferred Mode = 5 // Read from one of the nearest secondaries if available. Read from primary otherwise.
Nearest Mode = 6 // Read from one of the nearest members, irrespective of it being primary or secondary.
// Read preference modes are specific to mgo:
Eventual Mode = 0 // Same as Nearest, but may change servers between reads.
Monotonic Mode = 1 // Same as SecondaryPreferred before first write. Same as Primary after first write.
Strong Mode = 2 // Same as Primary.
)
// 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 {
m sync.RWMutex
cluster_ *mongoCluster
slaveSocket *mongoSocket
masterSocket *mongoSocket
slaveOk bool
consistency Mode
queryConfig query
safeOp *queryOp
syncTimeout time.Duration
sockTimeout time.Duration
defaultdb string
sourcedb string
dialCred *Credential
creds []Credential
poolLimit int
bypassValidation bool
sessionId bson.Binary
nextTransactionNumber int64
transaction *transaction
}
type sessionId struct {
Id bson.Binary `bson:"id"`
}
type sessionInfo struct {
Id sessionId `bson:"id"`
TimeoutMinutes int `bson:"timeoutMinutes"`
}
type transaction struct {
number int64
sessionId bson.Binary
started bool
}
type Database struct {
Session *Session
Name string
}
type Collection struct {
Database *Database
Name string // "collection"
FullName string // "db.collection"
}
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 "getLastError,omitempty"
W interface{} "w,omitempty"
WTimeout int "wtimeout,omitempty"
FSync bool "fsync,omitempty"
J bool "j,omitempty"
}
type Iter struct {
m sync.Mutex
gotReply sync.Cond
session *Session
server *mongoServer
docData queue
err error
op getMoreOp
prefetch float64
limit int32
docsToReceive int
docsBeforeMore int
timeout time.Duration
timedout bool
findCmd bool
}
var (
ErrNotFound = errors.New("not found")
ErrCursor = errors.New("invalid cursor")
ErrNoTransaction = errors.New("no transaction in progress")
)
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 SetSocketTimeout.
//
// 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.
//
//
// 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
}
direct := false
mechanism := ""
service := ""
source := ""
setName := ""
poolLimit := 0
for k, v := range uinfo.options {
switch k {
case "authSource":
source = v
case "authMechanism":
mechanism = v
case "gssapiServiceName":
service = v
case "replicaSet":
setName = v
case "maxPoolSize":
poolLimit, err = strconv.Atoi(v)
if err != nil {
return nil, errors.New("bad value for maxPoolSize: " + v)
}
case "connect":
if v == "direct" {
direct = true
break
}
if v == "replicaSet" {
break
}
fallthrough
default:
return nil, errors.New("unsupported connection URL option: " + k + "=" + v)
}
}
info := DialInfo{
Addrs: uinfo.addrs,
Direct: direct,
Database: uinfo.db,
Username: uinfo.user,
Password: uinfo.pass,
Mechanism: mechanism,
Service: service,
Source: source,
PoolLimit: poolLimit,
ReplicaSetName: setName,
}
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
// 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
// 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.
// Deprecated: Use SocketTimeout and SyncTimeout
Timeout time.Duration
// SyncTimeout sets the amount of time an operation with this session
// will wait before returning an error in case a connection to a usable
// server can't be established. Set it to zero to wait forever.
// SyncTimeout does not affect logic in DialServer.
SyncTimeout time.Duration
// SocketTimeout sets the amount of time to wait for a non-responding
// socket to the database before it is forcefully closed.
// SocketTimeout does not affect logic in DialServer.
SocketTimeout time.Duration
// 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
// 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 4096.
// See Session.SetPoolLimit for details.
PoolLimit 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)
}
// 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(info *DialInfo) (*Session, error) {
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
}
if info.SyncTimeout == time.Duration(0) {
info.SyncTimeout = info.Timeout
}
if info.SocketTimeout == time.Duration(0) {
info.SocketTimeout = info.Timeout
}
cluster := newCluster(addrs, info.Direct, info.FailFast, dialer{info.Dial, info.DialServer}, info.ReplicaSetName)
session := newSession(Eventual, cluster, info.SyncTimeout, info.SocketTimeout)
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}
}
if info.PoolLimit > 0 {
session.poolLimit = info.PoolLimit
}
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.SetMode(Strong, true)
return session, nil
}
func isOptSep(c rune) bool {
return c == ';' || c == '&'
}
type urlInfo struct {
addrs []string
user string
pass string
db string
options map[string]string
}
func extractURL(s string) (*urlInfo, error) {
if strings.HasPrefix(s, "mongodb://") {
s = s[10:]
}
info := &urlInfo{options: make(map[string]string)}
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[l[0]] = 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, syncTimeout time.Duration, socketTimeout time.Duration) (session *Session) {
cluster.Acquire()
session = &Session{
cluster_: cluster,
syncTimeout: syncTimeout,
sockTimeout: socketTimeout,
poolLimit: 4096,
}
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
scopy.m = sync.RWMutex{}
scopy.transaction = nil
scopy.sessionId = bson.Binary{}
scopy.creds = creds
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}
}
// 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)
}
// Credential holds details to authenticate with a MongoDB server.
type Credential struct {
// Username and Password hold the basic details for authentication.
// Password is optional with some authentication mechanisms.
Username string
Password string
// Source is the database used to establish credentials and privileges
// with a MongoDB server. Defaults to the default database provided
// during dial, or "admin" if that was unset.
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
}
// Login authenticates with MongoDB using the provided credential. The
// authentication is valid for the whole session and will stay valid until
// Logout is explicitly called for the same database, or the session is
// closed.
func (db *Database) Login(user, pass string) error {
return db.Session.Login(&Credential{Username: user, Password: pass, Source: db.Name})
}
// Login authenticates with MongoDB using the provided credential. The
// authentication is valid for the whole session and will stay valid until
// Logout is explicitly called for the same database, or the session is
// closed.
func (s *Session) Login(cred *Credential) error {
socket, err := s.acquireSocket(true)
if err != nil {
return err
}
defer socket.Release()
credCopy := *cred
if cred.Source == "" {
if cred.Mechanism == "GSSAPI" {
credCopy.Source = "$external"
} else {
credCopy.Source = s.sourcedb
}
}
err = socket.Login(credCopy)
if err != nil {
return err
}
s.m.Lock()
s.creds = append(s.creds, credCopy)
s.m.Unlock()
return nil
}
func (s *Session) socketLogin(socket *mongoSocket) error {
for _, cred := range s.creds {
if err := socket.Login(cred); err != nil {
return err
}
}
return nil
}
// Logout removes any established authentication credentials for the database.
func (db *Database) Logout() {
session := db.Session
dbname := db.Name
session.m.Lock()
found := false
for i, cred := range session.creds {
if cred.Source == dbname {
copy(session.creds[i:], session.creds[i+1:])
session.creds = session.creds[:len(session.creds)-1]
found = true
break
}
}
if found {
if session.masterSocket != nil {
session.masterSocket.Logout(dbname)
}
if session.slaveSocket != nil {
session.slaveSocket.Logout(dbname)
}
}
session.m.Unlock()
}
// LogoutAll removes all established authentication credentials for the session.
func (s *Session) LogoutAll() {
s.m.Lock()
for _, cred := range s.creds {
if s.masterSocket != nil {
s.masterSocket.Logout(cred.Source)
}
if s.slaveSocket != nil {
s.slaveSocket.Logout(cred.Source)
}
}
s.creds = s.creds[0:0]
s.m.Unlock()
}
// User represents a MongoDB user.
//
// Relevant documentation:
//
// http://docs.mongodb.org/manual/reference/privilege-documents/
// http://docs.mongodb.org/manual/reference/user-privileges/
//
type User struct {
// Username is how the user identifies itself to the system.
Username string `bson:"user"`
// Password is the plaintext password for the user. If set,
// the UpsertUser method will hash it into PasswordHash and
// unset it before the user is added to the database.
Password string `bson:",omitempty"`
// PasswordHash is the MD5 hash of Username+":mongo:"+Password.
PasswordHash string `bson:"pwd,omitempty"`
// CustomData holds arbitrary data admins decide to associate
// with this user, such as the full name or employee id.
CustomData interface{} `bson:"customData,omitempty"`
// Roles indicates the set of roles the user will be provided.
// See the Role constants.
Roles []Role `bson:"roles"`
// OtherDBRoles allows assigning roles in other databases from
// user documents inserted in the admin database. This field
// only works in the admin database.
OtherDBRoles map[string][]Role `bson:"otherDBRoles,omitempty"`
// UserSource indicates where to look for this user's credentials.
// It may be set to a database name, or to "$external" for
// consulting an external resource such as Kerberos. UserSource
// must not be set if Password or PasswordHash are present.
//
// WARNING: This setting was only ever supported in MongoDB 2.4,
// and is now obsolete.
UserSource string `bson:"userSource,omitempty"`
}
type Role string
const (
// Relevant documentation:
//
// http://docs.mongodb.org/manual/reference/user-privileges/
//
RoleRoot Role = "root"
RoleRead Role = "read"
RoleReadAny Role = "readAnyDatabase"
RoleReadWrite Role = "readWrite"
RoleReadWriteAny Role = "readWriteAnyDatabase"
RoleDBAdmin Role = "dbAdmin"
RoleDBAdminAny Role = "dbAdminAnyDatabase"
RoleUserAdmin Role = "userAdmin"
RoleUserAdminAny Role = "userAdminAnyDatabase"
RoleClusterAdmin Role = "clusterAdmin"
)
// UpsertUser updates the authentication credentials and the roles for
// a MongoDB user within the db database. If the named user doesn't exist
// it will be created.
//
// This method should only be used from MongoDB 2.4 and on. For older
// MongoDB releases, use the obsolete AddUser method instead.
//
// Relevant documentation:
//
// http://docs.mongodb.org/manual/reference/user-privileges/
// http://docs.mongodb.org/manual/reference/privilege-documents/
//
func (db *Database) UpsertUser(user *User) error {
if user.Username == "" {
return fmt.Errorf("user has no Username")
}
if (user.Password != "" || user.PasswordHash != "") && user.UserSource != "" {
return fmt.Errorf("user has both Password/PasswordHash and UserSource set")
}
if len(user.OtherDBRoles) > 0 && db.Name != "admin" && db.Name != "$external" {
return fmt.Errorf("user with OtherDBRoles is only supported in the admin or $external databases")
}
// Attempt to run this using 2.6+ commands.
rundb := db
if user.UserSource != "" {
// Compatibility logic for the userSource field of MongoDB <= 2.4.X
rundb = db.Session.DB(user.UserSource)
}
err := rundb.runUserCmd("updateUser", user)
// retry with createUser when isAuthError in order to enable the "localhost exception"
if isNotFound(err) || isAuthError(err) {
return rundb.runUserCmd("createUser", user)
}
if !isNoCmd(err) {
return err
}
// Command does not exist. Fallback to pre-2.6 behavior.
var set, unset bson.D
if user.Password != "" {
psum := md5.New()
psum.Write([]byte(user.Username + ":mongo:" + user.Password))
set = append(set, bson.DocElem{"pwd", hex.EncodeToString(psum.Sum(nil))})
unset = append(unset, bson.DocElem{"userSource", 1})
} else if user.PasswordHash != "" {
set = append(set, bson.DocElem{"pwd", user.PasswordHash})
unset = append(unset, bson.DocElem{"userSource", 1})
}
if user.UserSource != "" {
set = append(set, bson.DocElem{"userSource", user.UserSource})
unset = append(unset, bson.DocElem{"pwd", 1})
}
if user.Roles != nil || user.OtherDBRoles != nil {
set = append(set, bson.DocElem{"roles", user.Roles})
if len(user.OtherDBRoles) > 0 {
set = append(set, bson.DocElem{"otherDBRoles", user.OtherDBRoles})
} else {
unset = append(unset, bson.DocElem{"otherDBRoles", 1})
}
}
users := db.C("system.users")
err = users.Update(bson.D{{"user", user.Username}}, bson.D{{"$unset", unset}, {"$set", set}})
if err == ErrNotFound {
set = append(set, bson.DocElem{"user", user.Username})
if user.Roles == nil && user.OtherDBRoles == nil {
// Roles must be sent, as it's the way MongoDB distinguishes
// old-style documents from new-style documents in pre-2.6.
set = append(set, bson.DocElem{"roles", user.Roles})
}
err = users.Insert(set)
}
return err
}
func isNoCmd(err error) bool {
e, ok := err.(*QueryError)
return ok && (e.Code == 59 || e.Code == 13390 || strings.HasPrefix(e.Message, "no such cmd:"))
}
func isNotFound(err error) bool {
e, ok := err.(*QueryError)
return ok && e.Code == 11
}
func isAuthError(err error) bool {
e, ok := err.(*QueryError)
return ok && e.Code == 13
}
func (db *Database) runUserCmd(cmdName string, user *User) error {
cmd := make(bson.D, 0, 16)
cmd = append(cmd, bson.DocElem{cmdName, user.Username})
if user.Password != "" {
cmd = append(cmd, bson.DocElem{"pwd", user.Password})
}
var roles []interface{}
for _, role := range user.Roles {
roles = append(roles, role)
}
for db, dbroles := range user.OtherDBRoles {
for _, role := range dbroles {
roles = append(roles, bson.D{{"role", role}, {"db", db}})
}
}
if roles != nil || user.Roles != nil || cmdName == "createUser" {
cmd = append(cmd, bson.DocElem{"roles", roles})
}
err := db.Run(cmd, nil)
if !isNoCmd(err) && user.UserSource != "" && (user.UserSource != "$external" || db.Name != "$external") {
return fmt.Errorf("MongoDB 2.6+ does not support the UserSource setting")
}
return err
}
// AddUser creates or updates the authentication credentials of user within
// the db database.
//
// WARNING: This method is obsolete and should only be used with MongoDB 2.2
// or earlier. For MongoDB 2.4 and on, use UpsertUser instead.
func (db *Database) AddUser(username, password string, readOnly bool) error {
// Try to emulate the old behavior on 2.6+
user := &User{Username: username, Password: password}
if db.Name == "admin" {
if readOnly {
user.Roles = []Role{RoleReadAny}
} else {
user.Roles = []Role{RoleReadWriteAny}
}