This repository has been archived by the owner on Aug 30, 2019. It is now read-only.
/
agent.go
182 lines (167 loc) · 4.37 KB
/
agent.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
package test
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/spf13/viper"
yaml "gopkg.in/yaml.v2"
)
// ErrNotInstalled is returned when the trace-agent can not be found in $PATH.
var ErrNotInstalled = errors.New("agent: trace-agent not found in $PATH")
type agentRunner struct {
mu sync.RWMutex // guards pid
pid int // agent pid, if running
port int // agent port
log *safeBuffer // agent log
ddAddr string // Datadog API address (host:port)
verbose bool
}
func newAgentRunner(ddAddr string, verbose bool) (*agentRunner, error) {
if _, err := exec.LookPath("trace-agent"); err != nil {
// trace-agent not in $PATH, try to install
if verbose {
log.Print("agent: trace-agent not found, trying to install...")
}
err := exec.Command("go", "install", "github.com/DataDog/datadog-trace-agent/cmd/trace-agent").Run()
if err != nil {
return nil, ErrNotInstalled
}
if _, err := exec.LookPath("trace-agent"); err != nil {
// still not in $PATH, fail
if verbose {
log.Print("trace-agent installed but not found in $PATH")
}
return nil, ErrNotInstalled
}
}
return &agentRunner{
ddAddr: ddAddr,
log: newSafeBuffer(),
verbose: verbose,
}, nil
}
// Run runs the agent using a given yaml config. If an agent is already running,
// it will be killed.
func (s *agentRunner) Run(conf []byte) error {
cfgPath, err := s.createConfigFile(conf)
if err != nil {
return fmt.Errorf("agent: error creating config: %v", err)
}
timeout := time.After(5 * time.Second)
exit := s.runAgentConfig(cfgPath)
for {
select {
case err := <-exit:
return fmt.Errorf("agent: %v, log output:\n%s", err, s.Log())
case <-timeout:
return fmt.Errorf("agent: timed out waiting for start, log:\n%s", s.Log())
default:
if strings.Contains(s.log.String(), "listening for traces at") {
if s.verbose {
log.Print("agent: listening for traces")
}
return nil
}
time.Sleep(5 * time.Millisecond)
}
}
}
// Log returns the tail of the agent log (up to 1M).
func (s *agentRunner) Log() string { return s.log.String() }
// PID returns the process ID of the trace-agent. If the trace-agent is not running
// as a child process of this program, it will be 0.
func (s *agentRunner) PID() int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.pid
}
// Addr returns the address of the trace agent receiver.
func (s *agentRunner) Addr() string { return fmt.Sprintf("localhost:%d", s.port) }
// Kill stops a running trace-agent, if it was started by this process.
func (s *agentRunner) Kill() {
pid := s.PID()
if pid == 0 {
return
}
proc, err := os.FindProcess(pid)
if err != nil {
return
}
if err := proc.Kill(); err != nil {
if s.verbose {
log.Print("couldn't kill running agent: ", err)
}
}
proc.Wait()
}
func (s *agentRunner) runAgentConfig(path string) <-chan error {
s.Kill()
cmd := exec.Command("trace-agent", "-config", path)
s.log.Reset()
cmd.Stdout = s.log
cmd.Stderr = ioutil.Discard
cmd.Start()
s.mu.Lock()
s.pid = cmd.Process.Pid
s.mu.Unlock()
ch := make(chan error, 1) // don't block
go func() {
ch <- cmd.Wait()
os.Remove(path)
s.mu.Lock()
s.pid = 0
s.mu.Unlock()
if s.verbose {
log.Print("agent: killed")
}
}()
return ch
}
// createConfigFile creates a config file from the given config, altering the
// apm_config.apm_dd_url and log_level values and returns the full path.
func (s *agentRunner) createConfigFile(conf []byte) (string, error) {
v := viper.New()
v.SetConfigType("yaml")
if err := v.ReadConfig(bytes.NewReader(conf)); err != nil {
return "", err
}
s.port = 8126
if v.IsSet("apm_config.receiver_port") {
s.port = v.GetInt("apm_config.receiver_port")
}
v.Set("apm_config.apm_dd_url", "http://"+s.ddAddr)
if !v.IsSet("api_key") {
v.Set("api_key", "testing123")
}
if !v.IsSet("apm_config.trace_writer.flush_period_seconds") {
v.Set("apm_config.trace_writer.flush_period_seconds", 0.1)
}
v.Set("log_level", "info")
out, err := yaml.Marshal(v.AllSettings())
if err != nil {
return "", err
}
dir, err := ioutil.TempDir("", "agent-conf-")
if err != nil {
return "", err
}
f, err := os.Create(filepath.Join(dir, "datadog.yaml"))
if err != nil {
return "", err
}
if _, err := f.Write(out); err != nil {
return "", err
}
if err := f.Close(); err != nil {
return "", err
}
return f.Name(), nil
}