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 akka.actor.ActorRef;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.RemovalNotification;
16 import java.io.IOException;
17 import java.io.ObjectOutputStream;
18 import java.io.Serializable;
19 import java.util.Iterator;
20 import java.util.Optional;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.atomic.AtomicLong;
23 import java.util.function.Predicate;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.controller.cluster.io.FileBackedOutputStream;
26 import org.opendaylight.controller.cluster.io.FileBackedOutputStreamFactory;
27 import org.opendaylight.yangtools.concepts.Identifier;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * This class slices messages into smaller chunks. {@link MessageAssembler} is used to re-assemble the messages.
34 * @author Thomas Pantelis
35 * @see MessageAssembler
37 public class MessageSlicer implements AutoCloseable {
38 private static final Logger LOG = LoggerFactory.getLogger(MessageSlicer.class);
39 private static final AtomicLong SLICER_ID_COUNTER = new AtomicLong(1);
40 public static final int DEFAULT_MAX_SLICING_TRIES = 3;
42 private final Cache<MessageSliceIdentifier, SlicedMessageState<ActorRef>> stateCache;
43 private final FileBackedOutputStreamFactory fileBackedStreamFactory;
44 private final int messageSliceSize;
45 private final int maxSlicingTries;
46 private final String logContext;
47 private final long id;
49 MessageSlicer(final Builder builder) {
50 this.fileBackedStreamFactory = builder.fileBackedStreamFactory;
51 this.messageSliceSize = builder.messageSliceSize;
52 this.maxSlicingTries = builder.maxSlicingTries;
54 id = SLICER_ID_COUNTER.getAndIncrement();
55 this.logContext = builder.logContext + "_slicer-id-" + id;
57 CacheBuilder<Identifier, SlicedMessageState<ActorRef>> cacheBuilder =
58 CacheBuilder.newBuilder().removalListener(notification -> stateRemoved(notification));
59 if (builder.expireStateAfterInactivityDuration > 0) {
60 cacheBuilder = cacheBuilder.expireAfterAccess(builder.expireStateAfterInactivityDuration,
61 builder.expireStateAfterInactivityUnit);
63 stateCache = cacheBuilder.build();
72 * Returns a new Builder for creating MessageSlicer instances.
74 * @return a Builder instance
76 public static Builder builder() {
81 * Checks if the given message is handled by this class. If so, it should be forwarded to the
82 * {@link #handleMessage(Object)} method
84 * @param message the message to check
85 * @return true if handled, false otherwise
87 public static boolean isHandledMessage(final Object message) {
88 return message instanceof MessageSliceReply;
92 * Slices a message into chunks based on the serialized size, the maximum message slice size and the given
95 * @param options the SliceOptions
96 * @return true if the message was sliced, false otherwise
98 public boolean slice(final SliceOptions options) {
99 final Identifier identifier = options.getIdentifier();
100 final Serializable message = options.getMessage();
101 final FileBackedOutputStream fileBackedStream;
102 if (message != null) {
103 LOG.debug("{}: slice: identifier: {}, message: {}", logContext, identifier, message);
105 Preconditions.checkNotNull(fileBackedStreamFactory,
106 "The FiledBackedStreamFactory must be set in order to call this slice method");
108 // Serialize the message to a FileBackedOutputStream.
109 fileBackedStream = fileBackedStreamFactory.newInstance();
110 try (ObjectOutputStream out = new ObjectOutputStream(fileBackedStream)) {
111 out.writeObject(message);
112 } catch (IOException e) {
113 LOG.debug("{}: Error serializing message for {}", logContext, identifier, e);
114 fileBackedStream.cleanup();
115 options.getOnFailureCallback().accept(e);
119 fileBackedStream = options.getFileBackedStream();
122 return initializeSlicing(options, fileBackedStream);
125 private boolean initializeSlicing(final SliceOptions options, final FileBackedOutputStream fileBackedStream) {
126 final Identifier identifier = options.getIdentifier();
127 MessageSliceIdentifier messageSliceId = new MessageSliceIdentifier(identifier, id);
128 SlicedMessageState<ActorRef> state = null;
130 state = new SlicedMessageState<>(messageSliceId, fileBackedStream, messageSliceSize, maxSlicingTries,
131 options.getReplyTo(), options.getOnFailureCallback(), logContext);
133 final Serializable message = options.getMessage();
134 if (state.getTotalSlices() == 1 && message != null) {
135 LOG.debug("{}: Message does not need to be sliced - sending original message", logContext);
137 sendTo(options, message, options.getReplyTo());
141 final MessageSlice firstSlice = getNextSliceMessage(state);
143 LOG.debug("{}: Sending first slice: {}", logContext, firstSlice);
145 stateCache.put(messageSliceId, state);
146 sendTo(options, firstSlice, ActorRef.noSender());
148 } catch (IOException e) {
149 LOG.error("{}: Error initializing SlicedMessageState for {}", logContext, identifier, e);
153 fileBackedStream.cleanup();
156 options.getOnFailureCallback().accept(e);
161 private static void sendTo(final SliceOptions options, final Object message, final ActorRef sender) {
162 if (options.getSendToRef() != null) {
163 options.getSendToRef().tell(message, sender);
165 options.getSendToSelection().tell(message, sender);
170 * Invoked to handle messages pertaining to this class.
172 * @param message the message
173 * @return true if the message was handled, false otherwise
175 public boolean handleMessage(final Object message) {
176 if (message instanceof MessageSliceReply) {
177 LOG.debug("{}: handleMessage: {}", logContext, message);
178 return onMessageSliceReply((MessageSliceReply) message);
185 * Checks for and removes sliced message state that has expired due to inactivity from the assembling component
188 public void checkExpiredSlicedMessageState() {
189 if (stateCache.size() > 0) {
190 stateCache.cleanUp();
195 * Closes and removes all in-progress sliced message state.
198 public void close() {
199 LOG.debug("{}: Closing", logContext);
200 stateCache.invalidateAll();
204 * Cancels all in-progress sliced message state that matches the given filter.
206 * @param filter filters by Identifier
208 public void cancelSlicing(@Nonnull final Predicate<Identifier> filter) {
209 final Iterator<MessageSliceIdentifier> iter = stateCache.asMap().keySet().iterator();
210 while (iter.hasNext()) {
211 if (filter.test(iter.next().getClientIdentifier())) {
217 private static MessageSlice getNextSliceMessage(final SlicedMessageState<ActorRef> state) throws IOException {
218 final byte[] firstSliceBytes = state.getNextSlice();
219 return new MessageSlice(state.getIdentifier(), firstSliceBytes, state.getCurrentSliceIndex(),
220 state.getTotalSlices(), state.getLastSliceHashCode(), state.getReplyTarget());
223 private boolean onMessageSliceReply(final MessageSliceReply reply) {
224 final Identifier identifier = reply.getIdentifier();
225 if (!(identifier instanceof MessageSliceIdentifier)
226 || ((MessageSliceIdentifier)identifier).getSlicerId() != id) {
230 final SlicedMessageState<ActorRef> state = stateCache.getIfPresent(identifier);
232 LOG.warn("{}: SlicedMessageState not found for {}", logContext, reply);
233 reply.getSendTo().tell(new AbortSlicing(identifier), ActorRef.noSender());
237 synchronized (state) {
239 final Optional<MessageSliceException> failure = reply.getFailure();
240 if (failure.isPresent()) {
241 LOG.warn("{}: Received failed {}", logContext, reply);
242 processMessageSliceException(failure.get(), state, reply.getSendTo());
246 if (state.getCurrentSliceIndex() != reply.getSliceIndex()) {
247 LOG.warn("{}: Slice index {} in {} does not match expected index {}", logContext,
248 reply.getSliceIndex(), reply, state.getCurrentSliceIndex());
249 reply.getSendTo().tell(new AbortSlicing(identifier), ActorRef.noSender());
250 possiblyRetrySlicing(state, reply.getSendTo());
254 if (state.isLastSlice(reply.getSliceIndex())) {
255 LOG.debug("{}: Received last slice reply for {}", logContext, identifier);
256 removeState(identifier);
258 final MessageSlice nextSlice = getNextSliceMessage(state);
259 LOG.debug("{}: Sending next slice: {}", logContext, nextSlice);
260 reply.getSendTo().tell(nextSlice, ActorRef.noSender());
262 } catch (IOException e) {
263 LOG.warn("{}: Error processing {}", logContext, reply, e);
271 private void processMessageSliceException(final MessageSliceException exception,
272 final SlicedMessageState<ActorRef> state, final ActorRef sendTo) throws IOException {
273 if (exception.isRetriable()) {
274 possiblyRetrySlicing(state, sendTo);
276 fail(state, exception.getCause() != null ? exception.getCause() : exception);
280 private void possiblyRetrySlicing(final SlicedMessageState<ActorRef> state, final ActorRef sendTo)
282 if (state.canRetry()) {
283 LOG.info("{}: Retrying message slicing for {}", logContext, state.getIdentifier());
285 sendTo.tell(getNextSliceMessage(state), ActorRef.noSender());
287 String message = String.format("Maximum slicing retries reached for identifier %s - failing the message",
288 state.getIdentifier());
290 fail(state, new RuntimeException(message));
294 private void removeState(final Identifier identifier) {
295 LOG.debug("{}: Removing state for {}", logContext, identifier);
296 stateCache.invalidate(identifier);
299 private void stateRemoved(final RemovalNotification<Identifier, SlicedMessageState<ActorRef>> notification) {
300 final SlicedMessageState<ActorRef> state = notification.getValue();
302 if (notification.wasEvicted()) {
303 LOG.warn("{}: SlicedMessageState for {} was expired from the cache", logContext, notification.getKey());
304 state.getOnFailureCallback().accept(new RuntimeException(String.format(
305 "The slicing state for message identifier %s was expired due to inactivity from the assembling "
306 + "component on the other end", state.getIdentifier())));
308 LOG.debug("{}: SlicedMessageState for {} was removed from the cache due to {}", logContext,
309 notification.getKey(), notification.getCause());
313 private void fail(final SlicedMessageState<ActorRef> state, final Throwable failure) {
314 removeState(state.getIdentifier());
315 state.getOnFailureCallback().accept(failure);
319 boolean hasState(final Identifier forIdentifier) {
320 boolean exists = stateCache.getIfPresent(forIdentifier) != null;
321 stateCache.cleanUp();
325 public static class Builder {
326 private FileBackedOutputStreamFactory fileBackedStreamFactory;
327 private int messageSliceSize = -1;
328 private long expireStateAfterInactivityDuration = -1;
329 private TimeUnit expireStateAfterInactivityUnit = TimeUnit.MINUTES;
330 private int maxSlicingTries = DEFAULT_MAX_SLICING_TRIES;
331 private String logContext = "<no-context>";
334 * Sets the factory for creating FileBackedOutputStream instances used for streaming messages. This factory
335 * is used by the {@link MessageSlicer#slice(SliceOptions)} method if a Serializable message is passed.
336 * If Serializable messages aren't passed then the factory need not be set.
338 * @param newFileBackedStreamFactory the factory for creating FileBackedOutputStream instances
339 * @return this Builder
341 public Builder fileBackedStreamFactory(final FileBackedOutputStreamFactory newFileBackedStreamFactory) {
342 this.fileBackedStreamFactory = Preconditions.checkNotNull(newFileBackedStreamFactory);
347 * Sets the maximum size (in bytes) for a message slice.
349 * @param newMessageSliceSize the maximum size (in bytes)
350 * @return this Builder
352 public Builder messageSliceSize(final int newMessageSliceSize) {
353 Preconditions.checkArgument(newMessageSliceSize > 0, "messageSliceSize must be > 0");
354 this.messageSliceSize = newMessageSliceSize;
359 * Sets the maximum number of tries for slicing a message. If exceeded, slicing fails. The default is
360 * defined by {@link #DEFAULT_MAX_SLICING_TRIES}
362 * @param newMaxSlicingTries the maximum number of tries
363 * @return this Builder
365 public Builder maxSlicingTries(final int newMaxSlicingTries) {
366 Preconditions.checkArgument(newMaxSlicingTries > 0, "newMaxSlicingTries must be > 0");
367 this.maxSlicingTries = newMaxSlicingTries;
372 * Sets the duration and time unit whereby sliced message state is purged from the cache and the associated
373 * failure callback is notified due to inactivity from the assembling component on the other end. By default,
374 * state is not purged due to inactivity.
376 * @param duration the length of time after which a state entry is purged
377 * @param unit the unit the duration is expressed in
378 * @return this Builder
380 public Builder expireStateAfterInactivity(final long duration, final TimeUnit unit) {
381 Preconditions.checkArgument(duration > 0, "duration must be > 0");
382 this.expireStateAfterInactivityDuration = duration;
383 this.expireStateAfterInactivityUnit = unit;
388 * Sets the context for log messages.
390 * @param newLogContext the log context
391 * @return this Builder
393 public Builder logContext(final String newLogContext) {
394 this.logContext = Preconditions.checkNotNull(newLogContext);
399 * Builds a new MessageSlicer instance.
401 * @return a new MessageSlicer
403 public MessageSlicer build() {
404 return new MessageSlicer(this);