def get_subnets(context, limit=None, page_reverse=False, sorts=['<STR_LIT:id>'],<EOL>marker=None, filters=None, fields=None):

LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters, fields))<EOL>filters = filters or {}<EOL>subnets = db_api.subnet_find(context, limit=limit,<EOL>page_reverse=page_reverse, sorts=sorts,<EOL>marker_obj=marker, join_dns=True,<EOL>join_routes=True, join_pool=True, **filters)<EOL>for subnet in subnets:<EOL><INDENT>cache = subnet.get("<STR_LIT>")<EOL>if not cache:<EOL><INDENT>db_api.subnet_update_set_alloc_pool_cache(<EOL>context, subnet, subnet.allocation_pools)<EOL><DEDENT><DEDENT>return v._make_subnets_list(subnets, fields=fields)<EOL>

Retrieve a list of subnets.

    The contents of the list depends on the identity of the user
    making the request (as indicated by the context) as well as any
    filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a subnet as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.
    : param fields: a list of strings that are valid keys in a
        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters))<EOL>return db_api.subnet_count_all(context, **filters)<EOL>

Return the number of subnets.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)<EOL>if not subnet:<EOL><INDENT>raise n_exc.SubnetNotFound(subnet_id=id)<EOL><DEDENT>if not context.is_admin:<EOL><INDENT>if STRATEGY.is_provider_network(subnet.network_id):<EOL><INDENT>if subnet.tenant_id == context.tenant_id:<EOL><INDENT>raise n_exc.NotAuthorized(subnet_id=id)<EOL><DEDENT>else:<EOL><INDENT>raise n_exc.SubnetNotFound(subnet_id=id)<EOL><DEDENT><DEDENT><DEDENT>_delete_subnet(context, subnet)<EOL><DEDENT>

Delete a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to delete.


allowed = ['<STR_LIT>', '<STR_LIT>']<EOL>filtered = {}<EOL>for k, val in rule.iteritems():<EOL><INDENT>if k in allowed:<EOL><INDENT>if isinstance(val, basestring) andlen(val) <= GROUP_NAME_MAX_LENGTH:<EOL><INDENT>filtered[k] = val<EOL><DEDENT><DEDENT><DEDENT>return filtered<EOL>

Only two fields are allowed for modification:

        external_service and external_service_id


@env.has_capability(env.Capabilities.SG_UPDATE_ASYNC)<EOL>def _perform_async_update_rule(context, id, db_sg_group, rule_id, action):

rpc_reply = None<EOL>sg_rpc = sg_rpc_api.QuarkSGAsyncProcessClient()<EOL>ports = db_api.sg_gather_associated_ports(context, db_sg_group)<EOL>if len(ports) > <NUM_LIT:0>:<EOL><INDENT>rpc_reply = sg_rpc.start_update(context, id, rule_id, action)<EOL>if rpc_reply:<EOL><INDENT>job_id = rpc_reply['<STR_LIT>']<EOL>job_api.add_job_to_context(context, job_id)<EOL><DEDENT>else:<EOL><INDENT>LOG.error("<STR_LIT>")<EOL><DEDENT><DEDENT>

Updates a SG rule async and return the job information.

    Only happens if the security group has associated ports. If the async
    connection fails the update continues (legacy mode).


LOG.info("<STR_LIT>" %<EOL>(context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>rule = _validate_security_group_rule(<EOL>context, security_group_rule["<STR_LIT>"])<EOL>rule["<STR_LIT:id>"] = uuidutils.generate_uuid()<EOL>group_id = rule["<STR_LIT>"]<EOL>group = db_api.security_group_find(context, id=group_id,<EOL>scope=db_api.ONE)<EOL>if not group:<EOL><INDENT>raise sg_ext.SecurityGroupNotFound(id=group_id)<EOL><DEDENT>quota.QUOTAS.limit_check(<EOL>context, context.tenant_id,<EOL>security_rules_per_group=len(group.get("<STR_LIT>", [])) + <NUM_LIT:1>)<EOL>new_rule = db_api.security_group_rule_create(context, **rule)<EOL><DEDENT>if group:<EOL><INDENT>_perform_async_update_rule(context, group_id, group, new_rule.id,<EOL>RULE_CREATE)<EOL><DEDENT>return v._make_security_group_rule_dict(new_rule)<EOL>

Creates a rule and updates the ports (async) if enabled.


def update_security_group_rule(context, id, security_group_rule):

LOG.info("<STR_LIT>" %<EOL>(context.tenant_id))<EOL>new_rule = security_group_rule["<STR_LIT>"]<EOL>new_rule = _filter_update_security_group_rule(new_rule)<EOL>with context.session.begin():<EOL><INDENT>rule = db_api.security_group_rule_find(context, id=id,<EOL>scope=db_api.ONE)<EOL>if not rule:<EOL><INDENT>raise sg_ext.SecurityGroupRuleNotFound(id=id)<EOL><DEDENT>db_rule = db_api.security_group_rule_update(context, rule, **new_rule)<EOL>group_id = db_rule.group_id<EOL>group = db_api.security_group_find(context, id=group_id,<EOL>scope=db_api.ONE)<EOL>if not group:<EOL><INDENT>raise sg_ext.SecurityGroupNotFound(id=group_id)<EOL><DEDENT><DEDENT>if group:<EOL><INDENT>_perform_async_update_rule(context, group_id, group, rule.id,<EOL>RULE_UPDATE)<EOL><DEDENT>return v._make_security_group_rule_dict(db_rule)<EOL>


LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>rule = db_api.security_group_rule_find(context, id=id,<EOL>scope=db_api.ONE)<EOL>if not rule:<EOL><INDENT>raise sg_ext.SecurityGroupRuleNotFound(id=id)<EOL><DEDENT>group = db_api.security_group_find(context, id=rule["<STR_LIT>"],<EOL>scope=db_api.ONE)<EOL>if not group:<EOL><INDENT>raise sg_ext.SecurityGroupNotFound(id=id)<EOL><DEDENT>rule["<STR_LIT:id>"] = id<EOL>db_api.security_group_rule_delete(context, rule)<EOL><DEDENT>if group:<EOL><INDENT>_perform_async_update_rule(context, group.id, group, id, RULE_DELETE)<EOL><DEDENT>

Deletes a rule and updates the ports (async) if enabled.


LOG.info("<STR_LIT>" % context.tenant_id)<EOL>port_attrs = port["<STR_LIT:port>"]<EOL>admin_only = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>utils.filter_body(context, port_attrs, admin_only=admin_only)<EOL>port_attrs = port["<STR_LIT:port>"]<EOL>mac_address = utils.pop_param(port_attrs, "<STR_LIT>", None)<EOL>use_forbidden_mac_range = utils.pop_param(port_attrs,<EOL>"<STR_LIT>", False)<EOL>segment_id = utils.pop_param(port_attrs, "<STR_LIT>")<EOL>fixed_ips = utils.pop_param(port_attrs, "<STR_LIT>")<EOL>if "<STR_LIT>" not in port_attrs:<EOL><INDENT>port_attrs['<STR_LIT>'] = "<STR_LIT>"<EOL><DEDENT>device_id = port_attrs['<STR_LIT>']<EOL>if "<STR_LIT>" not in port_attrs:<EOL><INDENT>port_attrs['<STR_LIT>'] = "<STR_LIT>"<EOL><DEDENT>instance_node_id = port_attrs['<STR_LIT>']<EOL>net_id = port_attrs["<STR_LIT>"]<EOL>port_id = uuidutils.generate_uuid()<EOL>net = db_api.network_find(context=context, limit=None, sorts=['<STR_LIT:id>'],<EOL>marker=None, page_reverse=False, fields=None,<EOL>id=net_id, scope=db_api.ONE)<EOL>if not net:<EOL><INDENT>raise n_exc.NetworkNotFound(net_id=net_id)<EOL><DEDENT>_raise_if_unauthorized(context, net)<EOL>if device_id:<EOL><INDENT>existing_ports = db_api.port_find(context,<EOL>network_id=net_id,<EOL>device_id=device_id,<EOL>scope=db_api.ONE)<EOL>if existing_ports:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT:port>", msg="<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if fixed_ips:<EOL><INDENT>quota.QUOTAS.limit_check(context, context.tenant_id,<EOL>fixed_ips_per_port=len(fixed_ips))<EOL><DEDENT>if not STRATEGY.is_provider_network(net_id):<EOL><INDENT>segment_id = None<EOL>port_count = db_api.port_count_all(context, network_id=[net_id],<EOL>tenant_id=[context.tenant_id])<EOL>quota.QUOTAS.limit_check(<EOL>context, context.tenant_id,<EOL>ports_per_network=port_count + <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>if not segment_id:<EOL><INDENT>raise q_exc.AmbiguousNetworkId(net_id=net_id)<EOL><DEDENT><DEDENT>network_plugin = utils.pop_param(port_attrs, "<STR_LIT>")<EOL>if not network_plugin:<EOL><INDENT>network_plugin = net["<STR_LIT>"]<EOL><DEDENT>port_attrs["<STR_LIT>"] = network_plugin<EOL>ipam_driver = _get_ipam_driver(net, port=port_attrs)<EOL>net_driver = _get_net_driver(net, port=port_attrs)<EOL>base_net_driver = _get_net_driver(net)<EOL>security_groups = utils.pop_param(port_attrs, "<STR_LIT>")<EOL>if security_groups is not None:<EOL><INDENT>raise q_exc.SecurityGroupsNotImplemented()<EOL><DEDENT>group_ids, security_groups = _make_security_group_list(context,<EOL>security_groups)<EOL>quota.QUOTAS.limit_check(context, context.tenant_id,<EOL>security_groups_per_port=len(group_ids))<EOL>addresses = []<EOL>backend_port = None<EOL>with utils.CommandManager().execute() as cmd_mgr:<EOL><INDENT>@cmd_mgr.do<EOL>def _allocate_ips(fixed_ips, net, port_id, segment_id, mac,<EOL>**kwargs):<EOL><INDENT>if fixed_ips:<EOL><INDENT>if (STRATEGY.is_provider_network(net_id) and<EOL>not context.is_admin):<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>ips, subnets = split_and_validate_requested_subnets(context,<EOL>net_id,<EOL>segment_id,<EOL>fixed_ips)<EOL>kwargs["<STR_LIT>"] = ips<EOL>kwargs["<STR_LIT>"] = subnets<EOL><DEDENT>ipam_driver.allocate_ip_address(<EOL>context, addresses, net["<STR_LIT:id>"], port_id,<EOL>CONF.QUARK.ipam_reuse_after, segment_id=segment_id,<EOL>mac_address=mac, **kwargs)<EOL><DEDENT>@cmd_mgr.undo<EOL>def _allocate_ips_undo(addr, **kwargs):<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>if addresses:<EOL><INDENT>for address in addresses:<EOL><INDENT>try:<EOL><INDENT>with context.session.begin():<EOL><INDENT>ipam_driver.deallocate_ip_address(context, address,<EOL>**kwargs)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>LOG.exception("<STR_LIT>" % address)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>@cmd_mgr.do<EOL>def _allocate_mac(net, port_id, mac_address,<EOL>use_forbidden_mac_range=False,<EOL>**kwargs):<EOL><INDENT>mac = ipam_driver.allocate_mac_address(<EOL>context, net["<STR_LIT:id>"], port_id, CONF.QUARK.ipam_reuse_after,<EOL>mac_address=mac_address,<EOL>use_forbidden_mac_range=use_forbidden_mac_range, **kwargs)<EOL>return mac<EOL><DEDENT>@cmd_mgr.undo<EOL>def _allocate_mac_undo(mac, **kwargs):<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>if mac:<EOL><INDENT>try:<EOL><INDENT>with context.session.begin():<EOL><INDENT>ipam_driver.deallocate_mac_address(context,<EOL>mac["<STR_LIT:address>"])<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>LOG.exception("<STR_LIT>" % mac)<EOL><DEDENT><DEDENT><DEDENT>@cmd_mgr.do<EOL>def _allocate_backend_port(mac, addresses, net, port_id, **kwargs):<EOL><INDENT>backend_port = net_driver.create_port(<EOL>context, net["<STR_LIT:id>"],<EOL>port_id=port_id,<EOL>security_groups=group_ids,<EOL>device_id=device_id,<EOL>instance_node_id=instance_node_id,<EOL>mac_address=mac,<EOL>addresses=addresses,<EOL>base_net_driver=base_net_driver)<EOL>_filter_backend_port(backend_port)<EOL>return backend_port<EOL><DEDENT>@cmd_mgr.undo<EOL>def _allocate_back_port_undo(backend_port,<EOL>**kwargs):<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>try:<EOL><INDENT>backend_port_uuid = None<EOL>if backend_port:<EOL><INDENT>backend_port_uuid = backend_port.get("<STR_LIT>")<EOL><DEDENT>net_driver.delete_port(context, backend_port_uuid)<EOL><DEDENT>except Exception:<EOL><INDENT>LOG.exception(<EOL>"<STR_LIT>" % backend_port)<EOL><DEDENT><DEDENT>@cmd_mgr.do<EOL>def _allocate_db_port(port_attrs, backend_port, addresses, mac,<EOL>**kwargs):<EOL><INDENT>port_attrs["<STR_LIT>"] = net["<STR_LIT:id>"]<EOL>port_attrs["<STR_LIT:id>"] = port_id<EOL>port_attrs["<STR_LIT>"] = security_groups<EOL>LOG.info("<STR_LIT>" % backend_port)<EOL>port_attrs.update(backend_port)<EOL>with context.session.begin():<EOL><INDENT>new_port = db_api.port_create(<EOL>context, addresses=addresses, mac_address=mac["<STR_LIT:address>"],<EOL>backend_key=backend_port["<STR_LIT>"], **port_attrs)<EOL><DEDENT>return new_port<EOL><DEDENT>@cmd_mgr.undo<EOL>def _allocate_db_port_undo(new_port,<EOL>**kwargs):<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>if not new_port:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>with context.session.begin():<EOL><INDENT>db_api.port_delete(context, new_port)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>LOG.exception(<EOL>"<STR_LIT>" % backend_port)<EOL><DEDENT><DEDENT>mac = _allocate_mac(net, port_id, mac_address,<EOL>use_forbidden_mac_range=use_forbidden_mac_range)<EOL>_allocate_ips(fixed_ips, net, port_id, segment_id, mac)<EOL>backend_port = _allocate_backend_port(mac, addresses, net, port_id)<EOL>new_port = _allocate_db_port(port_attrs, backend_port, addresses, mac)<EOL><DEDENT>return v._make_port_dict(new_port)<EOL>

Create a port

    Create a port which is a connection point of a device (e.g., a VM
    NIC) to attach to a L2 Neutron network.
    : param context: neutron api request context
    : param port: dictionary describing the port, with keys
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.  All keys will be populated.


@utils.exc_wrapper(internal=True)<EOL>def update_port(context, id, port):

LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>port_db = db_api.port_find(context, id=id, scope=db_api.ONE)<EOL>if not port_db:<EOL><INDENT>raise n_exc.PortNotFound(port_id=id)<EOL><DEDENT>port_dict = port["<STR_LIT:port>"]<EOL>fixed_ips = port_dict.pop("<STR_LIT>", None)<EOL>admin_only = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>always_filter = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>utils.filter_body(context, port_dict, admin_only=admin_only,<EOL>always_filter=always_filter)<EOL>if fixed_ips:<EOL><INDENT>quota.QUOTAS.limit_check(context, context.tenant_id,<EOL>fixed_ips_per_port=len(fixed_ips))<EOL><DEDENT>new_security_groups = utils.pop_param(port_dict, "<STR_LIT>")<EOL>if new_security_groups is not None:<EOL><INDENT>if (Capabilities.TENANT_NETWORK_SG not in<EOL>CONF.QUARK.environment_capabilities):<EOL><INDENT>if not STRATEGY.is_provider_network(port_db["<STR_LIT>"]):<EOL><INDENT>raise q_exc.TenantNetworkSecurityGroupRulesNotEnabled()<EOL><DEDENT><DEDENT><DEDENT>if new_security_groups is not None and not port_db["<STR_LIT>"]:<EOL><INDENT>raise q_exc.SecurityGroupsRequireDevice()<EOL><DEDENT>group_ids, security_group_mods = _make_security_group_list(<EOL>context, new_security_groups)<EOL>quota.QUOTAS.limit_check(context, context.tenant_id,<EOL>security_groups_per_port=len(group_ids))<EOL>if fixed_ips is not None:<EOL><INDENT>ipam_driver = ipam.IPAM_REGISTRY.get_strategy(<EOL>ipam.QuarkIpamANY.get_name())<EOL>addresses, subnet_ids = [], []<EOL>ip_addresses = {}<EOL>for fixed_ip in fixed_ips:<EOL><INDENT>subnet_id = fixed_ip.get("<STR_LIT>")<EOL>ip_address = fixed_ip.get("<STR_LIT>")<EOL>if not (subnet_id or ip_address):<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>if ip_address and not subnet_id:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>if subnet_id and ip_address:<EOL><INDENT>ip_netaddr = None<EOL>try:<EOL><INDENT>ip_netaddr = netaddr.IPAddress(ip_address).ipv6()<EOL><DEDENT>except netaddr.AddrFormatError:<EOL><INDENT>raise n_exc.InvalidInput(<EOL>error_message="<STR_LIT>")<EOL><DEDENT>ip_addresses[ip_netaddr] = subnet_id<EOL><DEDENT>else:<EOL><INDENT>subnet_ids.append(subnet_id)<EOL><DEDENT><DEDENT>port_ips = set([netaddr.IPAddress(int(a["<STR_LIT:address>"]))<EOL>for a in port_db["<STR_LIT>"]])<EOL>new_ips = set([a for a in ip_addresses.keys()])<EOL>ips_to_allocate = list(new_ips - port_ips)<EOL>ips_to_deallocate = list(port_ips - new_ips)<EOL>for ip in ips_to_allocate:<EOL><INDENT>if ip in ip_addresses:<EOL><INDENT>allocated = []<EOL>ipam_driver.allocate_ip_address(<EOL>context, allocated, port_db["<STR_LIT>"],<EOL>port_db["<STR_LIT:id>"], reuse_after=None, ip_addresses=[ip],<EOL>subnets=[ip_addresses[ip]])<EOL>addresses.extend(allocated)<EOL><DEDENT><DEDENT>for ip in ips_to_deallocate:<EOL><INDENT>ipam_driver.deallocate_ips_by_port(<EOL>context, port_db, ip_address=ip)<EOL><DEDENT>for subnet_id in subnet_ids:<EOL><INDENT>ipam_driver.allocate_ip_address(<EOL>context, addresses, port_db["<STR_LIT>"], port_db["<STR_LIT:id>"],<EOL>reuse_after=CONF.QUARK.ipam_reuse_after,<EOL>subnets=[subnet_id])<EOL><DEDENT>if addresses:<EOL><INDENT>port_dict["<STR_LIT>"] = port_db["<STR_LIT>"]<EOL>port_dict["<STR_LIT>"].extend(addresses)<EOL><DEDENT><DEDENT>net_driver = _get_net_driver(port_db.network, port=port_db)<EOL>base_net_driver = _get_net_driver(port_db.network)<EOL>kwargs = {}<EOL>if new_security_groups is not None:<EOL><INDENT>kwargs["<STR_LIT>"] = security_group_mods<EOL><DEDENT>net_driver.update_port(context, port_id=port_db["<STR_LIT>"],<EOL>mac_address=port_db["<STR_LIT>"],<EOL>device_id=port_db["<STR_LIT>"],<EOL>base_net_driver=base_net_driver,<EOL>**kwargs)<EOL>port_dict["<STR_LIT>"] = security_group_mods<EOL>with context.session.begin():<EOL><INDENT>port = db_api.port_update(context, port_db, **port_dict)<EOL><DEDENT>if port_db in context.session:<EOL><INDENT>context.session.expunge(port_db)<EOL><DEDENT>port_db = db_api.port_find(context, id=id, scope=db_api.ONE)<EOL>return v._make_port_dict(port_db)<EOL>

Update values of a port.

    : param context: neutron api request context
    : param id: UUID representing the port to update.
    : param port: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.


@utils.exc_wrapper(internal=True)<EOL>def get_port(context, id, fields=None):

LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id, fields))<EOL>results = db_api.port_find(context, id=id, fields=fields,<EOL>scope=db_api.ONE)<EOL>if not results:<EOL><INDENT>raise n_exc.PortNotFound(port_id=id)<EOL><DEDENT>return v._make_port_dict(results)<EOL>

Retrieve a port.

    : param context: neutron api request context
    : param id: UUID representing the port to fetch.
    : param fields: a list of strings that are valid keys in a
        port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


@utils.exc_wrapper(internal=True)<EOL>def get_ports(context, limit=None, sorts=['<STR_LIT:id>'], marker=None,<EOL>page_reverse=False, filters=None, fields=None):

LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters, fields))<EOL>if filters is None:<EOL><INDENT>filters = {}<EOL><DEDENT>if "<STR_LIT>" in filters:<EOL><INDENT>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>ips = []<EOL>try:<EOL><INDENT>ips = [netaddr.IPAddress(ip) for ip in filters.pop("<STR_LIT>")]<EOL><DEDENT>except netaddr.AddrFormatError:<EOL><INDENT>raise n_exc.InvalidInput(<EOL>error_message="<STR_LIT>")<EOL><DEDENT>query = db_api.port_find_by_ip_address(context, ip_address=ips,<EOL>scope=db_api.ALL, **filters)<EOL>ports = []<EOL>for ip in query:<EOL><INDENT>ports.extend(ip.ports)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ports = db_api.port_find(context, limit, sorts, marker,<EOL>fields=fields, join_security_groups=True,<EOL>**filters)<EOL><DEDENT>return v._make_ports_list(ports, fields)<EOL>

