/
daemon.go
208 lines (175 loc) · 5.26 KB
/
daemon.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
package commons
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"strings"
"github.com/cyverse/s3rods/commons"
log "github.com/sirupsen/logrus"
"golang.org/x/xerrors"
"gopkg.in/yaml.v2"
)
const (
// InterProcessCommunicationFinishSuccess is the message that parent process receives when child process is executed successfully
InterProcessCommunicationFinishSuccess string = "<<COMMUNICATION_CLOSE_SUCCESS>>"
// InterProcessCommunicationFinishError is the message that parent process receives when child process fails to run
InterProcessCommunicationFinishError string = "<<COMMUNICATION_CLOSE_ERROR>>"
)
// NilWriter drains output
type NilWriter struct{}
// Write does nothing
func (w *NilWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}
func (w *NilWriter) Close() (err error) {
return nil
}
func ReportChildProcessError() {
fmt.Fprintln(os.Stderr, InterProcessCommunicationFinishError)
}
func ReportChildProcessStartSuccessfully() {
fmt.Fprintln(os.Stdout, InterProcessCommunicationFinishSuccess)
}
func SetNilLogWriter() {
var nilWriter NilWriter
log.SetOutput(&nilWriter)
}
func RunChildProcess(serverExec string) (io.WriteCloser, io.ReadCloser, error) {
logger := log.WithFields(log.Fields{
"package": "commons",
"function": "RunChildProcess",
})
// run child process in background and pass parameters via stdin PIPE
// receives result from the child process
logger.Info("Running the child process in the background mode")
childProcessArgument := fmt.Sprintf("--%s", ChildProcessArgument)
cmd := exec.Command(serverExec, childProcessArgument)
childStdin, err := cmd.StdinPipe()
if err != nil {
pipeErr := xerrors.Errorf("failed to get the child process's STDIN: %w", err)
logger.Errorf("%+v", pipeErr)
return nil, nil, pipeErr
}
childStdout, err := cmd.StdoutPipe()
if err != nil {
pipeErr := xerrors.Errorf("failed to get the child process's STDOUT: %w", err)
logger.Errorf("%+v", pipeErr)
return nil, nil, pipeErr
}
cmd.Stderr = cmd.Stdout
// start
err = cmd.Start()
if err != nil {
cmdErr := xerrors.Errorf("failed to start the child process: %w", err)
logger.Errorf("%+v", cmdErr)
return nil, nil, cmdErr
}
logger.Infof("Child process id = %d", cmd.Process.Pid)
return childStdin, childStdout, nil
}
func ParentProcessSendConfigViaSTDIN(config *commons.Config, stdin io.WriteCloser, stdout io.ReadCloser) error {
logger := log.WithFields(log.Fields{
"package": "commons",
"function": "ParentProcessSendConfigViaSTDIN",
})
logger.Info("Sending configuration via STDIN")
configBytes, err := yaml.Marshal(config)
if err != nil {
yamlErr := xerrors.Errorf("failed to marshal configuration to yaml: %w", err)
logger.Errorf("%+v", yamlErr)
return yamlErr
}
// send it to child
_, err = io.WriteString(stdin, string(configBytes))
if err != nil {
writeErr := xerrors.Errorf("failed to send via STDIN: %w", err)
logger.Errorf("%+v", writeErr)
return writeErr
}
stdin.Close()
logger.Info("Successfully sent configuration to STDIN")
// receive output from child
childProcessFailed := false
childOutputScanner := bufio.NewScanner(stdout)
for {
if childOutputScanner.Scan() {
errMsg := strings.TrimSpace(childOutputScanner.Text())
if errMsg == InterProcessCommunicationFinishSuccess {
logger.Info("Successfully started child process")
break
} else if errMsg == InterProcessCommunicationFinishError {
logger.Error("failed to start child process")
childProcessFailed = true
break
} else {
logger.Info(errMsg)
}
} else {
// check err
if childOutputScanner.Err() != nil {
logger.Error(childOutputScanner.Err().Error())
childProcessFailed = true
break
}
}
}
stdout.Close()
if childProcessFailed {
return xerrors.Errorf("failed to start child process")
}
return nil
}
func ChildProcessReadConfigViaSTDIN() (*commons.Config, io.WriteCloser, error) {
logger := log.WithFields(log.Fields{
"package": "commons",
"function": "ChildProcessReadConfigViaSTDIN",
})
// read from stdin
logger.Info("Check STDIN to communicate to other process")
_, err := os.Stdin.Stat()
if err != nil {
statErr := xerrors.Errorf("failed to read from STDIN: %w", err)
logger.Errorf("%+v", statErr)
return nil, nil, statErr
}
logger.Info("Reading configuration from STDIN")
configBytes, err := io.ReadAll(os.Stdin)
if err != nil {
readErr := xerrors.Errorf("failed to read configuration: %w", err)
logger.Errorf("%+v", readErr)
return nil, nil, readErr
}
logger.Info("Successfully read configuration from STDIN")
config, err := commons.NewConfigFromYAML(configBytes)
if err != nil {
logger.Errorf("%+v", err)
return nil, nil, err
}
if config.Debug {
log.SetLevel(log.DebugLevel)
}
err = config.Validate()
if err != nil {
logger.Errorf("%+v", err)
return nil, nil, err
}
err = config.MakeLogDir()
if err != nil {
logger.Errorf("%+v", err)
return nil, nil, err
}
// output to log file
logFilePath := config.GetLogFilePath()
if len(logFilePath) > 0 && logFilePath != "-" {
logWriter, childLogFilePath := getLogWriterForChildProcess(logFilePath)
log.SetOutput(logWriter)
logger.Infof("Logging to %s", childLogFilePath)
return config, logWriter, nil
} else {
var nilWriter NilWriter
log.SetOutput(&nilWriter)
return config, &nilWriter, nil
}
}