openrvdas.server.config_snapshot

Capture a snapshot of everything that determines how a cruise's data were acquired and processed, so that the data can be understood later and the processing reproduced: the cruise definition, every file it was built from, the device definitions its parsers use, the version of the code, and the environment it ran in. See issue #413.

Usage:

config_snapshot test/NBP1406/NBP1406_cruise.yaml --output /var/data/snapshots
config_snapshot my_cruise.yaml --tar

which writes a directory (and, with --tar, a .tar.gz of it) named _, containing:

MANIFEST.yaml          when and where the snapshot was taken; the OpenRVDAS
                       version; git commit, branch, tag and remote of each
                       repository a file came from, and whether it had
                       uncommitted changes, and its code version (see
                       code_version()); the OS, Python and installed
                       packages; and every captured file with its sha256,
                       size, modification time and git status, and - if it
                       was reached through a symlink - the file it
                       resolves to
expanded_config.yaml   the fully expanded cruise definition, as the logger
                       manager sees it, with passwords, tokens and other
                       secrets redacted
sources/               every file captured, at its path relative to the
                       OpenRVDAS directory (files outside it go under
                       sources/_abs/), so the tree can be loaded again
patches/               for each repository with uncommitted changes, the
                       output of "git diff HEAD"
logger_manager_journal.jsonl
                       the logger manager's journal entries (issue #670)
                       from its last start before this cruise definition
                       was loaded: every mode change, config change,
                       logger start, stop, crash and recovery since then

From the journal, the manifest also records:

  • whether the definition the logger manager loaded is the one being snapshotted, by comparing the sha256 the journal recorded for it at load time with the file's sha256 now;
  • the current state: the active mode, and each logger's config, whether it is running, crashing or failed, and whether the config it is running is identical to the one in this definition (by comparing config hashes), and the code version it was started with - which may differ from the repository's now, if the code has changed since.

Files captured are the cruise definition; every file it includes; the device definition files named by any ParseTransform or RegexParseTransform (or the defaults a ParseTransform uses if it names none), and the files they include; and any LogfileWriter header files.

Source files are copied exactly, so they can be reloaded. If any of them appears to contain a password, token or similar, the manifest lists where, and a warning is printed, so the snapshot can be handled accordingly.

  1#!/usr/bin/env python3
  2"""Capture a snapshot of everything that determines how a cruise's data were
  3acquired and processed, so that the data can be understood later and the
  4processing reproduced: the cruise definition, every file it was built from,
  5the device definitions its parsers use, the version of the code, and the
  6environment it ran in. See issue #413.
  7
  8Usage:
  9
 10    config_snapshot test/NBP1406/NBP1406_cruise.yaml --output /var/data/snapshots
 11    config_snapshot my_cruise.yaml --tar
 12
 13which writes a directory (and, with --tar, a .tar.gz of it) named
 14<cruise id>_<UTC time>, containing:
 15
 16    MANIFEST.yaml          when and where the snapshot was taken; the OpenRVDAS
 17                           version; git commit, branch, tag and remote of each
 18                           repository a file came from, and whether it had
 19                           uncommitted changes, and its code version (see
 20                           code_version()); the OS, Python and installed
 21                           packages; and every captured file with its sha256,
 22                           size, modification time and git status, and - if it
 23                           was reached through a symlink - the file it
 24                           resolves to
 25    expanded_config.yaml   the fully expanded cruise definition, as the logger
 26                           manager sees it, with passwords, tokens and other
 27                           secrets redacted
 28    sources/               every file captured, at its path relative to the
 29                           OpenRVDAS directory (files outside it go under
 30                           sources/_abs/), so the tree can be loaded again
 31    patches/               for each repository with uncommitted changes, the
 32                           output of "git diff HEAD"
 33    logger_manager_journal.jsonl
 34                           the logger manager's journal entries (issue #670)
 35                           from its last start before this cruise definition
 36                           was loaded: every mode change, config change,
 37                           logger start, stop, crash and recovery since then
 38
 39From the journal, the manifest also records:
 40
 41  - whether the definition the logger manager loaded is the one being
 42    snapshotted, by comparing the sha256 the journal recorded for it at load
 43    time with the file's sha256 now;
 44  - the current state: the active mode, and each logger's config, whether it
 45    is running, crashing or failed, and whether the config it is running is
 46    identical to the one in this definition (by comparing config hashes),
 47    and the code version it was started with - which may differ from the
 48    repository's now, if the code has changed since.
 49
 50Files captured are the cruise definition; every file it includes; the device
 51definition files named by any ParseTransform or RegexParseTransform (or the
 52defaults a ParseTransform uses if it names none), and the files they include;
 53and any LogfileWriter header files.
 54
 55Source files are copied exactly, so they can be reloaded. If any of them
 56appears to contain a password, token or similar, the manifest lists where,
 57and a warning is printed, so the snapshot can be handled accordingly.
 58"""
 59import argparse
 60import copy
 61import datetime
 62import glob
 63import hashlib
 64import importlib.metadata
 65import json
 66import logging
 67import os
 68import platform
 69import re
 70import shutil
 71import socket
 72import subprocess
 73import sys
 74import tarfile
 75
 76import yaml
 77
 78from logger.utils import read_config  # noqa: E402
 79from server.state_journal import config_hash  # noqa: E402
 80
 81OPENRVDAS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 82
 83# Default definition path for a ParseTransform that doesn't name one. Kept as
 84# a string rather than imported, so that taking a snapshot doesn't depend on
 85# importing the parser. Must match record_parser.DEFAULT_DEFINITION_PATH.
 86DEFAULT_DEFINITION_PATH = 'logger/devices/*.yaml,contrib/devices/*.yaml'
 87
 88# Transforms that read device definitions, and whether they have a default.
 89PARSER_CLASSES = {
 90    'ParseTransform': DEFAULT_DEFINITION_PATH,
 91    'RegexParseTransform': None,
 92}
 93
 94# Names that suggest a value is a secret. Matched against config keys, and
 95# against keys in source files.
 96SECRET_PATTERN = r'(password|passwd|secret|token|api_?key|credential)'
 97SECRET_KEY = re.compile(SECRET_PATTERN, re.IGNORECASE)
 98SECRET_LINE = re.compile(r'^\s*-?\s*["\']?[\w.-]*' + SECRET_PATTERN +
 99                         r'[\w.-]*["\']?\s*:\s*\S', re.IGNORECASE)
