forked from stackimpact/stackimpact-go
/
agent.go
219 lines (182 loc) · 4.39 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
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
package internal
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"math/rand"
"os"
"strconv"
"sync"
"sync/atomic"
"time"
)
const AgentVersion = "1.3.6"
const SAASDashboardAddress = "https://agent-api.stackimpact.com"
var agentStarted bool = false
type Agent struct {
nextId int64
buildId string
runId string
runTs int64
apiRequest *APIRequest
config *Config
configLoader *ConfigLoader
messageQueue *MessageQueue
processReporter *ProcessReporter
cpuReporter *CPUReporter
allocationReporter *AllocationReporter
blockReporter *BlockReporter
segmentReporter *SegmentReporter
errorReporter *ErrorReporter
// Syncronization
profilingLock *sync.RWMutex
profilingActive bool
// Options
DashboardAddress string
AgentKey string
AppName string
AppVersion string
AppEnvironment string
HostName string
Debug bool
}
func NewAgent() *Agent {
a := &Agent{
nextId: 0,
runId: "",
buildId: "",
runTs: time.Now().Unix(),
apiRequest: nil,
config: nil,
configLoader: nil,
messageQueue: nil,
processReporter: nil,
cpuReporter: nil,
allocationReporter: nil,
blockReporter: nil,
segmentReporter: nil,
errorReporter: nil,
profilingLock: &sync.RWMutex{},
profilingActive: false,
DashboardAddress: SAASDashboardAddress,
AgentKey: "",
AppName: "",
AppVersion: "",
AppEnvironment: "",
HostName: "",
Debug: false,
}
a.buildId = a.calculateProgramSHA1()
a.runId = a.uuid()
a.apiRequest = newAPIRequest(a)
a.config = newConfig(a)
a.configLoader = newConfigLoader(a)
a.messageQueue = newMessageQueue(a)
a.processReporter = newProcessReporter(a)
a.cpuReporter = newCPUReporter(a)
a.allocationReporter = newAllocationReporter(a)
a.blockReporter = newBlockReporter(a)
a.segmentReporter = newSegmentReporter(a)
a.errorReporter = newErrorReporter(a)
return a
}
func (a *Agent) Start() {
if agentStarted {
a.log("Agent configuration failed. Another agent has already been initialized.")
return
}
agentStarted = true
if a.HostName == "" {
hostName, err := os.Hostname()
if err != nil {
a.error(err)
}
a.HostName = hostName
}
a.configLoader.start()
a.messageQueue.start()
a.processReporter.start()
a.cpuReporter.start()
a.allocationReporter.start()
a.blockReporter.start()
a.segmentReporter.start()
a.errorReporter.start()
a.log("Agent started.")
return
}
func (a *Agent) calculateProgramSHA1() string {
file, err := os.Open(os.Args[0])
if err != nil {
a.error(err)
return ""
}
defer file.Close()
hash := sha1.New()
if _, err := io.Copy(hash, file); err != nil {
a.error(err)
return ""
}
return hex.EncodeToString(hash.Sum(nil))
}
func (a *Agent) RecordSegment(path []string, duration int64) {
if !agentStarted {
return
}
a.segmentReporter.recordSegment(path, duration)
}
func (a *Agent) RecordError(group string, msg interface{}, skipFrames int) {
if !agentStarted {
return
}
var err error
switch v := msg.(type) {
case error:
err = v
default:
err = fmt.Errorf("%v", v)
}
a.errorReporter.recordError(group, err, skipFrames+1)
}
func (a *Agent) setProfilingActive(val bool) {
a.profilingLock.Lock()
defer a.profilingLock.Unlock()
a.profilingActive = val
}
func (a *Agent) isProfilingActive() bool {
a.profilingLock.RLock()
defer a.profilingLock.RUnlock()
return a.profilingActive
}
func (a *Agent) log(format string, values ...interface{}) {
if a.Debug {
fmt.Printf("["+time.Now().Format(time.StampMilli)+"]"+
" StackImpact "+AgentVersion+": "+
format+"\n", values...)
}
}
func (a *Agent) error(err error) {
if a.Debug {
fmt.Println("[" + time.Now().Format(time.StampMilli) + "]" +
" StackImpact " + AgentVersion + ": Error")
fmt.Println(err)
}
}
func (a *Agent) recoverAndLog() {
if err := recover(); err != nil {
a.log("Recovered from panic in agent: %v", err)
}
}
func (a *Agent) uuid() string {
n := atomic.AddInt64(&a.nextId, 1)
uuid :=
strconv.FormatInt(time.Now().Unix(), 10) +
strconv.Itoa(rand.Intn(1000000000)) +
strconv.FormatInt(n, 10)
return sha1String(uuid)
}
func sha1String(s string) string {
sha1 := sha1.New()
sha1.Write([]byte(s))
return hex.EncodeToString(sha1.Sum(nil))
}