openrvdas.logger.readers.logfile_reader

No module-level documentation available.
  1#!/usr/bin/env python3
  2import json
  3import logging
  4import time
  5
  6try:
  7    import parse
  8    PARSE_INSTALLED = True
  9except ImportError:
 10    PARSE_INSTALLED = False
 11
 12from logger.utils import timestamp  # noqa: E402
 13from logger.utils.das_record import DASRecord  # noqa: E402
 14from logger.readers.text_file_reader import TextFileReader  # noqa: E402
 15from logger.readers.reader import TimestampedReader  # noqa: E402
 16
 17
 18################################################################################
 19# Open and read single-line records from one or more text files.
 20class LogfileReader(TimestampedReader):
 21    """
 22    Read lines from one or more text files. Sequentially open all
 23    files that match the file_spec.
 24
 25    Expect that each line will either be a string prefixed by a timestamp that
 26    follows the time_format parameter (ISO8601 by default) or a line of JSON
 27    encoding a DASRecord.
 28
 29    If line is a string prefixed by a timestamp, return the string. If JSON,
 30    return the DASRecord encoded by the JSON string.
 31    """
 32    ############################
 33    def __init__(self, filebase=None, tail=False, refresh_file_spec=False,
 34                 retry_interval=0.1, interval=0, use_timestamps=False,
 35                 time_acceleration_factor=1.0,
 36                 record_format=None,
 37                 time_format=timestamp.TIME_FORMAT,
 38                 date_format=timestamp.DATE_FORMAT,
 39                 eol=None, quiet=False, **kwargs):
 40        """
 41        ```
 42        filebase     Possibly wildcarded string specifying files to be opened.
 43                     Special case: if file_spec is None, read from stdin.
 44
 45        tail         If False, return None upon reaching end of last file; if
 46                     True, block upon reaching EOF of last file and wait for
 47                     more records.
 48
 49        refresh_file_spec
 50                     If True, refresh the search for matching filenames when
 51                     reaching last EOF to see if any new matching files have
 52                     appeared in the interim.
 53
 54        retry_interval
 55                     If tail and/or refresh_file_spec are True, how long to
 56                     wait before looking to see if any new records or files
 57                     have shown up.
 58
 59        interval
 60                     How long to sleep between returning records. In general
 61                     this should be zero except for debugging purposes.
 62
 63        use_timestamps
 64                     If True, use the timestamps from the log file to determine
 65                     at what interval each record should be emitted.
 66
 67        time_acceleration_factor
 68                     When use_timestamps is True, multiplies the time intervals
 69                     between records by this factor. Values greater than 1.0 will
 70                     speed up playback, values between 0 and 1.0 will slow it down.
 71                     Default is 1.0 (normal speed).
 72
 73        record_format
 74                     If specified, a custom record format to use for extracting
 75                     timestamp and record. The default is '{timestamp:ti} {record}'.
 76
 77        eol          Optional character by which to recognize the end of a record
 78
 79        quiet - if not False, don't complain when unable to parse a record.
 80
 81        ```
 82        Note that the order in which files are opened will probably be in
 83        alphanumeric by filename, but this is not strictly enforced and
 84        depends on how glob returns them.
 85        """
 86        super().__init__(**kwargs)
 87
 88        if not PARSE_INSTALLED:
 89            raise ImportError('LogfileReader requires Python "parse" module; '
 90                              'please run "pip install parse"')
 91        if interval and use_timestamps:
 92            raise ValueError('Can not specify both "interval" and "use_timestamps"')
 93
 94        self.filebase = filebase
 95        self.use_timestamps = use_timestamps
 96
 97        # Validate time_acceleration_factor
 98        if time_acceleration_factor is None:
 99            raise ValueError("time_acceleration_factor must be a number")