100REDACTED = '<redacted>'
101
102TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
103
104# Where the logger manager writes its journal by default; must match
105# DEFAULT_STATE_JOURNAL in server/logger_manager.py, which isn't imported so
106# that taking a snapshot doesn't import the logger manager.
107DEFAULT_JOURNAL = '/var/log/openrvdas/logger_manager_journal'
108JOURNAL_FILE = 'logger_manager_journal.jsonl'
109
110
111################################################################################
112def _utc_iso(timestamp):
113    return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).strftime(TIME_FORMAT)
114
115
116def _sha256(path):
117    digest = hashlib.sha256()
118    with open(path, 'rb') as f:
119        for block in iter(lambda: f.read(1 << 16), b''):
120            digest.update(block)
121    return digest.hexdigest()
122
123
124def _git(args, cwd):
125    """Run git; return its stripped output, or None if it fails."""
126    try:
127        return subprocess.run(['git'] + args, cwd=cwd, capture_output=True,
128                              text=True, check=True, timeout=30).stdout.strip()
129    except (OSError, subprocess.SubprocessError):
130        return None
131
132
133def code_version(repo_root=OPENRVDAS_ROOT):
134    """A short string identifying the exact code in a git working tree: its
135    'git describe', plus - if it differs from that commit - a hash of the
136    differences, e.g. v2.6.3.dev0-12-g2c1a06f5-dirty.3fa94c1e02ab. The hash
137    covers uncommitted changes and untracked Python files (which 'git
138    describe --dirty' ignores), so two different sets of local edits give
139    two different versions. Returns None if repo_root isn't in a git
140    repository or git isn't available.
141
142    The logger manager records this in its journal each time it starts a
143    logger, and a snapshot records it for the repository, so the two can be
144    compared."""
145    describe = _git(['describe', '--tags', '--always'], repo_root)
146    if describe is None:
147        return None
148    digest = hashlib.sha256()
149    diff = _git(['diff', 'HEAD'], repo_root) or ''
150    digest.update(diff.encode('utf-8'))
151    untracked = _git(['ls-files', '--others', '--exclude-standard', '--', '*.py'],
152                     repo_root) or ''
153    for rel in sorted(untracked.splitlines()):
154        digest.update(b'\0' + rel.encode('utf-8') + b'\0')
155        try:
156            with open(os.path.join(repo_root, rel), 'rb') as f:
157                digest.update(f.read())
158        except OSError:
159            pass
160    if not diff and not untracked:
161        return describe
162    return f'{describe}-dirty.{digest.hexdigest()[:12]}'
163
164
165################################################################################
166def find_definition_files(configs, files_read, errors):
167    """Find the device definition files and header files that the logger
168    configs in an expanded cruise definition refer to, appending each file
169    read to files_read."""
170    def visit(node):
171        if isinstance(node, dict):
172            kwargs = node.get('kwargs') if isinstance(node.get('kwargs'), dict) else {}
173            if node.get('class') in PARSER_CLASSES:
174                definition_path = kwargs.get('definition_path',
175                                             PARSER_CLASSES[node['class']])
176                if definition_path:
177                    _read_definitions(definition_path, files_read, errors)
178            header_file = kwargs.get('header_file') if node.get('class') else None
179            if isinstance(header_file, str):
180                header_file = [header_file]
181            elif isinstance(header_file, dict):
182                header_file = list(header_file.values())
183            for path in header_file or []:
184                path = _resolve(path)
185                if os.path.isfile(path):
186                    files_read.append(path)
187                else:
188                    errors.append(f'Header file not found: "{path}"')
189            for value in node.values():
190                visit(value)
191        elif isinstance(node, list):
192            for value in node:
193                visit(value)
194
195    visit(configs)
196
197
198def _resolve(path):
199    """Loggers run with the OpenRVDAS directory as their working directory,
200    so resolve relative paths against it, whatever ours is."""
201    return path if os.path.isabs(path) else os.path.join(OPENRVDAS_ROOT, path)
202
203
204def _read_definitions(definition_path, files_read, errors):
205    globs = [_resolve(g.strip()) for g in definition_path.split(',') if g.strip()]
206    for pattern in globs:
207        if not glob.glob(pattern):
208            errors.append(f'No device definition files match "{pattern}"')
209    read_config.load_definitions(','.join(globs), files_read=files_read)
210
211
212################################################################################
213def definition_files(cruise_file):
214    """Load and expand a cruise definition, recording every file it is built
215    from. Returns (expanded definition, list of absolute paths in the order
216    first read, list of problems found). Raises ValueError if the definition
217    itself can't be read."""
218    errors, files_read = [], []
219    definition = read_config.read_config(cruise_file, errors=errors, files_read=files_read)
220    if errors:
221        raise ValueError(f'Could not read cruise definition: {"; ".join(errors)}')
222    expanded = read_config.expand_cruise_definition(definition, errors=errors,
223                                                    files_read=files_read)
224    find_definition_files(expanded.get('configs', {}), files_read, errors)
225    return expanded, list(dict.fromkeys(files_read)), errors
226
227
228def definition_file_hashes(cruise_file):
229    """{absolute path: sha256} for every file a cruise definition is built
230    from. The logger manager records this when it loads a definition, so a
231    later snapshot can tell exactly which files have changed since."""
232    _, paths, _ = definition_files(_resolve(cruise_file))
233    hashes = {}
234    for path in paths:
235        try:
236            hashes[path] = _sha256(path)
237        except OSError:
238            hashes[path] = None
239    return hashes
240
241
242################################################################################
243def redact(node):
244    """Return a copy of node with the values of secret-looking keys replaced."""
245    if isinstance(node, dict):
246        return {key: (REDACTED if isinstance(key, str) and SECRET_KEY.search(key)
247                      and value not in (None, '') else redact(value))
248                for key, value in node.items()}
249    if isinstance(node, list):
250        return [redact(value) for value in node]
251    return node
252
253
254def find_secret_lines(path):
255    """Line numbers in a text file that look like they set a secret."""
256    try:
257        with open(path, errors='replace') as f:
258            return [n for n, line in enumerate(f, 1) if SECRET_LINE.search(line)]
259    except OSError:
260        return []
261
262
263################################################################################
264def repository_info(repo_root, captured_paths):
265    """git state of a repository, and the git status of each captured file in
266    it. Returns (info, statuses, diff)."""
267    info = {
268        'root': repo_root,
269        'commit': _git(['rev-parse', 'HEAD'], repo_root),
270        'branch': _git(['rev-parse', '--abbrev-ref', 'HEAD'], repo_root),
271        'describe': _git(['describe', '--tags', '--always', '--dirty'], repo_root),
272        'remote': (_git(['remote', 'get-url', 'origin'], repo_root)
273                   or None),
274        # Comparable with the 'code' the logger manager journals for each logger
275        'code_version': code_version(repo_root),
276    }
277    if info['branch'] == 'HEAD':
278        info['branch'] = None  # detached
279
280    diff = _git(['diff', 'HEAD'], repo_root) or ''
281    info['uncommitted_changes'] = bool(diff)
282
283    # Status of each captured file: clean, modified, untracked or ignored.
284    statuses = {}
285    porcelain = _git(['status', '--porcelain', '--untracked-files=all', '--ignored'],
286                     repo_root) or ''
287    by_path = {}
288    for line in porcelain.splitlines():
289        code, rel = line[:2], line[3:]
290        by_path[rel.split(' -> ')[-1]] = code
291
292    # "git diff HEAD" doesn't show new files that haven't been added to git,
293    # so list untracked Python files: new code that is in use would otherwise
294    # leave no trace in the snapshot. (Only code, so that stray files in a
295    # working tree aren't listed in a manifest that travels with the data.)
296    info['untracked_code'] = sorted(rel for rel, code in by_path.items()
297                                    if code == '??' and rel.endswith('.py'))
298    for path in captured_paths:
299        rel = os.path.relpath(os.path.realpath(path), repo_root)
300        code = by_path.get(rel)
301        statuses[path] = ('clean' if code is None else
302                          'untracked' if code == '??' else
303                          'ignored' if code == '!!' else 'modified')
304    return info, statuses, diff
305
306
307def environment_info():
308    """Where and on what the snapshot was taken."""
309    try:
310        from logger.utils.read_version import get_version
311        version = get_version()
312    except Exception as e:  # noqa: BLE001 - a snapshot must not fail for this
313        version = f'unknown ({type(e).__name__}: {e})'
314
315    packages = {}
316    for dist in importlib.metadata.distributions():
317        name = dist.metadata.get('Name')
318        if name:
319            packages[name] = dist.version
320    return {
321        'openrvdas_version': version,
322        'openrvdas_root': OPENRVDAS_ROOT,
323        'hostname': socket.gethostname(),
324        'user': os.environ.get('USER') or os.environ.get('USERNAME'),
325        'os': platform.platform(),
326        'python': sys.version.split()[0],
327        'python_executable': sys.executable,
328        'packages': dict(sorted(packages.items(), key=lambda kv: kv[0].lower())),
329    }
330
331
332################################################################################
333def read_journal(filebase):
334    """Read the logger manager's journal: a list of (line, record dict), in
335    order. Lines that aren't JSON are skipped."""
336    entries = []
337    for path in sorted(glob.glob(filebase + '-*')):
338        with open(path, errors='replace') as f:
339            for line in f:
340                line = line.rstrip('\n')
341                try:
342                    record = json.loads(line)
343                except ValueError:
344                    continue
345                if isinstance(record, dict) and isinstance(record.get('fields'), dict):
346                    entries.append((line, record))
347    entries.sort(key=lambda entry: entry[1].get('timestamp') or 0)
348    return entries
349
350
351def _same_file(journal_filename, cruise_file):
352    """Is the file the journal says was loaded the one we're snapshotting?
353    The logger manager may have been given a relative path; it runs in the
354    OpenRVDAS directory, so resolve against that."""
355    if not journal_filename:
356        return False
357    return os.path.realpath(_resolve(journal_filename)) == os.path.realpath(cruise_file)
358
359
360def last_load(entries, cruise_file=None):
361    """Index of the latest definition_loaded entry for this cruise file (or
362    for any file, if cruise_file is None), or None if the journal doesn't
363    record it being loaded."""
364    for index in range(len(entries) - 1, -1, -1):
365        record = entries[index][1]
366        if record.get('message_type') == 'definition_loaded' and (
367                cruise_file is None or
368                _same_file(record['fields'].get('filename'), cruise_file)):
369            return index
370    return None
371
372
373def last_loaded_file(journal):
374    """The cruise definition file the logger manager most recently loaded,
375    according to its journal, or None."""
376    entries = read_journal(journal) if journal else []
377    index = last_load(entries)
378    if index is None:
379        return None
380    filename = entries[index][1]['fields'].get('filename')
381    return _resolve(filename) if filename else None
382
383
384def run_start(entries, load_index):
385    """Index of the logger manager's start preceding the load at load_index
386    (or 0 if the journal doesn't go back that far).
387
388    State has to be replayed from here rather than from the load itself:
389    the logger manager applies a newly loaded definition's configs - mode
390    change, loggers started - just before it records definition_loaded, and
391    the state is cumulative in any case."""
392    for index in range(load_index, -1, -1):
393        if entries[index][1].get('message_type') == 'manager_start':
394            return index
395    return 0
396
397
398def _config_matches(config, config_name, journal_sha256):
399    """Is the config the logger manager ran (as hashed in the journal) this
400    definition's config? The data stores add the config's name to each
401    config when it is loaded - so that is what the logger manager hashes -
402    but accept the bare config too, in case a store doesn't."""
403    if config is None or not journal_sha256:
404        return False
405    return journal_sha256 in (config_hash({**config, 'name': config_name}),
406                              config_hash(config))
407
408
409def current_state(records, configs):
410    """Replay journal records to find the active mode and each logger's
411    state, and check each running config against this definition's."""
412    mode = None
413    loggers = {}
414    for record in records:
415        event, fields = record.get('message_type'), record['fields']
416        logger = fields.get('logger')
417        if event == 'mode_changed':
418            mode = fields.get('to')
419        elif event in ('logger_started', 'config_changed'):
420            loggers[logger] = {'config': fields.get('config') or fields.get('to'),
421                               'config_sha256': fields.get('config_sha256'),
422                               'code': fields.get('code'),
423                               'status': 'running', 'since': fields.get('time')}
424        elif event == 'logger_stopped' and logger in loggers:
425            loggers[logger].update(status='stopped', since=fields.get('time'))
426        elif event == 'logger_crashed' and logger in loggers:
427            loggers[logger].update(status='crashing', since=fields.get('time'))
428        elif event == 'logger_recovered' and logger in loggers:
429            loggers[logger].update(status='running', since=fields.get('time'),
430                                   code=fields.get('code', loggers[logger]['code']),
431                                   crashes_before_recovery=fields.get('crashes'))
432        elif event == 'logger_failed' and logger in loggers:
433            loggers[logger].update(status='failed', since=fields.get('time'),
434                                   crashes=fields.get('crashes'))
435        elif event == 'manager_stop':
436            for state in loggers.values():
437                state.update(status='stopped', since=fields.get('time'))
438
439    for state in loggers.values():
440        state['matches_definition'] = _config_matches(
441            configs.get(state['config']), state['config'], state['config_sha256'])
442    return {'as_of': records[-1]['fields'].get('time') if records else None,
443            'active_mode': mode,
444            'loggers': dict(sorted(loggers.items()))}
445
446
447################################################################################
448def take_snapshot(cruise_file=None, output_dir='.', make_tar=False, redact_secrets=True,
449                  loaded_time=None, journal=DEFAULT_JOURNAL):
450    """Snapshot a cruise definition and everything it depends on.
451
452    cruise_file     Path of the cruise definition file. If None, the file the
453                    logger manager most recently loaded, according to its
454                    journal - i.e. a snapshot of what is running now.
455    output_dir      Directory in which to create the snapshot directory.
456    make_tar        Also write <snapshot>.tar.gz next to the directory.
457    redact_secrets  Redact secret-looking values in expanded_config.yaml.
458    loaded_time     Optional datetime (UTC) when the definition was loaded
459                    into the logger manager. Any captured file modified after
460                    it is flagged, since the snapshot may then differ from
461                    what is actually running. If not given, taken from the
462                    logger manager's journal, if it records loading this file.
463    journal         Path prefix of the logger manager's journal files
464                    (--state_journal), or None not to look for them.
465
466    Returns the path of the snapshot directory (or of the .tar.gz, if
467    make_tar is set).
468    """
469    now = datetime.datetime.now(datetime.timezone.utc)
470    if cruise_file is None:
471        cruise_file = last_loaded_file(journal)
472        if cruise_file is None:
473            raise ValueError('No cruise definition given, and no logger manager '
474                             f'journal at {journal} records loading one')
475    cruise_file = os.path.abspath(cruise_file)
476
477    # Load and expand the definition, recording every file it is built from.
478    expanded, captured, errors = definition_files(cruise_file)
479
480    cruise_id = str((expanded.get('cruise') or {}).get('id') or
481                    os.path.splitext(os.path.basename(cruise_file))[0])
482
483    # The logger manager's journal, from when it last loaded this definition.
484    journal_info, journal_lines, state, hashes_at_load = None, [], None, None
485    entries = read_journal(journal) if journal else []
486    if journal and not entries:
487        errors.append(f'No logger manager journal found at {journal}-*')
488    elif entries:
489        start = last_load(entries, cruise_file)
490        if start is None:
491            errors.append(f'The logger manager journal at {journal} does not record '
492                          f'loading {cruise_file}, so the current state is unknown')
493        else:
494            loaded = entries[start][1]['fields']
495            start = run_start(entries, start)
496            file_sha256 = _sha256(cruise_file)
497            journal_lines = [line for line, _ in entries[start:]]
498            journal_info = {
499                'source': journal,
500                'path': JOURNAL_FILE,
501                'entries': len(journal_lines),
502                'since': entries[start][1]['fields'].get('time'),
503                'definition_loaded': loaded.get('loaded_time'),
504                'definition_sha256_at_load': loaded.get('file_sha256'),
505                'definition_unchanged_since_load': loaded.get('file_sha256') == file_sha256,
506            }
507            if not journal_info['definition_unchanged_since_load']:
508                errors.append(f'{cruise_file} has changed since the logger manager loaded '
509                              f'it, so what is running may not match this snapshot')
510            state = current_state([record for _, record in entries[start:]],
511                                  expanded.get('configs', {}))
512            mismatched = [name for name, s in state['loggers'].items()
513                          if not s['matches_definition'] and s['status'] != 'stopped']
514            if mismatched:
515                errors.append('These loggers are running configs that differ from this '
516                              f'definition: {", ".join(mismatched)}')
517            # Which files have changed since the definition was loaded: exact,
518            # if the logger manager recorded each file's hash at load time.
519            hashes_at_load = loaded.get('files')
520            if isinstance(hashes_at_load, dict):
521                journal_info['files_added_since_load'] = sorted(
522                    set(captured) - set(hashes_at_load))
523                journal_info['files_removed_since_load'] = sorted(
524                    set(hashes_at_load) - set(captured))
525                for kind in ('added', 'removed'):
526                    if journal_info[f'files_{kind}_since_load']:
527                        errors.append(f'Files {kind} since the definition was loaded: '
528                                      + ', '.join(journal_info[f'files_{kind}_since_load']))
529            else:
530                hashes_at_load = None
531            if loaded_time is None and loaded.get('loaded_time'):
532                try:
533                    loaded_time = datetime.datetime.strptime(
534                        loaded['loaded_time'], '%Y-%m-%dT%H:%M:%S.%fZ').replace(
535                            tzinfo=datetime.timezone.utc)
536                except ValueError:
537                    pass
538
539    base_name = re.sub(r'[^\w.-]+', '_', cruise_id) + '_' + now.strftime('%Y%m%dT%H%M%SZ')
540    # Two snapshots in the same second get _2, _3... rather than colliding.
541    name, count = base_name, 1
542    while os.path.exists(os.path.join(output_dir, name)) or \
543            os.path.exists(os.path.join(output_dir, name + '.tar.gz')):
544        count += 1
545        name = f'{base_name}_{count}'
546    snapshot_dir = os.path.join(output_dir, name)
547    os.makedirs(snapshot_dir)
548
549    # Copy the files, keeping paths relative to the OpenRVDAS directory.
550    files = []
551    for path in captured:
552        rel = os.path.relpath(path, OPENRVDAS_ROOT)
553        archive_path = (os.path.join('sources', rel) if not rel.startswith('..')
554                        else os.path.join('sources', '_abs', path.lstrip(os.sep)))
555        dest = os.path.join(snapshot_dir, archive_path)
556        os.makedirs(os.path.dirname(dest), exist_ok=True)
557        shutil.copy2(path, dest)
558        stat = os.stat(path)
559        entry = {'path': archive_path, 'source': path, 'sha256': _sha256(path),
560                 'size': stat.st_size, 'modified': _utc_iso(stat.st_mtime)}
561        # Reached through a symlink - such as a calibrations.yaml link to the
562        # current dated file, or a local/ linked to another repository? Then
563        # record what it really is, which the contents alone don't say.
564        real_path = os.path.realpath(path)
565        if real_path != os.path.abspath(path):
566            entry['resolves_to'] = real_path
567        if hashes_at_load is not None:
568            # Exact: compare with the hash recorded when it was loaded
569            entry['modified_after_load'] = (path in hashes_at_load and
570                                            hashes_at_load[path] != entry['sha256'])
571        elif loaded_time is not None:
572            # Approximate: by modification time, which git operations change too
573            entry['modified_after_load'] = stat.st_mtime > loaded_time.timestamp()
574        secret_lines = find_secret_lines(path)
575        if secret_lines:
576            entry['possible_secrets_on_lines'] = secret_lines
577        files.append(entry)
578
579    # The state of each git repository the files came from.
580    repos = {}
581    for entry in files:
582        top = _git(['rev-parse', '--show-toplevel'],
583                   os.path.dirname(os.path.realpath(entry['source'])))
584        repos.setdefault(top, []).append(entry['source'])
585    repositories = []
586    for top, paths in repos.items():
587        if top is None:
588            for entry in files:
589                if entry['source'] in paths:
590                    entry['git'] = 'not in a git repository'
591            continue
592        info, statuses, diff = repository_info(top, paths)
593        if diff:
594            patch_name = re.sub(r'[^\w.-]+', '_', top.strip(os.sep)) + '.diff'
595            os.makedirs(os.path.join(snapshot_dir, 'patches'), exist_ok=True)
596            with open(os.path.join(snapshot_dir, 'patches', patch_name), 'w') as f:
597                f.write(diff + '\n')
598            info['patch'] = os.path.join('patches', patch_name)
599        for entry in files:
600            if entry['source'] in statuses:
601                entry['git'] = statuses[entry['source']]
602        repositories.append(info)
603
604    # The expanded definition, as the logger manager sees it.
605    with open(os.path.join(snapshot_dir, 'expanded_config.yaml'), 'w') as f:
606        yaml.safe_dump(redact(copy.deepcopy(expanded)) if redact_secrets else expanded,
607                       f, sort_keys=False, default_flow_style=False)
608
609    if journal_lines:
610        with open(os.path.join(snapshot_dir, JOURNAL_FILE), 'w') as f:
611            f.write('\n'.join(journal_lines) + '\n')
612
613    manifest = {
614        'snapshot': {
615            'taken': now.strftime(TIME_FORMAT),
616            'cruise_id': cruise_id,
617            'cruise_definition': cruise_file,
618            'cruise_definition_loaded': (loaded_time.strftime(TIME_FORMAT)
619                                         if loaded_time else None),
620            'expanded_definition': 'expanded_config.yaml',
621            'secrets_redacted': redact_secrets,
622        },
623        'environment': environment_info(),
624        'repositories': repositories,
625        'files': files,
626        'journal': journal_info,
627        'current_state': state,
628        'warnings': errors,
629    }
630    with open(os.path.join(snapshot_dir, 'MANIFEST.yaml'), 'w') as f:
631        yaml.safe_dump(manifest, f, sort_keys=False, default_flow_style=False)
632
633    # Only the files' paths are logged; MANIFEST.yaml gives the line numbers.
634    files_with_possible_secrets = [e['path'] for e in files
635                                   if e.get('possible_secrets_on_lines')]
636    if files_with_possible_secrets:
637        logging.warning('These captured files may contain passwords or tokens, '
638                        'copied as-is: %s. See MANIFEST.yaml.',
639                        ', '.join(files_with_possible_secrets))
640    changed = [e['path'] for e in files if e.get('modified_after_load')]
641    if changed:
642        logging.warning('These files have changed since the definition was '
643                        'loaded, so may not match what is running: %s', ', '.join(changed))
644    for error in errors:
645        logging.warning(error)
646
647    if not make_tar:
648        return snapshot_dir
649    tar_path = snapshot_dir + '.tar.gz'
650    with tarfile.open(tar_path, 'w:gz') as tar:
651        tar.add(snapshot_dir, arcname=name)
652    return tar_path
653
654
655################################################################################
656def main(argv=None):
657    parser = argparse.ArgumentParser(
658        description='Snapshot a cruise definition, every file it was built '
659        'from, the device definitions it uses, the code version and the '
660        'environment, so that data can be traced back to how they were '
661        'acquired and processed.')
662    parser.add_argument('cruise_file', nargs='?', default=None,
663                        help='Cruise definition file. If omitted, the one the '
664                        'logger manager most recently loaded, according to its '
665                        'journal: a snapshot of what is running now.')
666    parser.add_argument('--output', default='.',
667                        help='Directory to write the snapshot in (default: .)')
668    parser.add_argument('--tar', action='store_true',
669                        help='Also write the snapshot as a .tar.gz')
670    parser.add_argument('--no-redact', dest='redact', action='store_false',
671                        help='Don\'t redact secrets in expanded_config.yaml')
672    parser.add_argument('--journal', default=DEFAULT_JOURNAL,
673                        help='Path prefix of the logger manager\'s journal files '
674                        f'(default: {DEFAULT_JOURNAL}); "none" not to use one')
675    parser.add_argument('--loaded-time',
676                        help='When the definition was loaded, as UTC '
677                        'YYYY-MM-DDTHH:MM:SSZ; files modified since are flagged')
678    args = parser.parse_args(argv)
679    logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)
680
681    loaded_time = None
682    if args.loaded_time:
683        loaded_time = datetime.datetime.strptime(args.loaded_time, TIME_FORMAT).replace(
684            tzinfo=datetime.timezone.utc)
685    journal = None if args.journal.lower() == 'none' else args.journal
686    print(take_snapshot(args.cruise_file, output_dir=args.output, make_tar=args.tar,
687                        redact_secrets=args.redact, loaded_time=loaded_time,
688                        journal=journal))
689
690
691if __name__ == '__main__':
692    main()
OPENRVDAS_ROOT = $OLDPWD
DEFAULT_DEFINITION_PATH = 'logger/devices/*.yaml,contrib/devices/*.yaml'
PARSER_CLASSES = {'ParseTransform': 'logger/devices/*.yaml,contrib/devices/*.yaml', 'RegexParseTransform': None}
SECRET_PATTERN = '(password|passwd|secret|token|api_?key|credential)'
SECRET_KEY = re.compile('(password|passwd|secret|token|api_?key|credential)', re.IGNORECASE)
SECRET_LINE = re.compile('^\\s*-?\\s*["\\\']?[\\w.-]*(password|passwd|secret|token|api_?key|credential)[\\w.-]*["\\\']?\\s*:\\s*\\S', re.IGNORECASE)
REDACTED = '<redacted>'
TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
DEFAULT_JOURNAL = '/var/log/openrvdas/logger_manager_journal'
JOURNAL_FILE = 'logger_manager_journal.jsonl'
def code_version(repo_root='/home/runner/work/openrvdas/openrvdas'):
134def code_version(repo_root=OPENRVDAS_ROOT):
135    """A short string identifying the exact code in a git working tree: its
136    'git describe', plus - if it differs from that commit - a hash of the
137    differences, e.g. v2.6.3.dev0-12-g2c1a06f5-dirty.3fa94c1e02ab. The hash
138    covers uncommitted changes and untracked Python files (which 'git
139    describe --dirty' ignores), so two different sets of local edits give
140    two different versions. Returns None if repo_root isn't in a git
141    repository or git isn't available.
142
143    The logger manager records this in its journal each time it starts a
144    logger, and a snapshot records it for the repository, so the two can be
145    compared."""
146    describe = _git(['describe', '--tags', '--always'], repo_root)
147    if describe is None:
148        return None
149    digest = hashlib.sha256()
150    diff = _git(['diff', 'HEAD'], repo_root) or ''
151    digest.update(diff.encode('utf-8'))
152    untracked = _git(['ls-files', '--others', '--exclude-standard', '--', '*.py'],
153                     repo_root) or ''
154    for rel in sorted(untracked.splitlines()):
155        digest.update(b'\0' + rel.encode('utf-8') + b'\0')
156        try:
157            with open(os.path.join(repo_root, rel), 'rb') as f:
158                digest.update(f.read())
159        except OSError:
160            pass
161    if not diff and not untracked:
162        return describe
163    return f'{describe}-dirty.{digest.hexdigest()[:12]}'

