Return RDSI Operational Stats for interface.
        
        @param iface: Interface name. (Ex. w1g1)
        @return:      Nested dictionary of statistics for interface.
166457
def getPRIstats(self, iface):
        
        info_dict = {}
        output = util.exec_command([wanpipemonCmd, '-i', iface, '-c',  'Ta'])
        for line in output.splitlines():
            mobj = re.match('^\s*(Line Code Violation|Far End Block Errors|'
                            'CRC4 Errors|FAS Errors)\s*:\s*(\d+)\s*$', 
                            line, re.IGNORECASE)
            if mobj:
                info_dict[mobj.group(1).lower().replace(' ', '')] = int(mobj.group(2))
                continue
            mobj = re.match('^\s*(Rx Level)\s*:\s*>{0,1}\s*([-\d\.]+)db\s*', 
                            line, re.IGNORECASE)
            if mobj:
                info_dict[mobj.group(1).lower().replace(' ', '')] = float(mobj.group(2))
                continue
        return info_dict
402401
def interface_ip(iface):
    '''
    
    '''
    iface_info, error = _get_iface_info(iface)

    if error is False:
        inet = iface_info.get(iface, {}).get('inet', None)
        return inet[0].get('address', '') if inet else ''
    else:
        return error
1062846
def getProcessStats(self):
        
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            data = fp.read()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        for line in data.splitlines():
            arr = line.split()
            if len(arr) > 1 and arr[0] in ('ctxt', 'intr', 'softirq',
                                           'processes', 'procs_running', 
                                           'procs_blocked'):
                info_dict[arr[0]] = arr[1]
        return info_dict
1105273
def _ip_ifaces():
    '''
    
    '''
    tmp = {}
    ret = {}
    if_ = None
    at_ = None
    out = __salt__['cmd.run']('ip a')
    for line in out.splitlines():
        if not line.startswith(' '):
            comps = line.split(':')
            if_ = comps[1].strip()
            opts_comps = comps[2].strip().split()
            flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',')
            opts_iter = iter(opts_comps)
            ret[if_] = {
                'flags': flags,
                'options': dict(list(zip(opts_iter, opts_iter)))
            }
        else:
            if line.strip().startswith('link'):
                comps = iter(line.strip().split())
                ret[if_]['link_layer'] = dict(list(zip(comps, comps)))
            elif line.strip().startswith('inet'):
                comps = line.strip().split()
                at_ = comps[0]
                if len(comps) % 2 != 0:
                    last = comps.pop()
                    comps[-1] += ' {0}'.format(last)
                ifi = iter(comps)
                ret[if_][at_] = dict(list(zip(ifi, ifi)))
            else:
                comps = line.strip().split()
                ifi = iter(comps)
                ret[if_][at_].update(dict(list(zip(ifi, ifi))))
    return ret
1046356
def network_io_counters(interface=None):
    '''
    
    '''
    if not interface:
        return dict(psutil.net_io_counters()._asdict())
    else:
        stats = psutil.net_io_counters(pernic=True)
        if interface in stats:
            return dict(stats[interface]._asdict())
        else:
            return False
1017596
def _get_nest_stats(self):
        
        for x in self.rdict:
            check = urlparse(x)
            if check.scheme:
                nested_dict = self.rdict[x]['nestedStats']
                tmp_dict = nested_dict['entries']
                return self._key_dot_replace(tmp_dict)

        return self._key_dot_replace(self.rdict)
448959
def interfaces_info():
    
    def replace(value):
        if value == netifaces.AF_LINK:
            return 'link'
        if value == netifaces.AF_INET:
            return 'ipv4'
        if value == netifaces.AF_INET6:
            return 'ipv6'
        return value

    results = {}
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        results[iface] = {replace(k): v for k, v in addrs.items()}

    return results
982451
def in6_ifaceidtomac(ifaceid): # TODO: finish commenting function behavior
    
    try:
        ifaceid = inet_pton(socket.AF_INET6, "::"+ifaceid)[8:16]
    except:
        return None
    if ifaceid[3:5] != b'\xff\xfe':
        return None
    first = struct.unpack("B", ifaceid[:1])[0]
    ulbit = 2*[1,'-',0][first & 0x02]
    first = struct.pack("B", ((first & 0xFD) | ulbit))
    oui = first + ifaceid[1:3]
    end = ifaceid[5:]
    #l = map(lambda x: "%.02x" % struct.unpack("B", x)[0], list(oui+end))
    l = map(lambda x: "%.02x" % x, list(oui+end))
    return ":".join(l)