100        if not isinstance(time_acceleration_factor, (int, float)):
101            raise ValueError("time_acceleration_factor must be a number")
102        if time_acceleration_factor <= 0:
103            raise ValueError("time_acceleration_factor must be greater than zero")
104        self.time_acceleration_factor = time_acceleration_factor
105
106        self.record_format = record_format or '{timestamp:ti} {record}'
107        self.compiled_record_format = parse.compile(self.record_format)
108        self.date_format = date_format
109        self.time_format = time_format
110        self.tail = tail
111        self.refresh_file_spec = refresh_file_spec
112        self.eol = eol
113        self.quiet = quiet
114
115        # If use_timestamps, we need to keep track of our last_read to
116        # know how long to sleep
117        self.last_timestamp = 0
118        self.last_read = 0
119
120        self._first_msec_timestamp = None
121        self.prev_record = None
122
123        # If they give us a filebase, add wildcard to match its suffixes;
124        # otherwise, we'll pass on the empty string to TextFileReader so
125        # that it uses stdin. NOTE: we should really use a pattern that
126        # echoes timestamp.DATE_FORMAT, e.g.
127        # DATE_FORMAT_WILDCARD = '????-??-??'
128        self.file_spec = filebase + '*' if filebase else None
129        self.reader = TextFileReader(file_spec=self.file_spec,
130                                     tail=tail,
131                                     refresh_file_spec=refresh_file_spec,
132                                     retry_interval=retry_interval,
133                                     interval=interval, eol=eol)
134
135    ############################
136    def read(self):
137        """
138        Return the next line in the file(s), or None if there are no more
139        records (as opposed to '' if the next record is a blank line). To test
140        EOF you'll need to test
141
142          if record is None:
143            no more records...
144
145        rather than simply
146
147          if not record:
148            could be EOF or simply an empty next line
149        """
150        return self._read()
151
152    ############################
153    def _read(self):
154        """Do the work of read(). Internal code that consumes records without
155        handing them downstream (e.g. when seeking) should call this rather
156        than read() because, if we have a mirror_to writer, every record
157        returned by read() is mirrored."""
158
159        # NOTE: It feels like we should check here that the reader's
160        # current file really does match our logfile name format...
161        while True:
162            record = self.reader.read()
163            if not record:  # None means we're out of records
164                return record
165
166            # If we've got a record and we're not using timestamps, we're
167            # done - just return it.
168            if not self.use_timestamps:
169                self.prev_record = record
170                # We need this in case the next call is seek_time() or
171                # read_time_range(). This is less expensive than parsing every
172                # timestamp and keeping self.last_timestamp, but an
173                # alternative might be to implement read_previous(), which
174                # would be expensive but which could be called only when
175                # actually needed.
176
177                # Check whether this is a JSON-encoded DASRecord. If so, return
178                # as a DASRecord; otherwise, just return as string. Yes, this
179                # adds overhead, but our assumption is that the throughput on
180                # a LogfileReader is going to be pretty low.
181                try:
182                    das_record = DASRecord(json_str=record)
183                    return das_record
184                except json.JSONDecodeError:
185                    return record
186
187            # If we're here, we're going to be doling out records according to the
188            # differences in their timestamps.
189
190            # Try to parse the timestamp off the front. If we succeed, grab the
191            # timestamp and break out of loop.
192            try:
193                parsed_record = self.compiled_record_format.parse(record).named
194                ts = parsed_record['timestamp'].timestamp()
195                break
196            # We had a problem parsing as a timestamped string.
197            except (KeyError, ValueError, AttributeError):
198                pass
199
200            # Try parsing as JSON DASRecord. If we succeed, grab the
201            # timestamp and break out of loop.
202            try:
203                record = DASRecord(json_str=record)
204                ts = record.timestamp
205                break
206            except json.JSONDecodeError:
207                pass
208
209            # If we're here, we failed to parse the record. Complain, if appropriate,
210            # then spit out it out without updating timestamps.
211            if not self.quiet:
212                logging.warning('Unable to parse record into DASRecord')
213                logging.warning(f'Unable to parse record into "{self.record_format}"')
214                logging.warning(f'Record: "{record}"')
215            return record
216
217        # If this is not our first read, figure out how long we need to wait
218        # for our next one.
219        if self.last_read > 0:
220            # If here, we've got a record and a timestamp and are intending to
221            # use it. Figure out how long we should sleep before returning it.
222            desired_interval = ts - self.last_timestamp
223
224            # Apply the time acceleration factor to the desired interval
225            desired_interval = desired_interval / self.time_acceleration_factor
226
227            now = timestamp.timestamp()
228            actual_interval = now - self.last_read
229            logging.debug('Desired interval %f, actual %f; sleeping %f',
230                          desired_interval, actual_interval,
231                          max(0, desired_interval - actual_interval))
232            time.sleep(max(0, desired_interval - actual_interval))
233
234        self.last_timestamp = ts
235        self.last_read = timestamp.timestamp()
236
237        self.prev_record = record
238        return record
239
240    ############################
241    def _read_until(self, desired_time_msec):
242        while True:
243            record = self.reader.read()
244            if record is None:
245                return
246            self.prev_record = record
247            if self._get_msec_timestamp(record) >= desired_time_msec:
248                self.reader.seek(-1, 'current')
249                return
250
251    ############################
252    def _reset(self):
253        self.reader.seek(0, 'start')
254
255    ############################
256    def _get_msec_timestamp(self, record):
257        time_str = record.split(' ', 1)[0]
258        return timestamp.timestamp(time_str, time_format=self.time_format) * 1000
259
260    ############################
261    def _peek_msec(self):
262        record = self.reader.read()
263        if record is None:
264            return None
265        self.reader.seek(-1, 'current')
266        return self._get_msec_timestamp(record)
267
268    ############################
269    # Note: this will change the file position if necessary, and should not be used
270    # except where that behavior is appropriate.
271    def _get_first_msec_timestamp(self):
272        if self._first_msec_timestamp is None:
273            self._reset()
274            record = self.reader.read()
275            if record is None:
276                return None
277            self._first_msec_timestamp = self._get_msec_timestamp(record)
278        return self._first_msec_timestamp
279
280    ############################
281    def seek_time(self, offset=0, origin='current'):
282        """
283        Behavior is intended to mimic file seek() behavior but with
284        respect to timestamps.
285        After calling this, the next record read will be the first record
286        whose timestamp is the same as or later than the requested time;
287        if no such record is found, it will read to the end.
288        Exception: if the records are not in exact chronological order,
289        records appearing before the current record but with a later
290        timestamp might be missed.
291
292        Args:
293          offset: offset in msec relative to origin
294          origin: 'start', 'current' or 'end'
295
296        Returns:
297          Requested time in msec, i.e. timestamp of (T0 + offset),
298          where T0 = timestamp(first record) if origin = 'start'
299                   = timestamp(next record) if origin = 'current' and next record is not None
300                   = timestamp(last record) if origin = 'current' and next record is None
301                   = timestamp(last record) if origin = 'end'
302          Returns None if no timestamps were found
303        """
304        if self.filebase is None:
305            raise ValueError('seek_time() not allowed on stdin')
306
307        # TODO: Maybe these are OK, as long as 'end' is defined as the point where
308        # read() returns None for the first time.
309        if self.tail and origin == 'end':
310            raise ValueError('tail=True incompatible with origin == "end"')
311        if self.refresh_file_spec and origin == 'end':
312            raise ValueError('refresh_file_spec=True incompatible with origin == "end"')
313
314        if origin == 'start':
315            if offset < 0:
316                raise ValueError("Can't back up past earliest record")
317            first_timestamp = self._get_first_msec_timestamp()
318            if first_timestamp is None:
319                return None
320            desired_time = first_timestamp + offset
321            if self.prev_record is None:
322                self._reset()
323            else:
324                prev_timestamp = self._get_msec_timestamp(self.prev_record)
325                if prev_timestamp >= desired_time:
326                    self._reset()
327            self._read_until(desired_time)
328            return desired_time
329
330        elif origin == 'current':
331            next_timestamp = self._peek_msec()
332            curr_timestamp = next_timestamp or self._get_msec_timestamp(self.prev_record)
333            if curr_timestamp is None:
334                return None
335            desired_time = curr_timestamp + offset
336            if offset == 0:
337                return desired_time
338            if offset < 0:
339                self._reset()
340            self._read_until(desired_time)
341            return desired_time
342
343        elif origin == 'end':
344            while self._read() is not None:
345                pass
346            if self.prev_record is None:
347                return None
348            end_timestamp = self._get_msec_timestamp(self.prev_record)
349            desired_time = end_timestamp + offset
350            if offset < 0:
351                self._reset()
352                self._read_until(desired_time)
353            return desired_time
354
355        else:
356            raise ValueError('Unknown origin value: "%s"' % origin)
357
358    ############################
359    # Read a range of records beginning with timestamp start
360    # milliseconds, and ending *before* timestamp stop milliseconds.
361    def read_time_range(self, start=None, stop=None):
362        if self.filebase is None:
363            raise ValueError('read_time_range() not allowed on stdin')
364
365        # TODO: Is this needed? stop=None would be OK unless records are
366        # being written faster than they're being read.
367        if stop is None:
368            if self.tail:
369                raise ValueError('tail=True incompatible with stop=None')
370            if self.refresh_file_spec:
371                raise ValueError('refresh_file_spec=True incompatible with stop=None')
372
373        if start is None:
374            starting_offset = 0
375        else:
376            starting_offset = start - self._get_first_msec_timestamp()
377
378        self.seek_time(starting_offset, 'start')
379        records = []
380        while True:
381            record = self.read()
382            if record is None:
383                break
384            if stop and self._get_msec_timestamp(record) >= stop:
385                break
386            records.append(record)
387        return records
class LogfileReader(logger.readers.reader.TimestampedReader):
 21class LogfileReader(TimestampedReader):
 22    """
 23    Read lines from one or more text files. Sequentially open all
 24    files that match the file_spec.
 25
 26    Expect that each line will either be a string prefixed by a timestamp that
 27    follows the time_format parameter (ISO8601 by default) or a line of JSON
 28    encoding a DASRecord.
 29
 30    If line is a string prefixed by a timestamp, return the string. If JSON,
 31    return the DASRecord encoded by the JSON string.
 32    """
 33    ############################
 34    def __init__(self, filebase=None, tail=False, refresh_file_spec=False,
 35                 retry_interval=0.1, interval=0, use_timestamps=False,
 36                 time_acceleration_factor=1.0,
 37                 record_format=None,
 38                 time_format=timestamp.TIME_FORMAT,
 39                 date_format=timestamp.DATE_FORMAT,
 40                 eol=None, quiet=False, **kwargs):
 41        """
 42        ```
 43        filebase     Possibly wildcarded string specifying files to be opened.
 44                     Special case: if file_spec is None, read from stdin.
 45
 46        tail         If False, return None upon reaching end of last file; if
 47                     True, block upon reaching EOF of last file and wait for
 48                     more records.
 49
 50        refresh_file_spec
 51                     If True, refresh the search for matching filenames when
 52                     reaching last EOF to see if any new matching files have
 53                     appeared in the interim.
 54
 55        retry_interval
 56                     If tail and/or refresh_file_spec are True, how long to
 57                     wait before looking to see if any new records or files
 58                     have shown up.
 59
 60        interval
 61                     How long to sleep between returning records. In general
 62                     this should be zero except for debugging purposes.
 63
 64        use_timestamps
 65                     If True, use the timestamps from the log file to determine
 66                     at what interval each record should be emitted.
 67
 68        time_acceleration_factor
 69                     When use_timestamps is True, multiplies the time intervals
 70                     between records by this factor. Values greater than 1.0 will
 71                     speed up playback, values between 0 and 1.0 will slow it down.
 72                     Default is 1.0 (normal speed).
 73
 74        record_format
 75                     If specified, a custom record format to use for extracting
 76                     timestamp and record. The default is '{timestamp:ti} {record}'.
 77
 78        eol          Optional character by which to recognize the end of a record
 79
 80        quiet - if not False, don't complain when unable to parse a record.
 81
 82        ```
 83        Note that the order in which files are opened will probably be in
 84        alphanumeric by filename, but this is not strictly enforced and
 85        depends on how glob returns them.
 86        """
 87        super().__init__(**kwargs)
 88
 89        if not PARSE_INSTALLED:
 90            raise ImportError('LogfileReader requires Python "parse" module; '
 91                              'please run "pip install parse"')
 92        if interval and use_timestamps:
 93            raise ValueError('Can not specify both "interval" and "use_timestamps"')
 94
 95        self.filebase = filebase
 96        self.use_timestamps = use_timestamps
 97
 98        # Validate time_acceleration_factor
 99        if time_acceleration_factor is None:
