Instruction:
Can you generate the documentation for the following Python 3 function
def _delete_switch_entry(self, port, vlan_id, device_id, host_id, vni,
                             is_provider_vlan):
        """Delete the nexus switch entry.

        By accessing the current db entries determine if switch
        configuration can be removed.

        Called during delete postcommit port event.
        """

        connections = self._get_active_port_connections(port, host_id)

        # (nexus_port,switch_ip) will be unique in each iteration.
        # But switch_ip will repeat if host has >1 connection to same switch.
        # So track which switch_ips already have vlan removed in this loop.
        vlan_already_removed = []
        for switch_ip, intf_type, nexus_port, is_native, _ in connections:

            # if there are no remaining db entries using this vlan on this
            # nexus switch port then remove vlan from the switchport trunk.
            port_id = nexus_help.format_interface_name(intf_type, nexus_port)
            auto_create = True
            auto_trunk = True
            if is_provider_vlan:
                auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create
                auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk

            try:
                nxos_db.get_port_vlan_switch_binding(port_id, vlan_id,
                                                     switch_ip)
            except excep.NexusPortBindingNotFound:
                pass
            else:
                continue

            if auto_trunk:
                self.driver.disable_vlan_on_trunk_int(
                    switch_ip, vlan_id, intf_type, nexus_port,
                    is_native)

            # if there are no remaining db entries using this vlan on this
            # nexus switch then remove the vlan.
            if auto_create:
                try:
                    nxos_db.get_nexusvlan_binding(vlan_id, switch_ip)
                except excep.NexusPortBindingNotFound:
                    # Do not perform a second time on same switch
                    if switch_ip not in vlan_already_removed:
                        self.driver.delete_vlan(switch_ip, vlan_id)
                        vlan_already_removed.append(switch_ip)

            self._delete_port_channel_resources(
                host_id, switch_ip, intf_type, nexus_port, port_id)

        if nexus_help.is_baremetal(port):
            connections = self._get_baremetal_connections(
                port, False, True)
            for switch_ip, intf_type, nexus_port, is_native, _ in connections:
                if_id = nexus_help.format_interface_name(
                    intf_type, nexus_port)
                try:
                    mapping = nxos_db.get_switch_if_host_mappings(
                        switch_ip, if_id)
                    ch_grp = mapping[0].ch_grp
                except excep.NexusHostMappingNotFound:
                    ch_grp = 0
                bind_port_id = nexus_help.format_interface_name(
                    intf_type, nexus_port, ch_grp)
                binding = nxos_db.get_port_switch_bindings(
                    bind_port_id,
                    switch_ip)
                if not binding:
                    nxos_db.remove_host_mapping(if_id, switch_ip)

Response: Delete the nexus switch entry.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _port_action_vlan(self, port, segment, func, vni):

        # Verify segment.
        if not self._is_valid_segment(segment):
            return

        device_id = self._get_port_uuid(port)

        if nexus_help.is_baremetal(port):
            host_id = port.get('dns_name')
        else:
            host_id = port.get(bc.portbindings.HOST_ID)

        vlan_id = segment.get(api.SEGMENTATION_ID)
        is_provider = nxos_db.is_provider_vlan(vlan_id)

        settings = {"vlan_id": vlan_id,
                    "device_id": device_id,
                    "host_id": host_id}
        missing_fields = [field for field, value in settings.items()
                          if (field != 'host_id' and not value)]
        if not missing_fields:
            func(port, vlan_id, device_id, host_id, vni, is_provider)
        else:
            raise excep.NexusMissingRequiredFields(
                fields=' '.join(missing_fields))

Response: Verify configuration and then process event.


Instruction:
How would you explain what the following Python 3 function does
def _port_action_vxlan(self, port, segment, func):

        # If the segment is None, just log a warning message and return.
        if segment is None:
            self._log_missing_segment()
            return

        device_id = port.get('device_id')
        mcast_group = segment.get(api.PHYSICAL_NETWORK)
        host_id = port.get(bc.portbindings.HOST_ID)
        vni = segment.get(api.SEGMENTATION_ID)

        if vni and device_id and mcast_group and host_id:
            func(vni, device_id, mcast_group, host_id)
            return vni
        else:
            fields = "vni " if not vni else ""
            fields += "device_id " if not device_id else ""
            fields += "mcast_group " if not mcast_group else ""
            fields += "host_id" if not host_id else ""
            raise excep.NexusMissingRequiredFields(fields=fields)

Response: Verify configuration and then process event.


Instruction:
Write a Python 3 function that can
create port non - database commit event.

Response:
def create_port_postcommit(self, context):
        """Create port non-database commit event."""

        # No new events are handled until replay
        # thread has put the switch in active state.
        # If a switch is in active state, verify
        # the switch is still in active state
        # before accepting this new event.
        #
        # If create_port_postcommit fails, it causes
        # other openstack dbs to be cleared and
        # retries for new VMs will stop.  Subnet
        # transactions will continue to be retried.

        vlan_segment, vxlan_segment = self._get_segments(
                                        context.top_bound_segment,
                                        context.bottom_bound_segment)
        # Verify segment.
        if not self._is_valid_segment(vlan_segment):
            return

        port = context.current
        if self._is_supported_deviceowner(port):
            if nexus_help.is_baremetal(context.current):
                all_switches, active_switches = (
                    self._get_baremetal_switches(context.current))
            else:
                host_id = context.current.get(bc.portbindings.HOST_ID)
                all_switches, active_switches = (
                    self._get_host_switches(host_id))

            # Verify switch is still up before replay
            # thread checks.
            verified_active_switches = []
            for switch_ip in active_switches:
                try:
                    self.driver.get_nexus_type(switch_ip)
                    verified_active_switches.append(switch_ip)
                except Exception as e:
                    LOG.error("Failed to ping "
                        "switch ip %(switch_ip)s error %(exp_err)s",
                        {'switch_ip': switch_ip, 'exp_err': e})

            LOG.debug("Create Stats:  thread %(thid)d, "
                      "all_switches %(all)d, "
                      "active %(active)d, verified %(verify)d",
                      {'thid': threading.current_thread().ident,
                      'all': len(all_switches),
                      'active': len(active_switches),
                      'verify': len(verified_active_switches)})

            # if host_id is valid and there is no active
            # switches remaining
            if all_switches and not verified_active_switches:
                raise excep.NexusConnectFailed(
                    nexus_host=all_switches[0], config="None",
                    exc="Create Failed: Port event can not "
                    "be processed at this time.")


Instruction:
Here you have a function in Python 3, explain what it does
def update_port_precommit(self, context):
        vlan_segment, vxlan_segment = self._get_segments(
            context.top_bound_segment, context.bottom_bound_segment)
        orig_vlan_segment, orig_vxlan_segment = self._get_segments(
            context.original_top_bound_segment,
            context.original_bottom_bound_segment)

        if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
            self._is_status_down(context.current)):
            vni = (self._port_action_vxlan(
                context.original, orig_vxlan_segment, self._delete_nve_db)
                if orig_vxlan_segment else 0)
            self._port_action_vlan(context.original, orig_vlan_segment,
                                   self._delete_nxos_db, vni)
        elif self._is_supported_deviceowner(context.current):
            vni = self._port_action_vxlan(context.current, vxlan_segment,
                        self._configure_nve_db) if vxlan_segment else 0
            self._port_action_vlan(context.current, vlan_segment,
                                   self._configure_nxos_db, vni)

Response: Update port pre - database transaction commit event.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_port_postcommit(self, context):
        vlan_segment, vxlan_segment = self._get_segments(
            context.top_bound_segment, context.bottom_bound_segment)
        orig_vlan_segment, orig_vxlan_segment = self._get_segments(
            context.original_top_bound_segment,
            context.original_bottom_bound_segment)

        if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
                self._is_status_down(context.current)):
            vni = (self._port_action_vxlan(
                context.original, orig_vxlan_segment,
                self._delete_nve_member) if orig_vxlan_segment else 0)
            self._port_action_vlan(context.original, orig_vlan_segment,
                                   self._delete_switch_entry, vni)
        elif self._is_supported_deviceowner(context.current):
            if nexus_help.is_baremetal(context.current):
                all_switches, active_switches = (
                    self._get_baremetal_switches(context.current))
            else:
                host_id = context.current.get(bc.portbindings.HOST_ID)
                all_switches, active_switches = (
                    self._get_host_switches(host_id))

            # if switches not active but host_id is valid
            if not active_switches and all_switches:
                raise excep.NexusConnectFailed(
                    nexus_host=all_switches[0], config="None",
                    exc="Update Port Failed: Nexus Switch "
                    "is down or replay in progress")
            vni = self._port_action_vxlan(context.current, vxlan_segment,
                        self._configure_nve_member) if vxlan_segment else 0
            self._port_action_vlan(context.current, vlan_segment,
                                   self._configure_port_entries, vni)

Response: Update port non - database commit event.


Instruction:
How would you explain what the following Python 3 function does
def delete_port_precommit(self, context):
        if self._is_supported_deviceowner(context.current):
            vlan_segment, vxlan_segment = self._get_segments(
                                                context.top_bound_segment,
                                                context.bottom_bound_segment)
            vni = self._port_action_vxlan(context.current, vxlan_segment,
                             self._delete_nve_db) if vxlan_segment else 0
            self._port_action_vlan(context.current, vlan_segment,
                                   self._delete_nxos_db, vni)

Response: Delete port pre - database commit event.


Instruction:
How would you implement a function in Python 3 that
deletes port non - database commit event.

Response:
def delete_port_postcommit(self, context):
        """Delete port non-database commit event."""
        if self._is_supported_deviceowner(context.current):
            vlan_segment, vxlan_segment = self._get_segments(
                                                context.top_bound_segment,
                                                context.bottom_bound_segment)
            vni = self._port_action_vxlan(context.current, vxlan_segment,
                             self._delete_nve_member) if vxlan_segment else 0
            self._port_action_vlan(context.current, vlan_segment,
                                   self._delete_switch_entry, vni)


