コード例 #1
0
ファイル: pool.py プロジェクト: izogain/calico-containers
def validate_arguments(arguments):
    """
    Validate argument values:
        <CIDRS>

    :param arguments: Docopt processed arguments
    """
    # Validate CIDR
    cidrs = arguments.get("<CIDRS>")
    start_ip = arguments.get("<START_IP>")
    end_ip = arguments.get("<END_IP>")
    if cidrs:
        for cidr in cidrs:
            if not validate_cidr(cidr):
                print "Invalid CIDR specified %s" % cidr
                sys.exit(1)
    elif start_ip or end_ip:
        if not (validate_ip(start_ip, 4) or validate_ip(start_ip, 6)):
            print "Invalid START_IP specified."
            sys.exit(1)
        elif not (validate_ip(end_ip, 4) or validate_ip(end_ip, 6)):
            print "Invalid END_IP specified."
            sys.exit(1)
        elif IPAddress(start_ip).version != IPAddress(end_ip).version:
            print "START_IP and END_IP must be the same ip version"
            sys.exit(1)
        elif not IPAddress(start_ip) < IPAddress(end_ip):
            print "START_IP must be a smaller ip address than END_IP"
            sys.exit(1)
コード例 #2
0
def validate_arguments(arguments):
    """
    Validate argument values:
        <IP>

    Arguments not validated:
        <CONTAINER>
        <INTERFACE>

    :param arguments: Docopt processed arguments
    """
    # Validate IP
    requested_ip = arguments.get("<IP>")
    if not (requested_ip is None or validate_ip(requested_ip, 4)
            or validate_ip(requested_ip, 6) or validate_cidr(requested_ip)
            or requested_ip.lower() in ('ipv4', 'ipv6')):
        print_paragraph("Invalid IP address specified.  Argument must be a "
                        "valid IP or CIDR.")
        sys.exit(1)

    # Validate POOL
    if requested_ip is not None and '/' in requested_ip:
        requested_pool = IPNetwork(requested_ip)

        try:
            client.get_ip_pool_config(requested_pool.version, requested_pool)
        except KeyError:
            print_paragraph("Invalid CIDR specified for desired pool. "
                            "No pool found for {0}.".format(requested_pool))
            sys.exit(1)

    # Validate PROFILE
    endpoint.validate_arguments(arguments)
コード例 #3
0
def validate_arguments(arguments):
    """
    Validate argument values:
        <CIDRS>

    :param arguments: Docopt processed arguments
    """
    # Validate CIDR
    cidrs = arguments.get("<CIDRS>")
    start_ip = arguments.get("<START_IP>")
    end_ip = arguments.get("<END_IP>")
    if cidrs:
        for cidr in cidrs:
            if not validate_cidr(cidr):
                print "Invalid CIDR specified %s" % cidr
                sys.exit(1)
    elif start_ip or end_ip:
        if not (validate_ip(start_ip, 4) or validate_ip(start_ip, 6)):
            print "Invalid START_IP specified."
            sys.exit(1)
        elif not (validate_ip(end_ip, 4) or validate_ip(end_ip, 6)):
            print "Invalid END_IP specified."
            sys.exit(1)
        elif IPAddress(start_ip).version != IPAddress(end_ip).version:
            print "START_IP and END_IP must be the same ip version"
            sys.exit(1)
        elif not IPAddress(start_ip) < IPAddress(end_ip):
            print "START_IP must be a smaller ip address than END_IP"
            sys.exit(1)
コード例 #4
0
def validate_arguments(arguments):
    """
    Validate argument values:
        <IP>

    Arguments not validated:
        <CONTAINER>
        <INTERFACE>

    :param arguments: Docopt processed arguments
    """
    # Validate IP
    requested_ip = arguments.get("<IP>")
    if not (requested_ip is None or
            validate_ip(requested_ip, 4) or
            validate_ip(requested_ip, 6) or
            validate_cidr(requested_ip) or
            requested_ip.lower() in ('ipv4', 'ipv6')):
        sys.exit('Invalid IP address specified. Argument must be an IP, '
                 'a cidr, "ipv4" or "ipv6". '
                 '"{0}" was given'.format(requested_ip))

    # Validate POOL
    if requested_ip is not None and '/' in requested_ip:
        try:
            requested_pool = IPNetwork(requested_ip)
        except TypeError:
            sys.exit('Invalid cidr specified for desired pool. '
                     '"{0}" was given."'.format(pool))

        try:
            pool = client.get_ip_pool_config(requested_pool.version,
                                             requested_pool)
        except KeyError:
            sys.exit('Invalid cidr specified for desired pool. '
                     'No pool found for "{0}"'.format(requested_pool))


    # Validate PROFILE
    endpoint.validate_arguments(arguments)
