#!/usr/bin/python
"""Make a CEP report now, for a node or an installation with no Internet access.

On a node (run as root):

  cep-report-now [-o DIR] [--anonymize]

runs the CEP scripts of /usr/share/virtuozzo/cep-scripts the way the
disp-helper daemon does and writes DIR/report-<host>-<date>.tar.gz (default
DIR: the current directory) in the format the daemon sends: ./result.json,
a copy of the logs of "logs_to_collect" in /etc/vz/disp_helper.json,
masked and folded as the daemon does, and on a storage management node the
storage cluster reports (a node whose backend_info.py is older than this
tool leaves them in the daemon's archive instead; the tool says so, and in
the installation manifest as a "# note:" line naming the nodes). Nothing is
sent. The daemon, its
schedule (/vz/tmp/cep/.sent), its archive and the logs are not touched. The
scripts do what they do in a weekly run: host_config_snapshot.py, for one,
keeps a snapshot of the host configuration in /var/lib/vz-upgrade.
It takes from half a minute to some minutes; a script that runs longer than
601 s is stopped, as by the daemon, and its section is missing.

For an installation (run as root on any node that reaches the others):

  cep-report-now --name NAME --nodes NODE [NODE ...] [-o DIR] [--jobs N]
                 [--anonymize]

logs in to each NODE as root by ssh, makes the node report there as above
(the tool need not be installed there, only Python) and packs all of them
into one file DIR/cep-report-NAME-<date>.tar.gz:

  cep-report-NAME-<date>/report-<node>.tar.gz   one per node that succeeded
  cep-report-NAME-<date>/MANIFEST.sha256        sha256 of each node report,
                                                every node that failed with
                                                the reason ("# node"), and the
                                                notes of the nodes ("# note")

Nodes run --jobs at a time (default 4). Without ssh keys every node asks for
its password, and a node not yet in known_hosts asks to accept its key: use
--jobs 1 then, or log in to each node once before. --ssh-command replaces the
default ssh command, which only adds a keepalive so a dead link is noticed in
about a minute (for example "ssh -i /root/.ssh/cep_key"). A failed node does
not stop the others; the exit code is 1 if any node failed. A run stopped by
Ctrl-C leaves no file: the nodes already collected are not packed, and a node
still collecting finishes its current script (up to 601 s) before it exits.

Check the file before handing it over:

  tar -xzf cep-report-NAME-<date>.tar.gz
  cd cep-report-NAME-<date> && sha256sum -c MANIFEST.sha256
  tar -xzOf report-<node>.tar.gz ./result.json | python -m json.tool | less

The reports are plain JSON and text. They hold the data the node would send
to Virtuozzo by itself: hardware and licence identifiers, host names, IP and
MAC addresses, guest names. --anonymize (both modes) applies the masking the
scripts apply on Virtuozzo Hybrid Infrastructure to result.json (but the
package list) and to the log copies: an IP address written as a word of its
own becomes XXX.XXX.XXX.XXX (also with a netmask after it; IPv6 becomes
XXXX:...:XXXX, a port after an address XXX), a MAC address of the form
aa:bb:cc:dd:ee:ff becomes a 32-digit code that is the same for the same
address in every report, so one guest can still be followed from report to
report. It is a pseudonym, not an erasure, and it recognises only these two
forms: an address inside a URL or a path (a repository baseurl keeps its
host), an address glued to a colon (addr:10.1.2.3), an address range, a MAC
written with dashes or dots, the second of two MACs separated by one
character, an InfiniBand address and the storage
cluster reports stay as they are, as do serial numbers, licence data, HWID,
host and guest names and configuration text; a four-part version such as
1.0.58.1 standing alone is masked like an address, and the code of a MAC
differs between upper and lower case. The NODE names or addresses given on
the command line stay in the file names and in the manifest.
Review the result before handing it over.
The sha256 manifest shows that a file was not
damaged on the way. It is not a protection against editing: whoever can run
this tool can change a report and compute the sums again.

Hand the file to your Virtuozzo Technical Account Manager by the channel you
agreed on. Each node report is uploaded as that node's regular weekly report.
"""

from __future__ import print_function

import argparse
import calendar
from contextlib import closing
import errno
import gzip
import hashlib
import json
import os
import re
import shlex
import shutil
import signal
import socket
import stat
import struct
import subprocess
import sys
import tarfile
import tempfile
import time
import zlib