Instruction:
Make a summary of the following Python 3 code
def _detect_iplus(self):

        ver_expr = "([0-9]+)\.([0-9]+)\((.*)\)"
        re.compile(ver_expr)
        v1 = re.match(ver_expr, self._cur_ver)
        v2 = re.match(ver_expr, self._base_ver)

        if int(v1.group(1)) > int(v2.group(1)):
            self._is_iplus = True
        elif int(v1.group(1)) == int(v2.group(1)):
            if int(v1.group(2)) > int(v2.group(2)):
                self._is_iplus = True
            elif int(v1.group(2)) == int(v2.group(2)):
                self._is_iplus = v1.group(3) >= v2.group(3)

        LOG.info("DCNM version: %(cur_ver)s, iplus: %(is_iplus)s",
                 {'cur_ver': self._cur_ver, 'is_iplus': self._is_iplus})

Response: Detects if the DCNM version is for iplus


Instruction:
Write a Python 3 function that can
get segment id range from DCNM.

Response:
def get_segmentid_range(self, orchestrator_id):
        """Get segment id range from DCNM. """

        url = "%s/%s" % (self._segmentid_ranges_url, orchestrator_id)

        res = self._send_request('GET', url, None, 'segment-id range')
        if res and res.status_code in self._resp_ok:
            return res.json()


Instruction:
Implement a function in Python 3 to
set segment id range in DCNM.

Response:
def set_segmentid_range(self, orchestrator_id, segid_min, segid_max):
        """set segment id range in DCNM. """

        url = self._segmentid_ranges_url

        payload = {'orchestratorId': orchestrator_id,
                   'segmentIdRanges': "%s-%s" % (segid_min, segid_max)}

        res = self._send_request('POST', url, payload, 'segment-id range')
        if not (res and res.status_code in self._resp_ok):
            LOG.error("Failed to set segment id range for orchestrator "
                      "%(orch)s on DCNM: %(text)s",
                      {'orch': orchestrator_id, 'text': res.text})
            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))


Instruction:
Create a Python 3 function for
setting default network config profile.

Response:
def _set_default_cfg_profile(self):
        """Set default network config profile.

        Check whether the default_cfg_profile value exist in the current
        version of DCNM. If not, set it to new default value which is supported
        by latest version.
        """
        try:
            cfgplist = self.config_profile_list()
            if self.default_cfg_profile not in cfgplist:
                self.default_cfg_profile = ('defaultNetworkUniversalEfProfile'
                                            if self._is_iplus else
                                            'defaultNetworkIpv4EfProfile')
        except dexc.DfaClientRequestFailed:
            LOG.error("Failed to send request to DCNM.")
            self.default_cfg_profile = 'defaultNetworkIpv4EfProfile'


Instruction:
Can you implement a function in Python 3 that
sends create network request to DCNM.

Response:
def _create_network(self, network_info):
        """Send create network request to DCNM.

        :param network_info: network parameters to be created on DCNM
        """
        url = self._create_network_url % (network_info['organizationName'],
                                          network_info['partitionName'])
        payload = network_info

        LOG.info('url %(url)s payload %(payload)s',
                 {'url': url, 'payload': payload})
        return self._send_request('POST', url, payload, 'network')


Instruction:
How would you explain what the following Python 3 function does
def _config_profile_get(self, thisprofile):
        url = self._cfg_profile_get_url % (thisprofile)
        payload = {}

        res = self._send_request('GET', url, payload, 'config-profile')
        if res and res.status_code in self._resp_ok:
            return res.json()

Response: Get information of a config profile from DCNM.


Instruction:
Create a Python 3 function for
getting list of supported config profile from DCNM.

Response:
def _config_profile_list(self):
        """Get list of supported config profile from DCNM."""
        url = self._cfg_profile_list_url
        payload = {}

        try:
            res = self._send_request('GET', url, payload, 'config-profile')
            if res and res.status_code in self._resp_ok:
                return res.json()
        except dexc.DfaClientRequestFailed:
            LOG.error("Failed to send request to DCNM.")


Instruction:
Explain what the following Python 3 code does
def _get_settings(self):
        url = self._global_settings_url
        payload = {}
        res = self._send_request('GET', url, payload, 'settings')
        if res and res.status_code in self._resp_ok:
            return res.json()

Response: Get global mobility domain from DCNM.


Instruction:
Create a Python 3 function for
creating organization on the DCNM.

Response:
def _create_org(self, orch_id, name, desc):
        """Create organization on the DCNM.

        :param orch_id: orchestrator ID
        :param name: Name of organization
        :param desc: Description of organization
        """
        url = self._org_url
        payload = {
            "organizationName": name,
            "description": name if len(desc) == 0 else desc,
            "orchestrationSource": orch_id}

        return self._send_request('POST', url, payload, 'organization')


Instruction:
Can you tell what is the following Python 3 function doing
def _create_or_update_partition(self, org_name, part_name, desc,
                                    dci_id=UNKNOWN_DCI_ID, vrf_prof=None,
                                    service_node_ip=UNKNOWN_SRVN_NODE_IP,
                                    operation='POST'):
        """Send create or update partition request to the DCNM.

        :param org_name: name of organization
        :param part_name: name of partition
        :param desc: description of partition
        :dci_id: DCI ID for inter-DC
        :vrf_prof: VRF Profile Name
        :service_node_ip: Service Node's Address
        """
        if part_name is None:
            part_name = self._part_name
        if vrf_prof is None or dci_id == UNKNOWN_DCI_ID or (
           service_node_ip == UNKNOWN_SRVN_NODE_IP):
            part_info = self._get_partition(org_name, part_name)
        if vrf_prof is None:
            vrf_prof = self.get_partition_vrfProf(org_name, part_name,
                                                  part_info=part_info)
        if dci_id == UNKNOWN_DCI_ID:
            dci_id = self.get_partition_dciId(org_name, part_name,
                                              part_info=part_info)
        if service_node_ip == UNKNOWN_SRVN_NODE_IP:
            service_node_ip = self.get_partition_serviceNodeIp(
                org_name, part_name, part_info=part_info)
        url = ((self._create_part_url % (org_name)) if operation == 'POST' else
               self._update_part_url % (org_name, part_name))

        payload = {
            "partitionName": part_name,
            "description": part_name if len(desc) == 0 else desc,
            "serviceNodeIpAddress": service_node_ip,
            "organizationName": org_name}

        # Check the DCNM version and find out whether it is need to have
        # extra payload for the new version when creating/updating a partition.
        if self._is_iplus:
            # Need to add extra payload for the new version.
            enable_dci = "true" if dci_id and int(dci_id) != 0 else "false"
            extra_payload = {
                "vrfProfileName": vrf_prof,
                "vrfName": ':'.join((org_name, part_name)),
                "dciId": dci_id,
                "enableDCIExtension": enable_dci}
            payload.update(extra_payload)

        return self._send_request(operation, url, payload, 'partition')

Response: Create or update the partition in the DCNM.


Instruction:
Write a Python 3 script for
sending get partition request to the DCNM.

Response:
def _get_partition(self, org_name, part_name=None):
        """send get partition request to the DCNM.

        :param org_name: name of organization
        :param part_name: name of partition
        """
        if part_name is None:
            part_name = self._part_name
        url = self._update_part_url % (org_name, part_name)
        res = self._send_request("GET", url, '', 'partition')
        if res and res.status_code in self._resp_ok:
            return res.json()


Instruction:
Can you tell what is the following Python 3 function doing
def update_partition_static_route(self, org_name, part_name,
                                      static_ip_list, vrf_prof=None,
                                      service_node_ip=None):
        """Send static route update requests to DCNM.

        :param org_name: name of organization
        :param part_name: name of partition
        :static_ip_list: List of static IP addresses
        :vrf_prof: VRF Profile
        :service_node_ip: Service Node IP address
        """
        if part_name is None:
            part_name = self._part_name
        if vrf_prof is None:
            vrf_prof = self.default_vrf_profile
        operation = 'PUT'
        url = (self._update_part_url % (org_name, part_name))
        ip_str = ''
        ip_cnt = 0
        for ip in static_ip_list:
            ip_sub = "$n0" + str(ip_cnt) + "=" + str(ip) + ";"
            ip_str = ip_str + ip_sub
            ip_cnt = ip_cnt + 1
        cfg_args = {
            "$vrfName=" + org_name + ':' + part_name + ";"
            "$include_serviceNodeIpAddress=" + service_node_ip + ";" + ip_str
        }
        cfg_args = ';'.join(cfg_args)
        payload = {
            "partitionName": part_name,
            "organizationName": org_name,
            "dciExtensionStatus": "Not configured",
            "vrfProfileName": vrf_prof,
            "vrfName": ':'.join((org_name, part_name)),
            "configArg": cfg_args}

        res = self._send_request(operation, url, payload, 'partition')
        return (res is not None and res.status_code in self._resp_ok)

Response: Send static route update requests to DCNM.


Instruction:
How would you implement a function in Python 3 that
sends organization delete request to DCNM.

Response:
def _delete_org(self, org_name):
        """Send organization delete request to DCNM.

        :param org_name: name of organization to be deleted
        """
        url = self._del_org_url % (org_name)
        return self._send_request('DELETE', url, '', 'organization')


Instruction:
Create a Python 3 function to
send partition delete request to DCNM.

Response:
def _delete_partition(self, org_name, partition_name):
        """Send partition delete request to DCNM.

        :param org_name: name of organization
        :param partition_name: name of partition
        """
        url = self._del_part % (org_name, partition_name)
        return self._send_request('DELETE', url, '', 'partition')


Instruction:
Implement a Python 3 function for
sending network delete request to DCNM.

Response:
def _delete_network(self, network_info):
        """Send network delete request to DCNM.

        :param network_info: contains network info to be deleted.
        """
        org_name = network_info.get('organizationName', '')
        part_name = network_info.get('partitionName', '')
        segment_id = network_info['segmentId']
        if 'mobDomainName' in network_info:
            vlan_id = network_info['vlanId']
            mob_dom_name = network_info['mobDomainName']
            url = self._network_mob_url % (org_name, part_name, vlan_id,
                                           mob_dom_name)
        else:
            url = self._network_url % (org_name, part_name, segment_id)
        return self._send_request('DELETE', url, '', 'network')


Instruction:
Create a Python 3 function to
send network get request to DCNM.

Response:
def _get_network(self, network_info):
        """Send network get request to DCNM.

        :param network_info: contains network info to query.
        """
        org_name = network_info.get('organizationName', '')
        part_name = network_info.get('partitionName', '')
        segment_id = network_info['segmentId']
        url = self._network_url % (org_name, part_name, segment_id)
        return self._send_request('GET', url, '', 'network')