Retrieve a list of ports.

    The contents of the list depends on the identity of the user
    making the request (as indicated by the context) as well as any
    filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a port as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.
    : param fields: a list of strings that are valid keys in a
        port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters))<EOL>return db_api.port_count_all(context, join_security_groups=True, **filters)<EOL>

Return the number of ports.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a port as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>port = db_api.port_find(context, id=id, scope=db_api.ONE)<EOL>if not port:<EOL><INDENT>raise n_exc.PortNotFound(port_id=id)<EOL><DEDENT>if '<STR_LIT>' in port:  <EOL><INDENT>LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id, port['<STR_LIT>']))<EOL><DEDENT>backend_key = port["<STR_LIT>"]<EOL>mac_address = netaddr.EUI(port["<STR_LIT>"]).value<EOL>ipam_driver = _get_ipam_driver(port["<STR_LIT>"], port=port)<EOL>ipam_driver.deallocate_mac_address(context, mac_address)<EOL>ipam_driver.deallocate_ips_by_port(<EOL>context, port, ipam_reuse_after=CONF.QUARK.ipam_reuse_after)<EOL>net_driver = _get_net_driver(port["<STR_LIT>"], port=port)<EOL>base_net_driver = _get_net_driver(port["<STR_LIT>"])<EOL>net_driver.delete_port(context, backend_key, device_id=port["<STR_LIT>"],<EOL>mac_address=port["<STR_LIT>"],<EOL>base_net_driver=base_net_driver)<EOL>with context.session.begin():<EOL><INDENT>db_api.port_delete(context, port)<EOL><DEDENT>

Delete a port.

    : param context: neutron api request context
    : param id: UUID representing the port to delete.


return '<STR_LIT>'<EOL>

This function exists to mock and for future requirements if needed.


def update_ip_address(context, id, ip_address):

LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>ports = []<EOL>if '<STR_LIT>' not in ip_address:<EOL><INDENT>raise n_exc.BadRequest(resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>with context.session.begin():<EOL><INDENT>db_address = db_api.ip_address_find(context, id=id, scope=db_api.ONE)<EOL>if not db_address:<EOL><INDENT>raise q_exc.IpAddressNotFound(addr_id=id)<EOL><DEDENT>iptype = db_address.address_type<EOL>if iptype == ip_types.FIXED and not CONF.QUARK.ipaddr_allow_fixed_ip:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>reset = ip_address['<STR_LIT>'].get('<STR_LIT>', False)<EOL>if reset and db_address['<STR_LIT>'] == <NUM_LIT:1>:<EOL><INDENT>if context.is_admin:<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>db_address['<STR_LIT>'] = _get_deallocated_override()<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise webob.exc.HTTPForbidden(detail=msg)<EOL><DEDENT><DEDENT>port_ids = ip_address['<STR_LIT>'].get('<STR_LIT>', None)<EOL>if port_ids is not None and not port_ids:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>if iptype == ip_types.SHARED:<EOL><INDENT>has_owner = db_address.has_any_shared_owner()<EOL><DEDENT>if port_ids:<EOL><INDENT>if iptype == ip_types.FIXED and len(port_ids) > <NUM_LIT:1>:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>_raise_if_shared_and_enabled(ip_address, db_address)<EOL>ports = db_api.port_find(context, tenant_id=context.tenant_id,<EOL>id=port_ids, scope=db_api.ALL)<EOL>if len(ports) != len(port_ids):<EOL><INDENT>raise n_exc.PortNotFound(port_id=port_ids)<EOL><DEDENT>validate_and_fetch_segment(ports, db_address["<STR_LIT>"])<EOL>validate_port_ip_quotas(context, db_address.network_id, ports)<EOL>if iptype == ip_types.SHARED and has_owner:<EOL><INDENT>for assoc in db_address.associations:<EOL><INDENT>pid = assoc.port_id<EOL>if pid not in port_ids and '<STR_LIT:none>' != assoc.service:<EOL><INDENT>raise q_exc.PortRequiresDisassociation()<EOL><DEDENT><DEDENT><DEDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>" % (db_address.address_readable,<EOL>[p.id for p in ports]))<EOL>new_address = db_api.update_port_associations_for_ip(context,<EOL>ports,<EOL>db_address)<EOL><DEDENT>elif iptype == ip_types.SHARED and has_owner:<EOL><INDENT>raise q_exc.PortRequiresDisassociation()<EOL><DEDENT>elif '<STR_LIT>' in ip_address['<STR_LIT>']and context.is_admin:<EOL><INDENT>if len(db_address.associations) != <NUM_LIT:0>:<EOL><INDENT>exc_msg = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (db_address['<STR_LIT>'],<EOL>db_address.associations))<EOL>raise q_exc.ActionNotAuthorized(msg=exc_msg)<EOL><DEDENT>if ip_address['<STR_LIT>']['<STR_LIT>'] == '<STR_LIT:False>':<EOL><INDENT>db_address['<STR_LIT>'] = False<EOL><DEDENT>else:<EOL><INDENT>db_address['<STR_LIT>'] = True<EOL><DEDENT>return v._make_ip_dict(db_address, context.is_admin)<EOL><DEDENT>else:<EOL><INDENT>ipam_driver.deallocate_ip_address(context, db_address)<EOL>return v._make_ip_dict(db_address, context.is_admin)<EOL><DEDENT><DEDENT>return v._make_ip_dict(new_address, context.is_admin)<EOL>

Due to NCP-1592 ensure that address_type cannot change after update.


LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>ip_address = db_api.ip_address_find(<EOL>context, id=id, scope=db_api.ONE)<EOL>if not ip_address or ip_address.deallocated:<EOL><INDENT>raise q_exc.IpAddressNotFound(addr_id=id)<EOL><DEDENT>iptype = ip_address.address_type<EOL>if iptype == ip_types.FIXED and not CONF.QUARK.ipaddr_allow_fixed_ip:<EOL><INDENT>raise n_exc.BadRequest(<EOL>resource="<STR_LIT>",<EOL>msg="<STR_LIT>")<EOL><DEDENT>if ip_address.has_any_shared_owner():<EOL><INDENT>raise q_exc.PortRequiresDisassociation()<EOL><DEDENT>db_api.update_port_associations_for_ip(context, [], ip_address)<EOL>ipam_driver.deallocate_ip_address(context, ip_address)<EOL><DEDENT>

Delete an ip address.

    : param context: neutron api request context
    : param id: UUID representing the ip address to delete.


def get_ports_for_ip_address(context, ip_id, limit=None, sorts=['<STR_LIT:id>'],<EOL>marker=None, page_reverse=False, filters=None,<EOL>fields=None):

LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters, fields))<EOL>addr = db_api.ip_address_find(context, id=ip_id, scope=db_api.ONE)<EOL>if not addr:<EOL><INDENT>raise q_exc.IpAddressNotFound(addr_id=ip_id)<EOL><DEDENT>if filters is None:<EOL><INDENT>filters = {}<EOL><DEDENT>filters['<STR_LIT>'] = [ip_id]<EOL>ports = db_api.port_find(context, limit, sorts, marker,<EOL>fields=fields, join_security_groups=True,<EOL>**filters)<EOL>return v._make_ip_ports_list(addr, ports, fields)<EOL>


