/
client.go
114 lines (98 loc) · 2.46 KB
/
client.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
package main
import (
"github.com/robertkrimen/otto"
"github.com/sfreiberg/facts"
"flag"
"fmt"
"io/ioutil"
"os"
"path"
"time"
)
var (
// This is a global javascript interpreter.
// TODO: Remove this global interpreter because we might want multiples running
js *otto.Otto
// Number of minutes between runs
runInterval int
// Path to the main shepherd directory which should contain a file named
// shepherd.js.
shepherdPath string
// The current working directory. Used to keep track of which parent
// directory to use. For example when inside a module we want to work
// from that modules directory.
cwd string
)
func initJavascript() {
js = otto.New()
f := facts.FindFacts()
// TODO: log error
factsAsJson, err := f.ToJson()
if err == nil {
js.Object(`facts = ` + string(factsAsJson))
}
// Create javascript functions
js.Set("directory", directory)
js.Set("symlink", symlink)
js.Set("template", template)
js.Set("apt", apt)
js.Set("yum", yum)
js.Set("command", command)
js.Set("user", user)
js.Set("pg_user", pgUser)
js.Set("pg_database", pgDatabase)
js.Set("mysql_user", mysqlUser)
js.Set("mysql_database", mysqlDatabase)
js.Set("sleep", sleep)
js.Set("upstart", upstart)
js.Set("file", file)
js.Set("include", include)
}
func RunClient() {
flagSet := flag.NewFlagSet("client", flag.ExitOnError)
flagSet.StringVar(&shepherdPath, "dir", "/etc/shepherd", "Location of shepherd configs")
flagSet.IntVar(&runInterval, "interval", 30, "Number of minutes between runs")
if err := flagSet.Parse(os.Args[2:]); err != nil {
// TODO: Log this before panic and ideally don't panic
panic(err)
}
cwd = shepherdPath
for {
go executeMainJS()
time.Sleep(time.Duration(runInterval) * time.Minute)
}
}
func RunStandalone() {
jsFiles := os.Args[1:]
if len(jsFiles) == 0 {
fmt.Println("You must provide at least one javascript file.")
return
}
// Read and execute javascript
executeJSFiles(jsFiles)
}
func executeMainJS() {
jsFile := path.Join(shepherdPath, "shepherd.js")
jsFiles := []string{jsFile}
fmt.Println(jsFiles)
executeJSFiles(jsFiles)
}
func executeJSFiles(jsFiles []string) {
initJavascript()
for _, f := range jsFiles {
executeJSFile(f)
}
fmt.Println("\nFinished.")
}
func executeJSFile(file string) {
fmt.Printf("Executing %v...\n", file)
b, err := ioutil.ReadFile(file)
if err != nil {
panic(err.Error())
}
_, err = js.Run(string(b))
if err != nil {
fmt.Println("Error executing: ", file)
fmt.Println(err)
}
}