コード例 #5
0
ファイル: container.py プロジェクト: alexhersh/calico-docker
def validate_arguments(arguments):
    """
    Validate argument values:
        <IP>

    Arguments not validated:
        <CONTAINER>
        <INTERFACE>

    :param arguments: Docopt processed arguments
    """
    # Validate IP
    requested_ip = arguments.get("<IP>")
    if not (requested_ip is None or validate_ip(requested_ip, 4)
            or validate_ip(requested_ip, 6) or validate_cidr(requested_ip)
            or requested_ip.lower() in ('ipv4', 'ipv6')):
        sys.exit('Invalid IP address specified. Argument must be an IP, '
                 'a cidr, "ipv4" or "ipv6". '
                 '"{0}" was given'.format(requested_ip))

    # Validate POOL
    if requested_ip is not None and '/' in requested_ip:
        try:
            requested_pool = IPNetwork(requested_ip)
        except TypeError:
            sys.exit('Invalid cidr specified for desired pool. '
                     '"{0}" was given."'.format(pool))

        try:
            pool = client.get_ip_pool_config(requested_pool.version,
                                             requested_pool)
        except KeyError:
            sys.exit('Invalid cidr specified for desired pool. '
                     'No pool found for "{0}"'.format(requested_pool))

    # Validate PROFILE
    endpoint.validate_arguments(arguments)
コード例 #6
0
ファイル: container.py プロジェクト: xdongp/calico-docker
def validate_arguments(arguments):
    """
    Validate argument values:
        <IP>

    Arguments not validated:
        <CONTAINER>
        <INTERFACE>

    :param arguments: Docopt processed arguments
    """
    # Validate IP
    requested_ip = arguments.get("<IP>")
    if not (requested_ip is None or
            validate_ip(requested_ip, 4) or
            validate_ip(requested_ip, 6) or
            validate_cidr(requested_ip) or
            requested_ip.lower() in ('ipv4', 'ipv6')):
        print_paragraph("Invalid IP address specified.  Argument must be a "
                        "valid IP or CIDR.")
        sys.exit(1)

    # Validate POOL
    if requested_ip is not None and '/' in requested_ip:
        requested_pool = IPNetwork(requested_ip)

        try:
            client.get_ip_pool_config(requested_pool.version, requested_pool)
        except KeyError:
            print_paragraph("Invalid CIDR specified for desired pool. "
                            "No pool found for {0}.".format(requested_pool))
            sys.exit(1)


    # Validate PROFILE
    endpoint.validate_arguments(arguments)
