Exemplo n.º 1
0
def split_cidr_data_handler(value,
                            data,
                            dest_ip='ip',
                            dest_netmask='netmask',
                            neg=False):
    """
    Split a cidr address (e.g. 192.168.1.1/24) into separate IP address
    and netmask value. The names of the ip and netmask fields are
    specified (typically directly in the same block/dictionary where
    the argument data handler is specifed) with a 'dest-ip' and a
    'dest-netmask' values.
    """
    global bigsh

    m = COMMAND_CIDR_RE.match(value)
    if m:
        bits = int(m.group(3))
        if bits > 32:
            raise error.ArgumentValidationError("max cidr block is 32")

        data[dest_ip] = m.group(1)
        if neg:
            data[dest_netmask] = utif.inet_ntoa(~(0xffffffff << (32 - bits)))
        else:
            data[dest_netmask] = utif.inet_ntoa((0xffffffff << (32 - bits)))
Exemplo n.º 2
0
def convert_tag_to_parts(value, data, namespace_key, name_key, value_key):
    """
    Split a tag of the form [ns].name=value into the three
    component parts
    """

    if debug.description():
        print "convert_tag_to_parts: %s %s %s %s %s" % (
            value, data, namespace_key, name_key, value_key)

    tag_and_value = value.split('=')
    if len(tag_and_value) != 2:
        raise error.ArgumentValidationError(
            "tag <[tag-namespace.]name>=<value>")

    tag_parts = tag_and_value[0].split('.')
    if len(tag_parts) == 1:
        tag_namespace = "default"
        tag_name = tag_parts[0]
    elif len(tag_parts) >= 2:
        tag_namespace = '.'.join(tag_parts[:-1])
        tag_name = tag_parts[-1]

    # should the names have some specific validation?
    data[namespace_key] = tag_namespace
    data[name_key] = tag_name
    data[value_key] = tag_and_value[1]
Exemplo n.º 3
0
def warn_missing_interface(value, data, field, is_no, obj_value, many=False):
    if not is_no:
        bigdb = bigsh.bigdb

        if debug.description() or debug.cli():
            print 'warn_missing_interface:', value, data, field, is_no, \
                                             obj_value, many
        # need switch, if_name
        pk_data = {}
        bigdb.add_mode_stack_paths(pk_data)
        switch = pk_data.get('switch')
        if switch == None:
            switch = pk_data.get('dpid')
        if switch == None:
            switch = data.get('switch')
        if switch == None:
            switch = data.get('dpid')
        if bigdb.enabled and switch == None:
            for (n, v) in data.items() + pk_data.items():
                if n.find('/') >= 0:
                    parts = n.split('/')
                    for suffix in ['switch', 'switch-dpid', 'switch-id']:
                        if parts[-1] == suffix:
                            switch = v
        if switch == None:
            if debug.description():
                print 'warn_missing_interface:', data
            raise error.ArgumentValidationError(
                "Can't identify switch for validation")
        force = True if data.get('force', '') != '' else False
        # check to see if the interface is a list or a range,
        ifs = value.split(',')
        range_re = re.compile(r'([A-Za-z0-9-/\.:]*?)(\d+)-(\d+)$')
        if many:
            interfaces = []
            remedy = ''
            for if_name in ifs:
                # check for trailing "-<integer>" which is intended to
                # identify a range, if so split that into multiple entites
                m = range_re.match(if_name)
                if m:
                    print 'TAIL MATCH', m.group(1), m.group(2), m.group(3)
                    for suffix in range(int(m.group(2)), int(m.group(3)) + 1):
                        interfaces.append('%s%s' % (m.group(1), suffix))
                else:
                    interfaces.append(if_name)
        else:
            remedy = '\nUse \"exit; no interface %s\" to remove' % value
            interfaces = [value]

        check_missing_interface(switch, interfaces, remedy)
    data[field] = value
Exemplo n.º 4
0
def check_missing_interface(switch, interfaces, remedy):
    #
    # The switch value could be a compound key reference to a
    # switch, if there's a '|' in the switch valud, try to guess
    # which entry is the switch

    if type(interfaces) == str or type(interfaces) == unicode:
        interfaces = [interfaces]

    parts = switch.split('|')
    if len(parts) > 1:
        for part in parts:
            if utif.COMMAND_DPID_RE.match(part):
                switch = part
                break
        else:
            switch = part[0]

    bigdb = bigsh.bigdb
    try:
        (schema, result) = \
            bigdb.schema_and_result('core/switch', {'dpid' : switch })

        final_result = result.expect_single_result()
        if final_result == None:
            raise error.ArgumentValidationError("switch not connected")
    except:
        # no switch
        if debug.description() or debug.cli():
            traceback.print_exc()
        bigsh.warning('switch %s currently not active, '
                      'interface %s may not exist' %
                      (switch, ', '.join(interfaces)))
        return

    if not 'interface' in final_result:
        bigsh.warning('switch %s currently not active, '
                      'interface %s may not exist' %
                      (switch, ', '.join(interfaces)))
        return

    known_interfaces = [x['name'] for x in final_result['interface']]
    if_names = [x.lower() for x in known_interfaces]
    for interface in interfaces:
        if not interface.lower() in if_names:
            # pre-servce case, try to identify unique ranges
            ranges = interface_ranges(known_interfaces)

            bigsh.warning('active switch has no interface "%s", '
                          'known: %s' % (interface, ', '.join(ranges)) +
                          remedy)
            return
