Skip to content

Commit

Permalink
Start binding distributed tracing into selenium
Browse files Browse the repository at this point in the history
There are two major camps in the java world that
are important for distributed tracing. The first
is OpenTracing, the second is OpenCensus. By
supporting both of these, it becomes significantly
easier to hook Selenium into any system that can
be used for visualising distributed traces.

Right now, we've wired up a no-op implementation
that is mostly harmless. The next step along the
path will be to make it easy to use either Jaeger
or Zipkin with this.
  • Loading branch information
shs96c committed Nov 10, 2018
1 parent 72bc0f0 commit 6aa186b
Show file tree
Hide file tree
Showing 11 changed files with 557 additions and 16 deletions.
3 changes: 3 additions & 0 deletions java/client/src/org/openqa/selenium/remote/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ java_library(name = 'remote-lib',
'mobile/RemoteNetworkConnection.java',
] + glob([
'service/*.java',
'tracing/*.java',
]),
resources = [
':get-attribute',
Expand All @@ -137,6 +138,8 @@ java_library(name = 'remote-lib',
deps = [
':http-session-id',
'//java/client/src/org/openqa/selenium:selenium',
'//third_party/java/opencensus:opencensus-api',
'//third_party/java/opentracing:opentracing-noop',
'//third_party/java/guava:guava',
],
)
Expand Down
32 changes: 20 additions & 12 deletions java/client/src/org/openqa/selenium/remote/HttpCommandExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import com.google.common.collect.ImmutableMap;

import org.openqa.selenium.BuildInfo;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.UnsupportedCommandException;
Expand All @@ -36,6 +37,8 @@
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.tracing.DistributedTracer;
import org.openqa.selenium.remote.tracing.Span;

import java.io.IOException;
import java.net.MalformedURLException;
Expand Down Expand Up @@ -127,30 +130,35 @@ public Response execute(Command command) throws IOException {
}
}

DistributedTracer tracer = DistributedTracer.getInstance();

if (NEW_SESSION.equals(command.getName())) {
if (commandCodec != null) {
throw new SessionNotCreatedException("Session already exists");
}
ProtocolHandshake handshake = new ProtocolHandshake();
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
ProtocolHandshake.Result result = handshake.createSession(client, command);
Dialect dialect = result.getDialect();
commandCodec = dialect.getCommandCodec();
for (Map.Entry<String, CommandInfo> entry : additionalCommands.entrySet()) {
defineCommand(entry.getKey(), entry.getValue());
try (Span span = tracer.createSpan("new-session", tracer.getActiveSpan())) {
ProtocolHandshake handshake = new ProtocolHandshake();
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
ProtocolHandshake.Result result = handshake.createSession(client, command);
Dialect dialect = result.getDialect();
commandCodec = dialect.getCommandCodec();
for (Map.Entry<String, CommandInfo> entry : additionalCommands.entrySet()) {
defineCommand(entry.getKey(), entry.getValue());
}
responseCodec = dialect.getResponseCodec();
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));
return result.createResponse();
}
responseCodec = dialect.getResponseCodec();
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));
return result.createResponse();
}

if (commandCodec == null || responseCodec == null) {
throw new WebDriverException(
"No command or response codec has been defined. Unable to proceed");
"No command or response codec has been defined. Unable to proceed");
}

