#!/usr/bin/python

from base64 import b64encode
import os
import XenAPIPlugin
import zlib

# For the grab_log function to work, xenconsoled needs to
# have the logging turned on for at least guests. This can
# be done by running xenconsoled as
#
# xenconsoled --log=guest --log-dir=/var/log/xen/guest/
#
# On the Dom0 side, if the default log-dir is not used as
# above, then the environmental variable XENCONSOLED_LOG_DIR
# should be set to point to the log-dir location
#


def grab_log(session, arg_dict):
    instance = arg_dict['name']
    logdir = os.environ.get('XENCONSOLED_LOG_DIR', '/var/log/xen/guest')
    try:
        f = open("%s/guest-%s.log" % (logdir, instance), 'rb')
        return b64encode(zlib.compress("".join(f.readlines())))
    except IOError as exc:
        msg = "Console temporarily unavailable, please try later!"
        return b64encode(zlib.compress(msg))

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"grab_agent_log": grab_log})
