#!/usr/bin/python3
#
# Copyright (c) 2016-2017, Parallels International GmbH
# Copyright (c) 2017-2026 Virtuozzo International GmbH. All rights reserved.
#
# This file is part of Virtuozzo Core. Virtuozzo Core is free
# software; you can redistribute it and/or modify it under the terms
# of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#
"""Boot autostart of VMs and Containers.

Run by vz_systemd once the dispatcher is up. Every ENV with autostart gets a
transient timer vz_<uuid>.timer that runs vz_<uuid>.service = "prlctl start"
after the ENV's autostart delay. Transient units live in /run/systemd/transient,
so a "systemctl daemon-reload" before the delay is over keeps them.

The boot autostart is done once per boot: the lock file marks it, and it lives
on tmpfs so a reboot clears it. prl_disp_reboot keeps the saved "auto" list
until the lock appears and reads the vz_<uuid> units by these names.
"""

import ast
import collections
import os
import subprocess
import sys

import prlsdkapi

AUTOSTART_LIST = "/var/spool/prl-disp/prl_disp_autostart.py"
LOCKFILE = "/run/lock/vz-autostart.lock"
# One marker per scheduled ENV, so a rerun after a failure schedules only the rest.
STARTED_DIR = "/run/vz-autostart"
SDK_TIMEOUT = 600 * 1000

# What schedule() needs of an ENV, read while the SDK is still initialized.
Env = collections.namedtuple("Env", "uuid kind delay")


def log(mess):
    print(mess, flush=True)


def error(mess):
    print(mess, file=sys.stderr, flush=True)
    sys.exit(1)


def saved_auto_units():
    """UUIDs of the "auto" ENVs to start: those that were running at shutdown.

    prl_disp_reboot writes the list as 'units_to_start = (...)' and reads it back
    the same way (saved_units()); without it no "auto" ENV starts, as before.
    """
    try:
        with open(AUTOSTART_LIST) as f:
            return set(ast.literal_eval(f.read().split("=", 1)[1].strip()))
    except (OSError, IndexError, ValueError, SyntaxError, TypeError) as err:
        log("No saved autostart list: %r" % err)
        return set()


def autostart_env(config, saved):
    """The Env to start for this config, or None when it has no autostart now."""
    mode = config.get_auto_start()
    if not mode:
        return None
    if mode == prlsdkapi.consts.PAO_VM_START_ON_RELOAD and config.get_uuid() not in saved:
        return None
    kind = "Container" if config.get_vm_type() == prlsdkapi.consts.PVT_CT else "Virtual Machine"
    return Env(config.get_uuid(), kind, config.get_auto_start_delay())


def read_autostart_envs(server, saved, envs):
    """Append the ENVs to start to envs, so what was read survives an SDK error."""
    vms = server.get_vm_list_ex(prlsdkapi.consts.PVTF_VM + prlsdkapi.consts.PVTF_CT)
    for res in vms.wait(msecs=SDK_TIMEOUT):
        # One ENV whose config cannot be read is skipped, as prl_disp_reboot does,
        # so it does not keep the others from starting.
        try:
            env = autostart_env(res.get_config(), saved)
        except prlsdkapi.PrlSDKError as err:
            log("Unable to read an ENV config, skipped: %s" % err)
            continue
        if env:
            envs.append(env)


def unit_loaded(unit):
    proc = subprocess.run(["/usr/bin/systemctl", "show", "-p", "LoadState", "--value", unit],
            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
    return proc.returncode == 0 and proc.stdout.strip() == "loaded"


def uptime_seconds():
    with open("/proc/uptime") as f:
        return int(float(f.read().split()[0]))


def schedule(env):
    marker = os.path.join(STARTED_DIR, env.uuid.strip("{}"))
    if os.path.exists(marker):
        return True
    unit = "vz_" + env.uuid.strip("{}")
    # The delay is an absolute point in uptime, not OnActiveSec: a daemon-reload
    # restarts an OnActiveSec countdown from the reload (systemd 257), and on a
    # node that reloads every few minutes a long delay would never run out.
    cmd = ["/usr/bin/systemd-run", "--quiet", "--unit", unit,
           "--description", "%s %s autostart" % (env.kind, env.uuid),
           "--on-boot", str(uptime_seconds() + env.delay),
           "--property", "After=virtuozzo.target prl-disp.service vz.service",
           # prlctl start exits 253 when the start timed out: retry in a minute.
           "--property", "RestartSec=60s",
           "--property", "RestartForceExitStatus=253",
           "/bin/prlctl", "start", env.uuid]
    proc = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
    # The timer may be there from a run that failed after creating it.
    if proc.returncode != 0 and not unit_loaded(unit + ".timer"):
        log("Failed to schedule %s: %s" % (unit, proc.stderr.strip()))
        return False
    with open(marker, "w"):
        pass
    log("%s: %s start in %s s" % (env.uuid, env.kind, env.delay))
    return True


def main():
    if os.path.exists(LOCKFILE):
        log("Boot autostart is already done")
        return
    os.makedirs(STARTED_DIR, exist_ok=True)
    envs = []
    complete = True
    prlsdkapi.init_server_sdk()
    try:
        server = prlsdkapi.Server()
        server.login_local().wait(msecs=SDK_TIMEOUT)
        try:
            read_autostart_envs(server, saved_auto_units(), envs)
        finally:
            server.logoff().wait(msecs=SDK_TIMEOUT)
    except prlsdkapi.PrlSDKError as err:
        log("Failed to read the ENV list from the dispatcher: %s" % err)
        complete = False
    finally:
        # Every prlsdkapi.Server() starts a notification thread, and leaving
        # one running aborts the process while the SDK static state is destroyed.
        try:
            prlsdkapi.deinit_sdk()
        # deinit_sdk raises a plain Exception, not PrlSDKError (libprlsdk PythonTemplates.h).
        except Exception as err:  # noqa: BLE001
            log("SDK deinit failed: %s" % err)
    # Start what could be read even if the rest failed. Without the lock the next
    # run (vz_systemd retries, and runs again on the next dispatcher start)
    # schedules the rest; the markers keep it from doubling the ones done.
    scheduled = [env for env in envs if schedule(env)]
    if not complete or len(scheduled) != len(envs):
        error("Boot autostart is incomplete: %d of %d ENVs scheduled"
              % (len(scheduled), len(envs)))
    with open(LOCKFILE, "w"):
        pass
    log("Boot autostart scheduled for %d ENVs" % len(envs))


if __name__ == "__main__":
    main()
