-
Notifications
You must be signed in to change notification settings - Fork 37
/
sensor.go
219 lines (176 loc) · 5.65 KB
/
sensor.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
// (c) Copyright IBM Corp. 2021
// (c) Copyright Instana Inc. 2016
package instana
import (
"context"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/instana/go-sensor/acceptor"
"github.com/instana/go-sensor/autoprofile"
"github.com/instana/go-sensor/aws"
"github.com/instana/go-sensor/logger"
)
const (
// DefaultMaxBufferedSpans is the default span buffer size
DefaultMaxBufferedSpans = 1000
// DefaultForceSpanSendAt is the default max number of spans to buffer before force sending them to the agent
DefaultForceSpanSendAt = 500
defaultServerlessTimeout = 500 * time.Millisecond
)
type agentClient interface {
Ready() bool
SendMetrics(data acceptor.Metrics) error
SendEvent(event *EventData) error
SendSpans(spans []Span) error
SendProfiles(profiles []autoprofile.Profile) error
Flush(context.Context) error
}
// zero value for sensorS.Agent()
type noopAgent struct{}
func (noopAgent) Ready() bool { return false }
func (noopAgent) SendMetrics(data acceptor.Metrics) error { return nil }
func (noopAgent) SendEvent(event *EventData) error { return nil }
func (noopAgent) SendSpans(spans []Span) error { return nil }
func (noopAgent) SendProfiles(profiles []autoprofile.Profile) error { return nil }
func (noopAgent) Flush(context.Context) error { return nil }
type sensorS struct {
meter *meterS
logger LeveledLogger
options *Options
serviceName string
mu sync.RWMutex
agent agentClient
}
var (
sensor *sensorS
binaryName = filepath.Base(os.Args[0])
processStartedAt = time.Now()
)
func newSensor(options *Options) *sensorS {
options.setDefaults()
s := &sensorS{
options: options,
serviceName: options.Service,
}
if s.serviceName == "" {
s.serviceName = binaryName
}
s.setLogger(defaultLogger)
// override service name with an env value if set
if name, ok := os.LookupEnv("INSTANA_SERVICE_NAME"); ok {
s.serviceName = name
}
// handle the legacy (instana.Options).LogLevel value if we use logger.Logger to log
if l, ok := s.logger.(*logger.Logger); ok {
setLogLevel(l, options.LogLevel)
}
var agent agentClient
if agentEndpoint := os.Getenv("INSTANA_ENDPOINT_URL"); agentEndpoint != "" {
s.logger.Debug("INSTANA_ENDPOINT_URL= is set, switching to the serverless mode")
timeout, err := parseInstanaTimeout(os.Getenv("INSTANA_TIMEOUT"))
if err != nil {
s.logger.Warn("malformed INSTANA_TIMEOUT value, falling back to the default one: ", err)
timeout = defaultServerlessTimeout
}
client, err := acceptor.NewHTTPClient(timeout)
if err != nil {
if err == acceptor.ErrMalformedProxyURL {
s.logger.Warn(err)
} else {
s.logger.Error("failed to initialize acceptor HTTP client, falling back to the default one: ", err)
client = http.DefaultClient
}
}
agent = newServerlessAgent(s.serviceName, agentEndpoint, os.Getenv("INSTANA_AGENT_KEY"), client, s.logger)
}
if agent == nil {
agent = newAgent(s.serviceName, s.options.AgentHost, s.options.AgentPort, s.logger)
}
s.setAgent(agent)
s.meter = newMeter(s.logger)
return s
}
func (r *sensorS) setLogger(l LeveledLogger) {
r.logger = l
if agent, ok := r.Agent().(*agentS); ok && agent != nil {
agent.setLogger(r.logger)
}
}
func (r *sensorS) setAgent(agent agentClient) {
r.mu.Lock()
defer r.mu.Unlock()
r.agent = agent
}
// Agent returns the agent client used by the global sensor. It will return a noopAgent that is never ready
// until both the global sensor and its agent are initialized
func (r *sensorS) Agent() agentClient {
if r == nil {
return noopAgent{}
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.agent == nil {
return noopAgent{}
}
return r.agent
}
// InitSensor intializes the sensor (without tracing) to begin collecting
// and reporting metrics.
func InitSensor(options *Options) {
if sensor != nil {
return
}
if options == nil {
options = DefaultOptions()
}
sensor = newSensor(options)
// configure auto-profiling
autoprofile.SetLogger(sensor.logger)
autoprofile.SetOptions(autoprofile.Options{
IncludeProfilerFrames: options.IncludeProfilerFrames,
MaxBufferedProfiles: options.MaxBufferedProfiles,
})
autoprofile.SetSendProfilesFunc(func(profiles []autoprofile.Profile) error {
if !sensor.Agent().Ready() {
return errors.New("sender not ready")
}
sensor.logger.Debug("sending profiles to agent")
return sensor.Agent().SendProfiles(profiles)
})
if _, ok := os.LookupEnv("INSTANA_AUTO_PROFILE"); ok || options.EnableAutoProfile {
if !options.EnableAutoProfile {
sensor.logger.Info("INSTANA_AUTO_PROFILE is set, activating AutoProfile™")
}
autoprofile.Enable()
}
// start collecting metrics
go sensor.meter.Run(1 * time.Second)
sensor.logger.Debug("initialized Instana sensor v", Version)
}
func newServerlessAgent(serviceName, agentEndpoint, agentKey string, client *http.Client, logger LeveledLogger) agentClient {
switch {
case os.Getenv("AWS_EXECUTION_ENV") == "AWS_ECS_FARGATE" && os.Getenv("ECS_CONTAINER_METADATA_URI") != "":
// AWS Fargate
return newFargateAgent(
serviceName,
agentEndpoint,
agentKey,
client,
aws.NewECSMetadataProvider(os.Getenv("ECS_CONTAINER_METADATA_URI"), client),
logger,
)
case strings.HasPrefix(os.Getenv("AWS_EXECUTION_ENV"), "AWS_Lambda_"):
// AWS Lambda
return newLambdaAgent(serviceName, agentEndpoint, agentKey, client, logger)
case os.Getenv("K_SERVICE") != "" && os.Getenv("K_CONFIGURATION") != "" && os.Getenv("K_REVISION") != "":
// Knative, e.g. Google Cloud Run
return newGCRAgent(serviceName, agentEndpoint, agentKey, client, logger)
default:
return nil
}
}