-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathazure_application_insights_agent.go
More file actions
295 lines (249 loc) · 10.5 KB
/
azure_application_insights_agent.go
File metadata and controls
295 lines (249 loc) · 10.5 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Cloud Foundry Java Buildpack
// Copyright 2013-2021 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package frameworks
import (
"encoding/json"
"fmt"
"github.com/cloudfoundry/java-buildpack/src/java/common"
"github.com/cloudfoundry/java-buildpack/src/java/resources"
"os"
"path/filepath"
"strings"
)
// AzureApplicationInsightsAgentFramework represents the Azure Application Insights Java agent framework
type AzureApplicationInsightsAgentFramework struct {
context *common.Context
jarPath string
}
// NewAzureApplicationInsightsAgentFramework creates a new Azure Application Insights agent framework instance
func NewAzureApplicationInsightsAgentFramework(ctx *common.Context) *AzureApplicationInsightsAgentFramework {
return &AzureApplicationInsightsAgentFramework{context: ctx}
}
// Detect checks if Azure Application Insights should be enabled
func (a *AzureApplicationInsightsAgentFramework) Detect() (string, error) {
// Check for connection string environment variable
if os.Getenv("APPLICATIONINSIGHTS_CONNECTION_STRING") != "" {
a.context.Log.Debug("Azure Application Insights agent framework detected via APPLICATIONINSIGHTS_CONNECTION_STRING")
return "Azure Application Insights", nil
}
// Check for instrumentation key environment variable
if os.Getenv("APPINSIGHTS_INSTRUMENTATIONKEY") != "" {
a.context.Log.Debug("Azure Application Insights agent framework detected via APPINSIGHTS_INSTRUMENTATIONKEY")
return "Azure Application Insights", nil
}
// Check for Azure Application Insights service binding
vcapServices, err := GetVCAPServices()
if err != nil {
a.context.Log.Warning("Failed to parse VCAP_SERVICES: %s", err.Error())
return "", nil
}
// Azure Application Insights can be bound as:
// - "azure-application-insights" service (marketplace or label)
// - "application-insights" or "applicationinsights" service
// - Services with "application-insights", "applicationinsights", or "app-insights" tag
// - User-provided services with these patterns in the name (Docker platform)
if vcapServices.HasService("azure-application-insights") ||
vcapServices.HasService("application-insights") ||
vcapServices.HasService("applicationinsights") ||
vcapServices.HasTag("application-insights") ||
vcapServices.HasTag("applicationinsights") ||
vcapServices.HasTag("app-insights") ||
vcapServices.HasServiceByNamePattern("application-insights") ||
vcapServices.HasServiceByNamePattern("applicationinsights") ||
vcapServices.HasServiceByNamePattern("app-insights") ||
vcapServices.HasServiceByNamePattern("insights") {
a.context.Log.Info("Azure Application Insights service detected!")
return "Azure Application Insights", nil
}
a.context.Log.Debug("Azure Application Insights agent: no service binding or environment variables found")
return "", nil
}
// Supply downloads and installs the Azure Application Insights agent
func (a *AzureApplicationInsightsAgentFramework) Supply() error {
a.context.Log.Debug("Installing Azure Application Insights agent")
// Get dependency from manifest
dep, err := a.context.Manifest.DefaultVersion("azure-application-insights")
if err != nil {
return fmt.Errorf("unable to find Azure Application Insights agent in manifest: %w", err)
}
// Install the agent
agentDir := filepath.Join(a.context.Stager.DepDir(), "azure_application_insights_agent")
if err := a.context.Installer.InstallDependency(dep, agentDir); err != nil {
return fmt.Errorf("failed to install Azure Application Insights agent: %w", err)
}
// Install default configuration from embedded resources
if err := a.installDefaultConfiguration(agentDir); err != nil {
a.context.Log.Warning("Could not install default Azure Application Insights configuration: %s", err.Error())
}
// constructJarPath can be skipped here and do it only in finalize, but it can be left as a double check
// if jar path exists after the dependency install
err = a.constructJarPath(agentDir)
if err != nil {
return fmt.Errorf("azure application insights agent not found during supply: %w", err)
}
a.context.Log.Info("Azure Application Insights agent %s installed", dep.Version)
return nil
}
// installDefaultConfiguration installs the default AI-Agent.xml from embedded resources
func (a *AzureApplicationInsightsAgentFramework) installDefaultConfiguration(agentDir string) error {
configPath := filepath.Join(agentDir, "AI-Agent.xml")
// Check if configuration already exists (user-provided or from external config)
if _, err := os.Stat(configPath); err == nil {
a.context.Log.Debug("AI-Agent.xml already exists, skipping default configuration")
return nil
}
// Read embedded AI-Agent.xml
embeddedPath := "azure_application_insights_agent/AI-Agent.xml"
configData, err := resources.GetResource(embeddedPath)
if err != nil {
return fmt.Errorf("failed to read embedded AI-Agent.xml: %w", err)
}
// Write configuration file (no template processing needed)
if err := os.WriteFile(configPath, configData, 0644); err != nil {
return fmt.Errorf("failed to write AI-Agent.xml: %w", err)
}
a.context.Log.Debug("Installed default Azure Application Insights configuration")
a.context.Log.Debug(" - AI-Agent.xml (instrumentation settings)")
return nil
}
// Finalize configures the Azure Application Insights agent
func (a *AzureApplicationInsightsAgentFramework) Finalize() error {
agentDir := filepath.Join(a.context.Stager.DepDir(), "azure_application_insights_agent")
err := a.constructJarPath(agentDir)
if err != nil {
return fmt.Errorf("azure application insights agent not found during finalize: %w", err)
}
a.context.Log.BeginStep("Configuring Azure Application Insights agent")
// Get buildpack index for multi-buildpack support
depsIdx := a.context.Stager.DepsIdx()
// Convert staging path to runtime path
relPath, err := filepath.Rel(a.context.Stager.DepDir(), a.jarPath)
if err != nil {
return fmt.Errorf("failed to determine relative path for Azure Application Insights agent: %w", err)
}
runtimeJarPath := filepath.Join(fmt.Sprintf("$DEPS_DIR/%s", depsIdx), relPath)
// Build all JAVA_OPTS options
var opts []string
opts = append(opts, fmt.Sprintf("-javaagent:%s", runtimeJarPath))
// Get credentials from service binding or environment
credentials := a.getCredentials()
// Set connection string if available
if credentials.ConnectionString != "" {
opts = append(opts, fmt.Sprintf("-Dapplicationinsights.connection.string=%s", credentials.ConnectionString))
} else if credentials.InstrumentationKey != "" {
// Fallback to instrumentation key
opts = append(opts, fmt.Sprintf("-Dapplicationinsights.instrumentation-key=%s", credentials.InstrumentationKey))
}
// Set cloud role name (application name)
if appName := a.getApplicationName(); appName != "" {
opts = append(opts, fmt.Sprintf("-Dapplicationinsights.role.name=%s", appName))
}
// Write all options to .opts file
javaOpts := strings.Join(opts, " ")
if err := writeJavaOptsFile(a.context, 13, "azure_application_insights_agent", javaOpts); err != nil {
return fmt.Errorf("failed to write JAVA_OPTS for Azure Application Insights: %w", err)
}
a.context.Log.Debug("Azure Application Insights agent configured")
return nil
}
// AzureCredentials holds Azure Application Insights credentials
type AzureCredentials struct {
ConnectionString string
InstrumentationKey string
}
// getCredentials retrieves Azure Application Insights credentials
func (a *AzureApplicationInsightsAgentFramework) getCredentials() AzureCredentials {
creds := AzureCredentials{}
// Check environment variables first
creds.ConnectionString = os.Getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")
creds.InstrumentationKey = os.Getenv("APPINSIGHTS_INSTRUMENTATIONKEY")
if creds.ConnectionString != "" || creds.InstrumentationKey != "" {
return creds
}
// Check service binding
vcapServices := os.Getenv("VCAP_SERVICES")
if vcapServices == "" {
return creds
}
var services map[string][]map[string]interface{}
if err := json.Unmarshal([]byte(vcapServices), &services); err != nil {
return creds
}
// Look for Azure Application Insights service
serviceNames := []string{
"azure-application-insights",
"application-insights",
"applicationinsights",
"user-provided",
}
for _, serviceName := range serviceNames {
if serviceList, ok := services[serviceName]; ok {
for _, service := range serviceList {
if credentials, ok := service["credentials"].(map[string]interface{}); ok {
// Try connection_string
if connStr, ok := credentials["connection_string"].(string); ok {
creds.ConnectionString = connStr
return creds
}
if connStr, ok := credentials["connectionString"].(string); ok {
creds.ConnectionString = connStr
return creds
}
// Try instrumentation_key
if key, ok := credentials["instrumentation_key"].(string); ok {
creds.InstrumentationKey = key
return creds
}
if key, ok := credentials["instrumentationKey"].(string); ok {
creds.InstrumentationKey = key
return creds
}
}
}
}
}
return creds
}
// getApplicationName returns the application name from VCAP_APPLICATION
func (a *AzureApplicationInsightsAgentFramework) getApplicationName() string {
vcapApp := os.Getenv("VCAP_APPLICATION")
if vcapApp == "" {
return ""
}
var appData map[string]interface{}
if err := json.Unmarshal([]byte(vcapApp), &appData); err != nil {
return ""
}
if name, ok := appData["application_name"].(string); ok {
return name
}
return ""
}
func (a *AzureApplicationInsightsAgentFramework) constructJarPath(agentDir string) error {
// Find the installed JAR
jarPattern := filepath.Join(agentDir, "applicationinsights-agent-*.jar")
matches, err := filepath.Glob(jarPattern)
if err != nil {
return fmt.Errorf("failed to search for Azure Application Insights agent JAR: %w", err)
}
if len(matches) == 0 {
return fmt.Errorf("agent jar not found after installation in %s", agentDir)
}
a.jarPath = matches[0]
return nil
}
func (a *AzureApplicationInsightsAgentFramework) DependencyIdentifier() string {
return "azure-application-insights"
}