summaryrefslogtreecommitdiff
path: root/qpid/tools/src/py/qls/jrnl.py
blob: f4fb16ef9f67737e2aae03e37deaf05b2fab948d (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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#
# 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.
#

"""
Module: qls.jrnl

Contains journal record classes.
"""

import qls.err
import qls.utils
import string
import struct
import time

class RecordHeader(object):
    FORMAT = '<4s2H2Q'
    def __init__(self, file_offset, magic, version, user_flags, serial, record_id):
        self.file_offset = file_offset
        self.magic = magic
        self.version = version
        self.user_flags = user_flags
        self.serial = serial
        self.record_id = record_id
        self.warnings = []
        self.truncated_flag = False
    def encode(self):
        return struct.pack(RecordHeader.FORMAT, self.magic, self.version, self.user_flags, self.serial, self.record_id)
    def load(self, file_handle):
        pass
    @staticmethod
    def discriminate(args):
        """Use the last char in the header magic to determine the header type"""
        return CLASSES.get(args[1][-1], RecordHeader)
    def is_empty(self):
        """Return True if this record is empty (ie has a magic of 0x0000"""
        return self.magic == '\x00'*4
    def is_header_valid(self, file_header):
        """Check that this record is valid"""
        if self.is_empty():
            return False
        if self.magic[:3] != 'QLS' or self.magic[3] not in ['a', 'c', 'd', 'e', 'f', 'x']:
            return False
        if self.magic[-1] != 'x':
            if self.version != qls.utils.DEFAULT_RECORD_VERSION:
                raise qls.err.InvalidRecordVersionError(file_header, self, qls.utils.DEFAULT_RECORD_VERSION)
            if self.serial != file_header.serial:
                return False
        return True
    def to_string(self):
        """Return string representation of this header"""
        if self.is_empty():
            return '0x%08x: <empty>' % (self.file_offset)
        if self.magic[-1] == 'x':
            return '0x%08x: [X]' % (self.file_offset)
        if self.magic[-1] in ['a', 'c', 'd', 'e', 'f', 'x']:
            return '0x%08x: [%c v=%d f=0x%04x rid=0x%x]' % \
                (self.file_offset, self.magic[-1].upper(), self.version, self.user_flags, self.record_id)
        return '0x%08x: <error, unknown magic "%s" (possible overwrite boundary?)>' %  (self.file_offset, self.magic)
    def _get_warnings(self):
        warn_str = ''
        for warn in self.warnings:
            warn_str += '<%s>' % warn
        return warn_str
    def __str__(self):
        """Return string representation of this header"""
        return RecordHeader.to_string(self)

class RecordTail(object):
    FORMAT = '<4sL2Q'
    def __init__(self, file_handle): # TODO - clumsy, only allows reading from disk. Move all disk stuff to laod()
        self.file_offset = file_handle.tell() if file_handle is not None else 0
        self.complete = False
        self.read_size = struct.calcsize(RecordTail.FORMAT)
        self.fbin = file_handle.read(self.read_size) if file_handle is not None else None
        self.valid_flag = None
        if self.fbin is not None and len(self.fbin) >= self.read_size:
            self.complete = True
            self.xmagic, self.checksum, self.serial, self.record_id = struct.unpack(RecordTail.FORMAT, self.fbin)
    def load(self, file_handle):
        """Used to continue load of RecordTail object if it is split between files"""
        if not self.is_complete:
            self.fbin += file_handle.read(self.read_size - len(self.fbin))
            if (len(self.fbin)) >= self.read_size:
                self.complete = True
                self.xmagic, self.checksum, self.serial, self.record_id = struct.unpack(RecordTail.FORMAT, self.fbin)
    def is_complete(self):
        return self.complete
    def is_valid(self, record):
        if self.valid_flag is None:
            if not self.complete:
                return False
            self.valid_flag = qls.utils.inv_str(self.xmagic) == record.magic and \
                              self.serial == record.serial and \
                              self.record_id == record.record_id and \
                              qls.utils.adler32(record.checksum_encode()) == self.checksum
        return self.valid_flag
    def to_string(self):
        """Return a string representation of the this RecordTail instance"""
        if self.valid_flag is not None:
            if not self.valid_flag:
                return '[INVALID RECORD TAIL]'
        magic = qls.utils.inv_str(self.xmagic)
        magic_char = magic[-1].upper() if magic[-1] in string.printable else '?'
        return '[%c cs=0x%08x rid=0x%x]' % (magic_char, self.checksum, self.record_id)
    def __str__(self):
        """Return a string representation of the this RecordTail instance"""
        return RecordTail.to_string(self)

class FileHeader(RecordHeader):
    FORMAT = '<2H4x5QH'
    MAGIC = 'QLSf'
    def init(self, file_handle, _, file_header_size_sblks, partition_num, efp_data_size_kb, first_record_offset,
             timestamp_sec, timestamp_ns, file_num, queue_name_len):
        self.file_handle = file_handle
        self.file_header_size_sblks = file_header_size_sblks
        self.partition_num = partition_num
        self.efp_data_size_kb = efp_data_size_kb
        self.first_record_offset = first_record_offset
        self.timestamp_sec = timestamp_sec
        self.timestamp_ns = timestamp_ns
        self.file_num = file_num
        self.queue_name_len = queue_name_len
        self.queue_name = None
    def encode(self):
        if self.queue_name is None:
            return RecordHeader.encode(self) + struct.pack(self.FORMAT, self.file_header_size_sblks, \
                                                           self.partition_num, self.efp_data_size_kb, \
                                                           self.first_record_offset, self.timestamp_sec, \
                                                           self.timestamp_ns, self.file_num, 0)
        return RecordHeader.encode(self) + struct.pack(self.FORMAT, self.file_header_size_sblks, self.partition_num, \
                                                       self.efp_data_size_kb, self.first_record_offset, \
                                                       self.timestamp_sec, self.timestamp_ns, self.file_num, \
                                                       self.queue_name_len) + self.queue_name
    def get_file_size(self):
        """Sum of file header size and data size"""
        return (self.file_header_size_sblks * qls.utils.DEFAULT_SBLK_SIZE) + (self.efp_data_size_kb * 1024)
    def load(self, file_handle):
        self.queue_name = file_handle.read(self.queue_name_len)
    def is_end_of_file(self):
        return self.file_handle.tell() >= self.get_file_size()
    def is_valid(self):
        if not RecordHeader.is_header_valid(self, self):
            return False
        if self.file_handle is None or self.file_header_size_sblks == 0 or self.partition_num == 0 or \
           self.efp_data_size_kb == 0 or self.first_record_offset == 0 or self.timestamp_sec == 0 or \
           self.timestamp_ns == 0 or self.file_num == 0:
            return False
        if self.queue_name_len == 0:
            return False
        if self.queue_name is None:
            return False
        if len(self.queue_name) != self.queue_name_len:
            return False
        return True
    def timestamp_str(self):
        """Get the timestamp of this record in string format"""
        now = time.gmtime(self.timestamp_sec)
        fstr = '%%a %%b %%d %%H:%%M:%%S.%09d %%Y' % (self.timestamp_ns)
        return time.strftime(fstr, now)
    def to_string(self):
        """Return a string representation of the this FileHeader instance"""
        return '%s fnum=0x%x fro=0x%08x p=%d s=%dk t=%s %s' % (RecordHeader.to_string(self), self.file_num,
                                                             self.first_record_offset, self.partition_num,
                                                             self.efp_data_size_kb, self.timestamp_str(),
                                                             self._get_warnings())
    def __str__(self):
        """Return a string representation of the this FileHeader instance"""
        return FileHeader.to_string(self)

class EnqueueRecord(RecordHeader):
    FORMAT = '<2Q'
    MAGIC = 'QLSe'
    EXTERNAL_FLAG_MASK = 0x20
    TRANSIENT_FLAG_MASK = 0x10
    def init(self, _, xid_size, data_size):
        self.xid_size = xid_size
        self.data_size = data_size
        self.xid = None
        self.xid_complete = False
        self.data = None
        self.data_complete = False
        self.record_tail = None
    def checksum_encode(self): # encode excluding record tail
        bytes = RecordHeader.encode(self) + struct.pack(self.FORMAT, self.xid_size, self.data_size)
        if self.xid is not None:
            bytes += self.xid
        if self.data is not None:
            bytes += self.data
        return bytes
    def is_external(self):
        return self.user_flags & EnqueueRecord.EXTERNAL_FLAG_MASK > 0
    def is_transient(self):
        return self.user_flags & EnqueueRecord.TRANSIENT_FLAG_MASK > 0
    def is_valid(self, journal_file):
        if not RecordHeader.is_header_valid(self, journal_file.file_header):
            return False
        if not (self.xid_complete and self.data_complete):
            return False
        if self.xid_size > 0 and len(self.xid) != self.xid_size:
            return False
        if self.data_size > 0 and len(self.data) != self.data_size:
            return False
        if self.xid_size > 0 or self.data_size > 0:
            if self.record_tail is None:
                return False
            if not self.record_tail.is_valid(self):
                return False
        return True
    def load(self, file_handle):
        """Return True when load is incomplete and must be called again with new file handle"""
        self.xid, self.xid_complete = qls.utils.load_data(file_handle, self.xid, self.xid_size)
        if not self.xid_complete:
            return True
        if self.is_external():
            self.data_complete = True
        else:
            self.data, self.data_complete = qls.utils.load_data(file_handle, self.data, self.data_size)
            if not self.data_complete:
                return True
        if self.xid_size > 0 or self.data_size > 0:
            if self.record_tail is None:
                self.record_tail = RecordTail(file_handle)
            elif not self.record_tail.is_complete():
                self.record_tail.load(file_handle) # Continue loading partially loaded tail
            if self.record_tail.is_complete():
                self.record_tail.is_valid(self)
            else:
                return True
        return False
    def to_string(self, show_xid_flag, show_data_flag):
        """Return a string representation of the this EnqueueRecord instance"""
        if self.truncated_flag:
            return '%s xid(%d) data(%d) [Truncated, no more files in journal]' % (RecordHeader.__str__(self),
                                                                                  self.xid_size, self.data_size)
        if self.record_tail is None:
            record_tail_str = ''
        else:
            record_tail_str = self.record_tail.to_string()
        return '%s %s %s %s %s %s' % (RecordHeader.to_string(self),
                                      qls.utils.format_xid(self.xid, self.xid_size, show_xid_flag),
                                      qls.utils.format_data(self.data, self.data_size, show_data_flag),
                                      record_tail_str, self._print_flags(), self._get_warnings())
    def _print_flags(self):
        """Utility function to decode the flags field in the header and print a string representation"""
        fstr = ''
        if self.is_transient():
            fstr = '[TRANSIENT'
        if self.is_external():
            if len(fstr) > 0:
                fstr += ',EXTERNAL'
            else:
                fstr = '*EXTERNAL'
        if len(fstr) > 0:
            fstr += ']'
        return fstr
    def __str__(self):
        """Return a string representation of the this EnqueueRecord instance"""
        return EnqueueRecord.to_string(self, False, False)

class DequeueRecord(RecordHeader):
    FORMAT = '<2Q'
    MAGIC = 'QLSd'
    TXN_COMPLETE_COMMIT_FLAG = 0x10
    def init(self, _, dequeue_record_id, xid_size):
        self.dequeue_record_id = dequeue_record_id
        self.xid_size = xid_size
        self.transaction_prepared_list_flag = False
        self.xid = None
        self.xid_complete = False
        self.record_tail = None
    def checksum_encode(self): # encode excluding record tail
        return RecordHeader.encode(self) + struct.pack(self.FORMAT, self.dequeue_record_id, self.xid_size) + \
            self.xid
    def is_transaction_complete_commit(self):
        return self.user_flags & DequeueRecord.TXN_COMPLETE_COMMIT_FLAG > 0
    def is_valid(self, journal_file):
        if not RecordHeader.is_header_valid(self, journal_file.file_header):
            return False
        if self.xid_size > 0:
            if not self.xid_complete:
                return False
            if self.xid_size > 0 and len(self.xid) != self.xid_size:
                return False
            if self.record_tail is None:
                return False
            if not self.record_tail.is_valid(self):
                return False
        return True
    def load(self, file_handle):
        """Return True when load is incomplete and must be called again with new file handle"""
        self.xid, self.xid_complete = qls.utils.load_data(file_handle, self.xid, self.xid_size)
        if not self.xid_complete:
            return True
        if self.xid_size > 0:
            if self.record_tail is None:
                self.record_tail = RecordTail(file_handle)
            elif not self.record_tail.is_complete():
                self.record_tail.load(file_handle)
            if self.record_tail.is_complete():
                self.record_tail.is_valid(self)
            else:
                return True
        return False
    def to_string(self, show_xid_flag):
        """Return a string representation of the this DequeueRecord instance"""
        if self.truncated_flag:
            return '%s xid(%d) drid=0x%x [Truncated, no more files in journal]' % (RecordHeader.__str__(self),
                                                                                   self.xid_size,
                                                                                   self.dequeue_record_id)
        if self.record_tail is None:
            record_tail_str = ''
        else:
            record_tail_str = self.record_tail.to_string()
        return '%s drid=0x%x %s %s %s %s' % (RecordHeader.to_string(self), self.dequeue_record_id,
                                             qls.utils.format_xid(self.xid, self.xid_size, show_xid_flag),
                                             record_tail_str, self._print_flags(), self._get_warnings())
    def _print_flags(self):
        """Utility function to decode the flags field in the header and print a string representation"""
        if self.transaction_prepared_list_flag:
            if self.is_transaction_complete_commit():
                return '[COMMIT]'
            else:
                return '[ABORT]'
        return ''
    def __str__(self):
        """Return a string representation of the this DequeueRecord instance"""
        return DequeueRecord.to_string(self, False)

class TransactionRecord(RecordHeader):
    FORMAT = '<Q'
    MAGIC_ABORT = 'QLSa'
    MAGIC_COMMIT = 'QLSc'
    def init(self, _, xid_size):
        self.xid_size = xid_size
        self.xid = None
        self.xid_complete = False
        self.record_tail = None
    def checksum_encode(self): # encode excluding record tail
        return RecordHeader.encode(self) + struct.pack(self.FORMAT, self.xid_size) + self.xid
    def is_valid(self, journal_file):
        if not RecordHeader.is_header_valid(self, journal_file.file_header):
            return False
        if not self.xid_complete or len(self.xid) != self.xid_size:
            return False
        if self.record_tail is None:
            return False
        if not self.record_tail.is_valid(self):
            return False
        return True
    def load(self, file_handle):
        """Return True when load is incomplete and must be called again with new file handle"""
        self.xid, self.xid_complete = qls.utils.load_data(file_handle, self.xid, self.xid_size)
        if not self.xid_complete:
            return True
        if self.xid_size > 0:
            if self.record_tail is None:
                self.record_tail = RecordTail(file_handle)
            elif not self.record_tail.is_complete():
                self.record_tail.load(file_handle)
            if self.record_tail.is_complete():
                self.record_tail.is_valid(self)
            else:
                return True
        return False
    def to_string(self, show_xid_flag):
        """Return a string representation of the this TransactionRecord instance"""
        if self.truncated_flag:
            return '%s xid(%d) [Truncated, no more files in journal]' % (RecordHeader.__str__(self), self.xid_size)
        if self.record_tail is None:
            record_tail_str = ''
        else:
            record_tail_str = self.record_tail.to_string()
        return '%s %s %s %s' % (RecordHeader.to_string(self),
                                qls.utils.format_xid(self.xid, self.xid_size, show_xid_flag),
                                record_tail_str, self._get_warnings())
    def __str__(self):
        """Return a string representation of the this TransactionRecord instance"""
        return TransactionRecord.to_string(self, False)

# =============================================================================

CLASSES = {
    'a': TransactionRecord,
    'c': TransactionRecord,
    'd': DequeueRecord,
    'e': EnqueueRecord,
}

if __name__ == '__main__':
    print 'This is a library, and cannot be executed.'