-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
128 lines (115 loc) · 2.43 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
package main
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"github.com/robfig/cron"
"io/ioutil"
"log"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
type Config struct {
IsCron bool `json:"isCron"` //need in a task
CronSpec string `json:"cronSpec"` //task spec
DBs []DB `json:"configs"`
}
type DB struct {
Host string `json:"host"` //db host
User string `json:"user"` //db user
Pwd string `json:"pwd"` //db password
Db string `json:"db"` //database
Out string `json:"out"` //output file directory
}
func (c *Config) ReadConfig() error {
data, err := ioutil.ReadFile("conf.json")
if err != nil {
return errors.Wrap(err, "read config error")
}
err = json.Unmarshal(data, c)
if err != nil {
return errors.Wrap(err, "unable to unmarshal config")
}
return nil
}
func dirExists(path string) (bool, error) {
var err error
_, err = os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func (c *Config) Dump() error {
binOk, err := dirExists("./bin")
if err != nil {
return errors.Wrap(err, "unable to find mongodb bin")
}
if !binOk {
return errors.New("unable to find mongodb bin, please put in 'mongodb/bin'")
}
cmdStr := ""
goos := runtime.GOOS
switch goos {
case "windows":
cmdStr = ".\\bin\\mongodump"
case "linux":
cmdStr = "./bin/mongodump"
}
for _, v := range c.DBs {
od := v.Out
od = outputPattern(od)
cmd := exec.Command(cmdStr, "-h", v.Host, "-u", v.User, "-p", v.Pwd, "--authenticationDatabase", v.Db, "-d", v.Db, "-o", od)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return errors.Wrap(err, "command error")
}
log.Printf("Host: %s DB: %s is complete\n", v.Host, v.Db)
}
return nil
}
func outputPattern(out string) string {
if strings.Index(out, "${date}") > -1 {
out = strings.Replace(out, "${date}", time.Now().Format("20060102"), -1)
}
return out
}
func (c *Config) Task() {
cr := cron.New()
cr.AddFunc(c.CronSpec, func() {
err := c.Dump()
if err != nil {
log.Println("Dump error:", err)
}
})
cr.Start()
}
func main() {
var err error
conf := &Config{}
err = conf.ReadConfig()
if err != nil {
log.Panicln("Read config error:", err)
}
if !conf.IsCron {
//run once
err = conf.Dump()
if err != nil {
log.Panicln("Dump error:", err)
}
} else {
//task
go conf.Task()
select {}
}
}