コード例 #7
0
def validate_arguments(arguments):
    """
    Validate argument values:
        <PROFILE>
        <SRCTAG>
        <SRCCIDR>
        <DSTTAG>
        <DSTCIDR>
        <ICMPTYPE>
        <ICMPCODE>
        <SRCPORTS>
        <DSTPORTS>

    Arguments not validated:
        <POSITION>

    :param arguments: Docopt processed arguments
    """
    # Validate Profiles
    profile_ok = True
    if arguments.get("<PROFILE>") is not None:
        profile = arguments.get("<PROFILE>")
        profile_ok = validate_characters(profile)

    # Validate tags
    tag_src_ok = (arguments.get("<SRCTAG>") is None
                  or validate_characters(arguments["<SRCTAG>"]))
    tag_dst_ok = (arguments.get("<DSTTAG>") is None
                  or validate_characters(arguments["<DSTTAG>"]))

    # Validate IPs
    cidr_ok = True
    cidr_list = []
    for arg in ["<SRCCIDR>", "<DSTCIDR>"]:
        if arguments.get(arg) is not None:
            cidr_list.append(arguments[arg])
            cidr_ok = validate_cidr(arguments[arg])
            if not cidr_ok:
                break

    icmp_ok = True
    for arg in ["<ICMPCODE>", "<ICMPTYPE>"]:
        if arguments.get(arg) is not None:
            icmp_ok = validate_icmp_type(arguments[arg])
            if not icmp_ok:
                break

    ports_ok = True
    for arg in ["<SRCPORTS>", "<DSTPORTS>"]:
        if arguments.get(arg) is not None:
            ports_ok = validate_ports(arguments[arg])
            if not ports_ok:
                break

    cidr_versions_ok = True
    if cidr_list:
        ip_version = None
        if arguments.get("icmp"):
            ip_version = 4
        elif arguments.get("icmpv6"):
            ip_version = 6
        cidr_versions_ok = validate_cidr_versions(cidr_list,
                                                  ip_version=ip_version)

    # Print error message
    if not profile_ok:
        print_paragraph("Profile names must be < 40 character long and can "
                        "only contain numbers, letters, dots, dashes and "
                        "underscores.")
    if not (tag_src_ok and tag_dst_ok):
        print_paragraph("Tags names can only contain numbers, letters, dots, "
                        "dashes and underscores.")
    if not cidr_ok:
        print "Invalid CIDR specified."
    if not icmp_ok:
        print "Invalid ICMP type or ICMP code specified."
    if not ports_ok:
        print "Invalid SRCPORTS or DSTPORTS specified."
    if not cidr_versions_ok:
        print "Invalid or unmatching IP versions for SRCCIDR/DSTCIDR."

    # Exit if not valid
    if not (profile_ok and tag_src_ok and tag_dst_ok and cidr_ok and icmp_ok
            and ports_ok and cidr_versions_ok):
        sys.exit(1)
コード例 #8
0
ファイル: profile.py プロジェクト: xuzhaokui/calico-docker
def validate_arguments(arguments):
    """
    Validate argument values:
        <PROFILE>
        <SRCTAG>
        <SRCCIDR>
        <DSTTAG>
        <DSTCIDR>
        <ICMPTYPE>
        <ICMPCODE>
        <SRCPORTS>
        <DSTPORTS>

    Arguments not validated:
        <POSITION>

    :param arguments: Docopt processed arguments
    """
    # Validate Profiles
    profile_ok = True
    if arguments.get("<PROFILE>") is not None:
        profile = arguments.get("<PROFILE>")
        profile_ok = validate_characters(profile)

    # Validate tags
    tag_src_ok = (arguments.get("<SRCTAG>") is None or
                validate_characters(arguments["<SRCTAG>"]))
    tag_dst_ok = (arguments.get("<DSTTAG>") is None or
                validate_characters(arguments["<DSTTAG>"]))

    # Validate IPs
    cidr_ok = True
    for arg in ["<SRCCIDR>", "<DSTCIDR>"]:
        if arguments.get(arg) is not None:
            cidr_ok = validate_cidr(arguments[arg])
            if not cidr_ok:
                break

    icmp_ok = True
    for arg in ["<ICMPCODE>", "<ICMPTYPE>"]:
        if arguments.get(arg) is not None:
            icmp_ok = validate_icmp_type(arguments[arg])
            if not icmp_ok:
                break

    ports_ok = True
    for arg in ["<SRCPORTS>", "<DSTPORTS>"]:
        if arguments.get(arg) is not None:
            ports_ok = validate_ports(arguments[arg])
            if not ports_ok:
                break

    # Print error message
    if not profile_ok:
        print_paragraph("Profile names must be < 40 character long and can "
                        "only contain numbers, letters, dots, dashes and "
                        "underscores.")
    if not (tag_src_ok and tag_dst_ok):
        print_paragraph("Tags names can only contain numbers, letters, dots, "
                        "dashes and underscores.")
    if not cidr_ok:
        print "Invalid CIDR specified."
    if not icmp_ok:
        print "Invalid ICMP type or ICMP code specified."
    if not ports_ok:
        print "Invalid SRCPORTS or DSTPORTS specified."

    # Exit if not valid
    if not (profile_ok and tag_src_ok and tag_dst_ok
            and cidr_ok and icmp_ok and ports_ok):
        sys.exit(1)
