-
Notifications
You must be signed in to change notification settings - Fork 9
/
mysql.go
397 lines (367 loc) · 14.5 KB
/
mysql.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
package main
import (
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
gometrics "github.com/rcrowley/go-metrics"
)
var (
counterDbWriteFailures = gometrics.NewCounter()
counterDbWriteSuccesses = gometrics.NewCounter()
counterDbReadFailures = gometrics.NewCounter()
counterDbReadSuccesses = gometrics.NewCounter()
errBadMYSQLWhereClause = errors.New("Query too broad, no correctly configured filters for WHERE clause found")
)
type SQLDB struct {
db *sql.DB
// store allowable fields and type for each field
messageFields map[string]string
}
func NewSQLDB(config *Config, logger *Logger, metricsRegistry *gometrics.Registry) *SQLDB {
// Capture connection properties.
cfg := mysql.NewConfig()
cfg.User = config.MySQLUser
cfg.Passwd = config.MySQLPassword
cfg.Net = "tcp"
cfg.Addr = config.MySQLAddress
cfg.DBName = config.MySQLDBName
cfg.ParseTime = true
cfg.AllowNativePasswords = true
cfg.CheckConnLiveness = true
cfg.RejectReadOnly = true
cfg.Timeout = config.MySQLConnTimeout * time.Second
cfg.ReadTimeout = config.MySQLReadTimeout * time.Second
cfg.WriteTimeout = config.MySQLWriteTimeout * time.Second
// Get a database handle.
db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
logger.Errorf("Failed to get db handle with error: %w", err)
}
db.SetMaxOpenConns(config.MySQLMaxOpenConns)
db.SetMaxIdleConns(config.MySQLMaxIdleConns)
db.SetConnMaxLifetime(config.MySQLMaxConnLifeTime * time.Second)
db.SetConnMaxIdleTime(config.MySQLMaxConnIdleTime * time.Second)
sqlDB := SQLDB{
db: db,
// store types as strings so they can be compared in an simple if statement instead of type switch, these are not directly compared to or used as actual types just to map what params can use what filters
messageFields: map[string]string{
"id": "string",
"batch": "string",
"sent": "time.Time",
"application": "string",
"target": "string",
"destination": "string",
"mode": "string",
"plan": "string",
"body": "string",
"priority": "string",
"subject": "string",
"incident_id": "uint64",
},
}
if config.MetricsDryRun == false && metricsRegistry != nil {
sqlDB.registerMetrics(*metricsRegistry)
}
return &sqlDB
}
func (s *SQLDB) registerMetrics(reg gometrics.Registry) {
reg.Register("mysql.internal.db_write_failures_total", counterDbWriteFailures)
reg.Register("mysql.internal.db_write_successes_total", counterDbWriteSuccesses)
reg.Register("mysql.internal.db_read_failures_total", counterDbReadFailures)
reg.Register("mysql.internal.db_read_successes_total", counterDbReadSuccesses)
}
func (s *SQLDB) buildWhereClause(queryParams map[string]interface{}, fieldTypeMap map[string]string) (values []interface{}, where []string, err error) {
if len(queryParams) == 0 {
return values, where, errBadMYSQLWhereClause
}
for paramName, paramVal := range queryParams {
// query filters are delineated with __ split to get param and filter
paramSplit := strings.Split(paramName, "__")
// check if param corresponds to an allowed message field
if typeString, ok := fieldTypeMap[paramSplit[0]]; ok {
// no query filter specified, default to '=='(eq)
if len(paramSplit) == 1 {
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s = ?", paramSplit[0]))
case string:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s = ?", paramSplit[0]))
}
} else {
switch filter := paramSplit[1]; filter {
case "eq":
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s = ?", paramSplit[0]))
case string:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s = ?", paramSplit[0]))
}
case "ne":
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s != ?", paramSplit[0]))
case string:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s != ?", paramSplit[0]))
}
case "in":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString != "time.Time" {
switch paramVal.(type) {
case []uint64:
for _, listVal := range paramVal.([]uint64) {
values = append(values, listVal)
}
clause := paramSplit[0] + ` in (?` + strings.Repeat(",?", len(paramVal.([]uint64))-1) + `)`
where = append(where, clause)
case []string:
for _, listVal := range paramVal.([]string) {
values = append(values, listVal)
}
clause := paramSplit[0] + ` in (?` + strings.Repeat(",?", len(paramVal.([]string))-1) + `)`
where = append(where, clause)
}
}
case "gt":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "uint64" || typeString == "time.Time" {
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s > ?", paramSplit[0]))
case time.Time:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s > ?", paramSplit[0]))
}
}
case "ge":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "uint64" || typeString == "time.Time" {
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s >= ?", paramSplit[0]))
case time.Time:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s >= ?", paramSplit[0]))
}
}
case "lt":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "uint64" || typeString == "time.Time" {
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s < ?", paramSplit[0]))
case time.Time:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s < ?", paramSplit[0]))
}
}
case "le":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "uint64" || typeString == "time.Time" {
switch paramVal.(type) {
case uint64:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s <= ?", paramSplit[0]))
case time.Time:
values = append(values, paramVal)
where = append(where, fmt.Sprintf("%s <= ?", paramSplit[0]))
}
}
case "contains":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "string" {
switch paramVal.(type) {
case string:
values = append(values, "%"+paramVal.(string)+"%")
where = append(where, fmt.Sprintf("%s LIKE ?", paramSplit[0]))
}
}
case "startswith":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "string" {
switch paramVal.(type) {
case string:
values = append(values, paramVal.(string)+"%")
where = append(where, fmt.Sprintf("%s LIKE ?", paramSplit[0]))
}
}
case "endswith":
// verify that field is of correct type for this operation and that value is of same type as field
if typeString == "string" {
switch paramVal.(type) {
case string:
values = append(values, "%"+paramVal.(string))
where = append(where, fmt.Sprintf("%s LIKE ?", paramSplit[0]))
}
}
}
}
}
}
// there were no correctly configured filters
if len(where) == 0 {
return values, where, errBadMYSQLWhereClause
}
return values, where, nil
}
// select message with filters
func (s *SQLDB) SelectMessages(queryParams map[string]interface{}) ([]MessageRecord, error) {
// parse query params and build query
messages := make([]MessageRecord, 0)
values, where, err := s.buildWhereClause(queryParams, s.messageFields)
if err != nil {
return nil, err
}
// add limit if one is specified
limitStr := ""
if limit, ok := queryParams["limit"]; ok {
limitStr = " LIMIT " + strconv.Itoa(limit.(int))
}
rows, err := s.db.Query("SELECT `id`, `batch`, `sent`, `application`, `target`, `destination`, `mode`, `priority`, `plan`, `subject`, `body`, `incident_id`, `step` FROM message WHERE "+strings.Join(where, " AND ")+" ORDER BY sent DESC"+limitStr, values...)
if err != nil {
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve messages with error: %w", err)
}
defer rows.Close()
// Loop through rows, using Scan to assign column data to struct fields.
for rows.Next() {
var message MessageRecord
if err := rows.Scan(&message.MessageID, &message.Batch, &message.Sent, &message.Application, &message.Target, &message.Destination, &message.Mode, &message.Priority, &message.Plan, &message.Subject, &message.Body, &message.IncidentID, &message.PlanStep); err != nil {
if err == sql.ErrNoRows {
counterDbReadSuccesses.Inc(1)
return messages, nil
}
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve messages with error: %w", err)
}
message.SentTimestamp = message.Sent.Unix()
message.CreatedTimestamp = message.Sent.Unix()
message.Name = message.Target
messages = append(messages, message)
}
if err := rows.Err(); err != nil {
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve messages with error: %w", err)
}
counterDbReadSuccesses.Inc(1)
return messages, nil
}
// insert message
func (s *SQLDB) InsertMessage(msg MessageRecord) error {
_, err := s.db.Exec("INSERT INTO message (id, batch, sent, application, target, destination, mode, priority, plan, subject, body, incident_id, step) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
msg.MessageID, msg.Batch, msg.Sent, msg.Application, msg.Target, msg.Destination, msg.Mode, msg.Priority, msg.Plan, msg.Subject, msg.Body, msg.IncidentID, msg.PlanStep)
if err != nil {
counterDbWriteFailures.Inc(1)
return fmt.Errorf("Failed with error: %w", err)
}
counterDbWriteSuccesses.Inc(1)
return nil
}
// select message status
func (s *SQLDB) SelectMessageStatusByMsgID(msgID string) (MessageStatusRecord, error) {
var status MessageStatusRecord
row := s.db.QueryRow("SELECT `message_id`, `status`, `vendor_message_id`, `last_updated` FROM message_sent_status WHERE message_id = ? LIMIT 1", msgID)
if err := row.Scan(&status.MessageID, &status.Status, &status.VendorMessageIdentifier, &status.LastUpdated); err != nil {
if err == sql.ErrNoRows {
counterDbReadSuccesses.Inc(1)
return status, nil
}
counterDbReadFailures.Inc(1)
status.LastUpdatedTimestamp = status.LastUpdated.Unix()
return status, fmt.Errorf("Failed retrieving message status with error: %w", err)
}
counterDbReadSuccesses.Inc(1)
return status, nil
}
// select message status
func (s *SQLDB) SelectMessageStatusByVendorID(vendorMessageIdentifier string) (MessageStatusRecord, error) {
var status MessageStatusRecord
row := s.db.QueryRow("SELECT `message_id`, `status`, `vendor_message_id`, `last_updated` FROM message_sent_status WHERE vendor_message_id = ? LIMIT 1", vendorMessageIdentifier)
if err := row.Scan(&status.MessageID, &status.Status, &status.VendorMessageIdentifier, &status.LastUpdated); err != nil {
// it is possible for arbitrary vendorMessageIdentifier to not have rows
if err == sql.ErrNoRows {
counterDbReadSuccesses.Inc(1)
return status, nil
}
counterDbReadFailures.Inc(1)
status.LastUpdatedTimestamp = status.LastUpdated.Unix()
return status, fmt.Errorf("Failed retrieving message status with error: %w", err)
}
counterDbReadSuccesses.Inc(1)
return status, nil
}
// insert message status
func (s *SQLDB) InsertMessageStatus(status MessageStatusRecord) error {
_, err := s.db.Exec("INSERT INTO message_sent_status (message_id, status, vendor_message_id, last_updated) VALUES (?, ?, ?, ?)",
status.MessageID, status.Status, status.VendorMessageIdentifier, status.LastUpdated)
if err != nil {
counterDbWriteFailures.Inc(1)
return fmt.Errorf("Failed with error: %w", err)
}
counterDbWriteSuccesses.Inc(1)
return nil
}
// update message status
func (s *SQLDB) UpdateMessageStatus(status MessageStatusRecord) error {
_, err := s.db.Exec("UPDATE message_sent_status SET status = ?, last_updated = ? WHERE message_id = ?",
status.Status, status.LastUpdated, status.MessageID)
if err != nil {
counterDbWriteFailures.Inc(1)
return fmt.Errorf("Failed with error: %w", err)
}
counterDbWriteSuccesses.Inc(1)
return nil
}
// select message changelogs
func (s *SQLDB) SelectMessageChangelogs(msgID string) ([]MessageChangelogRecord, error) {
logs := make([]MessageChangelogRecord, 0)
rows, err := s.db.Query("SELECT `id`, `date`, `message_id`, `change_type`, `old`, `new`, `description` FROM message_changelog WHERE message_id = ? ORDER BY date DESC", msgID)
if err != nil {
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve msg changelogs with error: %w", err)
}
defer rows.Close()
// Loop through rows, using Scan to assign column data to struct fields.
for rows.Next() {
var changelog MessageChangelogRecord
if err := rows.Scan(&changelog.ChangelogID, &changelog.Date, &changelog.MessageID, &changelog.ChangeType, &changelog.Old, &changelog.New, &changelog.Description); err != nil {
if err == sql.ErrNoRows {
counterDbReadSuccesses.Inc(1)
return logs, nil
}
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve msg changelogs with error: %w", err)
}
changelog.DateTimestamp = changelog.Date.Unix()
logs = append(logs, changelog)
}
if err := rows.Err(); err != nil {
counterDbReadFailures.Inc(1)
return nil, fmt.Errorf("Failed to retrieve msg changelogs with error: %w", err)
}
counterDbReadSuccesses.Inc(1)
return logs, nil
}
// insert message changelog
func (s *SQLDB) InsertMessageChangelog(changelog MessageChangelogRecord) error {
_, err := s.db.Exec("INSERT INTO message_changelog (date, message_id, change_type, old, new, description) VALUES (?, ?, ?, ?, ?, ?)",
changelog.Date, changelog.MessageID, changelog.ChangeType, changelog.Old, changelog.New, changelog.Description)
if err != nil {
counterDbWriteFailures.Inc(1)
return fmt.Errorf("Failed with error: %w", err)
}
counterDbWriteSuccesses.Inc(1)
return nil
}