Instruction:
Make a summary of the following Python 3 code
def _login_request(self, url_login):

        expiration_time = self._exp_time
        payload = {'expirationTime': expiration_time}
        # TODO(padkrish), after testing with certificates, make the
        # verify option configurable.
        res = requests.post(url_login,
                            data=jsonutils.dumps(payload),
                            headers=self._req_headers,
                            auth=(self._user, self._pwd),
                            timeout=self.timeout_resp, verify=False)
        session_id = ''
        if res and res.status_code in self._resp_ok:
            session_id = res.json().get('Dcnm-Token')
        self._req_headers.update({'Dcnm-Token': session_id})

Response: Internal function to send login request.


Instruction:
Can you tell what is the following Python 3 function doing
def _logout_request(self, url_logout):

        requests.post(url_logout,
                      headers=self._req_headers,
                      timeout=self.timeout_resp, verify=False)

Response: Internal logout request to DCNM.


Instruction:
Here you have a function in Python 3, explain what it does
def _send_request(self, operation, url, payload, desc):

        res = None
        try:
            payload_json = None
            if payload and payload != '':
                payload_json = jsonutils.dumps(payload)
            self._login()
            desc_lookup = {'POST': ' creation', 'PUT': ' update',
                           'DELETE': ' deletion', 'GET': ' get'}

            res = requests.request(operation, url, data=payload_json,
                                   headers=self._req_headers,
                                   timeout=self.timeout_resp, verify=False)
            desc += desc_lookup.get(operation, operation.lower())
            LOG.info("DCNM-send_request: %(desc)s %(url)s %(pld)s",
                     {'desc': desc, 'url': url, 'pld': payload})

            self._logout()
        except (requests.HTTPError, requests.Timeout,
                requests.ConnectionError) as exc:
            LOG.exception('Error during request: %s', exc)
            raise dexc.DfaClientRequestFailed(reason=exc)

        return res

Response: Send request to DCNM.


Instruction:
Can you tell what is the following Python 3 function doing
def config_profile_list(self):

        these_profiles = self._config_profile_list() or []
        profile_list = [q for p in these_profiles for q in
                        [p.get('profileName')]]
        return profile_list

Response: Return config profile list from DCNM.


Instruction:
Implement a function in Python 3 to
return forwarding mode of given config profile.

Response:
def config_profile_fwding_mode_get(self, profile_name):
        """Return forwarding mode of given config profile."""

        profile_params = self._config_profile_get(profile_name)
        fwd_cli = 'fabric forwarding mode proxy-gateway'
        if profile_params and fwd_cli in profile_params['configCommands']:
            return 'proxy-gateway'
        else:
            return 'anycast-gateway'


Instruction:
Write a Python 3 function that can
get the config profile and fwding mode for a network.

Response:
def get_config_profile_for_network(self, net_name):
        """Get the list of profiles."""

        cfgplist = self.config_profile_list()
        cfgname = net_name.partition(':')[2]

        cfgtuple = set()
        for cfg_prof in cfgplist:
            if cfg_prof.startswith('defaultNetwork'):
                cfg_alias = (cfg_prof.split('defaultNetwork')[1].
                             split('Profile')[0])
            elif cfg_prof.endswith('Profile'):
                cfg_alias = cfg_prof.split('Profile')[0]
            else:
                cfg_alias = cfg_prof
            cfgtuple.update([(cfg_prof, cfg_alias)])
        cfgp = [a for a, b in cfgtuple if cfgname == b]
        prof = cfgp[0] if cfgp else self.default_cfg_profile
        fwd_mod = self.config_profile_fwding_mode_get(prof)
        return (prof, fwd_mod)


Instruction:
Write a Python 3 script for
creating the network on the DCNM.

Response:
def create_network(self, tenant_name, network, subnet,
                       dhcp_range=True):
        """Create network on the DCNM.

        :param tenant_name: name of tenant the network belongs to
        :param network: network parameters
        :param subnet: subnet parameters of the network
        """
        seg_id = str(network.segmentation_id)
        subnet_ip_mask = subnet.cidr.split('/')
        gw_ip = subnet.gateway_ip
        cfg_args = [
            "$segmentId=" + seg_id,
            "$netMaskLength=" + subnet_ip_mask[1],
            "$gatewayIpAddress=" + gw_ip,
            "$networkName=" + network.name,
            "$vlanId=0",
            "$vrfName=" + tenant_name + ':' + self._part_name
        ]
        cfg_args = ';'.join(cfg_args)

        ip_range = ','.join(["%s-%s" % (p['start'], p['end']) for p in
                             subnet.allocation_pools])

        dhcp_scopes = {'ipRange': ip_range,
                       'subnet': subnet.cidr,
                       'gateway': gw_ip}

        network_info = {"segmentId": seg_id,
                        "vlanId": "0",
                        "mobilityDomainId": "None",
                        "profileName": network.config_profile,
                        "networkName": network.name,
                        "configArg": cfg_args,
                        "organizationName": tenant_name,
                        "partitionName": self._part_name,
                        "description": network.name,
                        "netmaskLength": subnet_ip_mask[1],
                        "gateway": gw_ip}
        if dhcp_range:
            network_info["dhcpScope"] = dhcp_scopes

        if self._is_iplus:
            # Need to add the vrf name to the network info
            prof = self._config_profile_get(network.config_profile)
            if prof and prof.get('profileSubType') == 'network:universal':
                # For universal profile vrf has to e organization:partition
                network_info["vrfName"] = ':'.join((tenant_name,
                                                    self._part_name))
            else:
                # Otherwise, it should be left empty.
                network_info["vrfName"] = ""

        LOG.info("Creating %s network in DCNM.", network_info)

        res = self._create_network(network_info)
        if res and res.status_code in self._resp_ok:
            LOG.info("Created %s network in DCNM.", network_info)
        else:
            LOG.error("Failed to create %s network in DCNM.",
                      network_info)
            raise dexc.DfaClientRequestFailed(reason=res)


Instruction:
Write a Python 3 function that can
create the service network on the DCNM.

Response:
def create_service_network(self, tenant_name, network, subnet,
                               dhcp_range=True):
        """Create network on the DCNM.

        :param tenant_name: name of tenant the network belongs to
        :param network: network parameters
        :param subnet: subnet parameters of the network
        """
        network_info = {}
        subnet_ip_mask = subnet.cidr.split('/')
        if self._default_md is None:
            self._set_default_mobility_domain()
        vlan_id = '0'
        gw_ip = subnet.gateway_ip
        part_name = network.part_name
        if not part_name:
            part_name = self._part_name

        if network.vlan_id:
            vlan_id = str(network.vlan_id)
            if network.mob_domain_name is not None:
                mob_domain_name = network.mob_domain_name
            else:
                mob_domain_name = self._default_md
        else:
            mob_domain_name = None

        seg_id = str(network.segmentation_id)
        seg_str = "$segmentId=" + seg_id
        cfg_args = [
            seg_str,
            "$netMaskLength=" + subnet_ip_mask[1],
            "$gatewayIpAddress=" + gw_ip,
            "$networkName=" + network.name,
            "$vlanId=" + vlan_id,
            "$vrfName=" + tenant_name + ':' + part_name
        ]
        cfg_args = ';'.join(cfg_args)

        ip_range = ','.join(["%s-%s" % (p['start'], p['end']) for p in
                             subnet.allocation_pools])

        dhcp_scopes = {'ipRange': ip_range,
                       'subnet': subnet.cidr,
                       'gateway': gw_ip}

        network_info = {"vlanId": vlan_id,
                        "mobilityDomainId": mob_domain_name,
                        "profileName": network.config_profile,
                        "networkName": network.name,
                        "configArg": cfg_args,
                        "organizationName": tenant_name,
                        "partitionName": part_name,
                        "description": network.name,
                        "netmaskLength": subnet_ip_mask[1],
                        "gateway": gw_ip}
        if seg_id:
            network_info["segmentId"] = seg_id
        if dhcp_range:
            network_info["dhcpScope"] = dhcp_scopes
        if hasattr(subnet, 'secondary_gw'):
            network_info["secondaryGateway"] = subnet.secondary_gw
        if self._is_iplus:
            # Need to add the vrf name to the network info
            prof = self._config_profile_get(network.config_profile)
            if prof and prof.get('profileSubType') == 'network:universal':
                # For universal profile vrf has to e organization:partition
                network_info["vrfName"] = ':'.join((tenant_name, part_name))
            else:
                # Otherwise, it should be left empty.
                network_info["vrfName"] = ""

        LOG.info("Creating %s network in DCNM.", network_info)

        res = self._create_network(network_info)
        if res and res.status_code in self._resp_ok:
            LOG.info("Created %s network in DCNM.", network_info)
        else:
            LOG.error("Failed to create %s network in DCNM.",
                      network_info)
            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))


Instruction:
Write a Python 3 script to
delete the network on the DCNM.

Response:
def delete_network(self, tenant_name, network):
        """Delete network on the DCNM.

        :param tenant_name: name of tenant the network belongs to
        :param network: object that contains network parameters
        """
        seg_id = network.segmentation_id
        network_info = {
            'organizationName': tenant_name,
            'partitionName': self._part_name,
            'segmentId': seg_id,
        }
        LOG.debug("Deleting %s network in DCNM.", network_info)

        res = self._delete_network(network_info)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s network in DCNM.", network_info)
        else:
            LOG.error("Failed to delete %s network in DCNM.",
                      network_info)
            raise dexc.DfaClientRequestFailed(reason=res)


Instruction:
Write a Python 3 script to
delete the service network on the DCNM.

