-
Notifications
You must be signed in to change notification settings - Fork 138
/
mongo.go
207 lines (179 loc) · 5.59 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
201
202
203
204
205
206
207
// Copyright 2018 Globo.com authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package db
import (
"fmt"
"time"
"github.com/globocom/huskyCI/api/log"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Conn is the MongoDB connection variable.
var Conn *DB
// Collections names used in MongoDB.
var (
RepositoryCollection = "repository"
SecurityTestCollection = "securityTest"
AnalysisCollection = "analysis"
UserCollection = "user"
AccessTokenCollection = "accessToken"
DockerAPIAddressesCollection = "dockerAPIAddresses"
)
// DB is the struct that represents mongo session.
type DB struct {
Session *mgo.Session
}
const logActionConnect = "Connect"
const logActionReconnect = "autoReconnect"
const logInfoMongo = "DB"
// Database is the interface's database.
type Database interface {
Insert(obj interface{}, collection string) error
Search(query bson.M, selectors []string, collection string, obj interface{}) error
Update(query bson.M, updateQuery interface{}, collection string) error
UpdateAll(query, updateQuery bson.M, collection string) error
FindAndModify(findQuery, updateQuery interface{}, collection string, obj interface{}) error
Upsert(query bson.M, obj interface{}, collection string) (*mgo.ChangeInfo, error)
SearchOne(query bson.M, selectors []string, collection string, obj interface{}) error
}
// Connect connects to mongo and returns the session.
func Connect(address, dbName, username, password string, poolLimit, port int, timeout time.Duration) error {
log.Info(logActionConnect, logInfoMongo, 21)
dbAddress := fmt.Sprintf("%s:%d", address, port)
dialInfo := &mgo.DialInfo{
Addrs: []string{dbAddress},
Timeout: timeout,
FailFast: true,
Database: dbName,
Username: username,
Password: password,
PoolLimit: poolLimit,
}
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
log.Error(logActionConnect, logInfoMongo, 2001, err)
return err
}
session.SetSafe(&mgo.Safe{WMode: "majority"})
if err := session.Ping(); err != nil {
log.Error(logActionConnect, logInfoMongo, 2002, err)
return err
}
Conn = &DB{Session: session}
go autoReconnect()
return nil
}
// autoReconnect checks mongo's connection each second and, if an error is found, reconect to it.
func autoReconnect() {
log.Info(logActionReconnect, logInfoMongo, 22)
var err error
for {
err = Conn.Session.Ping()
if err != nil {
log.Error(logActionReconnect, logInfoMongo, 2003, err)
Conn.Session.Refresh()
err = Conn.Session.Ping()
if err == nil {
log.Info(logActionReconnect, logInfoMongo, 23)
} else {
log.Error(logActionReconnect, logInfoMongo, 2004, err)
}
}
time.Sleep(time.Second * 1)
}
}
// Insert inserts a new document.
func (db *DB) Insert(obj interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB("").C(collection)
defer session.Close()
return c.Insert(obj)
}
// Update updates a single document.
func (db *DB) Update(query, updateQuery interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB("").C(collection)
defer session.Close()
err := c.Update(query, updateQuery)
return err
}
// UpdateAll updates all documents that match the query.
func (db *DB) UpdateAll(query, updateQuery interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB("").C(collection)
defer session.Close()
_, err := c.UpdateAll(query, updateQuery)
return err
}
func (db *DB) FindAndModify(findQuery, updateQuery interface{}, collection string, obj interface{}) error {
session := db.Session.Clone()
col := session.DB("").C(collection)
defer session.Close()
change := mgo.Change{
Update: updateQuery,
Upsert: false,
Remove: false,
ReturnNew: false,
}
_, err := col.Find(findQuery).Apply(change, obj)
return err
}
// Search searchs all documents that match the query. If selectors are present, the return will be only the chosen fields.
func (db *DB) Search(query bson.M, selectors []string, collection string, obj interface{}) error {
session := db.Session.Clone()
defer session.Close()
c := session.DB("").C(collection)
var err error
if selectors != nil {
selector := bson.M{}
for _, v := range selectors {
selector[v] = 1
}
err = c.Find(query).Select(selector).All(obj)
} else {
err = c.Find(query).All(obj)
}
if err == nil && obj == nil {
err = mgo.ErrNotFound
}
return err
}
// Aggregation prepares a pipeline to aggregate.
func (db *DB) Aggregation(aggregation []bson.M, collection string) (interface{}, error) {
session := db.Session.Clone()
defer session.Close()
c := session.DB("").C(collection)
pipe := c.Pipe(aggregation)
resp := []bson.M{}
iter := pipe.Iter()
err := iter.All(&resp)
return resp, err
}
// SearchOne searchs for the first element that matchs with the given query.
func (db *DB) SearchOne(query bson.M, selectors []string, collection string, obj interface{}) error {
session := db.Session.Clone()
defer session.Close()
c := session.DB("").C(collection)
var err error
if selectors != nil {
selector := bson.M{}
for _, v := range selectors {
selector[v] = 1
}
err = c.Find(query).Select(selector).One(obj)
} else {
err = c.Find(query).One(obj)
}
if err == nil && obj == nil {
err = mgo.ErrNotFound
}
return err
}
// Upsert inserts a document or update it if it already exists.
func (db *DB) Upsert(query bson.M, obj interface{}, collection string) (*mgo.ChangeInfo, error) {
session := db.Session.Clone()
c := session.DB("").C(collection)
defer session.Close()
return c.Upsert(query, obj)
}