A short string identifying the exact code in a git working tree: its 'git describe', plus - if it differs from that commit - a hash of the differences, e.g. v2.6.3.dev0-12-g2c1a06f5-dirty.3fa94c1e02ab. The hash covers uncommitted changes and untracked Python files (which 'git describe --dirty' ignores), so two different sets of local edits give two different versions. Returns None if repo_root isn't in a git repository or git isn't available.

The logger manager records this in its journal each time it starts a logger, and a snapshot records it for the repository, so the two can be compared.

def find_definition_files(configs, files_read, errors):
167def find_definition_files(configs, files_read, errors):
168    """Find the device definition files and header files that the logger
169    configs in an expanded cruise definition refer to, appending each file
170    read to files_read."""
171    def visit(node):
172        if isinstance(node, dict):
173            kwargs = node.get('kwargs') if isinstance(node.get('kwargs'), dict) else {}
174            if node.get('class') in PARSER_CLASSES:
175                definition_path = kwargs.get('definition_path',
176                                             PARSER_CLASSES[node['class']])
177                if definition_path:
178                    _read_definitions(definition_path, files_read, errors)
179            header_file = kwargs.get('header_file') if node.get('class') else None
180            if isinstance(header_file, str):
181                header_file = [header_file]
182            elif isinstance(header_file, dict):
183                header_file = list(header_file.values())
184            for path in header_file or []:
185                path = _resolve(path)
186                if os.path.isfile(path):
187                    files_read.append(path)
188                else:
189                    errors.append(f'Header file not found: "{path}"')
190            for value in node.values():
191                visit(value)
192        elif isinstance(node, list):
193            for value in node:
194                visit(value)
195
196    visit(configs)

