/
script.go
50 lines (41 loc) · 1.07 KB
/
script.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
package mongo
import (
"fmt"
"github.com/naveego/bosun/pkg/command"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"strings"
)
// ScriptCommand runs a database command: https://docs.mongodb.com/manual/reference/command/
type ScriptCommand struct {
Conn Connection
Script string
Log *logrus.Entry `json:"-"`
}
func (m ScriptCommand) Execute() error {
if m.Log == nil {
m.Log = logrus.WithField("cmd", "MongoImportCommand")
}
pc, err := m.Conn.Prepare(m.Log)
if err != nil {
return err
}
if pc.CleanUp != nil {
defer pc.CleanUp()
}
addr := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=%s",
pc.Credentials.Username,
pc.Credentials.Password,
pc.Host,
pc.Port,
pc.DBName,
pc.Credentials.AuthSource)
safeAddr := strings.Replace(addr, pc.Credentials.Password, "%PASSWORD", 1)
m.Log.Infof("Using connection string %s", safeAddr)
m.Log.Infof("Executing script:\n %s", m.Script)
err = command.NewShellExe("mongo", addr, "--eval", m.Script).RunE()
if err != nil {
return errors.Wrapf(err, "running script %s", m.Script)
}
return nil
}