コード例 #9
0
def validate_arguments(arguments):
    """
    Validate argument values:
        <PROFILE>
        <SRCTAG>
        <SRCCIDR>
        <DSTTAG>
        <DSTCIDR>
        <ICMPTYPE>
        <ICMPCODE>

    Arguments not validated:
        <SRCPORTS>
        <DSTPORTS>
        <POSITION>

    :param arguments: Docopt processed arguments
    """
    # Validate Profiles
    profile_ok = True
    if arguments.get("<PROFILE>") is not None:
        profile = arguments.get("<PROFILE>")
        profile_ok = validate_characters(profile)

    # Validate tags
    tag_src_ok = (arguments.get("<SRCTAG>") is None
                  or validate_characters(arguments["<SRCTAG>"]))
    tag_dst_ok = (arguments.get("<DSTTAG>") is None
                  or validate_characters(arguments["<DSTTAG>"]))

    # Validate IPs
    cidr_ok = True
    for arg in ["<SRCCIDR>", "<DSTCIDR>"]:
        if arguments.get(arg) is not None:
            cidr_ok = validate_cidr(arguments[arg])

    icmp_ok = True
    for arg in ["<ICMPCODE>", "<ICMPTYPE>"]:
        if arguments.get(arg) is not None:
            try:
                value = int(arguments[arg])
                if not (0 <= value < 255):  # Felix doesn't support 255
                    raise ValueError("Invalid %s: %s" % (arg, value))
            except ValueError:
                icmp_ok = False

    # Print error message
    if not profile_ok:
        print_paragraph("Profile names must be < 40 character long and can "
                        "only contain numbers, letters, dots, dashes and "
                        "underscores.")
    if not (tag_src_ok and tag_dst_ok):
        print_paragraph("Tags names can only contain numbers, letters, dots, "
                        "dashes and underscores.")
    if not cidr_ok:
        print "Invalid CIDR specified."
    if not icmp_ok:
        print "Invalid ICMP type or code specified."

    # Exit if not valid
    if not (profile_ok and tag_src_ok and tag_dst_ok and cidr_ok and icmp_ok):
        sys.exit(1)