def warn_missing_interface(value, data, field, is_no, obj_type, obj_value):
    if not is_no:
        # need switch, if_name
        pk_data = {mi.pk(obj_type): obj_value}
        mi.split_compound_into_dict(obj_type, mi.pk(obj_type), pk_data, True)
        switch = pk_data.get('switch')
        if switch == None:
            switch = pk_data.get('dpid')
        if switch == None:
            switch = data.get('switch')
        if switch == None:
            switch = data.get('dpid')
        if switch == None:
            raise error.ArgumentValidationError(
                "Can't identify switch for validation")
        force = True if data.get('force', '') != '' else False
        check_missing_interface(switch, value)
    data[field] = value
Exemplo n.º 6
0
def validate_host(typedef, value):
    """
    """

    if _is_mac_address(value):
        return value

    pk = mi.pk('host-config')
    key = convert_alias_to_object_key('host-config', value)
    key_dict = {pk: key}
    mi.split_compound_into_dict('host-config', pk, key_dict, is_prefix=True)
    if 'mac' in key_dict and _is_mac_address(key_dict['mac']):
        try:
            _exists = rest_to_model.get_model_from_url('host', key_dict)
            return value
        except:
            raise error.ArgumentValidationError('host "%s": doesn\'t exist' %
                                                value)

    command._raise_argument_validation_exception(
        typedef, value, 'not host alias nor mac address')
Exemplo n.º 7
0
def convert_interface_to_port(value, data, field, other=None, scoped=None):
    # look for the switch name in data
    if scoped:
        dpid = data.get(scoped)
    elif 'dpid' in data:
        dpid = data['dpid']
    else:
        dpid = data.get('switch', '')  # possibly other choices

    # if its not a specific switch, no conversion is possible
    # should the value be passed through?
    if dpid == '':
        data[field] = value
        return

    ports = rest_to_model.get_model_from_url('interfaces', {'dpid': dpid})
    for port in ports:
        if port['portName'] == value:
            data[field] = port['portNumber']  # should this be a string?
            break
    else:
        raise error.ArgumentValidationError("Can't find port %s on switch %s" %
                                            (value, dpid))
def replace_value_handler(value, obj_type, data, field, other=None):
    """
    Use the other field when its present to find a related obj_type,
    look for the field in that structure to populate data.
    """
    global sdnsh

    table = obj_type

    if sdnsh.description:
        print "replace_value_handler: obj_type: %s value: %s data: %s field %s other %s" % \
                (obj_type, value, data, field, other)
    fields = [field]
    if other:
        parts = other.split('|')
        table = parts[0]
        fields = parts[1:]

    try:
        row = sdnsh.get_object_from_store(table, value)
    except Exception, e:
        raise error.ArgumentValidationError("Unknown value %s (%s)" %
                                            (value, obj_type))
def verify_router_gw_ip(data):
    if data['ip-address']=='0.0.0.0':
        raise error.ArgumentValidationError("0.0.0.0 is not a valid router interface ip address")
def verify_router_intf_ip(data):
    if data['ip-address']=='0.0.0.0':
        raise error.ArgumentValidationError("0.0.0.0 is not a valid router interface ip address")
    if data['subnet-mask']=='255.255.255.255':
        raise error.ArgumentValidationError("0.0.0.0 is not a valid router interface ip subnet mask")
        print "replace_value_handler: obj_type: %s value: %s data: %s field %s other %s" % \
                (obj_type, value, data, field, other)
    fields = [field]
    if other:
        parts = other.split('|')
        table = parts[0]
        fields = parts[1:]

    try:
        row = sdnsh.get_object_from_store(table, value)
    except Exception, e:
        raise error.ArgumentValidationError("Unknown value %s (%s)" %
                                            (value, obj_type))
    for field in fields:
        if field not in row:
            raise error.ArgumentValidationError("Unknown field %s (%s)" %
                                                (field, obj_type))
        if sdnsh.description:
            print 'replace_value_handler: set %s <- %s from obj-type %s' %\
                  (field, row[field], table)
        data[field] = row[field]


def enable_disable_to_boolean_handler(value, data, field):
    if value == 'enable':
        data[field] = True
    if value == 'disable':
        data[field] = False


def date_to_integer_handler(value, data, field):
    if (value == 'now' or value == 'current'):