forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongodb.go
63 lines (51 loc) · 1.48 KB
/
mongodb.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
package mongodb
import (
"fmt"
"net/url"
"strings"
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/metricbeat/mb/parse"
mgo "gopkg.in/mgo.v2"
)
func init() {
// Register the ModuleFactory function for the "mongodb" module.
if err := mb.Registry.AddModule("mongodb", 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
}
func ParseURL(module mb.Module, host string) (mb.HostData, error) {
c := struct {
Username string `config:"username"`
Password string `config:"password"`
}{}
if err := module.UnpackConfig(&c); err != nil {
return mb.HostData{}, err
}
if parts := strings.SplitN(host, "://", 2); len(parts) != 2 {
// Add scheme.
host = fmt.Sprintf("mongodb://%s", host)
}
// This doesn't use URLHostParserBuilder because MongoDB URLs can contain
// multiple hosts separated by commas (mongodb://host1,host2,host3?options).
u, err := url.Parse(host)
if err != nil {
return mb.HostData{}, fmt.Errorf("error parsing URL: %v", err)
}
parse.SetURLUser(u, c.Username, c.Password)
// https://docs.mongodb.com/manual/reference/connection-string/
_, err = mgo.ParseURL(u.String())
if err != nil {
return mb.HostData{}, err
}
return parse.NewHostDataFromURL(u), nil
}