コード例 #10
0
def subnet_create_api():
    """
    Implementation Notes
      Creates a subnet on a network.

    Response Class (Status 201)
      Subnet {
        subnetId (string, optional): Subnet uuid.
        subnetName (string, optional): Subnet name, a user readable name.
        networkId (string, optional): Network uuid.
        cidr (string, optional): The CIDR of subnet.
        allocation_pools (Array[inline_model], optional):
          The start and end addresses for the allocation pools.
        gatewayIp (string, required): The gateway IP address.
        dnsNameservers (Array[string], optional):
          A list of DNS name servers for the subnet.
      }
      inline_model {
        start (string, optional): Start IP address. ,
        end (string, optional): End IP address.
      }

    Parameters
      Subnet (body, required): Subnet description
    """
    try:
        req = models.Subnet(request.json)
        req.validate()
    except Exception as e:
        return err_return('Parameter Invalid', 'ParameterInvalid', '',
                          HTTP_BAD_REQUEST)
    try:
        if not req.network_id:
            return err_return('networkid is required', 'ParameterInvalid', '',
                              HTTP_BAD_REQUEST)
        if not req.subnet_id:
            req_id = str(uuid.uuid4())
        else:
            req_id = req.subnet_id
            sb_name = subnet_db_get_one('name', id=req_id)
            if sb_name:
                return err_return('id(%s) in use by %s' % (req_id, sb_name),
                                  'ParameterInvalid', '', HTTP_BAD_REQUEST)
        if req.subnet_name:
            if len(req.subnet_name) > NAME_MAX_LEN:
                return err_return('Length of name must be less than 255',
                                  'ParameterInvalid', '', HTTP_BAD_REQUEST)
        else:
            req.subnet_name = ''

        external = network_db_get_one('external', id=req.network_id)
        if external is None:
            return err_return("networkid does not exist", "ParameterInvalid",
                              "", HTTP_BAD_REQUEST)
        if not req.dns_nameservers:
            req.dns_nameservers = []
        if not req.allocation_pools:
            req.allocation_pools = []
        allocation_pools = []
        for all_pool in req.allocation_pools:
            allocation_pools.append(all_pool.to_primitive())
        req.allocation_pools = allocation_pools
        for pool in req.allocation_pools:
            if ip_to_bin(pool['start']) > ip_to_bin(pool['end']):
                return err_return("end_ip must be more than start_ip",
                                  "IPRangeError", "", HTTP_BAD_REQUEST)

        if external == 0:
            if not req.cidr:
                return err_return('cidr is required', 'ParameterInvalid', '',
                                  HTTP_BAD_REQUEST)
            if not validate_cidr(req.cidr):
                return err_return('cidr invalid', 'ParameterInvalid', '',
                                  HTTP_BAD_REQUEST)
            if not req.gateway_ip:
                return err_return('gateway ip is required', 'ParameterInvalid',
                                  '', HTTP_BAD_REQUEST)
            vl2lcid = yynetworkid_to_lcvl2id(req.network_id)
            log.debug('vl2lcid=%s' % vl2lcid)
            nets = [{
                "prefix": VFW_TOR_LINK_NET_PRE,
                "netmask": VFW_TOR_LINK_NET_MASK
            }]
            cidr = str(req.cidr).split('/')
            new_prf = cidr[0]
            new_mask = int(cidr[1])
            subnets = get_subnets_by_network(req.network_id)
            for subnet in subnets:
                cidr = subnet['cidr'].split('/')
                old_prf = cidr[0]
                old_mask = int(cidr[1])
                if subnet_equ(new_prf, old_prf, new_mask, old_mask):
                    log.error('cidr is the same')
                    return err_return('subnet already exist',
                                      'ParameterInvalid', '', HTTP_BAD_REQUEST)
                nets.append({"prefix": old_prf, "netmask": old_mask})
            nets.append({"prefix": new_prf, "netmask": new_mask})
            log.debug('nets=%s' % nets)
            nw_name = network_db_get_one('name', id=req.network_id)
            payload = json.dumps({"name": nw_name, "nets": nets})
            r = lcapi.patch(conf.livecloud_url + '/v1/vl2s/%s' % vl2lcid,
                            data=payload)
            if r.status_code != HTTP_OK:
                return Response(json.dumps(NEUTRON_400)), HTTP_NOT_FOUND
            nets = r.json()['DATA']['NETS']
            for net in nets:
                if subnet_equ(net['PREFIX'], new_prf, net['NETMASK'],
                              new_mask):
                    sb_lcuuid = net['LCUUID']
                    sb_idx = net['NET_INDEX']
                    break
            else:
                log.error('sb_lcuuid no found')
                sb_lcuuid = 'sb_lcuuid no found'
                sb_idx = -1
        else:
            subnetid = subnet_db_get_one('id', network_id=req.network_id)
            if subnetid:
                return err_return('subnet(%s) already exists' % subnetid,
                                  'Fail', '', HTTP_BAD_REQUEST)
            # ISP
            if not req.allocation_pools:
                return err_return('allocation_pools can not be empty',
                                  'ParameterInvalid', '', HTTP_BAD_REQUEST)
            id = subnet_db_get_one('id', network_id=req.network_id)
            if id:
                return subnet_get(subnetid=id)
            lcuuid = network_db_get_one('lcuuid', id=req.network_id)
            isp = lc_vl2_db_get_one('isp', lcuuid=lcuuid)
            items = lc_ip_res_db_get_all(req='ip, netmask, gateway, userid',
                                         isp=isp)
            if not items:
                return err_return("No ISP IP found", "BadRequest",
                                  "Please add ISP IP to system first",
                                  HTTP_BAD_REQUEST)
            req.gateway_ip = items[0]['gateway']
            req.cidr = ip_mask_to_cidr(items[0]['ip'], items[0]['netmask'])
            isp_all_ips = []
            ip_to_userid = {}
            for it in items:
                isp_all_ips.append(it['ip'])
                ip_to_userid[it['ip']] = it['userid']
            req_ips = alloc_pools_to_ip_list(req.allocation_pools)
            for req_ip in req_ips:
                if req_ip not in isp_all_ips:
                    return err_return("%s does not exist" % req_ip,
                                      "IPInvalid", "", HTTP_BAD_REQUEST)
                if ip_to_userid[req_ip] != 0:
                    return err_return("%s in use" % req_ip, "IPInUse", "",
                                      HTTP_BAD_REQUEST)
            sb_lcuuid = str(uuid.uuid4())
            sb_idx = -1

        sql = ("INSERT INTO neutron_subnets "
               "VALUES('%s','%s','%s','%s','%s','%s','%s','%s',%d)" %
               (req_id, req.subnet_name, req.network_id, req.cidr,
                json.dumps(req.allocation_pools), req.gateway_ip,
                json.dumps(req.dns_nameservers), sb_lcuuid, sb_idx))
        log.debug('add subnet sql=%s' % sql)
        with MySQLdb.connect(**DB_INFO) as cursor:
            cursor.execute(sql)
        if external:
            sql = "UPDATE ip_resource_v2_2 SET userid=%s WHERE ip in ('-1',"
            for req_ip in req_ips:
                sql += "'%s'," % req_ip
            sql = sql[:-1]
            sql += ")"
            log.debug('sql=%s' % sql)
            with MySQLdb.connect(**LCDB_INFO) as cursor:
                cursor.execute(sql, conf.livecloud_userid)

        resp, code = subnet_get(subnetid=req_id)
        return resp, HTTP_CREATED

    except Exception as e:
        log.error(e)
        return Response(json.dumps(NEUTRON_500)), HTTP_INTERNAL_SERVER_ERROR