def get_port_for_ip_address(context, ip_id, id, fields=None):

LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id, fields))<EOL>addr = db_api.ip_address_find(context, id=ip_id, scope=db_api.ONE)<EOL>if not addr:<EOL><INDENT>raise q_exc.IpAddressNotFound(addr_id=ip_id)<EOL><DEDENT>filters = {'<STR_LIT>': [ip_id]}<EOL>results = db_api.port_find(context, id=id, fields=fields,<EOL>scope=db_api.ONE, **filters)<EOL>if not results:<EOL><INDENT>raise n_exc.PortNotFound(port_id=id)<EOL><DEDENT>return v._make_port_for_ip_dict(addr, results)<EOL>


def update_port_for_ip_address(context, ip_id, id, port):

LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>sanitize_list = ['<STR_LIT>']<EOL>with context.session.begin():<EOL><INDENT>addr = db_api.ip_address_find(context, id=ip_id, scope=db_api.ONE)<EOL>if not addr:<EOL><INDENT>raise q_exc.IpAddressNotFound(addr_id=ip_id)<EOL><DEDENT>port_db = db_api.port_find(context, id=id, scope=db_api.ONE)<EOL>if not port_db:<EOL><INDENT>raise q_exc.PortNotFound(port_id=id)<EOL><DEDENT>port_dict = {k: port['<STR_LIT:port>'][k] for k in sanitize_list}<EOL>require_da = False<EOL>service = port_dict.get('<STR_LIT>')<EOL>if require_da and _shared_ip_and_active(addr, except_port=id):<EOL><INDENT>raise q_exc.PortRequiresDisassociation()<EOL><DEDENT>addr.set_service_for_port(port_db, service)<EOL>context.session.add(addr)<EOL><DEDENT>return v._make_port_for_ip_dict(addr, port_db)<EOL>

Update values of a port.

    : param context: neutron api request context
    : param ip_id: UUID representing the ip associated with port to update
    : param id: UUID representing the port to update.
    : param port: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.


db_job = db_api.async_transaction_find(<EOL>context, id=job_id, scope=db_api.ONE)<EOL>if not db_job:<EOL><INDENT>return<EOL><DEDENT>context.async_job = {"<STR_LIT>": v._make_job_dict(db_job)}<EOL>

Adds job to neutron context for use later.


LOG.info("<STR_LIT>" % context.tenant_id)<EOL>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>job = body.get('<STR_LIT>')<EOL>if '<STR_LIT>' in job:<EOL><INDENT>parent_id = job['<STR_LIT>']<EOL>if not parent_id:<EOL><INDENT>raise q_exc.JobNotFound(job_id=parent_id)<EOL><DEDENT>parent_job = db_api.async_transaction_find(<EOL>context, id=parent_id, scope=db_api.ONE)<EOL>if not parent_job:<EOL><INDENT>raise q_exc.JobNotFound(job_id=parent_id)<EOL><DEDENT>tid = parent_id<EOL>if parent_job.get('<STR_LIT>'):<EOL><INDENT>tid = parent_job.get('<STR_LIT>')<EOL><DEDENT>job['<STR_LIT>'] = tid<EOL><DEDENT>if not job:<EOL><INDENT>raise n_exc.BadRequest(resource="<STR_LIT>", msg="<STR_LIT>")<EOL><DEDENT>with context.session.begin(subtransactions=True):<EOL><INDENT>new_job = db_api.async_transaction_create(context, **job)<EOL><DEDENT>return v._make_job_dict(new_job)<EOL>

Creates a job with support for subjobs.

    If parent_id is not in the body:
    * the job is considered a parent job
    * it will have a NULL transaction id
    * its transaction id == its id
    * all subjobs will use its transaction id as theirs

    Else:
    * the job is a sub job
    * the parent id is the id passed in
    * the transaction id is the root of the job tree


LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>with context.session.begin():<EOL><INDENT>job = db_api.async_transaction_find(context, id=id, scope=db_api.ONE,<EOL>**filters)<EOL>if not job:<EOL><INDENT>raise q_exc.JobNotFound(job_id=id)<EOL><DEDENT>db_api.async_transaction_delete(context, job)<EOL><DEDENT>


LOG.info("<STR_LIT>" %<EOL>(sa_id, context.tenant_id))<EOL>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>with context.session.begin():<EOL><INDENT>sa_range = db_api.segment_allocation_range_find(<EOL>context, id=sa_id, scope=db_api.ONE)<EOL>if not sa_range:<EOL><INDENT>raise q_exc.SegmentAllocationRangeNotFound(<EOL>segment_allocation_range_id=sa_id)<EOL><DEDENT>_delete_segment_allocation_range(context, sa_range)<EOL><DEDENT>

Delete a segment_allocation_range.

    : param context: neutron api request context
    : param id: UUID representing the segment_allocation_range to delete.


LOG.info("<STR_LIT>" % context.tenant_id)<EOL>with context.session.begin():<EOL><INDENT>net_attrs = network["<STR_LIT>"]<EOL>subs = net_attrs.pop("<STR_LIT>", [])<EOL>if not context.is_admin:<EOL><INDENT>if len(subs) > <NUM_LIT:0>:<EOL><INDENT>v4_count, v6_count = <NUM_LIT:0>, <NUM_LIT:0><EOL>for s in subs:<EOL><INDENT>version = netaddr.IPNetwork(s['<STR_LIT>']['<STR_LIT>']).version<EOL>if version == <NUM_LIT:6>:<EOL><INDENT>v6_count += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>v4_count += <NUM_LIT:1><EOL><DEDENT><DEDENT>if v4_count > <NUM_LIT:0>:<EOL><INDENT>tenant_q_v4 = context.session.query(qdv.Quota).filter_by(<EOL>tenant_id=context.tenant_id,<EOL>resource='<STR_LIT>').first()<EOL>if tenant_q_v4 != -<NUM_LIT:1>:<EOL><INDENT>quota.QUOTAS.limit_check(<EOL>context,<EOL>context.tenant_id,<EOL>v4_subnets_per_network=v4_count)<EOL><DEDENT><DEDENT>if v6_count > <NUM_LIT:0>:<EOL><INDENT>tenant_q_v6 = context.session.query(qdv.Quota).filter_by(<EOL>tenant_id=context.tenant_id,<EOL>resource='<STR_LIT>').first()<EOL>if tenant_q_v6 != -<NUM_LIT:1>:<EOL><INDENT>quota.QUOTAS.limit_check(<EOL>context,<EOL>context.tenant_id,<EOL>v6_subnets_per_network=v6_count)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>net_uuid = utils.pop_param(net_attrs, "<STR_LIT:id>", None)<EOL>net_type = None<EOL>if net_uuid and context.is_admin:<EOL><INDENT>net = db_api.network_find(context=context, limit=None,<EOL>sorts=['<STR_LIT:id>'], marker=None,<EOL>page_reverse=False, id=net_uuid,<EOL>scope=db_api.ONE)<EOL>net_type = utils.pop_param(net_attrs, "<STR_LIT>", None)<EOL>if net:<EOL><INDENT>raise q_exc.NetworkAlreadyExists(id=net_uuid)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>net_uuid = uuidutils.generate_uuid()<EOL><DEDENT>pnet_type, phys_net, seg_id = _adapt_provider_nets(context, network)<EOL>ipam_strategy = utils.pop_param(net_attrs, "<STR_LIT>", None)<EOL>if not ipam_strategy or not context.is_admin:<EOL><INDENT>ipam_strategy = CONF.QUARK.default_ipam_strategy<EOL><DEDENT>if not ipam.IPAM_REGISTRY.is_valid_strategy(ipam_strategy):<EOL><INDENT>raise q_exc.InvalidIpamStrategy(strat=ipam_strategy)<EOL><DEDENT>net_attrs["<STR_LIT>"] = ipam_strategy<EOL>default_net_type = net_type or CONF.QUARK.default_network_type<EOL>net_driver = registry.DRIVER_REGISTRY.get_driver(default_net_type)<EOL>net_driver.create_network(context, net_attrs["<STR_LIT:name>"],<EOL>network_id=net_uuid, phys_type=pnet_type,<EOL>phys_net=phys_net, segment_id=seg_id)<EOL>net_attrs["<STR_LIT:id>"] = net_uuid<EOL>net_attrs["<STR_LIT>"] = context.tenant_id<EOL>net_attrs["<STR_LIT>"] = default_net_type<EOL>new_net = db_api.network_create(context, **net_attrs)<EOL>new_subnets = []<EOL>for sub in subs:<EOL><INDENT>sub["<STR_LIT>"]["<STR_LIT>"] = new_net["<STR_LIT:id>"]<EOL>sub["<STR_LIT>"]["<STR_LIT>"] = context.tenant_id<EOL>s = db_api.subnet_create(context, **sub["<STR_LIT>"])<EOL>new_subnets.append(s)<EOL><DEDENT>new_net["<STR_LIT>"] = new_subnets<EOL><DEDENT>return v._make_network_dict(new_net)<EOL>

Create a network.

    Create a network which represents an L2 network segment which
    can have a set of subnets and ports associated with it.
    : param context: neutron api request context
    : param network: dictionary describing the network, with keys
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.  All keys will be populated.


def update_network(context, id, network):

LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>net = db_api.network_find(context, id=id, scope=db_api.ONE)<EOL>if not net:<EOL><INDENT>raise n_exc.NetworkNotFound(net_id=id)<EOL><DEDENT>net_dict = network["<STR_LIT>"]<EOL>utils.pop_param(net_dict, "<STR_LIT>")<EOL>if not context.is_admin and "<STR_LIT>" in net_dict:<EOL><INDENT>utils.pop_param(net_dict, "<STR_LIT>")<EOL><DEDENT>net = db_api.network_update(context, net, **net_dict)<EOL><DEDENT>return v._make_network_dict(net)<EOL>

Update values of a network.

    : param context: neutron api request context
    : param id: UUID representing the network to update.
    : param network: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.


def get_network(context, id, fields=None):

LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id, fields))<EOL>network = db_api.network_find(context=context, limit=None, sorts=['<STR_LIT:id>'],<EOL>marker=None, page_reverse=False,<EOL>id=id, join_subnets=True, scope=db_api.ONE)<EOL>if not network:<EOL><INDENT>raise n_exc.NetworkNotFound(net_id=id)<EOL><DEDENT>return v._make_network_dict(network, fields=fields)<EOL>

Retrieve a network.

    : param context: neutron api request context
    : param id: UUID representing the network to fetch.
    : param fields: a list of strings that are valid keys in a
        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


def get_networks(context, limit=None, sorts=['<STR_LIT:id>'], marker=None,<EOL>page_reverse=False, filters=None, fields=None):

LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters, fields))<EOL>filters = filters or {}<EOL>nets = db_api.network_find(context, limit, sorts, marker, page_reverse,<EOL>join_subnets=True, **filters) or []<EOL>nets = [v._make_network_dict(net, fields=fields) for net in nets]<EOL>return nets<EOL>