100            raise ValueError("time_acceleration_factor must be a number")
101        if not isinstance(time_acceleration_factor, (int, float)):
102            raise ValueError("time_acceleration_factor must be a number")
103        if time_acceleration_factor <= 0:
104            raise ValueError("time_acceleration_factor must be greater than zero")
105        self.time_acceleration_factor = time_acceleration_factor
106
107        self.record_format = record_format or '{timestamp:ti} {record}'
108        self.compiled_record_format = parse.compile(self.record_format)
109        self.date_format = date_format
110        self.time_format = time_format
111        self.tail = tail
112        self.refresh_file_spec = refresh_file_spec
113        self.eol = eol
114        self.quiet = quiet
115
116        # If use_timestamps, we need to keep track of our last_read to
117        # know how long to sleep
118        self.last_timestamp = 0
119        self.last_read = 0
120
121        self._first_msec_timestamp = None
122        self.prev_record = None
123
124        # If they give us a filebase, add wildcard to match its suffixes;
125        # otherwise, we'll pass on the empty string to TextFileReader so
126        # that it uses stdin. NOTE: we should really use a pattern that
127        # echoes timestamp.DATE_FORMAT, e.g.
128        # DATE_FORMAT_WILDCARD = '????-??-??'
129        self.file_spec = filebase + '*' if filebase else None
130        self.reader = TextFileReader(file_spec=self.file_spec,
131                                     tail=tail,
132                                     refresh_file_spec=refresh_file_spec,
133                                     retry_interval=retry_interval,
134                                     interval=interval, eol=eol)
135
136    ############################
137    def read(self):
138        """
139        Return the next line in the file(s), or None if there are no more
140        records (as opposed to '' if the next record is a blank line). To test
141        EOF you'll need to test
142
143          if record is None:
144            no more records...
145
146        rather than simply
147
148          if not record:
149            could be EOF or simply an empty next line
150        """
151        return self._read()
152
153    ############################
154    def _read(self):
155        """Do the work of read(). Internal code that consumes records without
156        handing them downstream (e.g. when seeking) should call this rather
157        than read() because, if we have a mirror_to writer, every record
158        returned by read() is mirrored."""
159
160        # NOTE: It feels like we should check here that the reader's
161        # current file really does match our logfile name format...
162        while True:
163            record = self.reader.read()
164            if not record:  # None means we're out of records
165                return record
166
167            # If we've got a record and we're not using timestamps, we're
168            # done - just return it.
169            if not self.use_timestamps:
170                self.prev_record = record
171                # We need this in case the next call is seek_time() or
172                # read_time_range(). This is less expensive than parsing every
173                # timestamp and keeping self.last_timestamp, but an
174                # alternative might be to implement read_previous(), which
175                # would be expensive but which could be called only when
176                # actually needed.
177
178                # Check whether this is a JSON-encoded DASRecord. If so, return
179                # as a DASRecord; otherwise, just return as string. Yes, this
180                # adds overhead, but our assumption is that the throughput on
181                # a LogfileReader is going to be pretty low.
182                try:
183                    das_record = DASRecord(json_str=record)
184                    return das_record
185                except json.JSONDecodeError:
186                    return record
187
188            # If we're here, we're going to be doling out records according to the
189            # differences in their timestamps.
190
191            # Try to parse the timestamp off the front. If we succeed, grab the
192            # timestamp and break out of loop.
193            try:
194                parsed_record = self.compiled_record_format.parse(record).named
195                ts = parsed_record['timestamp'].timestamp()
196                break
197            # We had a problem parsing as a timestamped string.
198            except (KeyError, ValueError, AttributeError):
199                pass
200
201            # Try parsing as JSON DASRecord. If we succeed, grab the
202            # timestamp and break out of loop.
203            try:
204                record = DASRecord(json_str=record)
205                ts = record.timestamp
206                break
207            except json.JSONDecodeError:
208                pass
209
210            # If we're here, we failed to parse the record. Complain, if appropriate,
211            # then spit out it out without updating timestamps.
212            if not self.quiet:
213                logging.warning('Unable to parse record into DASRecord')
214                logging.warning(f'Unable to parse record into "{self.record_format}"')
215                logging.warning(f'Record: "{record}"')
216            return record
217
218        # If this is not our first read, figure out how long we need to wait
219        # for our next one.
220        if self.last_read > 0:
221            # If here, we've got a record and a timestamp and are intending to
222            # use it. Figure out how long we should sleep before returning it.
223            desired_interval = ts - self.last_timestamp
224
225            # Apply the time acceleration factor to the desired interval
226            desired_interval = desired_interval / self.time_acceleration_factor
227
228            now = timestamp.timestamp()
229            actual_interval = now - self.last_read
230            logging.debug('Desired interval %f, actual %f; sleeping %f',
231                          desired_interval, actual_interval,
232                          max(0, desired_interval - actual_interval))
233            time.sleep(max(0, desired_interval - actual_interval))
234
235        self.last_timestamp = ts
236        self.last_read = timestamp.timestamp()
237
238        self.prev_record = record
239        return record
240
241    ############################
242    def _read_until(self, desired_time_msec):
243        while True:
244            record = self.reader.read()
245            if record is None:
246                return
247            self.prev_record = record
248            if self._get_msec_timestamp(record) >= desired_time_msec:
249                self.reader.seek(-1, 'current')
250                return
251
252    ############################
253    def _reset(self):
254        self.reader.seek(0, 'start')
255
256    ############################
257    def _get_msec_timestamp(self, record):
258        time_str = record.split(' ', 1)[0]
259        return timestamp.timestamp(time_str, time_format=self.time_format) * 1000
260
261    ############################
262    def _peek_msec(self):
263        record = self.reader.read()
264        if record is None:
265            return None
266        self.reader.seek(-1, 'current')
267        return self._get_msec_timestamp(record)
268
269    ############################
270    # Note: this will change the file position if necessary, and should not be used
271    # except where that behavior is appropriate.
272    def _get_first_msec_timestamp(self):
273        if self._first_msec_timestamp is None:
274            self._reset()
275            record = self.reader.read()
276            if record is None:
277                return None
278            self._first_msec_timestamp = self._get_msec_timestamp(record)
279        return self._first_msec_timestamp
280
281    ############################
282    def seek_time(self, offset=0, origin='current'):
283        """
284        Behavior is intended to mimic file seek() behavior but with
285        respect to timestamps.
286        After calling this, the next record read will be the first record
287        whose timestamp is the same as or later than the requested time;
288        if no such record is found, it will read to the end.
289        Exception: if the records are not in exact chronological order,
290        records appearing before the current record but with a later
291        timestamp might be missed.
292
293        Args:
294          offset: offset in msec relative to origin
295          origin: 'start', 'current' or 'end'
296
297        Returns:
298          Requested time in msec, i.e. timestamp of (T0 + offset),
299          where T0 = timestamp(first record) if origin = 'start'
300                   = timestamp(next record) if origin = 'current' and next record is not None
301                   = timestamp(last record) if origin = 'current' and next record is None
302                   = timestamp(last record) if origin = 'end'
303          Returns None if no timestamps were found
304        """
305        if self.filebase is None:
306            raise ValueError('seek_time() not allowed on stdin')
307
308        # TODO: Maybe these are OK, as long as 'end' is defined as the point where
309        # read() returns None for the first time.
310        if self.tail and origin == 'end':
311            raise ValueError('tail=True incompatible with origin == "end"')
312        if self.refresh_file_spec and origin == 'end':
313            raise ValueError('refresh_file_spec=True incompatible with origin == "end"')
314
315        if origin == 'start':
316            if offset < 0:
317                raise ValueError("Can't back up past earliest record")
318            first_timestamp = self._get_first_msec_timestamp()
319            if first_timestamp is None:
320                return None
321            desired_time = first_timestamp + offset
322            if self.prev_record is None:
323                self._reset()
324            else:
325                prev_timestamp = self._get_msec_timestamp(self.prev_record)
326                if prev_timestamp >= desired_time:
327                    self._reset()
328            self._read_until(desired_time)
329            return desired_time
330
331        elif origin == 'current':
332            next_timestamp = self._peek_msec()
333            curr_timestamp = next_timestamp or self._get_msec_timestamp(self.prev_record)
334            if curr_timestamp is None:
335                return None
336            desired_time = curr_timestamp + offset
337            if offset == 0:
338                return desired_time
339            if offset < 0:
340                self._reset()
341            self._read_until(desired_time)
342            return desired_time
343
344        elif origin == 'end':
345            while self._read() is not None:
346                pass
347            if self.prev_record is None:
348                return None
349            end_timestamp = self._get_msec_timestamp(self.prev_record)
350            desired_time = end_timestamp + offset
351            if offset < 0:
352                self._reset()
353                self._read_until(desired_time)
354            return desired_time
355
356        else:
357            raise ValueError('Unknown origin value: "%s"' % origin)
358
359    ############################
360    # Read a range of records beginning with timestamp start
361    # milliseconds, and ending *before* timestamp stop milliseconds.
362    def read_time_range(self, start=None, stop=None):
363        if self.filebase is None:
364            raise ValueError('read_time_range() not allowed on stdin')
365
366        # TODO: Is this needed? stop=None would be OK unless records are
367        # being written faster than they're being read.
368        if stop is None:
369            if self.tail:
370                raise ValueError('tail=True incompatible with stop=None')
371            if self.refresh_file_spec:
372                raise ValueError('refresh_file_spec=True incompatible with stop=None')
373
374        if start is None:
375            starting_offset = 0
376        else:
377            starting_offset = start - self._get_first_msec_timestamp()
378
379        self.seek_time(starting_offset, 'start')
380        records = []
381        while True:
382            record = self.read()
383            if record is None:
384                break
385            if stop and self._get_msec_timestamp(record) >= stop:
386                break
387            records.append(record)
388        return records