Find the device definition files and header files that the logger configs in an expanded cruise definition refer to, appending each file read to files_read.

def definition_files(cruise_file):
214def definition_files(cruise_file):
215    """Load and expand a cruise definition, recording every file it is built
216    from. Returns (expanded definition, list of absolute paths in the order
217    first read, list of problems found). Raises ValueError if the definition
218    itself can't be read."""
219    errors, files_read = [], []
220    definition = read_config.read_config(cruise_file, errors=errors, files_read=files_read)
221    if errors:
222        raise ValueError(f'Could not read cruise definition: {"; ".join(errors)}')
223    expanded = read_config.expand_cruise_definition(definition, errors=errors,
224                                                    files_read=files_read)
225    find_definition_files(expanded.get('configs', {}), files_read, errors)
226    return expanded, list(dict.fromkeys(files_read)), errors

Load and expand a cruise definition, recording every file it is built from. Returns (expanded definition, list of absolute paths in the order first read, list of problems found). Raises ValueError if the definition itself can't be read.

def definition_file_hashes(cruise_file):
229def definition_file_hashes(cruise_file):
230    """{absolute path: sha256} for every file a cruise definition is built
231    from. The logger manager records this when it loads a definition, so a
232    later snapshot can tell exactly which files have changed since."""
233    _, paths, _ = definition_files(_resolve(cruise_file))
234    hashes = {}
235    for path in paths:
236        try:
237            hashes[path] = _sha256(path)
238        except OSError:
239            hashes[path] = None
240    return hashes