1022882
def provider_of(iface):
    
    def check(value):
        return (
            iface.providedBy(value),
            u"{value!r} does not provide {interface!s}".format(
                value=value,
                interface=fullyQualifiedName(iface),
            ),
        )
    return check
719827
def set_iface_monitor(iface, monitor):
    
    mode = get_iface_mode(iface)
    if mode == "unknown":
        warning("Could not parse iwconfig !")
    current_monitor = mode == "monitor"
    if monitor == current_monitor:
        # Already correct
        return True
    s_mode = "monitor" if monitor else "managed"

    def _check_call(commands):
        p = subprocess.Popen(commands,
                             stderr=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode != 0:
            warning("%s failed !" % " ".join(commands))
            return False
        return True
    try:
        assert _check_call(["ifconfig", iface, "down"])
        assert _check_call(["iwconfig", iface, "mode", s_mode])
        assert _check_call(["ifconfig", iface, "up"])
        return True
    except AssertionError:
        return False
273340
def get_bond(iface):
    '''
    
    '''
    path = os.path.join(_DEB_NETWORK_CONF_FILES, '{0}.conf'.format(iface))
    return _read_file(path)
739083
def output_iface(gandi, iface, datacenters, vms, output_keys, justify=10):
    
    output_generic(gandi, iface, output_keys, justify)

    if 'vm' in output_keys:
        vm_name = vms.get(iface['vm_id'], {}).get('hostname')
        if vm_name:
            output_line(gandi, 'vm', vm_name, justify)

    if 'dc' in output_keys:
        for dc in datacenters:
            if dc['id'] == iface.get('datacenter_id',
                                     iface.get('datacenter', {}).get('id')):
                dc_name = dc.get('dc_code', dc.get('iso', ''))
                break

        output_line(gandi, 'datacenter', dc_name, justify)

    if 'vlan_' in output_keys:
        vlan = iface.get('vlan') or {}
        output_line(gandi, 'vlan', vlan.get('name', '-'), justify)
1231798
def _parse_settings_eth(opts, iface_type, enabled, iface):
    '''
    
    '''
    adapters = salt.utils.odict.OrderedDict()
    adapters[iface] = salt.utils.odict.OrderedDict()

    adapters[iface]['type'] = iface_type

    adapters[iface]['data'] = salt.utils.odict.OrderedDict()
    iface_data = adapters[iface]['data']
    iface_data['inet'] = salt.utils.odict.OrderedDict()
    iface_data['inet6'] = salt.utils.odict.OrderedDict()

    if enabled:
        adapters[iface]['enabled'] = True

    if opts.get('hotplug', False):
        adapters[iface]['hotplug'] = True

    if opts.get('enable_ipv6', None) and opts.get('iface_type', '') == 'vlan':
        iface_data['inet6']['vlan_raw_device'] = (
            re.sub(r'\.\d*', '', iface))

    for addrfam in ['inet', 'inet6']:
        if iface_type not in ['bridge']:
            tmp_ethtool = _parse_ethtool_opts(opts, iface)
            if tmp_ethtool:
                ethtool = {}
                for item in tmp_ethtool:
                    ethtool[_ETHTOOL_CONFIG_OPTS[item]] = tmp_ethtool[item]

                iface_data[addrfam]['ethtool'] = ethtool
                # return a list of sorted keys to ensure consistent order
                iface_data[addrfam]['ethtool_keys'] = sorted(ethtool)

        if iface_type == 'bridge':
            bridging = _parse_bridge_opts(opts, iface)
            if bridging:
                iface_data[addrfam]['bridging'] = bridging
                iface_data[addrfam]['bridging_keys'] = sorted(bridging)
                iface_data[addrfam]['addrfam'] = addrfam

        elif iface_type == 'bond':
            bonding = _parse_settings_bond(opts, iface)
            if bonding:
                iface_data[addrfam]['bonding'] = bonding
                iface_data[addrfam]['bonding']['slaves'] = opts['slaves']
                iface_data[addrfam]['bonding_keys'] = sorted(bonding)
                iface_data[addrfam]['addrfam'] = addrfam

        elif iface_type == 'slave':
            adapters[iface]['master'] = opts['master']

            opts['proto'] = 'manual'
            iface_data[addrfam]['master'] = adapters[iface]['master']
            iface_data[addrfam]['addrfam'] = addrfam

        elif iface_type == 'vlan':
            iface_data[addrfam]['vlan_raw_device'] = re.sub(r'\.\d*', '', iface)
            iface_data[addrfam]['addrfam'] = addrfam

        elif iface_type == 'pppoe':
            tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface)
            if tmp_ethtool:
                for item in tmp_ethtool:
                    adapters[iface]['data'][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = tmp_ethtool[item]
            iface_data[addrfam]['addrfam'] = addrfam

    opts.pop('mode', None)

    for opt, val in opts.items():
        inet = None
        if opt.startswith('ipv4'):
            opt = opt[4:]
            inet = 'inet'
            iface_data['inet']['addrfam'] = 'inet'
        elif opt.startswith('ipv6'):
            iface_data['inet6']['addrfam'] = 'inet6'
            opt = opt[4:]
            inet = 'inet6'
        elif opt in ['ipaddr', 'address', 'ipaddresses', 'addresses', 'gateway', 'proto']:
            iface_data['inet']['addrfam'] = 'inet'
            inet = 'inet'

        _opt = SALT_ATTR_TO_DEBIAN_ATTR_MAP.get(opt, opt)
        _debopt = _opt.replace('-', '_')

        for addrfam in ['inet', 'inet6']:
            (valid, value, errmsg) = _validate_interface_option(_opt, val, addrfam=addrfam)
            if not valid:
                continue
            if inet is None and _debopt not in iface_data[addrfam]:
                iface_data[addrfam][_debopt] = value
            elif inet == addrfam:
                iface_data[addrfam][_debopt] = value

    for opt in ['up_cmds', 'pre_up_cmds', 'post_up_cmds',
                'down_cmds', 'pre_down_cmds', 'post_down_cmds']:
        if opt in opts:
            iface_data['inet'][opt] = opts[opt]
            iface_data['inet6'][opt] = opts[opt]

    # Remove incomplete/disabled inet blocks
    for (addrfam, opt) in [('inet', 'enable_ipv4'), ('inet6', 'enable_ipv6')]:
        if opts.get(opt, None) is False:
            iface_data.pop(addrfam)
        elif iface_data[addrfam].get('addrfam', '') != addrfam:
            iface_data.pop(addrfam)

    return adapters
357684
def get_stats(self):
        """"""

        try:
            ret = fcntl.ioctl(self.ins, BIOCGSTATS, struct.pack("2I", 0, 0))
            return struct.unpack("2I", ret)
        except IOError:
            warning("Unable to get stats from BPF !")
            return (None, None)
2908
def ParseIfaddrs(ifaddrs):
  
  precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs))

  ifaces = {}

  for ifaddr in IterIfaddrs(ifaddrs):
    ifname = ctypes.string_at(ifaddr.ifa_name).decode("utf-8")
    iface = ifaces.setdefault(ifname, rdf_client_network.Interface())
    iface.ifname = ifname

    if not ifaddr.ifa_addr:
      continue

    sockaddr = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddr))
    iffamily = sockaddr.contents.sa_family
    if iffamily == AF_INET:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET
      address.packed_bytes = struct.pack("=L", sockaddrin.contents.sin_addr)
      iface.addresses.append(address)
    elif iffamily == AF_INET6:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin6))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET6
      address.packed_bytes = bytes(list(sockaddrin.contents.sin6_addr))
      iface.addresses.append(address)
    elif iffamily == AF_LINK:
      sockaddrdl = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrdl))

      nlen = sockaddrdl.contents.sdl_nlen
      alen = sockaddrdl.contents.sdl_alen
      iface.mac_address = bytes(sockaddrdl.contents.sdl_data[nlen:nlen + alen])
    else:
      raise ValueError("Unexpected socket address family: %s" % iffamily)

  return itervalues(ifaces)