PROG = "cep-report-now"
# Paths, the interpreter, the script order, the 601 s limit, the locale and
# the log masks follow disp-helper 1.0.38 (Client.cpp Collector,
# Utils.cpp SafeExecute) and its systemd environment.
SCRIPTS_DIR = "/usr/share/virtuozzo/cep-scripts"
SETTINGS = "/etc/vz/disp_helper.json"
# backend_info.py older than this release packs the storage cluster reports
# into the daemon's archive, whatever directory it was given; this function
# of it is what packs them next to the given directory instead.
BACKEND_INFO = "backend_info.py"
RESULTS_DIR_MARK = b"def results_dir("
# Prefix of a stderr line a node wants in the installation manifest.
NOTE = "note: "
PYTHON = "/usr/bin/python"
BUILDER = "infra_builder.py"
LAST_SCRIPT = "backend_info.py"
SCRIPT_TIMEOUT = 601
CHILD_ENV = {"LANG": "en_US.UTF-8",
             "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"}
LOG_MASKS = (
    (re.compile(br"\d*:\d*:[0-9.]*"), b"XX:XX:XX"),
    (re.compile(br"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
                br"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"),
     b"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"),
    (re.compile(br"\[[^[\]]*\]"), b"[XXXXX]"),
)
# "addr/dotted netmask" as ves.py and firewalld write it: hide_ips() of
# infra_cep_helper knows only "addr/NN" and leaves these as they are.
MASKED_IPV4 = re.compile(br"\b(\d{1,3}(?:\.\d{1,3}){3})(/\d{1,3}(?:\.\d{1,3}){3})\b")
RESULT_MEMBER = "./result.json"
MANIFEST = "MANIFEST.sha256"
# Names go into file names and the ssh command line.
NAME_RE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9._-]*\Z")
POLL_SECONDS = 0.5
REAP_SECONDS = 10
# Default ssh: a dead link to a node is noticed in about a minute instead of
# holding the installation run until the TCP timeout.
SSH_DEFAULT = "ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=4"


class ReportError(Exception):
    """A report cannot be made; the message says why."""


def say(text):
    """One progress line on stderr; stdout may carry an archive."""
    sys.stderr.write("%s: %s\n" % (PROG, text))
    sys.stderr.flush()


def stamp():
    """The date part of the file names."""
    return time.strftime("%Y%m%d-%H%M%S")


def load_settings(path):
    """The daemon settings; the daemon also goes on with none."""
    try:
        with open(path) as f:
            settings = json.load(f)
    except (IOError, OSError, ValueError) as e:
        say("cannot read %s (%s), no logs and no noexecute list" % (path, e))
        return {}
    return settings if isinstance(settings, dict) else {}


def blacklist(settings, scripts_dir):
    """Paths of "noexecute": absolute, or relative to the scripts directory."""
    entries = settings.get("noexecute") or []
    return set(os.path.join(scripts_dir, e) for e in entries)


def logs_to_collect(settings):
    """The "logs_to_collect" files, ";"-separated."""
    return [p for p in settings.get("logs_to_collect", "").split(";") if p]


def is_collector(scripts_dir, name, skip):
    """What the daemon runs in its weekly pass (Client.cpp IsOrdinaryScript)."""
    path = os.path.join(scripts_dir, name)
    if path in skip or not name.endswith(".py") or name == ".py":
        return False
    if name.startswith("infra_") or name.startswith("perf_"):
        return False
    try:
        mode = os.stat(path).st_mode
    except OSError:
        return False
    return stat.S_ISREG(mode) and bool(mode & stat.S_IXUSR)


def collectors(scripts_dir, skip):
    """The scripts in the daemon's order: by name, backend_info.py last."""
    names = sorted(n for n in os.listdir(scripts_dir)
                   if is_collector(scripts_dir, n, skip))
    if LAST_SCRIPT in names:
        names.remove(LAST_SCRIPT)
        names.append(LAST_SCRIPT)
    return names


def daemon_time():
    """--time=: the daemon passes local time read as UTC (Utils.cpp)."""
    return "--time=%d" % calendar.timegm(time.localtime())


def kill_group(proc):
    """SIGKILL the child's process group (a script's yum ignores SIGTERM).

    The wait is bounded: a script stuck in the kernel (a df on a dead mount)
    does not die on SIGKILL, and the daemon goes on without it too.
    """
    try:
        os.killpg(proc.pid, signal.SIGKILL)
    except OSError as e:
        if e.errno != errno.ESRCH:
            raise
    deadline = time.time() + REAP_SECONDS
    while proc.poll() is None and time.time() < deadline:
        time.sleep(POLL_SECONDS)
    if proc.poll() is None:
        say("pid %d does not die, left behind" % proc.pid)


