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
 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
 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 _Normalize(self):
     if self.properties is None:
         return
     is_geo = any(x.mode == 'geospatial' for x in self.properties)
     for prop in self.properties:
         if is_geo:
             if prop.direction is not None:
                 raise validation.ValidationError(
                     'direction not supported in a geospatial index')
         else:
             # Normalize the property object by making direction explicit
             if prop.IsAscending():
                 prop.direction = 'asc'
Beispiel #6
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 #7
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 #8
0
 def CheckInitialized(self):
     if self.direction is not None and self.mode is not None:
         raise validation.ValidationError(
             'direction and mode are mutually exclusive')
     super(Property, self).CheckInitialized()
Beispiel #9
0
def _ValidateMatch(regex, value, message):
    """Validate value matches regex."""
    matcher = regex.match(value)
    if not matcher:
        raise validation.ValidationError(message)
    return matcher
Beispiel #10
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 #11
0
  def MapTo(self, subject, key, value):
    """Map key-value pair to an objects attribute.

    Args:
      subject: _ObjectMapper of object that will receive new attribute.
      key: Key of attribute.
      value: Value of new attribute.

    Raises:
      UnexpectedAttribute when the key is not a validated attribute of
      the subject value class.
    """
    assert isinstance(subject.value, validation.ValidatedBase)

    try:
      attribute = subject.value.GetValidator(key)
    except validation.ValidationError as err:
      raise yaml_errors.UnexpectedAttribute(err)

    if isinstance(value, _ObjectMapper):
      # Now know what class the new instance should be.
      # Time to construct it from the attributes expected type.
      value.set_value(attribute.expected_type())
      value = value.value
    elif isinstance(value, _ObjectSequencer):
      # Now know what class new instances within the sequence should be.
      value.set_constructor(self._GetRepeated(attribute))
      value = value.value

    subject.see(key)
    try:
      subject.value.Set(key, value)
    except validation.ValidationError as 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>'

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

      # Update error message with a better message.
      e.message = ("Unable to assign value '%s' to attribute '%s':\n%s" %
                   (value_str, key, error_str))
      raise e
    except Exception as 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)