338291
def parse_interface(iface):
    
    sections = [ ]
    docs = iface['comment']
    code = '<span class="k">interface</span> <span class="gs">%s</span> {\n' % iface['name']
    for v in iface["functions"]:
        func_code = '    <span class="nf">%s</span>(' % v['name']
        i = 0
        for p in v["params"]:
            if i == 0: i = 1
            else: func_code += ", "
            func_code += '<span class="na">%s</span> <span class="kt">%s</span>' % (p['name'], format_type(p))
        func_code += ') <span class="kt">%s</span>\n' % format_type(v['returns'])
        if v.has_key('comment') and v['comment']:
            if code:
                sections.append(to_section(docs, code))
            docs = v['comment']
            code = func_code
        else:
            code += func_code
    code += "}"

    sections.append(to_section(docs, code))
    return sections
1050729
def get_stats(self):
        
        sent = ctypes.c_uint32()
        recv = ctypes.c_uint32()
        send_errors = ctypes.c_uint32()
        recv_errors = ctypes.c_uint32()
        result = self.library.Par_GetStats(self.pointer, ctypes.byref(sent),
                                   ctypes.byref(recv),
                                   ctypes.byref(send_errors),
                                   ctypes.byref(recv_errors))
        check_error(result, "partner")
        return sent, recv, send_errors, recv_errors