atomic-storage: remove type dependency at segment level I/O
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / messaging / MessageAssembler.java
1 /*
2  * Copyright (c) 2017 Inocybe Technologies and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.messaging;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
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;
29
30 /**
31  * This class re-assembles messages sliced into smaller chunks by {@link MessageSlicer}.
32  *
33  * @author Thomas Pantelis
34  * @see MessageSlicer
35  */
36 public final  class MessageAssembler implements AutoCloseable {
37     private static final Logger LOG = LoggerFactory.getLogger(MessageAssembler.class);
38
39     private final Cache<Identifier, AssembledMessageState> stateCache;
40     private final FileBackedOutputStreamFactory fileBackedStreamFactory;
41     private final BiConsumer<Object, ActorRef> assembledMessageCallback;
42     private final String logContext;
43
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;
50
51         stateCache = CacheBuilder.newBuilder()
52                 .expireAfterAccess(builder.expireStateAfterInactivityDuration, builder.expireStateAfterInactivityUnit)
53                 .removalListener(this::stateRemoved).build();
54     }
55
56     /**
57      * Returns a new Builder for creating MessageAssembler instances.
58      *
59      * @return a Builder instance
60      */
61     public static Builder builder() {
62         return new Builder();
63     }
64
65     /**
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
68      *
69      * @param message the message to check
70      * @return true if handled, false otherwise
71      */
72     public static boolean isHandledMessage(final Object message) {
73         return message instanceof MessageSlice || message instanceof AbortSlicing;
74     }
75
76     @Override
77     public void close() {
78         LOG.debug("{}: Closing", logContext);
79         stateCache.invalidateAll();
80     }
81
82     /**
83      * Checks for and removes assembled message state that has expired due to inactivity from the slicing component
84      * on the other end.
85      */
86     public void checkExpiredAssembledMessageState() {
87         if (stateCache.size() > 0) {
88             stateCache.cleanUp();
89         }
90     }
91
92     /**
93      * Invoked to handle message slices and other messages pertaining to this class.
94      *
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
98      */
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);
103             return true;
104         } else if (message instanceof AbortSlicing abortSlicing) {
105             LOG.debug("{}: handleMessage: {}", logContext, abortSlicing);
106             onAbortSlicing(abortSlicing);
107             return true;
108         }
109
110         return false;
111     }
112
113     private void onMessageSlice(final MessageSlice messageSlice, final ActorRef sendTo) {
114         final Identifier identifier = messageSlice.getIdentifier();
115         try {
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);
122
123             messageSlice.getReplyTo().tell(MessageSliceReply.failed(identifier, messageSliceEx, sendTo),
124                     ActorRef.noSender());
125         }
126     }
127
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);
134         }
135
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);
140     }
141
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();
149             try {
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);
153
154                     reAssembledMessage = reAssembleMessage(state);
155
156                     replyTo.tell(successReply, ActorRef.noSender());
157                     removeState(identifier);
158                 } else {
159                     LOG.debug("{}: Added slice for {} - expecting more", logContext, identifier);
160                     replyTo.tell(successReply, ActorRef.noSender());
161                 }
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);
166             }
167         }
168
169         if (reAssembledMessage != null) {
170             LOG.debug("{}: Notifying callback of re-assembled message {}", logContext, reAssembledMessage);
171             assembledMessageCallback.accept(reAssembledMessage, replyTo);
172         }
173     }
174
175     private static Object reAssembleMessage(final AssembledMessageState state) throws MessageSliceException {
176         try {
177             final ByteSource assembledBytes = state.getAssembledBytes();
178             try (ObjectInputStream in = new ObjectInputStream(assembledBytes.openStream())) {
179                 return in.readObject();
180             }
181
182         } catch (IOException | ClassNotFoundException  e) {
183             throw new MessageSliceException(String.format("Error re-assembling bytes for identifier %s",
184                     state.getIdentifier()), e);
185         }
186     }
187
188     private void onAbortSlicing(final AbortSlicing message) {
189         removeState(message.getIdentifier());
190     }
191
192     private void removeState(final Identifier identifier) {
193         LOG.debug("{}: Removing state for {}", logContext, identifier);
194         stateCache.invalidate(identifier);
195     }
196
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());
200         } else {
201             LOG.debug("{}: AssembledMessageState for {} was removed from the cache due to {}", logContext,
202                     notification.getKey(), notification.getCause());
203         }
204
205         notification.getValue().close();
206     }
207
208     @VisibleForTesting
209     boolean hasState(final Identifier forIdentifier) {
210         boolean exists = stateCache.getIfPresent(forIdentifier) != null;
211         stateCache.cleanUp();
212         return exists;
213     }
214
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>";
221
222         /**
223          * Sets the factory for creating FileBackedOutputStream instances used for streaming messages.
224          *
225          * @param newFileBackedStreamFactory the factory for creating FileBackedOutputStream instances
226          * @return this Builder
227          */
228         public Builder fileBackedStreamFactory(final FileBackedOutputStreamFactory newFileBackedStreamFactory) {
229             fileBackedStreamFactory = requireNonNull(newFileBackedStreamFactory);
230             return this;
231         }
232
233         /**
234          * Sets the Consumer callback for assembled messages. The callback takes the assembled message and the
235          * original sender ActorRef as arguments.
236          *
237          * @param newAssembledMessageCallback the Consumer callback
238          * @return this Builder
239          */
240         public Builder assembledMessageCallback(final BiConsumer<Object, ActorRef> newAssembledMessageCallback) {
241             assembledMessageCallback = newAssembledMessageCallback;
242             return this;
243         }
244
245         /**
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
248          * inactivity.
249          *
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
253          */
254         public Builder expireStateAfterInactivity(final long duration, final TimeUnit unit) {
255             checkArgument(duration > 0, "duration must be > 0");
256             expireStateAfterInactivityDuration = duration;
257             expireStateAfterInactivityUnit = unit;
258             return this;
259         }
260
261         /**
262          * Sets the context for log messages.
263          *
264          * @param newLogContext the log context
265          * @return this Builder
266          */
267         public Builder logContext(final String newLogContext) {
268             logContext = newLogContext;
269             return this;
270         }
271
272         /**
273          * Builds a new MessageAssembler instance.
274          *
275          * @return a new MessageAssembler
276          */
277         public MessageAssembler build() {
278             return new MessageAssembler(this);
279         }
280     }
281 }