@Before public void testInitialize() throws Exception { RequestTelemetryContext requestTelemetryContext = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime()); ThreadContext.setRequestTelemetryContext(requestTelemetryContext); RequestTelemetry requestTelemetry = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry(); requestTelemetry.setHttpMethod(HTTP_METHOD); // Setting mock for action context // We can't stub classes of Method and Class, so We should use RequestNameInterceptorTests class for stub clazz = this.getClass(); method = clazz.getMethod("classInitialize"); invocationContext = mock(InvocationContext.class); when(invocationContext.getMethod()).thenReturn(method); when(invocationContext.proceed()).thenReturn(null); }
RequestTelemetry telemetry = context.getHttpRequestTelemetry(); telemetry.setName(String.format("%s %s", method, rUriWithoutSessionId)); telemetry.getContext().getUser().setUserAgent(userAgent); telemetry.setTimestamp(new Date(context.getRequestStartTimeTicks()));
/** * Helper method to retrieve Tracestate from ThreadLocal * @return */ public static String retriveTracestate() { //check if context is null - no correlation will happen if (ThreadContext.getRequestTelemetryContext() == null || ThreadContext.getRequestTelemetryContext(). getTracestate() == null) { InternalLogger.INSTANCE.warn("No correlation wil happen, Thread context is null"); return null; } Tracestate tracestate = ThreadContext.getRequestTelemetryContext().getTracestate(); return tracestate.toString(); }
/** * Begin request processing. * * @param req The request to process * @param res The response to modify */ @Override public void onBeginRequest(ServletRequest req, ServletResponse res) { HttpServletRequest request = (HttpServletRequest)req; RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); UserCookie userCookie = com.microsoft.applicationinsights.web.internal.cookies.Cookie.getCookie( UserCookie.class, request, UserCookie.COOKIE_NAME); if (userCookie == null) { return; } String userId = userCookie.getUserId(); Date acquisitionDate = userCookie.getAcquisitionDate(); context.setUserCookie(userCookie); UserContext userContext = context.getHttpRequestTelemetry().getContext().getUser(); userContext.setId(userId); userContext.setAcquisitionDate(acquisitionDate); }
private SessionContext getTelemetrySessionContext(RequestTelemetryContext aiContext) { return aiContext.getHttpRequestTelemetry().getContext().getSession(); }
@Test public void testTracestateIsPassedAsIsWhenAppIdResolutionIsFailed() { //turn on W3C defaultModule.isW3CEnabled = true; //setup: initialize a request context RequestTelemetryContext context = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime()); ThreadContext.setRequestTelemetryContext(context); //mock a servlet request with cross-component correlation headers Map<String, String> headers = new HashMap<>(); Traceparent tp = new Traceparent(); headers.put(TraceContextCorrelation.TRACEPARENT_HEADER_NAME, tp.toString()); headers.put(TraceContextCorrelation.TRACESTATE_HEADER_NAME, TraceContextCorrelationTests.getTracestateHeaderValue("id1")); HttpServletRequest request = ServletUtils.createServletRequestWithHeaders(headers); HttpServletResponse response = (HttpServletResponse)ServletUtils.generateDummyServletResponse(); //configure mock appId fetcher to return different appId from what's on the request header mockProfileFetcher.setAppIdToReturn("id2"); mockProfileFetcher.setResultStatus(ProfileFetcherResultTaskStatus.FAILED); //run defaultModule.onBeginRequest(request, response); Assert.assertNotNull(ThreadContext.getRequestTelemetryContext().getTracestate()); Assert.assertEquals(TraceContextCorrelationTests.getTracestateHeaderValue("id1"), ThreadContext.getRequestTelemetryContext().getTracestate().toString()); }
RequestTelemetryContext context = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime()); ThreadContext.setRequestTelemetryContext(context); ExceptionTelemetry exceptionTelemetry = items.get(0); RequestTelemetry requestTelemetry = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry(); Assert.assertEquals(requestTelemetry.getId(), exceptionTelemetry.getContext().getOperation().getParentId()); Assert.assertNotNull(ThreadContext.getRequestTelemetryContext().getTracestate()); Assert.assertEquals(TraceContextCorrelationTests.getTracestateHeaderValue("id2"), ThreadContext.getRequestTelemetryContext().getTracestate().toString());
private boolean invokeSafeOnBeginRequest(ServletRequest req, ServletResponse res) { if (!isInitialized) { return false; } boolean success = true; try { RequestTelemetryContext context = new RequestTelemetryContext(new Date().getTime(), (HttpServletRequest) req); ThreadContext.setRequestTelemetryContext(context); webModulesContainer.invokeOnBeginRequest(req, res); } catch (Exception e) { InternalLogger.INSTANCE.error( "Failed to invoke OnBeginRequest on telemetry modules with the following exception: %s", ExceptionUtils.getStackTrace(e)); success = false; } return success; }
/** * Generates child TraceParent by retrieving values from ThreadLocal. * @return Outbound Traceparent */ public static String generateChildDependencyTraceparent() { try { RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); //check if context is null, no incoming request is present. // This is likely worker role scenario, where a worker is trying // to create a new outbound call, so generate a new traceparent. if (context == null) { return new Traceparent().toString(); } RequestTelemetry requestTelemetry = context.getHttpRequestTelemetry(); String traceId = requestTelemetry.getContext().getOperation().getId(); Traceparent tp = new Traceparent(0, traceId, null, context.getTraceflag()); // We need to propagate full blown traceparent header. return tp.toString(); } catch (Exception ex) { InternalLogger.INSTANCE.error("Failed to generate child ID. Exception information: %s", ex.toString()); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } return null; }
/** * Generates a child Id for dependencies. Dependencies are children of requests and, therefore, their ID's * reflect this. The generated ID is based on the current request scope (stored in TLS). * @return The child Id. */ public static String generateChildDependencyId() { try { RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); //check if context is null - no correlation will happen if (context == null) { InternalLogger.INSTANCE.warn("No Correlation will happen, Thread context is null while generating child dependency"); return ""; } RequestTelemetry requestTelemetry = context.getHttpRequestTelemetry(); String parentId = requestTelemetry.getContext().getOperation().getParentId(); // if parentId is non-hierarchical, it means the incoming requestId // does not follow hierarchical convention, so we must not modify the children ID's. if (parentId != null && parentId.length() > 0 && !isHierarchicalId((parentId))) { return requestTelemetry.getContext().getOperation().getParentId(); } return requestTelemetry.getId() + context.incrementChildId() + "."; } catch (Exception ex) { InternalLogger.INSTANCE.error("Failed to generate child ID. Exception information: %s", ex.toString()); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } return null; }
RequestTelemetry requestTelemetry = telemetryContext.getHttpRequestTelemetry(); String currentOperationId = requestTelemetry.getContext().getOperation().getId(); Map<String, String> correlationContextMap = telemetryContext.getCorrelationContext().getMappings(); for (String key : correlationContextMap.keySet()) { if (telemetry.getProperties().get(key) == null) {
ThreadContext.getRequestTelemetryContext().setTraceflag(processedTraceParent.getTraceFlags()); ThreadContext.getRequestTelemetryContext().setTracestate(tracestate);
private void validate() { long currentTicks = ThreadContext.getRequestTelemetryContext().getRequestStartTimeTicks(); Assert.assertEquals("Found a thread with unexpected value.", startTicks, currentTicks); } }
/** * Retrieves the currently stored correlation context from the request context. * @return The correlation context as a string. */ public static String retrieveCorrelationContext() { //check if context is null - no correlation will happen if (ThreadContext.getRequestTelemetryContext() == null) { InternalLogger.INSTANCE.warn("No correlation wil happen, Thread context is null"); return ""; } CorrelationContext context = ThreadContext.getRequestTelemetryContext().getCorrelationContext(); return context.toString(); }
@Override protected void onInitializeTelemetry(Telemetry telemetry) { RequestTelemetryContext telemetryContext = ThreadContext.getRequestTelemetryContext(); if (telemetryContext == null) { return; } HttpServletRequest request = telemetryContext.getHttpServletRequest(); if (request == null) { return; } String syntheticSourceHeader = request.getHeader(SYNTHETIC_TEST_SOURCE); if (CommonUtils.isNullOrEmpty(syntheticSourceHeader)) { handlePossibleGSMSyntheticRequest(telemetry, request); } else { handleCommonSyntheticRequest(syntheticSourceHeader, telemetry, request); } }
/** * Begin request processing. * * @param req The request to process * @param res The response to modify */ @Override public void onBeginRequest(ServletRequest req, ServletResponse res) { HttpServletRequest request = (HttpServletRequest)req; RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); SessionCookie sessionCookie = com.microsoft.applicationinsights.web.internal.cookies.Cookie.getCookie( SessionCookie.class, request, SessionCookie.COOKIE_NAME); if (sessionCookie == null) { return; } context.setSessionCookie(sessionCookie); String sessionId = sessionCookie.getSessionId(); getTelemetrySessionContext(context).setId(sessionId); }
private SessionContext getTelemetrySessionContext(RequestTelemetryContext aiContext) { return aiContext.getHttpRequestTelemetry().getContext().getSession(); }
@Test public void testTracestateIsSetWhenHeaderIsEmpty() { //turn on W3C defaultModule.isW3CEnabled = true; //setup: initialize a request context RequestTelemetryContext context = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime()); ThreadContext.setRequestTelemetryContext(context); //mock a servlet request with cross-component correlation headers Map<String, String> headers = new HashMap<>(); Traceparent tp = new Traceparent(); headers.put(TraceContextCorrelation.TRACEPARENT_HEADER_NAME, tp.toString()); headers.put(TraceContextCorrelation.TRACESTATE_HEADER_NAME, ""); HttpServletRequest request = ServletUtils.createServletRequestWithHeaders(headers); HttpServletResponse response = (HttpServletResponse)ServletUtils.generateDummyServletResponse(); //configure mock appId fetcher to return different appId from what's on the request header mockProfileFetcher.setAppIdToReturn("id2"); mockProfileFetcher.setResultStatus(ProfileFetcherResultTaskStatus.COMPLETE); //run defaultModule.onBeginRequest(request, response); Assert.assertNotNull(ThreadContext.getRequestTelemetryContext().getTracestate()); Assert.assertEquals(TraceContextCorrelationTests.getTracestateHeaderValue("id2"), ThreadContext.getRequestTelemetryContext().getTracestate().toString()); }
private boolean invokeSafeOnBeginRequest(ServletRequest req, ServletResponse res) { if (!isInitialized) { return false; } boolean success = true; try { RequestTelemetryContext context = new RequestTelemetryContext(new Date().getTime(), (HttpServletRequest) req); ThreadContext.setRequestTelemetryContext(context); webModulesContainer.invokeOnBeginRequest(req, res); } catch (Exception e) { InternalLogger.INSTANCE.error( "Failed to invoke OnBeginRequest on telemetry modules with the following exception: %s", ExceptionUtils.getStackTrace(e)); success = false; } return success; }
/** * Generates child TraceParent by retrieving values from ThreadLocal. * @return Outbound Traceparent */ public static String generateChildDependencyTraceparent() { try { RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext(); //check if context is null, no incoming request is present. // This is likely worker role scenario, where a worker is trying // to create a new outbound call, so generate a new traceparent. if (context == null) { return new Traceparent().toString(); } RequestTelemetry requestTelemetry = context.getHttpRequestTelemetry(); String traceId = requestTelemetry.getContext().getOperation().getId(); Traceparent tp = new Traceparent(0, traceId, null, context.getTraceflag()); // We need to propagate full blown traceparent header. return tp.toString(); } catch (Exception ex) { InternalLogger.INSTANCE.error("Failed to generate child ID. Exception information: %s", ex.toString()); InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(ex)); } return null; }