{absolute path: sha256} for every file a cruise definition is built from. The logger manager records this when it loads a definition, so a later snapshot can tell exactly which files have changed since.

def redact(node):
244def redact(node):
245    """Return a copy of node with the values of secret-looking keys replaced."""
246    if isinstance(node, dict):
247        return {key: (REDACTED if isinstance(key, str) and SECRET_KEY.search(key)
248                      and value not in (None, '') else redact(value))
249                for key, value in node.items()}
250    if isinstance(node, list):
251        return [redact(value) for value in node]
252    return node

Return a copy of node with the values of secret-looking keys replaced.

def find_secret_lines(path):
255def find_secret_lines(path):
256    """Line numbers in a text file that look like they set a secret."""
257    try:
258        with open(path, errors='replace') as f:
259            return [n for n, line in enumerate(f, 1) if SECRET_LINE.search(line)]
260    except OSError:
261        return []

Line numbers in a text file that look like they set a secret.

def repository_info(repo_root, captured_paths):
265def repository_info(repo_root, captured_paths):
266    """git state of a repository, and the git status of each captured file in
267    it. Returns (info, statuses, diff)."""
268    info = {
269        'root': repo_root,
270        'commit': _git(['rev-parse', 'HEAD'], repo_root),
271        'branch': _git(['rev-parse', '--abbrev-ref', 'HEAD'], repo_root),
272        'describe': _git(['describe', '--tags', '--always', '--dirty'], repo_root),
273        'remote': (_git(['remote', 'get-url', 'origin'], repo_root)
274                   or None),
275        # Comparable with the 'code' the logger manager journals for each logger
276        'code_version': code_version(repo_root),
277    }
278    if info['branch'] == 'HEAD':
279        info['branch'] = None  # detached
280
281    diff = _git(['diff', 'HEAD'], repo_root) or ''
282    info['uncommitted_changes'] = bool(diff)
283
284    # Status of each captured file: clean, modified, untracked or ignored.
285    statuses = {}
286    porcelain = _git(['status', '--porcelain', '--untracked-files=all', '--ignored'],
287                     repo_root) or ''
288    by_path = {}
289    for line in porcelain.splitlines():
290        code, rel = line[:2], line[3:]
291        by_path[rel.split(' -> ')[-1]] = code
292
293    # "git diff HEAD" doesn't show new files that haven't been added to git,
294    # so list untracked Python files: new code that is in use would otherwise
295    # leave no trace in the snapshot. (Only code, so that stray files in a
296    # working tree aren't listed in a manifest that travels with the data.)
297    info['untracked_code'] = sorted(rel for rel, code in by_path.items()
298                                    if code == '??' and rel.endswith('.py'))
299    for path in captured_paths:
300        rel = os.path.relpath(os.path.realpath(path), repo_root)
301        code = by_path.get(rel)
302        statuses[path] = ('clean' if code is None else
303                          'untracked' if code == '??' else
304                          'ignored' if code == '!!' else 'modified')
305    return info, statuses, diff