Response:
def delete_service_network(self, tenant_name, network):
        """Delete service network on the DCNM.

        :param tenant_name: name of tenant the network belongs to
        :param network: object that contains network parameters
        """

        network_info = {}
        part_name = network.part_name
        if not part_name:
            part_name = self._part_name
        seg_id = str(network.segmentation_id)
        if network.vlan:
            vlan_id = str(network.vlan)
            if network.mob_domain_name is not None:
                mob_domain_name = network.mob_domain_name
            else:
                # The current way will not work since _default_md is obtained
                # during create_service_network. It's preferrable to get it
                # during init TODO(padkrish)
                if self._default_md is None:
                    self._set_default_mobility_domain()
                mob_domain_name = self._default_md
            network_info = {
                'organizationName': tenant_name,
                'partitionName': part_name,
                'mobDomainName': mob_domain_name,
                'vlanId': vlan_id,
                'segmentId': seg_id,
            }
        else:
            network_info = {
                'organizationName': tenant_name,
                'partitionName': part_name,
                'segmentId': seg_id,
            }
        LOG.debug("Deleting %s network in DCNM.", network_info)

        res = self._delete_network(network_info)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s network in DCNM.", network_info)
        else:
            LOG.error("Failed to delete %s network in DCNM.",
                      network_info)
            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))


Instruction:
Can you implement a function in Python 3 that
deletes the project on the DCNM.

Response:
def delete_project(self, tenant_name, part_name):
        """Delete project on the DCNM.

        :param tenant_name: name of project.
        :param part_name: name of partition.
        """
        res = self._delete_partition(tenant_name, part_name)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s partition in DCNM.", part_name)
        else:
            LOG.error("Failed to delete %(part)s partition in DCNM."
                      "Response: %(res)s", {'part': part_name, 'res': res})
            raise dexc.DfaClientRequestFailed(reason=res)

        res = self._delete_org(tenant_name)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s organization in DCNM.", tenant_name)
        else:
            LOG.error("Failed to delete %(org)s organization in DCNM."
                      "Response: %(res)s", {'org': tenant_name, 'res': res})
            raise dexc.DfaClientRequestFailed(reason=res)


Instruction:
Make a summary of the following Python 3 code
def delete_partition(self, org_name, partition_name):
        res = self._delete_partition(org_name, partition_name)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Deleted %s partition in DCNM.", partition_name)
        else:
            LOG.error("Failed to delete %(part)s partition in DCNM."
                      "Response: %(res)s",
                      ({'part': partition_name, 'res': res}))
            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))

Response: Send partition delete request to DCNM.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_project(self, orch_id, org_name, part_name, dci_id, desc=None):
        desc = desc or org_name
        res = self._create_org(orch_id, org_name, desc)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Created %s organization in DCNM.", org_name)
        else:
            LOG.error("Failed to create %(org)s organization in DCNM."
                      "Response: %(res)s", {'org': org_name, 'res': res})
            raise dexc.DfaClientRequestFailed(reason=res)

        self.create_partition(org_name, part_name, dci_id,
                              self.default_vrf_profile, desc=desc)

Response: Create a project on the DCNM.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_project(self, org_name, part_name, dci_id=UNKNOWN_DCI_ID,
                       service_node_ip=UNKNOWN_SRVN_NODE_IP,
                       vrf_prof=None, desc=None):
        """Update project on the DCNM.

        :param org_name: name of organization.
        :param part_name: name of partition.
        :param dci_id: Data Center interconnect id.
        :param desc: description of project.
        """
        desc = desc or org_name
        res = self._create_or_update_partition(org_name, part_name, desc,
                                               dci_id=dci_id,
                                               service_node_ip=service_node_ip,
                                               vrf_prof=vrf_prof,
                                               operation='PUT')
        if res and res.status_code in self._resp_ok:
            LOG.debug("Update %s partition in DCNM.", part_name)
        else:
            LOG.error("Failed to update %(part)s partition in DCNM."
                      "Response: %(res)s", {'part': part_name, 'res': res})
            raise dexc.DfaClientRequestFailed(reason=res)

Response: Update the project on the DCNM.


Instruction:
How would you explain what the following Python 3 function does
def create_partition(self, org_name, part_name, dci_id, vrf_prof,
                         service_node_ip=None, desc=None):
        """Create partition on the DCNM.

        :param org_name: name of organization to be created
        :param part_name: name of partition to be created
        :param dci_id: DCI ID
        :vrf_prof: VRF profile for the partition
        :param service_node_ip: Specifies the Default route IP address.
        :param desc: string that describes organization
        """
        desc = desc or org_name
        res = self._create_or_update_partition(org_name, part_name,
                                               desc, dci_id=dci_id,
                                               service_node_ip=service_node_ip,
                                               vrf_prof=vrf_prof)
        if res and res.status_code in self._resp_ok:
            LOG.debug("Created %s partition in DCNM.", part_name)
        else:
            LOG.error("Failed to create %(part)s partition in DCNM."
                      "Response: %(res)s", ({'part': part_name, 'res': res}))
            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))

Response: Create a new partition on the DCNM.


Instruction:
Create a Python 3 function for
getting VRF Profile for the partition from the DCNM.

Response:
def get_partition_vrfProf(self, org_name, part_name=None, part_info=None):
        """get VRF Profile for the partition from the DCNM.

        :param org_name: name of organization
        :param part_name: name of partition
        """
        vrf_profile = None
        if part_info is None:
            part_info = self._get_partition(org_name, part_name)
            LOG.info("query result from dcnm for partition info is %s",
                     part_info)
        if ("vrfProfileName" in part_info):
            vrf_profile = part_info.get("vrfProfileName")
        return vrf_profile


Instruction:
Write a Python 3 function for
getting DCI ID for the partition.

Response:
def get_partition_dciId(self, org_name, part_name, part_info=None):
        """get DCI ID for the partition.

        :param org_name: name of organization
        :param part_name: name of partition
        """
        if part_info is None:
            part_info = self._get_partition(org_name, part_name)
            LOG.info("query result from dcnm for partition info is %s",
                     part_info)
        if part_info is not None and "dciId" in part_info:
            return part_info.get("dciId")


Instruction:
Explain what the following Python 3 code does
def list_networks(self, org, part):
        if org and part:
            list_url = self._del_part + '/networks'
            list_url = list_url % (org, part)
            res = self._send_request('GET', list_url, '', 'networks')
            if res and res.status_code in self._resp_ok:
                return res.json()

Response: Return list of networks from DCNM.


Instruction:
Can you tell what is the following Python 3 function doing
def list_organizations(self):

        try:
            res = self._send_request('GET', self._org_url, '', 'organizations')
            if res and res.status_code in self._resp_ok:
                return res.json()
        except dexc.DfaClientRequestFailed:
            LOG.error("Failed to send request to DCNM.")

Response: Return list of organizations from DCNM.


Instruction:
How would you implement a function in Python 3 that
gets the given network from DCNM.

Response:
def get_network(self, org, segid):
        """Return given network from DCNM.

        :param org: name of organization.
        :param segid: segmentation id of the network.
        """
        network_info = {
            'organizationName': org,
            'partitionName': self._part_name,
            'segmentId': segid,
        }
        res = self._get_network(network_info)
        if res and res.status_code in self._resp_ok:
            return res.json()


Instruction:
Can you write a function in Python 3 where it
gets the DCNM version.

Response:
def get_version(self):
        """Get the DCNM version."""

        url = '%s://%s/rest/dcnm-version' % (self.dcnm_protocol, self._ip)
        payload = {}

        try:
            res = self._send_request('GET', url, payload, 'dcnm-version')
            if res and res.status_code in self._resp_ok:
                return res.json().get('Dcnm-Version')
        except dexc.DfaClientRequestFailed as exc:
            LOG.error("Failed to get DCNM version.")
            sys.exit("ERROR: Failed to connect to DCNM: %s", exc)


Instruction:
How would you explain what the following Python 3 function does
def fill_urls(self):

        protocol = self.dcnm_protocol
        self._org_url = '%s://%s/rest/auto-config/organizations' % (
            (protocol, self._ip))
        self._create_network_url = ('%s://%s/' % (protocol, self._ip) +
                                    'rest/auto-config/organizations'
                                    '/%s/partitions/%s/networks')
        self.host_protocol_url = '%s://%s/' % (protocol, self._ip)
        self._create_network_url = self._build_url(
            'rest/auto-config/organizations'
            '/%s/partitions/%s/networks')
        self._cfg_profile_list_url = '%s://%s/rest/auto-config/profiles' % (
            (protocol, self._ip))
        self._cfg_profile_get_url = self._cfg_profile_list_url + '/%s'
        self._global_settings_url = self._build_url(
            'rest/auto-config/settings')
        self._create_part_url = self._build_url(
            'rest/auto-config/organizations/%s/partitions')
        self._update_part_url = self._build_url(
            'rest/auto-config/organizations/%s/partitions/%s')
        self._del_org_url = self._build_url(
            'rest/auto-config/organizations/%s')
        self._del_part = self._build_url(
            'rest/auto-config/organizations/%s/partitions/%s')
        self._network_url = self._build_url(
            'rest/auto-config/organizations/%s/partitions/'
            '%s/networks/segment/%s')
        self._network_mob_url = self._build_url(
            'rest/auto-config/organizations/%s/partitions/'
            '%s/networks/vlan/%s/mobility-domain/%s')
        self._segmentid_ranges_url = self._build_url(
            'rest/settings/segmentid-ranges')
        self._login_url = self._build_url('rest/logon')
        self._logout_url = self._build_url('rest/logout')

Response: This method assigns the URL s based on the protocol and IP.


Instruction:
Can you write a function in Python 3 where it
returns a list of tuples that is built based on retrieved tables where column with name tenant_id exists.

Response:
def get_data():
    """Returns combined list of tuples: [(table, column)].
    List is built, based on retrieved tables, where column with name
    ``tenant_id`` exists.
    """

    output = []
    tables = get_tables()
    for table in tables:
        columns = get_columns(table)

        for column in columns:
            if column['name'] == 'tenant_id':
                output.append((table, column))

    return output


Instruction:
Implement a Python 3 function for
notifying the Cisco cfg agent handling a particular hosting_device.

