-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
3228 lines (2997 loc) · 95.7 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 <gustavo@niemeyer.net>
//
// 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"
"labix.org/v2/mgo/bson"
"math"
"net"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
)
type mode int
const (
Eventual mode = 0
Monotonic mode = 1
Strong mode = 2
)
// When changing the Session type, check if newSession and copySession
// need to be updated too.
type Session struct {
m sync.RWMutex
cluster_ *mongoCluster
slaveSocket *mongoSocket
masterSocket *mongoSocket
slaveOk bool
consistency mode
queryConfig query
safeOp *queryOp
syncTimeout time.Duration
defaultdb string
dialAuth *authInfo
auth []authInfo
}
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"
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
}
var ErrNotFound = errors.New("not found")
const defaultPrefetch = 0.25
// 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
// and SetSyncTimeout.
//
// 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
//
// This option will disable the automatic replica set server
// discovery logic, and will only use the servers provided.
// This enables forcing the communication with a specific
// server or set of servers (even if they are slaves). Note
// that to talk to a slave you'll need to relax the consistency
// requirements using a Monotonic or Eventual mode via SetMode.
//
// Relevant documentation:
//
// http://www.mongodb.org/display/DOCS/Connections
//
func Dial(url string) (*Session, error) {
session, err := DialWithTimeout(url, 10*time.Second)
if err == nil {
session.SetSyncTimeout(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) {
uinfo, err := parseURL(url)
if err != nil {
return nil, err
}
direct := false
for k, v := range uinfo.options {
switch k {
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,
Timeout: timeout,
Username: uinfo.user,
Password: uinfo.pass,
Database: uinfo.db,
}
return DialWithInfo(&info)
}
// 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 time.Duration
// Database is the database name used during the initial authentication.
// If set, the value is also returned as the default result from the
// Session.DB method, in place of "test".
Database string
// Username and Password inform the credentials for the initial
// authentication done against Database, if that is set,
// or the "admin" database otherwise. See the Session.Login method too.
Username string
Password string
// Dial optionally specifies the dial function for creating connections.
// At the moment addr will have type *net.TCPAddr, but other types may
// be provided in the future, so check and fail if necessary.
Dial func(addr net.Addr) (net.Conn, error)
}
// 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
}
cluster := newCluster(addrs, info.Direct, info.Dial)
session := newSession(Eventual, cluster, info.Timeout)
session.defaultdb = info.Database
if session.defaultdb == "" {
session.defaultdb = "test"
}
if info.Username != "" {
db := info.Database
if db == "" {
db = "admin"
}
session.dialAuth = &authInfo{db, info.Username, info.Password}
session.auth = []authInfo{*session.dialAuth}
}
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 parseURL(url string) (*urlInfo, error) {
if strings.HasPrefix(url, "mongodb://") {
url = url[10:]
}
info := &urlInfo{options: make(map[string]string)}
if c := strings.Index(url, "?"); c != -1 {
for _, pair := range strings.FieldsFunc(url[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]
}
url = url[:c]
}
if c := strings.Index(url, "@"); c != -1 {
pair := strings.SplitN(url[:c], ":", 2)
if len(pair) != 2 || pair[0] == "" {
return nil, errors.New("Credentials must be provided as user:pass@host")
}
info.user = pair[0]
info.pass = pair[1]
url = url[c+1:]
}
if c := strings.Index(url, "/"); c != -1 {
info.db = url[c+1:]
url = url[:c]
}
info.addrs = strings.Split(url, ",")
return info, nil
}
func newSession(consistency mode, cluster *mongoCluster, syncTimeout time.Duration) (session *Session) {
cluster.Acquire()
session = &Session{cluster_: cluster, syncTimeout: syncTimeout}
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, keepAuth bool) (s *Session) {
cluster := session.cluster()
cluster.Acquire()
if session.masterSocket != nil {
session.masterSocket.Acquire()
}
if session.slaveSocket != nil {
session.slaveSocket.Acquire()
}
var auth []authInfo
if keepAuth {
auth = make([]authInfo, len(session.auth))
copy(auth, session.auth)
} else if session.dialAuth != nil {
auth = []authInfo{*session.dialAuth}
}
scopy := *session
scopy.m = sync.RWMutex{}
scopy.auth = auth
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 against the 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 against 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 {
if name, ok := cmd.(string); ok {
cmd = bson.D{{name, 1}}
}
return db.C("$cmd").Find(cmd).One(result)
}
// Login authenticates against MongoDB with the provided credentials. 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.
//
// Concurrent Login calls will work correctly.
func (db *Database) Login(user, pass string) (err error) {
session := db.Session
dbname := db.Name
socket, err := session.acquireSocket(false)
if err != nil {
return err
}
defer socket.Release()
err = socket.Login(dbname, user, pass)
if err != nil {
return err
}
session.m.Lock()
defer session.m.Unlock()
for _, a := range session.auth {
if a.db == dbname {
a.user = user
a.pass = pass
return nil
}
}
session.auth = append(session.auth, authInfo{dbname, user, pass})
return nil
}
func (s *Session) socketLogin(socket *mongoSocket) error {
for _, a := range s.auth {
if err := socket.Login(a.db, a.user, a.pass); 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, a := range session.auth {
if a.db == dbname {
copy(session.auth[i:], session.auth[i+1:])
session.auth = session.auth[:len(session.auth)-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 _, a := range s.auth {
if s.masterSocket != nil {
s.masterSocket.Logout(a.db)
}
if s.slaveSocket != nil {
s.slaveSocket.Logout(a.db)
}
}
s.auth = s.auth[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"`
// 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.
UserSource string `bson:"userSource,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"`
}
type Role string
const (
// Relevant documentation:
//
// http://docs.mongodb.org/manual/reference/user-privileges/
//
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 != "" {
psum := md5.New()
psum.Write([]byte(user.Username + ":mongo:" + user.Password))
user.PasswordHash = hex.EncodeToString(psum.Sum(nil))
user.Password = ""
}
if user.PasswordHash != "" && user.UserSource != "" {
return fmt.Errorf("user has both Password/PasswordHash and UserSource set")
}
if len(user.OtherDBRoles) > 0 && db.Name != "admin" {
return fmt.Errorf("user with OtherDBRoles is only supported in admin database")
}
var unset bson.D
if user.PasswordHash == "" {
unset = append(unset, bson.DocElem{"pwd", 1})
}
if user.UserSource == "" {
unset = append(unset, bson.DocElem{"userSource", 1})
}
// user.Roles is always sent, as it's the way MongoDB distinguishes
// old-style documents from new-style documents.
if len(user.OtherDBRoles) == 0 {
unset = append(unset, bson.DocElem{"otherDBRoles", 1})
}
c := db.C("system.users")
_, err := c.Upsert(bson.D{{"user", user.Username}}, bson.D{{"$unset", unset}, {"$set", user}})
return err
}
// AddUser creates or updates the authentication credentials of user within
// the db database.
//
// 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(user, pass string, readOnly bool) error {
psum := md5.New()
psum.Write([]byte(user + ":mongo:" + pass))
digest := hex.EncodeToString(psum.Sum(nil))
c := db.C("system.users")
_, err := c.Upsert(bson.M{"user": user}, bson.M{"$set": bson.M{"user": user, "pwd": digest, "readOnly": readOnly}})
return err
}
// RemoveUser removes the authentication credentials of user from the database.
func (db *Database) RemoveUser(user string) error {
c := db.C("system.users")
return c.Remove(bson.M{"user": user})
}
type indexSpec struct {
Name, NS string
Key bson.D
Unique bool ",omitempty"
DropDups bool "dropDups,omitempty"
Background bool ",omitempty"
Sparse bool ",omitempty"
Bits, Min, Max int ",omitempty"
ExpireAfter int "expireAfterSeconds,omitempty"
}
type Index struct {
Key []string // Index key fields; prefix name with dash (-) for descending order
Unique bool // Prevent two documents from having the same index key
DropDups bool // Drop documents with the same index key as a previously indexed one
Background bool // Build index in background and return immediately
Sparse bool // Only index documents containing the Key fields
ExpireAfter time.Duration // Periodically delete docs with indexed time.Time older than that.
Name string // Index name, computed by EnsureIndex
Bits, Min, Max int // Properties for spatial indexes
}
func parseIndexKey(key []string) (name string, realKey bson.D, err error) {
var order interface{}
for _, field := range key {
raw := field
if name != "" {
name += "_"
}
var kind string
if field != "" {
if field[0] == '$' {
if c := strings.Index(field, ":"); c > 1 && c < len(field)-1 {
kind = field[1:c]
field = field[c+1:]
}
}
switch field[0] {
case '$':
// Logic above failed. Reset and error.
field = ""
case '@':
order = "2d"
field = field[1:]
name += field + "_" // Why don't they put 2d here?
case '-':
order = -1
field = field[1:]
name += field + "_-1"
case '+':
field = field[1:]
fallthrough
default:
if kind == "" {
order = 1
name += field + "_1"
} else {
order = kind
name += field + "_" // Seems wrong. What about the kind?
}
}
}
if field == "" || kind != "" && order != kind {
return "", nil, fmt.Errorf(`Invalid index key: want "[$<kind>:][-]<field name>", got %q`, raw)
}
realKey = append(realKey, bson.DocElem{field, order})
}
if name == "" {
return "", nil, errors.New("Invalid index key: no fields provided")
}
return
}
// EnsureIndexKey ensures an index with the given key exists, creating it
// if necessary.
//
// This example:
//
// err := collection.EnsureIndexKey("a", "b")
//
// Is equivalent to:
//
// err := collection.EnsureIndex(mgo.Index{Key: []string{"a", "b"}})
//
// See the EnsureIndex method for more details.
func (c *Collection) EnsureIndexKey(key ...string) error {
return c.EnsureIndex(Index{Key: key})
}
// EnsureIndex ensures an index with the given key exists, creating it with
// the provided parameters if necessary.
//
// Once EnsureIndex returns successfully, following requests for the same index
// will not contact the server unless Collection.DropIndex is used to drop the
// same index, or Session.ResetIndexCache is called.
//
// For example:
//
// index := Index{
// Key: []string{"lastname", "firstname"},
// Unique: true,
// DropDups: true,
// Background: true, // See notes.
// Sparse: true,
// }
// err := collection.EnsureIndex(index)
//
// The Key value determines which fields compose the index. The index ordering
// will be ascending by default. To obtain an index with a descending order,
// the field name should be prefixed by a dash (e.g. []string{"-time"}).
//
// If Unique is true, the index must necessarily contain only a single
// document per Key. With DropDups set to true, documents with the same key
// as a previously indexed one will be dropped rather than an error returned.
//
// If Background is true, other connections will be allowed to proceed using
// the collection without the index while it's being built. Note that the
// session executing EnsureIndex will be blocked for as long as it takes for
// the index to be built.
//
// If Sparse is true, only documents containing the provided Key fields will be
// included in the index. When using a sparse index for sorting, only indexed
// documents will be returned.
//
// If ExpireAfter is non-zero, the server will periodically scan the collection
// and remove documents containing an indexed time.Time field with a value
// older than ExpireAfter. See the documentation for details:
//
// http://docs.mongodb.org/manual/tutorial/expire-data
//
// Other kinds of indexes are also supported through that API. Here is an example:
//
// index := Index{
// Key: []string{"$2d:loc"},
// Bits: 26,
// }
// err := collection.EnsureIndex(index)
//
// The example above requests the creation of a "2d" index for the "loc" field.
//
// The 2D index bounds may be changed using the Min and Max attributes of the
// Index value. The default bound setting of (-180, 180) is suitable for
// latitude/longitude pairs.
//
// The Bits parameter sets the precision of the 2D geohash values. If not
// provided, 26 bits are used, which is roughly equivalent to 1 foot of
// precision for the default (-180, 180) index bounds.
//
// Relevant documentation:
//
// http://www.mongodb.org/display/DOCS/Indexes
// http://www.mongodb.org/display/DOCS/Indexing+Advice+and+FAQ
// http://www.mongodb.org/display/DOCS/Indexing+as+a+Background+Operation
// http://www.mongodb.org/display/DOCS/Geospatial+Indexing
// http://www.mongodb.org/display/DOCS/Multikeys
//
func (c *Collection) EnsureIndex(index Index) error {
name, realKey, err := parseIndexKey(index.Key)
if err != nil {
return err
}
session := c.Database.Session
cacheKey := c.FullName + "\x00" + name
if session.cluster().HasCachedIndex(cacheKey) {
return nil
}
spec := indexSpec{
Name: name,
NS: c.FullName,
Key: realKey,
Unique: index.Unique,
DropDups: index.DropDups,
Background: index.Background,
Sparse: index.Sparse,
Bits: index.Bits,
Min: index.Min,
Max: index.Max,
ExpireAfter: int(index.ExpireAfter / time.Second),
}
session = session.Clone()
defer session.Close()
session.SetMode(Strong, false)
session.EnsureSafe(&Safe{})
db := c.Database.With(session)
err = db.C("system.indexes").Insert(&spec)
if err == nil {
session.cluster().CacheIndex(cacheKey, true)
}
session.Close()
return err
}
// DropIndex removes the index with key from the collection.
//
// The key value determines which fields compose the index. The index ordering
// will be ascending by default. To obtain an index with a descending order,
// the field name should be prefixed by a dash (e.g. []string{"-time"}).
//
// For example:
//
// err := collection.DropIndex("lastname", "firstname")
//
// See the EnsureIndex method for more details on indexes.
func (c *Collection) DropIndex(key ...string) error {
name, _, err := parseIndexKey(key)
if err != nil {
return err
}
session := c.Database.Session
cacheKey := c.FullName + "\x00" + name
session.cluster().CacheIndex(cacheKey, false)
session = session.Clone()
defer session.Close()
session.SetMode(Strong, false)
db := c.Database.With(session)
result := struct {
ErrMsg string
Ok bool
}{}
err = db.Run(bson.D{{"dropIndexes", c.Name}, {"index", name}}, &result)
if err != nil {
return err
}
if !result.Ok {
return errors.New(result.ErrMsg)
}
return nil
}
// Indexes returns a list of all indexes for the collection.
//
// For example, this snippet would drop all available indexes:
//
// indexes, err := collection.Indexes()
// if err != nil {
// return err
// }
// for _, index := range indexes {
// err = collection.DropIndex(index.Key...)
// if err != nil {
// return err
// }
// }
//
// See the EnsureIndex method for more details on indexes.
func (c *Collection) Indexes() (indexes []Index, err error) {
query := c.Database.C("system.indexes").Find(bson.M{"ns": c.FullName})
iter := query.Sort("name").Iter()
for {
var spec indexSpec
if !iter.Next(&spec) {
break
}
index := Index{
Name: spec.Name,
Key: simpleIndexKey(spec.Key),
Unique: spec.Unique,
DropDups: spec.DropDups,
Background: spec.Background,
Sparse: spec.Sparse,
ExpireAfter: time.Duration(spec.ExpireAfter) * time.Second,
}
indexes = append(indexes, index)
}
err = iter.Close()
return
}
func simpleIndexKey(realKey bson.D) (key []string) {
for i := range realKey {
field := realKey[i].Name
i, _ := realKey[i].Value.(int)
if i == 1 {
key = append(key, field)
continue
}
if i == -1 {
key = append(key, "-"+field)
continue
}
if s, ok := realKey[i].Value.(string); ok {
key = append(key, "$"+s+":"+field)
continue
}
panic("Got unknown index key type for field " + field)
}
return
}
// ResetIndexCache() clears the cache of previously ensured indexes.
// Following requests to EnsureIndex will contact the server.
func (s *Session) ResetIndexCache() {
s.cluster().ResetIndexCache()
}
// New creates a new session with the same parameters as the original
// session, including consistency, batch size, prefetching, safety mode,
// etc. The returned session will use sockets from the poll, so there's
// a chance that writes just performed in another session may not yet
// be visible.
//
// Login information from the original session will not be copied over
// into the new session unless it was provided through the initial URL
// for the Dial function.
//
// See the Copy and Clone methods.
//
func (s *Session) New() *Session {
s.m.Lock()
scopy := copySession(s, false)
s.m.Unlock()
scopy.Refresh()
return scopy
}
// Copy works just like New, but preserves the exact authentication
// information from the original session.
func (s *Session) Copy() *Session {
s.m.Lock()
scopy := copySession(s, true)
s.m.Unlock()
scopy.Refresh()
return scopy
}
// Clone works just like Copy, but also reuses the same socket as the original