Exemple #1
0
    def lookup(self, name):
        if encode_value(name) not in map(encode_value, ethtool.get_devices()):
            raise NotFoundError('KCHIFACE0001E', {'name': name})

        ipaddr = ''
        netmask = ''
        module = 'unknown'
        status = 'down'
        try:
            ipaddr = ethtool.get_ipaddr(encode_value(name))
            netmask = ethtool.get_netmask(encode_value(name))
            module = ethtool.get_module(encode_value(name))

            flags = ethtool.get_flags(encode_value(name))
            status = 'up' if flags & (ethtool.IFF_RUNNING
                                      | ethtool.IFF_UP) else 'down'
        except IOError:
            pass

        iface_type = netinfo.get_interface_type(name)

        return {
            'name': name,
            'type': iface_type,
            'status': status,
            'ipaddr': ipaddr,
            'netmask': netmask,
            'module': module,
        }
Exemple #2
0
    def lookup(self, name):
        if encode_value(name) not in map(encode_value, ethtool.get_devices()):
            raise NotFoundError("KCHIFACE0001E", {'name': name})

        ipaddr = ''
        netmask = ''
        module = 'unknown'
        status = 'down'
        try:
            ipaddr = ethtool.get_ipaddr(encode_value(name))
            netmask = ethtool.get_netmask(encode_value(name))
            module = ethtool.get_module(encode_value(name))

            flags = ethtool.get_flags(encode_value(name))
            status = 'up' if flags & (ethtool.IFF_RUNNING | ethtool.IFF_UP) \
                     else 'down'
        except IOError:
            pass

        iface_type = netinfo.get_interface_type(name)

        return {'name': name,
                'type': iface_type,
                'status': status,
                'ipaddr': ipaddr,
                'netmask': netmask,
                'module': module}
def get_bridge_port_device(bridge):
    """Return the nics list that belongs to a port of 'bridge'.

    Args:
        bridge (str): the bridge name.

    Returns:
        List[str]: the nic list.

    """
    #   br  --- v  --- bond --- nic1
    if encode_value(bridge) not in map(encode_value, bridges()):
        raise ValueError('unknown bridge %s' % bridge)
    nics_list = []
    for port in ports(bridge):
        if encode_value(port) in map(encode_value, vlans()):
            device = get_vlan_device(port)
            if encode_value(device) in map(encode_value, bondings()):
                nics_list.extend(slaves(device))
            else:
                nics_list.append(device)
        if encode_value(port) in map(encode_value, bondings()):
            nics_list.extend(slaves(port))
        else:
            nics_list.append(port)
    return nics_list
Exemple #4
0
def get_bridge_port_device(bridge):
    """Return the nics list that belongs to a port of 'bridge'.

    Args:
        bridge (str): the bridge name.

    Returns:
        List[str]: the nic list.

    """
    #   br  --- v  --- bond --- nic1
    if encode_value(bridge) not in map(encode_value, bridges()):
        raise ValueError('unknown bridge %s' % bridge)
    nics_list = []
    for port in ports(bridge):
        if encode_value(port) in map(encode_value, vlans()):
            device = get_vlan_device(port)
            if encode_value(device) in map(encode_value, bondings()):
                nics_list.extend(slaves(device))
            else:
                nics_list.append(device)
        if encode_value(port) in map(encode_value, bondings()):
            nics_list.extend(slaves(port))
        else:
            nics_list.append(port)
    return nics_list