Read lines from one or more text files. Sequentially open all files that match the file_spec.

Expect that each line will either be a string prefixed by a timestamp that follows the time_format parameter (ISO8601 by default) or a line of JSON encoding a DASRecord.

If line is a string prefixed by a timestamp, return the string. If JSON, return the DASRecord encoded by the JSON string.

LogfileReader( filebase=None, tail=False, refresh_file_spec=False, retry_interval=0.1, interval=0, use_timestamps=False, time_acceleration_factor=1.0, record_format=None, time_format='%Y-%m-%dT%H:%M:%S.%fZ', date_format='%Y-%m-%d', eol=None, quiet=False, **kwargs)
 34    def __init__(self, filebase=None, tail=False, refresh_file_spec=False,
 35                 retry_interval=0.1, interval=0, use_timestamps=False,
 36                 time_acceleration_factor=1.0,
 37                 record_format=None,
 38                 time_format=timestamp.TIME_FORMAT,
 39                 date_format=timestamp.DATE_FORMAT,
 40                 eol=None, quiet=False, **kwargs):
 41        """
 42        ```
 43        filebase     Possibly wildcarded string specifying files to be opened.
 44                     Special case: if file_spec is None, read from stdin.
 45
 46        tail         If False, return None upon reaching end of last file; if
 47                     True, block upon reaching EOF of last file and wait for
 48                     more records.
 49
 50        refresh_file_spec
 51                     If True, refresh the search for matching filenames when
 52                     reaching last EOF to see if any new matching files have
 53                     appeared in the interim.
 54
 55        retry_interval
 56                     If tail and/or refresh_file_spec are True, how long to
 57                     wait before looking to see if any new records or files
 58                     have shown up.
 59
 60        interval
 61                     How long to sleep between returning records. In general
 62                     this should be zero except for debugging purposes.
 63
 64        use_timestamps
 65                     If True, use the timestamps from the log file to determine
 66                     at what interval each record should be emitted.
 67
 68        time_acceleration_factor
 69                     When use_timestamps is True, multiplies the time intervals
 70                     between records by this factor. Values greater than 1.0 will
 71                     speed up playback, values between 0 and 1.0 will slow it down.
 72                     Default is 1.0 (normal speed).
 73
 74        record_format
 75                     If specified, a custom record format to use for extracting
 76                     timestamp and record. The default is '{timestamp:ti} {record}'.
 77
 78        eol          Optional character by which to recognize the end of a record
 79
 80        quiet - if not False, don't complain when unable to parse a record.
 81
 82        ```
 83        Note that the order in which files are opened will probably be in
 84        alphanumeric by filename, but this is not strictly enforced and
 85        depends on how glob returns them.
 86        """
 87        super().__init__(**kwargs)
 88
 89        if not PARSE_INSTALLED:
 90            raise ImportError('LogfileReader requires Python "parse" module; '
 91                              'please run "pip install parse"')
 92        if interval and use_timestamps:
 93            raise ValueError('Can not specify both "interval" and "use_timestamps"')
 94
 95        self.filebase = filebase
 96        self.use_timestamps = use_timestamps
 97
 98        # Validate time_acceleration_factor
 99        if time_acceleration_factor is None:
