Beispiel #1
0
def get_bond_options(mode, usr_opts):
    MIIMON_100 = dict(miimon='100')
    DEFAULT_MODE_OPTS = {
        '1': MIIMON_100,
        '2': MIIMON_100,
        '3': MIIMON_100,
        '4': dict(xmit_hash_policy='2', **MIIMON_100)
    }

    options = []
    if mode is None:
        return options

    def get_type_name(mode_number):
        """
        We need to maintain this type strings, for the __compare_options method,
        for easier comparision.
        """
        modes = [
            'Active-Backup',
            'Load balance (balance-xor)',
            None,
            'Dynamic link aggregation (802.3ad)',
        ]
        if (not 0 < mode_number <= len(modes)):
            return None
        return modes[mode_number - 1]

    try:
        mode_number = int(mode)
    except ValueError:
        raise Exception('Bond mode must be a number.')

    options.append(
        otypes.Option(
            name='mode',
            type=get_type_name(mode_number),
            value=str(mode_number)
        )
    )

    opts_dict = DEFAULT_MODE_OPTS.get(str(mode), {})
    if usr_opts is not None:
        opts_dict.update(**usr_opts)

    options.extend(
        [otypes.Option(name=opt, value=str(value))
         for opt, value in six.iteritems(opts_dict)]
    )
    return options
 def test_action_parameters(self):
     """
     Test if action parameters are constructed in correct way.
     """
     self.server.set_xml_response("hosts/123/setupnetworks", 200,
                                  "<action/>")
     hosts_service = self.connection.system_service().hosts_service()
     host_service = hosts_service.host_service('123')
     host_service.setup_networks(modified_bonds=[
         types.HostNic(
             name='bond0',
             bonding=types.Bonding(
                 options=[
                     types.Option(
                         name="mode",
                         type="4",
                     ),
                 ],
                 slaves=[
                     types.HostNic(name='eth1', ),
                     types.HostNic(name='eth2', ),
                 ],
             ),
         ),
     ])
     assert_equal(
         self.server.last_request_content, "<action>" + "<modified_bonds>" +
         "<host_nic>" + "<bonding>" + "<options>" + "<option>" +
         "<name>mode</name>" + "<type>4</type>" + "</option>" +
         "</options>" + "<slaves>" + "<host_nic>" + "<name>eth1</name>" +
         "</host_nic>" + "<host_nic>" + "<name>eth2</name>" +
         "</host_nic>" + "</slaves>" + "</bonding>" + "<name>bond0</name>" +
         "</host_nic>" + "</modified_bonds>" + "</action>")
Beispiel #3
0
def get_mode_type(mode_number):
    """
    Adaptive transmit load balancing (balance-tlb): mode=1 miimon=100
    Dynamic link aggregation (802.3ad): mode=2 miimon=100
    Load balance (balance-xor): mode=3 miimon=100
    Active-Backup: mode=4 miimon=100 xmit_hash_policy=2
    """
    options = []
    if mode_number is None:
        return options

    def get_type_name(mode_number):
        """
        We need to maintain this type strings, for the __compare_options method,
        for easier comparision.
        """
        return [
            'Active-Backup',
            'Load balance (balance-xor)',
            None,
            'Dynamic link aggregation (802.3ad)',
        ][mode_number]

    try:
        mode_number = int(mode_number)
        if mode_number >= 1 and mode_number <= 4:
            if mode_number == 4:
                options.append(
                    otypes.Option(name='xmit_hash_policy', value='2'))

            options.append(otypes.Option(name='miimon', value='100'))
            options.append(
                otypes.Option(name='mode',
                              type=get_type_name(mode_number - 1),
                              value=str(mode_number)))
        else:
            options.append(otypes.Option(name='mode', value=str(mode_number)))
    except ValueError:
        raise Exception("Bond mode must be a number.")

    return options
Beispiel #4
0
 def build_entity(self):
     return otypes.Agent(
         address=self._module.params['address'],
         encrypt_options=self._module.params['encrypt_options'],
         options=[
             otypes.Option(
                 name=name,
                 value=value,
             ) for name, value in self._module.params['options'].items()
         ] if self._module.params['options'] else None,
         password=self._module.params['password'],
         port=self._module.params['port'],
         type=self._module.params['type'],
         username=self._module.params['username'],
         order=self._module.params.get('order', 100),
     )
