#!/usr/bin/python

import sys
import time
sys.path.insert(0, '/usr/lib/xen-3.1-1/lib/python')
from xen.lowlevel import xs

xsc = xs.xs()

def live_vms():
    domids = set(xsc.ls('', '/local/domain'))
    domids.discard('0')

    vms = dict()

    for domid in domids:
        try:
            name, data = get_dom(int(domid))
        except (xs.Error, TypeError):
            continue # went down since we started
        if name.startswith('d_'):
            name = name[2:]
            vms[name] = data
    return vms

def get_dom(domid):
    name = xsc.read('', '/local/domain/%d/name' % domid)
    data = dict()
    data['domid'] = domid
    # presence of a graphical console
    data['console'] = xsc.read('', '/local/domain/%d/device/vfb/0/state' % domid)
    # uptime
    data['vm'] = xsc.read('', '/local/domain/%d/vm' % domid)
    data['start_time'] = float(xsc.read('', '%s/start_time' % data['vm']))
    data['uptime'] = time.time()-data['start_time']
    
    return name, data

if __name__ == '__main__':
    vms = live_vms()
    if '--json' in sys.argv[1:]:
        import cjson
        print cjson.encode(vms)
    elif '--pickle' in sys.argv[1:]:
        import cPickle
        cPickle.dump(vms, sys.stdout, cPickle.HIGHEST_PROTOCOL)
    else:
        import yaml
        print yaml.dump(vms, Dumper=yaml.CSafeDumper, default_flow_style=False)