100            raise ValueError("time_acceleration_factor must be a number")
101        if not isinstance(time_acceleration_factor, (int, float)):
102            raise ValueError("time_acceleration_factor must be a number")
103        if time_acceleration_factor <= 0:
104            raise ValueError("time_acceleration_factor must be greater than zero")
105        self.time_acceleration_factor = time_acceleration_factor
106
107        self.record_format = record_format or '{timestamp:ti} {record}'
108        self.compiled_record_format = parse.compile(self.record_format)
109        self.date_format = date_format
110        self.time_format = time_format
111        self.tail = tail
112        self.refresh_file_spec = refresh_file_spec
113        self.eol = eol
114        self.quiet = quiet
115
116        # If use_timestamps, we need to keep track of our last_read to
117        # know how long to sleep
118        self.last_timestamp = 0
119        self.last_read = 0
120
121        self._first_msec_timestamp = None
122        self.prev_record = None
123
124        # If they give us a filebase, add wildcard to match its suffixes;
125        # otherwise, we'll pass on the empty string to TextFileReader so
126        # that it uses stdin. NOTE: we should really use a pattern that
127        # echoes timestamp.DATE_FORMAT, e.g.
128        # DATE_FORMAT_WILDCARD = '????-??-??'
129        self.file_spec = filebase + '*' if filebase else None
130        self.reader = TextFileReader(file_spec=self.file_spec,
131                                     tail=tail,
132                                     refresh_file_spec=refresh_file_spec,
133                                     retry_interval=retry_interval,
134                                     interval=interval, eol=eol)
filebase     Possibly wildcarded string specifying files to be opened.
             Special case: if file_spec is None, read from stdin.

tail         If False, return None upon reaching end of last file; if
             True, block upon reaching EOF of last file and wait for
             more records.

refresh_file_spec
             If True, refresh the search for matching filenames when
             reaching last EOF to see if any new matching files have
             appeared in the interim.

retry_interval
             If tail and/or refresh_file_spec are True, how long to
             wait before looking to see if any new records or files
             have shown up.

interval
             How long to sleep between returning records. In general
             this should be zero except for debugging purposes.

use_timestamps
             If True, use the timestamps from the log file to determine
             at what interval each record should be emitted.

time_acceleration_factor
             When use_timestamps is True, multiplies the time intervals
             between records by this factor. Values greater than 1.0 will
             speed up playback, values between 0 and 1.0 will slow it down.
             Default is 1.0 (normal speed).

record_format
             If specified, a custom record format to use for extracting
             timestamp and record. The default is '{timestamp:ti} {record}'.

eol          Optional character by which to recognize the end of a record

quiet - if not False, don't complain when unable to parse a record.

Note that the order in which files are opened will probably be in alphanumeric by filename, but this is not strictly enforced and depends on how glob returns them.

filebase
use_timestamps
time_acceleration_factor
record_format
compiled_record_format
date_format
time_format
tail
refresh_file_spec
eol
quiet
last_timestamp
last_read
prev_record
file_spec
reader
def read(self):
137    def read(self):
138        """
139        Return the next line in the file(s), or None if there are no more
140        records (as opposed to '' if the next record is a blank line). To test
141        EOF you'll need to test
142
143          if record is None:
144            no more records...
145
146        rather than simply
147
148          if not record:
149            could be EOF or simply an empty next line
150        """
151        return self._read()