Exemple #5
0
 def activate_iface(self, ifacename):
     wok_log.info('Bring up an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     if iface_type == "nic":
         cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
         out, error, returncode = run_command(cmd_ipup)
         if returncode != 0:
             # non-ascii encoded value and unicode value
             # cannot be concatenated, so convert both variable
             # to one format.
             raise OperationFailed('GINNET0059E', {
                 'name': encode_value(ifacename),
                 'error': encode_value(error)
             })
         # Some times based on system load, it takes few seconds to
         # reflect the  /sys/class/net files upon execution of 'ip link
         # set' command.  Following snippet is to wait util files get
         # reflect.
         timeout = self.wait_time(ifacename)
         if timeout == 5:
             wok_log.warn("Time-out has happened upon execution of 'ip "
                          "link set <interface> up', hence behavior of "
                          "activating an interface may not as expected.")
         else:
             wok_log.info('Successfully brought up the interface ' +
                          ifacename)
     wok_log.info('Activating an interface ' + ifacename)
     cmd_ifup = ['ifup', ifacename]
     out, error, returncode = run_command(cmd_ifup)
     if (returncode == 4):
         raise OperationFailed('GINNET0095E', {'name': ifacename})
     # Timeout is used for carrier file
     # since the carrier file needs few seconds approx 5 sec
     # to update the carrier value of an iface from 0 to 1.
     self.wait_time_carrier(ifacename)
     # Check for the carrier value after the device is activated
     if os.path.isfile(carrier_path % ifacename):
         with open(carrier_path % ifacename) as car_file:
             carrier_val = car_file.readline().strip()
         if (carrier_val == '0'):
             if iface_type != "nic":
                 raise OperationFailed('GINNET0094E', {'name': ifacename})
             else:
                 raise OperationFailed('GINNET0090E', {'name': ifacename})
     else:
         raise OperationFailed('GINNET0091E', {'name': ifacename})
     if returncode != 0:
         raise OperationFailed('GINNET0016E', {
             'name': encode_value(ifacename),
             'error': encode_value(error)
         })
     wok_log.info('Connection successfully activated for the interface ' +
                  ifacename)
 def activate_iface(self, ifacename):
     wok_log.info('Bring up an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     filename = ifcfg_filename_format % ifacename
     filepath = os.sep + network_configpath + filename
     if os.path.exists(filepath):
         if not (os.stat(filepath).st_size == 0):
             wok_log.info('Activating an interface ' + ifacename)
             cmd_ifup = ['ifup', ifacename]
             out, error, returncode = run_command(cmd_ifup)
             if (returncode == 4):
                 raise OperationFailed('GINNET0095E', {'name': ifacename})
             # Timeout is used for carrier file
             # since the carrier file needs few seconds approx 5 sec
             # to update the carrier value of an iface from 0 to 1.
             self.wait_time_carrier(ifacename)
             # Check for the carrier value after the device is activated
             if os.path.isfile(carrier_path % ifacename):
                 with open(carrier_path % ifacename) as car_file:
                     carrier_val = car_file.readline().strip()
                 if (carrier_val == '0'):
                     if iface_type != "nic":
                         raise OperationFailed('GINNET0094E',
                                               {'name': ifacename})
                     else:
                         raise OperationFailed('GINNET0090E',
                                               {'name': ifacename})
             else:
                 raise OperationFailed('GINNET0091E', {'name': ifacename})
             if returncode != 0:
                 raise OperationFailed(
                     'GINNET0016E', {
                         'name': encode_value(ifacename),
                         'error': encode_value(error)
                     })
             wok_log.info('Connection successfully activated for the '
                          'interface ' + ifacename)
         else:
             cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
             out, error, returncode = run_command(cmd_ipup)
             if returncode != 0:
                 raise OperationFailed('GINNET0059E', {'name': ifacename})
             wok_log.info('Connection successfully activated for the '
                          'interface ' + ifacename)
     else:
         cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
         out, error, returncode = run_command(cmd_ipup)
         if returncode != 0:
             raise OperationFailed('GINNET0059E', {'name': ifacename})
         wok_log.info('Connection successfully activated for the '
                      'interface ' + ifacename)
Exemple #7
0
def get_interface_info(iface):
    """Returns information about the interface iface.

    Args:
        iface (str): the interface name.

    Returns:
        dict: a dict containing the interface info. Format:
            {
                'device': (str),
                'name': (str),
                'type': (str),
                'status': (str),
                'link_detected': (str),
                'ipaddr': (str),
                'netmask': (str),
                'macaddr': (str),
                'module': (str),
                'nic_type': (str)
            }

    """
    if encode_value(iface) not in map(encode_value, ethtool.get_devices()):
        raise ValueError('unknown interface: %s' % iface)

    ipaddr = ''
    netmask = ''
    try:
        ipaddr = ethtool.get_ipaddr(encode_value(iface))
        netmask = ethtool.get_netmask(encode_value(iface))
    except IOError:
        pass

    kernel_module = get_interface_kernel_module(iface)
    iface_type = get_interface_type(iface)
    nic_type = 'N/A' if iface_type != 'nic' else get_nic_type(
        iface, kernel_module)

    return {
        'device': iface,
        'name': iface,
        'type': iface_type,
        'status': operstate(iface),
        'link_detected': link_detected(iface),
        'ipaddr': ipaddr,
        'netmask': netmask,
        'macaddr': macaddr(iface),
        'module': kernel_module,
        'nic_type': nic_type
    }
 def activate_iface(self, ifacename):
     wok_log.info('Bring up an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     filename = ifcfg_filename_format % ifacename
     filepath = os.sep + network_configpath + filename
     if os.path.exists(filepath):
         if not (os.stat(filepath).st_size == 0):
             wok_log.info('Activating an interface ' + ifacename)
             cmd_ifup = ['ifup', ifacename]
             out, error, returncode = run_command(cmd_ifup)
             if (returncode == 4):
                 raise OperationFailed('GINNET0095E', {'name': ifacename})
             # Timeout is used for carrier file
             # since the carrier file needs few seconds approx 5 sec
             # to update the carrier value of an iface from 0 to 1.
             self.wait_time_carrier(ifacename)
             # Check for the carrier value after the device is activated
             if os.path.isfile(carrier_path % ifacename):
                 with open(carrier_path % ifacename) as car_file:
                     carrier_val = car_file.readline().strip()
                 if (carrier_val == '0'):
                     if iface_type != "nic":
                         raise OperationFailed('GINNET0094E',
                                               {'name': ifacename})
                     else:
                         raise OperationFailed('GINNET0090E',
                                               {'name': ifacename})
             else:
                 raise OperationFailed('GINNET0091E', {'name': ifacename})
             if returncode != 0:
                 raise OperationFailed('GINNET0016E',
                                       {'name': encode_value(ifacename),
                                        'error': encode_value(error)})
             wok_log.info('Connection successfully activated for the '
                          'interface ' + ifacename)
         else:
             cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
             out, error, returncode = run_command(cmd_ipup)
             if returncode != 0:
                 raise OperationFailed('GINNET0059E', {'name': ifacename})
             wok_log.info('Connection successfully activated for the '
                          'interface ' + ifacename)
     else:
         cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
         out, error, returncode = run_command(cmd_ipup)
         if returncode != 0:
             raise OperationFailed('GINNET0059E', {'name': ifacename})
         wok_log.info('Connection successfully activated for the '
                      'interface ' + ifacename)
 def activate_iface(self, ifacename):
     wok_log.info('Bring up an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     if iface_type == "nic":
         cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
         out, error, returncode = run_command(cmd_ipup)
         if returncode != 0:
             # non-ascii encoded value and unicode value
             # cannot be concatenated, so convert both variable
             # to one format.
             raise OperationFailed('GINNET0059E',
                                   {'name': encode_value(ifacename),
                                    'error': encode_value(error)})
         # Some times based on system load, it takes few seconds to
         # reflect the  /sys/class/net files upon execution of 'ip link
         # set' command.  Following snippet is to wait util files get
         # reflect.
         timeout = self.wait_time(ifacename)
         if timeout == 5:
             wok_log.warn("Time-out has happened upon execution of 'ip "
                          "link set <interface> up', hence behavior of "
                          "activating an interface may not as expected.")
         else:
             wok_log.info('Successfully brought up the interface ' +
                          ifacename)
     wok_log.info('Activating an interface ' + ifacename)
     cmd_ifup = ['ifup', ifacename]
     out, error, returncode = run_command(cmd_ifup)
     # Timeout is used for carrier file
     # since the carrier file needs few seconds approx 5 sec
     # to update the carrier value of an iface from 0 to 1.
     self.wait_time_carrier(ifacename)
     # Check for the carrier value after the device is activated
     if os.path.isfile(carrier_path % ifacename):
         with open(carrier_path % ifacename) as car_file:
             carrier_val = car_file.readline().strip()
         if (carrier_val == '0'):
             if iface_type != "nic":
                 raise OperationFailed('GINNET0094E', {'name': ifacename})
             else:
                 raise OperationFailed('GINNET0090E', {'name': ifacename})
     else:
         raise OperationFailed('GINNET0091E', {'name': ifacename})
     if returncode != 0:
         raise OperationFailed('GINNET0016E',
                               {'name': encode_value(ifacename),
                                'error': encode_value(error)})
     wok_log.info(
         'Connection successfully activated for the interface ' + ifacename)
def get_interface_info(iface):
    """Returns information about the interface iface.

    Args:
        iface (str): the interface name.

    Returns:
        dict: a dict containing the interface info. Format:
            {
                'device': (str),
                'name': (str),
                'type': (str),
                'status': (str),
                'link_detected': (str),
                'ipaddr': (str),
                'netmask': (str),
                'macaddr': (str),
                'module': (str),
                'nic_type': (str)
            }

    """
    if encode_value(iface) not in map(encode_value, ethtool.get_devices()):
        raise ValueError('unknown interface: %s' % iface)

    ipaddr = ''
    netmask = ''
    try:
        ipaddr = ethtool.get_ipaddr(encode_value(iface))
        netmask = ethtool.get_netmask(encode_value(iface))
    except IOError:
        pass

    kernel_module = get_interface_kernel_module(iface)
    iface_type = get_interface_type(iface)
    nic_type = 'N/A' if iface_type is not 'nic' \
        else get_nic_type(iface, kernel_module)

    return {'device': iface,
            'name': iface,
            'type': iface_type,
            'status': operstate(iface),
            'link_detected': link_detected(iface),
            'ipaddr': ipaddr,
            'netmask': netmask,
            'macaddr': macaddr(iface),
            'module': kernel_module,
            'nic_type': nic_type}
Exemple #11
0
def create_disk_image(format_type, path, capacity):
    """
    Create a disk image for the Guest
    Args:
        format: Format of the storage. e.g. qcow2
        path: Path where the virtual disk will be created
        capacity: Capacity of the virtual disk in GBs

    Returns:

    """
    out, err, rc = run_command(
        [
            '/usr/bin/qemu-img',
            'create',
            '-f',
            format_type,
            '-o',
            'preallocation=metadata',
            path,
            encode_value(capacity) + 'G',
        ]
    )

    if rc != 0:
        raise OperationFailed('KCHTMPL0041E', {'err': err})

    return
 def get_routes_ipformat(self, routecfg_path):
     """
     Constructs a list of route map with key,value information
     for the below format of routes.
     :param: route file which has information in ip format
     :return: list of dictionaries of the key,value information
              of the routes.
     Ex:
     10.10.10.0/24 via 192.168.0.10 dev eth0
     172.16.1.10/32 via 192.168.0.10 dev eth0
     """
     with open(routecfg_path, "r") as routecfg_file:
         line = routecfg_file.read()
         cfg_map = []
         try:
             each_route = [x for x in (y.split() for y in line.split('\n'))
                           if x]
             for options in each_route:
                 if len(options) >= 3:
                     route_info = {'ADDRESS': options[0].split('/')[0],
                                   'NETMASK': options[0].split('/')[1],
                                   'GATEWAY': options[2]}
                     if metric in options and options[3] == metric:
                         route_info['METRIC'] = options[4]
                     elif metric in options and options[5] == metric:
                         route_info['METRIC'] = options[6]
                     cfg_map.append(route_info)
                 else:
                     wok_log.warn("Skipping the invalid route information" +
                                  encode_value(options))
         except Exception, e:
             raise OperationFailed("GINNET0030E", {'err': e.message})
         return cfg_map
Exemple #13
0
def create_disk_image(format_type, path, capacity):
    """
    Create a disk image for the Guest
    Args:
        format: Format of the storage. e.g. qcow2
        path: Path where the virtual disk will be created
        capacity: Capacity of the virtual disk in GBs

    Returns:

    """
    out, err, rc = run_command([
        '/usr/bin/qemu-img',
        'create',
        '-f',
        format_type,
        '-o',
        'preallocation=metadata',
        path,
        encode_value(capacity) + 'G',
    ])

    if rc != 0:
        raise OperationFailed('KCHTMPL0041E', {'err': err})

    return
Exemple #14
0
 def _get_resources(self, flag_filter):
     try:
         get_list = getattr(self.model, model_fn(self, 'get_list'))
         idents = get_list(*self.model_args, **flag_filter)
         res_list = []
         for ident in idents:
             # internal text, get_list changes ident to unicode for sorted
             args = self.resource_args + [ident]
             res = self.resource(self.model, *args)
             try:
                 res.lookup()
             except Exception as e:
                 # In case of errors when fetching a resource info, pass and
                 # log the error, so, other resources are returned
                 # Encoding error message as ident is also encoded value.
                 # This has to be done to avoid unicode error,
                 # as combination of encoded and unicode value results into
                 # unicode error.
                 wok_log.error("Problem in lookup of resource '%s'. "
                               "Detail: %s" % (ident,
                                               encode_value(e.message)))
                 continue
             res_list.append(res)
         return res_list
     except AttributeError:
         return []
    def validate_and_get_bond_info(self, params, cfgmap):
        if cfgmap[TYPE] in IFACE_BOND:
            cfgInterfacesHelper.clean_slaves(cfgmap, params)
        bond_info = {}
        wok_log.info('Validating bond info given for interface')
        if DEVICE not in cfgmap:
            raise MissingParameter("GINNET0025E")
        cfgInterfacesHelper.validate_device_name(cfgmap[DEVICE])
        if BONDINFO not in params[BASIC_INFO]:
            raise MissingParameter("GINNET0032E")
        bondinfo = params[BASIC_INFO][BONDINFO]
        if BONDING_MASTER in bondinfo:
            if not bondinfo[BONDING_MASTER] == "yes":
                raise MissingParameter("GINNET0033E")
            else:
                bond_info[BONDING_MASTER] = bondinfo[BONDING_MASTER]
        else:
            raise MissingParameter("GINNET0034E")

        if BONDING_OPTS in params[BASIC_INFO][BONDINFO]:
            bond_opt_value = ""
            bondopts = bondinfo[BONDING_OPTS]
            if cfgInterfacesHelper.validate_bond_opts(bondopts, params):
                for bond_opt_key in BONDING_OPTS_LIST:
                    if bond_opt_key in bondinfo[BONDING_OPTS]:
                        value = bondinfo[BONDING_OPTS][bond_opt_key]
                        if type(value) is not list:
                            bond_opt_value = \
                                bond_opt_value + bond_opt_key + "=" + \
                                encode_value(bondinfo[BONDING_OPTS][
                                    bond_opt_key]) + " "
                        else:
                            values_as_str = map(encode_value, value)
                            values_as_str = encode_value(values_as_str)
                            v = values_as_str.replace(" ", "")
                            bond_opt_value = \
                                bond_opt_value + bond_opt_key + "=" + v + " "
                bond_opt_value = '"' + bond_opt_value + '"'
                bond_info[BONDING_OPTS] = bond_opt_value
        if SLAVES not in bondinfo:
            raise MissingParameter("GINNET0036E")
        if len(bondinfo[SLAVES]) == 0:
            raise MissingParameter("GINNET0037E")
        name = cfgmap[DEVICE]
        self.create_slaves(name, params)
        bond_info[TYPE] = params[BASIC_INFO][TYPE]
        return bond_info
Exemple #16
0
    def validate_and_get_bond_info(self, params, cfgmap):
        if cfgmap[TYPE] in IFACE_BOND:
            cfgInterfacesHelper.clean_slaves(cfgmap, params)
        bond_info = {}
        wok_log.info('Validating bond info given for interface')
        if DEVICE not in cfgmap:
            raise MissingParameter("GINNET0025E")
        cfgInterfacesHelper.validate_device_name(cfgmap[DEVICE])
        if BONDINFO not in params[BASIC_INFO]:
            raise MissingParameter("GINNET0032E")
        bondinfo = params[BASIC_INFO][BONDINFO]
        if BONDING_MASTER in bondinfo:
            if not bondinfo[BONDING_MASTER] == "yes":
                raise MissingParameter("GINNET0033E")
            else:
                bond_info[BONDING_MASTER] = bondinfo[BONDING_MASTER]
        else:
            raise MissingParameter("GINNET0034E")

        if BONDING_OPTS in params[BASIC_INFO][BONDINFO]:
            bond_opt_value = ""
            bondopts = bondinfo[BONDING_OPTS]
            if cfgInterfacesHelper.validate_bond_opts(bondopts, params):
                for bond_opt_key in BONDING_OPTS_LIST:
                    if bond_opt_key in bondinfo[BONDING_OPTS]:
                        value = bondinfo[BONDING_OPTS][bond_opt_key]
                        if type(value) is not list:
                            bond_opt_value = \
                                bond_opt_value + bond_opt_key + "=" + \
                                encode_value(bondinfo[BONDING_OPTS][
                                    bond_opt_key]) + " "
                        else:
                            values_as_str = map(encode_value, value)
                            values_as_str = encode_value(values_as_str)
                            v = values_as_str.replace(" ", "")
                            bond_opt_value = \
                                bond_opt_value + bond_opt_key + "=" + v + " "
                bond_opt_value = '"' + bond_opt_value + '"'
                bond_info[BONDING_OPTS] = bond_opt_value
        if SLAVES not in bondinfo:
            raise MissingParameter("GINNET0036E")
        if len(bondinfo[SLAVES]) == 0:
            raise MissingParameter("GINNET0037E")
        name = cfgmap[DEVICE]
        self.create_slaves(name, params)
        bond_info[TYPE] = params[BASIC_INFO][TYPE]
        return bond_info
 def deactivate_iface(self, ifacename):
     filename = ifcfg_filename_format % ifacename
     filepath = os.sep + network_configpath + filename
     wok_log.info('Deactivating an interface ' + ifacename)
     if os.path.exists(filepath):
         cmd_ifdown = ['ifdown', '%s' % ifacename]
         out, error, returncode = run_command(cmd_ifdown)
         if returncode != 0:
             raise OperationFailed('GINNET0017E', {
                 'name': encode_value(ifacename),
                 'error': encode_value(error)
             })
         wok_log.info(
             'Connection successfully deactivated for the interface ' +
             ifacename)
     wok_log.info('Bringing down an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     if iface_type == "nic":
         cmd_ipdown = ['ip', 'link', 'set', '%s' % ifacename, 'down']
         out, error, returncode = run_command(cmd_ipdown)
         if returncode != 0:
             raise OperationFailed('GINNET0060E', {
                 'name': encode_value(ifacename),
                 'error': encode_value(error)
             })
         # Some times based on system load, it takes few seconds to
         # reflect the  /sys/class/net files upon execution of 'ip link
         # set' command. Following snippet is to wait util files get
         # reflect.
         timeout = self.wait_time(ifacename)
         if timeout == 5:
             wok_log.warn("Time-out has happened upon execution of 'ip "
                          "link set <interface> down', hence behavior "
                          "of activating an interface may not as "
                          "expected.")
         else:
             wok_log.info('Successfully brought down the interface ' +
                          ifacename)
     vlan_or_bond = [
         nw_cfginterfaces_utils.IFACE_BOND,
         nw_cfginterfaces_utils.IFACE_VLAN
     ]
     if iface_type in vlan_or_bond:
         if encode_value(ifacename) in ethtool.get_devices():
             cmd_ip_link_del = ['ip', 'link', 'delete', '%s' % ifacename]
             out, error, returncode = run_command(cmd_ip_link_del)
             if (returncode != 0 and
                 (encode_value(ifacename) in ethtool.get_devices())):
                 raise OperationFailed(
                     'GINNET0017E', {
                         'name': encode_value(ifacename),
                         'error': encode_value(error)
                     })
Exemple #18
0
def is_vlan(iface):
    """Checks if iface is a vlan.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a vlan, False otherwise.

    """
    return encode_value(iface) in map(encode_value, vlans())
Exemple #19
0
def is_bridge(iface):
    """Checks if iface is a bridge.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a bridge, False otherwise.

    """
    return encode_value(iface) in map(encode_value, bridges())
Exemple #20
0
def is_wlan(iface):
    """Checks if iface is a wlan.

    Args:
        iface (str): interface to be checked.

    Returns:
        bool: True if iface is a wlan, False otherwise.

    """
    return encode_value(iface) in map(encode_value, wlans())
def is_wlan(iface):
    """Checks if iface is a wlan.

    Args:
        iface (str): interface to be checked.

    Returns:
        bool: True if iface is a wlan, False otherwise.

    """
    return encode_value(iface) in map(encode_value, wlans())
def is_vlan(iface):
    """Checks if iface is a vlan.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a vlan, False otherwise.

    """
    return encode_value(iface) in map(encode_value, vlans())
def is_bridge(iface):
    """Checks if iface is a bridge.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a bridge, False otherwise.

    """
    return encode_value(iface) in map(encode_value, bridges())
Exemple #24
0
def is_nic(iface):
    """Checks if iface is a nic.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a nic, False otherwise.

    """
    return encode_value(iface) in map(encode_value, nics())
def is_nic(iface):
    """Checks if iface is a nic.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a nic, False otherwise.

    """
    return encode_value(iface) in map(encode_value, nics())
Exemple #26
0
def operstate(dev):
    """Get the operstate status of a device.

    Args:
        dev (str): name of the device.

    Returns:
        str: "up" or "down"

    """
    flags = ethtool.get_flags(encode_value(dev))
    return 'up' if flags & (ethtool.IFF_RUNNING | ethtool.IFF_UP) else 'down'
Exemple #27
0
def operstate(dev):
    """Get the operstate status of a device.

    Args:
        dev (str): name of the device.

    Returns:
        str: "up" or "down"

    """
    flags = ethtool.get_flags(encode_value(dev))
    return 'up' if flags & (ethtool.IFF_RUNNING | ethtool.IFF_UP) else 'down'
Exemple #28
0
def is_vlan(iface):
    """Checks if iface is a vlan.

    Args:
        iface (str): name of the interface.

    Returns:
        bool: True if iface is a vlan, False otherwise.

    """
    return encode_value(iface) in map(encode_value, vlans()) or \
        'vlan_raw_device' in _parse_interfaces_file(iface).keys()
 def deactivate_iface(self, ifacename):
     filename = ifcfg_filename_format % ifacename
     filepath = os.sep + network_configpath + filename
     wok_log.info('Deactivating an interface ' + ifacename)
     if os.path.exists(filepath):
         cmd_ifdown = ['ifdown', '%s' % ifacename]
         out, error, returncode = run_command(cmd_ifdown)
         if returncode != 0:
             raise OperationFailed('GINNET0017E',
                                   {'name': encode_value(ifacename),
                                    'error': encode_value(error)})
         wok_log.info(
             'Connection successfully deactivated for the interface ' +
             ifacename)
     wok_log.info('Bringing down an interface ' + ifacename)
     iface_type = netinfo.get_interface_type(ifacename)
     if iface_type == "nic":
         cmd_ipdown = ['ip', 'link', 'set', '%s' % ifacename, 'down']
         out, error, returncode = run_command(cmd_ipdown)
         if returncode != 0:
             raise OperationFailed('GINNET0060E',
                                   {'name': encode_value(ifacename),
                                    'error': encode_value(error)})
         # Some times based on system load, it takes few seconds to
         # reflect the  /sys/class/net files upon execution of 'ip link
         # set' command. Following snippet is to wait util files get
         # reflect.
         timeout = self.wait_time(ifacename)
         if timeout == 5:
             wok_log.warn("Time-out has happened upon execution of 'ip "
                          "link set <interface> down', hence behavior "
                          "of activating an interface may not as "
                          "expected.")
         else:
             wok_log.info('Successfully brought down the interface ' +
                          ifacename)
     vlan_or_bond = [nw_cfginterfaces_utils.IFACE_BOND,
                     nw_cfginterfaces_utils.IFACE_VLAN]
     if iface_type in vlan_or_bond:
         if encode_value(ifacename) in ethtool.get_devices():
             cmd_ip_link_del = ['ip', 'link', 'delete', '%s' % ifacename]
             out, error, returncode = run_command(cmd_ip_link_del)
             if (returncode != 0 and
                (encode_value(ifacename) in ethtool.get_devices())):
                 raise OperationFailed('GINNET0017E',
                                       {'name': encode_value(ifacename),
                                        'error': encode_value(error)})
Exemple #30
0
def _is_dev_leaf(devNodePath, name=None, devs=None, devtype=None):
    try:
        if devs and devtype != 'mpath':
            for dev in devs:
                if encode_value(name) == dev['pkname']:
                    return False
            return True
        # By default, lsblk prints a device information followed by children
        # device information
        childrenCount = len(_get_lsblk_devs(['NAME'], [devNodePath])) - 1
    except OperationFailed as e:
        # lsblk is known to fail on multipath devices
        # Assume these devices contain children
        wok_log.error('Error getting device info for %s: %s', devNodePath, e)
        return False

    return childrenCount == 0
Exemple #31
0
def _is_dev_leaf(devNodePath, name=None, devs=None, devtype=None):
    try:
        if devs and devtype != 'mpath':
            for dev in devs:
                if encode_value(name) == dev['pkname']:
                    return False
            return True
        # By default, lsblk prints a device information followed by children
        # device information
        childrenCount = len(
            _get_lsblk_devs(["NAME"], [devNodePath])) - 1
    except OperationFailed as e:
        # lsblk is known to fail on multipath devices
        # Assume these devices contain children
        wok_log.error(
            "Error getting device info for %s: %s", devNodePath, e)
        return False

    return childrenCount == 0
Exemple #32
0
def create_disk_image(format_type, path, capacity):
    """
    Create a disk image for the Guest
    Args:
        format: Format of the storage. e.g. qcow2
        path: Path where the virtual disk will be created
        capacity: Capacity of the virtual disk in GBs

    Returns:

    """
    out, err, rc = run_command(
        ["/usr/bin/qemu-img", "create", "-f", format_type, "-o",
         "preallocation=metadata", path, encode_value(capacity) + "G"])

    if rc != 0:
        raise OperationFailed("KCHTMPL0041E", {'err': err})

    return
Exemple #33
0
    def lookup(self, name):
        """
        Populate info using runtime information from /sys/class/net files for
        active interfaces and for inactive bond and vlan interfaces from cfg
        files
        :param name:
        :return:
        """
        try:
            # encode name to ensure comparison are in same type.
            if encode_value(name) in ethtool.get_devices():
                info = netinfo.get_interface_info(name)
            elif cfgInterfacesHelper.is_cfgfileexist(name):
                type = cfgInterfacesHelper.get_type(name).lower()
                if type not in IFACE_BOND + [IFACE_VLAN]:
                    raise ValueError
                device = cfgInterfacesHelper.get_device(name)
                info = {
                    'device': device,
                    'type': cfgInterfacesHelper.get_type(name),
                    'status': "down",
                    'ipaddr': "",
                    'netmask': "",
                    'macaddr': "",
                    'module': netinfo.get_interface_kernel_module(name)
                }

                if info.get('type') is not 'nic':
                    info['nic_type'] = 'N/A'
                else:
                    info['nic_type'] = netinfo.get_nic_type(device)

            else:
                raise ValueError('unknown interface: %s' % name)

            info['rdma_enabled'] = netinfo.is_rdma_enabled(name)

            return info

        except ValueError:
            raise NotFoundError("GINNET0014E", {'name': name})
Exemple #34
0
def create_disk_image(format_type, path, capacity):
    """
    Create a disk image for the Guest
    Args:
        format: Format of the storage. e.g. qcow2
        path: Path where the virtual disk will be created
        capacity: Capacity of the virtual disk in GBs

    Returns:

    """
    out, err, rc = run_command([
        "/usr/bin/qemu-img", "create", "-f", format_type, "-o",
        "preallocation=metadata", path,
        encode_value(capacity) + "G"
    ])

    if rc != 0:
        raise OperationFailed("KCHTMPL0041E", {'err': err})

    return
Exemple #35
0
 def validate_bond_for_vlan(self, parent_iface):
     """
     method to validate in the case of VLANs over bonds, it is important
     that the bond has slaves and that they are up, and vlan can not be
     configured over bond with the fail_over_mac=follow option.
     :param parent_iface:
     """
     if encode_value(parent_iface) in ethtool.get_devices():
         try:
             with open(FAIL_OVER_MAC % parent_iface) as dev_file:
                 fail_over_mac = dev_file.readline().strip()
         except IOError:
             fail_over_mac = "n/a"
         if fail_over_mac == "follow 2":
             raise OperationFailed("GINNET0046E")
     else:
         """TODO: Need an investigation on, if parent of type bond is not
         active whether we can still create vlan interface or not. If
         'yes', then can include code to validate the fail_over_mac in
         ifcfg persistant file"""
         raise OperationFailed("GINNET0051E")
     cfgdata = CfginterfaceModel().get_cfginterface_info(parent_iface)
     cfgInterfacesHelper.validate_dict_bond_for_vlan(cfgdata)
     slave_list = cfgdata[BASIC_INFO][BONDINFO][SLAVES]
     if len(slave_list) != 0:
         active_slave_found = True
         for slave in slave_list:
             # Fix ginger issue #144
             if netinfo.operstate(slave) == STATE_DOWN:
                 active_slave_found = False
             else:
                 active_slave_found = True
                 wok_log.info("One active slave is found:" + slave)
                 break
         if (not active_slave_found):
             raise OperationFailed("GINNET0047E")
     else:
         raise OperationFailed("GINNET0037E")
     return
Exemple #36
0
    def lookup(self, name):
        """
        Populate info using runtime information from /sys/class/net files for
        active interfaces and for inactive bond and vlan interfaces from cfg
        files
        :param name:
        :return:
        """
        try:
            # encode name to ensure comparison are in same type.
            if encode_value(name) in ethtool.get_devices():
                info = netinfo.get_interface_info(name)
            elif cfgInterfacesHelper.is_cfgfileexist(name):
                type = cfgInterfacesHelper.get_type(name).lower()
                if type not in IFACE_BOND + [IFACE_VLAN]:
                    raise ValueError
                device = cfgInterfacesHelper.get_device(name)
                info = {'device': device,
                        'type': cfgInterfacesHelper.get_type(name),
                        'status': "down",
                        'ipaddr': "",
                        'netmask': "",
                        'macaddr': "",
                        'module': netinfo.get_interface_kernel_module(name)}

                if info.get('type') is not 'nic':
                    info['nic_type'] = 'N/A'
                else:
                    info['nic_type'] = netinfo.get_nic_type(device)

            else:
                raise ValueError('unknown interface: %s' % name)

            info['rdma_enabled'] = netinfo.is_rdma_enabled(name)

            return info

        except ValueError:
            raise NotFoundError("GINNET0014E", {'name': name})
Exemple #37
0
 def validate_bond_for_vlan(self, parent_iface):
     """
     method to validate in the case of VLANs over bonds, it is important
     that the bond has slaves and that they are up, and vlan can not be
     configured over bond with the fail_over_mac=follow option.
     :param parent_iface:
     """
     if encode_value(parent_iface) in ethtool.get_devices():
         try:
             with open(FAIL_OVER_MAC % parent_iface) as dev_file:
                 fail_over_mac = dev_file.readline().strip()
         except IOError:
             fail_over_mac = "n/a"
         if fail_over_mac == "follow 2":
             raise OperationFailed("GINNET0046E")
     else:
         """TODO: Need an investigation on, if parent of type bond is not
         active whether we can still create vlan interface or not. If
         'yes', then can include code to validate the fail_over_mac in
         ifcfg persistant file"""
         raise OperationFailed("GINNET0051E")
     cfgdata = CfginterfaceModel().get_cfginterface_info(parent_iface)
     cfgInterfacesHelper.validate_dict_bond_for_vlan(cfgdata)
     slave_list = cfgdata[BASIC_INFO][BONDINFO][SLAVES]
     if len(slave_list) != 0:
         active_slave_found = True
         for slave in slave_list:
             # Fix ginger issue #144
             if netinfo.operstate(slave) == STATE_DOWN:
                 active_slave_found = False
             else:
                 active_slave_found = True
                 wok_log.info("One active slave is found:" + slave)
                 break
         if (not active_slave_found):
             raise OperationFailed("GINNET0047E")
     else:
         raise OperationFailed("GINNET0037E")
     return
Exemple #38
0
 def get_routes_ipformat(self, routecfg_path):
     """
     Constructs a list of route map with key,value information
     for the below format of routes.
     :param: route file which has information in ip format
     :return: list of dictionaries of the key,value information
              of the routes.
     Ex:
     10.10.10.0/24 via 192.168.0.10 dev eth0
     172.16.1.10/32 via 192.168.0.10 dev eth0
     """
     with open(routecfg_path, "r") as routecfg_file:
         line = routecfg_file.read()
         cfg_map = []
         try:
             each_route = [
                 x for x in (y.split() for y in line.split('\n')) if x
             ]
             for options in each_route:
                 if len(options) >= 3:
                     route_info = {
                         'ADDRESS': options[0].split('/')[0],
                         'NETMASK': options[0].split('/')[1],
                         'GATEWAY': options[2]
                     }
                     if metric in options and options[3] == metric:
                         route_info['METRIC'] = options[4]
                     elif metric in options and options[5] == metric:
                         route_info['METRIC'] = options[6]
                     cfg_map.append(route_info)
                 else:
                     wok_log.warn("Skipping the invalid route information" +
                                  encode_value(options))
         except Exception, e:
             raise OperationFailed("GINNET0030E", {'err': e.message})
         return cfg_map