validators.py 1.59 KB
Newer Older
1
from django.core.exceptions import ValidationError
2 3
from django.utils.translation import ugettext_lazy as _

4
from lxml import etree as ET
5
import logging
6 7 8

rng_file = "/usr/share/libvirt/schemas/domain.rng"

9 10 11 12 13 14 15
# Mandatory xml elements dor parsing
header = "<domain type='kvm'><name>validator</name>\
<memory unit='KiB'>1024</memory>\
<os><type>hvm</type></os>"
footer = "</domain>"

logger = logging.getLogger()
16 17 18 19


def domain_validator(value):
    xml = header + value + footer
20 21 22 23 24 25 26 27 28 29 30 31 32 33
    try:
        parsed_xml = ET.fromstring(xml)
    except Exception as e:
        raise ValidationError(e.message)
    try:
        relaxng = ET.RelaxNG(file=rng_file)
    except:
        logger.critical("%s RelaxNG libvirt domain schema file "
                        "is missing for validation.", rng_file)
    else:
        try:
            relaxng.assertValid(parsed_xml)
        except Exception as e:
            raise ValidationError(e.message)
34 35 36


def connect_command_template_validator(value):
37 38 39 40 41 42 43 44 45 46 47 48
    """Validate value as a connect command template.

    >>> try: connect_command_template_validator("%(host)s")
    ... except ValidationError as e: print e
    ...
    >>> connect_command_template_validator("%(host)s")
    >>> try: connect_command_template_validator("%(host)s %s")
    ... except ValidationError as e: print e
    ...
    [u'Invalid template string.']
    """

49 50 51 52 53 54 55 56 57
    try:
        value % {
            'username': "uname",
            'password': "pw",
            'host': "111.111.111.111",
            'port': 12345,
        }
    except (KeyError, TypeError, ValueError):
        raise ValidationError(_("Invalid template string."))