Return the next line in the file(s), or None if there are no more records (as opposed to '' if the next record is a blank line). To test EOF you'll need to test

if record is None: no more records...

rather than simply

if not record: could be EOF or simply an empty next line

def seek_time(self, offset=0, origin='current'):
282    def seek_time(self, offset=0, origin='current'):
283        """
284        Behavior is intended to mimic file seek() behavior but with
285        respect to timestamps.
286        After calling this, the next record read will be the first record
287        whose timestamp is the same as or later than the requested time;
288        if no such record is found, it will read to the end.
289        Exception: if the records are not in exact chronological order,
290        records appearing before the current record but with a later
291        timestamp might be missed.
292
293        Args:
294          offset: offset in msec relative to origin
295          origin: 'start', 'current' or 'end'
296
297        Returns:
298          Requested time in msec, i.e. timestamp of (T0 + offset),
299          where T0 = timestamp(first record) if origin = 'start'
300                   = timestamp(next record) if origin = 'current' and next record is not None
301                   = timestamp(last record) if origin = 'current' and next record is None
302                   = timestamp(last record) if origin = 'end'
303          Returns None if no timestamps were found
304        """
305        if self.filebase is None:
306            raise ValueError('seek_time() not allowed on stdin')
307
308        # TODO: Maybe these are OK, as long as 'end' is defined as the point where
309        # read() returns None for the first time.
310        if self.tail and origin == 'end':
311            raise ValueError('tail=True incompatible with origin == "end"')
312        if self.refresh_file_spec and origin == 'end':
313            raise ValueError('refresh_file_spec=True incompatible with origin == "end"')
314
315        if origin == 'start':
316            if offset < 0:
317                raise ValueError("Can't back up past earliest record")
318            first_timestamp = self._get_first_msec_timestamp()
319            if first_timestamp is None:
320                return None
321            desired_time = first_timestamp + offset
322            if self.prev_record is None:
323                self._reset()
324            else:
325                prev_timestamp = self._get_msec_timestamp(self.prev_record)
326                if prev_timestamp >= desired_time:
327                    self._reset()
328            self._read_until(desired_time)
329            return desired_time
330
331        elif origin == 'current':
332            next_timestamp = self._peek_msec()
333            curr_timestamp = next_timestamp or self._get_msec_timestamp(self.prev_record)
334            if curr_timestamp is None:
335                return None
336            desired_time = curr_timestamp + offset
337            if offset == 0:
338                return desired_time
339            if offset < 0:
340                self._reset()
341            self._read_until(desired_time)
342            return desired_time
343
344        elif origin == 'end':
345            while self._read() is not None:
346                pass
347            if self.prev_record is None:
348                return None
349            end_timestamp = self._get_msec_timestamp(self.prev_record)
350            desired_time = end_timestamp + offset
351            if offset < 0:
352                self._reset()
353                self._read_until(desired_time)
354            return desired_time
355
356        else:
357            raise ValueError('Unknown origin value: "%s"' % origin)