def run_child(argv, log):
    """Run one collector step; its exit code, or None if it was killed."""
    with open(os.devnull, "rb") as null:
        proc = subprocess.Popen(argv, cwd="/", env=CHILD_ENV, stdin=null,
                                stdout=log, stderr=subprocess.STDOUT,
                                close_fds=True, preexec_fn=os.setsid)
    deadline = time.time() + SCRIPT_TIMEOUT
    try:
        while proc.poll() is None:
            if time.time() > deadline:
                kill_group(proc)
                return None
            time.sleep(POLL_SECONDS)
    except BaseException:
        # The script runs in its own session: an interrupt here would leave it.
        kill_group(proc)
        raise
    return proc.returncode


def old_backend_info(scripts_dir):
    """True when the node's backend_info.py packs the storage cluster reports
    into the daemon's directory (it has no results_dir()); False if absent."""
    try:
        with open(os.path.join(scripts_dir, BACKEND_INFO), "rb") as f:
            return RESULTS_DIR_MARK not in f.read()
    except IOError:
        return False


def run_scripts(scripts_dir, names, prelim, log):
    """Every collector, then infra_builder.py into <final>/result.json."""
    for name in names:
        started = time.time()
        rc = run_child([PYTHON, os.path.join(scripts_dir, name), prelim,
                        daemon_time()], log)
        if rc is None:
            # A note: in installation mode it reaches the manifest.
            say(NOTE + "%s killed after %d s, its section is missing"
                % (name, SCRIPT_TIMEOUT))
        else:
            say("%s: exit %d, %d s" % (name, rc, time.time() - started))


def build_result(scripts_dir, prelim, final, log):
    """infra_builder.py merges the <script>.json files as for the daemon."""
    result = os.path.join(final, "result.json")
    run_child([PYTHON, os.path.join(scripts_dir, BUILDER), prelim,
               daemon_time(), result], log)
    if not os.path.isfile(result):
        raise ReportError("%s wrote no result.json" % BUILDER)


def mask_line(line):
    """The daemon's masks: clock times, UUIDs, then any [...] text."""
    for pattern, replacement in LOG_MASKS:
        line = pattern.sub(replacement, line)
    return line


class Anonymizer(object):
    """--anonymize: MAC and IP addresses masked as on HCI.

    Uses hide_hwaddrs() and hide_ips() of infra_cep_helper.py (disp-helper),
    which the scripts apply only on HCI: a MAC becomes a salted hash, an IP
    XXX.XXX.XXX.XXX. Nothing else changes. That helper is Python 2 code
    (str() of the value, sha512 of str), as the node runs it.
    """

    def __init__(self, scripts_dir):
        if sys.version_info[0] != 2:
            raise ReportError("--anonymize needs the node's Python 2 (%s)"
                              % PYTHON)
        sys.path.insert(0, scripts_dir)
        try:
            import infra_cep_helper
        finally:
            sys.path.remove(scripts_dir)

        class Helper(infra_cep_helper.CEPCollecting):
            def fill_results(self):
                pass

        self.helper = Helper()
        self.skip = set(self.helper.skip_anonymization())

    def text(self, value):
        """A str or unicode with the addresses masked, of the same type."""
        if isinstance(value, bytes):
            value = MASKED_IPV4.sub(br"XXX.XXX.XXX.XXX\2", value)
            return self.helper.hide_ips(self.helper.hide_hwaddrs(value))
        return self.text(value.encode("utf-8")).decode("utf-8")

    def value(self, value):
        """Every string in a parsed JSON value; keys stay."""
        if isinstance(value, dict):
            return dict((k, self.value(v)) for k, v in value.items())
        if isinstance(value, list):
            return [self.value(v) for v in value]
        if isinstance(value, (bytes, type(u""))):
            return self.text(value)
        return value

    def result(self, path):
        """result.json in place, but the sections the helper skips."""
        with open(path) as f:
            result = json.load(f)
        for section in result:
            if section not in self.skip:
                result[section] = self.value(result[section])
        with open(path, "w") as f:
            json.dump(result, f)


def fold_log(src, dst, anonymizer=None):
    """Copy a log as the daemon does: masked, equal lines as "<line> x N".

    The addresses go first: the daemon's clock mask eats parts of a MAC.
    """
    counts = {}
    with open(src, "rb") as f:
        for line in f:
            if line.endswith(b"\n"):
                line = line[:-1]
            if anonymizer:
                line = anonymizer.text(line)
            line = mask_line(line)
            counts[line] = counts.get(line, 0) + 1
    with open(dst, "wb") as out:
        for line in sorted(counts):
            out.write(line + b" x " + str(counts[line]).encode() + b"\n")


