summaryrefslogtreecommitdiff
path: root/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/FileQueueBackingStore.java
blob: 0e5a4efba6575dacf95507c4c9c67df3ee556d4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.qpid.server.queue;

import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.BasicContentHeaderProperties;
import org.apache.qpid.framing.ContentHeaderBody;
import org.apache.qpid.framing.abstraction.ContentChunk;
import org.apache.qpid.framing.abstraction.MessagePublishInfo;
import org.apache.qpid.util.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FileQueueBackingStore implements QueueBackingStore
{
    private static final Logger _log = Logger.getLogger(FileQueueBackingStore.class);

    private String _flowToDiskLocation;

    public FileQueueBackingStore(String location)
    {
        _flowToDiskLocation = location;
    }

    public AMQMessage load(Long messageId)
    {
        _log.info("Loading Message (ID:" + messageId + ")");

        MessageMetaData mmd;

        File handle = getFileHandle(messageId);

        ObjectInputStream input = null;

        Exception error = null;
        try
        {
            input = new ObjectInputStream(new FileInputStream(handle));

            long arrivaltime = input.readLong();

            final AMQShortString exchange = new AMQShortString(input.readUTF());
            final AMQShortString routingKey = new AMQShortString(input.readUTF());
            final boolean mandatory = input.readBoolean();
            final boolean immediate = input.readBoolean();

            int bodySize = input.readInt();
            byte[] underlying = new byte[bodySize];

            input.readFully(underlying, 0, bodySize);

            ByteBuffer buf = ByteBuffer.wrap(underlying);

            ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(buf, bodySize);

            int chunkCount = input.readInt();

            // There are WAY to many annonymous MPIs in the code this should be made concrete.
            MessagePublishInfo info = new MessagePublishInfo()
            {

                public AMQShortString getExchange()
                {
                    return exchange;
                }

                public void setExchange(AMQShortString exchange)
                {

                }

                public boolean isImmediate()
                {
                    return immediate;
                }

                public boolean isMandatory()
                {
                    return mandatory;
                }

                public AMQShortString getRoutingKey()
                {
                    return routingKey;
                }
            };

            mmd = new MessageMetaData(info, chb, chunkCount);
            mmd.setArrivalTime(arrivaltime);

            AMQMessage message;
            if (((BasicContentHeaderProperties) chb.properties).getDeliveryMode() == 2)
            {
                message = new PersistentAMQMessage(messageId, null);
            }
            else
            {
                message = new TransientAMQMessage(messageId);
            }

            message.recoverFromMessageMetaData(mmd);

            for (int chunk = 0; chunk < chunkCount; chunk++)
            {
                int length = input.readInt();

                byte[] data = new byte[length];

                input.readFully(data, 0, length);

                try
                {
                    message.recoverContentBodyFrame(new RecoverDataBuffer(length, data), (chunk + 1 == chunkCount));
                }
                catch (AMQException e)
                {
                    //ignore as this will not occur.
                    // It is thrown by the _transactionLog method in load on PersistentAMQMessage
                    // but we have created the message with a null log and will never call that method.
                }
            }

            return message;
        }
        catch (Exception e)
        {
            error = e;
        }
        finally
        {
            try
            {
                input.close();
                // We can purge the message here then reflow it if required but I believe it to be cleaner to leave it
                // on disk until it has been deleted from the queue at that point we can be sure we won't need the data
                //handle.delete();
            }
            catch (IOException e)
            {
                _log.info("Unable to close input on message(" + messageId + ") recovery due to:" + e.getMessage());
            }
        }

        throw new UnableToRecoverMessageException(error);
    }

    public void unload(AMQMessage message) throws UnableToFlowMessageException
    {
        long messageId = message.getMessageId();

        File handle = getFileHandle(messageId);

        //If we have written the data once then we don't need to do it again.
        if (handle.exists())
        {
            if (_log.isDebugEnabled())
            {
                _log.debug("Message(ID:" + messageId + ") already unloaded.");
            }
            return;
        }

        if (_log.isInfoEnabled())
        {
            _log.info("Unloading Message (ID:" + messageId + ")");
        }

        ObjectOutputStream writer = null;
        Exception error = null;

        try
        {
            writer = new ObjectOutputStream(new FileOutputStream(handle));

            writer.writeLong(message.getArrivalTime());

            MessagePublishInfo mpi = message.getMessagePublishInfo();
            writer.writeUTF(String.valueOf(mpi.getExchange()));
            writer.writeUTF(String.valueOf(mpi.getRoutingKey()));
            writer.writeBoolean(mpi.isMandatory());
            writer.writeBoolean(mpi.isImmediate());
            ContentHeaderBody chb = message.getContentHeaderBody();

            // write out the content header body
            final int bodySize = chb.getSize();
            byte[] underlying = new byte[bodySize];
            ByteBuffer buf = ByteBuffer.wrap(underlying);
            chb.writePayload(buf);

            writer.writeInt(bodySize);
            writer.write(underlying, 0, bodySize);

            int bodyCount = message.getBodyCount();
            writer.writeInt(bodyCount);

            //WriteContentBody
            for (int index = 0; index < bodyCount; index++)
            {
                ContentChunk chunk = message.getContentChunk(index);
                int length = chunk.getSize();

                byte[] chunk_underlying = new byte[length];

                ByteBuffer chunk_buf = chunk.getData();

                chunk_buf.duplicate().rewind().get(chunk_underlying);

                writer.writeInt(length);
                writer.write(chunk_underlying, 0, length);
            }
        }
        catch (FileNotFoundException e)
        {
            error = e;
        }
        catch (IOException e)
        {
            error = e;
        }
        finally
        {
            // In a FileNotFound situation writer will be null.
            if (writer != null)
            {
                try
                {
                    writer.flush();
                    writer.close();
                }
                catch (IOException e)
                {
                    error = e;
                }
            }
        }

        if (error != null)
        {
            _log.error("Unable to unload message(" + messageId + ") to disk, restoring state.");
            handle.delete();
            throw new UnableToFlowMessageException(messageId, error);
        }
    }

    /**
     * Use the messageId to calculate the file path on disk.
     *
     * Current implementation will give us 256 bins.
     * Therefore the maximum messages that can be flowed before error/platform is:
     * ext3 : 256 bins * 32000  = 8192000
     * FAT32 : 256 bins * 65534 = 16776704
     * Other FS have much greater limits than we need to worry about.
     *
     * @param messageId the Message we need a file Handle for.
     *
     * @return the File handle
     */
    private File getFileHandle(long messageId)
    {
        // grab the 8 LSB to give us 256 bins
        long bin = messageId & 0xFFL;

        String bin_path = _flowToDiskLocation + File.separator + bin;
        File bin_dir = new File(bin_path);

        if (!bin_dir.exists())
        {
            bin_dir.mkdirs();
        }

        String id = bin_path + File.separator + messageId;

        return new File(id);
    }

    public void delete(Long messageId)
    {
        File handle = getFileHandle(messageId);

        if (handle.exists())
        {
            if (_log.isInfoEnabled())
            {
                _log.info("Message(" + messageId + ") delete flowToDisk.");
            }
            if (!handle.delete())
            {
                throw new RuntimeException("Unable to delete flowToDisk data");
            }
        }
    }

    public void close()
    {
        _log.info("Closing Backing store at:" + _flowToDiskLocation);
        if (!FileUtils.delete(new File(_flowToDiskLocation), true))
        {
            _log.error("Unable to fully delete backing store location");
        }
    }

    private class RecoverDataBuffer implements ContentChunk
    {
        private int _length;
        private ByteBuffer _dataBuffer;

        public RecoverDataBuffer(int length, byte[] data)
        {
            _length = length;
            _dataBuffer = ByteBuffer.wrap(data);
        }

        public int getSize()
        {
            return _length;
        }

        public ByteBuffer getData()
        {
            return _dataBuffer;
        }

        public void reduceToFit()
        {

        }

    }

}