forked from premendrasingh/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
91 lines (77 loc) · 2.21 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
/*
Package mysql is Metricbeat module for MySQL server.
*/
package mysql
import (
"database/sql"
"github.com/elastic/beats/metricbeat/mb"
"github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
)
func init() {
// Register the ModuleFactory function for the "mysql" module.
if err := mb.Registry.AddModule("mysql", NewModule); err != nil {
panic(err)
}
}
func NewModule(base mb.BaseModule) (mb.Module, error) {
// Validate that at least one host has been specified.
config := struct {
Hosts []string `config:"hosts" validate:"nonzero,required"`
}{}
if err := base.UnpackConfig(&config); err != nil {
return nil, err
}
return &base, nil
}
// ParseDSN creates a DSN (data source name) string by parsing the host.
// It validates the resulting DSN and returns an error if the DSN is invalid.
//
// Format: [username[:password]@][protocol[(address)]]/
// Example: root:test@tcp(127.0.0.1:3306)/
func ParseDSN(mod mb.Module, host string) (mb.HostData, error) {
c := struct {
Username string `config:"username"`
Password string `config:"password"`
}{}
if err := mod.UnpackConfig(&c); err != nil {
return mb.HostData{}, err
}
config, err := mysql.ParseDSN(host)
if err != nil {
return mb.HostData{}, errors.Wrapf(err, "error parsing mysql host")
}
if config.User == "" {
config.User = c.Username
}
if config.Passwd == "" {
config.Passwd = c.Password
}
// Add connection timeouts to the DSN.
if timeout := mod.Config().Timeout; timeout > 0 {
config.Timeout = timeout
config.ReadTimeout = timeout
config.WriteTimeout = timeout
}
noCredentialsConfig := *config
noCredentialsConfig.User = ""
noCredentialsConfig.Passwd = ""
return mb.HostData{
URI: config.FormatDSN(),
SanitizedURI: noCredentialsConfig.FormatDSN(),
Host: config.Addr,
User: config.User,
Password: config.Passwd,
}, nil
}
// NewDB returns a new mysql database handle. The dsn value (data source name)
// must be valid, otherwise an error will be returned.
//
// DSN Format: [username[:password]@][protocol[(address)]]/
func NewDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, errors.Wrap(err, "sql open failed")
}
return db, nil
}