def copy_logs(paths, final, anonymizer):
    """The logs of logs_to_collect; a missing one is skipped, as by the daemon."""
    for path in paths:
        if not os.path.isfile(path):
            say("%s: no such log, skipped" % path)
            continue
        fold_log(path, os.path.join(final, os.path.basename(path)), anonymizer)


def tar_dir(directory, archive):
    """The daemon's own tar command, so the members are ./result.json etc."""
    rc = subprocess.call(["/usr/bin/tar", "-zcf", archive,
                          "--directory=" + directory, "."])
    if rc != 0:
        raise ReportError("tar exited with %d" % rc)


def node_report(args, archive):
    """Make this node's report as the daemon would and write it to archive."""
    if os.geteuid() != 0:
        # The scripts swallow EACCES: a non-root run looks fine and is empty.
        raise ReportError("run as root, as the daemon does")
    settings = load_settings(args.settings)
    names = collectors(args.scripts_dir, blacklist(settings, args.scripts_dir))
    if not names:
        raise ReportError("no CEP scripts in %s" % args.scripts_dir)
    anonymizer = Anonymizer(args.scripts_dir) if args.anonymize else None
    work = tempfile.mkdtemp(prefix=PROG + ".")
    try:
        # Siblings as in /vz/tmp/cep/output: backend_info.py packs the
        # storage cluster reports into final/ next to its output directory.
        prelim = os.path.join(work, "preliminary")
        final = os.path.join(work, "final")
        os.mkdir(prelim)
        os.mkdir(final)
        if BACKEND_INFO in names and old_backend_info(args.scripts_dir):
            say(NOTE + "%s of this node is older than this tool: the storage"
                " cluster reports, if any, go to the daemon's archive, not into"
                " this report" % BACKEND_INFO)
        with open(os.path.join(work, "scripts.log"), "ab") as log:
            run_scripts(args.scripts_dir, names, prelim, log)
            build_result(args.scripts_dir, prelim, final, log)
        if anonymizer:
            anonymizer.result(os.path.join(final, "result.json"))
            say("MAC and IP addresses masked")
        copy_logs(logs_to_collect(settings), final, anonymizer)
        tar_dir(final, archive)
    finally:
        shutil.rmtree(work, ignore_errors=True)


def sha256(path):
    """Hex sha256 of a file."""
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def publish(tmp, path):
    """Move a finished file to its place and print where it is.

    Across file systems the copy goes to <path>.part first, so a copy cut
    short (ENOSPC, a signal) never stands under the final name.
    """
    part = path + ".part"
    try:
        shutil.move(tmp, part)
        os.rename(part, path)
    finally:
        if os.path.exists(part):
            os.unlink(part)
    print(os.path.abspath(path))
    say("sha256 %s" % sha256(path))


def run_node(args):
    """cep-report-now [-o DIR]: this node's report into DIR."""
    host = socket.gethostname().split(".")[0] or "node"
    path = os.path.join(args.output_dir,
                        "report-%s-%s.tar.gz" % (host, stamp()))
    tmp = path + ".part"
    try:
        node_report(args, tmp)
        publish(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)
    return 0


def run_stdout(args):
    """--stdout: the node report on stdout, for --nodes over ssh."""
    out = getattr(sys.stdout, "buffer", sys.stdout)
    if sys.stdout.isatty():
        raise ReportError("--stdout writes an archive: redirect it")
    work = tempfile.mkdtemp(prefix=PROG + ".")
    try:
        archive = os.path.join(work, "report.tar.gz")
        node_report(args, archive)
        with open(archive, "rb") as f:
            shutil.copyfileobj(f, out)
        out.flush()
    finally:
        shutil.rmtree(work, ignore_errors=True)
    return 0


