-
Notifications
You must be signed in to change notification settings - Fork 37
/
azure_agent.go
215 lines (167 loc) · 4.98 KB
/
azure_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
// (c) Copyright IBM Corp. 2022
package instana
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/instana/go-sensor/acceptor"
"github.com/instana/go-sensor/autoprofile"
)
const (
flushPeriodInSec = 2
azureCustomRuntime string = "custom"
)
type azureAgent struct {
Endpoint string
Key string
PID int
snapshot serverlessSnapshot
mu sync.Mutex
spanQueue []Span
client *http.Client
logger LeveledLogger
}
func newAzureAgent(acceptorEndpoint, agentKey string, client *http.Client, logger LeveledLogger) *azureAgent {
if logger == nil {
logger = defaultLogger
}
if client == nil {
client = http.DefaultClient
client.Timeout = 500 * time.Millisecond
}
logger.Debug("initializing azure agent")
agent := &azureAgent{
Endpoint: acceptorEndpoint,
Key: agentKey,
PID: os.Getpid(),
client: client,
logger: logger,
}
go func() {
t := time.NewTicker(flushPeriodInSec * time.Second)
defer t.Stop()
for range t.C {
if err := agent.Flush(context.Background()); err != nil {
agent.logger.Error("failed to post collected data: ", err)
}
}
}()
return agent
}
func (a *azureAgent) Ready() bool { return true }
func (a *azureAgent) SendMetrics(acceptor.Metrics) error { return nil }
func (a *azureAgent) SendEvent(*EventData) error { return nil }
func (a *azureAgent) SendSpans(spans []Span) error {
a.enqueueSpans(spans)
return nil
}
func (a *azureAgent) SendProfiles([]autoprofile.Profile) error { return nil }
func (a *azureAgent) Flush(ctx context.Context) error {
a.collectSnapshot()
if a.snapshot.EntityID == "" {
return ErrAgentNotReady
}
from := newServerlessAgentFromS(a.snapshot.EntityID, "azure")
payload := struct {
Metrics metricsPayload `json:"metrics,omitempty"`
Spans []Span `json:"spans,omitempty"`
}{
Metrics: metricsPayload{
Plugins: []acceptor.PluginPayload{
acceptor.NewAzurePluginPayload(a.snapshot.EntityID),
},
},
}
a.mu.Lock()
payload.Spans = make([]Span, len(a.spanQueue))
copy(payload.Spans, a.spanQueue)
a.spanQueue = a.spanQueue[:0]
a.mu.Unlock()
for i := range payload.Spans {
payload.Spans[i].From = from
}
buf := bytes.NewBuffer(nil)
if err := json.NewEncoder(buf).Encode(payload); err != nil {
return fmt.Errorf("failed to marshal traces payload: %s", err)
}
payloadSize := buf.Len()
if payloadSize > maxContentLength {
a.logger.Warn(fmt.Sprintf("failed to send the spans. Payload size: %d exceeded max size: %d", payloadSize, maxContentLength))
return payloadTooLargeErr
}
req, err := http.NewRequest(http.MethodPost, a.Endpoint+"/bundle", buf)
if err != nil {
a.enqueueSpans(payload.Spans)
return fmt.Errorf("failed to prepare send traces request: %s", err)
}
req.Header.Set("Content-Type", "application/json")
if err := a.sendRequest(req.WithContext(ctx)); err != nil {
a.enqueueSpans(payload.Spans)
return fmt.Errorf("failed to send traces, will retry later: %dsec. Error details: %s",
flushPeriodInSec, err.Error())
}
return nil
}
func (a *azureAgent) enqueueSpans(spans []Span) {
a.mu.Lock()
defer a.mu.Unlock()
a.spanQueue = append(a.spanQueue, spans...)
}
func (a *azureAgent) sendRequest(req *http.Request) error {
req.Header.Set("X-Instana-Host", a.snapshot.Host)
req.Header.Set("X-Instana-Key", a.Key)
resp, err := a.client.Do(req)
if err != nil {
return fmt.Errorf("failed to send request to the serverless agent: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
a.logger.Debug("failed to read serverless agent response: ", err.Error())
return err
}
a.logger.Info("serverless agent has responded with ", resp.Status, ": ", string(respBody))
return err
}
io.CopyN(ioutil.Discard, resp.Body, 1<<20)
return nil
}
func (a *azureAgent) collectSnapshot() {
if a.snapshot.EntityID != "" {
return
}
var subscriptionID, resourceGrp, functionApp string
var ok bool
if websiteOwnerName, ok := os.LookupEnv("WEBSITE_OWNER_NAME"); ok {
arr := strings.Split(websiteOwnerName, "+")
if len(arr) > 1 {
subscriptionID = arr[0]
} else {
a.logger.Warn("failed to retrieve the subscription id. This will affect the correlation metrics.")
}
} else {
a.logger.Warn("failed to retrieve the subscription id. This will affect the correlation metrics.")
}
if resourceGrp, ok = os.LookupEnv("WEBSITE_RESOURCE_GROUP"); !ok {
a.logger.Warn("failed to retrieve the resource group. This will affect the correlation metrics.")
}
if functionApp, ok = os.LookupEnv("APPSETTING_WEBSITE_SITE_NAME"); !ok {
a.logger.Warn("failed to retrieve the function app. This will affect the correlation metrics.")
}
entityID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Web/sites/%s",
subscriptionID, resourceGrp, functionApp)
a.snapshot = serverlessSnapshot{
EntityID: entityID,
PID: a.PID,
}
a.logger.Debug("collected snapshot")
}