Beispiel #5
0
 def build_entity(self):
     last = next((s for s in sorted([a.order for a in self._service.list()])), 0)
     order = self.param('order') if self.param('order') is not None else self.entity.order if self.entity else last + 1
     return otypes.Agent(
         address=self._module.params['address'],
         encrypt_options=self._module.params['encrypt_options'],
         options=[
             otypes.Option(
                 name=name,
                 value=value,
             ) for name, value in self._module.params['options'].items()
         ] if self._module.params['options'] else None,
         password=self._module.params['password'],
         port=self._module.params['port'],
         type=self._module.params['type'],
         username=self._module.params['username'],
         order=order,
     )
 def _sdk_options(self):
     return [
         types.Option(name=key, value=value)
         for key, value in self._options.items()
     ]
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        host_networks_module = HostNetworksModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        host = host_networks_module.search_entity()
        if host is None:
            raise Exception("Host '%s' was not found." % module.params['name'])

        bond = module.params['bond']
        interface = module.params['interface']
        networks = module.params['networks']
        labels = module.params['labels']
        nic_name = bond.get('name') if bond else module.params['interface']

        nics_service = hosts_service.host_service(host.id).nics_service()
        nic = search_by_name(nics_service, nic_name)

        state = module.params['state']
        if (state == 'present'
                and (nic is None or host_networks_module.has_update(
                    nics_service.service(nic.id)))):
            host_networks_module.action(
                entity=host,
                action='setup_networks',
                post_action=host_networks_module._action_save_configuration,
                check_connectivity=module.params['check'],
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=[
                                otypes.Option(
                                    name="mode",
                                    value=str(bond.get('mode')),
                                )
                            ],
                            slaves=[
                                otypes.HostNic(name=i)
                                for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        network=otypes.Network(
                            name=network['name']) if network['name'] else None,
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                        ip_address_assignments=[
                            otypes.IpAddressAssignment(
                                assignment_method=otypes.BootProtocol(
                                    network.get('boot_protocol', 'none')),
                                ip=otypes.Ip(
                                    address=network.get('address'),
                                    gateway=network.get('gateway'),
                                    netmask=network.get('netmask'),
                                    version=otypes.IpVersion(
                                        network.get('version'))
                                    if network.get('version') else None,
                                ),
                            ),
                        ],
                    ) for network in networks
                ] if networks else None,
            )
        elif state == 'absent' and nic:
            nic_service = nics_service.nic_service(nic.id)

            attachments_service = nic_service.network_attachments_service()
            attachments = attachments_service.list()
            attached_labels = set([
                str(lbl.id)
                for lbl in nic_service.network_labels_service().list()
            ])
            if networks:
                network_names = [network['name'] for network in networks]
                attachments = [
                    attachment for attachment in attachments if get_link_name(
                        connection, attachment.network) in network_names
                ]

            # Need to check if there are any labels to be removed, as backend fail
            # if we try to send remove non existing label, for bond and attachments it's OK:
            if (labels and set(labels).intersection(attached_labels)
                ) or bond or attachments:
                host_networks_module.action(
                    entity=host,
                    action='setup_networks',
                    post_action=host_networks_module.
                    _action_save_configuration,
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(name=bond.get('name'), ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(id=str(name)) for name in labels
                    ],
                    removed_network_attachments=list(attachments),
                )

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(
            **{
                'changed': host_networks_module.changed,
                'id': nic.id if nic else None,
                'host_nic': get_dict_of_struct(nic),
            })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Beispiel #8
0
# Find the host:
host = hosts_service.list(search='name=myhost')[0]

# Find the service that manages the host:
host_service = hosts_service.host_service(host.id)

# Configure the network adding a bond with two slaves and attaching it to a
# network with an static IP address:
host_service.setup_networks(
    modified_bonds=[
        types.HostNic(
            name='bond0',
            bonding=types.Bonding(
                options=[
                    types.Option(
                        name='mode',
                        value='1',
                    ),
                    types.Option(
                        name='miimon',
                        value='100',
                    ),
                ],
                slaves=[
                    types.HostNic(name='eth1', ),
                    types.HostNic(name='eth2', ),
                ],
            ),
        ),
    ],
    modified_network_attachments=[
        types.NetworkAttachment(
# The host may have multiple fencing agents, so we need to locate the
# first of type 'ipmilan':
agents = agents_service.list()
agent = next(x for x in agents if x.type == 'ipmilan')

# Get the options of the fencing agent. There may be no options, in that
# case we need to use an empty list:
original = agent.options
if original is None:
    original = []

# Create a list of modified options, containing all the original options
# except the one with the name that we want to modify, as we will add that
# with the right value later:
modified = [x for x in original if x.name != name]

# Add the modified option to the list of modified options:
option = types.Option(name=name, value=value)
modified.append(option)

# Find the service that manages the fence agent:
agent_service = agents_service.agent_service(agent.id)

# Send the update request containg the original list of options plus the
# modifications that we did:
agent_service.update(agent=types.Agent(options=modified))

# Close the connection to the server:
connection.close()
Beispiel #10
0
hosts_service = connection.system_service().hosts_service()
host = hosts_service.list(search='name=myhost')[0]
host_service = hosts_service.host_service(host.id)

# Using fence agent service of the host, add ipmilan fence
# agent:
fence_agents_service = host_service.fence_agents_service()
fence_agents_service.add(
    types.Agent(
        address='1.2.3.4',
        type='ipmilan',
        username='******',
        password='******',
        options=[
            types.Option(
                name='myname',
                value='myvalue',
            ),
        ],
        order=0,
    ))

# Prepare the update host object:
host_update = types.Host()

# If power management isn't enabled, enable it. Note that
# power management can be enabled only if at least one fence
# agent exists for host:
if not host.power_management.enabled:
    host_update.power_management = types.PowerManagement(enabled=True)

# If kdump isn't enabled, enable it. Note that kdump