Get subnet details.
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
783969
def get_subnets():
        
        LOGGER.debug("SubnetService.get_subnets")
        args = {'http_operation': 'GET', 'operation_path': ''}
        response = SubnetService.requester.call(args)
        ret = None
        if response.rc == 0:
            ret = []
            for subnet in response.response_content['subnets']:
                ret.append(Subnet.json_2_subnet(subnet))
        elif response.rc != 404:
            err_msg = 'SubnetService.get_subnets - Problem while getting subnets. ' \
                      '. Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \
                      " (" + str(response.rc) + ")"
            LOGGER.warning(err_msg)
        return ret
280614
def subnets_list(resource_group_name, vnet_name, address_prefix = nil)
      list = network_resource_client.subnets.list(resource_group_name, vnet_name)
      !address_prefix.nil? && !list.empty? ? subnets_list_for_specific_address_space(address_prefix, list) : list
    end
1236897
def get_bgp_neighbors_detail(self, neighbor_address=""):
        """"""
        bgp_neighbors = {}
        default_neighbor_details = {
            "up": False,
            "local_as": 0,
            "remote_as": 0,
            "router_id": "",
            "local_address": "",
            "routing_table": "",
            "local_address_configured": False,
            "local_port": 0,
            "remote_address": "",
            "remote_port": 0,
            "multihop": False,
            "multipath": False,
            "remove_private_as": False,
            "import_policy": "",
            "export_policy": "",
            "input_messages": -1,
            "output_messages": -1,
            "input_updates": -1,
            "output_updates": -1,
            "messages_queued_out": -1,
            "connection_state": "",
            "previous_connection_state": "",
            "last_event": "",
            "suppress_4byte_as": False,
            "local_as_prepend": False,
            "holdtime": 0,
            "configured_holdtime": 0,
            "keepalive": 0,
            "configured_keepalive": 0,
            "active_prefix_count": -1,
            "received_prefix_count": -1,
            "accepted_prefix_count": -1,
            "suppressed_prefix_count": -1,
            "advertised_prefix_count": -1,
            "flap_count": 0,
        }
        OPTION_KEY_MAP = {
            "RemovePrivateAS": "remove_private_as",
            "Multipath": "multipath",
            "Multihop": "multihop",
            "AddressFamily": "local_address_configured"
            # 'AuthKey'        : 'authentication_key_set'
            # but other vendors do not specify if auth key is set
            # other options:
            # Preference, HoldTime, Ttl, LogUpDown, Refresh
        }

        def _bgp_iter_core(neighbor_data, instance=None):
            """
            Iterate over a list of neighbors.
            For older junos, the routing instance is not specified inside the
            BGP neighbors XML, therefore we need to use a super sub-optimal structure
            as in get_bgp_neighbors: iterate through the list of network instances
            then execute one request for each and every routing instance.
            For newer junos, this is not necessary as the routing instance is available
            and we can get everything solve in a single request.
            """
            for bgp_neighbor in neighbor_data:
                remote_as = int(bgp_neighbor[0])
                neighbor_details = deepcopy(default_neighbor_details)
                neighbor_details.update(
                    {
                        elem[0]: elem[1]
                        for elem in bgp_neighbor[1]
                        if elem[1] is not None
                    }
                )
                if not instance:
                    peer_fwd_rti = neighbor_details.pop("peer_fwd_rti")
                    instance = peer_fwd_rti
                else:
                    peer_fwd_rti = neighbor_details.pop("peer_fwd_rti", "")
                instance_name = "global" if instance == "master" else instance
                options = neighbor_details.pop("options", "")
                if isinstance(options, str):
                    options_list = options.split()
                    for option in options_list:
                        key = OPTION_KEY_MAP.get(option)
                        if key is not None:
                            neighbor_details[key] = True
                four_byte_as = neighbor_details.pop("4byte_as", 0)
                local_address = neighbor_details.pop("local_address", "")
                local_details = local_address.split("+")
                neighbor_details["local_address"] = napalm.base.helpers.convert(
                    napalm.base.helpers.ip, local_details[0], local_details[0]
                )
                if len(local_details) == 2:
                    neighbor_details["local_port"] = int(local_details[1])
                else:
                    neighbor_details["local_port"] = 179
                neighbor_details["suppress_4byte_as"] = remote_as != four_byte_as
                peer_address = neighbor_details.pop("peer_address", "")
                remote_details = peer_address.split("+")
                neighbor_details["remote_address"] = napalm.base.helpers.convert(
                    napalm.base.helpers.ip, remote_details[0], remote_details[0]
                )
                if len(remote_details) == 2:
                    neighbor_details["remote_port"] = int(remote_details[1])
                else:
                    neighbor_details["remote_port"] = 179
                neighbor_details["routing_table"] = instance_name
                neighbor_details["local_as"] = napalm.base.helpers.as_number(
                    neighbor_details["local_as"]
                )
                neighbor_details["remote_as"] = napalm.base.helpers.as_number(
                    neighbor_details["remote_as"]
                )
                neighbors_rib = neighbor_details.pop("rib")
                neighbors_queue = neighbor_details.pop("queue")
                messages_queued_out = 0
                for queue_entry in neighbors_queue.items():
                    messages_queued_out += queue_entry[1][0][1]
                neighbor_details["messages_queued_out"] = messages_queued_out
                if instance_name not in bgp_neighbors.keys():
                    bgp_neighbors[instance_name] = {}
                if remote_as not in bgp_neighbors[instance_name].keys():
                    bgp_neighbors[instance_name][remote_as] = []
                neighbor_rib_stats = neighbors_rib.items()
                if not neighbor_rib_stats:
                    bgp_neighbors[instance_name][remote_as].append(neighbor_details)
                    continue  # no RIBs available, pass default details
                neighbor_rib_details = {
                    "active_prefix_count": 0,
                    "received_prefix_count": 0,
                    "accepted_prefix_count": 0,
                    "suppressed_prefix_count": 0,
                    "advertised_prefix_count": 0,
                }
                for rib_entry in neighbor_rib_stats:
                    for elem in rib_entry[1]:
                        if elem[1] is None:
                            neighbor_rib_details[elem[0]] += 0
                        else:
                            neighbor_rib_details[elem[0]] += elem[1]
                neighbor_details.update(neighbor_rib_details)
                bgp_neighbors[instance_name][remote_as].append(neighbor_details)

        # old_junos = napalm.base.helpers.convert(
        #     int, self.device.facts.get('version', '0.0').split('.')[0], 0) < 15
        bgp_neighbors_table = junos_views.junos_bgp_neighbors_table(self.device)

        # if old_junos:
        instances = junos_views.junos_route_instance_table(self.device)
        for instance, instance_data in instances.get().items():
            if instance.startswith("__"):
                # junos internal instances
                continue
            neighbor_data = bgp_neighbors_table.get(
                instance=instance, neighbor_address=str(neighbor_address)
            ).items()
            _bgp_iter_core(neighbor_data, instance=instance)
        # else:
        #     bgp_neighbors_table = junos_views.junos_bgp_neighbors_table(self.device)
        #     neighbor_data = bgp_neighbors_table.get(neighbor_address=neighbor_address).items()
        #     _bgp_iter_core(neighbor_data)
        return bgp_neighbors