HttpRequest httpRequest = commandCodec.encode(command);
try {
try (Span span = tracer.createSpan(command.getName(), tracer.getActiveSpan())) {
span.addTag("selenium-sessionid", String.valueOf(command.getSessionId()));
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
HttpResponse httpResponse = client.execute(httpRequest);
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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 org.openqa.selenium.remote.tracing;

import com.google.common.collect.ImmutableSet;

import java.util.Objects;

class CompoundSpan implements Span {

private final DistributedTracer tracer;
private final ImmutableSet<Span> allSpans;

public CompoundSpan(DistributedTracer tracer, ImmutableSet<Span> allSpans) {
this.tracer = Objects.requireNonNull(tracer);
this.allSpans = Objects.requireNonNull(allSpans);
}

@Override
public Span activate() {
allSpans.forEach(Span::activate);

// It's important we do this last, since the activations of all the wrapped spans has caused
// them to _also_ attempt to set themselves as the active span.
tracer.setActiveSpan(this);
return this;
}

@Override
public Span createChild(String operation) {
ImmutableSet.Builder<Span> allChildren = ImmutableSet.builder();
allSpans.forEach(span -> allChildren.add(span.createChild(operation)));

CompoundSpan child = new CompoundSpan(tracer, allChildren.build());
return child.activate();
}

@Override
public Span addTraceTag(String key, String value) {
Objects.requireNonNull(key, "Key must be set");
allSpans.forEach(span -> span.addTraceTag(key, value));
return this;
}

@Override
public Span addTag(String key, String value) {
Objects.requireNonNull(key, "Key must be set");
allSpans.forEach(span -> span.addTag(key, value));
return this;
}

@Override
public Span addTag(String key, boolean value) {
Objects.requireNonNull(key, "Key must be set");
allSpans.forEach(span -> span.addTag(key, value));
return this;
}

@Override
public Span addTag(String key, long value) {
Objects.requireNonNull(key, "Key must be set");
allSpans.forEach(span -> span.addTag(key, value));
return this;
}

@Override
public void close() {
allSpans.forEach(Span::close);
tracer.remove(this);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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 org.openqa.selenium.remote.tracing;

import com.google.common.collect.ImmutableSet;

import org.openqa.selenium.BuildInfo;

import io.opentracing.noop.NoopTracerFactory;

import java.util.LinkedList;
import java.util.Objects;

/**
* Represents an entry point for accessing all aspects of distributed tracing.
*/
public class DistributedTracer {

private static volatile DistributedTracer INSTANCE = DistributedTracer.builder().build();
private static final ThreadLocal<LinkedList<Span>> ACTIVE_SPANS =
ThreadLocal.withInitial(LinkedList::new);
private final ImmutableSet<io.opencensus.trace.Tracer> ocTracers;
private final ImmutableSet<io.opentracing.Tracer> otTracers;

private DistributedTracer(
ImmutableSet<io.opencensus.trace.Tracer> ocTracers,
ImmutableSet<io.opentracing.Tracer> otTracers) {
this.ocTracers = Objects.requireNonNull(ocTracers);
this.otTracers = Objects.requireNonNull(otTracers);
}

public static DistributedTracer getInstance() {
return INSTANCE;
}

public synchronized void setInstance(DistributedTracer distributedTracer) {
INSTANCE = distributedTracer;
}

public static Builder builder() {
return new Builder();
}

/**
* A distributed trace is made of a series of {@link Span}s, which are either
* independent or have a parent/child relationship. Creating a span will make
* it the currently active {@code Span}, as returned by
* {@link #getActiveSpan()}.
*
* @param parent The parent span. If this is {@code null}, then the span is
* assumed to be independent.
*/
public Span createSpan(String operation, Span parent) {
if (parent != null) {
Span child = parent.createChild(operation);
setActiveSpan(child);
return child;
}

ImmutableSet.Builder<Span> spans = ImmutableSet.builder();

for (io.opencensus.trace.Tracer tracer : ocTracers) {
spans.add(new OpenCensusSpan(this, tracer, null, "root"));
}

for (io.opentracing.Tracer tracer : otTracers) {
spans.add(new OpenTracingSpan(this, tracer, null, "root"));
}

Span child = new CompoundSpan(this, spans.build());
child.addTraceTag("selenium-version", new BuildInfo().getReleaseLabel());
child.addTag("selenium-client", "java");
setActiveSpan(child);
return child;
}

/**
* Each thread can have one currently active span. This can be accessed via
* this method. If there is no currently active span, then a new one will
* be created. Should a new span be created, it will be set as the currently
* active span.
*/
public Span getActiveSpan() {
if (ACTIVE_SPANS.get().isEmpty()) {
return null;
}

return ACTIVE_SPANS.get().getLast().activate();
}

void setActiveSpan(Span span) {
ACTIVE_SPANS.get().add(span);
}

void remove(Span span) {
Objects.requireNonNull(span, "Span to remove must not be null");

ACTIVE_SPANS.get().removeIf(span::equals);
}

public static class Builder {

private ImmutableSet.Builder<io.opencensus.trace.Tracer> ocTracers = ImmutableSet.builder();
private ImmutableSet.Builder<io.opentracing.Tracer> otTracers = ImmutableSet.builder();

private Builder() {
// Only accessible through the parent class

// Make sure we have at least one tracer, but make it one that does nothing.
register(NoopTracerFactory.create());
}

public Builder register(io.opentracing.Tracer openTracingTracer) {
otTracers.add(Objects.requireNonNull(openTracingTracer, "Tracer must be set."));
return this;
}

public Builder register(io.opencensus.trace.Tracer openCensusTracer) {
ocTracers.add(Objects.requireNonNull(openCensusTracer, "Tracer must be set."));
return this;
}

public DistributedTracer build() {
return new DistributedTracer(ocTracers.build(), otTracers.build());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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 org.openqa.selenium.remote.tracing;

import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Tracer;

import java.util.Objects;

class OpenCensusSpan implements Span {

private final io.opencensus.trace.Span span;
private final DistributedTracer distributedTracer;
private final Tracer tracer;

OpenCensusSpan(
DistributedTracer distributedTracer,
Tracer tracer,
io.opencensus.trace.Span parent,
String operation) {
this.distributedTracer = Objects.requireNonNull(distributedTracer);
this.tracer = Objects.requireNonNull(tracer);
this.span = tracer.spanBuilderWithExplicitParent(operation, parent).startSpan();
activate();
}

@Override
public Span activate() {
tracer.withSpan(span);
distributedTracer.setActiveSpan(this);
return this;
}

@Override
public Span addTraceTag(String key, String value) {
span.putAttribute(Objects.requireNonNull(key), AttributeValue.stringAttributeValue(value));
return this;
}

@Override
public Span addTag(String key, String value) {
span.putAttribute(Objects.requireNonNull(key), AttributeValue.stringAttributeValue(value));
return this;
}

@Override
public Span addTag(String key, boolean value) {
span.putAttribute(Objects.requireNonNull(key), AttributeValue.booleanAttributeValue(value));
return this;
}

@Override
public Span addTag(String key, long value) {
span.putAttribute(Objects.requireNonNull(key), AttributeValue.longAttributeValue(value));
return this;
}

@Override
public Span createChild(String operation) {
Span child = new OpenCensusSpan(distributedTracer, tracer, span, operation);
return child.activate();
}

@Override
public void close() {
span.end();
distributedTracer.remove(this);
}

}
Loading

0 comments on commit 6aa186b

Please sign in to comment.