opentelemetry-java-instrumentation icon indicating copy to clipboard operation
opentelemetry-java-instrumentation copied to clipboard

HttpUrlConnectionInstrumentationModule may leak spans

Open vovencij opened this issue 5 years ago • 7 comments

Describe the bug Current implementation of java.net.HttpURLConnection instrumentation in io.opentelemetry.javaagent.instrumentation.httpurlconnection.HttpUrlConnectionInstrumentationModule may leak spans.

io.opentelemetry.javaagent.instrumentation.httpurlconnection.HttpUrlConnectionInstrumentationModule.HttpUrlConnectionAdvice#methodEnter starts spans on connect, getOutputStream and getInputStream methods, but io.opentelemetry.javaagent.instrumentation.httpurlconnection.HttpUrlConnectionInstrumentationModule.HttpUrlConnectionAdvice#methodExit closes spans only on getInputStream or exception. If for some reason getInputStream won't be called, span will leak.

vovencij avatar Jan 22 '21 08:01 vovencij

@vovencij what's an example of this? e.g. sending a POST request and not reading the response? thx

trask avatar Jan 25 '21 18:01 trask

For example, If you do connect() which would throw an Exception, so that getInputStream() will be never called.

Following example ends with OOM:

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class SpanLeak {

  public static void main(String[] args) throws IOException {
    while (true) {
      try {
        InputStream inputStream = getConnection().getInputStream();
        inputStream.readAllBytes();
      } catch (IOException ignored) {

      }
    }
  }

  private static URLConnection getConnection() throws IOException {
    var url = new URL("http://this-domain-is-probably-not-existant.com");
    var connection = url.openConnection();
    connection.connect();
    return connection;
  }
}

Heap dump says that I have lots of spans on the heap: image

vovencij avatar Jan 26 '21 08:01 vovencij

the memory leak aspect of this issue is surprising, what's the retention path for those spans?

trask avatar Jan 27 '21 02:01 trask

They were in BatchSpanProcessor. To get results faster I tried to run with -Xmx=16m - with this much memory happy-path with resolvable domain worked without OOMing. Increasing Xmx to 32m also eliminated OOM in this example, because exporter had a chance to run. Setting otel.bsp.schedule.delay.millis to something very small also eliminates OOM in this case even with xmx16m.

So the memory leak is apparently not the case, indeed.

vovencij avatar Jan 27 '21 07:01 vovencij

hey @vovencij! do you think there is something here that should still be addressed?

trask avatar May 09 '21 04:05 trask

this is related: #875

trask avatar May 09 '21 05:05 trask

I think if the memory leak is not the case here, then this can be closed.

vovencij avatar May 14 '21 12:05 vovencij