Beispiel #1
0
    def EndMapping(self, top_value, mapping):
        """When leaving scope, makes sure new object is initialized.

    This method is mainly for picking up on any missing required attributes.

    Args:
      top_value: Parent of closing mapping object.
      mapping: _ObjectMapper instance that is leaving scope.
    """
        # make sure that mapping.value is a non-built-in type (i.e. can have
        # 'CheckInitialized' called on it)
        if not hasattr(mapping.value, 'CheckInitialized'):
            raise validation.ValidationError(
                'Cannot convert map to non-map value.')

        try:
            mapping.value.CheckInitialized()
        except validation.ValidationError:
            # These should just pass through.
            raise
        except Exception, e:
            # Some errors may have problematic encoding or other issues.
            # Re-raising an error in this block would be very hard to debug
            # for the time being so instead, on error, the value is merely
            # obscured.
            try:
                error_str = str(e)
            except Exception:
                error_str = '<unknown>'

            # Wrap in a ValidationError
            raise validation.ValidationError(error_str, e)
Beispiel #2
0
def _ValidateNotIpV4Address(host):
  """Validate host is not an IPV4 address."""
  matcher = _URL_IP_V4_ADDR_RE.match(host)
  if matcher and sum(1 for x in matcher.groups() if int(x) <= 255) == 4:
    raise validation.ValidationError('Host may not match an ipv4 address \'%s\''
                                     % host)
  return matcher
Beispiel #3
0
 def Validate(self, value, key=None):
     """Validates a timezone."""
     if value is None:
         # optional
         return
     if not isinstance(value, basestring):
         raise TypeError('timezone must be a string, not \'%r\'' %
                         type(value))
     if pytz is None:
         # pytz not installed, silently accept anything without validating
         return value
     try:
         pytz.timezone(value)
     except pytz.UnknownTimeZoneError:
         raise validation.ValidationError('timezone \'%s\' is unknown' %
                                          value)
     except IOError:
         # When running under dev_appserver, pytz can't open it's resource files.
         # I have no idea how to test this.
         return value
     except:
         # The yaml and validation code repeatedly re-raise exceptions that
         # consume tracebacks.
         unused_e, v, t = sys.exc_info()
         logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                         'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
         raise
     return value
Beispiel #4
0
 def Validate(self, value, key=None):
     """Validates a schedule."""
     if value is None:
         raise validation.MissingAttribute('schedule must be specified')
     if not isinstance(value, basestring):
         raise TypeError('schedule must be a string, not \'%r\'' %
                         type(value))
     try:
         groctimespecification.GrocTimeSpecification(value)
     except groc.GrocException, e:
         raise validation.ValidationError(
             'schedule \'%s\' failed to parse: %s' % (value, e.args[0]))
Beispiel #5
0
    def Validate(self, value, unused_key=None):
        """Validates a subnet."""
        if value is None:
            raise validation.MissingAttribute('subnet must be specified')
        if not isinstance(value, basestring):
            raise validation.ValidationError(
                'subnet must be a string, not \'%r\'' % type(value))
        try:
            ipaddr.IPNetwork(value)
        except ValueError:
            raise validation.ValidationError(
                '%s is not a valid IPv4 or IPv6 subnet' % value)

        # Extra validation check since ipaddr accepts quad-dotted subnet masks.
        parts = value.split('/')
        if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
            raise validation.ValidationError(
                'Prefix length of subnet %s must be an '
                'integer (quad-dotted masks are not '
                'supported)' % value)

        return value
Beispiel #6
0
  def Validate(self, value, unused_key=None):
    """Validates an URL pattern."""
    if value is None:
      raise validation.MissingAttribute('url must be specified')
    if not isinstance(value, basestring):
      raise validation.ValidationError('url must be a string, not \'%r\'' %
                                       type(value))

    url_holder = ParsedURL(value)
    if url_holder.host_exact:
      _ValidateMatch(_URL_HOST_EXACT_PATTERN_RE, url_holder.host,
                     'invalid host_pattern \'%s\'' % url_holder.host)
      # Explicitly disallow IpV4 #.#.#.# addresses. These will match
      # _URL_HOST_EXACT_PATTERN_RE above.
      _ValidateNotIpV4Address(url_holder.host)
    else:
      _ValidateMatch(_URL_HOST_SUFFIX_PATTERN_RE, url_holder.host_pattern,
                     'invalid host_pattern \'%s\'' % url_holder.host_pattern)

    #TODO(user): validate path_pattern and lengths of both patterns.
    #                also validate hostname label lengths 63 charn max)
    return value
Beispiel #7
0
            raise e
        except Exception, e:
            try:
                error_str = str(e)
            except Exception:
                error_str = '<unknown>'

            try:
                value_str = str(value)
            except Exception:
                value_str = '<unknown>'

            # Raise a more generic exception message.
            message = ("Unable to assign value '%s' to attribute '%s':\n%s" %
                       (value_str, key, error_str))
            raise validation.ValidationError(message, e)

    def AppendTo(self, subject, value):
        """Append a value to a sequence.

    Args:
      subject: _ObjectSequence that is receiving new value.
      value: Value that is being appended to sequence.
    """
        if isinstance(value, _ObjectMapper):
            # Construct a new instance of the list.
            value.set_value(subject.constructor())
            subject.value.append(value.value)
        else:
            # Append value to list.
            subject.value.append(value)
Beispiel #8
0
def _ValidateMatch(regex, value, message):
  """Validate value matches regex."""
  matcher = regex.match(value)
  if not matcher:
    raise validation.ValidationError(message)
  return matcher