Behavior is intended to mimic file seek() behavior but with respect to timestamps. After calling this, the next record read will be the first record whose timestamp is the same as or later than the requested time; if no such record is found, it will read to the end. Exception: if the records are not in exact chronological order, records appearing before the current record but with a later timestamp might be missed.

Args: offset: offset in msec relative to origin origin: 'start', 'current' or 'end'

Returns: Requested time in msec, i.e. timestamp of (T0 + offset), where T0 = timestamp(first record) if origin = 'start' = timestamp(next record) if origin = 'current' and next record is not None = timestamp(last record) if origin = 'current' and next record is None = timestamp(last record) if origin = 'end' Returns None if no timestamps were found

def read_time_range(self, start=None, stop=None):
362    def read_time_range(self, start=None, stop=None):
363        if self.filebase is None:
364            raise ValueError('read_time_range() not allowed on stdin')
365
366        # TODO: Is this needed? stop=None would be OK unless records are
367        # being written faster than they're being read.
368        if stop is None:
369            if self.tail:
370                raise ValueError('tail=True incompatible with stop=None')
371            if self.refresh_file_spec:
372                raise ValueError('refresh_file_spec=True incompatible with stop=None')
373
374        if start is None:
375            starting_offset = 0
376        else:
377            starting_offset = start - self._get_first_msec_timestamp()
378
379        self.seek_time(starting_offset, 'start')
380        records = []
381        while True:
382            record = self.read()
383            if record is None:
384                break
385            if stop and self._get_msec_timestamp(record) >= stop:
386                break
387            records.append(record)
388        return records