forked from signalfx/splunk-otel-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommander.go
167 lines (140 loc) · 4.22 KB
/
commander.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
// Copyright Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scriptedinputsreceiver
import (
"context"
"io"
"os/exec"
"strings"
"sync/atomic"
"syscall"
"time"
"go.uber.org/zap"
)
// commander can start/stop/restart the shell executable and also watch for a signal
// for the shell process to finish.
type commander struct {
name string
content string
stdout io.Writer
logger *zap.Logger
cmd *exec.Cmd
doneCh chan struct{}
waitCh chan struct{}
args []string
running int64
}
func newCommander(logger *zap.Logger, name string, content string, stdout io.Writer, args ...string) *commander {
return &commander{
name: name,
content: content,
logger: logger,
args: args,
stdout: stdout,
}
}
// Start the shell and begin watching the process.
func (c *commander) Start(ctx context.Context) error {
c.logger.Info("Starting script.", zap.String("script", c.name))
c.cmd = exec.CommandContext(ctx, "sh", c.args...) //nolint:gosec
// Capture standard output and standard error.
c.cmd.Stdin = strings.NewReader(c.content)
c.cmd.Stdout = c.stdout
// TODO: handle this separately for data integrity and diagnostics
c.cmd.Stderr = c.stdout
c.doneCh = make(chan struct{}, 1)
c.waitCh = make(chan struct{})
if err := c.cmd.Start(); err != nil {
return err
}
c.logger.Debug("shell process started", zap.Any("PID", c.cmd.Process.Pid))
atomic.StoreInt64(&c.running, 1)
go c.watch()
return nil
}
func (c *commander) watch() {
defer func() { close(c.waitCh) }()
err := c.cmd.Wait()
if err != nil {
c.logger.Error("Error in cmd wait: %v", zap.Error(err))
return
}
c.doneCh <- struct{}{}
atomic.StoreInt64(&c.running, 0)
}
// Done returns a channel that will send a signal when the shell process is finished.
func (c *commander) Done() <-chan struct{} {
return c.doneCh
}
// Pid returns shell process PID if it is started or 0 if it is not.
func (c *commander) Pid() int {
if c.cmd == nil || c.cmd.Process == nil {
return 0
}
return c.cmd.Process.Pid
}
// ExitCode returns shell process exit code if it exited or 0 if it is not.
func (c *commander) ExitCode() int {
if c.cmd == nil || c.cmd.ProcessState == nil {
return -1
}
return c.cmd.ProcessState.ExitCode()
}
func (c *commander) IsRunning() bool {
return atomic.LoadInt64(&c.running) != 0
}
// Stop the shell process. Sends SIGTERM to the process and wait for up 10 seconds
// and if the process does not finish kills it forcedly by sending SIGKILL.
// Returns after the process is terminated.
func (c *commander) Stop(ctx context.Context) error {
if c.cmd == nil || c.cmd.Process == nil {
// Not started, nothing to do.
return nil
}
c.logger.Debug("Stopping shell process", zap.Any("PID", c.cmd.Process.Pid))
// Gracefully signal process to stop.
if err := c.cmd.Process.Signal(syscall.SIGTERM); err != nil {
return err
}
finished := make(chan struct{})
// Setup a goroutine to wait a while for process to finish and send kill signal
// to the process if it doesn't finish.
var innerErr error
go func() {
// Wait 10 seconds.
select {
case <-ctx.Done():
break
case <-time.After(10 * time.Second):
// Time is out. Kill the process.
c.logger.Debug(
"shell process PID=%d is not responding to SIGTERM. Sending SIGKILL to kill forcedly.",
zap.Any("PID", c.cmd.Process.Pid))
if innerErr = c.cmd.Process.Signal(syscall.SIGKILL); innerErr != nil {
return
}
break
case <-finished:
// Process is successfully finished.
c.logger.Debug("shell process PID=%v successfully stopped.", zap.Any("PID", c.cmd.Process.Pid))
return
}
}()
// Wait for process to terminate
<-c.waitCh
atomic.StoreInt64(&c.running, 0)
// Let goroutine know process is finished.
close(finished)
return innerErr
}