validators.py 4.68 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
20
import jinja2
21 22 23

from lxml import etree as ET
import logging
24 25 26
import yaml

from vm.models import Instance
27

28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
rng_file = "/usr/share/libvirt/schemas/domain.rng"

# 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()


def domain_validator(value):
    xml = header + value + footer
    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)


58
def meta_data_validator(instance, value):
59
    try:
60
        instance.validate_ci_data(value)
61
    except yaml.YAMLError as exc:
62 63 64 65 66 67 68 69 70 71
        if hasattr(exc, 'problem_mark'):
            if exc.context != None:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
                    str(exc.problem) + ' ' + str(exc.context) +
                    '\nPlease correct data and retry.')
            else:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
                    str(exc.problem) + '\nPlease correct data and retry.')
        else:
            raise ValidationError("Something went wrong while parsing yaml file")
72 73
    except jinja2.exceptions.TemplateError as exc:
        raise ValidationError(exc.message)
74 75


76
def user_data_validator(instance, value):
77
    try:
78
        instance.validate_ci_data(value)
79
    except yaml.YAMLError as exc:
80 81 82 83 84 85 86
        if hasattr(exc, 'problem_mark'):
            if exc.context != None:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
                    str(exc.problem) + ' ' + str(exc.context) +
                    '\nPlease correct data and retry.')
            else:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
                    str(exc.problem) + '\nPlease correct data and retry.')
        else:
            raise ValidationError("Something went wrong while parsing yaml file")
    except jinja2.exceptions.TemplateError as exc:
        raise ValidationError(exc.message)

def network_data_validator(instance, value):
    try:
        instance.validate_ci_data(value)
    except yaml.YAMLError as exc:
        if hasattr(exc, 'problem_mark'):
            if exc.context != None:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
                    str(exc.problem) + ' ' + str(exc.context) +
                    '\nPlease correct data and retry.')
            else:
                raise ValidationError('  parser says\n' + str(exc.problem_mark) + '\n  ' +
104 105 106
                    str(exc.problem) + '\nPlease correct data and retry.')
        else:
            raise ValidationError("Something went wrong while parsing yaml file")
107 108
    except jinja2.exceptions.TemplateError as exc:
        raise ValidationError(exc.message)
109 110


111 112 113 114
def connect_command_template_validator(value):
    """Validate value as a connect command template.

    >>> try: connect_command_template_validator("%(host)s")
Kohl Krisztofer committed
115 116
    ... except ValidationError as e: print(e)
    ... 
117 118
    >>> connect_command_template_validator("%(host)s")
    >>> try: connect_command_template_validator("%(host)s %s")
Kohl Krisztofer committed
119 120
    ... except ValidationError as e: print(e)
    ... 
Karsa Zoltán István committed
121
    ['Invalid template string.']
122 123 124 125 126 127 128 129 130 131 132
    """

    try:
        value % {
            'username': "uname",
            'password': "pw",
            'host': "111.111.111.111",
            'port': 12345,
        }
    except (KeyError, TypeError, ValueError):
        raise ValidationError(_("Invalid template string."))
Kohl Krisztofer committed
133