Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log correlation remake suggestions #4

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@
import co.elastic.apm.agent.bci.classloading.IndyPluginClassLoader;
import co.elastic.apm.agent.bci.classloading.LookupExposer;
import co.elastic.apm.agent.common.JvmRuntimeInfo;
import co.elastic.apm.agent.sdk.logging.Logger;
import co.elastic.apm.agent.sdk.logging.LoggerFactory;
import co.elastic.apm.agent.sdk.state.CallDepth;
import co.elastic.apm.agent.sdk.state.GlobalState;
import co.elastic.apm.agent.util.PackageScanner;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.loading.ClassInjector;
import co.elastic.apm.agent.sdk.logging.Logger;
import co.elastic.apm.agent.sdk.logging.LoggerFactory;
import org.stagemonitor.configuration.ConfigurationOptionProvider;
import org.stagemonitor.util.IOUtils;

Expand Down Expand Up @@ -211,6 +212,8 @@ public class IndyBootstrap {
@Nullable
static Method indyBootstrapMethod;

private static final CallDepth callDepth = CallDepth.get(IndyBootstrap.class);

public static Method getIndyBootstrapMethod(final Logger logger) {
if (indyBootstrapMethod != null) {
return indyBootstrapMethod;
Expand Down Expand Up @@ -356,6 +359,12 @@ public static ConstantCallSite bootstrap(MethodHandles.Lookup lookup,
MethodType adviceMethodType,
Object... args) {
try {
if (callDepth.isNestedCallAndIncrement()) {
// avoid re-entrancy and stack overflow errors
// may happen when bootstrapping an instrumentation that also gets triggered during the bootstrap
// for example, adding correlation ids to the thread context when executing logger.debug
return null;
}
Comment on lines +362 to +367
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that an issue related to us instrumenting our own logging?
If that so, the proper handling is to avoid instrumenting it. I did it through getClassLoaderMatcher.
I am not opposed to this safety check, but it should be treated as such - log an error before returning null.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMHO, we'll also want to instrument our logging so that we also have correlation IDs in the agent logs.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having correlation IDs within the agent logs is a great idea, but I think the proper way to achieve that is through direct addition to the MDC. We can use an ActivationListener for that.
Instrumenting classes loaded by the agent class loader can open a can of worms. It would create a plugin CL for it and treat the agent CL as the target CL. This deviates from anything our complicated class loading hierarchy is designed for, so I really think we should avoid that.

String adviceClassName = (String) args[0];
int enter = (Integer) args[1];
Class<?> instrumentedType = (Class<?>) args[2];
Expand Down Expand Up @@ -411,6 +420,8 @@ public static ConstantCallSite bootstrap(MethodHandles.Lookup lookup,
// must not be a static field as it would initialize logging before it's ready
LoggerFactory.getLogger(IndyBootstrap.class).error(e.getMessage(), e);
return null;
} finally {
callDepth.decrement();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,12 @@
import co.elastic.apm.agent.sdk.state.CallDepth;

import javax.annotation.Nullable;
import java.util.Map;

public abstract class AbstractLogCorrelationHelper {

private static final CallDepth callDepth = CallDepth.get(AbstractLogCorrelationHelper.class);

public static final String TRACE_ID_MDC_KEY = "trace.id";
public static final String TRANSACTION_ID_MDC_KEY = "transaction.id";

/**
* Adds the active transaction's ID and trace ID to the MDC in the outmost logging API call
* @param activeTransaction the currently active transaction, or {@code null} if there is no such
Expand All @@ -39,8 +37,9 @@ public boolean beforeLoggingApiCall(@Nullable Transaction activeTransaction) {
if (callDepth.isNestedCallAndIncrement() || activeTransaction == null) {
return false;
}
addToMdc(TRACE_ID_MDC_KEY, activeTransaction.getTraceContext().getTraceId().toString());
addToMdc(TRANSACTION_ID_MDC_KEY, activeTransaction.getTraceContext().getTransactionId().toString());
addToMdc(CorrelationIdMapAdapter.TRACE_ID, activeTransaction.getTraceContext().getTraceId().toString());
addToMdc(CorrelationIdMapAdapter.TRANSACTION_ID, activeTransaction.getTraceContext().getTransactionId().toString());
addToMdc(CorrelationIdMapAdapter.get());
return true;
}

Expand All @@ -50,12 +49,21 @@ public boolean beforeLoggingApiCall(@Nullable Transaction activeTransaction) {
*/
public void afterLoggingApi(boolean added) {
if (callDepth.isNestedCallAndDecrement() && added) {
removeFromMdc(TRACE_ID_MDC_KEY);
removeFromMdc(TRANSACTION_ID_MDC_KEY);
removeFromMdc(CorrelationIdMapAdapter.TRACE_ID);
removeFromMdc(CorrelationIdMapAdapter.TRANSACTION_ID);
removeFromMdc(CorrelationIdMapAdapter.allKeys());
}
}

protected abstract void addToMdc(String key, String value);
protected void addToMdc(String key, String value) {
}

protected void addToMdc(Map<String, String> correlationIds) {
}

protected abstract void removeFromMdc(String key);
protected void removeFromMdc(String key) {
}

protected void removeFromMdc(Iterable<String> correlationIdKeys) {
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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 co.elastic.apm.agent.log.shader;

import co.elastic.apm.agent.impl.GlobalTracer;
import co.elastic.apm.agent.impl.Tracer;
import co.elastic.apm.agent.impl.transaction.Transaction;

import javax.annotation.Nullable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable;

public class CorrelationIdMapAdapter extends AbstractMap<String, String> {

public static final String TRACE_ID = "trace.id";
public static final String TRANSACTION_ID = "transaction.id";
public static final String SPAN_ID = "span.id";

private static final CorrelationIdMapAdapter INSTANCE = new CorrelationIdMapAdapter();
private static final Set<Entry<String, String>> ENTRY_SET = new TraceIdentifierEntrySet();
private static final List<String> ALL_KEYS = Arrays.asList(TRACE_ID, TRANSACTION_ID/*, SPAN_ID*/);
private static final Tracer tracer = GlobalTracer.get();
private static final List<Entry<String, String>> ENTRIES = Arrays.<Entry<String, String>>asList(
new LazyEntry(TRACE_ID, new Callable<String>() {
@Override
@Nullable
public String call() {
Transaction transaction = tracer.currentTransaction();
if (transaction == null) {
return null;
}
return transaction.getTraceContext().getTraceId().toString();
}
}),
new LazyEntry(TRANSACTION_ID, new Callable<String>() {
@Override
@Nullable
public String call() {
Transaction transaction = tracer.currentTransaction();
if (transaction == null) {
return null;
}
return transaction.getTraceContext().getId().toString();
}
})/*,
new LazyEntry(SPAN_ID, new Callable<String>() {
@Override
@Nullable
public String call() {
Span span = tracer.getActiveSpan();
if (span == null) {
return null;
}
return span.getTraceContext().getId().toString();
}
})*/
);

public static Map<String, String> get() {
return INSTANCE;
}

public static Iterable<String> allKeys() {
return ALL_KEYS;
}

private CorrelationIdMapAdapter() {
}

@Override
public Set<Entry<String, String>> entrySet() {
return ENTRY_SET;
}

private static class TraceIdentifierEntrySet extends AbstractSet<Entry<String, String>> {

@Override
public int size() {
int size = 0;
for (Entry<String, String> ignored : this) {
size++;
}
return size;
}

@Override
public Iterator<Entry<String, String>> iterator() {
return new Iterator<Entry<String, String>>() {
private int i = 0;
@Nullable
private Entry<String, String> next = findNext();

@Override
public boolean hasNext() {
return next != null;
}

@Override
public Entry<String, String> next() {
if (next != null) {
try {
return next;
} finally {
next = findNext();
}
} else {
throw new NoSuchElementException();
}
}

@Nullable
private Entry<String, String> findNext() {
Entry<String, String> next = null;
while (next == null && i < ENTRIES.size()) {
next = ENTRIES.get(i++);
if (next.getValue() == null) {
next = null;
}
}
return next;
}
};
}

}

private static class LazyEntry implements Entry<String, String> {
private final String key;
private final Callable<String> valueSupplier;

private LazyEntry(String key, Callable<String> valueSupplier) {
this.key = key;
this.valueSupplier = valueSupplier;
}

@Override
public String getKey() {
return this.key;
}

@Override
public String getValue() {
try {
return this.valueSupplier.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@Override
public String setValue(String value) {
throw new UnsupportedOperationException();
}
}
}
Loading