#!/usr/bin/python3
#
# Copyright (c) 2015-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.
#

try:
    import subprocess32 as subprocess
except ImportError:
    import subprocess

import sys
import os
import ast
import fcntl
import logging
import threading
import prlsdkapi

AUTOSTART_LIST = "/var/spool/prl-disp/prl_disp_autostart.py"
WRITE_LOCK = "/run/lock/prl_disp_autostart.lock"
QUEUE_LOCK = "/run/lock/prl_disp_autostart.queue"
BOOT_LIST_READ = "/run/lock/vz-autostart.lock"
BOOT_TARGET_STARTING = "/run/virtuozzo.target.start"

def error(mess):
    logger.error(mess)
    sys.exit(1)

def process_vms(timeout = 60 * 1000, do_stop = True, pending = ()):
    threads = []
    # Connect to dispatcher
    logger.info("SDK init...")
    prlsdkapi.init_server_sdk()
    logger.info("Connecting to dispatcher...")
    server = prlsdkapi.Server()
    server.login_local().wait(msecs = timeout)

    # Create file with list of auto autostart
    autostart = "units_to_start = ("

    logger.info("Retreiving VMs list...")

    # Get VMs list
    vms = server.get_vm_list_ex(prlsdkapi.consts.PVTF_VM + prlsdkapi.consts.PVTF_CT)
    for res in [ r for r in vms.wait(msecs = timeout) ]:
        # wrap get_config in a separate try-catch to make sure
        # we will not get another Exception in "except" due to get_config
        try:
            rescfg = res.get_config()
        except Exception as e:
            logger.error("Unable to get config, skip resource: %s" % e)
            continue

        try:
            # Place to list only if it was not in running state
            logger.info("UUID: %s" % rescfg.get_uuid())
            if (rescfg.get_auto_start() == prlsdkapi.consts.PAO_VM_START_ON_RELOAD and
                    (res.get_vm_info().get_state() == prlsdkapi.consts.VMS_RUNNING or
                    rescfg.get_uuid() in pending)):
                autostart += "\"%s\", " % rescfg.get_uuid()
                logger.info("%s: Autostart enabled" % rescfg.get_uuid())

            # Skip CTs and stopped/suspended VMs
            state = res.get_vm_info().get_state()
            if (rescfg.get_vm_type() != prlsdkapi.consts.PVT_VM or
                    state in (prlsdkapi.consts.VMS_STOPPED, prlsdkapi.consts.VMS_STOPPING,
                    prlsdkapi.consts.VMS_SUSPENDING, prlsdkapi.consts.VMS_SUSPENDED)):
                continue

            if not do_stop:
                continue

            # Suspend or Stop VMs based on Autostop configuration
            stopmode = rescfg.get_auto_stop()
            if stopmode == prlsdkapi.consts.PAO_VM_SUSPEND:
                logger.info("Suspending VM %s (state %d)..." % (rescfg.get_uuid(), state))
                thread = threading.Thread(target=res.suspend().wait)
            elif stopmode in [prlsdkapi.consts.PAO_VM_STOP, prlsdkapi.consts.PAO_VM_SHUTDOWN]:
                logger.info("Stopping VM %s (state %d)..." %  (rescfg.get_uuid(), state))
                thread = threading.Thread(target=res.stop_ex(prlsdkapi.consts.PSM_ACPI, 0).wait)
            else:
                logger.error("Unknown autostop mode %d for VM %s (state %d). Stopping..." %
                        (stopmode, rescfg.get_uuid()), state)
                thread = threading.Thread(target=res.stop_ex(prlsdkapi.consts.PSM_ACPI, 0).wait)

            thread.start()
            threads.append(thread)

        except Exception as e:
            logger.error("Exception on VM %s:" % rescfg.get_uuid())
            logger.error("\t%s" % e)

    # Write atomically: a bare open("w") truncates the file first, so an
    # overlapping producer (eager refresh on autostart-mode change, the daily
    # cron run, or graceful shutdown) could read/leave a half-written list that
    # vz_autostart then reads as a corrupt list at boot. Write to a temp
    # file in the same directory and os.replace() it into place so readers only
    # ever see the old or the new complete list, never a truncated one.
    dst = AUTOSTART_LIST
    tmp = dst + ".tmp.%d" % os.getpid()
    with open(tmp, "w") as f:
        f.write(autostart + ")\n")
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, dst)

    logger.info("Waiting for suspend threads...")

    # Wait for VMs suspended
    for thread in threads:
        thread.join()

    # Disconnect
    logger.info("Disconnecting from dispatcher...")
    server.logoff().wait(msecs = timeout)
    logger.info("SDK deinit...")
    prlsdkapi.deinit_sdk()

