diff --git a/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java b/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java index 066e30bd4..78d8955b6 100644 --- a/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/BytesChronicleMap.java @@ -147,9 +147,13 @@ public class BytesChronicleMap implements AbstractChronicleMap { Bytes prevValue = prevValueOnPut(c); c.newTimestamp = timestamp; c.newIdentifier = id; - c.writeReplicationBytes(); + //c.writeReplicationBytes(); c.put(value); return prevValue; } } + + + + } diff --git a/src/main/java/net/openhft/chronicle/map/ChannelListProvider.java b/src/main/java/net/openhft/chronicle/map/ChannelListProvider.java deleted file mode 100644 index bd8dde12f..000000000 --- a/src/main/java/net/openhft/chronicle/map/ChannelListProvider.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2014 Higher Frequency Trading - * - * http://www.higherfrequencytrading.com - * - * Licensed 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 net.openhft.chronicle.map; - -import java.util.List; - -/** - * Created by Rob Austin - */ -public interface ChannelListProvider { - List chronicleChannelList(); -} diff --git a/src/main/java/net/openhft/chronicle/map/ChannelProvider.java b/src/main/java/net/openhft/chronicle/map/ChannelProvider.java index df180beb2..c5ba83b94 100644 --- a/src/main/java/net/openhft/chronicle/map/ChannelProvider.java +++ b/src/main/java/net/openhft/chronicle/map/ChannelProvider.java @@ -48,7 +48,7 @@ import static net.openhft.chronicle.map.Replica.ModificationNotifier.NOP; /** * @author Rob Austin. */ -final class ChannelProvider implements Closeable, ChannelListProvider { +final class ChannelProvider implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ChannelProvider.class.getName()); static final Map implMapping = new IdentityHashMap<>(); @@ -70,7 +70,7 @@ final class ChannelProvider implements Closeable, ChannelListProvider { hub.remoteNodeValidator(), null, hub.name(), - null); + channelProvider.chronicleChannelList()); channelProvider.add(tcpReplicator); } @@ -268,8 +268,8 @@ final class ChannelProvider implements Closeable, ChannelListProvider { // start of channel data private final Replica[] chronicleChannels; - @Override - public List chronicleChannelList() { + + private List chronicleChannelList() { return Collections.unmodifiableList(chronicleChannelList); } diff --git a/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java b/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java index 0aeed758c..14c888f0f 100644 --- a/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java @@ -23,7 +23,6 @@ import net.openhft.chronicle.hash.hashing.LongHashFunction; import net.openhft.chronicle.hash.impl.ContextFactory; import net.openhft.chronicle.hash.impl.HashContext; import net.openhft.chronicle.hash.replication.AbstractReplication; -import net.openhft.chronicle.hash.replication.LateUpdateException; import net.openhft.chronicle.hash.replication.TimeProvider; import net.openhft.chronicle.hash.serialization.BytesReader; import net.openhft.chronicle.hash.serialization.internal.BytesBytesInterop; @@ -376,8 +375,12 @@ final class ReplicatedChronicleMap channelList; - private ArrayList bytesChronicleMaps = new ArrayList<>(); - private TextWire inWire = new TextWire(Bytes.elasticByteBuffer()); - private TextWire outWire = new TextWire(Bytes.elasticByteBuffer()); - - - MapIOBuffer mapIOBuffer = new MapIOBuffer() { + private final byte localIdentifier; + private final StringBuilder methodName = new StringBuilder(); + private final ByteBuffer resultBuffer = ByteBuffer.allocateDirect(64); + private ByteBuffer inLanByteBuffer = ByteBuffer.allocateDirect(64); + private final MapIOBuffer mapIOBuffer = new MapIOBuffer() { @Override - public void ensureBufferSize(long l) { - outWire.bytes().ensureCapacity(l); + public void ensureBufferSize(long size) { + + if (inLanByteBuffer.capacity() < size) + // reallocate the buffer in chunks of OS.pageSize() bytes + inLanByteBuffer = ByteBuffer.allocateDirect(OS.pageSize() * (1 + (int) (size / OS.pageSize()))); + + + outWire.bytes().ensureCapacity(size); + try { + + // move the lang byte buffer so that its pointing to the same memory as the wireBuffer + long address = BB_ADDRESS.getLong(inLanByteBuffer); + NATIVE_ADDRESS.invoke(inLangBytes, address); + NATIVE_CAPACITY.invoke(inLangBytes, size + address); + inLangBytes.limit(size); + } catch (Exception e) { + throw new RuntimeException(e); + } + } /** * maps the outWire.bytes() to lang bytes + * * @return lang bytes that represent the {@code outWire.bytes()} */ @Override public net.openhft.lang.io.Bytes in() { - try { - ByteBuffer buffer = (ByteBuffer) outWire.bytes().underlyingObject(); - langBytes.address(ADDRESS.getLong(buffer)); - langBytes.capacity(CAPACITY.getLong(buffer)); - langBytes.limit(buffer.limit()); - langBytes.position(buffer.position()); - return langBytes; - } catch (Exception e) { - LOG.error("", e); - } - return langBytes; + return inLangBytes; } }; - - private byte identifier; - private long transactionId; private long timestamp; private short channelId; - private String methodName; + @Nullable + // maybe null if the server has not been set up to use channel + private List channelList; + private byte remoteIdentifier; + private Bytes resultBytes = Bytes.wrap(resultBuffer); + private SelectionKey key; - public StatelessWiredConnector(@Nullable List channelList) { + public StatelessWiredConnector(@Nullable List channelList, byte localIdentifier) { this.channelList = channelList; + // final TextWire inWire = new TextWire(toChronicleBytes(inBytes)); // this.identifier = inWire.read(() -> "IDENTIFIER").int8(); + this.localIdentifier = localIdentifier; } public void onRead(SocketChannel socketChannel, SelectionKey key) throws IOException { - socketChannel.read(inWireBuffer()); + this.key = key; - if (nextWireMessage() == null) + if (!handshingComplete) + outWire.bytes().writeByte(localIdentifier); + + final int len = readSocket(socketChannel); + assert inWire.bytes().remaining() < 999; + if (len == -1) { + socketChannel.close(); return; + } - if (handshingComplete) { - onEvent(); - } else - onHandShaking(); + if (len == 0) { + System.out.println("nothing read"); + return; + } - } + assert inWire.bytes().remaining() < 999; - public void onWrite(SocketChannel socketChannel, SelectionKey key) throws IOException { - socketChannel.write((ByteBuffer) outWire.bytes()); - if (outWire.bytes().remaining() == 0) { - ((ByteBuffer) outWire.bytes().underlyingObject()).clear(); - outWire.bytes().clear(); + System.out.println("remaining=>" + inWire.bytes().remaining()); + + while (inWire.bytes().remaining() > 4) { + + final long limit = inWire.bytes().limit(); + + if (nextWireMessage() == null) { + if (shouldCompactInBufffer()) + compactInBuffer(); + else if (shouldClearInBuffer()) + clearInBuffer(); + return; + } + + if (!handshingComplete) { + System.out.println("doHandshaking"); + + onHandShaking(); + System.out.println("end-doHandshaking"); + } else { + System.out.println("onEvent"); + onEvent(); + System.out.println("end-onEvent"); + } + + System.out.println("limit=>" + outWire.bytes().limit()); + assert inWire.bytes().remaining() < 999; + inWire.bytes().limit(limit); + assert inWire.bytes().remaining() < 999; } } + private void clearInBuffer() { + System.out.println("clear"); + inWire.bytes().clear(); + inWireBuffer().clear(); + } + + private boolean shouldClearInBuffer() { + return inWire.bytes().position() == inWireBuffer().position(); + } + + /** + * @return true if remaining space is less than 50% + */ + private boolean shouldCompactInBufffer() { + return inWire.bytes().position() > 0 && inWire.bytes().remaining() < (inWireBuffer().capacity() / 2); + } + + public void onWrite(SocketChannel socketChannel, SelectionKey key) throws IOException { + + ((ByteBuffer) outWire.bytes().underlyingObject()).limit((int) outWire.bytes().position()); + socketChannel.write((ByteBuffer) outWire.bytes().underlyingObject()); + + if (((ByteBuffer) outWire.bytes().underlyingObject()).remaining() == 0) { + ((ByteBuffer) outWire.bytes().underlyingObject()).clear(); + outWire.bytes().clear(); + key.interestOps(OP_READ); + } + + } + + private void compactInBuffer() { + System.out.println("compacting"); + inWireBuffer().position((int) inWire.bytes().position()); + inWireBuffer().limit(inWireBuffer().position()); + inWireBuffer().compact(); + + inWire.bytes().position(0); + inWire.bytes().limit(0); + } + + private ByteBuffer inWireBuffer() { + return (ByteBuffer) inWire.bytes().underlyingObject(); + } + + private int readSocket(SocketChannel socketChannel) throws IOException { + ByteBuffer dst = inWireBuffer(); + int len = socketChannel.read(dst); + System.out.println("len=" + len); + int readUpTo = dst.position(); + inWire.bytes().limit(readUpTo); + return len; + } private Wire nextWireMessage() { - if (inWireBuffer().remaining() < 4) + if (inWire.bytes().remaining() < 4) return null; final Bytes bytes = inWire.bytes(); @@ -151,21 +265,21 @@ class StatelessWiredConnector "IDENTIFIER").int8(); + remoteIdentifier = inWire.read(() -> "IDENTIFIER").int8(); handshingComplete = true; } @@ -173,10 +287,10 @@ class StatelessWiredConnector "TRANSACTION_ID").int64(); + long transactionId = inWire.read(() -> "TRANSACTION_ID").int64(); timestamp = inWire.read(() -> "TIME_STAMP").int64(); channelId = inWire.read(() -> "CHANNEL_ID").int16(); - methodName = inWire.read(() -> "METHOD_NAME").text(); + inWire.read(() -> "METHOD_NAME").text(methodName); // for the length outWire.bytes().skip(4); @@ -184,56 +298,10 @@ class StatelessWiredConnector "TRANSACTION_ID").int64(transactionId); - switch (methodName) { - - case "PUT": + if ("PUT".contentEquals(methodName)) return put(); - - default: - throw new IllegalStateException("unsupported event=" + methodName); - } - } - - /** - * gets the map for this channel id - * - * @param channelId the ID of the map - * @return the chronicle map with this {@code channelId} - */ - private ReplicatedChronicleMap map(short channelId) { - - // todo this cast is a bit of a hack, improve later - final ReplicatedChronicleMap replicas = - (ReplicatedChronicleMap) channelList.get(channelId - 1); - - if (replicas != null) - return replicas; - - throw new IllegalStateException(); - } - - /** - * this is used to push the data straight into the entry in memory - * - * @param channelId the ID of the map - * @return a BytesChronicleMap used to update the memory which holds the chronicle map - */ - private BytesChronicleMap bytesMap(short channelId) { - - final BytesChronicleMap bytesChronicleMap = bytesChronicleMaps.get(channelId - 1); - - if (bytesChronicleMap != null) - return bytesChronicleMap; - - // grow the array - for (int i = bytesChronicleMaps.size(); i < channelId; i++) { - bytesChronicleMaps.add(null); - } - - final ReplicatedChronicleMap delegate = map(channelId); - final BytesChronicleMap element = new BytesChronicleMap(delegate); - bytesChronicleMaps.set(channelId - 1, element); - return element; + else + throw new IllegalStateException("unsupported event=" + methodName); } @@ -279,20 +347,98 @@ class StatelessWiredConnector 0) { + + BB_ADDRESS.set(resultBuffer, result.address()); + BB_CAPACITY.set(resultBuffer, result.capacity()); + resultBytes.limit(result.capacity()); + + outWire.write(() -> "RESULT_IS_NULL").bool(false); + outWire.write(() -> "RESULT").bytes(resultBytes); + } else { + outWire.write(() -> "RESULT_IS_NULL").bool(true); + } + + key.interestOps(OP_WRITE | OP_READ); + } catch (Throwable e) { + + // todo remove + e.printStackTrace(); + // move back to the start outWire.bytes().position(2); + return sendException(outWire, e); } finally { bytesMap.output = null; diff --git a/src/main/java/net/openhft/chronicle/map/TcpReplicator.java b/src/main/java/net/openhft/chronicle/map/TcpReplicator.java index 024fd0381..df03c31ca 100644 --- a/src/main/java/net/openhft/chronicle/map/TcpReplicator.java +++ b/src/main/java/net/openhft/chronicle/map/TcpReplicator.java @@ -72,7 +72,7 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo public static final long TIMESTAMP_FACTOR = 10000; private static final int STATELESS_CLIENT = -127; - private static final int WIRED_CONNECTION = -126; + public static final int WIRED_CONNECTION = -126; private static final byte NOT_SET = (byte) HEARTBEAT.ordinal(); private static final Logger LOG = LoggerFactory.getLogger(TcpReplicator.class.getName()); private static final int BUFFER_SIZE = 0x100000; // 1MB @@ -783,7 +783,26 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo // sniff just a single byte from the socket and write it to attached.entryReader.in // this way we can switch to StatelessWiredConnector without reading any other data - socketChannel.read(ByteBuffer.wrap(data)); + int len; + for (; ; ) { + len = socketChannel.read(ByteBuffer.wrap(data)); + if (len != 0) + break; + } + + + if (len == -1) { + socketChannel.register(selector, 0); + if (replicationConfig.autoReconnectedUponDroppedConnection()) { + AbstractConnector connector = attached.connector; + if (connector != null) + connector.connectLater(); + } else + socketChannel.close(); + return; + } + + byte b = data[0]; attached.entryReader.in.put(b); attached.entryReader.out.limit(1); @@ -791,7 +810,8 @@ final class TcpReplicator extends AbstractChannelReplicator implements Clo if (b == WIRED_CONNECTION) attached.useWire = true; forceRead = true; - attached.statelessWiredConnector = new StatelessWiredConnector(channelList); + attached.statelessWiredConnector = new StatelessWiredConnector(channelList, localIdentifier); + attached.handShakingComplete = true; } if (attached.useWire) { diff --git a/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java b/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java index 25d232109..a07a15c62 100644 --- a/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java +++ b/src/main/java/net/openhft/chronicle/map/WiredChronicleMapStatelessClientBuilder.java @@ -19,7 +19,6 @@ package net.openhft.chronicle.map; import net.openhft.chronicle.hash.ChronicleHashStatelessClientBuilder; -import net.openhft.chronicle.hash.serialization.internal.SerializationBuilder; import net.openhft.lang.MemoryUnit; import java.io.IOException; @@ -35,9 +34,11 @@ public final class WiredChronicleMapStatelessClientBuilder implements ChronicleMap>, MapBuilder> { - public WiredStatelessClientTcpConnectionHub hub; - public SerializationBuilder keyBuilder; - public SerializationBuilder valueBuilder; + WiredStatelessClientTcpConnectionHub hub; + private Class keyClass; + private Class valueClass; + private byte localIdentifier; + private short channelID; public WiredStatelessClientTcpConnectionHub hub() { return hub; @@ -47,9 +48,11 @@ public final class WiredChronicleMapStatelessClientBuilder implements this.hub = hub; } - static WiredChronicleMapStatelessClientBuilder of( - InetSocketAddress serverAddress) { - return new WiredChronicleMapStatelessClientBuilder<>(serverAddress); + public WiredChronicleMapStatelessClientBuilder(InetSocketAddress remoteAddress, Class keyClass, Class valueClass, short channelID) { + this.keyClass = keyClass; + this.valueClass = valueClass; + this.remoteAddress = remoteAddress; + this.channelID = channelID; } // This method is meaningful, despite you could call of().create(), because Java 7 doesn't @@ -60,18 +63,7 @@ public final class WiredChronicleMapStatelessClientBuilder implements // createClientOf(addr) // static import // -- the second is really shorter. - /** - * Equivalent of {@code ChronicleMapStatelessClientBuilder.of(serverAddress).create()}. - * - * @param serverAddress address of the server map - * @param key type of the map - * @param value type of the map - * @return stateless client of the ChronicleMap of server - */ - public static ChronicleMap createClientOf(InetSocketAddress serverAddress) - throws IOException { - return WiredChronicleMapStatelessClientBuilder.of(serverAddress).create(); - } + private final InetSocketAddress remoteAddress; private boolean putReturnsNull = false; @@ -82,9 +74,7 @@ public final class WiredChronicleMapStatelessClientBuilder implements private final AtomicBoolean used = new AtomicBoolean(false); - WiredChronicleMapStatelessClientBuilder(InetSocketAddress remoteAddress) { - this.remoteAddress = remoteAddress; - } + InetSocketAddress remoteAddress() { return remoteAddress; @@ -145,10 +135,10 @@ public final class WiredChronicleMapStatelessClientBuilder implements // todo clean this up if (hub == null) - hub = new WiredStatelessClientTcpConnectionHub(this); + hub = new WiredStatelessClientTcpConnectionHub(this, localIdentifier); if (!used.getAndSet(true)) { - return new WiredStatelessChronicleMap(this); + return new WiredStatelessChronicleMap(this, keyClass, valueClass, channelID); } else { throw new IllegalStateException( @@ -157,4 +147,8 @@ public final class WiredChronicleMapStatelessClientBuilder implements "to create a new stateless client"); } } + + public void identifier(byte identifier) { + this.localIdentifier = identifier; + } } diff --git a/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java b/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java index e71833344..4e65e03a4 100644 --- a/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/WiredStatelessChronicleMap.java @@ -47,26 +47,29 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable private static final Logger LOG = LoggerFactory.getLogger(WiredStatelessChronicleMap.class); private final WiredStatelessClientTcpConnectionHub hub; - protected Class kClass; protected Class vClass; private boolean putReturnsNull; private boolean removeReturnsNull; + private short channelID; - - WiredStatelessChronicleMap(@NotNull final WiredChronicleMapStatelessClientBuilder config) { + WiredStatelessChronicleMap(@NotNull final WiredChronicleMapStatelessClientBuilder config, + @NotNull final Class kClass, + @NotNull final Class vClass, + short channelID) { + this.channelID = channelID; hub = config.hub; this.putReturnsNull = config.putReturnsNull(); this.removeReturnsNull = config.removeReturnsNull(); - kClass = config.keyBuilder.eClass; - vClass = config.valueBuilder.eClass; + this.kClass = kClass; + this.vClass = vClass; } @SuppressWarnings("UnusedDeclaration") - void identifier(int identifier) { - hub.identifier = identifier; + void identifier(int localIdentifier) { + hub.localIdentifier = localIdentifier; } @Override @@ -108,7 +111,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable public String serverApplicationVersion() { - return hub.serverApplicationVersion(); + return hub.serverApplicationVersion(channelID); } @Override @@ -197,12 +200,12 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable @NotNull public String toString() { - return hub.proxyReturnString(TO_STRING.toString()); + return hub.proxyReturnString(TO_STRING.toString(), channelID); } @NotNull public String serverPersistedDataVersion() { - return hub.proxyReturnString(PERSISTED_DATA_VERSION.toString()); + return hub.proxyReturnString(PERSISTED_DATA_VERSION.toString(), channelID); } public boolean isEmpty() { @@ -261,7 +264,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable public V put(K key, V value) { if (key == null || value == null) throw new NullPointerException(); - return proxyReturnObject(putReturnsNull ? PUT_WITHOUT_ACC.toString() : PUT.toString(), key, value, vClass); + return proxyReturnObject(putReturnsNull ? "PUT_WITHOUT_ACC" : "PUT", key, value, vClass); } @Nullable @@ -327,7 +330,9 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable assert !hub.inBytesLock().isHeldByCurrentThread(); if (value instanceof CharSequence) { + hub.outWire().write(() -> fieldName).text((CharSequence) value); + System.out.println(hub.outWire().bytes().position() + "fieldName=" + fieldName + ",value=" + value); } else if (value instanceof Marshallable) { hub.outWire().write(() -> fieldName).marshallable((Marshallable) value); } else { @@ -345,9 +350,11 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable final Wire wireIn = hub.proxyReply(timeoutTime, transactionId); - if (usingValue == null) { + if (usingValue == null) usingValue = newValueInstance(); - } + + if (wireIn.read(() -> "RESULT_IS_NULL").bool()) + return null; if (usingValue instanceof StringBuilder) { wireIn.read(() -> "RESULT").text((StringBuilder) usingValue); @@ -404,7 +411,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); writeField("ARG_1", key); writeField("ARG_2", value); @@ -428,7 +435,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable long transactionId; hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); writeField("ARG_1", value1); writeField("ARG_2", value2); @@ -448,7 +455,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable long transactionId; hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); writeField("ARG_1", value); hub.writeSocket(); @@ -467,7 +474,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); writeField("ARG_1", key); hub.writeSocket(); @@ -486,7 +493,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); hub.writeSocket(); } finally { @@ -504,7 +511,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); hub.writeSocket(); } finally { @@ -523,7 +530,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); hub.writeSocket(); } finally { @@ -542,7 +549,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); hub.writeSocket(); } finally { @@ -554,9 +561,8 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable @Nullable private R proxyReturnObject(@NotNull final String methodName, K key, V value, Class resultType) { + final long startTime = System.currentTimeMillis(); - - long transactionId; hub.outBytesLock().lock(); @@ -564,16 +570,16 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable assert hub.outBytesLock().isHeldByCurrentThread(); assert !hub.inBytesLock().isHeldByCurrentThread(); - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); - writeField("ARG_2", key); + writeField("ARG_1", key); writeField("ARG_2", value); hub.writeSocket(); + } finally { hub.outBytesLock().unlock(); } - if (eventReturnsNull(methodName)) return null; @@ -593,7 +599,7 @@ class WiredStatelessChronicleMap implements ChronicleMap, Cloneable hub.outBytesLock().lock(); try { - transactionId = hub.writeHeader(startTime); + transactionId = hub.writeHeader(startTime, channelID); writeField("METHOD_NAME", methodName); writeField("ARG_1", key); hub.writeSocket(); diff --git a/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java b/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java index 090e3f0d3..4954ec7ea 100644 --- a/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java +++ b/src/main/java/net/openhft/chronicle/map/WiredStatelessClientTcpConnectionHub.java @@ -39,6 +39,7 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import static net.openhft.chronicle.map.AbstractChannelReplicator.SIZE_OF_SIZE; +import static net.openhft.chronicle.map.AbstractChannelReplicator.openSocketChannel; import static net.openhft.chronicle.map.WiredStatelessChronicleMap.EventId.APPLICATION_VERSION; /** @@ -62,15 +63,12 @@ public class WiredStatelessClientTcpConnectionHub { private final AtomicLong transactionID = new AtomicLong(0); @Nullable protected CloseablesManager closeables; - // used by the enterprise version - protected int identifier; - long largestChunkSoFar = 0; - - //private net.openhft.chronicle.bytes.Bytes outBytes; - private Wire outWire = new TextWire(Bytes.elasticByteBuffer()); - - private Wire intWire = new TextWire(Bytes.elasticByteBuffer()); + private final Wire outWire = new TextWire(Bytes.elasticByteBuffer()); + long largestChunkSoFar = 0; + private final Wire intWire = new TextWire(Bytes.elasticByteBuffer()); + // used by the enterprise version + protected int localIdentifier; private SocketChannel clientChannel; @@ -84,7 +82,8 @@ public class WiredStatelessClientTcpConnectionHub { private long sizeMark; private long startTime; - public WiredStatelessClientTcpConnectionHub(WiredChronicleMapStatelessClientBuilder config) { + public WiredStatelessClientTcpConnectionHub(WiredChronicleMapStatelessClientBuilder config, byte localIdentifier) { + this.localIdentifier = localIdentifier; this.remoteAddress = config.remoteAddress(); this.tcpBufferSize = config.tcpBufferSize(); this.name = config.name(); @@ -93,7 +92,8 @@ public class WiredStatelessClientTcpConnectionHub { this.timeoutMs = config.timeoutMs(); attemptConnect(remoteAddress); - checkVersion(); + // todo +// checkVersion(); } @@ -124,16 +124,17 @@ public class WiredStatelessClientTcpConnectionHub { return outBytesLock; } - protected void checkVersion() { + protected void checkVersion(short channelID) { - String serverVersion = serverApplicationVersion(); - String clientVersion = clientVersion(); + + final String serverVersion = serverApplicationVersion(channelID); + final String clientVersion = clientVersion(); if (!serverVersion.equals(clientVersion)) { LOG.warn("DIFFERENT CHRONICLE-MAP VERSIONS: The Chronicle-Map-Server and " + "Stateless-Client are on different " + "versions, " + - " we suggest that you use the same version, server=" + serverApplicationVersion() + ", " + + " we suggest that you use the same version, server=" + serverApplicationVersion(channelID) + ", " + "client=" + clientVersion); } } @@ -185,22 +186,47 @@ public class WiredStatelessClientTcpConnectionHub { } clientChannel = result; - // clear in and out buffer - intWire.clear(); - inWireByteBuffer().clear(); - outWire.clear(); - outWireByteBuffer().clear(); + ByteBuffer byteBuffer = ByteBuffer.allocateDirect(128); + Bytes bufferBytes = Bytes.wrap(byteBuffer); + TextWire wire = new TextWire(bufferBytes); + wire.bytes().skip(4); + + + // write out identifier as part of the handshaking + wire.write(() -> "IDENTIFIER").int8(localIdentifier); + + // write the size + wire.bytes().writeInt(0, (int) wire.bytes().position()); + + // update the write byte buffer + byteBuffer.limit((int) wire.bytes().position()); + + try { - checkVersion(); - } finally { - // clear in and out buffer - intWire.clear(); - outWire.clear(); + while (byteBuffer.remaining() > 0) { + + int i = result.write(byteBuffer); + if (i == -1) { + result.close(); + clientChannel = null; + return; + } + + } + } catch (Exception e) { + try { + result.close(); + clientChannel = null; + } catch (IOException e1) { + // + } + } } private ByteBuffer outWireByteBuffer() { + assert outBytesLock().isHeldByCurrentThread(); return (ByteBuffer) outWire.bytes().underlyingObject(); } @@ -225,7 +251,7 @@ public class WiredStatelessClientTcpConnectionHub { */ protected synchronized void doHandShaking(@NotNull final SocketChannel clientChannel) throws IOException { - connectionByte[0] = 0; + connectionByte[0] = TcpReplicator.WIRED_CONNECTION; this.connectionOutBuffer.clear(); long timeoutTime = System.currentTimeMillis() + timeoutMs; @@ -241,19 +267,30 @@ public class WiredStatelessClientTcpConnectionHub { if (!clientChannel.finishConnect() || !clientChannel.socket().isBound()) return; - // read a single byte back - while (this.connectionOutBuffer.position() <= 0) { + /* // read a single byte back + while (this.connectionOutBuffer.position() <= 4) { int read = clientChannel.read(this.connectionOutBuffer);// the remote identifier if (read == -1) - throw new IOException("server conncetion closed"); + throw new IOException("server connection closed"); checkTimeout(timeoutTime); } - byte remoteIdentifier = connectionByte[0]; + this.connectionOutBuffer.clear(); - if (LOG.isDebugEnabled()) + int len = this.connectionOutBuffer.getInt(); + + // block till the message is read + while (this.connectionOutBuffer.position() <= len ) { + int read = clientChannel.read(this.connectionOutBuffer);// the remote identifier + if (read == -1) + throw new IOException("server connection closed"); + checkTimeout(timeoutTime); + } + */ + + /* if (LOG.isDebugEnabled()) LOG.debug("Attached to a map with a remote identifier=" + remoteIdentifier + " ,name=" + name); - +*/ } public synchronized void close() { @@ -284,8 +321,8 @@ public class WiredStatelessClientTcpConnectionHub { } @NotNull - public String serverApplicationVersion() { - String result = proxyReturnString(APPLICATION_VERSION.toString()); + public String serverApplicationVersion(short channelID) { + String result = proxyReturnString(APPLICATION_VERSION.toString(), channelID); return (result == null) ? "" : result; } @@ -336,11 +373,13 @@ public class WiredStatelessClientTcpConnectionHub { } private void writeLength(Wire outWire) { + assert outBytesLock().isHeldByCurrentThread(); long position = outWire.bytes().position(); if (position > Integer.MAX_VALUE || position < Integer.MIN_VALUE) throw new IllegalStateException("message too large"); - outWire.bytes().writeInt(0, (int) position); + System.out.println("writeLength len=" + position); + outWire.bytes().writeInt(sizeMark, (int) position); } protected Wire proxyReply(long timeoutTime, final long transactionId) { @@ -382,22 +421,27 @@ public class WiredStatelessClientTcpConnectionHub { // reads just the size readSocket(SIZE_OF_SIZE, timeoutTime); - final int messageSize = intWire.bytes().readInt(); + final int messageSize = intWire.bytes().readInt(intWire.bytes().position()); + assert messageSize > 0 : "Invalid message size " + messageSize; assert messageSize < 16 << 20 : "Invalid message size " + messageSize; final int remainingBytes0 = messageSize - SIZE_OF_SIZE; readSocket(remainingBytes0, timeoutTime); - intWire.bytes().limit(messageSize); - final long transactionId0 = intWire.read(() -> "TRANSACTION_ID").int64(); + intWire.bytes().skip(4); + intWire.bytes().limit(messageSize); + String text = intWire.read(() -> "TRANSACTION_ID").text(); + System.out.println(text); + long transactionId0 =0; + System.out.println("transactionId0=" + transactionId0); // check the transaction id is reasonable - assert transactionId0 > 1410000000000L * TcpReplicator.TIMESTAMP_FACTOR : + /* assert transactionId0 > 1410000000000L * TcpReplicator.TIMESTAMP_FACTOR : "TransactionId too small " + transactionId0 + " messageSize " + messageSize; assert transactionId0 < 2100000000000L * TcpReplicator.TIMESTAMP_FACTOR : "TransactionId too large " + transactionId0 + " messageSize " + messageSize; - +*/ // if the transaction id is for this thread process it if (transactionId0 == transactionId) { clearParked(); @@ -480,7 +524,7 @@ public class WiredStatelessClientTcpConnectionHub { assert inBytesLock().isHeldByCurrentThread(); ByteBuffer buffer = inWireByteBuffer(); - while (buffer.remaining() > requiredNumberOfBytes) { + while (buffer.position() < requiredNumberOfBytes) { int len = clientChannel.read(inWireByteBuffer()); @@ -570,7 +614,7 @@ public class WiredStatelessClientTcpConnectionHub { } - private long proxySend(@NotNull final String methodName, final long startTime) { + private long proxySend(@NotNull final String methodName, final long startTime, short channelID) { assert outBytesLock().isHeldByCurrentThread(); assert !inBytesLock().isHeldByCurrentThread(); @@ -578,7 +622,7 @@ public class WiredStatelessClientTcpConnectionHub { // send outBytesLock().lock(); try { - long transactionId = writeHeader(startTime); + long transactionId = writeHeader(startTime, channelID); outWire.write(() -> "METHOD_NAME").text(methodName); writeSocket(); return transactionId; @@ -590,13 +634,13 @@ public class WiredStatelessClientTcpConnectionHub { @SuppressWarnings("SameParameterValue") @Nullable O fetchObject(final Class tClass, - @NotNull final String methodName) { + @NotNull final String methodName, short channelID) { final long startTime = System.currentTimeMillis(); long transactionId; outBytesLock().lock(); try { - transactionId = proxySend(methodName, startTime); + transactionId = proxySend(methodName, startTime, channelID); } finally { outBytesLock().unlock(); } @@ -619,13 +663,13 @@ public class WiredStatelessClientTcpConnectionHub { @SuppressWarnings("SameParameterValue") @Nullable - String proxyReturnString(@NotNull final String messageId) { + String proxyReturnString(@NotNull final String messageId, short channelID) { final long startTime = System.currentTimeMillis(); long transactionId; outBytesLock().lock(); try { - transactionId = proxySend(messageId, startTime); + transactionId = proxySend(messageId, startTime, channelID); } finally { outBytesLock().unlock(); } @@ -644,17 +688,23 @@ public class WiredStatelessClientTcpConnectionHub { } - Wire outWire() { + Wire outWire() { + assert outBytesLock().isHeldByCurrentThread(); return outWire; } - long writeHeader(long startTime) { + long writeHeader(long startTime, short channelID) { + + assert outBytesLock().isHeldByCurrentThread(); markSize(); startTime(startTime); + long transactionId = nextUniqueTransaction(startTime); + outWire().write(() -> "TRANSACTION_ID").int64(transactionId); outWire().write(() -> "TIME_STAMP").int64(startTime); - outWire().write(() -> "CHANNEL_ID").int64(startTime); + outWire().write(() -> "CHANNEL_ID").int16(channelID); + return transactionId; } @@ -664,7 +714,9 @@ public class WiredStatelessClientTcpConnectionHub { */ void markSize() { - // this is where the size will go + assert outBytesLock().isHeldByCurrentThread(); + + // this is where the size will go sizeMark = outWire.bytes().position(); diff --git a/src/test/java/net/openhft/chronicle/wire/TestWire.java b/src/test/java/net/openhft/chronicle/wire/TestWire.java index 30233acac..849861290 100644 --- a/src/test/java/net/openhft/chronicle/wire/TestWire.java +++ b/src/test/java/net/openhft/chronicle/wire/TestWire.java @@ -22,21 +22,20 @@ import net.openhft.chronicle.bytes.BytesStore; import net.openhft.chronicle.hash.replication.ReplicationHub; import net.openhft.chronicle.hash.replication.TcpTransportAndNetworkConfig; import net.openhft.chronicle.map.ChronicleMap; -import net.openhft.chronicle.util.ShortConsumer; +import net.openhft.chronicle.map.WiredChronicleMapStatelessClientBuilder; import net.openhft.lang.io.ByteBufferBytes; import net.openhft.lang.io.Bytes; -import org.junit.Before; +import org.jetbrains.annotations.NotNull; +import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; -import java.util.concurrent.atomic.AtomicInteger; import static java.nio.ByteBuffer.allocate; import static java.util.concurrent.TimeUnit.SECONDS; import static net.openhft.chronicle.map.ChronicleMapBuilder.of; -import static net.openhft.chronicle.map.ChronicleMapStatelessClientBuilder.createClientOf; import static org.junit.Assert.assertEquals; /** @@ -44,28 +43,28 @@ import static org.junit.Assert.assertEquals; */ public class TestWire { - public static class Details { - Class keyClass; - Class valueClass; - short channelID; - } - private ChronicleMap map1a; + private ChronicleMap map1a; + + private static ChronicleMap localClient(int port, + byte identifier, + @NotNull Class keyClass, + @NotNull Class valueClass, + short channelID) throws IOException { + + final WiredChronicleMapStatelessClientBuilder builder = new WiredChronicleMapStatelessClientBuilder(new InetSocketAddress("localhost", port), keyClass, valueClass, channelID); + builder.identifier(identifier); + return builder.create(); + } private ChronicleMap map2a; private ChronicleMap map3a; private ReplicationHub hubA; - public static ChronicleMap localClient(int port) throws IOException { - return createClientOf(new InetSocketAddress("localhost", port)); - } - - - - - @Before - public void setup() throws IOException { + @Ignore + @Test + public void test() throws IOException { { final TcpTransportAndNetworkConfig tcpConfig = TcpTransportAndNetworkConfig @@ -76,36 +75,38 @@ public class TestWire { .createWithId((byte) 1); // this is how you add maps after the custer is created - map1a = of(String.class, Details.class) - .instance().replicatedViaChannel(hubA.createChannel((short) 1)).create(); + map1a = of(byte[].class, byte[].class) + .instance().replicatedViaChannel(hubA.createChannel((short) 2)).create(); map2a = of(byte[].class, byte[].class) .entries(1000) - .instance().replicatedViaChannel(hubA.createChannel((short) 2)).create(); + .instance().replicatedViaChannel(hubA.createChannel((short) 3)).create(); map3a = of(byte[].class, byte[].class) .entries(1000) - .instance().replicatedViaChannel(hubA.createChannel((short) 2)).create(); + .instance().replicatedViaChannel(hubA.createChannel((short) 4)).create(); byte[] key = new byte[4]; Bytes keyBuffer = new ByteBufferBytes(ByteBuffer.wrap(key)); - try (ChronicleMap statelessMap = localClient(8086)) { + short channelID = (short) 2; + byte identifier = (byte) 2; + try (ChronicleMap statelessMap = localClient(8086, identifier, String.class, String.class, channelID)) { for (int i = 0; i < 10; i++) { - keyBuffer.clear(); - keyBuffer.writeInt(i); - statelessMap.put(key, key); + try { + statelessMap.put("Hello", "World"); + } catch (Throwable t) { + t.printStackTrace(); + } } assertEquals(10, statelessMap.size()); } - - net.openhft.chronicle.bytes.Bytes bytes = BytesStore.wrap(allocate(128)).bytes(); TextWire textWire = new TextWire(bytes); textWire.write(() -> "TYPE").text("TextWire"); @@ -115,7 +116,45 @@ public class TestWire { } + @Test + public void testName() throws Exception { + + TextWire wire = new TextWire(net.openhft.chronicle.bytes.Bytes.elasticByteBuffer()); + + WireOut world = wire.write(() -> "hello").text("world"); + System.out.println(wire.bytes()); + } + public static class Details implements Marshallable { + + Class keyClass; + Class valueClass; + short channelID; + + public Details(Class keyClass, Class valueClass, short channelID) { + this.keyClass = keyClass; + this.valueClass = valueClass; + this.channelID = channelID; + } + + @Override + public void writeMarshallable(WireOut wire) { + wire.write(() -> "keyClass").text(keyClass.getName()); + wire.write(() -> "valueClass").text(valueClass.getName()); + wire.write(() -> "channelID").int16(channelID); + } + + @Override + public void readMarshallable(WireIn wire) throws IllegalStateException { + try { + keyClass = Class.forName(wire.read(() -> "keyClass").text()); + valueClass = Class.forName(wire.read(() -> "valueClass").text()); + channelID = wire.read(() -> "channelID").int16(); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + } }