Skip to content

Commit d5e0759

Browse files
johnoliverCopilotCopilot
authored
Add manual profile triggering and cooldown mechanism (#4730)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent dbca1ff commit d5e0759

21 files changed

Lines changed: 1098 additions & 28 deletions

File tree

‎.github/copilot-instructions.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ This is a **Java agent** that extends OpenTelemetry Java Agent to provide Azure
99
- **Agent Entry Point**: `Agent.java` - wraps OpenTelemetry Agent with Application Insights-specific initialization
1010
- **Agent Bootstrap**: Minimal classes loaded into bootstrap classloader for early initialization
1111
- **Agent Tooling**: Main Application Insights logic (configuration, exporters, processors) isolated in agent classloader
12+
- **Profiler Subsystem**: JFR-based profiling with threshold triggers (CPU, memory, request), manual triggers (file touch, JMX MBean), and global cooldown
1213
- **Instrumentation Modules**: C Functions, ASP.NET Core interop, etc.
1314
- **Classic SDK**: Legacy 2.x SDK maintained for compatibility
1415

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# CHANGELOG
22

3+
## Unreleased
4+
5+
### Enhancements
6+
7+
* Add manual profile triggering via file touch and JMX MBean
8+
* Add global cooldown (`globalCooldownSeconds`) to prevent rapid successive profiles from different
9+
trigger sources
10+
* Add `manualTriggeredSettings` configuration for controlling the JFR profile used during manual
11+
recordings
12+
313
## Version 3.7.8 GA (03/24/2026)
414

515
* Update to OpenTelemetry Java Instrumentation 2.26.1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.microsoft.applicationinsights.alerting.config;
5+
6+
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
7+
import java.io.File;
8+
9+
/**
10+
* Configuration for the file-based manual profile trigger.
11+
*
12+
* <p>When enabled, the alerting subsystem periodically checks for the existence of a trigger file.
13+
* If the file exists and was recently modified (within {@link #MANUAL_TRIGGER_FILE_MAX_AGE_MS}), it
14+
* is deleted and a manual profile recording is initiated.
15+
*
16+
* <p>This provides an operator-friendly mechanism for triggering on-demand profiles without
17+
* requiring JMX access – simply {@code touch} the trigger file from a shell or orchestration tool.
18+
*/
19+
public class AlertingProfileFileTriggerConfiguration {
20+
private static final String DEFAULT_TRIGGER_FILENAME =
21+
"applicationinsights-agent-profile-trigger";
22+
23+
/**
24+
* Maximum age (in milliseconds) of the trigger file for it to be considered valid. Files older
25+
* than this threshold are ignored to prevent stale trigger files from initiating unexpected
26+
* recordings (e.g., after a restart).
27+
*/
28+
public static final long MANUAL_TRIGGER_FILE_MAX_AGE_MS = 60_000; // 1 minute
29+
30+
// Whether the file-based manual trigger is enabled.
31+
private final boolean enabled;
32+
33+
// Path to the file that triggers a manual profile when created/touched.
34+
// If relative, it is resolved against the agent's temp directory.
35+
private final File filePath;
36+
37+
/** The default duration (in seconds) used for profiles triggered via this file mechanism. */
38+
private final int defaultProfileDurationSeconds;
39+
40+
private AlertingProfileFileTriggerConfiguration(
41+
boolean enabled, File filePath, int defaultProfileDurationSeconds) {
42+
this.enabled = enabled;
43+
this.filePath = filePath;
44+
this.defaultProfileDurationSeconds = defaultProfileDurationSeconds;
45+
}
46+
47+
/**
48+
* Creates a file trigger configuration, resolving relative paths against the provided temp
49+
* directory.
50+
*
51+
* @param enabled whether file-based triggering is active
52+
* @param filePath path to the trigger file (absolute or relative to {@code tempDir})
53+
* @param defaultProfileDurationSeconds duration in seconds for the profile if no override is
54+
* configured in the collection plan
55+
* @param tempDir base directory used to resolve relative file paths
56+
* @return a fully resolved configuration instance
57+
*/
58+
@SuppressFBWarnings(
59+
value = "SECPTI",
60+
justification = "File path is set by trusted user configuration (applicationinsights.json)")
61+
public static AlertingProfileFileTriggerConfiguration create(
62+
boolean enabled, String filePath, int defaultProfileDurationSeconds, File tempDir) {
63+
String resolvedFilePath = filePath;
64+
if (resolvedFilePath == null || resolvedFilePath.trim().isEmpty()) {
65+
resolvedFilePath = DEFAULT_TRIGGER_FILENAME;
66+
}
67+
68+
File manualTriggerFile = new File(resolvedFilePath);
69+
if (!manualTriggerFile.isAbsolute() && tempDir != null) {
70+
manualTriggerFile = new File(tempDir, resolvedFilePath);
71+
}
72+
73+
return new AlertingProfileFileTriggerConfiguration(
74+
enabled, manualTriggerFile, defaultProfileDurationSeconds);
75+
}
76+
77+
/** Creates a disabled configuration suitable for tests. */
78+
public static AlertingProfileFileTriggerConfiguration createDefault() {
79+
return new AlertingProfileFileTriggerConfiguration(
80+
false, new File(DEFAULT_TRIGGER_FILENAME), 120);
81+
}
82+
83+
/** Returns the default profile duration in seconds for file-triggered recordings. */
84+
public int getDefaultProfileDurationSeconds() {
85+
return defaultProfileDurationSeconds;
86+
}
87+
88+
/** Returns the resolved path of the trigger file. */
89+
public File getFilePath() {
90+
return filePath;
91+
}
92+
93+
/** Returns whether the file-based manual trigger is enabled. */
94+
public boolean isEnabled() {
95+
return enabled;
96+
}
97+
}

‎agent/agent-profiler/agent-alerting/src/main/java/com/microsoft/applicationinsights/alerting/AlertingSubsystem.java‎

Lines changed: 107 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
import com.microsoft.applicationinsights.alerting.config.AlertConfiguration;
1212
import com.microsoft.applicationinsights.alerting.config.AlertMetricType;
1313
import com.microsoft.applicationinsights.alerting.config.AlertingConfiguration;
14+
import com.microsoft.applicationinsights.alerting.config.AlertingProfileFileTriggerConfiguration;
1415
import com.microsoft.applicationinsights.alerting.config.CollectionPlanConfiguration;
1516
import com.microsoft.applicationinsights.alerting.config.CollectionPlanConfiguration.EngineMode;
1617
import com.microsoft.applicationinsights.alerting.config.DefaultConfiguration;
18+
import java.io.File;
1719
import java.time.Instant;
1820
import java.util.ArrayList;
1921
import java.util.HashSet;
@@ -33,7 +35,6 @@
3335
public class AlertingSubsystem {
3436

3537
private static final Logger logger = LoggerFactory.getLogger(AlertingSubsystem.class);
36-
3738
// Downstream observer of alerts produced by the alerting system
3839
private final Consumer<AlertBreach> alertHandler;
3940

@@ -46,25 +47,40 @@ public class AlertingSubsystem {
4647
// Current configuration of the alerting subsystem
4748
private AlertingConfiguration alertConfig;
4849

49-
private boolean enableRequestTriggerUpdates;
50+
/** Configuration controlling the file-based manual profile trigger. */
51+
private final AlertingProfileFileTriggerConfiguration alertingProfileFileTriggerConfiguration;
5052

51-
protected AlertingSubsystem(Consumer<AlertBreach> alertHandler) {
52-
this(alertHandler, TimeSource.DEFAULT, false);
53-
}
53+
private boolean enableRequestTriggerUpdates;
5454

5555
protected AlertingSubsystem(
5656
Consumer<AlertBreach> alertHandler,
5757
TimeSource timeSource,
58-
boolean enableRequestTriggerUpdates) {
58+
boolean enableRequestTriggerUpdates,
59+
AlertingProfileFileTriggerConfiguration alertingProfileFileTriggerConfiguration) {
5960
this.alertHandler = alertHandler;
6061
this.alertPipelines = new AlertPipelines(alertHandler);
6162
this.timeSource = timeSource;
6263
this.enableRequestTriggerUpdates = enableRequestTriggerUpdates;
64+
this.alertingProfileFileTriggerConfiguration = alertingProfileFileTriggerConfiguration;
6365
}
6466

67+
/**
68+
* Creates and initializes an {@link AlertingSubsystem} with an initially-disabled configuration.
69+
*
70+
* @param alertHandler downstream consumer that handles generated alert breaches
71+
* @param timeSource time source used for alert evaluation windows
72+
* @param alertingProfileFileTriggerConfiguration configuration for the file-based manual trigger
73+
* @return a fully initialized alerting subsystem ready to receive configuration updates
74+
*/
6575
public static AlertingSubsystem create(
66-
Consumer<AlertBreach> alertHandler, TimeSource timeSource) {
67-
AlertingSubsystem alertingSubsystem = new AlertingSubsystem(alertHandler, timeSource, true);
76+
Consumer<AlertBreach> alertHandler,
77+
TimeSource timeSource,
78+
AlertingProfileFileTriggerConfiguration alertingProfileFileTriggerConfiguration) {
79+
80+
AlertingSubsystem alertingSubsystem =
81+
new AlertingSubsystem(
82+
alertHandler, timeSource, true, alertingProfileFileTriggerConfiguration);
83+
6884
// init with disabled config
6985
alertingSubsystem.initialize(
7086
AlertingConfiguration.create(
@@ -145,14 +161,23 @@ private void updateRequestPipelineConfig(
145161
}
146162
}
147163

148-
/** Determine if a manual alert has been requested. */
164+
/**
165+
* Determine if a manual alert has been requested via any supported mechanism. Currently evaluates
166+
* both the server-side collection plan and the local file-based trigger.
167+
*/
149168
private void evaluateManualTrigger(AlertingConfiguration alertConfig) {
169+
evaluateCollectionPlanTrigger(alertConfig);
170+
evaluateFileTrigger(alertConfig);
171+
}
172+
173+
/** Check if the collection plan configuration requests a manual profile. */
174+
private void evaluateCollectionPlanTrigger(AlertingConfiguration alertConfig) {
150175
CollectionPlanConfiguration config = alertConfig.getCollectionPlanConfiguration();
151176

152177
boolean shouldTrigger =
153178
config.isSingle()
154179
&& config.getMode() == EngineMode.immediate
155-
&& Instant.now().isBefore(config.getExpiration())
180+
&& timeSource.getNow().isBefore(config.getExpiration())
156181
&& !manualTriggersExecuted.contains(config.getSettingsMoniker());
157182

158183
if (shouldTrigger) {
@@ -176,6 +201,78 @@ private void evaluateManualTrigger(AlertingConfiguration alertConfig) {
176201
}
177202
}
178203

204+
/**
205+
* Check if a trigger file is present on the local file system and was recently modified. If so,
206+
* delete the file and trigger a manual profile. The global cooldown in Profiler prevents
207+
* overlapping profiles.
208+
*/
209+
public void evaluateFileTrigger() {
210+
if (!alertingProfileFileTriggerConfiguration.isEnabled()) {
211+
return;
212+
}
213+
214+
if (alertConfig == null) {
215+
return;
216+
}
217+
218+
evaluateFileTrigger(alertConfig);
219+
}
220+
221+
private void evaluateFileTrigger(AlertingConfiguration currentConfig) {
222+
if (!alertingProfileFileTriggerConfiguration.isEnabled()) {
223+
return;
224+
}
225+
226+
if (currentConfig == null) {
227+
return;
228+
}
229+
230+
File manualTriggerFile = alertingProfileFileTriggerConfiguration.getFilePath();
231+
if (manualTriggerFile == null || !manualTriggerFile.exists()) {
232+
return;
233+
}
234+
235+
long lastModified = manualTriggerFile.lastModified();
236+
long age = timeSource.getNow().toEpochMilli() - lastModified;
237+
238+
if (age < 0 || age > AlertingProfileFileTriggerConfiguration.MANUAL_TRIGGER_FILE_MAX_AGE_MS) {
239+
return;
240+
}
241+
242+
// Delete the trigger file to prevent re-triggering
243+
if (!manualTriggerFile.delete()) {
244+
logger.warn(
245+
"Failed to delete manual profile trigger file: {}", manualTriggerFile.getAbsolutePath());
246+
return;
247+
}
248+
249+
logger.info("Manual profile trigger file detected, initiating profile recording");
250+
251+
// Use the collection plan's duration if configured, otherwise fall back to the
252+
// file trigger's default duration setting.
253+
CollectionPlanConfiguration collectionPlan = currentConfig.getCollectionPlanConfiguration();
254+
int durationSeconds = collectionPlan.getImmediateProfilingDurationSeconds();
255+
if (durationSeconds <= 0) {
256+
durationSeconds = alertingProfileFileTriggerConfiguration.getDefaultProfileDurationSeconds();
257+
}
258+
259+
AlertBreach alertBreach =
260+
AlertBreach.builder()
261+
.setType(AlertMetricType.MANUAL)
262+
.setAlertValue(0.0)
263+
.setAlertConfiguration(
264+
AlertConfiguration.builder()
265+
.setType(AlertMetricType.MANUAL)
266+
.setEnabled(true)
267+
.setProfileDurationSeconds(durationSeconds)
268+
.build())
269+
.setProfileId(UUID.randomUUID().toString())
270+
.setCpuMetric(0)
271+
.setMemoryUsage(0)
272+
.build();
273+
alertHandler.accept(alertBreach);
274+
}
275+
179276
public void setPipeline(AlertMetricType type, AlertPipeline alertPipeline) {
180277
alertPipelines.setAlertPipeline(type, alertPipeline);
181278
}

0 commit comments

Comments
 (0)