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

Makes SpanBytesDecoder work on ByteBuffer #2589

Merged
merged 9 commits into from
May 15, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
7 changes: 7 additions & 0 deletions benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@
<groupId>org.apache.zipkin.proto3</groupId>
<artifactId>zipkin-proto3</artifactId>
</dependency>

<dependency>
<groupId>${project.groupId}.zipkin2</groupId>
<artifactId>zipkin-tests</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
104 changes: 104 additions & 0 deletions benchmarks/src/main/java/zipkin2/codec/JsonCodecBenchmarks.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 zipkin2.codec;

import com.google.common.io.Resources;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import zipkin2.Span;

@Measurement(iterations = 5, time = 1)
@Warmup(iterations = 10, time = 1)
@Fork(3)
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
@Threads(1)
public class JsonCodecBenchmarks {
static final MoshiSpanDecoder MOSHI = MoshiSpanDecoder.create();

static final byte[] clientSpanJsonV2 = read("/zipkin2-client.json");
static final Span clientSpan = SpanBytesDecoder.JSON_V2.decodeOne(clientSpanJsonV2);

// Assume a message is 1000 spans (which is a high number for as this is per-node-second)
static final List<Span> spans = Collections.nCopies(1000, clientSpan);
static final byte[] encodedBytes = SpanBytesEncoder.JSON_V2.encodeList(spans);

private ByteBuf encodedBuf;

@Setup public void setup() {
encodedBuf = PooledByteBufAllocator.DEFAULT.buffer(encodedBytes.length);
encodedBuf.writeBytes(encodedBytes);
}

@TearDown public void tearDown() {
encodedBuf.release();
}

@Benchmark public List<Span> bytes_moshiDecoder() {
return MOSHI.decodeList(encodedBytes);
}

@Benchmark public List<Span> bytes_zipkinDecoder() {
return SpanBytesDecoder.JSON_V2.decodeList(encodedBytes);
}

@Benchmark public List<Span> bytebuffer_moshiDecoder() {
return MOSHI.decodeList(encodedBuf.nioBuffer());
}

@Benchmark public List<Span> bytebuffer_zipkinDecoder() {
return SpanBytesDecoder.JSON_V2.decodeList(encodedBuf.nioBuffer());
}

// Convenience main entry-point
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(".*" + JsonCodecBenchmarks.class.getSimpleName())
.addProfiler("gc")
.build();

new Runner(opt).run();
}