git state of a repository, and the git status of each captured file in it. Returns (info, statuses, diff).

def environment_info():
308def environment_info():
309    """Where and on what the snapshot was taken."""
310    try:
311        from logger.utils.read_version import get_version
312        version = get_version()
313    except Exception as e:  # noqa: BLE001 - a snapshot must not fail for this
314        version = f'unknown ({type(e).__name__}: {e})'
315
316    packages = {}
317    for dist in importlib.metadata.distributions():
318        name = dist.metadata.get('Name')
319        if name:
320            packages[name] = dist.version
321    return {
322        'openrvdas_version': version,
323        'openrvdas_root': OPENRVDAS_ROOT,
324        'hostname': socket.gethostname(),
325        'user': os.environ.get('USER') or os.environ.get('USERNAME'),
326        'os': platform.platform(),
327        'python': sys.version.split()[0],
328        'python_executable': sys.executable,
329        'packages': dict(sorted(packages.items(), key=lambda kv: kv[0].lower())),
330    }

Where and on what the snapshot was taken.

def read_journal(filebase):
334def read_journal(filebase):
335    """Read the logger manager's journal: a list of (line, record dict), in
336    order. Lines that aren't JSON are skipped."""
337    entries = []
338    for path in sorted(glob.glob(filebase + '-*')):
339        with open(path, errors='replace') as f:
340            for line in f:
341                line = line.rstrip('\n')
342                try:
343                    record = json.loads(line)
344                except ValueError:
345                    continue
346                if isinstance(record, dict) and isinstance(record.get('fields'), dict):
347                    entries.append((line, record))
348    entries.sort(key=lambda entry: entry[1].get('timestamp') or 0)
349    return entries

Read the logger manager's journal: a list of (line, record dict), in order. Lines that aren't JSON are skipped.

def last_load(entries, cruise_file=None):
361def last_load(entries, cruise_file=None):
362    """Index of the latest definition_loaded entry for this cruise file (or
363    for any file, if cruise_file is None), or None if the journal doesn't
364    record it being loaded."""
365    for index in range(len(entries) - 1, -1, -1):
366        record = entries[index][1]
367        if record.get('message_type') == 'definition_loaded' and (
368                cruise_file is None or
369                _same_file(record['fields'].get('filename'), cruise_file)):
370            return index
371    return None

Index of the latest definition_loaded entry for this cruise file (or for any file, if cruise_file is None), or None if the journal doesn't record it being loaded.

def last_loaded_file(journal):
374def last_loaded_file(journal):
375    """The cruise definition file the logger manager most recently loaded,
376    according to its journal, or None."""
377    entries = read_journal(journal) if journal else []
378    index = last_load(entries)
379    if index is None:
380        return None
381    filename = entries[index][1]['fields'].get('filename')
382    return _resolve(filename) if filename else None

The cruise definition file the logger manager most recently loaded, according to its journal, or None.

def run_start(entries, load_index):
385def run_start(entries, load_index):
386    """Index of the logger manager's start preceding the load at load_index
387    (or 0 if the journal doesn't go back that far).
388
389    State has to be replayed from here rather than from the load itself:
390    the logger manager applies a newly loaded definition's configs - mode
391    change, loggers started - just before it records definition_loaded, and
392    the state is cumulative in any case."""
393    for index in range(load_index, -1, -1):
394        if entries[index][1].get('message_type') == 'manager_start':
395            return index
396    return 0

Index of the logger manager's start preceding the load at load_index (or 0 if the journal doesn't go back that far).

