-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.go
439 lines (319 loc) · 9.34 KB
/
link.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
*/
package main
import (
"bufio"
"errors"
"fmt"
"github.com/codeskyblue/go-sh"
"github.com/fatih/color"
"io/ioutil"
"os"
"strconv"
"strings"
)
const processFileName string = ".links"
// Setup the properties required to sync directories
type dirSync struct {
from string
to string
}
/**
* Configure the link properties
* @param {[type]} link *dirSync) configure(from, to string [description]
* @return {[type]} [description]
*/
func (link *dirSync) Configure(from, to string) {
link.from = from
link.to = to
}
/**
* List all current links
* @param {[type]} link *dirSync) List( [description]
* @return {[type]} [description]
*/
func (link *dirSync) List() {
// Try to read a current process file
linkData, err := ioutil.ReadFile(processFileName)
// Soft error as it may not exists
if err != nil {
color.Red("No links available")
os.Exit(1)
}
links := strings.Split(string(linkData[:]), "\n")
fmt.Println("\tStatus\t\tPID\tFrom\tTo")
// Display links
for index, value := range links {
var status string
currentLink := strings.Split(value, " ")
// Check if process is active
if active := checkProcessActive(currentLink[0]); active {
status = color.GreenString("Active")
} else {
status = color.RedString("Inactive")
}
fmt.Printf("[%d]\t%s\t%s\t%s\t%s\n", index, status, currentLink[0], currentLink[1], currentLink[2])
}
}
/**
* Remove a link
* @param {[type]} link *dirSync) Remove( [description]
* @return {[type]} [description]
*/
func (link *dirSync) Remove() {
// First show current links
link.List()
// Prompt user to choose which link to remove
consolereader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the link number you want to remove: ")
input, err := consolereader.ReadString('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Validate that the link reference is correct and get the pid
linkIndex, _ := strconv.Atoi(input)
currentLink, err := getLinkByIndex(linkIndex)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if active := checkProcessActive(currentLink["pid"]); active == true {
// Remove a link
_, err := sh.Command("kill", currentLink["pid"]).Output()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// TODO: Remove link from file
color.Green(fmt.Sprintf("Successfully removed link from:%s to:%s", currentLink["from"], currentLink["to"]))
}
/**
* Add a new link
* @param {[type]} link *dirSync) Add( [description]
* @return {[type]} [description]
*/
func (link *dirSync) Add() {
// TODO: If a mac user check for notify_loop and any dependencies
// Create new link
newLink, err := launchLink(link.from, link.to)
if err != nil {
color.Red(fmt.Sprintf("Link could not be created: '%s'", err))
os.Exit(1)
}
// Convert byte array to string
processId := string(newLink[:])
// Add new process to link file
err = saveLinkProcess(processId, link.from, link.to)
if err != nil {
color.Red("Link could not be saved for later use. It was created however.")
os.Exit(1)
}
}
/**
* Enable a folder sync
* @param {[type]} link *dirSync) Up( [description]
* @return nil
*/
func (link *dirSync) Up() {
// First show current links
link.List()
// Prompt user to choose which link to enable
consolereader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the link number you want to enable: ")
input, err := consolereader.ReadString('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
linkIndex, _ := strconv.Atoi(input)
linkData, err := getLinkByIndex(linkIndex)
// Make sure the link isnt active
if active := checkProcessActive(linkData["pid"]); active {
color.Yellow("Link is already active")
os.Exit(1)
}
// Launch the process
newLink, err := launchLink(linkData["from"], linkData["to"])
if err != nil {
color.Red(fmt.Sprintf("Link could not be initialised: '%s'", err))
os.Exit(1)
}
// Convert byte array to string
processId := string(newLink[:])
err = updateLinkProcess(processId, linkIndex)
if err != nil {
color.Red("Link could not be saved for later use. It was created however.")
os.Exit(1)
}
color.Green(fmt.Sprintf("Successfully enabled link from:%s to:%s", linkData["from"], linkData["to"]))
}
/**
* Disable a folder sync
* @param {[type]} link *dirSync) Down( [description]
* @return nil
*/
func (link *dirSync) Down() {
// First show current links
link.List()
// Prompt user to choose which link to remove
consolereader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the link number you want to disable: ")
input, err := consolereader.ReadString('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Get link
linkIndex, _ := strconv.Atoi(input)
linkData, err := getLinkByIndex(linkIndex)
// Make sure the link is active
if active := checkProcessActive(linkData["pid"]); !active {
color.Yellow("Link is already inactive")
os.Exit(1)
}
// We need to kill the process but leave the data in the file
_, err = sh.Command("kill", linkData["pid"]).Output()
if err != nil {
color.Red("Could not disable the link. Try again or otherwise logout/reboot to reset.")
os.Exit(1)
}
color.Green(fmt.Sprintf("Successfully disabled link from:%s to:%s", linkData["from"], linkData["to"]))
color.Green("You can re-enable the link by running kubefactory link up")
}
/**
* Initialise/re-initialise a link
* @param {[type]} from [description]
* @param {[type]} to string) (msg, err [description]
* @return {[type]} [description]
*/
func launchLink(from, to string) (msg []byte, err error) {
msg, err = sh.Command("bash", "watchout(){", "notify_loop", from+";", "rsync", "-chavzP", "--stats", "--delete", from, to, "&&", "watchout;", "watchout", ">", "/dev/null", "&").Command("awk", "{print $2}").Output()
return
// watchout(){ notify_loop /Users/work/code/fig-esm/; rsync -chavzP --stats --delete /Users/work/code/fig-esm/ [email protected]:/tmp/test && watchout; }; watchout > /dev/null &
// Base rsync call for transferring files
// rsync -chavzP --delete --stats ./ [email protected]:/tmp/test
// msg, err := sh.Command("lsyncd", " -nodaemon", "-rsyncssh", link.from, link.user+"@"+link.host, link.to).Output()
}
/**
* Updates the processId of a link and saves to file
* @param {string} pid
* @param {int} linkIndex
* @return {error} err
*/
func updateLinkProcess(pid string, linkIndex int) (err error) {
// Get the link file
links, err := getLinks()
// Find the index
for index, _ := range links {
if index != linkIndex {
continue
}
// Update the pid with the one given
links[linkIndex]["pid"] = pid
}
return nil
}
/**
* Writes an array of links to file
* @param {[]map[string]string} links
* @return {error} err
*/
func writeLinkFile(links []map[string]string) (err error) {
var linksData string
for _, link := range links {
linksData += fmt.Sprintf("%s %s %s\n", link["pid"], link["from"], link["to"])
}
// Write process file
err = ioutil.WriteFile(processFileName, []byte(linksData), 0600)
if err != nil {
return errors.New("Couldnt write to file " + processFileName)
}
return nil
}
/**
* Check to see if a given processId is active
* @param {string} pid
* @return {bool}
*/
func checkProcessActive(pid string) bool {
msg, err := sh.Command("ps", "-p", pid).Command("grep", "bash").Command("awk", "$1").Output()
if err != nil {
return false
}
output := string(msg[:])
if output != pid {
return false
}
return true
}
/**
* Get an array of all links available
* @param {[type]} ) (links []map[string]string, err error [description]
* @return {[type]} [description]
*/
func getLinks() (links []map[string]string, err error) {
// Try to read a current process file
linkData, err := ioutil.ReadFile(processFileName)
if err != nil {
return nil, errors.New("No links available")
}
lines := strings.Split(string(linkData[:]), "\n")
// Build links
for _, value := range lines {
currentLink := strings.Split(value, " ")
fmt.Println(currentLink)
links = append(links, map[string]string{"pid": currentLink[0], "from": currentLink[1], "to": currentLink[2]})
}
return links, nil
}
/**
* Get a link by index
* @param {[type]} index int) (pid int, err error [description]
* @return {[type]} [description]
*/
func getLinkByIndex(index int) (pid map[string]string, err error) {
links, _ := getLinks()
for key, link := range links {
if key != index {
continue
}
return link, nil
}
return nil, errors.New("Index could not be found")
}
/**
* Save the process id from a link for later use
* @param {[type]} processId string) (err error [description]
* @return {[type]} [description]
* TODO: Update to use objects for saving data
*/
func saveLinkProcess(processId, from, to string) (err error) {
var processIds string
newLink := fmt.Sprintf("%s %s %s\n", processId, from, to)
// Try to read a current process file
dat, err := ioutil.ReadFile(processFileName)
// Soft error as it may not exists
if err != nil {
processIds = processId
} else {
processIds = string(dat[:]) + newLink
}
// Rewrite process file
err = ioutil.WriteFile(processFileName, []byte(processIds), 0644)
if err != nil {
return errors.New("Couldnt write to file " + processFileName)
}
return nil
}
/**
* Handle an error ungracefully
* @param {error} e error
* @return nil
*/
func check(e error) {
if e != nil {
panic(e)
}
}