forked from DataDog/datadog-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
87 lines (72 loc) · 2.17 KB
/
util.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build python
// +build python
package python
/*
#include <datadog_agent_rtloader.h>
#cgo !windows LDFLAGS: -ldatadog-agent-rtloader -ldl
#cgo windows LDFLAGS: -ldatadog-agent-rtloader -lstdc++ -static
*/
import "C"
import (
"fmt"
"io/ioutil"
"os/exec"
"sync"
"syscall"
)
// GetSubprocessOutput runs the subprocess and returns the output
// Indirectly used by the C function `get_subprocess_output` that's mapped to `_util.get_subprocess_output`.
//export GetSubprocessOutput
func GetSubprocessOutput(argv **C.char, env **C.char, cStdout **C.char, cStderr **C.char, cRetCode *C.int, exception **C.char) {
subprocessArgs := cStringArrayToSlice(argv)
// this should never happen as this case is filtered by rtloader
if len(subprocessArgs) == 0 {
return
}
ctx, _ := GetSubprocessContextCancel()
cmd := exec.CommandContext(ctx, subprocessArgs[0], subprocessArgs[1:]...)
subprocessEnv := cStringArrayToSlice(env)
if len(subprocessEnv) != 0 {
cmd.Env = subprocessEnv
}
stdout, err := cmd.StdoutPipe()
if err != nil {
*exception = TrackedCString(fmt.Sprintf("internal error creating stdout pipe: %v", err))
return
}
var wg sync.WaitGroup
var output []byte
wg.Add(1)
go func() {
defer wg.Done()
output, _ = ioutil.ReadAll(stdout)
}()
stderr, err := cmd.StderrPipe()
if err != nil {
*exception = TrackedCString(fmt.Sprintf("internal error creating stderr pipe: %v", err))
return
}
var outputErr []byte
wg.Add(1)
go func() {
defer wg.Done()
outputErr, _ = ioutil.ReadAll(stderr)
}()
cmd.Start() //nolint:errcheck
// Wait for the pipes to be closed *before* waiting for the cmd to exit, as per os.exec docs
wg.Wait()
retCode := 0
err = cmd.Wait()
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
retCode = status.ExitStatus()
}
}
*cStdout = TrackedCString(string(output))
*cStderr = TrackedCString(string(outputErr))
*cRetCode = C.int(retCode)
}