State has to be replayed from here rather than from the load itself: the logger manager applies a newly loaded definition's configs - mode change, loggers started - just before it records definition_loaded, and the state is cumulative in any case.

def current_state(records, configs):
410def current_state(records, configs):
411    """Replay journal records to find the active mode and each logger's
412    state, and check each running config against this definition's."""
413    mode = None
414    loggers = {}
415    for record in records:
416        event, fields = record.get('message_type'), record['fields']
417        logger = fields.get('logger')
418        if event == 'mode_changed':
419            mode = fields.get('to')
420        elif event in ('logger_started', 'config_changed'):
421            loggers[logger] = {'config': fields.get('config') or fields.get('to'),
422                               'config_sha256': fields.get('config_sha256'),
423                               'code': fields.get('code'),
424                               'status': 'running', 'since': fields.get('time')}
425        elif event == 'logger_stopped' and logger in loggers:
426            loggers[logger].update(status='stopped', since=fields.get('time'))
427        elif event == 'logger_crashed' and logger in loggers:
428            loggers[logger].update(status='crashing', since=fields.get('time'))
429        elif event == 'logger_recovered' and logger in loggers:
430            loggers[logger].update(status='running', since=fields.get('time'),
431                                   code=fields.get('code', loggers[logger]['code']),
432                                   crashes_before_recovery=fields.get('crashes'))
433        elif event == 'logger_failed' and logger in loggers:
434            loggers[logger].update(status='failed', since=fields.get('time'),
435                                   crashes=fields.get('crashes'))
436        elif event == 'manager_stop':
437            for state in loggers.values():
438                state.update(status='stopped', since=fields.get('time'))
439
440    for state in loggers.values():
441        state['matches_definition'] = _config_matches(
442            configs.get(state['config']), state['config'], state['config_sha256'])
443    return {'as_of': records[-1]['fields'].get('time') if records else None,
444            'active_mode': mode,
445            'loggers': dict(sorted(loggers.items()))}

Replay journal records to find the active mode and each logger's state, and check each running config against this definition's.

def take_snapshot( cruise_file=None, output_dir='.', make_tar=False, redact_secrets=True, loaded_time=None, journal='/var/log/openrvdas/logger_manager_journal'):
449def take_snapshot(cruise_file=None, output_dir='.', make_tar=False, redact_secrets=True,
450                  loaded_time=None, journal=DEFAULT_JOURNAL):
451    """Snapshot a cruise definition and everything it depends on.
452
453    cruise_file     Path of the cruise definition file. If None, the file the
454                    logger manager most recently loaded, according to its
455                    journal - i.e. a snapshot of what is running now.
456    output_dir      Directory in which to create the snapshot directory.
457    make_tar        Also write <snapshot>.tar.gz next to the directory.
458    redact_secrets  Redact secret-looking values in expanded_config.yaml.
459    loaded_time     Optional datetime (UTC) when the definition was loaded
460                    into the logger manager. Any captured file modified after
461                    it is flagged, since the snapshot may then differ from
462                    what is actually running. If not given, taken from the
463                    logger manager's journal, if it records loading this file.
464    journal         Path prefix of the logger manager's journal files
465                    (--state_journal), or None not to look for them.
466
467    Returns the path of the snapshot directory (or of the .tar.gz, if
468    make_tar is set).
469    """
470    now = datetime.datetime.now(datetime.timezone.utc)
471    if cruise_file is None:
472        cruise_file = last_loaded_file(journal)
473        if cruise_file is None:
474            raise ValueError('No cruise definition given, and no logger manager '
475                             f'journal at {journal} records loading one')
476    cruise_file = os.path.abspath(cruise_file)
477
478    # Load and expand the definition, recording every file it is built from.
479    expanded, captured, errors = definition_files(cruise_file)
480
481    cruise_id = str((expanded.get('cruise') or {}).get('id') or
482                    os.path.splitext(os.path.basename(cruise_file))[0])
483
484    # The logger manager's journal, from when it last loaded this definition.
485    journal_info, journal_lines, state, hashes_at_load = None, [], None, None
486    entries = read_journal(journal) if journal else []
487    if journal and not entries:
488        errors.append(f'No logger manager journal found at {journal}-*')
489    elif entries:
490        start = last_load(entries, cruise_file)
491        if start is None:
492            errors.append(f'The logger manager journal at {journal} does not record '
493                          f'loading {cruise_file}, so the current state is unknown')
494        else:
495            loaded = entries[start][1]['fields']
496            start = run_start(entries, start)
497            file_sha256 = _sha256(cruise_file)
498            journal_lines = [line for line, _ in entries[start:]]
499            journal_info = {
500                'source': journal,
501                'path': JOURNAL_FILE,
502                'entries': len(journal_lines),
503                'since': entries[start][1]['fields'].get('time'),
504                'definition_loaded': loaded.get('loaded_time'),
505                'definition_sha256_at_load': loaded.get('file_sha256'),
506                'definition_unchanged_since_load': loaded.get('file_sha256') == file_sha256,
507            }
508            if not journal_info['definition_unchanged_since_load']:
509                errors.append(f'{cruise_file} has changed since the logger manager loaded '
510                              f'it, so what is running may not match this snapshot')
511            state = current_state([record for _, record in entries[start:]],
512                                  expanded.get('configs', {}))
513            mismatched = [name for name, s in state['loggers'].items()
514                          if not s['matches_definition'] and s['status'] != 'stopped']
515            if mismatched:
516                errors.append('These loggers are running configs that differ from this '
517                              f'definition: {", ".join(mismatched)}')
518            # Which files have changed since the definition was loaded: exact,
519            # if the logger manager recorded each file's hash at load time.
520            hashes_at_load = loaded.get('files')
521            if isinstance(hashes_at_load, dict):
522                journal_info['files_added_since_load'] = sorted(
523                    set(captured) - set(hashes_at_load))
524                journal_info['files_removed_since_load'] = sorted(
525                    set(hashes_at_load) - set(captured))
526                for kind in ('added', 'removed'):
527                    if journal_info[f'files_{kind}_since_load']:
528                        errors.append(f'Files {kind} since the definition was loaded: '
529                                      + ', '.join(journal_info[f'files_{kind}_since_load']))
530            else:
531                hashes_at_load = None
532            if loaded_time is None and loaded.get('loaded_time'):
533                try:
534                    loaded_time = datetime.datetime.strptime(
535                        loaded['loaded_time'], '%Y-%m-%dT%H:%M:%S.%fZ').replace(
536                            tzinfo=datetime.timezone.utc)
537                except ValueError:
538                    pass
539
540    base_name = re.sub(r'[^\w.-]+', '_', cruise_id) + '_' + now.strftime('%Y%m%dT%H%M%SZ')
541    # Two snapshots in the same second get _2, _3... rather than colliding.
542    name, count = base_name, 1
543    while os.path.exists(os.path.join(output_dir, name)) or \
544            os.path.exists(os.path.join(output_dir, name + '.tar.gz')):
545        count += 1
546        name = f'{base_name}_{count}'
547    snapshot_dir = os.path.join(output_dir, name)
548    os.makedirs(snapshot_dir)
549
550    # Copy the files, keeping paths relative to the OpenRVDAS directory.
551    files = []
552    for path in captured:
553        rel = os.path.relpath(path, OPENRVDAS_ROOT)
554        archive_path = (os.path.join('sources', rel) if not rel.startswith('..')
555                        else os.path.join('sources', '_abs', path.lstrip(os.sep)))
556        dest = os.path.join(snapshot_dir, archive_path)
557        os.makedirs(os.path.dirname(dest), exist_ok=True)
558        shutil.copy2(path, dest)
559        stat = os.stat(path)
560        entry = {'path': archive_path, 'source': path, 'sha256': _sha256(path),
561                 'size': stat.st_size, 'modified': _utc_iso(stat.st_mtime)}
562        # Reached through a symlink - such as a calibrations.yaml link to the
563        # current dated file, or a local/ linked to another repository? Then
564        # record what it really is, which the contents alone don't say.
565        real_path = os.path.realpath(path)
566        if real_path != os.path.abspath(path):
567            entry['resolves_to'] = real_path
568        if hashes_at_load is not None:
569            # Exact: compare with the hash recorded when it was loaded
570            entry['modified_after_load'] = (path in hashes_at_load and
571                                            hashes_at_load[path] != entry['sha256'])
572        elif loaded_time is not None:
573            # Approximate: by modification time, which git operations change too
574            entry['modified_after_load'] = stat.st_mtime > loaded_time.timestamp()
575        secret_lines = find_secret_lines(path)
576        if secret_lines:
577            entry['possible_secrets_on_lines'] = secret_lines
578        files.append(entry)
579
580    # The state of each git repository the files came from.
581    repos = {}
582    for entry in files:
583        top = _git(['rev-parse', '--show-toplevel'],
584                   os.path.dirname(os.path.realpath(entry['source'])))
585        repos.setdefault(top, []).append(entry['source'])
586    repositories = []
587    for top, paths in repos.items():
588        if top is None:
589            for entry in files:
590                if entry['source'] in paths:
591                    entry['git'] = 'not in a git repository'
592            continue
593        info, statuses, diff = repository_info(top, paths)
594        if diff:
595            patch_name = re.sub(r'[^\w.-]+', '_', top.strip(os.sep)) + '.diff'
596            os.makedirs(os.path.join(snapshot_dir, 'patches'), exist_ok=True)
597            with open(os.path.join(snapshot_dir, 'patches', patch_name), 'w') as f:
598                f.write(diff + '\n')
599            info['patch'] = os.path.join('patches', patch_name)
600        for entry in files:
601            if entry['source'] in statuses:
602                entry['git'] = statuses[entry['source']]
603        repositories.append(info)
604
605    # The expanded definition, as the logger manager sees it.
606    with open(os.path.join(snapshot_dir, 'expanded_config.yaml'), 'w') as f:
607        yaml.safe_dump(redact(copy.deepcopy(expanded)) if redact_secrets else expanded,
608                       f, sort_keys=False, default_flow_style=False)
609
610    if journal_lines:
611        with open(os.path.join(snapshot_dir, JOURNAL_FILE), 'w') as f:
612            f.write('\n'.join(journal_lines) + '\n')
613
614    manifest = {
615        'snapshot': {
616            'taken': now.strftime(TIME_FORMAT),
617            'cruise_id': cruise_id,
618            'cruise_definition': cruise_file,
619            'cruise_definition_loaded': (loaded_time.strftime(TIME_FORMAT)
620                                         if loaded_time else None),
621            'expanded_definition': 'expanded_config.yaml',
622            'secrets_redacted': redact_secrets,
623        },
624        'environment': environment_info(),
625        'repositories': repositories,
626        'files': files,
627        'journal': journal_info,
628        'current_state': state,
629        'warnings': errors,
630    }
631    with open(os.path.join(snapshot_dir, 'MANIFEST.yaml'), 'w') as f:
632        yaml.safe_dump(manifest, f, sort_keys=False, default_flow_style=False)
633
634    # Only the files' paths are logged; MANIFEST.yaml gives the line numbers.
635    files_with_possible_secrets = [e['path'] for e in files
636                                   if e.get('possible_secrets_on_lines')]
637    if files_with_possible_secrets:
638        logging.warning('These captured files may contain passwords or tokens, '
639                        'copied as-is: %s. See MANIFEST.yaml.',
640                        ', '.join(files_with_possible_secrets))
641    changed = [e['path'] for e in files if e.get('modified_after_load')]
642    if changed:
643        logging.warning('These files have changed since the definition was '
644                        'loaded, so may not match what is running: %s', ', '.join(changed))
645    for error in errors:
646        logging.warning(error)
647
648    if not make_tar:
649        return snapshot_dir
650    tar_path = snapshot_dir + '.tar.gz'
651    with tarfile.open(tar_path, 'w:gz') as tar:
652        tar.add(snapshot_dir, arcname=name)
653    return tar_path

