Support YAML (default), JSON, and Pickle formats, depending on the client's choice
[invirt/packages/invirt-remote.git] / files / usr / sbin / sipb-xen-listvms
1 #!/usr/bin/python
2
3 import sys
4 import time
5 sys.path.insert(0, '/usr/lib/xen-3.1-1/lib/python')
6 from xen.lowlevel.xs import xs
7
8 trans = xs()
9
10 def live_vms():
11     domids = set(trans.ls('', '/local/domain'))
12     domids.discard('0')
13
14     vms = dict()
15
16     for domid in domids:
17         name, data = get_dom(int(domid))
18         if name.startswith('d_'):
19             name = name[2:]
20             vms[name] = data
21     return vms
22
23 def get_dom(domid):
24     name = trans.read('', '/local/domain/%d/name' % domid)
25     data = dict()
26     data['domid'] = domid
27     # presence of a graphical console
28     data['console'] = trans.read('', '/local/domain/%d/device/vfb/0/state' % domid)
29     # uptime
30     data['vm'] = trans.read('', '/local/domain/%d/vm' % domid)
31     data['start_time'] = float(trans.read('', '%s/start_time' % data['vm']))
32     data['uptime'] = time.time()-data['start_time']
33     
34     return name, data
35
36 if __name__ == '__main__':
37     vms = live_vms()
38     if '--json' in sys.argv[1:]:
39         import cjson
40         print cjson.encode(vms)
41     elif '--pickle' in sys.argv[1:]:
42         import cPickle
43         cPickle.dump(vms, sys.stdout, cPickle.HIGHEST_PROTOCOL)
44     else:
45         import yaml
46         print yaml.safe_dump(vms, default_flow_style=False)