static byte[] read(String resource) {
try {
return Resources.toByteArray(Resources.getResource(CodecBenchmarks.class, resource));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
95 changes: 95 additions & 0 deletions benchmarks/src/main/java/zipkin2/codec/MoshiSpanDecoder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 zipkin2.codec;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Timeout;
import zipkin2.Span;
import zipkin2.elasticsearch.ElasticsearchAccess;

/**
* Read-only json adapters resurrected from before we switched to Java 6 as storage components can
* be Java 7+
*/
public final class MoshiSpanDecoder {
final JsonAdapter<List<Span>> listSpansAdapter;

public static MoshiSpanDecoder create() {
return new MoshiSpanDecoder();
}

MoshiSpanDecoder() {
listSpansAdapter = new Moshi.Builder()
.add(Span.class, ElasticsearchAccess.jsonSpanAdapter())
.build().adapter(Types.newParameterizedType(List.class, Span.class));
}

public List<Span> decodeList(byte[] spans) {
BufferedSource source = new Buffer().write(spans);
try {
return listSpansAdapter.fromJson(source);
} catch (IOException e) {
throw new AssertionError(e); // no I/O
}
}

public List<Span> decodeList(ByteBuffer spans) {
try {
return listSpansAdapter.fromJson(JsonReader.of(Okio.buffer(new ByteBufferSource(spans))));
} catch (IOException e) {
throw new AssertionError(e); // no I/O
}
}

final class ByteBufferSource implements okio.Source {
final ByteBuffer source;

final Buffer.UnsafeCursor cursor = new Buffer.UnsafeCursor();

ByteBufferSource(ByteBuffer source) {
this.source = source;
}

@Override public long read(Buffer sink, long byteCount) {
try (Buffer.UnsafeCursor ignored = sink.readAndWriteUnsafe(cursor)) {
long oldSize = sink.size();
int length = (int) Math.min(source.remaining(), Math.min(8192, byteCount));
if (length == 0) return -1;
cursor.expandBuffer(length);
source.get(cursor.data, cursor.start, length);
cursor.resizeBuffer(oldSize + length);
return length;
}
}

@Override public Timeout timeout() {
return Timeout.NONE;
}

@Override public void close() {
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public List<Span> bytes_wireDecoder() {

@Benchmark
public List<Span> bytebuffer_zipkinDecoder() {
return SpanBytesDecoder.PROTO3.decodeList(ByteBufUtil.getBytes(encodedBuf));
return SpanBytesDecoder.PROTO3.decodeList(encodedBuf.nioBuffer());
Copy link
Member Author

Choose a reason for hiding this comment

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

here is us decoding directly the bytebuffer in benchmarks

}

@Benchmark
Expand All @@ -103,7 +103,7 @@ public List<Span> bytebuffer_wireDecoder() {
// Convenience main entry-point
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(".*" + ProtoCodecBenchmarks.class.getSimpleName() + ".*bytes.*")
.include(".*" + ProtoCodecBenchmarks.class.getSimpleName())
.addProfiler("gc")
.build();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 zipkin2.elasticsearch;

import com.squareup.moshi.JsonAdapter;
import zipkin2.Span;

public class ElasticsearchAccess {
public static JsonAdapter<Span> jsonSpanAdapter() {
return JsonAdapters.SPAN_ADAPTER;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
@Threads(1)
public class UnsafeBufferBenchmarks {
public class WriteBufferBenchmarks {
static final Charset UTF_8 = Charset.forName("UTF-8");
// Order id = d07c4daa-0fa9-4c03-90b1-e06c4edae250 doesn't exist
static final String CHINESE_UTF8 = "订单d07c4daa-0fa9-4c03-90b1-e06c4edae250不存在";
Expand All @@ -50,52 +50,50 @@ public class UnsafeBufferBenchmarks {
static final int TEST_INT = 1024;
/* epoch micros timestamp */
static final long TEST_LONG = 1472470996199000L;
UnsafeBuffer buffer = UnsafeBuffer.allocate(8);
byte[] bytes = new byte[8];
WriteBuffer buffer = WriteBuffer.wrap(bytes);

@Benchmark public int utf8SizeInBytes_chinese() {
return UnsafeBuffer.utf8SizeInBytes(CHINESE_UTF8);
return WriteBuffer.utf8SizeInBytes(CHINESE_UTF8);
}

@Benchmark public byte[] writeUtf8_chinese() {
UnsafeBuffer bufferUtf8 = UnsafeBuffer.allocate(CHINESE_UTF8_SIZE);
bufferUtf8.writeUtf8(CHINESE_UTF8);
return bufferUtf8.unwrap();
byte[] bytesUtf8 = new byte[CHINESE_UTF8_SIZE];
WriteBuffer.wrap(bytesUtf8, 0).writeUtf8(CHINESE_UTF8);
return bytesUtf8;
}

@Benchmark public ByteBuffer writeUtf8_chinese_jdk() {
return UTF_8.encode(CHINESE_UTF8);
}

@Benchmark public int varIntSizeInBytes_32() {
return UnsafeBuffer.varintSizeInBytes(TEST_INT);
return WriteBuffer.varintSizeInBytes(TEST_INT);
}

@Benchmark public int varIntSizeInBytes_64() {
return UnsafeBuffer.varintSizeInBytes(TEST_LONG);
return WriteBuffer.varintSizeInBytes(TEST_LONG);
}

@Benchmark public int writeVarint_32() {
buffer.reset();
buffer.writeVarint(TEST_INT);
return buffer.pos();
}

@Benchmark public int writeVarint_64() {
buffer.reset();
buffer.writeVarint(TEST_LONG);
return buffer.pos();
}

@Benchmark public int writeLongLe() {
buffer.reset();
buffer.writeLongLe(TEST_LONG);
return buffer.pos();
}

// Convenience main entry-point
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + UnsafeBufferBenchmarks.class.getSimpleName() + ".*")
.include(".*" + WriteBufferBenchmarks.class.getSimpleName() + ".*")
.build();

new Runner(opt).run();
Expand Down
40 changes: 40 additions & 0 deletions benchmarks/src/test/java/zipkin2/codec/MoshiSpanDecoderTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 zipkin2.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static zipkin2.TestObjects.TRACE;

public class MoshiSpanDecoderTest {
byte[] encoded = SpanBytesEncoder.JSON_V2.encodeList(TRACE);

@Test public void decodeList_bytes() {
assertThat(new MoshiSpanDecoder().decodeList(encoded))
.isEqualTo(TRACE);
}

@Test public void decodeList_byteBuffer() {
ByteBuf encodedBuf = PooledByteBufAllocator.DEFAULT.buffer(encoded.length);
encodedBuf.writeBytes(encoded);
assertThat(new MoshiSpanDecoder().decodeList(encoded))
.isEqualTo(TRACE);
}
}
Loading