コード例 #11
0
ファイル: profile.py プロジェクト: kriss9/calico-docker
def validate_arguments(arguments):
    """
    Validate argument values:
        <PROFILE>
        <SRCTAG>
        <SRCCIDR>
        <DSTTAG>
        <DSTCIDR>
        <ICMPTYPE>
        <ICMPCODE>

    Arguments not validated:
        <SRCPORTS>
        <DSTPORTS>
        <POSITION>

    :param arguments: Docopt processed arguments
    """
    # Validate Profiles
    profile_ok = True
    if arguments.get("<PROFILE>") is not None:
        profile = arguments.get("<PROFILE>")
        profile_ok = validate_characters(profile)

    # Validate tags
    tag_src_ok = arguments.get("<SRCTAG>") is None or validate_characters(arguments["<SRCTAG>"])
    tag_dst_ok = arguments.get("<DSTTAG>") is None or validate_characters(arguments["<DSTTAG>"])

    # Validate IPs
    cidr_ok = True
    for arg in ["<SRCCIDR>", "<DSTCIDR>"]:
        if arguments.get(arg) is not None:
            cidr_ok = validate_cidr(arguments[arg])

    icmp_ok = True
    for arg in ["<ICMPCODE>", "<ICMPTYPE>"]:
        if arguments.get(arg) is not None:
            try:
                value = int(arguments[arg])
                if not (0 <= value < 255):  # Felix doesn't support 255
                    raise ValueError("Invalid %s: %s" % (arg, value))
            except ValueError:
                icmp_ok = False

    # Print error message
    if not profile_ok:
        print_paragraph(
            "Profile names must be < 40 character long and can "
            "only contain numbers, letters, dots, dashes and "
            "underscores."
        )
    if not (tag_src_ok and tag_dst_ok):
        print_paragraph("Tags names can only contain numbers, letters, dots, " "dashes and underscores.")
    if not cidr_ok:
        print "Invalid CIDR specified."
    if not icmp_ok:
        print "Invalid ICMP type or code specified."

    # Exit if not valid
    if not (profile_ok and tag_src_ok and tag_dst_ok and cidr_ok and icmp_ok):
        sys.exit(1)