Retrieve a list of networks.

    The contents of the list depends on the identity of the user
    making the request (as indicated by the context) as well as any
    filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.
    : param fields: a list of strings that are valid keys in a
        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


LOG.info("<STR_LIT>" %<EOL>(context.tenant_id, filters))<EOL>return db_api.network_count_all(context)<EOL>

Return the number of networks.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


LOG.info("<STR_LIT>" % (id, context.tenant_id))<EOL>with context.session.begin():<EOL><INDENT>net = db_api.network_find(context=context, limit=None, sorts=['<STR_LIT:id>'],<EOL>marker=None, page_reverse=False, id=id,<EOL>scope=db_api.ONE)<EOL>if not net:<EOL><INDENT>raise n_exc.NetworkNotFound(net_id=id)<EOL><DEDENT>if not context.is_admin:<EOL><INDENT>if STRATEGY.is_provider_network(net.id):<EOL><INDENT>raise n_exc.NotAuthorized(net_id=id)<EOL><DEDENT><DEDENT>if net.ports:<EOL><INDENT>raise n_exc.NetworkInUse(net_id=id)<EOL><DEDENT>net_driver = registry.DRIVER_REGISTRY.get_driver(net["<STR_LIT>"])<EOL>net_driver.delete_network(context, id)<EOL>for subnet in net["<STR_LIT>"]:<EOL><INDENT>subnets._delete_subnet(context, subnet)<EOL><DEDENT>db_api.network_delete(context, net)<EOL><DEDENT>

Delete a network.

    : param context: neutron api request context
    : param id: UUID representing the network to delete.


def get_mac_address_range(context, id, fields=None):

LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id, fields))<EOL>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>mac_address_range = db_api.mac_address_range_find(<EOL>context, id=id, scope=db_api.ONE)<EOL>if not mac_address_range:<EOL><INDENT>raise q_exc.MacAddressRangeNotFound(<EOL>mac_address_range_id=id)<EOL><DEDENT>return v._make_mac_range_dict(mac_address_range)<EOL>

Retrieve a mac_address_range.

    : param context: neutron api request context
    : param id: UUID representing the network to fetch.
    : param fields: a list of strings that are valid keys in a
        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


LOG.info("<STR_LIT>" %<EOL>(id, context.tenant_id))<EOL>if not context.is_admin:<EOL><INDENT>raise n_exc.NotAuthorized()<EOL><DEDENT>with context.session.begin():<EOL><INDENT>mar = db_api.mac_address_range_find(context, id=id, scope=db_api.ONE)<EOL>if not mar:<EOL><INDENT>raise q_exc.MacAddressRangeNotFound(<EOL>mac_address_range_id=id)<EOL><DEDENT>_delete_mac_address_range(context, mar)<EOL><DEDENT>

Delete a mac_address_range.

    : param context: neutron api request context
    : param id: UUID representing the mac_address_range to delete.


plugin = directory.get_plugin()<EOL>controller = IPPoliciesController(plugin)<EOL>return [extensions.ResourceExtension(Ip_policies.get_alias(),<EOL>controller)]<EOL>


plugin = directory.get_plugin()<EOL>controller = IPAvailabilityController(plugin)<EOL>return [extensions.ResourceExtension(Ip_availability.get_alias(),<EOL>controller)]<EOL>


ip_controller = IpAddressesController(<EOL>directory.get_plugin())<EOL>ip_port_controller = IpAddressPortController(<EOL>directory.get_plugin())<EOL>resources = []<EOL>resources.append(extensions.ResourceExtension(<EOL>Ip_addresses.get_alias(),<EOL>ip_controller))<EOL>parent = {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>resources.append(extensions.ResourceExtension(<EOL>'<STR_LIT>', ip_port_controller, parent=parent))<EOL>return resources<EOL>


job_controller = JobsController(<EOL>directory.get_plugin())<EOL>resources = []<EOL>resources.append(extensions.ResourceExtension(<EOL>Jobs.get_alias(),<EOL>job_controller))<EOL>return resources<EOL>


plugin = directory.get_plugin()<EOL>controller = SegmentAllocationRangesController(plugin)<EOL>return [extensions.ResourceExtension(<EOL>Segment_allocation_ranges.get_alias(),<EOL>controller)]<EOL>


plural_mappings = resource_helper.build_plural_mappings(<EOL>{}, RESOURCE_ATTRIBUTE_MAP)<EOL>return resource_helper.build_resource_info(plural_mappings,<EOL>RESOURCE_ATTRIBUTE_MAP,<EOL>None,<EOL>register_quota=True)<EOL>


controller = RoutesController(directory.get_plugin())<EOL>return [extensions.ResourceExtension(<EOL>Routes.get_alias(),<EOL>controller)]<EOL>


plugin = directory.get_plugin()<EOL>controller = MacAddressRangesController(plugin)<EOL>return [extensions.ResourceExtension(Mac_address_ranges.get_alias(),<EOL>controller)]<EOL>


def _allocate_from_v6_subnet(self, context, net_id, subnet,<EOL>port_id, reuse_after, ip_address=None,<EOL>**kwargs):

LOG.info("<STR_LIT>".format(<EOL>utils.pretty_kwargs(network_id=net_id, subnet=subnet,<EOL>port_id=port_id, ip_address=ip_address)))<EOL>if ip_address:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>" % ip_address)<EOL>return self._allocate_from_subnet(context, net_id=net_id,<EOL>subnet=subnet, port_id=port_id,<EOL>reuse_after=reuse_after,<EOL>ip_address=ip_address, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>mac = kwargs.get("<STR_LIT>")<EOL>if mac:<EOL><INDENT>mac = kwargs["<STR_LIT>"].get("<STR_LIT:address>")<EOL><DEDENT>if subnet and subnet["<STR_LIT>"]:<EOL><INDENT>ip_policy_cidrs = subnet["<STR_LIT>"].get_cidrs_ip_set()<EOL><DEDENT>else:<EOL><INDENT>ip_policy_cidrs = netaddr.IPSet([])<EOL><DEDENT>for tries, ip_address in enumerate(<EOL>generate_v6(mac, port_id, subnet["<STR_LIT>"])):<EOL><INDENT>LOG.info("<STR_LIT>".format(<EOL>tries + <NUM_LIT:1>, CONF.QUARK.v6_allocation_attempts))<EOL>if tries > CONF.QUARK.v6_allocation_attempts - <NUM_LIT:1>:<EOL><INDENT>LOG.info("<STR_LIT>")<EOL>raise ip_address_failure(net_id)<EOL><DEDENT>ip_address = netaddr.IPAddress(ip_address).ipv6()<EOL>LOG.info("<STR_LIT>".format(<EOL>str(ip_address)))<EOL>if (ip_policy_cidrs is not None and<EOL>ip_address in ip_policy_cidrs):<EOL><INDENT>LOG.info("<STR_LIT>".format(<EOL>str(ip_address)))<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>with context.session.begin():<EOL><INDENT>address = db_api.ip_address_create(<EOL>context, address=ip_address,<EOL>subnet_id=subnet["<STR_LIT:id>"],<EOL>version=subnet["<STR_LIT>"], network_id=net_id,<EOL>address_type=kwargs.get('<STR_LIT>',<EOL>ip_types.FIXED))<EOL>return address<EOL><DEDENT><DEDENT>except db_exception.DBDuplicateEntry:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>".format(str(ip_address)))<EOL>LOG.debug("<STR_LIT>"<EOL>"<STR_LIT>", subnet["<STR_LIT:id>"], ip_address)<EOL><DEDENT><DEDENT><DEDENT>

This attempts to allocate v6 addresses as per RFC2462 and RFC3041.

        To accomodate this, we effectively treat all v6 assignment as a
        first time allocation utilizing the MAC address of the VIF. Because
        we recycle MACs, we will eventually attempt to recreate a previously
        generated v6 address. Instead of failing, we've opted to handle
        reallocating that address in this method.

        This should provide a performance boost over attempting to check
        each and every subnet in the existing reallocate logic, as we'd
        have to iterate over each and every subnet returned