Response:
def _agent_notification_bulk(self, context, method, routers,
                                 hosting_device, operation):
        """Notify the Cisco cfg agent handling a particular hosting_device.

        A single notification can contain multiple routers.
        """
        admin_context = context.is_admin and context or context.elevated()
        dmplugin = bc.get_plugin(cisco_constants.DEVICE_MANAGER)
        if (hosting_device is not None and extensions.is_extension_supported(
                dmplugin, CFGAGENT_SCHED)):
            agents = dmplugin.get_cfg_agents_for_hosting_devices(
                admin_context, [hosting_device['id']], admin_state_up=True,
                schedule=True)
            if agents:
                agent = agents[0]
                LOG.debug('Notify %(agent_type)s at %(topic)s.%(host)s the '
                          'message %(method)s [BULK]',
                          {'agent_type': agent.agent_type,
                           'topic': CFG_AGENT_L3_ROUTING,
                           'host': agent.host,
                           'method': method})
                cctxt = self.client.prepare(server=agent.host,
                                            version='1.1')
                cctxt.cast(context, method, routers=routers)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _notification(self, context, method, routers, operation,
                      shuffle_agents):
        """Notify all or individual Cisco cfg agents."""
        if extensions.is_extension_supported(self._l3plugin, L3AGENT_SCHED):
            adm_context = (context.is_admin and context or context.elevated())
            # This is where hosting device gets scheduled to Cisco cfg agent
            self._l3plugin.schedule_routers(adm_context, routers)
            self._agent_notification(
                context, method, routers, operation, shuffle_agents)
        else:
            cctxt = self.client.prepare(topics=topics.L3_AGENT, fanout=True)
            cctxt.cast(context, method, routers=[r['id'] for r in routers])

Response: Notify all or individual Cisco cfg agents.


Instruction:
Here you have a function in Python 3, explain what it does
def routers_updated(self, context, routers, operation=None, data=None,
                        shuffle_agents=False):
        """Notify cfg agents about configuration changes to routers.

        This includes operations performed on the router like when a
        router interface is added or removed.
        """
        if routers:
            self._notification(context, 'routers_updated', routers, operation,
                               shuffle_agents)

Response: Notify cfg agents about routers configuration changes.


Instruction:
Write a Python 3 script to
notify cfg agent about router removed from hosting device.

Response:
def router_removed_from_hosting_device(self, context, router):
        """Notify cfg agent about router removed from hosting device."""
        self._notification(context, 'router_removed_from_hosting_device',
                           [router], operation=None, shuffle_agents=False)


Instruction:
Can you create a Python 3 function that
notifies cfg agent about router added to hosting device.

Response:
def router_added_to_hosting_device(self, context, router):
        """Notify cfg agent about router added to hosting device."""
        self._notification(context, 'router_added_to_hosting_device',
                           [router], operation=None, shuffle_agents=False)


Instruction:
Implement a Python 3 function for
notifying cfg agent that routers have been removed from hosting device.

Response:
def routers_removed_from_hosting_device(self, context, router_ids,
                                            hosting_device):
        """Notify cfg agent that routers have been removed from hosting device.
        @param: context - information about tenant, user etc
        @param: router-ids - list of ids
        @param: hosting_device - device hosting the routers
        """
        self._agent_notification_bulk(
            context, 'router_removed_from_hosting_device', router_ids,
            hosting_device, operation=None)


Instruction:
Implement a Python 3 function for
processing the messages in the queue and call callbacks to process them.

Response:
def process_amqp_msgs(self):
        """Process AMQP queue messages.

        It connects to AMQP server and calls callbacks to process DCNM events,
        i.e. routing key containing '.cisco.dcnm.', once they arrive in the
        queue.
        """

        LOG.info('Starting process_amqp_msgs...')
        while True:
            (mtd_fr, hdr_fr, body) = (None, None, None)
            try:
                if self.consume_channel:
                    (mtd_fr, hdr_fr, body) = self.consume_channel.basic_get(
                        self._dcnm_queue_name)
                if mtd_fr:
                    # Queue has messages.
                    LOG.info('RX message: %s', body)
                    self._cb_dcnm_msg(mtd_fr, body)
                    self.consume_channel.basic_ack(mtd_fr.delivery_tag)
                else:
                    # Queue is empty.
                    try:
                        self._conn.sleep(1)
                    except AttributeError:
                        time.sleep(1)
            except Exception:
                exc_type, exc_value, exc_tb = sys.exc_info()
                tb_str = traceback.format_exception(exc_type,
                                                    exc_value, exc_tb)
                LOG.exception("Failed to read from queue: %(queue)s "
                              "%(exc_type)s, %(exc_value)s, %(exc_tb)s.", {
                                  'queue': self._dcnm_queue_name,
                                  'exc_type': exc_type,
                                  'exc_value': exc_value,
                                  'exc_tb': tb_str})


Instruction:
Can you implement a function in Python 3 that
checks whether an IP address is reachable by pinging.

Response:
def _is_pingable(ip):
    """Checks whether an IP address is reachable by pinging.

    Use linux utils to execute the ping (ICMP ECHO) command.
    Sends 5 packets with an interval of 0.2 seconds and timeout of 1
    seconds. Runtime error implies unreachability else IP is pingable.
    :param ip: IP to check
    :return: bool - True or False depending on pingability.
    """
    ping_cmd = ['ping',
                '-c', '5',
                '-W', '1',
                '-i', '0.2',
                ip]
    try:
        linux_utils.execute(ping_cmd, check_exit_code=True)
        return True
    except RuntimeError:
        LOG.warning("Cannot ping ip address: %s", ip)
        return False


Instruction:
Write a Python 3 script for
checking if a TCP port at IP address is possible to connect to the base TCP server.

Response:
def _can_connect(ip, port):
    """Checks if a TCP port at IP address is possible to connect to"""
    cs = socket.socket()
    try:
        cs.connect((ip, port))
        cs.close()
        return True
    except socket.error:
        return False


Instruction:
Implement a function in Python 3 to
get a list of dead hosting devices that have been marked dead.

Response:
def get_dead_hosting_devices_info(self):
        """
        Get a list of hosting devices that have been marked dead
        :return: List of dead hosting device ids
        """
        res = []
        for hd_id in self.hosting_devices_backlog:
            hd = self.hosting_devices_backlog[hd_id]['hd']
            if hd['hd_state'] == cc.HD_DEAD:
                res.append(hd['id'])
        return res


Instruction:
Can you generate the documentation for the following Python 3 function
def is_hosting_device_reachable(self, hosting_device):
        ret_val = False

        hd = hosting_device
        hd_id = hosting_device['id']
        hd_mgmt_ip = hosting_device['management_ip_address']

        dead_hd_list = self.get_dead_hosting_devices_info()
        if hd_id in dead_hd_list:
            LOG.debug("Hosting device: %(hd_id)s@%(ip)s is already marked as"
                      " Dead. It is assigned as non-reachable",
                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})
            return False

        # Modifying the 'created_at' to a date time object if it is not
        if not isinstance(hd['created_at'], datetime.datetime):
            hd['created_at'] = datetime.datetime.strptime(hd['created_at'],
                                                          '%Y-%m-%d %H:%M:%S')

        if _is_pingable(hd_mgmt_ip):
            LOG.debug("Hosting device: %(hd_id)s@%(ip)s is reachable.",
                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})
            hd['hd_state'] = cc.HD_ACTIVE
            ret_val = True
        else:
            LOG.debug("Hosting device: %(hd_id)s@%(ip)s is NOT reachable.",
                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})
            hd['hd_state'] = cc.HD_NOT_RESPONDING
            ret_val = False

        if self.enable_heartbeat is True or ret_val is False:
            self.backlog_hosting_device(hd)

        return ret_val

Response: Check the hosting device which hosts this resource is reachable.


Instruction:
Write a Python 3 script to
check the status of the backlogged hosting devices.

Response:
def check_backlogged_hosting_devices(self, driver_mgr):
        """Checks the status of backlogged hosting devices.

        Skips newly spun up instances during their booting time as specified
        in the boot time parameter.

        Each hosting-device tracked has a key, hd_state, that represents the
        last known state for the hosting device.  Valid values for hd_state
        are ['Active', 'Unknown', 'Dead']

        Each time check_backlogged_hosting_devices is invoked, a ping-test
        is performed to determine the current state.  If the current state
        differs, hd_state is updated.

        The hd_state transitions/actions are represented by the following
        table.

        +------------+---------------------+----------------+----------------+
        | current /  | Active              | Unknown        | Dead           |
        | last state |                     |                |                |
        +============+=====================+================+================+
        | Active     | Device is reachable.| Device was     | Dead device    |
        |            | No state change     | temporarily    | recovered.     |
        |            |                     | unreachable.   | Trigger resync |
        +------------+---------------------+----------------+----------------+
        | Unknown    | Device connectivity | Device         | Not a valid    |
        |            | test failed.  Set   | connectivity   | state          |
        |            | backlog timestamp   | test failed.   | transition.    |
        |            | and wait for dead   | Dead timeout   |                |
        |            | timeout to occur.   | has not        |                |
        |            |                     | occurred yet.  |                |
        +------------+---------------------+----------------+----------------+
        | Dead       | Not a valid state   | Dead timeout   | Device is      |
        |            | transition.         | for device has | still dead.    |
        |            |                     | elapsed.       | No state       |
        |            |                     | Notify plugin  | change.        |
        +------------+---------------------+----------------+----------------+

        :returns: A dict of the format:

        ::

          {"reachable": [<hd_id>,..],
          "dead": [<hd_id>,..],
          "revived": [<hd_id>,..]}

        * reachable - a list of hosting devices that are now reachable
        * dead      - a list of hosting devices deemed dead
        * revived   - a list of hosting devices (dead to active)
        """
        response_dict = {'reachable': [], 'revived': [], 'dead': []}
        LOG.debug("Current Backlogged hosting devices: \n%s\n",
                  self.hosting_devices_backlog.keys())
        for hd_id in self.hosting_devices_backlog.keys():
            hd = self.hosting_devices_backlog[hd_id]['hd']
            if not timeutils.is_older_than(hd['created_at'],
                                           hd['booting_time']):
                LOG.info("Hosting device: %(hd_id)s @ %(ip)s hasn't "
                         "passed minimum boot time. Skipping it. ",
                         {'hd_id': hd_id, 'ip': hd['management_ip_address']})
                continue
            LOG.info("Checking hosting device: %(hd_id)s @ %(ip)s for "
                     "reachability.", {'hd_id': hd_id,
                                       'ip': hd['management_ip_address']})
            hd_state = hd['hd_state']
            if _is_pingable(hd['management_ip_address']):
                if hd_state == cc.HD_NOT_RESPONDING:
                    LOG.debug("hosting devices revived & reachable, %s" %
                              (pprint.pformat(hd)))
                    hd['hd_state'] = cc.HD_ACTIVE
                    # hosting device state
                    response_dict['reachable'].append(hd_id)
                elif hd_state == cc.HD_DEAD:
                    # test if management port is available
                    if _can_connect(hd['management_ip_address'],
                                    hd['protocol_port']) is True:
                        LOG.debug("Dead hosting devices revived %s" %
                                  (pprint.pformat(hd)))
                        hd['hd_state'] = cc.HD_ACTIVE
                        response_dict['revived'].append(hd_id)
                    else:
                        LOG.debug("Cannot connect to management port %(p)d on "
                                  "hosting device with ip %(ip)s",
                                  {'p': hd['protocol_port'],
                                   'ip': hd['management_ip_address']})
                else:
                    LOG.debug("No-op."
                              "_is_pingable is True and current"
                              " hd['hd_state']=%s" % hd_state)

                LOG.info("Hosting device: %(hd_id)s @ %(ip)s is now "
                         "reachable. Adding it to response",
                         {'hd_id': hd_id, 'ip': hd['management_ip_address']})
            else:
                LOG.info("Hosting device: %(hd_id)s %(hd_state)s"
                         " @ %(ip)s not reachable ",
                         {'hd_id': hd_id,
                          'hd_state': hd['hd_state'],
                          'ip': hd['management_ip_address']})
                if hd_state == cc.HD_ACTIVE:
                    LOG.debug("hosting device lost connectivity, %s" %
                              (pprint.pformat(hd)))
                    hd['backlog_insertion_ts'] = timeutils.utcnow()
                    hd['hd_state'] = cc.HD_NOT_RESPONDING

                elif hd_state == cc.HD_NOT_RESPONDING:
                    if timeutils.is_older_than(
                            hd['backlog_insertion_ts'],
                            cfg.CONF.cfg_agent.hosting_device_dead_timeout):
                        # current hd_state is now dead, previous state: Unknown
                        hd['hd_state'] = cc.HD_DEAD
                        LOG.debug("Hosting device: %(hd_id)s @ %(ip)s hasn't "
                                  "been reachable for the "
                                  "last %(time)d seconds. "
                                  "Marking it dead.",
                                  {'hd_id': hd_id,
                                   'ip': hd['management_ip_address'],
                                   'time': cfg.CONF.cfg_agent.
                                   hosting_device_dead_timeout})
                        response_dict['dead'].append(hd_id)
        LOG.debug("Response: %s", response_dict)
        return response_dict


