Commit 8f2c0702 authored by Marco Mariani's avatar Marco Mariani

unicode fix + small cleanup on xml creation

parent 52cbf052
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vim: set et sts=2:
############################################################################## ##############################################################################
# #
# Copyright (c) 2010, 2011, 2012 Vifib SARL and Contributors. # Copyright (c) 2010, 2011, 2012 Vifib SARL and Contributors.
...@@ -35,10 +36,10 @@ from lxml import etree ...@@ -35,10 +36,10 @@ from lxml import etree
import logging import logging
import os import os
import pkg_resources import pkg_resources
from random import random import random
import socket import socket
import subprocess
import StringIO import StringIO
import subprocess
import sys import sys
import tempfile import tempfile
import time import time
...@@ -82,6 +83,11 @@ SLAPGRID_PROMISE_FAIL = 2 ...@@ -82,6 +83,11 @@ SLAPGRID_PROMISE_FAIL = 2
# XXX hardcoded watchdog_path # XXX hardcoded watchdog_path
WATCHDOG_PATH = '/opt/slapos/bin/slapos-watchdog' WATCHDOG_PATH = '/opt/slapos/bin/slapos-watchdog'
class _formatXMLError(Exception):
pass
def parseArgumentTupleAndReturnSlapgridObject(*argument_tuple): def parseArgumentTupleAndReturnSlapgridObject(*argument_tuple):
"""Parses arguments either from command line, from method parameters or from """Parses arguments either from command line, from method parameters or from
config file. Then returns a new instance of slapgrid.Slapgrid with those config file. Then returns a new instance of slapgrid.Slapgrid with those
...@@ -275,7 +281,7 @@ def parseArgumentTupleAndReturnSlapgridObject(*argument_tuple): ...@@ -275,7 +281,7 @@ def parseArgumentTupleAndReturnSlapgridObject(*argument_tuple):
else: else:
maximal_delay = int(option_dict.get("maximal_delay", "0")) maximal_delay = int(option_dict.get("maximal_delay", "0"))
if maximal_delay > 0: if maximal_delay > 0:
duration = int(maximal_delay * random()) duration = random.randint(1, maximal_delay)
logging.info("Sleeping for %s seconds. To disable this feature, " \ logging.info("Sleeping for %s seconds. To disable this feature, " \
"check --now parameter in slapgrid help." % duration) "check --now parameter in slapgrid help." % duration)
time.sleep(duration) time.sleep(duration)
...@@ -970,10 +976,8 @@ class Slapgrid(object): ...@@ -970,10 +976,8 @@ class Slapgrid(object):
xmlschema_doc = etree.parse(xsd_model) xmlschema_doc = etree.parse(xsd_model)
xmlschema = etree.XMLSchema(xmlschema_doc) xmlschema = etree.XMLSchema(xmlschema_doc)
string_to_validate = StringIO.StringIO(to_be_validated)
try: try:
document = etree.parse(string_to_validate) document = etree.fromstring(to_be_validated)
except (etree.XMLSyntaxError, etree.DocumentInvalid) as e: except (etree.XMLSyntaxError, etree.DocumentInvalid) as e:
logger.info('Failed to parse this XML report : %s\n%s' % \ logger.info('Failed to parse this XML report : %s\n%s' % \
(to_be_validated, _formatXMLError(e))) (to_be_validated, _formatXMLError(e)))
...@@ -988,59 +992,50 @@ class Slapgrid(object): ...@@ -988,59 +992,50 @@ class Slapgrid(object):
def asXML(self, computer_partition_usage_list): def asXML(self, computer_partition_usage_list):
"""Generates a XML report from computer partition usage list """Generates a XML report from computer partition usage list
""" """
xml_head = "" # XXX TODO rewrite without string composition...
xml_movements = ""
xml_foot = "" xml = ['<?xml version="1.0"?>',
'<journal>',
xml_head = "<?xml version='1.0' encoding='utf-8'?>" \ '<transaction type="Sale Packing List">',
"<journal>" \ '<title>Resource consumptions</title>',
"<transaction type=\"Sale Packing List\">" \ '<start_date></start_date>',
"<title>Resource consumptions</title>" \ '<stop_date>%s</stop_date>' % time.strftime("%Y-%m-%d at %H:%M:%S"),
"<start_date></start_date>" \ '<reference>%s</reference>' % self.computer_id,
"<stop_date>%s</stop_date>" \ '<currency></currency>',
"<reference>%s</reference>" \ '<payment_mode></payment_mode>',
"<currency></currency>" \ '<category></category>',
"<payment_mode></payment_mode>" \ '<arrow type="Administration">',
"<category></category>" \ '<source></source>',
"<arrow type=\"Administration\">" \ '<destination></destination>',
"<source></source>" \ '</arrow>']
"<destination></destination>" \
"</arrow>" \
% (time.strftime("%Y-%m-%d at %H:%M:%S"),
self.computer_id)
for computer_partition_usage in computer_partition_usage_list: for computer_partition_usage in computer_partition_usage_list:
try: try:
usage_string = StringIO.StringIO(computer_partition_usage.usage) root = etree.fromstring(computer_partition_usage.usage)
root = etree.parse(usage_string)
except UnicodeError: except UnicodeError:
self.logger.info("Failed to read %s." % ( self.logger.info("Failed to read %s." % (
computer_partition_usage.usage)) computer_partition_usage.usage))
self.logger.error(UnicodeError) self.logger.error(UnicodeError)
raise "Failed to read %s." % (computer_partition_usage.usage) raise "Failed to read %s." % (computer_partition_usage.usage)
except (etree.XMLSyntaxError, etree.DocumentInvalid) as e: except (etree.XMLSyntaxError, etree.DocumentInvalid) as e:
self.logger.info("Failed to parse %s." % (usage_string)) self.logger.info("Failed to parse %s." % (computer_parition_usage.usage))
self.logger.error(e) self.logger.error(e)
raise _formatXMLError(e) raise _formatXMLError(e)
except Exception: except Exception:
raise "Failed to generate XML report." raise "Failed to generate XML report."
for movement in root.findall('movement'): for movement in root.findall('movement'):
xml_movements += "<movement>" xml.append('<movement>')
for children in movement.getchildren(): for child in movement.getchildren():
if children.tag == "reference": if child.tag == "reference":
xml_movements += "<%s>%s</%s>" % (children.tag, xml.append('<%s>%s</%s>' % (child.tag, computer_partition_usage.getId(), child.tag))
computer_partition_usage.getId(), children.tag)
else: else:
xml_movements += "<%s>%s</%s>" % (children.tag, children.text, xml.append('<%s>%s</%s>' % (child.tag, child.text, child.tag))
children.tag) xml.append('</movement>')
xml_movements += "</movement>"
xml_foot = "</transaction>" \ xml.append('</transaction></journal>')
"</journal>"
xml = xml_head + xml_movements + xml_foot return ''.join(xml)
return xml
def agregateAndSendUsage(self): def agregateAndSendUsage(self):
"""Will agregate usage from each Computer Partition. """Will agregate usage from each Computer Partition.
...@@ -1081,6 +1076,7 @@ class Slapgrid(object): ...@@ -1081,6 +1076,7 @@ class Slapgrid(object):
# Loop on the different computer partitions # Loop on the different computer partitions
computer_partition_list = self.FilterComputerPartitionList( computer_partition_list = self.FilterComputerPartitionList(
slap_computer_usage.getComputerPartitionList()) slap_computer_usage.getComputerPartitionList())
for computer_partition in computer_partition_list: for computer_partition in computer_partition_list:
try: try:
computer_partition_id = computer_partition.getId() computer_partition_id = computer_partition.getId()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment