-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
200 lines (168 loc) · 3.97 KB
/
main.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 main
import (
"context"
"database/sql"
"log"
"sync"
"time"
_ "github.com/go-sql-driver/mysql"
timod "github.com/thingsdb/go-timod"
"github.com/vmihailenco/msgpack"
)
var db *sql.DB = nil
var mux sync.Mutex
type confMySQL struct {
Dsn string `msgpack:"dsn"`
ConnMaxLifetime int64 `msgpack:"conn_max_lifetime"`
MaxOpenConn int `msgpack:"max_open_conn"`
MaxIdleConn int `msgpack:"max_idle_conn"`
MaxIdleTimeConn int64 `msgpack:"max_idle_time_conn"`
}
type reqMySQL struct {
AffectedRows *AffectedRows `msgpack:"affected_rows"`
GetDBStats bool `msgpack:"get_db_stats"`
InsertRows *InsertRows `msgpack:"insert_rows"`
QueryRows *QueryRows `msgpack:"query_rows"`
Timeout int `msgpack:"timeout"`
Transaction bool `msgpack:"transaction"`
}
func handleConf(config *confMySQL) {
mux.Lock()
defer mux.Unlock()
if db != nil {
db.Close()
}
var err error
db, err = sql.Open("mysql", config.Dsn)
if err != nil {
timod.WriteConfErr()
return
}
if config.MaxIdleTimeConn != 0 {
db.SetConnMaxLifetime(time.Minute * time.Duration(config.ConnMaxLifetime))
}
if config.MaxIdleTimeConn != 0 {
db.SetMaxOpenConns(config.MaxOpenConn)
}
if config.MaxIdleTimeConn != 0 {
db.SetMaxIdleConns(config.MaxIdleConn)
}
if config.MaxIdleTimeConn != 0 {
db.SetConnMaxIdleTime(time.Minute * time.Duration(config.MaxIdleTimeConn))
}
timod.WriteConfOk()
}
func onModuleReq(pkg *timod.Pkg) {
mux.Lock()
defer mux.Unlock()
if db == nil || db.Ping() != nil {
timod.WriteEx(
pkg.Pid,
timod.ExOperation,
"Error: MySQL is not connected; please check the module configuration")
return
}
var req reqMySQL
err := msgpack.Unmarshal(pkg.Data, &req)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
"Error: Failed to unpack MySQL request")
return
}
num := 0
var fn func(stmt *sql.Stmt, ctx context.Context) (interface{}, error)
var q *Query
if req.QueryRows != nil {
q = (*Query)(req.QueryRows)
fn = req.QueryRows.run
num++
}
if req.InsertRows != nil {
q = (*Query)(req.InsertRows)
fn = req.InsertRows.run
num++
}
if req.AffectedRows != nil {
q = (*Query)(req.AffectedRows)
fn = req.AffectedRows.run
num++
}
if req.GetDBStats {
if num == 0 {
ret := db.Stats()
timod.WriteResponse(pkg.Pid, ret)
return
}
num++
}
if num == 0 {
timod.WriteEx(
pkg.Pid,
timod.ExOperation,
"Error: MySQL requires either `query_rows`, `insert_rows`, `affected_rows`, or `get_db_stats`")
return
}
if num > 1 {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
"Error: MySQL requires either `query_rows`, `insert_rows`, `affected_rows`, or `get_db_stats, not more then one")
return
}
if req.Timeout == 0 {
req.Timeout = 10
}
ctx, cancelfunc := context.WithTimeout(context.Background(), time.Duration(req.Timeout)*time.Second)
defer cancelfunc()
var ret interface{}
if req.Transaction {
ret, err = q.handleTransaction(db, ctx, fn)
} else {
ret, err = q.handleQuery(db, ctx, fn)
}
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExOperation,
err.Error())
return
}
timod.WriteResponse(pkg.Pid, ret)
}
func handler(buf *timod.Buffer, quit chan bool) {
for {
select {
case pkg := <-buf.PkgCh:
switch timod.Proto(pkg.Tp) {
case timod.ProtoModuleConf:
var conf confMySQL
err := msgpack.Unmarshal(pkg.Data, &conf)
if err == nil {
handleConf(&conf)
} else {
log.Println("Error: Failed to unpack MySQL configuration")
timod.WriteConfErr()
}
case timod.ProtoModuleReq:
onModuleReq(pkg)
default:
log.Printf("Error: Unexpected package type: %d", pkg.Tp)
}
case err := <-buf.ErrCh:
// In case of an error you probably want to quit the module.
// ThingsDB will try to restart the module a few times if this
// happens.
log.Printf("Error: %s", err)
quit <- true
}
}
}
func main() {
// Starts the module
timod.StartModule("mysql", handler)
if db != nil {
db.Close()
}
}