Instruction:
Write a Python 3 function that can
create a floating IP object.

Response:
def create_floatingip(self, context, floatingip):
        """Create floating IP.

        :param context: Neutron request context
        :param floatingip: data for the floating IP being created
        :returns: A floating IP object on success

        As the l3 router plugin asynchronously creates floating IPs
        leveraging the l3 agent and l3 cfg agent, the initial status for the
        floating IP object will be DOWN.
        """
        return super(CiscoRouterPlugin, self).create_floatingip(
            context, floatingip,
            initial_status=bc.constants.FLOATINGIP_STATUS_DOWN)


Instruction:
Here you have a function in Python 3, explain what it does
def attach_intf_router(self, tenant_id, tenant_name, router_id):
        in_sub = self.get_in_subnet_id(tenant_id)
        out_sub = self.get_out_subnet_id(tenant_id)
        # Modify Hard coded Name fixme
        subnet_lst = set()
        subnet_lst.add(in_sub)
        subnet_lst.add(out_sub)
        ret = self.os_helper.add_intf_router(router_id, tenant_id, subnet_lst)
        return ret, in_sub, out_sub

Response: Routine to attach the interface to the router.


Instruction:
Can you implement a function in Python 3 that
retrieves the router ID.

Response:
def get_router_id(self, tenant_id, tenant_name):
        """Retrieve the router ID. """
        router_id = None
        if tenant_id in self.tenant_dict:
            router_id = self.tenant_dict.get(tenant_id).get('router_id')
        if not router_id:
            router_list = self.os_helper.get_rtr_by_name(
                'FW_RTR_' + tenant_name)
            if len(router_list) > 0:
                router_id = router_list[0].get('id')
        return router_id


Instruction:
Can you tell what is the following Python 3 function doing
def delete_intf_router(self, tenant_id, tenant_name, router_id):
        in_sub = self.get_in_subnet_id(tenant_id)
        out_sub = self.get_out_subnet_id(tenant_id)
        subnet_lst = set()
        subnet_lst.add(in_sub)
        subnet_lst.add(out_sub)
        router_id = self.get_router_id(tenant_id, tenant_name)
        if router_id:
            ret = self.os_helper.delete_intf_router(tenant_name, tenant_id,
                                                    router_id, subnet_lst)
            if not ret:
                LOG.error("Failed to delete router intf id %(rtr)s, "
                          "tenant %(tenant)s",
                          {'rtr': router_id, 'tenant': tenant_id})
            return ret
        LOG.error("Invalid router ID, can't delete interface from "
                  "router")

Response: Routine to delete the router.


Instruction:
How would you code a function in Python 3 to
send the native FW message to the queue.

Response:
def send_router_port_msg(self, tenant_id, tenant_name, router_id, net_id,
                             subnet_id, seg, status):
        """Sends the router port message to the queue. """
        data = self.prepare_router_vm_msg(tenant_id, tenant_name, router_id,
                                          net_id, subnet_id, seg, status)
        if data is None:
            return False
        timestamp = time.ctime()
        pri = Q_PRIORITY
        LOG.info("Sending native FW data into queue %(data)s",
                 {'data': data})
        self.que_obj.put((pri, timestamp, data))
        return True


Instruction:
Explain what the following Python 3 code does
def update_dcnm_partition_static_route(self, tenant_id, arg_dict):
        ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,
                                                     arg_dict.get('excl_list'))
        srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
        ret = self.dcnm_obj.update_partition_static_route(
            arg_dict.get('tenant_name'), fw_const.SERV_PART_NAME, ip_list,
            vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
            service_node_ip=srvc_node_ip)
        if not ret:
            LOG.error("Unable to update DCNM ext profile with static "
                      "route %s", arg_dict.get('router_id'))
            self.delete_intf_router(tenant_id, arg_dict.get('tenant_name'),
                                    arg_dict.get('router_id'))
            return False
        return True

Response: Update DCNM partition static route in DCNM s partition.


Instruction:
Can you generate the documentation for the following Python 3 function
def _create_arg_dict(self, tenant_id, data, in_sub, out_sub):
        in_seg, in_vlan = self.get_in_seg_vlan(tenant_id)
        out_seg, out_vlan = self.get_out_seg_vlan(tenant_id)
        in_ip_dict = self.get_in_ip_addr(tenant_id)
        out_ip_dict = self.get_out_ip_addr(tenant_id)
        excl_list = [in_ip_dict.get('subnet'), out_ip_dict.get('subnet')]

        arg_dict = {'tenant_id': tenant_id,
                    'tenant_name': data.get('tenant_name'),
                    'in_seg': in_seg, 'in_vlan': in_vlan,
                    'out_seg': out_seg, 'out_vlan': out_vlan,
                    'router_id': data.get('router_id'),
                    'in_sub': in_sub, 'out_sub': out_sub,
                    'in_gw': in_ip_dict.get('gateway'),
                    'out_gw': out_ip_dict.get('gateway'),
                    'excl_list': excl_list}
        return arg_dict

Response: Create the argument dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_fw(self, tenant_id, data):
        try:
            return self._create_fw(tenant_id, data)
        except Exception as exc:
            LOG.error("Failed to create FW for device native, tenant "
                      "%(tenant)s data %(data)s Exc %(exc)s",
                      {'tenant': tenant_id, 'data': data, 'exc': exc})
            return False

Response: Top level routine called when a FW is created.


Instruction:
Can you tell what is the following Python 3 function doing
def delete_fw(self, tenant_id, data):
        try:
            ret = self._delete_fw(tenant_id, data)
            return ret
        except Exception as exc:
            LOG.error("Failed to delete FW for device native, tenant "
                      "%(tenant)s data %(data)s Exc %(exc)s",
                      {'tenant': tenant_id, 'data': data, 'exc': exc})
            return False

Response: Top level routine called when a FW is deleted.


Instruction:
Create a Python 3 function for
programing DCNM static route.

Response:
def _program_dcnm_static_route(self, tenant_id, tenant_name):
        """Program DCNM Static Route. """
        in_ip_dict = self.get_in_ip_addr(tenant_id)
        in_gw = in_ip_dict.get('gateway')
        in_ip = in_ip_dict.get('subnet')
        if in_gw is None:
            LOG.error("No FW service GW present")
            return False
        out_ip_dict = self.get_out_ip_addr(tenant_id)
        out_ip = out_ip_dict.get('subnet')

        # Program DCNM to update profile's static IP address on OUT part
        excl_list = []
        excl_list.append(in_ip)
        excl_list.append(out_ip)
        subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
                                                        excl_part=True)
        # This count is for telling DCNM to insert the static route in a
        # particular position. Total networks created - exclusive list as
        # above - the network that just got created.
        srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
        ret = self.dcnm_obj.update_partition_static_route(
            tenant_name, fw_const.SERV_PART_NAME, subnet_lst,
            vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
            service_node_ip=srvc_node_ip)
        if not ret:
            LOG.error("Unable to update DCNM ext profile with static "
                      "route")
            return False
        return True


Instruction:
Make a summary of the following Python 3 code
def network_create_notif(self, tenant_id, tenant_name, cidr):
        router_id = self.get_router_id(tenant_id, tenant_name)
        if not router_id:
            LOG.error("Rout ID not present for tenant")
            return False
        ret = self._program_dcnm_static_route(tenant_id, tenant_name)
        if not ret:
            LOG.error("Program DCNM with static routes failed "
                      "for router %s", router_id)
            return False

        # Program router namespace to have this network to be routed
        # to IN service network
        in_ip_dict = self.get_in_ip_addr(tenant_id)
        in_gw = in_ip_dict.get('gateway')
        if in_gw is None:
            LOG.error("No FW service GW present")
            return False
        ret = self.os_helper.program_rtr_nwk_next_hop(router_id, in_gw, cidr)
        if not ret:
            LOG.error("Unable to program default router next hop %s",
                      router_id)
            return False
        return True

Response: Tenant Network create Notification.