813172
def get_network(self, org, segid):
        
        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()
99654
def get_internal_ip():
    """"""
    nics = {}
    for interface_name in interfaces():
        addresses = ifaddresses(interface_name)
        try:
            nics[interface_name] = {
                'ipv4': addresses[AF_INET],
                'link_layer': addresses[AF_LINK],
                'ipv6': addresses[AF_INET6],
            }
        except KeyError:
            pass

    return nics
108754
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
295157
def ec2_subnet_subnet_id(self, lookup, default=None):
    
    subnets = EFAwsResolver.__CLIENTS["ec2"].describe_subnets(Filters=[{
      'Name': 'tag:Name',
      'Values': [lookup]
    }])
    if len(subnets["Subnets"]) > 0:
      return subnets["Subnets"][0]["SubnetId"]
    else:
      return default
303309
def get_instance_subnet_name(self, instance):
        
        # TODO: we have to do this here since we are monkeypatching Instance.
        # If we switch to custom Instance (sub)class then we could do it in the
        # object, provided it has access to the configuration data.
        if instance.subnet_id:
            # Account for omitted 'subnet-'
            subnet = self.config['subnets'][instance.subnet_id[7:]]
        else:
            subnet = BLANK
        return subnet
445588
def gather_details():
    """"""
    try:
        data = {
            'kernel': platform.uname(),
            'distribution': platform.linux_distribution(),
            'libc': platform.libc_ver(),
            'arch': platform.machine(),
            'python_version': platform.python_version(),
            'os_name': platform.system(),
            'static_hostname': platform.node(),
            'cpu': platform.processor(),
            'fqdn': socket.getfqdn(),
        }
    except AttributeError:
        return {}

    return data
79683
def get_out_subnet_id(cls, tenant_id):
        
        if 'out' not in cls.ip_db_obj:
            LOG.error("Fabric not prepared for tenant %s", tenant_id)
            return None
        db_obj = cls.ip_db_obj.get('out')
        out_subnet_dict = cls.get_out_ip_addr(tenant_id)
        sub = db_obj.get_subnet(out_subnet_dict.get('subnet'))
        return sub.subnet_id
