#!/usr/bin/python
# vim: ts=4 sts=4 sw=4 et si
#
# Obtain VM status and max memory size.
# Shaman master executes this script to prepare data for pdrs
# during resource relocation.
#
# RESOURCE_PATH environment variable points to VM bundle
# output : "VM:<subtype>\n<VM total memory size in KB>"
#
# Copyright (c) 2013-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

from __future__ import print_function
import sys
import os
sys.path.append('/usr/share/shaman')
import shaman_functions as shaman


def error(msg):
    print(msg, file=sys.stderr)


def get_env(name):
    '''Get the value of a given environment variable'''
    val = os.environ.get(name)
    if not val:
        error('%r environment variable undefined' % name)
        sys.exit(1)
    return val

try:
    path = get_env('RESOURCE_PATH')
    conf = shaman.VmConfig(path)
    if not conf.is_valid():
        sys.exit(2)
    if conf.get_element('/Settings/ClusterOptions/Running') != '1':
        error('VM %r is not running -- skip it' % path)
        sys.exit(0)
    ram = conf.get_element('/Hardware/Memory/RAM')
    if not ram:
        error('can not get RAM size for VM %r -- skip it' % path)
        sys.exit(3)
    video_mem = conf.get_element('/Hardware/Video/VideoMemorySize')
    if not video_mem:
        error('can not get video memory size for VM %r -- skip it' % path)
        sys.exit(4)
    flavor = conf.get_flavor()
    if not flavor:
        error('can not get the flavor of VM %r -- skip it' % path)
        sys.exit(5)
    print('{0}\n{1}'.format(flavor, (long(ram) + long(video_mem)) * 1024))
except SystemExit:
    raise
except:
    error('Unexpected error: %s' % sys.exc_info()[0])
    raise