Snapshot a cruise definition and everything it depends on.

cruise_file Path of the cruise definition file. If None, the file the logger manager most recently loaded, according to its journal - i.e. a snapshot of what is running now. output_dir Directory in which to create the snapshot directory. make_tar Also write .tar.gz next to the directory. redact_secrets Redact secret-looking values in expanded_config.yaml. loaded_time Optional datetime (UTC) when the definition was loaded into the logger manager. Any captured file modified after it is flagged, since the snapshot may then differ from what is actually running. If not given, taken from the logger manager's journal, if it records loading this file. journal Path prefix of the logger manager's journal files (--state_journal), or None not to look for them.

Returns the path of the snapshot directory (or of the .tar.gz, if make_tar is set).

def main(argv=None):
657def main(argv=None):
658    parser = argparse.ArgumentParser(
659        description='Snapshot a cruise definition, every file it was built '
660        'from, the device definitions it uses, the code version and the '
661        'environment, so that data can be traced back to how they were '
662        'acquired and processed.')
663    parser.add_argument('cruise_file', nargs='?', default=None,
664                        help='Cruise definition file. If omitted, the one the '
665                        'logger manager most recently loaded, according to its '
666                        'journal: a snapshot of what is running now.')
667    parser.add_argument('--output', default='.',
668                        help='Directory to write the snapshot in (default: .)')
669    parser.add_argument('--tar', action='store_true',
670                        help='Also write the snapshot as a .tar.gz')
671    parser.add_argument('--no-redact', dest='redact', action='store_false',
672                        help='Don\'t redact secrets in expanded_config.yaml')
673    parser.add_argument('--journal', default=DEFAULT_JOURNAL,
674                        help='Path prefix of the logger manager\'s journal files '
675                        f'(default: {DEFAULT_JOURNAL}); "none" not to use one')
676    parser.add_argument('--loaded-time',
677                        help='When the definition was loaded, as UTC '
678                        'YYYY-MM-DDTHH:MM:SSZ; files modified since are flagged')
679    args = parser.parse_args(argv)
680    logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)
681
682    loaded_time = None
683    if args.loaded_time:
684        loaded_time = datetime.datetime.strptime(args.loaded_time, TIME_FORMAT).replace(
685            tzinfo=datetime.timezone.utc)
686    journal = None if args.journal.lower() == 'none' else args.journal
687    print(take_snapshot(args.cruise_file, output_dir=args.output, make_tar=args.tar,
688                        redact_secrets=args.redact, loaded_time=loaded_time,
689                        journal=journal))