def shutdown_pending():
    proc = subprocess.Popen(["/usr/bin/systemctl", "-q", "--no-legend", "list-jobs"],
            stderr=subprocess.PIPE, stdout=subprocess.PIPE,
            stdin=subprocess.PIPE)
    (output, err) = proc.communicate()

    logger.debug("systemctl return code: %d" % proc.returncode)
    logger.debug("stdout of systemctl:")
    logger.debug(output)
    logger.debug("stderr of systemctl:")
    logger.debug(err)

    if proc.returncode != 0:
        return None
    for line in output.splitlines():
        fields = line.split()
        if len(fields) > 1 and fields[1] in (b"reboot.target", b"shutdown.target"):
            return True
    return False

def unit_states(units):
    proc = subprocess.Popen(["/usr/bin/systemctl", "show", "-p", "Id", "-p", "LoadState",
            "-p", "ActiveState", "-p", "SubState"] + units,
            stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    (output, err) = proc.communicate()
    if proc.returncode != 0:
        logger.debug(err)
        return None
    states = {}
    for block in output.split(b"\n\n"):
        props = dict(line.split(b"=", 1) for line in block.splitlines() if b"=" in line)
        if b"Id" in props:
            states[props[b"Id"].decode()] = props
    return states

def boot_start_pending(timer, service):
    not_started = timer.get(b"LoadState") == b"loaded" and timer.get(b"SubState") == b"dead"
    return (not_started or timer.get(b"SubState") in (b"waiting", b"running") or
            service.get(b"ActiveState") in (b"activating", b"active"))

def saved_units():
    try:
        with open(AUTOSTART_LIST) as f:
            return set(ast.literal_eval(f.read().split("=", 1)[1].strip()))
    except Exception as err:
        logger.error("Unable to read the saved list: %s" % err)
        return set()

def pending_units():
    saved = saved_units()
    if not saved or os.path.exists(BOOT_TARGET_STARTING):
        return saved
    units = dict((u, "vz_" + u.strip("{}")) for u in saved)
    states = unit_states([n + t for n in units.values() for t in (".timer", ".service")])
    if states is None:
        logger.warning("Unable to read the boot autostart units, keeping the saved ENVs")
        return saved
    return set(u for u, n in units.items()
            if boot_start_pending(states.get(n + ".timer", {}), states.get(n + ".service", {})))

def keep_reason():
    if not os.path.exists(BOOT_LIST_READ):
        return "Boot autostart has not read the list yet"
    pending = shutdown_pending()
    if pending is None:
        return "Unable to tell whether a reboot or shutdown is in progress"
    if pending:
        return "Reboot or shutdown in progress"
    return None

def run(action):
    try:
        action()
    except Exception as err:
        error(repr(err))

def prepare_to_reboot():
    with open(WRITE_LOCK, "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        run(process_vms)

def update_list():
    with open(QUEUE_LOCK, "w") as queue:
        try:
            fcntl.flock(queue, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            logger.info("Another update is already queued")
            return
        with open(WRITE_LOCK, "w") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            fcntl.flock(queue, fcntl.LOCK_UN)
            reason = keep_reason()
            if reason:
                logger.warning("%s, keeping the saved list" % reason)
                return
            run(lambda: process_vms(do_stop = False, pending = pending_units()))

# Redirect messages to /dev/null
devnull = open("/dev/null", 'w')
sys.stdout.flush()
sys.stderr.flush()
sys.stdout, sys.stderr = devnull, devnull

progname = "prl_disp_reboot"

# Setup logger
defloglevel = logging.DEBUG
logformat = "%(asctime)-15s %(message)s"
logging.basicConfig(format=logformat)
logger = logging.getLogger(progname)
logger.setLevel(defloglevel)
fh = logging.FileHandler("/var/log/%s.log" % progname)
fh.setLevel(defloglevel)
fh.setFormatter(logging.Formatter(logformat))
logger.addHandler(fh)

# Detect that we're started from cronjob as intermediate list creator
if os.path.basename(sys.argv[0]) == "prl_disp_autostart_list_update":
    logger.info("Started as autostart list updater")
    update_list()
    logger.info("All done!")
    sys.exit(0)

logger.info("Determining state...")
if shutdown_pending():
    prepare_to_reboot()
else:
    logger.info("Not in reboot or shutdown state!")

logger.info("All done!")
