tom | 43e836a | 2014-09-30 01:50:29 -0700 | [diff] [blame] | 1 | package org.onlab.onos.store.cluster.impl; |
tom | 1d416c5 | 2014-09-29 20:55:24 -0700 | [diff] [blame] | 2 | |
| 3 | import org.onlab.nio.IOLoop; |
| 4 | import org.onlab.nio.MessageStream; |
| 5 | import org.onlab.onos.cluster.DefaultControllerNode; |
tom | 43e836a | 2014-09-30 01:50:29 -0700 | [diff] [blame] | 6 | import org.onlab.onos.store.cluster.messaging.ClusterMessage; |
| 7 | import org.onlab.onos.store.cluster.messaging.SerializationService; |
tom | 1d416c5 | 2014-09-29 20:55:24 -0700 | [diff] [blame] | 8 | |
| 9 | import java.nio.ByteBuffer; |
| 10 | import java.nio.channels.ByteChannel; |
| 11 | |
| 12 | import static com.google.common.base.Preconditions.checkState; |
| 13 | |
| 14 | /** |
| 15 | * Stream for transferring messages between two cluster members. |
| 16 | */ |
| 17 | public class ClusterMessageStream extends MessageStream<ClusterMessage> { |
| 18 | |
| 19 | private static final int COMM_BUFFER_SIZE = 32 * 1024; |
| 20 | private static final int COMM_IDLE_TIME = 500; |
| 21 | |
| 22 | private DefaultControllerNode node; |
| 23 | private SerializationService serializationService; |
| 24 | |
| 25 | /** |
| 26 | * Creates a message stream associated with the specified IO loop and |
| 27 | * backed by the given byte channel. |
| 28 | * |
| 29 | * @param serializationService service for encoding/decoding messages |
| 30 | * @param loop IO loop |
| 31 | * @param byteChannel backing byte channel |
| 32 | */ |
| 33 | public ClusterMessageStream(SerializationService serializationService, |
| 34 | IOLoop<ClusterMessage, ?> loop, |
| 35 | ByteChannel byteChannel) { |
| 36 | super(loop, byteChannel, COMM_BUFFER_SIZE, COMM_IDLE_TIME); |
| 37 | this.serializationService = serializationService; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Returns the node with which this stream is associated. |
| 42 | * |
| 43 | * @return controller node |
| 44 | */ |
| 45 | public DefaultControllerNode node() { |
| 46 | return node; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Sets the node with which this stream is affiliated. |
| 51 | * |
| 52 | * @param node controller node |
| 53 | */ |
| 54 | public void setNode(DefaultControllerNode node) { |
| 55 | checkState(this.node == null, "Stream is already bound to a node"); |
| 56 | this.node = node; |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | protected ClusterMessage read(ByteBuffer buffer) { |
| 61 | return serializationService.decode(buffer); |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | protected void write(ClusterMessage message, ByteBuffer buffer) { |
| 66 | serializationService.encode(message, buffer); |
| 67 | } |
| 68 | |
| 69 | } |