class NodeJob(object):
    """One node's report fetched by ssh into the installation directory."""

    def __init__(self, node, directory, workdir):
        self.node = node
        self.name = "report-%s.tar.gz" % node
        self.path = os.path.join(directory, self.name)
        self.err_path = os.path.join(workdir, node + ".err")
        self.proc = None
        self.reason = None
        self.notes = []

    def start(self, ssh, source, options):
        """ssh root@node python - --stdout, this file on its stdin."""
        say("%s: started" % self.node)
        argv = ssh + ["root@" + self.node, PYTHON, "-", "--stdout"] + options
        with open(source, "rb") as src, open(self.path, "wb") as out, \
                open(self.err_path, "wb") as err:
            self.proc = subprocess.Popen(argv, stdin=src, stdout=out,
                                         stderr=err, close_fds=True)

    def finish(self):
        """After the exit: the reason it failed, or None."""
        rc = self.proc.returncode
        self.reason = check_archive(self.path) if rc == 0 else \
            "%s (exit %d)" % (last_line(self.err_path), rc)
        if self.reason:
            os.unlink(self.path)
            say("%s: FAILED: %s" % (self.node, self.reason))
            return
        self.notes = notes(self.err_path)
        for note in self.notes:
            say("%s: %s%s" % (self.node, NOTE, note))
        say("%s: done" % self.node)


def ascii_text(text):
    """ASCII for the manifest and stderr under any locale, py2 or 3."""
    data = text.encode("ascii", "backslashreplace")
    return data if isinstance(data, str) else data.decode("ascii")


def notes(path):
    """The notes a node wrote to its stderr, without the prefixes, ASCII."""
    mark = "%s: %s" % (PROG, NOTE)
    with open(path, "rb") as f:
        text = f.read().decode("utf-8", "replace")
    return [ascii_text(line.split(mark, 1)[1].strip())
            for line in text.splitlines() if mark in line]


def last_line(path):
    """The last non-empty line of a captured stderr, as ASCII text.

    ASCII because it goes to the manifest and to stderr under any locale and
    Python 2 or 3; a localized remote message is kept as escapes.
    """
    with open(path, "rb") as f:
        text = f.read().decode("utf-8", "replace")
    lines = [line.strip() for line in text.splitlines() if line.strip()]
    return ascii_text(lines[-1]) if lines else "no message"


def check_archive(path):
    """Why a node archive is not a report, or None.

    The gzip stream is read to its end first: its CRC catches any change
    of the compressed bytes, while tarfile stops quietly at the first bad
    header after the first one. A damaged deflate stream raises
    zlib.error, a cut trailer struct.error, neither a TarError.
    """
    try:
        with closing(gzip.open(path, "rb")) as f:
            for _ in iter(lambda: f.read(1 << 20), b""):
                pass
        with tarfile.open(path, "r:gz") as tar:
            names = tar.getnames()
    except (tarfile.TarError, IOError, OSError, EOFError,
            zlib.error, struct.error) as e:
        return "not a tar.gz archive: %s" % e
    if RESULT_MEMBER not in names:
        return "no %s in the archive" % RESULT_MEMBER
    return None


def kill_quiet(proc):
    """SIGKILL and reap a child; one already gone (py2 kill() does not check
    returncode) must not stop the cleanup of the others."""
    try:
        proc.kill()
    except OSError as e:
        if e.errno != errno.ESRCH:
            raise
    proc.wait()


def run_jobs(jobs, ssh, source, limit, options):
    """Run the node jobs, at most limit at a time."""
    waiting = list(jobs)
    running = []
    try:
        while waiting or running:
            while waiting and len(running) < limit:
                job = waiting.pop(0)
                job.start(ssh, source, options)
                running.append(job)
            for job in [j for j in running if j.proc.poll() is not None]:
                running.remove(job)
                job.finish()
            time.sleep(POLL_SECONDS)
    except BaseException:
        for job in running:
            kill_quiet(job.proc)
        raise


def write_manifest(directory, args, jobs):
    """sha256sum -c input; failed nodes and the notes as "#" comments."""
    lines = [
        "# %s: installation %s, %s, made on %s" % (
            PROG, args.name, time.strftime("%Y-%m-%d %H:%M:%S %z"),
            socket.gethostname()),
        "# Integrity only: whoever runs %s can edit a report and recompute"
        " these sums." % PROG,
    ]
    if args.anonymize:
        lines.append("# --anonymize: in result.json and the logs of every node,"
                     " IP and MAC addresses of the forms the HCI masking knows"
                     " are replaced; other forms stay (cep-report-now --help).")
    lines += ["# node %s: FAILED: %s" % (j.node, j.reason)
              for j in jobs if j.reason]
    lines += note_lines(jobs)
    lines += ["%s  %s" % (sha256(j.path), j.name) for j in jobs if not j.reason]
    with open(os.path.join(directory, MANIFEST), "w") as f:
        f.write("\n".join(lines) + "\n")


