
from __future__ import absolute_import
from __future__ import division

import io
import logging

from vdsm.network.link import dpdk
from vdsm.network.link.iface import iface


class ReadSpeedValueError(Exception):
    pass


def speed(nic_name):
    interface = iface(nic_name)
    if interface.is_oper_up():
        if dpdk.is_dpdk(nic_name):
            return dpdk.speed(nic_name)
        try:
            return read_speed_using_sysfs(nic_name)
        except Exception:
            logging.debug('cannot read %s speed', nic_name)
    return 0


def read_speed_using_sysfs(nic_name):
    with io.open('/sys/class/net/%s/speed' % nic_name) as f:
        s = int(f.read())
    if s in (2 ** 16 - 1, 2 ** 32 - 1) or s <= 0:
        raise ReadSpeedValueError(s)
    return s


def duplex(nic_name):
    try:
        with open('/sys/class/net/%s/duplex' % nic_name) as f:
            return f.read().strip()
    except IOError:
        return 'unknown'