1137639
def getNetworkSummary(self, suid, verbose=None):
        

        surl=self.___url
        sv=surl.split('/')[-1]
        surl=surl.rstrip(sv+'/')
        response=api(url=surl+'/cyndex2/'+sv+'/networks/'+str(suid)+'', method="GET", verbose=verbose, parse_params=False)
        return response
404937
def _configure_subnet(config):
    """"""

    # Rationale: avoid subnet lookup if the network is already
    # completely manually configured
    if ("networkInterfaces" in config["head_node"]
            and "networkInterfaces" in config["worker_nodes"]):
        return config

    subnets = _list_subnets(config)

    if not subnets:
        raise NotImplementedError("Should be able to create subnet.")

    # TODO: make sure that we have usable subnet. Maybe call
    # compute.subnetworks().listUsable? For some reason it didn't
    # work out-of-the-box
    default_subnet = subnets[0]

    if "networkInterfaces" not in config["head_node"]:
        config["head_node"]["networkInterfaces"] = [{
            "subnetwork": default_subnet["selfLink"],
            "accessConfigs": [{
                "name": "External NAT",
                "type": "ONE_TO_ONE_NAT",
            }],
        }]

    if "networkInterfaces" not in config["worker_nodes"]:
        config["worker_nodes"]["networkInterfaces"] = [{
            "subnetwork": default_subnet["selfLink"],
            "accessConfigs": [{
                "name": "External NAT",
                "type": "ONE_TO_ONE_NAT",
            }],
        }]

    return config
145821
def get_computer_network_details
      network_adapters = []
      response = rest_get('/redfish/v1/Systems/1/NetworkAdapters/')
      networks = response_handler(response)['links']['Member']
      networks.each do |network|
        response = rest_get(network['href'])
        detail = response_handler(response)
        physical_ports = []
        detail['PhysicalPorts'].each do |port|
          n = {
            'Name' => port['Name'],
            'StructuredName' => port['Oem']['Hp']['StructuredName'],
            'MacAddress' => port['MacAddress'],
            'State' => port['Status']['State']
          }
          physical_ports.push(n)
        end
        nets = {
          'Name' => detail['Name'],
          'StructuredName' => detail['StructuredName'],
          'PartNumber' => detail['PartNumber'],
          'State' => detail['Status']['State'],
          'Health' => detail['Status']['Health'],
          'PhysicalPorts' => physical_ports
        }
        network_adapters.push(nets)
      end
      {
        'NetworkAdapters' => network_adapters
      }
    end
613683
def ips(self):
        """"""
        r = []
        names = ['X_FORWARDED_FOR', 'CLIENT_IP', 'X_REAL_IP', 'X_FORWARDED', 
               'X_CLUSTER_CLIENT_IP', 'FORWARDED_FOR', 'FORWARDED', 'VIA',
               'REMOTE_ADDR']

        for name in names:
            vs = self.get_header(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

            vs = self.environ.get(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

        return r
682811
def __get_subnetwork(vm_):
    '''
    
    '''
    ex_subnetwork = config.get_cloud_config_value(
        'subnetwork', vm_, __opts__,
        search_global=False)

    return ex_subnetwork
65883
def network_details():
        
        # Get IPv4 details
        ipv4_addresses = [
            info[4][0]
            for info in socket.getaddrinfo(
                socket.gethostname(), None, socket.AF_INET
            )
        ]

        # Add localhost
        ipv4_addresses.extend(
            info[4][0]
            for info in socket.getaddrinfo("localhost", None, socket.AF_INET)
        )

        # Filter addresses
        ipv4_addresses = sorted(set(ipv4_addresses))

        try:
            # Get IPv6 details
            ipv6_addresses = [
                info[4][0]
                for info in socket.getaddrinfo(
                    socket.gethostname(), None, socket.AF_INET6
                )
            ]

            # Add localhost
            ipv6_addresses.extend(
                info[4][0]
                for info in socket.getaddrinfo(
                    "localhost", None, socket.AF_INET6
                )
            )

            # Filter addresses
            ipv6_addresses = sorted(set(ipv6_addresses))
        except (socket.gaierror, AttributeError):
            # AttributeError: AF_INET6 is missing in some versions of Python
            ipv6_addresses = None

        return {
            "IPv4": ipv4_addresses,
            "IPv6": ipv6_addresses,
            "host.name": socket.gethostname(),
            "host.fqdn": socket.getfqdn(),
        }