2 * Copyright (c) 2017 Inocybe Technologies and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.messaging;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import akka.actor.ActorRef;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.cache.Cache;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.RemovalNotification;
18 import com.google.common.io.ByteSource;
19 import java.io.IOException;
20 import java.io.ObjectInputStream;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import java.util.function.BiConsumer;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.controller.cluster.io.FileBackedOutputStreamFactory;
26 import org.opendaylight.yangtools.concepts.Identifier;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * This class re-assembles messages sliced into smaller chunks by {@link MessageSlicer}.
33 * @author Thomas Pantelis
36 public final class MessageAssembler implements AutoCloseable {
37 private static final Logger LOG = LoggerFactory.getLogger(MessageAssembler.class);
39 private final Cache<Identifier, AssembledMessageState> stateCache;
40 private final FileBackedOutputStreamFactory fileBackedStreamFactory;
41 private final BiConsumer<Object, ActorRef> assembledMessageCallback;
42 private final String logContext;
44 MessageAssembler(final Builder builder) {
45 fileBackedStreamFactory = requireNonNull(builder.fileBackedStreamFactory,
46 "FiledBackedStreamFactory cannot be null");
47 assembledMessageCallback = requireNonNull(builder.assembledMessageCallback,
48 "assembledMessageCallback cannot be null");
49 logContext = builder.logContext;
51 stateCache = CacheBuilder.newBuilder()
52 .expireAfterAccess(builder.expireStateAfterInactivityDuration, builder.expireStateAfterInactivityUnit)
53 .removalListener(this::stateRemoved).build();
57 * Returns a new Builder for creating MessageAssembler instances.
59 * @return a Builder instance
61 public static Builder builder() {
66 * Checks if the given message is handled by this class. If so, it should be forwarded to the
67 * {@link #handleMessage(Object, ActorRef)} method
69 * @param message the message to check
70 * @return true if handled, false otherwise
72 public static boolean isHandledMessage(final Object message) {
73 return message instanceof MessageSlice || message instanceof AbortSlicing;
78 LOG.debug("{}: Closing", logContext);
79 stateCache.invalidateAll();
83 * Checks for and removes assembled message state that has expired due to inactivity from the slicing component
86 public void checkExpiredAssembledMessageState() {
87 if (stateCache.size() > 0) {
93 * Invoked to handle message slices and other messages pertaining to this class.
95 * @param message the message
96 * @param sendTo the reference of the actor to which subsequent message slices should be sent
97 * @return true if the message was handled, false otherwise
99 public boolean handleMessage(final Object message, final @NonNull ActorRef sendTo) {
100 if (message instanceof MessageSlice messageSlice) {
101 LOG.debug("{}: handleMessage: {}", logContext, messageSlice);
102 onMessageSlice(messageSlice, sendTo);
104 } else if (message instanceof AbortSlicing abortSlicing) {
105 LOG.debug("{}: handleMessage: {}", logContext, abortSlicing);
106 onAbortSlicing(abortSlicing);
113 private void onMessageSlice(final MessageSlice messageSlice, final ActorRef sendTo) {
114 final Identifier identifier = messageSlice.getIdentifier();
116 final AssembledMessageState state = stateCache.get(identifier, () -> createState(messageSlice));
117 processMessageSliceForState(messageSlice, state, sendTo);
118 } catch (ExecutionException e) {
119 final Throwable cause = e.getCause();
120 final MessageSliceException messageSliceEx = cause instanceof MessageSliceException sliceEx ? sliceEx
121 : new MessageSliceException(String.format("Error creating state for identifier %s", identifier), cause);
123 messageSlice.getReplyTo().tell(MessageSliceReply.failed(identifier, messageSliceEx, sendTo),
124 ActorRef.noSender());
128 private AssembledMessageState createState(final MessageSlice messageSlice) throws MessageSliceException {
129 final Identifier identifier = messageSlice.getIdentifier();
130 if (messageSlice.getSliceIndex() == SlicedMessageState.FIRST_SLICE_INDEX) {
131 LOG.debug("{}: Received first slice for {} - creating AssembledMessageState", logContext, identifier);
132 return new AssembledMessageState(identifier, messageSlice.getTotalSlices(),
133 fileBackedStreamFactory, logContext);
136 LOG.debug("{}: AssembledMessageState not found for {} - returning failed reply", logContext, identifier);
137 throw new MessageSliceException(String.format(
138 "No assembled state found for identifier %s and slice index %s", identifier,
139 messageSlice.getSliceIndex()), true);
142 private void processMessageSliceForState(final MessageSlice messageSlice, final AssembledMessageState state,
143 final ActorRef sendTo) {
144 final Identifier identifier = messageSlice.getIdentifier();
145 final ActorRef replyTo = messageSlice.getReplyTo();
146 Object reAssembledMessage = null;
147 synchronized (state) {
148 final int sliceIndex = messageSlice.getSliceIndex();
150 final MessageSliceReply successReply = MessageSliceReply.success(identifier, sliceIndex, sendTo);
151 if (state.addSlice(sliceIndex, messageSlice.getData(), messageSlice.getLastSliceHashCode())) {
152 LOG.debug("{}: Received last slice for {}", logContext, identifier);
154 reAssembledMessage = reAssembleMessage(state);
156 replyTo.tell(successReply, ActorRef.noSender());
157 removeState(identifier);
159 LOG.debug("{}: Added slice for {} - expecting more", logContext, identifier);
160 replyTo.tell(successReply, ActorRef.noSender());
162 } catch (MessageSliceException e) {
163 LOG.warn("{}: Error processing {}", logContext, messageSlice, e);
164 replyTo.tell(MessageSliceReply.failed(identifier, e, sendTo), ActorRef.noSender());
165 removeState(identifier);
169 if (reAssembledMessage != null) {
170 LOG.debug("{}: Notifying callback of re-assembled message {}", logContext, reAssembledMessage);
171 assembledMessageCallback.accept(reAssembledMessage, replyTo);
175 private static Object reAssembleMessage(final AssembledMessageState state) throws MessageSliceException {
177 final ByteSource assembledBytes = state.getAssembledBytes();
178 try (ObjectInputStream in = new ObjectInputStream(assembledBytes.openStream())) {
179 return in.readObject();
182 } catch (IOException | ClassNotFoundException e) {
183 throw new MessageSliceException(String.format("Error re-assembling bytes for identifier %s",
184 state.getIdentifier()), e);
188 private void onAbortSlicing(final AbortSlicing message) {
189 removeState(message.getIdentifier());
192 private void removeState(final Identifier identifier) {
193 LOG.debug("{}: Removing state for {}", logContext, identifier);
194 stateCache.invalidate(identifier);
197 private void stateRemoved(final RemovalNotification<Identifier, AssembledMessageState> notification) {
198 if (notification.wasEvicted()) {
199 LOG.warn("{}: AssembledMessageState for {} was expired from the cache", logContext, notification.getKey());
201 LOG.debug("{}: AssembledMessageState for {} was removed from the cache due to {}", logContext,
202 notification.getKey(), notification.getCause());
205 notification.getValue().close();
209 boolean hasState(final Identifier forIdentifier) {
210 boolean exists = stateCache.getIfPresent(forIdentifier) != null;
211 stateCache.cleanUp();
215 public static class Builder {
216 private FileBackedOutputStreamFactory fileBackedStreamFactory;
217 private BiConsumer<Object, ActorRef> assembledMessageCallback;
218 private long expireStateAfterInactivityDuration = 1;
219 private TimeUnit expireStateAfterInactivityUnit = TimeUnit.MINUTES;
220 private String logContext = "<no-context>";
223 * Sets the factory for creating FileBackedOutputStream instances used for streaming messages.
225 * @param newFileBackedStreamFactory the factory for creating FileBackedOutputStream instances
226 * @return this Builder
228 public Builder fileBackedStreamFactory(final FileBackedOutputStreamFactory newFileBackedStreamFactory) {
229 fileBackedStreamFactory = requireNonNull(newFileBackedStreamFactory);
234 * Sets the Consumer callback for assembled messages. The callback takes the assembled message and the
235 * original sender ActorRef as arguments.
237 * @param newAssembledMessageCallback the Consumer callback
238 * @return this Builder
240 public Builder assembledMessageCallback(final BiConsumer<Object, ActorRef> newAssembledMessageCallback) {
241 assembledMessageCallback = newAssembledMessageCallback;
246 * Sets the duration and time unit whereby assembled message state is purged from the cache due to
247 * inactivity from the slicing component on the other end. By default, state is purged after 1 minute of
250 * @param duration the length of time after which a state entry is purged
251 * @param unit the unit the duration is expressed in
252 * @return this Builder
254 public Builder expireStateAfterInactivity(final long duration, final TimeUnit unit) {
255 checkArgument(duration > 0, "duration must be > 0");
256 expireStateAfterInactivityDuration = duration;
257 expireStateAfterInactivityUnit = unit;
262 * Sets the context for log messages.
264 * @param newLogContext the log context
265 * @return this Builder
267 public Builder logContext(final String newLogContext) {
268 logContext = newLogContext;
273 * Builds a new MessageAssembler instance.
275 * @return a new MessageAssembler
277 public MessageAssembler build() {
278 return new MessageAssembler(this);