/
main.go
310 lines (272 loc) · 6.73 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
* nomad-syncer
* Copyright (c) 2016 Yieldbot, Inc.
* For the full copyright and license information, please view the LICENSE.txt file.
*/
// nomad-syncer - An opinionated CLI for Nomad
package main
import (
"encoding/json"
"errors"
"flag"
"io/ioutil"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"github.com/yieldbot/gocli"
"github.com/yieldbot/nomad-syncer/client"
)
var (
cli gocli.Cli
nomadURL string
proxyURL string
nomadClient client.Client
usageFlag bool
versionFlag bool
versionExtFlag bool
prettyPrintFlag bool
nomadFlag string
proxyFlag string
dockerPullFlag bool
)
func init() {
// Init flags
flag.BoolVar(&usageFlag, "h", false, "Display usage")
flag.BoolVar(&usageFlag, "help", false, "Display usage")
flag.BoolVar(&versionFlag, "version", false, "Display version information")
flag.BoolVar(&versionFlag, "v", false, "Display version information")
flag.BoolVar(&versionExtFlag, "vv", false, "Display extended version information")
flag.BoolVar(&prettyPrintFlag, "pp", false, "Pretty print for JSON output")
flag.StringVar(&nomadFlag, "nomad", "", "Nomad url (default \"http://localhost:4646\")")
flag.StringVar(&proxyFlag, "proxy", "", "Proxy url")
flag.BoolVar(&dockerPullFlag, "docker-pull", false, "Pull Docker images before sync")
}
func main() {
// Init cli
cli = gocli.Cli{
Name: "nomad-syncer",
Version: "1.1.1",
Description: "An opinionated CLI for Nomad",
Commands: map[string]string{
"jobs": "Retrieve jobs",
"add": "Add a job",
"get": "Get a job information",
"del": "Delete a job",
"sync": "Sync jobs via a file or directory",
},
}
cli.Init()
// Run the app
// Command
if cli.SubCommand != "" {
// Init the Nomad client
if nomadFlag != "" {
nomadURL = nomadFlag
} else if os.Getenv("NOMAD_URL") != "" {
nomadURL = os.Getenv("NOMAD_URL")
} else {
nomadURL = "http://localhost:4646"
}
if proxyFlag != "" {
proxyURL = proxyFlag
} else if os.Getenv("NOMAD_SYNCER_PROXY_URL") != "" {
proxyURL = os.Getenv("NOMAD_SYNCER_PROXY_URL")
}
if proxyURL != "" {
p, err := url.Parse(proxyURL)
if err != nil {
cli.LogErr.Fatal("invalid proxy value due to " + err.Error())
}
if p != nil {
}
nomadClient = client.Client{URL: nomadURL, ProxyURL: p}
} else {
nomadClient = client.Client{URL: nomadURL}
}
// Run the command
if cli.SubCommand == "jobs" {
// Get the jobs
runJobsCmd()
} else if cli.SubCommand == "add" {
// Add a job
runAddCmd()
} else if cli.SubCommand == "get" {
// Get a job information
runGetCmd()
} else if cli.SubCommand == "del" {
// Delete a job
runDelCmd()
} else if cli.SubCommand == "sync" {
// Sync jobs
runSyncCmd()
}
} else if versionFlag || versionExtFlag {
// Version
cli.PrintVersion(versionExtFlag)
} else {
// Default
cli.PrintUsage()
}
}
// runAddCmd runs the add command
func runAddCmd() {
// Get the job name
var jobj string
if len(cli.SubCommandArgs) > 0 {
jobj = cli.SubCommandArgs[0]
}
// Add the job
if err := nomadClient.AddJob(jobj); err != nil {
cli.LogErr.Fatal(err)
} else {
cli.LogOut.Printf("job is added\n")
}
}
// runJobsCmd runs the jobs command
func runJobsCmd() {
if err := nomadClient.PrintJobs(prettyPrintFlag); err != nil {
cli.LogErr.Fatal(err)
}
}
// runGetCmd runs the get command
func runGetCmd() {
// Get the job id
var job string
if len(cli.SubCommandArgs) > 0 {
job = cli.SubCommandArgs[0]
}
if err := nomadClient.PrintJob(job, prettyPrintFlag); err != nil {
cli.LogErr.Fatal(err)
}
}
// runDelCmd runs the remove command
func runDelCmd() {
// Get the job id
var job string
if len(cli.SubCommandArgs) > 0 {
job = cli.SubCommandArgs[0]
}
// Delete the job
if err := nomadClient.DeleteJob(job); err != nil {
cli.LogErr.Fatal(err)
} else {
cli.LogOut.Printf("%s job is removed\n", job)
}
}
// syncFile syncs the given file
func syncFile(file string) {
// Read file
buf, err := ioutil.ReadFile(file)
if err != nil {
cli.LogErr.Fatal(err)
}
syncIt := true
// Pull docker images
if dockerPullFlag {
cli.LogOut.Printf("syncing %s\n", path.Base(file))
if err := findAndPullDockerImages(string(buf)); err != nil {
cli.LogErr.Println("failed to sync " + path.Base(file) + " due to " + err.Error())
syncIt = false
}
}
// Add the job
if syncIt {
if err := nomadClient.AddJob(string(buf)); err != nil {
cli.LogErr.Fatal(err)
} else {
cli.LogOut.Printf("%s is synced\n", path.Base(file))
}
}
}
// walkFn called for each directory during walk function execution
func walkFn(path string, info os.FileInfo, err error) error {
// If it is not a directory then
if !info.IsDir() {
// Sync the file
syncFile(path)
}
return nil
}
// runSyncCmd runs the sync command
func runSyncCmd() {
// Get the file or directory path
var path string
if len(cli.SubCommandArgs) > 0 {
path = cli.SubCommandArgs[0]
}
// Check file
var fi os.FileInfo
fi, err := os.Stat(path)
if os.IsNotExist(err) {
cli.LogErr.Fatal("no such file or directory: " + path) // fatal error
}
// If it is a file than
if !fi.IsDir() {
// Sync the file
syncFile(path)
} else {
// Otherwise recursively sync files
if err := filepath.Walk(path, walkFn); err != nil {
cli.LogErr.Fatal(err)
}
}
}
// findDockerImages finds docker images from the given content
func findDockerImages(jobJSON string) ([]string, error) {
// Check job
buf := []byte(jobJSON)
var sj client.SyncJob
if err := json.Unmarshal(buf, &sj); err != nil {
return nil, errors.New("failed to unmarshal JSON data due to " + err.Error())
}
// Get images
var images []string
if sj.Job != nil && sj.Job.TaskGroups != nil {
for _, tg := range sj.Job.TaskGroups {
if tg.Tasks != nil {
for _, t := range tg.Tasks {
if t.Config != nil && t.Driver == "docker" {
for ck, cv := range t.Config {
if ck == "image" {
images = append(images, cv.(string))
}
}
}
}
}
}
}
return images, nil
}
// pullDockerImage pulls a docker image by the given name
func pullDockerImage(image string) error {
cmd := exec.Command("docker", "pull", image)
err := cmd.Start()
if err != nil {
return err
}
cli.LogOut.Println("pulling " + image)
err = cmd.Wait()
if err != nil {
return errors.New("fail to pull " + image)
}
return nil
}
// findAndPullDockerImages finds and pulls docker images from the given content
func findAndPullDockerImages(jobJSON string) error {
// Find images
var images []string
images, err := findDockerImages(jobJSON)
if err != nil {
return errors.New("failed to find docker images due to " + err.Error())
}
// Pull images
for _, i := range images {
if err := pullDockerImage(i); err != nil {
return err
}
}
return nil
}