def ssh_argv(command):
    """--ssh-command split, its program checked before any node starts."""
    argv = shlex.split(command)
    if not argv:
        raise ReportError("--ssh-command is empty")
    program = argv[0]
    dirs = [""] if os.sep in program else \
        os.environ.get("PATH", os.defpath).split(os.pathsep)
    for d in dirs:
        path = os.path.join(d, program)
        if os.path.isfile(path) and os.access(path, os.X_OK):
            return argv
    raise ReportError("cannot run %r: no such program" % program)


def note_lines(jobs):
    """One manifest line per distinct note, with the nodes it came from."""
    nodes_of = {}
    order = []
    for job in jobs:
        for note in job.notes:
            if note not in nodes_of:
                nodes_of[note] = []
                order.append(note)
            nodes_of[note].append(job.node)
    return ["# %s%s (nodes: %s)" % (NOTE, note, " ".join(nodes_of[note]))
            for note in order]


def run_installation(args):
    """--nodes: every node's report and a manifest in one tar.gz."""
    ssh = ssh_argv(args.ssh_command)
    base = "cep-report-%s-%s" % (args.name, stamp())
    path = os.path.join(args.output_dir, base + ".tar.gz")
    work = tempfile.mkdtemp(prefix=PROG + ".")
    try:
        directory = os.path.join(work, base)
        os.mkdir(directory)
        jobs = [NodeJob(n, directory, work) for n in args.nodes]
        options = ["--anonymize"] if args.anonymize else []
        run_jobs(jobs, ssh, os.path.realpath(__file__), args.jobs, options)
        write_manifest(directory, args, jobs)
        tmp = os.path.join(work, base + ".tar.gz")
        with tarfile.open(tmp, "w:gz") as tar:
            tar.add(directory, arcname=base)
        publish(tmp, path)
    finally:
        shutil.rmtree(work, ignore_errors=True)
    failed = [j.node for j in jobs if j.reason]
    if failed:
        say("no report from: %s" % " ".join(failed))
    return 1 if failed else 0


def name_arg(value):
    """A node or installation name: letters, digits, ".", "_", "-"."""
    if not NAME_RE.match(value):
        raise argparse.ArgumentTypeError("bad name %r" % value)
    return value


def parse_args(argv):
    parser = argparse.ArgumentParser(
        prog=PROG, description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-o", "--output-dir", default=".",
                        help="where the file is written (default: .)")
    parser.add_argument("--nodes", nargs="+", type=name_arg, metavar="NODE",
                        help="host names or IPv4 addresses of the nodes")
    parser.add_argument("--name", type=name_arg,
                        help="installation name for the file name")
    parser.add_argument("--jobs", type=int, default=4,
                        help="nodes at a time (default: 4)")
    parser.add_argument("--anonymize", action="store_true",
                        help="mask MAC and IP addresses (see above)")
    parser.add_argument("--ssh-command", default=SSH_DEFAULT,
                        help='how to run ssh (default: "%s")' % SSH_DEFAULT)
    parser.add_argument("--stdout", action="store_true",
                        help=argparse.SUPPRESS)
    parser.add_argument("--scripts-dir", default=SCRIPTS_DIR,
                        help=argparse.SUPPRESS)
    parser.add_argument("--settings", default=SETTINGS, help=argparse.SUPPRESS)
    args = parser.parse_args(argv)
    if args.nodes and not args.name:
        parser.error("--nodes needs --name")
    if args.jobs < 1:
        parser.error("--jobs must be 1 or more")
    # Before the scripts run: a wrong DIR found at the end costs the whole run.
    if not args.stdout and not (os.path.isdir(args.output_dir) and
                                os.access(args.output_dir, os.W_OK)):
        parser.error("%s is not a writable directory" % args.output_dir)
    if args.nodes:
        args.nodes = sorted(set(args.nodes), key=args.nodes.index)
    return args


def on_signal(signum, _frame):
    """SIGTERM/SIGHUP: leave through the cleanup of the temp files."""
    raise SystemExit(128 + signum)


def main(argv=None):
    args = parse_args(argv)
    os.umask(0o027)
    signal.signal(signal.SIGTERM, on_signal)
    signal.signal(signal.SIGHUP, on_signal)
    try:
        if args.stdout:
            return run_stdout(args)
        if args.nodes:
            return run_installation(args)
        return run_node(args)
    except (ReportError, IOError, OSError) as e:
        say("error: %s" % e)
        return 1
    except KeyboardInterrupt:
        say("interrupted, nothing written")
        return 130


if __name__ == "__main__":
    sys.exit(main())
