import re from ....builtins import * from ...exceptions import * from ...expressions import * from ...streams import * import pytz import dateutil.parser datetimeparser = dateutil.parser.parser() ## ## vmquery has records separated by a line of = characters ## def stream(stream, format='vmquery -X'): if format in ['vmquery -X']: return LineSeparatorStream(stream, separator='================================================================================', header=1) else: raise ParseError, 'Unknown format %s' % (format) ## ## Parse a vmquery record ## ## vmquery -a -X ## def parse(record, format='vmquery -X', version=None, tz=None): volume = ExtendedDict() #re_pair = re.compile('^([^:]+):\s*(.*)$') re_pair = re.compile('^\s*([^:]+):\s*(.*)\s*$') re_dashes = re.compile('^-+$') #re_type_id = re.compile('^(.+)\s+\((\d+)\)$') re_type_id = re.compile('^([0-9a-zA-Z\-_ /"]+)\s+\((\d+)\)$') if format == 'vmquery -X': try: for line in record: if line == '': continue match = re_pair.match(line) key = match.group(1) value = match.group(2) key = key.lower() key = key.replace(' ', '_') key = key.replace('/', '_') # # convert text values to python datatypes # while True: # # convert to integer value # match = re_integer.match(value) if match: value = int(value) break # # convert - to None # match = re_dashes.match(value) if match: value = None break # # separate type and id # match = re_type_id.match(value) if match: idkey = '%s_id' % (key) value = match.group(1) volume[idkey] = int(match.group(2)) break # # convert timestamps to Python datetime objects with timezone # if key in ['created', 'assigned', 'first_mounted', 'last_mounted', 'expiration']: if value is None: break try: dt = datetimeparser.parse(value) dt = dt.replace(tzinfo=tz) value = dt break except ValueError: value = value # # break out of enclosing while loop # break volume[key] = value return volume except Exception, e: #raise ParseError, e raise else: raise ParseError, 'Unknown format %s' % (format)