Instruction:
How would you explain what the following Python 3 function does
def network_delete_notif(self, tenant_id, tenant_name, network_id):
        router_id = self.get_router_id(tenant_id, tenant_name)
        if router_id is None:
            LOG.error("Rout ID not present for tenant")
            return False
        ret = self._program_dcnm_static_route(tenant_id, tenant_name)
        if not ret:
            LOG.error("Program DCNM with static routes failed for "
                      "router %s", router_id)
            return False

        # Program router namespace to have this network to be routed
        # to IN service network
        in_ip_dict = self.get_in_ip_addr(tenant_id)
        in_gw = in_ip_dict.get('gateway')
        in_ip = in_ip_dict.get('subnet')
        if in_gw is None:
            LOG.error("No FW service GW present")
            return False
        out_ip_dict = self.get_out_ip_addr(tenant_id)
        out_ip = out_ip_dict.get('subnet')
        excl_list = []
        excl_list.append(in_ip)
        excl_list.append(out_ip)
        subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
                                                        excl_part=True)
        ret = self.os_helper.remove_rtr_nwk_next_hop(router_id, in_gw,
                                                     subnet_lst, excl_list)
        if not ret:
            LOG.error("Unable to program default router next hop %s",
                      router_id)
            return False
        return True

Response: Tenant Network delete Notification.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_hosting_device_resources(self, context, complementary_id,
                                        tenant_id, mgmt_context, max_hosted):
        """Create resources for a hosting device in a plugin specific way."""
        mgmt_port = None
        if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_id:
            # Create port for mgmt interface
            p_spec = {'port': {
                'tenant_id': tenant_id,
                'admin_state_up': True,
                'name': 'mgmt',
                'network_id': mgmt_context['mgmt_nw_id'],
                'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
                'fixed_ips': self._mgmt_subnet_spec(context, mgmt_context),
                'device_id': "",
                # Use device_owner attribute to ensure we can query for these
                # ports even before Nova has set device_id attribute.
                'device_owner': complementary_id}}
            try:
                mgmt_port = self._core_plugin.create_port(context, p_spec)
            except n_exc.NeutronException as e:
                LOG.error('Error %s when creating management port. '
                          'Cleaning up.', e)
                self.delete_hosting_device_resources(
                    context, tenant_id, mgmt_port)
                mgmt_port = None
        # We are setting the 'ports' to an empty list as it is expected by
        # the callee: device_handling_db._create_svc_vm_hosting_devices()
        return {'mgmt_port': mgmt_port, 'ports': []}

Response: Create resources for a hosting device in a specific way.


Instruction:
Implement a Python 3 function for
returning information about all resources for a hosting device.

Response:
def get_hosting_device_resources(self, context, id, complementary_id,
                                     tenant_id, mgmt_nw_id):
        """Returns information about all resources for a hosting device."""
        mgmt_port = None
        # Ports for hosting device may not yet have 'device_id' set to
        # Nova assigned uuid of VM instance. However, those ports will still
        # have 'device_owner' attribute set to complementary_id. Hence, we
        # use both attributes in the query to ensure we find all ports.
        query = context.session.query(models_v2.Port)
        query = query.filter(expr.or_(
            models_v2.Port.device_id == id,
            models_v2.Port.device_owner == complementary_id))
        for port in query:
            if port['network_id'] != mgmt_nw_id:
                raise Exception
            else:
                mgmt_port = port
        return {'mgmt_port': mgmt_port}


Instruction:
How would you implement a function in Python 3 that
deletes resources for a hosting device in a plugin specific way.

Response:
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port,
                                        **kwargs):
        """Deletes resources for a hosting device in a plugin specific way."""

        if mgmt_port is not None:
            try:
                self._cleanup_hosting_port(context, mgmt_port['id'])
            except n_exc.NeutronException as e:
                LOG.error("Unable to delete port:%(port)s after %(tries)d"
                          " attempts due to exception %(exception)s. "
                          "Skipping it", {'port': mgmt_port['id'],
                                          'tries': DELETION_ATTEMPTS,
                                          'exception': str(e)})


Instruction:
Can you generate the documentation for the following Python 3 function
def setup_logical_port_connectivity(self, context, port_db,
                                        hosting_device_id):
        """Establishes connectivity for a logical port.

        This is done by hot plugging the interface(VIF) corresponding to the
        port from the VM.
        """
        hosting_port = port_db.hosting_info.hosting_port
        if hosting_port:
            try:
                self._dev_mgr.svc_vm_mgr.interface_attach(hosting_device_id,
                                                          hosting_port.id)
                LOG.debug("Setup logical port completed for port:%s",
                          port_db.id)
            except nova_exc.Conflict as e:
                # VM is still in vm_state building
                LOG.debug("Failed to attach interface - spawn thread "
                          "error %(error)s", {'error': str(e)})
                self._gt_pool.spawn_n(self._attach_hosting_port,
                                      hosting_device_id, hosting_port.id)
            except Exception as e:
                LOG.error("Failed to attach interface mapped to port:"
                          "%(p_id)s on hosting device:%(hd_id)s due to "
                          "error %(error)s", {'p_id': hosting_port.id,
                                              'hd_id': hosting_device_id,
                                              'error': str(e)})

Response: Setup connectivity for a logical port.


Instruction:
Here you have a function in Python 3, explain what it does
def teardown_logical_port_connectivity(self, context, port_db,
                                           hosting_device_id):
        """Removes connectivity for a logical port.

        Unplugs the corresponding data interface from the VM.
        """
        if port_db is None or port_db.get('id') is None:
            LOG.warning("Port id is None! Cannot remove port "
                        "from hosting_device:%s", hosting_device_id)
            return
        hosting_port_id = port_db.hosting_info.hosting_port.id
        try:
            self._dev_mgr.svc_vm_mgr.interface_detach(hosting_device_id,
                                                      hosting_port_id)
            self._gt_pool.spawn_n(self._cleanup_hosting_port, context,
                                  hosting_port_id)
            LOG.debug("Teardown logicalport completed for port:%s", port_db.id)

        except Exception as e:
            LOG.error("Failed to detach interface corresponding to port:"
                      "%(p_id)s on hosting device:%(hd_id)s due to "
                      "error %(error)s", {'p_id': hosting_port_id,
                                          'hd_id': hosting_device_id,
                                          'error': str(e)})

Response: Removes connectivity for a logical port.


Instruction:
Given the following Python 3 function, write the documentation
def allocate_hosting_port(self, context, router_id, port_db, network_type,
                              hosting_device_id):
        """Allocates a hosting port for a logical port.

        We create a hosting port for the router port
        """
        l3admin_tenant_id = self._dev_mgr.l3_tenant_id()
        hostingport_name = 'hostingport_' + port_db['id'][:8]
        p_spec = {'port': {
                  'tenant_id': l3admin_tenant_id,
                  'admin_state_up': True,
                  'name': hostingport_name,
                  'network_id': port_db['network_id'],
                  'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
                  'fixed_ips': [],
                  'device_id': '',
                  'device_owner': '',
                  'port_security_enabled': False}}
        try:
            hosting_port = self._core_plugin.create_port(context, p_spec)
        except n_exc.NeutronException as e:
            LOG.error('Error %s when creating hosting port'
                      'Cleaning up.', e)
            self.delete_hosting_device_resources(
                context, l3admin_tenant_id, hosting_port)
            hosting_port = None
        finally:
            if hosting_port:
                return {'allocated_port_id': hosting_port['id'],
                        'allocated_vlan': None}
            else:
                return None

Response: Allocates a hosting port for a logical port.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def disable(self, retain_port=False):
        self.update_server(disabled=True)
        if retain_port:
            return
        self.update_device(disabled=True)
        if self.conf.dhcp_delete_namespaces and self.network.namespace:
            ns_ip = ip_lib.IPWrapper(self.root_helper,
                                     self.network.namespace)
            try:
                ns_ip.netns.delete(self.network.namespace)
            except RuntimeError:
                msg = _('Failed trying to delete namespace: %s')
                LOG.exception(msg, self.network.namespace)

Response: Teardown DHCP. This method disables DHCP for this network.


Instruction:
Can you create a Python 3 function that
creates global dict to track device names across driver invocations and populates based on current devices configured on the system.

Response:
def recover_devices(cls):
        """Track devices.

        Creates global dict to track device names across driver invocations
        and populates based on current devices configured on the system.
        """

        if "_devices" in globals():
            return

        global _devices
        confs_dir = os.path.abspath(os.path.normpath(cfg.CONF.dhcp_confs))
        for netid in os.listdir(confs_dir):
            conf_dir = os.path.join(confs_dir, netid)
            intf_filename = os.path.join(conf_dir, 'interface')
            try:
                with open(intf_filename, 'r') as f:
                    ifname = f.read()
                _devices[netid] = ifname
            except IOError:
                LOG.error('Unable to read interface file: %s',
                          intf_filename)
            LOG.debug("Recovered device %s for network %s'",
                      ifname, netid)


Instruction:
Create a Python 3 function to
check server version against minimum required version.

Response:
def check_version(cls):
        """Checks server version against minimum required version."""
        super(SimpleCpnrDriver, cls).check_version()
        model.configure_pnr()
        cls.recover_networks()
        ver = model.get_version()
        if ver < cls.MIN_VERSION:
            LOG.warning("CPNR version does not meet minimum requirements, "
                        "expected: %(ever)f, actual: %(rver)f",
                        {'ever': cls.MIN_VERSION, 'rver': ver})
        return ver


Instruction:
How would you implement a function in Python 3 that
returns a list of existing networks ids that we have configs for.

Response:
def existing_dhcp_networks(cls, conf):
        """Return a list of existing networks ids that we have configs for."""
        global _networks
        sup = super(SimpleCpnrDriver, cls)
        superkeys = sup.existing_dhcp_networks(conf)
        return set(_networks.keys()) & set(superkeys)


Instruction:
Write a Python 3 function that can
update server with latest network configuration.

Response:
def _unsafe_update_server(self, disabled=False):
        """Update server with latest network configuration."""
        id = self.network.id
        net = model.Network.from_neutron(self.network)
        if id not in _networks:
            if disabled:
                return
            _networks[id] = net
            _networks[id].create()
        elif disabled:
            _networks[id].delete()
            del _networks[id]
        else:
            _networks[id].update(net)
            _networks[id] = net


