-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
79 lines (71 loc) · 2.37 KB
/
Copy pathcommand.go
File metadata and controls
79 lines (71 loc) · 2.37 KB
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
package stop
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
)
const stopProcessFileName = "process.stop"
const processStoppedFileName = "process.stopped"
const Signal = "stop"
//This method is called by the custom stop command.
//It expects to receive a channel on which the caller can wait.
//It return any error that might occur while sending the signal
func SendStopSignalAndWait(stopChannel chan string) error {
signalError := sendStopSignal()
if signalError != nil {
return signalError
}
go waitForProcessToStop(stopChannel)
return nil
}
//This method should be called by the application that wants to handle the halt process.
//It returns a channel on which the caller can wait, until a stop signal is found.
func ListenForStopSignal() <-chan string {
c := make(chan string)
go func() {
log.Println("Starting stop signal listener")
checkForSignal := true
tempDir := os.TempDir()
stopProcessFile := filepath.Join(tempDir, stopProcessFileName)
for checkForSignal {
time.Sleep(time.Second * 2)
if _, err := os.Stat(stopProcessFile); err == nil {
log.Println("Found stop signal:", stopProcessFile)
c <- Signal
checkForSignal = false
} else if !os.IsNotExist(err) {
log.Fatalf("Error while testing for the existence of the stop signal %s: %v", stopProcessFile, err)
}
}
}()
return c
}
//This method should be called by the application once it has finished cleaning up, and is ready to shutdown
func SignalThatProcessHasStopped() error {
tempDir := os.TempDir()
processStoppedFile := filepath.Join(tempDir, processStoppedFileName)
return ioutil.WriteFile(processStoppedFile, []byte{}, 600)
}
func sendStopSignal() error {
tempDir := os.TempDir()
stopProcessFile := filepath.Join(tempDir, stopProcessFileName)
log.Println("Received stop command. Writing message to", stopProcessFile)
return ioutil.WriteFile(stopProcessFile, []byte{}, 600)
}
func waitForProcessToStop(stopChannel chan string) {
log.Println("Waiting for process to stop")
tempDir := os.TempDir()
processStoppedFile := filepath.Join(tempDir, processStoppedFileName)
var stopped bool
for !stopped {
time.Sleep(time.Second * 2)
if _, err := os.Stat(processStoppedFile); err == nil {
stopped = true
} else if !os.IsNotExist(err) {
log.Fatalf("Error while testing for the existence of the stopped signal %s: %v", processStoppedFile, err)
}
}
stopChannel <- Signal
}