|
| 1 | +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================== |
| 15 | + |
| 16 | +"""Implementation for a multi-file directory loader.""" |
| 17 | + |
| 18 | +from __future__ import absolute_import |
| 19 | +from __future__ import division |
| 20 | +from __future__ import print_function |
| 21 | + |
| 22 | +from tensorboard.backend.event_processing import directory_watcher |
| 23 | +from tensorboard.backend.event_processing import io_wrapper |
| 24 | +from tensorboard.compat import tf |
| 25 | +from tensorboard.util import tb_logging |
| 26 | + |
| 27 | + |
| 28 | +logger = tb_logging.get_logger() |
| 29 | + |
| 30 | + |
| 31 | +# Sentinel object for an inactive path. |
| 32 | +_INACTIVE = object() |
| 33 | + |
| 34 | + |
| 35 | +class DirectoryLoader(object): |
| 36 | + """Loader for an entire directory, maintaining multiple active file loaders. |
| 37 | +
|
| 38 | + This class takes a directory, a factory for loaders, and optionally a |
| 39 | + path filter and watches all the paths inside that directory for new data. |
| 40 | + Each file loader created by the factory must read a path and produce an |
| 41 | + iterator of (timestamp, value) pairs. |
| 42 | +
|
| 43 | + Unlike DirectoryWatcher, this class does not assume that only one file |
| 44 | + receives new data at a time; there can be arbitrarily many active files. |
| 45 | + However, any file whose maximum load timestamp fails an "active" predicate |
| 46 | + will be marked as inactive and no longer checked for new data. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, directory, loader_factory, path_filter=lambda x: True, |
| 50 | + active_filter=lambda timestamp: True): |
| 51 | + """Constructs a new MultiFileDirectoryLoader. |
| 52 | +
|
| 53 | + Args: |
| 54 | + directory: The directory to load files from. |
| 55 | + loader_factory: A factory for creating loaders. The factory should take a |
| 56 | + path and return an object that has a Load method returning an iterator |
| 57 | + yielding (unix timestamp as float, value) pairs for any new data |
| 58 | + path_filter: If specified, only paths matching this filter are loaded. |
| 59 | + active_filter: If specified, any loader whose maximum load timestamp does |
| 60 | + not pass this filter will be marked as inactive and no longer read. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + ValueError: If directory or loader_factory are None. |
| 64 | + """ |
| 65 | + if directory is None: |
| 66 | + raise ValueError('A directory is required') |
| 67 | + if loader_factory is None: |
| 68 | + raise ValueError('A loader factory is required') |
| 69 | + self._directory = directory |
| 70 | + self._loader_factory = loader_factory |
| 71 | + self._path_filter = path_filter |
| 72 | + self._active_filter = active_filter |
| 73 | + self._loaders = {} |
| 74 | + self._max_timestamps = {} |
| 75 | + |
| 76 | + def Load(self): |
| 77 | + """Loads new values from all active files. |
| 78 | +
|
| 79 | + Yields: |
| 80 | + All values that have not been yielded yet. |
| 81 | +
|
| 82 | + Raises: |
| 83 | + DirectoryDeletedError: If the directory has been permanently deleted |
| 84 | + (as opposed to being temporarily unavailable). |
| 85 | + """ |
| 86 | + try: |
| 87 | + all_paths = io_wrapper.ListDirectoryAbsolute(self._directory) |
| 88 | + paths = sorted(p for p in all_paths if self._path_filter(p)) |
| 89 | + for path in paths: |
| 90 | + for value in self._LoadPath(path): |
| 91 | + yield value |
| 92 | + except tf.errors.OpError as e: |
| 93 | + if not tf.io.gfile.exists(self._directory): |
| 94 | + raise directory_watcher.DirectoryDeletedError( |
| 95 | + 'Directory %s has been permanently deleted' % self._directory) |
| 96 | + else: |
| 97 | + logger.info('Ignoring error during file loading: %s' % e) |
| 98 | + |
| 99 | + def _LoadPath(self, path): |
| 100 | + """Generator for values from a single path's loader. |
| 101 | +
|
| 102 | + Args: |
| 103 | + path: the path to load from |
| 104 | +
|
| 105 | + Yields: |
| 106 | + All values from this path's loader that have not been yielded yet. |
| 107 | + """ |
| 108 | + max_timestamp = self._max_timestamps.get(path, None) |
| 109 | + if max_timestamp is _INACTIVE or self._MarkIfInactive(path, max_timestamp): |
| 110 | + logger.debug('Skipping inactive path %s', path) |
| 111 | + return |
| 112 | + loader = self._loaders.get(path, None) |
| 113 | + if loader is None: |
| 114 | + try: |
| 115 | + loader = self._loader_factory(path) |
| 116 | + except tf.errors.NotFoundError: |
| 117 | + # Happens if a file was removed after we listed the directory. |
| 118 | + logger.debug('Skipping nonexistent path %s', path) |
| 119 | + return |
| 120 | + self._loaders[path] = loader |
| 121 | + logger.info('Loading data from path %s', path) |
| 122 | + for timestamp, value in loader.Load(): |
| 123 | + if max_timestamp is None or timestamp > max_timestamp: |
| 124 | + max_timestamp = timestamp |
| 125 | + yield value |
| 126 | + if not self._MarkIfInactive(path, max_timestamp): |
| 127 | + self._max_timestamps[path] = max_timestamp |
| 128 | + |
| 129 | + def _MarkIfInactive(self, path, max_timestamp): |
| 130 | + """If max_timestamp is inactive, returns True and marks the path as such.""" |
| 131 | + logger.debug('Checking active status of %s at %s', path, max_timestamp) |
| 132 | + if max_timestamp is not None and not self._active_filter(max_timestamp): |
| 133 | + self._max_timestamps[path] = _INACTIVE |
| 134 | + del self._loaders[path] |
| 135 | + return True |
| 136 | + return False |
0 commit comments