Instruction:
Create a Python 3 function for
creating the openstack network including the subnet.

Response:
def create_network(self, name, tenant_id, subnet, gw=None):
        """Create the openstack network, including the subnet. """

        try:
            body = {'network': {'name': name, 'tenant_id': tenant_id,
                                'admin_state_up': True}}
            netw = self.neutronclient.create_network(body=body)
            net_dict = netw.get('network')
            net_id = net_dict.get('id')
        except Exception as exc:
            LOG.error("Failed to create network %(name)s, Exc %(exc)s",
                      {'name': name, 'exc': str(exc)})
            return None, None

        try:
            if gw is None:
                body = {'subnet': {'cidr': subnet,
                                   'ip_version': 4,
                                   'network_id': net_id,
                                   'tenant_id': tenant_id,
                                   'enable_dhcp': False}}
            else:
                body = {'subnet': {'cidr': subnet,
                                   'ip_version': 4,
                                   'network_id': net_id,
                                   'tenant_id': tenant_id,
                                   'enable_dhcp': False,
                                   'gateway_ip': gw}}
            subnet_ret = self.neutronclient.create_subnet(body=body)
            subnet_dict = subnet_ret.get('subnet')
            subnet_id = subnet_dict.get('id')
        except Exception as exc:
            LOG.error("Failed to create subnet %(sub)s, exc %(exc)s",
                      {'sub': subnet, 'exc': str(exc)})
            try:
                self.neutronclient.delete_network(net_id)
            except Exception as exc:
                LOG.error("Failed to delete network %(net)s, exc %(exc)s",
                          {'net': net_id, 'exc': str(exc)})
            return None, None
        return net_id, subnet_id


Instruction:
Here you have a function in Python 3, explain what it does
def delete_network(self, name, tenant_id, subnet_id, net_id):
        try:
            self.neutronclient.delete_subnet(subnet_id)
        except Exception as exc:
            LOG.error("Failed to delete subnet %(sub)s exc %(exc)s",
                      {'sub': subnet_id, 'exc': str(exc)})
            return
        try:
            self.neutronclient.delete_network(net_id)
        except Exception as exc:
            LOG.error("Failed to delete network %(name)s exc %(exc)s",
                      {'name': name, 'exc': str(exc)})

Response: Delete the openstack subnet and network.


Instruction:
How would you explain what the following Python 3 function does
def delete_network_all_subnets(self, net_id):
        try:
            body = {'network_id': net_id}
            subnet_list = self.neutronclient.list_subnets(body=body)
            subnet_list = subnet_list.get('subnets')
            for subnet in subnet_list:
                if subnet.get('network_id') == net_id:
                    subnet_id = subnet.get('id')
                    self.neutronclient.delete_subnet(subnet_id)
        except Exception as exc:
            LOG.error("Failed to delete subnet for net %(net)s "
                      "Exc %(exc)s", {'net': net_id, 'exc': str(exc)})
            return False
        try:
            self.neutronclient.delete_network(net_id)
        except Exception as exc:
            LOG.error("Failed to delete network %(net)s Exc %(exc)s",
                      {'net': net_id, 'exc': str(exc)})
            return False
        return True

Response: Delete the openstack network including all its subnets.


Instruction:
Here you have a function in Python 3, explain what it does
def is_subnet_present(self, subnet_addr):
        try:
            subnet_list = self.neutronclient.list_subnets(body={})
            subnet_dat = subnet_list.get('subnets')
            for sub in subnet_dat:
                if sub.get('cidr') == subnet_addr:
                    return True
            return False
        except Exception as exc:
            LOG.error("Failed to list subnet %(sub)s, Exc %(exc)s",
                      {'sub': subnet_addr, 'exc': str(exc)})
            return False

Response: Returns if a subnet is present.


Instruction:
Implement a Python 3 function for
returning all the subnets.

Response:
def get_all_subnets_cidr(self, no_mask=False):
        """Returns all the subnets. """
        body = {}
        subnet_cidrs = []
        try:
            subnet_list = self.neutronclient.list_subnets(body=body)
            subnet_dat = subnet_list.get('subnets')
            for sub in subnet_dat:
                if no_mask:
                    subnet_cidrs.append(sub.get('cidr').split('/')[0])
                else:
                    subnet_cidrs.append(sub.get('cidr'))
        except Exception as exc:
            LOG.error("Failed to list subnet Exc %s", str(exc))
        return subnet_cidrs


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_subnets_for_net(self, net):
        try:
            subnet_list = self.neutronclient.list_subnets(network_id=net)
            subnet_dat = subnet_list.get('subnets')
            return subnet_dat
        except Exception as exc:
            LOG.error("Failed to list subnet net %(net)s, Exc: %(exc)s",
                      {'net': net, 'exc': str(exc)})
            return None

Response: Returns the subnets in a network.


Instruction:
Given the following Python 3 function, write the documentation
def get_subnet_cidr(self, subnet_id):
        try:
            subnet_list = self.neutronclient.list_subnets(id=subnet_id)
            subnet_dat = subnet_list.get('subnets')[0]
            return subnet_dat.get('cidr')
        except Exception as exc:
            LOG.error("Failed to list subnet for ID %(subnet)s, "
                      "exc %(exc)s", {'subnet': subnet_id, 'exc': exc})
            return None

Response: retrieve the CIDR associated with a subnet given its ID.


Instruction:
Here you have a function in Python 3, explain what it does
def delete_network_subname(self, sub_name):
        try:
            body = {}
            net_list = self.neutronclient.list_networks(body=body)
            for net in net_list:
                if net.get('name').find(sub_name) != -1:
                    self.delete_network_all_subnets(net.get('net_id'))
        except Exception as exc:
            LOG.error("Failed to get network by subname %(name)s, "
                      "Exc %(exc)s",
                      {'name': sub_name, 'exc': str(exc)})

Response: Delete the network by part of its name use with caution.


Instruction:
Can you write a function in Python 3 where it
searches for a openstack network by name.

Response:
def get_network_by_name(self, nwk_name):
        """Search for a openstack network by name. """
        ret_net_lst = []
        try:
            body = {}
            net_list = self.neutronclient.list_networks(body=body)
            net_list = net_list.get('networks')
            for net in net_list:
                if net.get('name') == nwk_name:
                    ret_net_lst.append(net)
        except Exception as exc:
            LOG.error("Failed to get network by name %(name)s, "
                      "Exc %(exc)s",
                      {'name': nwk_name, 'exc': str(exc)})
        return ret_net_lst


Instruction:
Implement a function in Python 3 to
return the list of networks in a given tenant.

Response:
def get_network_by_tenant(self, tenant_id):
        """Returns the network of a given tenant. """
        ret_net_lst = []
        try:
            net_list = self.neutronclient.list_networks(body={})
            for net in net_list.get('networks'):
                if net.get('tenant_id') == tenant_id:
                    ret_net_lst.append(net)
        except Exception as exc:
            LOG.error("Failed to get network by tenant %(tenant)s, "
                      "Exc %(exc)s",
                      {'tenant': tenant_id, 'exc': str(exc)})
        return ret_net_lst


Instruction:
Write a Python 3 function for
searching a router by its name.

Response:
def get_rtr_by_name(self, rtr_name):
        """Search a router by its name. """
        upd_rtr_list = []
        try:
            rtr_list = self.neutronclient.list_routers()
            for rtr in rtr_list.get('routers'):
                if rtr_name == rtr['name']:
                    upd_rtr_list.append(rtr)
        except Exception as exc:
            LOG.error("Failed to get router by name %(name)s, "
                      "Exc %(exc)s",
                      {'name': rtr_name, 'exc': str(exc)})
        return upd_rtr_list


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_router(self, name, tenant_id, subnet_lst):
        try:
            body = {'router': {'name': name, 'tenant_id': tenant_id,
                               'admin_state_up': True}}
            router = self.neutronclient.create_router(body=body)
            rout_dict = router.get('router')
            rout_id = rout_dict.get('id')
        except Exception as exc:
            LOG.error("Failed to create router with name %(name)s"
                      " Exc %(exc)s", {'name': name, 'exc': str(exc)})
            return None

        ret = self.add_intf_router(rout_id, tenant_id, subnet_lst)
        if not ret:
            try:
                ret = self.neutronclient.delete_router(rout_id)
            except Exception as exc:
                LOG.error("Failed to delete router %(name)s, Exc %(exc)s",
                          {'name': name, 'exc': str(exc)})
            return None
        return rout_id

Response: Create a openstack router and add the interfaces.


Instruction:
Explain what the following Python 3 code does
def add_intf_router(self, rout_id, tenant_id, subnet_lst):
        try:
            for subnet_id in subnet_lst:
                body = {'subnet_id': subnet_id}
                intf = self.neutronclient.add_interface_router(rout_id,
                                                               body=body)
                intf.get('port_id')
        except Exception as exc:
            LOG.error("Failed to create router intf ID %(id)s,"
                      " Exc %(exc)s", {'id': rout_id, 'exc': str(exc)})
            return False
        return True

Response: Add the interfaces to a router.


Instruction:
Write a Python 3 script to
delete the openstack router and remove the interfaces attached to it.

Response:
def delete_router(self, name, tenant_id, rout_id, subnet_lst):
        """Delete the openstack router.

        Delete the router and remove the interfaces attached to it.
        """
        ret = self.delete_intf_router(name, tenant_id, rout_id, subnet_lst)
        if not ret:
            return False

        try:
            ret = self.neutronclient.delete_router(rout_id)
        except Exception as exc:
            LOG.error("Failed to delete router %(name)s ret %(ret)s "
                      "Exc %(exc)s",
                      {'name': name, 'ret': str(ret), 'exc': str(exc)})
            return False
        return True


Instruction:
Can you implement a function in Python 3 that
deletes the openstack router and remove the interfaces attached.

Response:
def delete_intf_router(self, name, tenant_id, rout_id, subnet_lst):
        """Delete the openstack router and remove the interfaces attached. """
        try:
            for subnet_id in subnet_lst:
                body = {'subnet_id': subnet_id}
                intf = self.neutronclient.remove_interface_router(rout_id,
                                                                  body=body)
                intf.get('id')
        except Exception as exc:
            LOG.error("Failed to delete router interface %(name)s, "
                      " Exc %(exc)s", {'name': name, 'exc': str(exc)})
            return False
        return True