/
mongo.go
200 lines (169 loc) · 4.19 KB
/
mongo.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
package db
import (
"errors"
"log"
"strings"
"sync"
"sync/atomic"
"time"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var config *MongoConfig
var instances []*mgo.Session
var instanceOnce sync.Once
var instancesIndex uint32
const mgoMaxSessions = 8
type M bson.M
func (m M) Update(qs ...M) M {
for _, q := range qs {
for k, v := range q {
m[k] = v
}
}
return m
}
var ErrInitResource = errors.New("ezorm/db: failed to initial mongo resource")
var ErrOperaBeforeInit = errors.New("please set db.SetOnFinishInit when needed operating db in init()")
// non-multhreads
var afterEvents []func()
var indexEvents []func()
func EnsureAllIndex() {
for _, f := range indexEvents {
f()
}
}
func SetOnEnsureIndex(f func()) {
indexEvents = append(indexEvents, f)
}
func SetOnFinishInit(f func()) {
if IsFinishInit() {
f()
return
}
afterEvents = append(afterEvents, f)
}
func IsFinishInit() bool {
return instances != nil
}
func Setup(c *MongoConfig) {
config = c
}
func ShareSession() *mgo.Session {
doInit := false
instanceOnce.Do(func() {
instances = MustNewMgoSessions(config)
SetupIdleSessionRefresher(config, instances, 3*time.Minute)
})
if doInit {
for _, f := range afterEvents {
f()
}
}
i := atomic.AddUint32(&instancesIndex, 1)
i = i % uint32(len(instances))
// use Clone here to avoid socket refresh
return instances[int(i)].Clone()
}
// SetupIdleSessionRefresher will always refresh idle sessions if it is possible
func SetupIdleSessionRefresher(config *MongoConfig, instances []*mgo.Session, every time.Duration) {
go func() {
var cursor uint64
// NOTE: `instances` itself is read-only
instanceLen := uint64(len(instances))
for {
time.Sleep(every)
// Acquire one idle session ,and do refresh(re-dail)
// move the session instance cursor to next
idleSession := instances[int(cursor%instanceLen)]
// reset session socket , and the socket will be re-allocated in next mongo operation
idleSession.Refresh()
// Ping the server after refresh sockets, it will pre-allocate the socket
// if ping fails , the socket will not be pre-allocated
if err := idleSession.Ping(); err != nil {
log.Printf("sessionRefreher: %q", err)
}
// move to next instance
cursor++
}
}()
}
func MustNewMgoSessions(config *MongoConfig) []*mgo.Session {
maxSession := config.MaxSession
if maxSession == 0 {
maxSession = mgoMaxSessions
}
sessions := make([]*mgo.Session, maxSession)
for i := 0; i < mgoMaxSessions; i++ {
if config == nil {
log.Fatal(ErrOperaBeforeInit)
}
session, err := mgo.Dial(config.MongoDB)
if err != nil {
log.Println("failed to dial mongo:", err)
panic(ErrInitResource)
}
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
if err := session.Ping(); err != nil {
log.Println("failed to ping mongo:", err)
panic(ErrInitResource)
}
poolLimit := config.PoolLimit
if poolLimit <= 0 {
poolLimit = 16
}
session.SetPoolLimit(poolLimit)
sessions[i] = session
// Refresh session in case of network error.
go func(s *mgo.Session) {
for {
if err := s.Ping(); err != nil {
s.Refresh()
s.Ping()
}
time.Sleep(time.Second)
}
}(session)
}
return sessions
}
func InID(ids []string) (ret M) {
return M{"_id": M{"$in": ObjectIds(ids)}}
}
func In(ids []string) M {
return M{"$in": ObjectIds(ids)}
}
func ObjectIds(ids []string) (ret []bson.ObjectId) {
ret = make([]bson.ObjectId, 0, len(ids))
for _, id := range ids {
id = strings.TrimSpace(id)
if bson.IsObjectIdHex(id) {
ret = append(ret, bson.ObjectIdHex(id))
}
}
return
}
func NewSession() (session *mgo.Session) {
return ShareSession()
}
func NewCollection(session *mgo.Session, dbName, name string) *mgo.Collection {
if dbName == "" {
return session.DB(config.DBName).C(name)
}
return session.DB(dbName).C(name)
}
func GetCol(dbName, col string) (session *mgo.Session, collection *mgo.Collection) {
session = NewSession()
collection = NewCollection(session, dbName, col)
return
}
func NewObjectId() bson.ObjectId {
return bson.NewObjectId()
}
func IsMgoNotFound(err error) bool {
return err == mgo.ErrNotFound
}
func IsMgoDup(err error) bool {
return mgo.IsDup(err)
}