@wraps(func)<EOL>def wrapped_dec(*args, **kwargs):<EOL><INDENT>if len(args) == <NUM_LIT:1> and len(kwargs) == <NUM_LIT:0> and callable(args[<NUM_LIT:0>]):<EOL><INDENT>return func(args[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>return lambda realf: func(realf, *args, **kwargs)<EOL><DEDENT><DEDENT>return wrapped_dec<EOL>

A decorator to be used on another decorator

    This is done to allow separate handling on the basis of argument values


if '<STR_LIT>' in conf:<EOL><INDENT>conf.set_override('<STR_LIT>', "<STR_LIT::>".join(extensions.__path__))<EOL><DEDENT>

Adds the Quark API Extensions to the extension path.

    Pulled out for test coveage.


def _fix_missing_tenant_id(self, context, body, key):

if not body:<EOL><INDENT>raise n_exc.BadRequest(resource=key,<EOL>msg="<STR_LIT>")<EOL><DEDENT>resource = body.get(key)<EOL>if not resource:<EOL><INDENT>raise n_exc.BadRequest(resource=key,<EOL>msg="<STR_LIT>")<EOL><DEDENT>if context.tenant_id is None:<EOL><INDENT>context.tenant_id = resource.get("<STR_LIT>")<EOL><DEDENT>if context.tenant_id is None:<EOL><INDENT>msg = _("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise n_exc.BadRequest(resource=key, msg=msg)<EOL><DEDENT>

Will add the tenant_id to the context from body.

        It is assumed that the body must have a tenant_id because neutron
        core could never have gotten here otherwise.


for id, net_params in self.strategy.iteritems():<EOL><INDENT>if id == CONF.QUARK.public_net_id:<EOL><INDENT>return id<EOL><DEDENT><DEDENT>return None<EOL>


ip_pools = self._alloc_pools<EOL>subnet_cidr = self._subnet_cidr<EOL>LOG.debug(_("<STR_LIT>"))<EOL>ip_sets = []<EOL>for ip_pool in ip_pools:<EOL><INDENT>try:<EOL><INDENT>start_ip = netaddr.IPAddress(ip_pool['<STR_LIT:start>'])<EOL>end_ip = netaddr.IPAddress(ip_pool['<STR_LIT:end>'])<EOL><DEDENT>except netaddr.AddrFormatError:<EOL><INDENT>LOG.info(_("<STR_LIT>"<EOL>"<STR_LIT>"),<EOL>{'<STR_LIT:start>': ip_pool['<STR_LIT:start>'],<EOL>'<STR_LIT:end>': ip_pool['<STR_LIT:end>']})<EOL>raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)<EOL><DEDENT>if (start_ip.version != self._subnet_cidr.version or<EOL>end_ip.version != self._subnet_cidr.version):<EOL><INDENT>LOG.info(_("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL>raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)<EOL><DEDENT>if end_ip < start_ip:<EOL><INDENT>LOG.info(_("<STR_LIT>"<EOL>"<STR_LIT>"),<EOL>{'<STR_LIT:start>': ip_pool['<STR_LIT:start>'], '<STR_LIT:end>': ip_pool['<STR_LIT:end>']})<EOL>raise n_exc_ext.InvalidAllocationPool(pool=ip_pool)<EOL><DEDENT>if (start_ip < self._subnet_first_ip or<EOL>end_ip > self._subnet_last_ip):<EOL><INDENT>LOG.info(_("<STR_LIT>"<EOL>"<STR_LIT>"),<EOL>{'<STR_LIT:start>': ip_pool['<STR_LIT:start>'],<EOL>'<STR_LIT:end>': ip_pool['<STR_LIT:end>']})<EOL>raise n_exc_ext.OutOfBoundsAllocationPool(<EOL>pool=ip_pool,<EOL>subnet_cidr=subnet_cidr)<EOL><DEDENT>ip_sets.append(netaddr.IPSet(netaddr.IPRange(<EOL>ip_pool['<STR_LIT:start>'],<EOL>ip_pool['<STR_LIT:end>']).cidrs()))<EOL><DEDENT>LOG.debug(_("<STR_LIT>"<EOL>"<STR_LIT>"))<EOL>ip_ranges = ip_pools[:]<EOL>for l_cursor in xrange(len(ip_sets)):<EOL><INDENT>for r_cursor in xrange(l_cursor + <NUM_LIT:1>, len(ip_sets)):<EOL><INDENT>if ip_sets[l_cursor] & ip_sets[r_cursor]:<EOL><INDENT>l_range = ip_ranges[l_cursor]<EOL>r_range = ip_ranges[r_cursor]<EOL>LOG.info(_("<STR_LIT>"<EOL>"<STR_LIT>"),<EOL>{'<STR_LIT>': l_range, '<STR_LIT>': r_range})<EOL>raise n_exc_ext.OverlappingAllocationPools(<EOL>pool_1=l_range,<EOL>pool_2=r_range,<EOL>subnet_cidr=subnet_cidr)<EOL><DEDENT><DEDENT><DEDENT>

Validate IP allocation pools.

        Verify start and end address for each allocation pool are valid,
        ie: constituted by valid and appropriately ordered IP addresses.
        Also, verify pools do not overlap among themselves.
        Finally, verify that each range fall within the subnet's CIDR.


def _lswitch_select_open(self, context, switches=None, **kwargs):

if switches is not None:<EOL><INDENT>for res in switches["<STR_LIT>"]:<EOL><INDENT>count = res["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>if (self.limits['<STR_LIT>'] == <NUM_LIT:0> or<EOL>count < self.limits['<STR_LIT>']):<EOL><INDENT>return res["<STR_LIT>"]<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>

Selects an open lswitch for a network.

        Note that it does not select the most full switch, but merely one with
        ports available.


def _add_default_tz_bindings(self, context, switch, network_id):

default_tz = CONF.NVP.default_tz<EOL>if not default_tz:<EOL><INDENT>LOG.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>if not network_id:<EOL><INDENT>LOG.warn("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>for net_type in CONF.NVP.additional_default_tz_types:<EOL><INDENT>if net_type in TZ_BINDINGS:<EOL><INDENT>binding = TZ_BINDINGS[net_type]<EOL>binding.add(context, switch, default_tz, network_id)<EOL><DEDENT>else:<EOL><INDENT>LOG.warn("<STR_LIT>" % (net_type))<EOL><DEDENT><DEDENT>

Configure any additional default transport zone bindings.


def _remove_default_tz_bindings(self, context, network_id):

default_tz = CONF.NVP.default_tz<EOL>if not default_tz:<EOL><INDENT>LOG.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>if not network_id:<EOL><INDENT>LOG.warn("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT>for net_type in CONF.NVP.additional_default_tz_types:<EOL><INDENT>if net_type in TZ_BINDINGS:<EOL><INDENT>binding = TZ_BINDINGS[net_type]<EOL>binding.remove(context, default_tz, network_id)<EOL><DEDENT>else:<EOL><INDENT>LOG.warn("<STR_LIT>" % (net_type))<EOL><DEDENT><DEDENT>

Deconfigure any additional default transport zone bindings.


def get_lswitch_ids_for_network(self, context, network_id):

lswitches = self._lswitches_for_network(context, network_id).results()<EOL>return [s['<STR_LIT>'] for s in lswitches["<STR_LIT>"]]<EOL>

Public interface for fetching lswitch ids for a given network.

        NOTE(morgabra) This is here because calling private methods
        from outside the class feels wrong, and we need to be able to
        fetch lswitch ids for use in other drivers.


def _lswitch_status_query(self, context, network_id):

pass<EOL>

Child implementation of lswitch_status_query.

        Deliberately empty as we rely on _get_network_details to be more
        efficient than we can be here.


lswitches = self._lswitches_for_network(context, network_id)<EOL>return [s['<STR_LIT>'] for s in lswitches]<EOL>


def select_ipam_strategy(self, network_id, network_strategy, **kwargs):

LOG.info("<STR_LIT>"<EOL>"<STR_LIT>" % (network_id, network_strategy))<EOL>net_type = "<STR_LIT>"<EOL>if STRATEGY.is_provider_network(network_id):<EOL><INDENT>net_type = "<STR_LIT>"<EOL><DEDENT>strategy = self._ipam_strategies.get(net_type, {})<EOL>default = strategy.get("<STR_LIT:default>")<EOL>overrides = strategy.get("<STR_LIT>", {})<EOL>if network_strategy in overrides:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>% (overrides[network_strategy]))<EOL>return overrides[network_strategy]<EOL><DEDENT>if default:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>" % (default))<EOL>return default<EOL><DEDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>" % (network_strategy))<EOL>return network_strategy<EOL>

Return relevant IPAM strategy name.

        :param network_id: neutron network id.
        :param network_strategy: default strategy for the network.

        NOTE(morgabra) This feels like a hack but I can't think of a better
        idea. The root problem is we can now attach ports to networks with
        a different backend driver/ipam strategy than the network speficies.

        We handle the the backend driver part with allowing network_plugin to
        be specified for port objects. This works pretty well because nova or
        whatever knows when we are hooking up an Ironic node so it can pass
        along that key during port_create().

        IPAM is a little trickier, especially in Ironic's case, because we
        *must* use a specific IPAM for provider networks. There isn't really
        much of an option other than involve the backend driver when selecting
        the IPAM strategy.


def _get_base_network_info(self, context, network_id, base_net_driver):

driver_name = base_net_driver.get_name()<EOL>net_info = {"<STR_LIT>": driver_name}<EOL>LOG.debug('<STR_LIT>'<EOL>% (driver_name, network_id))<EOL>if driver_name == '<STR_LIT>':<EOL><INDENT>LOG.debug('<STR_LIT>'<EOL>% (network_id))<EOL>lswitch_ids = base_net_driver.get_lswitch_ids_for_network(<EOL>context, network_id)<EOL>if not lswitch_ids or len(lswitch_ids) > <NUM_LIT:1>:<EOL><INDENT>msg = ('<STR_LIT>'<EOL>% (len(lswitch_ids)))<EOL>LOG.error(msg)<EOL>raise IronicException(msg)<EOL><DEDENT>lswitch_id = lswitch_ids.pop()<EOL>LOG.info('<STR_LIT>'<EOL>% (network_id, lswitch_id))<EOL>net_info['<STR_LIT>'] = lswitch_id<EOL><DEDENT>LOG.debug('<STR_LIT>'<EOL>% (driver_name, network_id, net_info))<EOL>return net_info<EOL>

Return a dict of extra network information.

        :param context: neutron request context.
        :param network_id: neturon network id.
        :param net_driver: network driver associated with network_id.
        :raises IronicException: Any unexpected data fetching failures will
            be logged and IronicException raised.

        This driver can attach to networks managed by other drivers. We may
        need some information from these drivers, or otherwise inform
        downstream about the type of network we are attaching to. We can
        make these decisions here.


def create_port(self, context, network_id, port_id, **kwargs):

LOG.info("<STR_LIT>" % (context.tenant_id, network_id,<EOL>port_id))<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>raise IronicException(msg='<STR_LIT>')<EOL><DEDENT>base_net_driver = kwargs['<STR_LIT>']<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>raise IronicException(msg='<STR_LIT>')<EOL><DEDENT>device_id = kwargs['<STR_LIT>']<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>raise IronicException(msg='<STR_LIT>')<EOL><DEDENT>instance_node_id = kwargs['<STR_LIT>']<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>raise IronicException(msg='<STR_LIT>')<EOL><DEDENT>mac_address = str(netaddr.EUI(kwargs["<STR_LIT>"]["<STR_LIT:address>"]))<EOL>mac_address = mac_address.replace('<STR_LIT:->', '<STR_LIT::>')<EOL>if kwargs.get('<STR_LIT>'):<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise IronicException(msg=msg)<EOL><DEDENT>fixed_ips = []<EOL>addresses = kwargs.get('<STR_LIT>')<EOL>if not isinstance(addresses, list):<EOL><INDENT>addresses = [addresses]<EOL><DEDENT>for address in addresses:<EOL><INDENT>fixed_ips.append(self._make_fixed_ip_dict(context, address))<EOL><DEDENT>body = {<EOL>"<STR_LIT:id>": port_id,<EOL>"<STR_LIT>": network_id,<EOL>"<STR_LIT>": device_id,<EOL>"<STR_LIT>": kwargs.get('<STR_LIT>', '<STR_LIT>'),<EOL>"<STR_LIT>": context.tenant_id or "<STR_LIT>",<EOL>"<STR_LIT>": context.roles,<EOL>"<STR_LIT>": mac_address,<EOL>"<STR_LIT>": fixed_ips,<EOL>"<STR_LIT>": instance_node_id,<EOL>"<STR_LIT>": not STRATEGY.is_provider_network(network_id)<EOL>}<EOL>net_info = self._get_base_network_info(<EOL>context, network_id, base_net_driver)<EOL>body.update(net_info)<EOL>try:<EOL><INDENT>LOG.info("<STR_LIT>" % (body))<EOL>port = self._create_port(context, body)<EOL>LOG.info("<STR_LIT>" % (port))<EOL>return {"<STR_LIT>": port['<STR_LIT:port>']['<STR_LIT:id>'],<EOL>"<STR_LIT>": port['<STR_LIT:port>']['<STR_LIT>']}<EOL><DEDENT>except Exception as e:<EOL><INDENT>msg = "<STR_LIT>" % (e)<EOL>raise IronicException(msg=msg)<EOL><DEDENT>

Create a port.

        :param context: neutron api request context.
        :param network_id: neutron network id.
        :param port_id: neutron port id.
        :param kwargs:
            required keys - device_id: neutron port device_id (instance_id)
                            instance_node_id: nova hypervisor host id
                            mac_address: neutron port mac address
                            base_net_driver: the base network driver
            optional keys - addresses: list of allocated IPAddress models
                            security_groups: list of associated security groups
        :raises IronicException: If the client is unable to create the
            downstream port for any reason, the exception will be logged
            and IronicException raised.


def update_port(self, context, port_id, **kwargs):

LOG.info("<STR_LIT>" % (context.tenant_id, port_id))<EOL>if kwargs.get("<STR_LIT>"):<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise IronicException(msg=msg)<EOL><DEDENT>return {"<STR_LIT>": port_id}<EOL>

Update a port.

        :param context: neutron api request context.
        :param port_id: neutron port id.
        :param kwargs: optional kwargs.
        :raises IronicException: If the client is unable to update the
            downstream port for any reason, the exception will be logged
            and IronicException raised.

        TODO(morgabra) It does not really make sense in the context of Ironic
        to allow updating ports. fixed_ips and mac_address are burned in the
        configdrive on the host, and we otherwise cannot migrate a port between
        instances. Eventually we will need to support security groups, but for
        now it's a no-op on port data changes, and we need to rely on the
        API/Nova to not allow updating data on active ports.


def delete_port(self, context, port_id, **kwargs):

LOG.info("<STR_LIT>" % (context.tenant_id, port_id))<EOL>try:<EOL><INDENT>self._delete_port(context, port_id)<EOL>LOG.info("<STR_LIT>" % (port_id))<EOL><DEDENT>except Exception:<EOL><INDENT>LOG.error("<STR_LIT>"<EOL>"<STR_LIT>" % (port_id))<EOL><DEDENT>

Delete a port.

        :param context: neutron api request context.
        :param port_id: neutron port id.
        :param kwargs: optional kwargs.
        :raises IronicException: If the client is unable to delete the
            downstream port for any reason, the exception will be logged
            and IronicException raised.


def diag_port(self, context, port_id, **kwargs):

LOG.info("<STR_LIT>" % port_id)<EOL>try:<EOL><INDENT>port = self._client.show_port(port_id)<EOL><DEDENT>except Exception as e:<EOL><INDENT>msg = "<STR_LIT>" % (str(e))<EOL>LOG.exception(msg)<EOL>raise IronicException(msg=msg)<EOL><DEDENT>return {"<STR_LIT>": port}<EOL>

Diagnose a port.

        :param context: neutron api request context.
        :param port_id: neutron port id.
        :param kwargs: optional kwargs.
        :raises IronicException: If the client is unable to fetch the
            downstream port for any reason, the exception will be
            logged and IronicException raised.


def create_network(self, *args, **kwargs):

raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>

Create a network.

        :raises NotImplementedError: This driver does not manage networks.

        NOTE: This is a no-op in the base driver, but this raises here as to
        explicitly disallow network operations in case of a misconfiguration.


def delete_network(self, *args, **kwargs):

Delete a network.

        :raises NotImplementedError: This driver does not manage networks.

        NOTE: This is a no-op in the base driver, but this raises here as to
        explicitly disallow network operations in case of a misconfiguration.


def diag_network(self, *args, **kwargs):

Diagnose a network.

        :raises NotImplementedError: This driver does not manage networks.

        NOTE: This is a no-op in the base driver, but this raises here as to
        explicitly disallow network operations in case of a misconfiguration.


def create_security_group(self, context, group_name, **group):

Create a security group.

        :raises NotImplementedError: This driver does not implement security
                                     groups.

        NOTE: Security groups will be supported in the future, but for now
        they are explicitly disallowed.


def delete_security_group(self, context, group_id, **kwargs):

Delete a security group.

        :raises NotImplementedError: This driver does not implement security
                                     groups.

        NOTE: Security groups will be supported in the future, but for now
        they are explicitly disallowed.


def update_security_group(self, context, group_id, **group):

Update a security group.

        :raises NotImplementedError: This driver does not implement security
                                     groups.

        NOTE: Security groups will be supported in the future, but for now
        they are explicitly disallowed.


def create_security_group_rule(self, context, group_id, rule):

Create a security group rule.

        :raises NotImplementedError: This driver does not implement security
                                     groups.

        NOTE: Security groups will be supported in the future, but for now
        they are explicitly disallowed.


def delete_security_group_rule(self, context, group_id, rule):

Delete a security group rule.

        :raises NotImplementedError: This driver does not implement security
                                     groups.

        NOTE: Security groups will be supported in the future, but for now
        they are explicitly disallowed.


def register_floating_ip(self, floating_ip, port_fixed_ips):

url = CONF.QUARK.floating_ip_base_url<EOL>timeout = CONF.QUARK.unicorn_api_timeout_seconds<EOL>req = self._build_request_body(floating_ip, port_fixed_ips)<EOL>try:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>% (url, req))<EOL>r = requests.post(url, data=json.dumps(req), timeout=timeout)<EOL><DEDENT>except Exception as e:<EOL><INDENT>LOG.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (floating_ip.id, e.message))<EOL>raise ex.RegisterFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>if r.status_code != <NUM_LIT:200> and r.status_code != <NUM_LIT>:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>" % (r.status_code, r.json())<EOL>LOG.error("<STR_LIT>" % msg)<EOL>raise ex.RegisterFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>

Register a floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to register
        :param port_fixed_ips: A dictionary containing the port and fixed ips
        to associate the floating IP with.  Has the structure of:
        {"<id of port>": {"port": <quark.db.models.Port>,
         "fixed_ip": "<fixed ip address>"}}
        :return: None


def update_floating_ip(self, floating_ip, port_fixed_ips):

url = "<STR_LIT>" % (CONF.QUARK.floating_ip_base_url,<EOL>floating_ip["<STR_LIT>"])<EOL>timeout = CONF.QUARK.unicorn_api_timeout_seconds<EOL>req = self._build_request_body(floating_ip, port_fixed_ips)<EOL>try:<EOL><INDENT>LOG.info("<STR_LIT>"<EOL>% (url, req))<EOL>r = requests.put(url, data=json.dumps(req), timeout=timeout)<EOL><DEDENT>except Exception as e:<EOL><INDENT>LOG.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (floating_ip.id, e.message))<EOL>raise ex.RegisterFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>if r.status_code != <NUM_LIT:200> and r.status_code != <NUM_LIT>:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>" % (r.status_code, r.json())<EOL>LOG.error("<STR_LIT>" % msg)<EOL>raise ex.RegisterFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>

Update an existing floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to update
        :param port_fixed_ips: A dictionary containing the port and fixed ips
        to associate the floating IP with.  Has the structure of:
        {"<id of port>": {"port": <quark.db.models.Port>,
         "fixed_ip": "<fixed ip address>"}}
        :return: None


url = "<STR_LIT>" % (CONF.QUARK.floating_ip_base_url,<EOL>floating_ip.address_readable)<EOL>timeout = CONF.QUARK.unicorn_api_timeout_seconds<EOL>try:<EOL><INDENT>LOG.info("<STR_LIT>" % url)<EOL>r = requests.delete(url, timeout=timeout)<EOL><DEDENT>except Exception as e:<EOL><INDENT>LOG.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (floating_ip.id, e.message))<EOL>raise ex.RemoveFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>if r.status_code == <NUM_LIT>:<EOL><INDENT>LOG.warn("<STR_LIT>"<EOL>% floating_ip.address_readable)<EOL><DEDENT>elif r.status_code != <NUM_LIT>:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>" % (r.status_code, r.json())<EOL>LOG.error("<STR_LIT>" % msg)<EOL>raise ex.RemoveFloatingIpFailure(id=floating_ip.id)<EOL><DEDENT>

Register a floating ip with Unicorn

        :param floating_ip: The quark.db.models.IPAddress to remove
        :return: None


lat_interval, lon_interval = (-<NUM_LIT>, <NUM_LIT>), (-<NUM_LIT>, <NUM_LIT>)<EOL>lat_err, lon_err = <NUM_LIT>, <NUM_LIT><EOL>is_even = True<EOL>for c in geohash:<EOL><INDENT>cd = __decodemap[c]<EOL>for mask in [<NUM_LIT:16>, <NUM_LIT:8>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:1>]:<EOL><INDENT>if is_even: <EOL><INDENT>lon_err /= <NUM_LIT:2><EOL>if cd & mask:<EOL><INDENT>lon_interval = ((lon_interval[<NUM_LIT:0>]+lon_interval[<NUM_LIT:1>])/<NUM_LIT:2>, lon_interval[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>lon_interval = (lon_interval[<NUM_LIT:0>], (lon_interval[<NUM_LIT:0>]+lon_interval[<NUM_LIT:1>])/<NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:      <EOL><INDENT>lat_err /= <NUM_LIT:2><EOL>if cd & mask:<EOL><INDENT>lat_interval = ((lat_interval[<NUM_LIT:0>]+lat_interval[<NUM_LIT:1>])/<NUM_LIT:2>, lat_interval[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>lat_interval = (lat_interval[<NUM_LIT:0>], (lat_interval[<NUM_LIT:0>]+lat_interval[<NUM_LIT:1>])/<NUM_LIT:2>)<EOL><DEDENT><DEDENT>is_even = not is_even<EOL><DEDENT><DEDENT>lat = (lat_interval[<NUM_LIT:0>] + lat_interval[<NUM_LIT:1>]) / <NUM_LIT:2><EOL>lon = (lon_interval[<NUM_LIT:0>] + lon_interval[<NUM_LIT:1>]) / <NUM_LIT:2><EOL>return lat, lon, lat_err, lon_err<EOL>

Decode the geohash to its exact values, including the error
margins of the result.  Returns four float values: latitude,
longitude, the plus/minus error for latitude (as a positive
number) and the plus/minus error for longitude (as a positive
number).


lat, lon, lat_err, lon_err = decode_exactly(geohash)<EOL>lats = "<STR_LIT>" % (max(<NUM_LIT:1>, int(round(-log10(lat_err)))) - <NUM_LIT:1>, lat)<EOL>lons = "<STR_LIT>" % (max(<NUM_LIT:1>, int(round(-log10(lon_err)))) - <NUM_LIT:1>, lon)<EOL>if '<STR_LIT:.>' in lats: lats = lats.rstrip('<STR_LIT:0>')<EOL>if '<STR_LIT:.>' in lons: lons = lons.rstrip('<STR_LIT:0>')<EOL>return lats, lons<EOL>

Decode geohash, returning two strings with latitude and longitude
containing only relevant digits and with trailing zeroes removed.


def encode(latitude, longitude, precision=<NUM_LIT:12>):

lat_interval, lon_interval = (-<NUM_LIT>, <NUM_LIT>), (-<NUM_LIT>, <NUM_LIT>)<EOL>geohash = []<EOL>bits = [ <NUM_LIT:16>, <NUM_LIT:8>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:1> ]<EOL>bit = <NUM_LIT:0><EOL>ch = <NUM_LIT:0><EOL>even = True<EOL>while len(geohash) < precision:<EOL><INDENT>if even:<EOL><INDENT>mid = (lon_interval[<NUM_LIT:0>] + lon_interval[<NUM_LIT:1>]) / <NUM_LIT:2><EOL>if longitude > mid:<EOL><INDENT>ch |= bits[bit]<EOL>lon_interval = (mid, lon_interval[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>lon_interval = (lon_interval[<NUM_LIT:0>], mid)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mid = (lat_interval[<NUM_LIT:0>] + lat_interval[<NUM_LIT:1>]) / <NUM_LIT:2><EOL>if latitude > mid:<EOL><INDENT>ch |= bits[bit]<EOL>lat_interval = (mid, lat_interval[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>lat_interval = (lat_interval[<NUM_LIT:0>], mid)<EOL><DEDENT><DEDENT>even = not even<EOL>if bit < <NUM_LIT:4>:<EOL><INDENT>bit += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>geohash += __base32[ch]<EOL>bit = <NUM_LIT:0><EOL>ch = <NUM_LIT:0><EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(geohash)<EOL>

Encode a position given in float arguments latitude, longitude to
a geohash which will have the character count precision.


@rate_limited()<EOL>def boto3_cached_conn(service, service_type='<STR_LIT>', future_expiration_minutes=<NUM_LIT:15>, account_number=None,<EOL>assume_role=None, session_name='<STR_LIT>', region='<STR_LIT>', return_credentials=False,<EOL>external_id=None, arn_partition='<STR_LIT>'):

key = (<EOL>account_number,<EOL>assume_role,<EOL>session_name,<EOL>external_id,<EOL>region,<EOL>service_type,<EOL>service,<EOL>arn_partition<EOL>)<EOL>if key in CACHE:<EOL><INDENT>retval = _get_cached_creds(key, service, service_type, region, future_expiration_minutes, return_credentials)<EOL>if retval:<EOL><INDENT>return retval<EOL><DEDENT><DEDENT>role = None<EOL>if assume_role:<EOL><INDENT>sts = boto3.session.Session().client('<STR_LIT>')<EOL>if not all([account_number, assume_role]):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>arn = '<STR_LIT>'.format(<EOL>account_number,<EOL>assume_role,<EOL>partition=arn_partition<EOL>)<EOL>assume_role_kwargs = {<EOL>'<STR_LIT>': arn,<EOL>'<STR_LIT>': session_name<EOL>}<EOL>if external_id:<EOL><INDENT>assume_role_kwargs['<STR_LIT>'] = external_id<EOL><DEDENT>role = sts.assume_role(**assume_role_kwargs)<EOL><DEDENT>if service_type == '<STR_LIT>':<EOL><INDENT>conn = _client(service, region, role)<EOL><DEDENT>elif service_type == '<STR_LIT>':<EOL><INDENT>conn = _resource(service, region, role)<EOL><DEDENT>if role:<EOL><INDENT>CACHE[key] = role<EOL><DEDENT>if return_credentials:<EOL><INDENT>return conn, role['<STR_LIT>']<EOL><DEDENT>return conn<EOL>

Used to obtain a boto3 client or resource connection.
For cross account, provide both account_number and assume_role.

:usage:

# Same Account:
client = boto3_cached_conn('iam')
resource = boto3_cached_conn('iam', service_type='resource')

# Cross Account Client:
client = boto3_cached_conn('iam', account_number='000000000000', assume_role='role_name')

# Cross Account Resource:
resource = boto3_cached_conn('iam', service_type='resource', account_number='000000000000', assume_role='role_name')

:param service: AWS service (i.e. 'iam', 'ec2', 'kms')
:param service_type: 'client' or 'resource'
:param future_expiration_minutes: Connections will expire from the cache
    when their expiration is within this many minutes of the present time. [Default 15]
:param account_number: Required if assume_role is provided.
:param assume_role:  Name of the role to assume into for account described by account_number.
:param session_name: Session name to attach to requests. [Default 'cloudaux']
:param region: Region name for connection. [Default us-east-1]
:param return_credentials: Indicates if the STS credentials should be returned with the client [Default False]
:param external_id: Optional external id to pass to sts:AssumeRole.
    See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
:param arn_partition: Optional parameter to specify other aws partitions such as aws-us-gov for aws govcloud
:return: boto3 client or resource connection


def sts_conn(service, service_type='<STR_LIT>', future_expiration_minutes=<NUM_LIT:15>):

def decorator(f):<EOL><INDENT>@wraps(f)<EOL>def decorated_function(*args, **kwargs):<EOL><INDENT>if kwargs.get("<STR_LIT>"):<EOL><INDENT>kwargs[service_type] = kwargs.pop("<STR_LIT>")<EOL>kwargs.pop("<STR_LIT>", None)<EOL>kwargs.pop("<STR_LIT>", None)<EOL><DEDENT>else:<EOL><INDENT>kwargs[service_type] = boto3_cached_conn(<EOL>service,<EOL>service_type=service_type,<EOL>future_expiration_minutes=future_expiration_minutes,<EOL>account_number=kwargs.pop('<STR_LIT>', None),<EOL>assume_role=kwargs.pop('<STR_LIT>', None),<EOL>session_name=kwargs.pop('<STR_LIT>', '<STR_LIT>'),<EOL>external_id=kwargs.pop('<STR_LIT>', None),<EOL>region=kwargs.pop('<STR_LIT>', '<STR_LIT>'),<EOL>arn_partition=kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>)<EOL><DEDENT>return f(*args, **kwargs)<EOL><DEDENT>return decorated_function<EOL><DEDENT>return decorator<EOL>

This will wrap all calls with an STS AssumeRole if the required parameters are sent over.
Namely, it requires the following in the kwargs:
- Service Type (Required)
- Account Number (Required for Assume Role)
- IAM Role Name (Required for Assume Role)
- Region (Optional, but recommended)
- AWS Partition (Optional, defaults to 'aws' if none specified)
- IAM Session Name (Optional, but recommended to appear in CloudTrail)

If `force_client` is set to a boto3 client, then this will simply pass that in as the client.
`force_client` is mostly useful for mocks and tests.
:param service:
:param service_type:
:param future_expiration_minutes:
:return:


kwargs = dict()<EOL>if arns:<EOL><INDENT>kwargs.update(dict(LoadBalancerArns=arns))<EOL><DEDENT>if names:<EOL><INDENT>kwargs.update(dict(Names=names))<EOL><DEDENT>return client.describe_load_balancers(**kwargs)<EOL>


kwargs = dict()<EOL>if load_balancer_arn:<EOL><INDENT>kwargs.update(dict(LoadBalancerArn=load_balancer_arn))<EOL><DEDENT>if listener_arns:<EOL><INDENT>kwargs.update(dict(ListenerArns=listener_arns))<EOL><DEDENT>return client.describe_listeners(**kwargs)<EOL>


return client.describe_load_balancer_attributes(<EOL>LoadBalancerArn=arn)['<STR_LIT>']<EOL>


@sts_conn('<STR_LIT>')<EOL>@rate_limited()<EOL>def describe_rules(listener_arn=None, rule_arns=None, client=None):

kwargs = dict()<EOL>if listener_arn:<EOL><INDENT>kwargs.update(dict(ListenerArn=listener_arn))<EOL><DEDENT>if rule_arns:<EOL><INDENT>kwargs.update(dict(RuleArns=rule_arns))<EOL><DEDENT>return client.describe_rules(**kwargs)['<STR_LIT>']<EOL>


return client.describe_tags(ResourceArns=arns)['<STR_LIT>']<EOL>


return client.describe_target_group_attributes(TargetGroupArn=arn)['<STR_LIT>']<EOL>


kwargs = dict()<EOL>if load_balancer_arn:<EOL><INDENT>kwargs.update(LoadBalancerArn=load_balancer_arn)<EOL><DEDENT>if target_group_arns:<EOL><INDENT>kwargs.update(TargetGroupArns=target_group_arns)<EOL><DEDENT>if names:<EOL><INDENT>kwargs.update(Names=names)<EOL><DEDENT>return client.describe_target_groups(**kwargs)<EOL>


@sts_conn('<STR_LIT>')<EOL>@rate_limited()<EOL>def describe_target_health(target_group_arn, targets=None, client=None):

kwargs = dict(TargetGroupArn=target_group_arn)<EOL>if targets:<EOL><INDENT>kwargs.update(Targets=targets)<EOL><DEDENT>return client.describe_target_health(**kwargs)['<STR_LIT>']<EOL>


return client.get_bucket_location(**kwargs)<EOL>


return client.get_bucket_acl(**kwargs)<EOL>


return client.get_bucket_policy(**kwargs)<EOL>


return client.get_bucket_tagging(**kwargs)<EOL>


return client.get_bucket_versioning(**kwargs)<EOL>


return client.get_bucket_lifecycle_configuration(**kwargs)<EOL>


return client.get_bucket_logging(**kwargs)<EOL>


return client.get_bucket_website(**kwargs)<EOL>


return client.get_bucket_cors(**kwargs)<EOL>


return client.get_bucket_notification_configuration(**kwargs)<EOL>


return client.get_bucket_accelerate_configuration(**kwargs)<EOL>


return client.get_bucket_replication(**kwargs)<EOL>


result = client.list_bucket_analytics_configurations(**kwargs)<EOL>if not result.get("<STR_LIT>"):<EOL><INDENT>result.update({"<STR_LIT>": []})<EOL><DEDENT>return result<EOL>


result = client.list_bucket_metrics_configurations(**kwargs)<EOL>if not result.get("<STR_LIT>"):<EOL><INDENT>result.update({"<STR_LIT>": []})<EOL><DEDENT>return result<EOL>


result = client.list_bucket_inventory_configurations(**kwargs)<EOL>if not result.get("<STR_LIT>"):<EOL><INDENT>result.update({"<STR_LIT>": []})<EOL><DEDENT>return result<EOL>


result = client.list_rules(**kwargs)<EOL>if not result.get("<STR_LIT>"):<EOL><INDENT>result.update({"<STR_LIT>": []})<EOL><DEDENT>return result<EOL>


return client.describe_rule(**kwargs)<EOL>


result = client.list_targets_by_rule(**kwargs)<EOL>if not result.get("<STR_LIT>"):<EOL><INDENT>result.update({"<STR_LIT>": []})<EOL><DEDENT>return result<EOL>


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_role_managed_policy_documents(role, client=None, **kwargs):

policies = get_role_managed_policies(role, force_client=client)<EOL>policy_names = (policy['<STR_LIT:name>'] for policy in policies)<EOL>delayed_gmpd_calls = (delayed(get_managed_policy_document)(policy['<STR_LIT>'], force_client=client) for policy<EOL>in policies)<EOL>policy_documents = Parallel(n_jobs=<NUM_LIT:20>, backend="<STR_LIT>")(delayed_gmpd_calls)<EOL>return dict(zip(policy_names, policy_documents))<EOL>

Retrieve the currently active policy version document for every managed policy that is attached to the role.


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_managed_policy_document(policy_arn, policy_metadata=None, client=None, **kwargs):

if not policy_metadata:<EOL><INDENT>policy_metadata = client.get_policy(PolicyArn=policy_arn)<EOL><DEDENT>policy_document = client.get_policy_version(PolicyArn=policy_arn,<EOL>VersionId=policy_metadata['<STR_LIT>']['<STR_LIT>'])<EOL>return policy_document['<STR_LIT>']['<STR_LIT>']<EOL>

Retrieve the currently active (i.e. 'default') policy version document for a policy.

    :param policy_arn:
    :param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
                            This is used to prevent unnecessary API calls to get the initial policy default version id.
    :param client:
    :param kwargs:
    :return:


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_policy(policy_arn, client=None, **kwargs):

return client.get_policy(PolicyArn=policy_arn, **kwargs)<EOL>


return client.get_group(**kwargs)<EOL>

Fetch the paginated users attached to the group.


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_group(group_name, users=True, client=None, **kwargs):

<EOL>result = client.get_group(GroupName=group_name, **kwargs)<EOL>if users:<EOL><INDENT>if result.get('<STR_LIT>'):<EOL><INDENT>kwargs_to_send = {'<STR_LIT>': group_name}<EOL>kwargs_to_send.update(kwargs)<EOL>user_list = result['<STR_LIT>']<EOL>kwargs_to_send['<STR_LIT>'] = result['<STR_LIT>']<EOL>result['<STR_LIT>'] = user_list + _get_users_for_group(client, **kwargs_to_send)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result.pop('<STR_LIT>', None)<EOL>result.pop('<STR_LIT>', None)<EOL>result.pop('<STR_LIT>', None)<EOL><DEDENT>return result<EOL>

Get's the IAM Group details.

    :param group_name:
    :param users: Optional -- will return the IAM users that the group is attached to if desired (paginated).
    :param client:
    :param kwargs:
    :return:


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@paginated('<STR_LIT>')<EOL>@rate_limited()<EOL>def list_group_policies(group_name, client=None, **kwargs):

return client.list_group_policies(GroupName=group_name, **kwargs)<EOL>

Lets the IAM group inline policies for a given group.


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@rate_limited()<EOL>def get_group_policy_document(group_name, policy_name, client=None, **kwargs):

return client.get_group_policy(GroupName=group_name, PolicyName=policy_name, **kwargs)['<STR_LIT>']<EOL>

Fetches the specific IAM group inline-policy document.


return client.list_attached_group_policies(GroupName=group_name, **kwargs)<EOL>

Lists the attached IAM managed policies for a given IAM group.


@sts_conn('<STR_LIT>', service_type='<STR_LIT>')<EOL>@paginated('<STR_LIT>')<EOL>@rate_limited()<EOL>def list_groups_for_user(user_name, client=None, **kwargs):

return client.list_groups_for_user(UserName=user_name, **kwargs)<EOL>

Lists the IAM groups that is attached to a given IAM user.


return client.list_server_certificates(**kwargs)<EOL>

Lists the IAM Server Certificates (IAM SSL) for a given AWS account.


return [x for x in getattr( getattr( conn, kwargs.pop('<STR_LIT>') ),<EOL>kwargs.pop('<STR_LIT>'))(**kwargs)]<EOL>


@registry.register(flag=FLAGS.POLICY, depends_on=FLAGS.VERSIONS, key='<STR_LIT>')<EOL>def _get_policy(lambda_function, **conn):

policies = dict(Versions=dict(), Aliases=dict(), DEFAULT=dict())<EOL>for version in [v['<STR_LIT>'] for v in lambda_function['<STR_LIT>']]:<EOL><INDENT>try:<EOL><INDENT>policies['<STR_LIT>'][version] = get_policy(FunctionName=lambda_function['<STR_LIT>'], Qualifier=version, **conn)<EOL>policies['<STR_LIT>'][version] = json.loads(policies['<STR_LIT>'][version])<EOL><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>for alias in [v['<STR_LIT:Name>'] for v in lambda_function['<STR_LIT>']]:<EOL><INDENT>try:<EOL><INDENT>policies['<STR_LIT>'][alias] = get_policy(FunctionName=lambda_function['<STR_LIT>'], Qualifier=alias, **conn)<EOL>policies['<STR_LIT>'][alias] = json.loads(policies['<STR_LIT>'][alias])<EOL><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>policies['<STR_LIT>'] = get_policy(FunctionName=lambda_function['<STR_LIT>'], **conn)<EOL>policies['<STR_LIT>'] = json.loads(policies['<STR_LIT>'])<EOL><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT>return policies<EOL>

Get LambdaFunction Policies.  (there can be many of these!)

    Lambda Function Policies are overly complicated.  They can be attached to a label,
    a version, and there is also a default policy.

    This method attempts to gather all three types.

    AWS returns an exception if the policy requested does not exist.  We catch and ignore these exceptions.


@modify_output<EOL>def get_lambda_function(lambda_function, flags=FLAGS.ALL, **conn):

<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError as _:<EOL><INDENT>basestring = str<EOL><DEDENT>if isinstance(lambda_function, basestring):<EOL><INDENT>lambda_function_arn = ARN(lambda_function)<EOL>if lambda_function_arn.error:<EOL><INDENT>lambda_function = dict(FunctionName=lambda_function)<EOL><DEDENT>else:<EOL><INDENT>lambda_function = dict(FunctionName=lambda_function_arn.name, FunctionArn=lambda_function)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in lambda_function:<EOL><INDENT>lambda_function_arn = ARN(lambda_function['<STR_LIT>'])<EOL>if not lambda_function_arn.error:<EOL><INDENT>if lambda_function_arn.account_number:<EOL><INDENT>conn['<STR_LIT>'] = lambda_function_arn.account_number<EOL><DEDENT>if lambda_function_arn.region:<EOL><INDENT>conn['<STR_LIT>'] = lambda_function_arn.region<EOL><DEDENT><DEDENT><DEDENT>return registry.build_out(flags, start_with=lambda_function, pass_datastructure=True, **conn)<EOL>

Fully describes a lambda function.

    Args:
        lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
        flags: Flags describing which sections should be included in the return value. Default ALL

    Returns:
        dictionary describing the requested lambda function.


@registry.register(flag=FLAGS.FLOW_LOGS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_vpc_flow_logs(vpc, **conn):

fl_result = describe_flow_logs(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>fl_ids = []<EOL>for fl in fl_result:<EOL><INDENT>fl_ids.append(fl["<STR_LIT>"])<EOL><DEDENT>return fl_ids<EOL>


@registry.register(flag=FLAGS.CLASSIC_LINK, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_classic_link(vpc, **conn):

result = {}<EOL>try:<EOL><INDENT>cl_result = describe_vpc_classic_link(VpcIds=[vpc["<STR_LIT:id>"]], **conn)[<NUM_LIT:0>]<EOL>result["<STR_LIT>"] = cl_result["<STR_LIT>"]<EOL>dns_result = describe_vpc_classic_link_dns_support(VpcIds=[vpc["<STR_LIT:id>"]], **conn)[<NUM_LIT:0>]<EOL>result["<STR_LIT>"] = dns_result["<STR_LIT>"]<EOL><DEDENT>except ClientError as e:<EOL><INDENT>if '<STR_LIT>' not in str(e):<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>return result<EOL>

Gets the Classic Link details about a VPC


@registry.register(flag=FLAGS.INTERNET_GATEWAY, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_internet_gateway(vpc, **conn):

result = {}<EOL>ig_result = describe_internet_gateways(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>if ig_result:<EOL><INDENT>result.update({<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>]["<STR_LIT>"][<NUM_LIT:0>]["<STR_LIT>"],<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>]["<STR_LIT>"],<EOL>"<STR_LIT>": ig_result[<NUM_LIT:0>].get("<STR_LIT>", [])<EOL>})<EOL><DEDENT>return result<EOL>

Gets the Internet Gateway details about a VPC


@registry.register(flag=FLAGS.VPC_PEERING_CONNECTIONS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_vpc_peering_connections(vpc, **conn):

accepter_result = describe_vpc_peering_connections(Filters=[{"<STR_LIT:Name>": "<STR_LIT>",<EOL>"<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>requester_result = describe_vpc_peering_connections(Filters=[{"<STR_LIT:Name>": "<STR_LIT>",<EOL>"<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>peer_ids = []<EOL>for peering in accepter_result + requester_result:<EOL><INDENT>peer_ids.append(peering["<STR_LIT>"])<EOL><DEDENT>return peer_ids<EOL>


@registry.register(flag=FLAGS.SUBNETS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_subnets(vpc, **conn):

subnets = describe_subnets(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>s_ids = []<EOL>for s in subnets:<EOL><INDENT>s_ids.append(s["<STR_LIT>"])<EOL><DEDENT>return s_ids<EOL>


@registry.register(flag=FLAGS.ROUTE_TABLES, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_route_tables(vpc, **conn):

route_tables = describe_route_tables(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>rt_ids = []<EOL>for r in route_tables:<EOL><INDENT>rt_ids.append(r["<STR_LIT>"])<EOL><DEDENT>return rt_ids<EOL>


@registry.register(flag=FLAGS.NETWORK_ACLS, depends_on=FLAGS.BASE, key="<STR_LIT>")<EOL>def get_network_acls(vpc, **conn):

route_tables = describe_network_acls(Filters=[{"<STR_LIT:Name>": "<STR_LIT>", "<STR_LIT>": [vpc["<STR_LIT:id>"]]}], **conn)<EOL>nacl_ids = []<EOL>for r in route_tables:<EOL><INDENT>nacl_ids.append(r["<STR_LIT>"])<EOL><DEDENT>return nacl_ids<EOL>


<EOL>base_result = describe_vpcs(VpcIds=[vpc["<STR_LIT:id>"]], **conn)[<NUM_LIT:0>]<EOL>vpc_name = None<EOL>for t in base_result.get("<STR_LIT>", []):<EOL><INDENT>if t["<STR_LIT>"] == "<STR_LIT:Name>":<EOL><INDENT>vpc_name = t["<STR_LIT>"]<EOL><DEDENT><DEDENT>dhcp_opts = None<EOL>if base_result.get("<STR_LIT>"):<EOL><INDENT>dhcp_opts = describe_dhcp_options(DhcpOptionsIds=[base_result["<STR_LIT>"]], **conn)[<NUM_LIT:0>]["<STR_LIT>"]<EOL><DEDENT>attributes = {}<EOL>attr_vals = [<EOL>("<STR_LIT>", "<STR_LIT>"),<EOL>("<STR_LIT>", "<STR_LIT>")<EOL>]<EOL>for attr, query in attr_vals:<EOL><INDENT>attributes[attr] = describe_vpc_attribute(VpcId=vpc["<STR_LIT:id>"], Attribute=query, **conn)[attr]<EOL><DEDENT>vpc.update({<EOL>'<STR_LIT:name>': vpc_name,<EOL>'<STR_LIT>': conn["<STR_LIT>"],<EOL>'<STR_LIT>': base_result.get("<STR_LIT>", []),<EOL>'<STR_LIT>': base_result["<STR_LIT>"],<EOL>'<STR_LIT>': base_result["<STR_LIT>"],<EOL>'<STR_LIT>': dhcp_opts,<EOL>'<STR_LIT>': base_result["<STR_LIT>"],<EOL>'<STR_LIT>': base_result.get("<STR_LIT>", []),<EOL>'<STR_LIT>': base_result.get("<STR_LIT>", []),<EOL>'<STR_LIT>': attributes,<EOL>'<STR_LIT>': <NUM_LIT:1><EOL>})<EOL>return vpc<EOL>

The base will return:
- ARN
- Region
- Name
- Id
- Tags
- IsDefault
- InstanceTenancy
- CidrBlock
- CidrBlockAssociationSet
- Ipv6CidrBlockAssociationSet
- DhcpOptionsId
- Attributes
- _version

:param bucket_name:
:param conn:
:return:


@modify_output<EOL>def get_vpc(vpc_id, flags=FLAGS.ALL, **conn):

<EOL>if not conn.get("<STR_LIT>"):<EOL><INDENT>raise CloudAuxException({"<STR_LIT:message>": "<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": vpc_id})<EOL><DEDENT>if not conn.get("<STR_LIT>"):<EOL><INDENT>raise CloudAuxException({"<STR_LIT:message>": "<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>": vpc_id})<EOL><DEDENT>start = {<EOL>'<STR_LIT>': "<STR_LIT>".format(region=conn["<STR_LIT>"],<EOL>account=conn["<STR_LIT>"],<EOL>vpc_id=vpc_id),<EOL>'<STR_LIT:id>': vpc_id<EOL>}<EOL>return registry.build_out(flags, start_with=start, pass_datastructure=True, **conn)<EOL>

Orchestrates all the calls required to fully fetch details about a VPC:

{
    "Arn": ...,
    "Region": ...,
    "Name": ...,
    "Id": ...,
    "Tags: ...,
    "VpcPeeringConnections": ...,
    "ClassicLink": ...,
    "DhcpOptionsId": ...,
    "InternetGateway": ...,
    "IsDefault": ...,
    "CidrBlock": ...,
    "CidrBlockAssociationSet": ...,
    "Ipv6CidrBlockAssociationSet": ...,
    "InstanceTenancy": ...,
    "RouteTables": ...,
    "NetworkAcls": ...,
    "FlowLogs": ...,
    "Subnets": ...,
    "Attributes": ...,
    "FlowLogs": ...,
    "_version": 1
}

:param vpc_id: The ID of the VPC
:param flags:
:param conn:
:return:


policy_name = policy['<STR_LIT>']<EOL>ret = {}<EOL>ret['<STR_LIT:type>'] = policy['<STR_LIT>']<EOL>attrs = policy['<STR_LIT>']<EOL>if ret['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>return policy_name, ret<EOL><DEDENT>attributes = dict()<EOL>for attr in attrs:<EOL><INDENT>attributes[attr['<STR_LIT>']] = attr['<STR_LIT>']<EOL><DEDENT>ret['<STR_LIT>'] = dict()<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>']['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>'] = bool(attributes.get('<STR_LIT>'))<EOL>ret['<STR_LIT>'] = attributes.get('<STR_LIT>', None)<EOL>non_ciphers = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>]<EOL>ciphers = []<EOL>for cipher in attributes:<EOL><INDENT>if attributes[cipher] == '<STR_LIT:true>' and cipher not in non_ciphers:<EOL><INDENT>ciphers.append(cipher)<EOL><DEDENT><DEDENT>ciphers.sort()<EOL>ret['<STR_LIT>'] = ciphers<EOL>return policy_name, ret<EOL>

Policies returned from boto3 are massive, ugly, and difficult to read.
This method flattens and reformats the policy.

:param policy: Result from invoking describe_load_balancer_policies(...)
:return: Returns a tuple containing policy_name and the reformatted policy dict.


result = dict()<EOL>if set(listener.keys()) == set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>result.update(listener['<STR_LIT>'])<EOL>result['<STR_LIT>'] = listener['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>result = dict(listener)<EOL><DEDENT>return result<EOL>

from

{
  "Listener": {
    "InstancePort": 80,
    "LoadBalancerPort": 80,
    "Protocol": "HTTP",
    "InstanceProtocol": "HTTP"
  },
  "PolicyNames": []
},

to

{
    "InstancePort": 80,
    "LoadBalancerPort": 80,
    "Protocol": "HTTP",
    "InstanceProtocol": "HTTP",
    "PolicyNames": []
}


@modify_output<EOL>def get_load_balancer(load_balancer, flags=FLAGS.ALL ^ FLAGS.POLICY_TYPES, **conn):

<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError as _:<EOL><INDENT>basestring = str<EOL><DEDENT>if isinstance(load_balancer, basestring):<EOL><INDENT>load_balancer = dict(LoadBalancerName=load_balancer)<EOL><DEDENT>return registry.build_out(flags, start_with=load_balancer, pass_datastructure=True, **conn)<EOL>

Fully describes an ELB.

:param loadbalancer: Could be an ELB Name or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerName'.
:param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL minus FLAGS.POLICY_TYPES.
:return: Returns a dictionary describing the ELB with the fields described in the flags parameter.


@modify_output<EOL>def get_vault(vault_obj, flags=FLAGS.ALL, **conn):

if isinstance(vault_obj, string_types):<EOL><INDENT>vault_arn = ARN(vault_obj)<EOL>if vault_arn.error:<EOL><INDENT>vault_obj = {'<STR_LIT>': vault_obj}<EOL><DEDENT>else:<EOL><INDENT>vault_obj = {'<STR_LIT>': vault_arn.parsed_name}<EOL><DEDENT><DEDENT>return registry.build_out(flags, vault_obj, **conn)<EOL>

Orchestrates calls to build a Glacier Vault in the following format:

{
    "VaultARN": ...,
    "VaultName": ...,
    "CreationDate" ...,
    "LastInventoryDate" ...,
    "NumberOfArchives" ...,
    "SizeInBytes" ...,
    "Policy" ...,
    "Tags" ...
}
Args:
    vault_obj: name, ARN, or dict of Glacier Vault
    flags: Flags describing which sections should be included in the return value. Default ALL

Returns:
    dictionary describing the requested Vault


@modify_output<EOL>def get_image(image_id, flags=FLAGS.ALL, **conn):

image = dict(ImageId=image_id)<EOL>conn['<STR_LIT>'] = conn.get('<STR_LIT>', '<STR_LIT>')<EOL>return registry.build_out(flags, image, **conn)<EOL>

Orchestrates all the calls required to fully build out an EC2 Image (AMI, AKI, ARI)

{
    "Architecture": "x86_64",
    "Arn": "arn:aws:ec2:us-east-1::image/ami-11111111",
    "BlockDeviceMappings": [],
    "CreationDate": "2013-07-11T16:04:06.000Z",
    "Description": "...",
    "Hypervisor": "xen",
    "ImageId": "ami-11111111",
    "ImageLocation": "111111111111/...",
    "ImageType": "machine",
    "KernelId": "aki-88888888",
    "LaunchPermissions": [],
    "Name": "...",
    "OwnerId": "111111111111",
    "ProductCodes": [],
    "Public": false,
    "RamdiskId": {},
    "RootDeviceName": "/dev/sda1",
    "RootDeviceType": "ebs",
    "SriovNetSupport": "simple",
    "State": "available",
    "Tags": [],
    "VirtualizationType": "hvm",
    "_version": 1
}

:param image_id: str ami id
:param flags: By default, set to ALL fields
:param conn: dict containing enough information to make a connection to the desired account.
Must at least have 'assume_role' key.
:return: dict containing a fully built out image.


@modify_output<EOL>def get_elbv2(alb, flags=FLAGS.ALL, **conn):

<EOL>try:<EOL><INDENT>basestring<EOL><DEDENT>except NameError as _:<EOL><INDENT>basestring = str<EOL><DEDENT>if isinstance(alb, basestring):<EOL><INDENT>from cloudaux.orchestration.aws.arn import ARN<EOL>alb_arn = ARN(alb)<EOL>if alb_arn.error:<EOL><INDENT>alb = dict(LoadBalancerName=alb)<EOL><DEDENT>else:<EOL><INDENT>alb = dict(LoadBalancerArn=alb)<EOL><DEDENT><DEDENT>return registry.build_out(flags, start_with=alb, pass_datastructure=True, **conn)<EOL>

Fully describes an ALB (ELBv2).

:param alb: Could be an ALB Name, ALB ARN, or a dictionary. Likely the return value from a previous call to describe_load_balancers. At a minimum, must contain a key titled 'LoadBalancerArn'.
:param flags: Flags describing which sections should be included in the return value. Default is FLAGS.ALL.
:return: Returns a dictionary describing the ALB with the fields described in the flags parameter.


@modify_output<EOL>def get_security_group(sg_obj, flags=FLAGS.ALL, **conn):

if isinstance(sg_obj, string_types):<EOL><INDENT>group_arn = ARN(sg_obj)<EOL>if group_arn.error:<EOL><INDENT>sg_obj = {'<STR_LIT>': sg_obj}<EOL><DEDENT>else:<EOL><INDENT>sg_obj = {'<STR_LIT>': group_arn.parsed_name}<EOL><DEDENT><DEDENT>return registry.build_out(flags, sg_obj, **conn)<EOL>

Orchestrates calls to build a Security Group in the following format:

{
    "Description": ...,
    "GroupName": ...,
    "IpPermissions" ...,
    "OwnerId" ...,
    "GroupId" ...,
    "IpPermissionsEgress" ...,
    "VpcId" ...
}
Args:
    sg_obj: name, ARN, or dict of Security Group
    flags: Flags describing which sections should be included in the return value. Default ALL

Returns:
    dictionary describing the requested Security Group


arn = ARN(arn)<EOL>if arn.error:<EOL><INDENT>raise CloudAuxException('<STR_LIT>'.format(arn=arn))<EOL><DEDENT>return dict(<EOL>account_number=arn.account_number,<EOL>)<EOL>

Extracts the account number from an ARN.
:param arn: Amazon ARN containing account number.
:return: dictionary with a single account_number key that can be merged with an existing
connection dictionary containing fields such as assume_role, session_name, region.


if item.get(default):<EOL><INDENT>return item.get(default)<EOL><DEDENT>if item.get('<STR_LIT>'):<EOL><INDENT>arn = item.get('<STR_LIT>')<EOL>item_arn = ARN(arn)<EOL>if item_arn.error:<EOL><INDENT>raise CloudAuxException('<STR_LIT>'.format(arn=arn))<EOL><DEDENT>return item_arn.parsed_name<EOL><DEDENT>raise MissingFieldException('<STR_LIT>'.format(input=item))<EOL>

Given a possibly sparsely populated item dictionary, try to retrieve the item name.
First try the default field.  If that doesn't exist, try to parse the from the ARN.
:param item: dict containing (at the very least) item_name and/or arn
:return: item name


@modify_output<EOL>def get_queue(queue, flags=FLAGS.ALL, **conn):

<EOL>if queue.startswith("<STR_LIT>") or queue.startswith("<STR_LIT>"):<EOL><INDENT>queue_name = queue<EOL><DEDENT>else:<EOL><INDENT>queue_name = get_queue_url(QueueName=queue, **conn)<EOL><DEDENT>sqs_queue = {"<STR_LIT>": queue_name}<EOL>return registry.build_out(flags, sqs_queue, **conn)<EOL>

Orchestrates all the calls required to fully fetch details about an SQS Queue:

{
    "Arn": ...,
    "Region": ...,
    "Name": ...,
    "Url": ...,
    "Attributes": ...,
    "Tags": ...,
    "DeadLetterSourceQueues": ...,
    "_version": 1
}

:param queue: Either the queue name OR the queue url
:param flags: By default, set to ALL fields.
:param conn: dict containing enough information to make a connection to the desired account. Must at least have
             'assume_role' key.
:return: dict containing a fully built out SQS queue.