-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.go
More file actions
636 lines (541 loc) · 14.5 KB
/
program.go
File metadata and controls
636 lines (541 loc) · 14.5 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Package program provides individual process execution and management capabilities.
// It offers comprehensive process lifecycle management, I/O handling, and monitoring.
package program
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/GustavoCaso/meeseeks/pkg/logger"
)
// Program defines the interface for managing individual external processes.
// It provides methods for execution, monitoring, I/O control, and lifecycle management
// with support for both synchronous and asynchronous execution modes.
type Program interface {
// Async returns true if the program runs asynchronously, false for synchronous execution.
Async() bool
// Name returns the human-readable name of this program.
Name() string
// Start begins program execution and returns a channel that closes when execution completes.
// Returns an error if the program cannot be started.
Start(ctx context.Context) (<-chan struct{}, error)
// Send writes data to the program's stdin. Requires KeepStdinOpen option.
// Returns an error if stdin is closed or the program is not running.
Send([]byte) error
// CloseStdin closes the program's stdin pipe. Requires KeepStdinOpen option.
// Returns an error if stdin is already closed or the program is not running.
CloseStdin() error
// Output returns all stdout content captured from the program.
Output() string
// Error returns all stderr content and error messages from the program.
Error() string
// State returns the current execution state of the program.
State() ProcessState
// String returns a human-readable representation of the program including name and command.
String() string
// Shutdown gracefully terminates the program with SIGTERM, falling back to SIGKILL after timeout.
// Returns an error if the shutdown process fails.
Shutdown(timeout time.Duration) error
}
// ProcessState represents the current execution state of a program.
type ProcessState int
// Process state constants define the possible execution states.
const (
// StateNotStarted indicates the program has not been started yet.
StateNotStarted ProcessState = iota
// StateRunning indicates the program is currently executing.
StateRunning
// StateFinished indicates the program completed successfully.
StateFinished
// StateError indicates the program failed with an error.
StateError
// StateCancelled indicates the program was terminated by a signal.
StateCancelled
)
// StateToString provides human-readable string representations of process states.
//
//nolint:gochecknoglobals // This gloabls is convinient
var StateToString = map[ProcessState]string{
StateNotStarted: "not started",
StateRunning: "running",
StateFinished: "finished",
StateError: "error",
StateCancelled: "cancelled",
}
// Option defines a function type for configuring program instances.
type Option func(*program)
// StdoutFile redirects program stdout to the specified file path.
// The file will be created if it doesn't exist, with output appended.
func StdoutFile(file string) Option {
return func(p *program) {
p.stdoutFile = file
}
}
// StderrFile redirects program stderr to the specified file path.
// The file will be created if it doesn't exist, with output appended.
func StderrFile(file string) Option {
return func(p *program) {
p.stderrFile = file
}
}
// Stdout redirects program stdout to the provided io.Writer.
// Output will be written to both the internal buffer and the provided writer.
func Stdout(o io.Writer) Option {
return func(p *program) {
p.customStdout = o
}
}
// Stderr redirects program stderr to the provided io.Writer.
// Output will be written to both the internal buffer and the provided writer.
func Stderr(o io.Writer) Option {
return func(p *program) {
p.customStderr = o
}
}
// Stdin provides input to the program from the specified io.Reader.
// Input will be available to the program's stdin in addition to any data sent via Send().
func Stdin(o io.Reader) Option {
return func(p *program) {
p.customStdin = o
}
}
// Args sets the command-line arguments for the program.
// These arguments will be passed to the program when it starts.
func Args(args ...string) Option {
return func(p *program) {
p.arguments = args
}
}
// Envs sets additional environment variables for the program.
// These are added to the current environment and should be in KEY=VALUE format.
func Envs(envs ...string) Option {
return func(p *program) {
p.customEnv = envs
}
}
// KeepStdinOpen keeps the program's stdin pipe open for sending data.
// Required if you plan to use Send() or CloseStdin() methods.
func KeepStdinOpen() Option {
return func(p *program) {
p.keepStdinOpen = true
}
}
// Async configures the program to run asynchronously.
// When async, Start() returns immediately without waiting for completion.
func Async() Option {
return func(p *program) {
p.async = true
}
}
// Logger sets the logger instance for the program.
// The logger will be used for internal logging operations and error reporting.
func Logger(logger logger.Logger) Option {
return func(p *program) {
p.logger = logger
}
}
// BufferSizeLimit sets the maximum size in bytes for stdout/stderr buffers.
// When the limit is reached, buffers are truncated to prevent memory issues.
// A limit of 0 means no limit (buffers can grow indefinitely).
func BufferSizeLimit(limit int) Option {
return func(p *program) {
p.bufferLimit = limit
}
}
type program struct {
customStderr io.Writer
logger logger.Logger
customStdin io.Reader
customStdout io.Writer
pipes *pipes
cmd *exec.Cmd
done chan struct{}
stderrFile string
stdoutFile string
name string
command string
errorBuffer strings.Builder
outputBuffer strings.Builder
arguments []string
finalizers []func() error
customEnv []string
bufferLimit int
exitCode int
state ProcessState
dataLock sync.RWMutex
cmdLock sync.Mutex
async bool
keepStdinOpen bool
}
type pipes struct {
outReader *io.PipeReader
outWriter *io.PipeWriter
errReader *io.PipeReader
errWriter *io.PipeWriter
inReader *io.PipeReader
inWriter *io.PipeWriter
}
func (p *pipes) closeWriters() error {
err := p.outWriter.Close()
if err != nil {
return err
}
err = p.errWriter.Close()
if err != nil {
return err
}
err = p.inWriter.Close()
if err != nil {
return err
}
return nil
}
func (p *pipes) closeReaders() error {
err := p.outReader.Close()
if err != nil {
return err
}
err = p.errReader.Close()
if err != nil {
return err
}
err = p.inReader.Close()
if err != nil {
return err
}
return nil
}
func (p *program) finalize() {
for _, finalizer := range p.finalizers {
err := finalizer()
if err != nil {
if p.logger != nil {
p.logger.Warn("error when executing finalizers", "error", err.Error())
}
}
}
close(p.done)
}
func (p *program) Start(ctx context.Context) (<-chan struct{}, error) {
cmd, err := p.setupCmd(ctx)
if err != nil {
done := make(chan struct{}, 1)
close(done)
return done, err
}
p.cmdLock.Lock()
p.cmd = cmd
p.cmdLock.Unlock()
p.done = make(chan struct{}, 1)
return p.done, p.run()
}
func (p *program) setupCmd(ctx context.Context) (*exec.Cmd, error) {
//nolint:gosec // We accept the arguments the users have manually defined
cmd := exec.CommandContext(
ctx,
p.command,
p.arguments...)
cmd.Env = append(os.Environ(), p.customEnv...)
outReader, outWriter := io.Pipe()
errReader, errWriter := io.Pipe()
inReader, inWriter := io.Pipe()
pipes := &pipes{
outReader: outReader,
outWriter: outWriter,
errReader: errReader,
errWriter: errWriter,
inReader: inReader,
inWriter: inWriter,
}
p.pipes = pipes
outputWriters := []io.Writer{
outWriter,
}
stderrWriters := []io.Writer{
errWriter,
}
stdinReaders := []io.Reader{
inReader,
}
if p.customStdout != nil {
outputWriters = append(outputWriters, p.customStdout)
}
if p.customStderr != nil {
stderrWriters = append(stderrWriters, p.customStderr)
}
if p.customStdin != nil {
stdinReaders = append(stdinReaders, p.customStdin)
}
prepareFile := func(filePath string) (*os.File, error) {
err := os.MkdirAll(filepath.Dir(filePath), 0750)
if err != nil {
return nil, err
}
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return nil, err
}
p.finalizers = append(p.finalizers, file.Close)
return file, nil
}
if p.stdoutFile != "" {
file, err := prepareFile(p.stdoutFile)
if err != nil {
return nil, fmt.Errorf("failed to open stdout file %s: %w", p.stdoutFile, err)
}
outputWriters = append(outputWriters, file)
}
if p.stderrFile != "" {
file, err := prepareFile(p.stderrFile)
if err != nil {
return nil, fmt.Errorf("failed to open stderr file %s: %w", p.stderrFile, err)
}
stderrWriters = append(stderrWriters, file)
}
cmd.Stdout = io.MultiWriter(outputWriters...)
cmd.Stderr = io.MultiWriter(stderrWriters...)
cmd.Stdin = io.MultiReader(stdinReaders...)
if !p.keepStdinOpen {
_ = inWriter.Close()
}
return cmd, nil
}
func (p *program) run() error {
p.cmdLock.Lock()
err := p.cmd.Start()
p.cmdLock.Unlock()
if err != nil {
p.dataLock.Lock()
p.writeOutput(&p.errorBuffer, err.Error())
p.state = StateError
p.dataLock.Unlock()
p.finalize()
return err
}
p.dataLock.Lock()
p.state = StateRunning
p.dataLock.Unlock()
if p.async {
go p.monitorProcess()
return nil
}
p.monitorProcess()
return nil
}
func (p *program) monitorProcess() {
// WaitGroup ensures readOutput goroutines finish reading all data.
// This prevents race conditions where callers might see incomplete output.
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
p.readOutput(p.pipes.outReader, false)
}()
go func() {
defer wg.Done()
p.readOutput(p.pipes.errReader, true)
}()
p.cmdLock.Lock()
cmd := p.cmd
p.cmdLock.Unlock()
err := cmd.Wait()
writersErr := p.pipes.closeWriters()
if writersErr != nil {
if p.logger != nil {
p.logger.Error(
"error closing writers",
"program",
p.name,
"error",
writersErr.Error(),
)
}
}
// Wait for readers to finish processing all data
wg.Wait()
readersErr := p.pipes.closeReaders()
if readersErr != nil {
if p.logger != nil {
p.logger.Error(
"error closing readers",
"program",
p.name,
"error",
readersErr.Error(),
)
}
}
p.exitCode = cmd.ProcessState.ExitCode()
p.dataLock.Lock()
if err != nil {
if strings.Contains(err.Error(), "signal: killed") {
p.state = StateCancelled
} else {
p.state = StateError
}
p.writeOutput(&p.errorBuffer, err.Error())
} else {
p.state = StateFinished
}
p.dataLock.Unlock()
p.finalize()
}
func (p *program) readOutput(reader io.Reader, isError bool) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
p.dataLock.Lock()
if isError {
p.writeOutput(&p.errorBuffer, line)
} else {
p.writeOutput(&p.outputBuffer, line)
}
p.dataLock.Unlock()
}
if err := scanner.Err(); err != nil && !errors.Is(err, io.EOF) {
if isError {
p.dataLock.Lock()
p.writeOutput(&p.errorBuffer, "Scanner error: "+err.Error())
p.dataLock.Unlock()
}
}
}
// writeOutput handles buffer management with proper truncation and thread safety.
func (p *program) writeOutput(buffer *strings.Builder, s string) {
newContent := s + "\n"
if p.bufferLimit <= 0 {
buffer.WriteString(newContent)
return
}
spaceNeeded := len(newContent)
currentSize := buffer.Len()
// Check if we need to truncate
threshold := int(float64(p.bufferLimit) * 0.95)
if currentSize+spaceNeeded > threshold {
buffer.Reset()
fmt.Fprintf(buffer, "[%s] truncated due to buffer limit: %d bytes\n", time.Now(), p.bufferLimit)
if p.logger != nil {
p.logger.Info("buffer truncated", "program", p.name)
}
}
buffer.WriteString(newContent)
}
func (p *program) Send(data []byte) error {
p.dataLock.RLock()
canSend := p.state == StateRunning
p.dataLock.RUnlock()
if !canSend {
return errors.New("can not send data to a non-running program")
}
if !p.keepStdinOpen {
return errors.New("to send data to a running please use the KeepStdinOpen option when initialazing the program")
}
_, err := p.pipes.inWriter.Write(data)
return err
}
func (p *program) CloseStdin() error {
p.dataLock.RLock()
canClose := p.state == StateRunning
p.dataLock.RUnlock()
if !canClose {
return errors.New("closing stdin of non-running process has no effect")
}
if !p.keepStdinOpen {
return errors.New(
"stding is already closed please KeepStdinOpen option when initialazing the program to have full control over stdin",
)
}
return p.pipes.inWriter.Close()
}
func (p *program) Async() bool {
return p.async
}
func (p *program) Name() string {
return p.name
}
func (p *program) Output() string {
p.dataLock.RLock()
defer p.dataLock.RUnlock()
return p.outputBuffer.String()
}
func (p *program) Error() string {
p.dataLock.RLock()
defer p.dataLock.RUnlock()
return p.errorBuffer.String()
}
func (p *program) State() ProcessState {
p.dataLock.RLock()
defer p.dataLock.RUnlock()
return p.state
}
func (p *program) Shutdown(timeout time.Duration) error {
p.cmdLock.Lock()
if p.cmd == nil || p.cmd.Process == nil {
p.cmdLock.Unlock()
return nil
}
// Send SIGTERM for graceful shutdown
err := p.cmd.Process.Signal(syscall.SIGTERM)
p.cmdLock.Unlock()
if err != nil {
if errors.Is(err, os.ErrProcessDone) {
return nil
}
// If SIGTERM fails, fall back to force kill
return p.forcekill()
}
// Wait for the existing monitoring to handle process exit
select {
case <-p.done:
return nil
case <-time.After(timeout):
// Timeout exceeded, force kill
return p.forcekill()
}
}
func (p *program) String() string {
return fmt.Sprintf("%s [%s %s]", p.name, p.command, strings.Join(p.arguments, " "))
}
func (p *program) forcekill() error {
p.cmdLock.Lock()
if p.cmd == nil || p.cmd.Process == nil {
p.cmdLock.Unlock()
return nil
}
err := p.cmd.Process.Kill()
p.cmdLock.Unlock()
p.dataLock.Lock()
p.state = StateError
p.dataLock.Unlock()
if err != nil {
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return err
}
return nil
}
// New creates a new Program instance with the provided options.
func New(name, command string, opts ...Option) Program {
p := &program{
name: name,
command: command,
finalizers: []func() error{},
}
for _, opt := range opts {
opt(p)
}
if p.bufferLimit > 0 {
p.outputBuffer.Grow(p.bufferLimit)
p.errorBuffer.Grow(p.bufferLimit)
}
return p
}