Ejemplo n.º 1
0
def _get_connection_info():
    '''
    Return connection information for the passed VM data
    '''
    vm_ = get_configured_provider()

    try:
        ret = {'username': vm_['username'],
               'password': vm_['password'],
               'eauth': vm_['eauth'],
               'vm': vm_,
               }
    except KeyError:
        raise SaltCloudException(
            'Configuration must define salt-api "username", "password" and "eauth"')
    return ret
Ejemplo n.º 2
0
def avail_sizes(session=None, call=None):
    '''
    Return a list of Xen template definitions

    .. code-block:: bash

        salt-cloud --list-sizes myxen

    '''
    if call == 'action':
        raise SaltCloudException(
            'The avail_sizes function must be called with -f or --function.')
    return {
        'STATUS':
        'Sizes are build into templates. Consider running --list-images to see sizes'
    }
Ejemplo n.º 3
0
def avail_sizes(session=None, call=None):
    """
    Return a list of Xen template definitions

    .. code-block:: bash

        salt-cloud --list-sizes myxen

    """
    if call == "action":
        raise SaltCloudException(
            "The avail_sizes function must be called with -f or --function."
        )
    return {
        "STATUS": "Sizes are build into templates. Consider running --list-images to see sizes"
    }
Ejemplo n.º 4
0
def destroy(name, call=None):
    '''
    Destroys a Linode by name.

    name
        The name of VM to be be destroyed.

    CLI Example:

    .. code-block:: bash

        salt-cloud -d vm_name
    '''
    if call == 'function':
        raise SaltCloudException(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.')

    salt.utils.cloud.fire_event('event',
                                'destroying instance',
                                'salt/cloud/{0}/destroying'.format(name),
                                args={'name': name},
                                sock_dir=__opts__['sock_dir'],
                                transport=__opts__['transport'])

    linode_id = get_linode_id_from_name(name)

    response = _query('linode',
                      'delete',
                      args={
                          'LinodeID': linode_id,
                          'skipChecks': True
                      })

    salt.utils.cloud.fire_event('event',
                                'destroyed instance',
                                'salt/cloud/{0}/destroyed'.format(name),
                                args={'name': name},
                                sock_dir=__opts__['sock_dir'],
                                transport=__opts__['transport'])

    if __opts__.get('update_cachedir', False) is True:
        salt.utils.cloud.delete_minion_cachedir(
            name,
            __active_provider_name__.split(':')[0], __opts__)

    return response
def list_nodes_full(call=None):
    """
    List Kamatera servers, with all available information.

    CLI Example:

    .. code-block:: bash

        salt-cloud -F
        salt-cloud --full-query
        salt-cloud -f list_nodes_full my-kamatera-config
    """
    if call == "action":
        raise SaltCloudException(
            "The list_nodes_full function must be called with -f or --function."
        )
    return list_nodes(full=True)
def list_nodes(call=None, full=False, name_regex=None):
    """
    Returns a list of servers, keeping only a brief listing.

    CLI Example:

    .. code-block:: bash

        salt-cloud -Q
        salt-cloud --query
        salt-cloud -f list_nodes my-kamatera-config
    """
    if call == "action":
        raise SaltCloudException(
            "The list_nodes function must be called with -f or --function."
        )
    ret = {}
    for server_res in _list_servers(name_regex=name_regex):
        public_ips, private_ips, networks = [], [], []
        for network in server_res.pop("networks"):
            networks.append(network["network"])
            if network["network"].startswith("wan-"):
                public_ips += network["ips"]
            else:
                private_ips += network["ips"]
        name = server_res.pop("name")
        server = {
            "id": server_res.pop("id"),
            "image": "",
            "size": "{0}{1}-{2}mb-{3}gb".format(
                server_res.pop("cpu_cores"),
                server_res.pop("cpu_type"),
                server_res.pop("ram_mb"),
                server_res.pop("disk_size_gb"),
            ),
            "state": server_res.pop("state"),
            "private_ips": private_ips,
            "public_ips": public_ips,
        }
        if full:
            server_res["networks"] = networks
            for k, v in server_res.pop("extra", {}).items():
                server_res[k] = v
            server["extra"] = server_res
        ret[name] = server
    return ret
Ejemplo n.º 7
0
def _check_and_set_node_id(name, linode_id):
    '''
    Helper function that checks against name and linode_id collisions and returns a node_id.
    '''
    node_id = ''
    if linode_id and name is None:
        node_id = linode_id
    elif name:
        node_id = get_linode_id_from_name(name)

    if linode_id and (linode_id != node_id):
        raise SaltCloudException(
            'A name and a linode_id were provided, but the provided linode_id, {0}, '
            'does not match the linode_id found for the provided '
            'name: \'{1}\': \'{2}\'. Nothing was done.'.format(
                linode_id, name, node_id))

    return node_id
Ejemplo n.º 8
0
def get_vm_ip(name=None, session=None, call=None):
    '''
    Get the IP address of the VM

    .. code-block:: bash

        salt-cloud -a get_vm_ip xenvm01

    .. note:: Requires xen guest tools to be installed in VM

    '''
    if call == 'function':
        raise SaltCloudException(
            'This function must be called with -a or --action.'
        )
    if session is None:
        log.debug('New session being created')
        session = _get_session()
    vm = _get_vm(name, session=session)
    ret = None
    # -- try to get ip from vif
    vifs = session.xenapi.VM.get_VIFs(vm)
    if vifs is not None:
        for vif in vifs:
            if len(session.xenapi.VIF.get_ipv4_addresses(vif)) != 0:
                cidr = session.xenapi.VIF.get_ipv4_addresses(vif).pop()
                ret, subnet = cidr.split('/')
                log.debug(
                    'VM vif returned for instance: {} ip: {}'.format(name, ret))
                return ret
    # -- try to get ip from get tools metrics
    vgm = session.xenapi.VM.get_guest_metrics(vm)
    try:
        net = session.xenapi.VM_guest_metrics.get_networks(vgm)
        if "0/ip" in net.keys():
            log.debug(
                'VM guest metrics returned for instance: {} 0/ip: {}'.format(
                    name,
                    net["0/ip"]))
            ret = net["0/ip"]
    # except Exception as ex:
    except XenAPI.Failure:
        log.info('Could not get vm metrics at this time')
    return ret
Ejemplo n.º 9
0
def resume(name, call=None, session=None):
    '''
    Resume a vm from disk

    .. code-block:: bash

        salt-cloud -a resume xenvm01

    '''
    if call == 'function':
        raise SaltCloudException(
            'The show_instnce function must be called with -a or --action.')
    if session is None:
        session = _get_session()
    log.info('Resuming VM {0}'.format(name))
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.resume(vm, False, True)
    _run_async_task(task, session)
    return show_instance(name)
Ejemplo n.º 10
0
def vdi_list(call=None, kwargs=None):
    '''
    Return available Xen VDI images

    If this function is called with the ``-f`` or ``--function`` then
    it can return a list with minimal deatil using the ``terse=True`` keyword
    argument.

    .. code-block:: bash

        salt-cloud -f vdi_list myxen terse=True

    '''
    if call == 'action':
        raise SaltCloudException(
            'This function must be called with -f or --function.')
    log.debug('kwargs is %s', kwargs)
    if kwargs is not None:
        if 'terse' in kwargs:
            if kwargs['terse'] == 'True':
                terse = True
            else:
                terse = False
        else:
            terse = False
    else:
        kwargs = {}
        terse = False
    session = _get_session()
    vdis = session.xenapi.VDI.get_all()
    ret = {}
    for vdi in vdis:
        data = session.xenapi.VDI.get_record(vdi)
        log.debug(type(terse))
        if terse is True:
            ret[data.get('name_label')] = {
                'uuid': data.get('uuid'),
                'OpqueRef': vdi
            }
        else:
            data.update({'OpaqueRef': vdi})
            ret[data.get('name_label')] = data
    return ret
Ejemplo n.º 11
0
def suspend(name, call=None, session=None):
    '''
    Suspend a vm to disk

    .. code-block:: bash

        salt-cloud -a suspend xenvm01

    '''
    if call == 'function':
        raise SaltCloudException(
            'The show_instnce function must be called with -a or --action.')
    if session is None:
        session = _get_session()
    log.info('Suspending VM %s', name)
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.suspend(vm)
    _run_async_task(task, session)
    return show_instance(name)
Ejemplo n.º 12
0
def stop(name, call=None):
    """
    Stop a Kamatera server.

    .. versionadded:: 2015.8.0

    name
        The name of the server to stop.

    CLI Example:

    .. code-block:: bash

        salt-cloud -a stop server_name
    """
    if call != "action":
        raise SaltCloudException(
            "The show_instance action must be called with -a or --action.")
    return _server_operation(name, "poweroff")
Ejemplo n.º 13
0
def show_instance(name, call=None):
    """
    Displays details about a specific Kamatera server

    .. versionadded:: 2015.8.0

    name
        Server name

    CLI Example:

    .. code-block:: bash

        salt-cloud -a show_instance server_name
    """
    if call != "action":
        raise SaltCloudException(
            "The show_instance action must be called with -a or --action.")
    return list_nodes(full=True, name_regex=name)[name]
Ejemplo n.º 14
0
def get_config_id(kwargs=None, call=None):
    """
    Returns a config_id for a given linode.

    .. versionadded:: 2015.8.0

    name
        The name of the Linode for which to get the config_id. Can be used instead
        of ``linode_id``.h

    linode_id
        The ID of the Linode for which to get the config_id. Can be used instead
        of ``name``.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f get_config_id my-linode-config name=my-linode
        salt-cloud -f get_config_id my-linode-config linode_id=1234567
    """
    if call == "action":
        raise SaltCloudException(
            "The get_config_id function must be called with -f or --function."
        )

    if kwargs is None:
        kwargs = {}

    name = kwargs.get("name", None)
    linode_id = kwargs.get("linode_id", None)
    if name is None and linode_id is None:
        raise SaltCloudSystemExit(
            "The get_config_id function requires either a 'name' or a 'linode_id' "
            "to be provided."
        )
    if linode_id is None:
        linode_id = get_linode_id_from_name(name)

    response = _query("linode", "config.list", args={"LinodeID": linode_id})["DATA"]
    config_id = {"config_id": response[0]["ConfigID"]}

    return config_id
Ejemplo n.º 15
0
def show_instance(name, call=None):
    """
    Displays details about a particular Linode VM. Either a name or a linode_id must
    be provided.

    .. versionadded:: 2015.8.0

    name
        The name of the VM for which to display details.

    CLI Example:

    .. code-block:: bash

        salt-cloud -a show_instance vm_name

    .. note::

        The ``image`` label only displays information about the VM's distribution vendor,
        such as "Debian" or "RHEL" and does not display the actual image name. This is
        due to a limitation of the Linode API.
    """
    if call != "action":
        raise SaltCloudException(
            "The show_instance action must be called with -a or --action."
        )

    node_id = get_linode_id_from_name(name)
    node_data = get_linode(kwargs={"linode_id": node_id})
    ips = get_ips(node_id)
    state = int(node_data["STATUS"])

    ret = {
        "id": node_data["LINODEID"],
        "image": node_data["DISTRIBUTIONVENDOR"],
        "name": node_data["LABEL"],
        "size": node_data["TOTALRAM"],
        "state": _get_status_descr_by_id(state),
        "private_ips": ips["private_ips"],
        "public_ips": ips["public_ips"],
    }

    return ret
Ejemplo n.º 16
0
def get_config_id(kwargs=None, call=None):
    '''
    Returns a config_id for a given linode.

    .. versionadded:: 2015.8.0

    name
        The name of the Linode for which to get the config_id. Can be used instead
        of ``linode_id``.h

    linode_id
        The ID of the Linode for which to get the config_id. Can be used instead
        of ``name``.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f get_config_id my-linode-config name=my-linode
        salt-cloud -f get_config_id my-linode-config linode_id=1234567
    '''
    if call == 'action':
        raise SaltCloudException(
            'The get_config_id function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    name = kwargs.get('name', None)
    linode_id = kwargs.get('linode_id', None)
    if name is None and linode_id is None:
        raise SaltCloudSystemExit(
            'The get_config_id function requires either a \'name\' or a \'linode_id\' '
            'to be provided.'
        )
    if linode_id is None:
        linode_id = get_linode_id_from_name(name)

    response = _query('linode', 'config.list', args={'LinodeID': linode_id})['DATA']
    config_id = {'config_id': response[0]['ConfigID']}

    return config_id
Ejemplo n.º 17
0
Archivo: xen.py Proyecto: zxstar/salt
def resume(name, call=None, session=None):
    """
    Resume a vm from disk

    .. code-block:: bash

        salt-cloud -a resume xenvm01

    """
    if call == "function":
        raise SaltCloudException(
            "The show_instnce function must be called with -a or --action.")
    if session is None:
        session = _get_session()
    log.info("Resuming VM %s", name)
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.resume(vm, False, True)
    _run_async_task(task, session)
    return show_instance(name)
Ejemplo n.º 18
0
Archivo: xen.py Proyecto: zxstar/salt
def set_vm_ip(name=None,
              ipv4_cidr=None,
              ipv4_gw=None,
              session=None,
              call=None):
    """
    Set the IP address on a virtual interface (vif)

    """
    mode = "static"
    # TODO: Need to add support for IPv6
    if call == "function":
        raise SaltCloudException(
            "The function must be called with -a or --action.")

    log.debug(
        "Setting name: %s ipv4_cidr: %s ipv4_gw: %s mode: %s",
        name,
        ipv4_cidr,
        ipv4_gw,
        mode,
    )
    if session is None:
        log.debug("New session being created")
        session = _get_session()
    vm = _get_vm(name, session)
    # -- try to get ip from vif
    # TODO: for now will take first interface
    #       addition consideration needed for
    #       multiple interface(vif) VMs
    vifs = session.xenapi.VM.get_VIFs(vm)
    if vifs is not None:
        log.debug("There are %s vifs.", len(vifs))
        for vif in vifs:
            record = session.xenapi.VIF.get_record(vif)
            log.debug(record)
            try:
                session.xenapi.VIF.configure_ipv4(vif, mode, ipv4_cidr,
                                                  ipv4_gw)
            except XenAPI.Failure:
                log.info("Static IP assignment could not be performed.")

    return True
Ejemplo n.º 19
0
def show_instance(name, session=None, call=None):
    '''
    Show information about a specific VM or template

        .. code-block:: bash

            salt-cloud -a show_instance xenvm01

    .. note:: memory is memory_dynamic_max

    '''
    if call == 'function':
        raise SaltCloudException(
            'The show_instnce function must be called with -a or --action.'
        )
    log.debug('show_instance-> name: %s session: %s', name, session)
    if session is None:
        session = _get_session()
    vm = _get_vm(name, session=session)
    record = session.xenapi.VM.get_record(vm)
    if not record['is_a_template'] and not record['is_control_domain']:
        try:
            base_template_name = record['other_config']['base_template_name']
        except Exception:
            base_template_name = None
            log.debug(
                'VM %s, doesnt have base_template_name attribute',
                record['name_label']
            )
        ret = {'id': record['uuid'],
               'image': base_template_name,
               'name': record['name_label'],
               'size': record['memory_dynamic_max'],
               'state': record['power_state'],
               'private_ips': get_vm_ip(name, session),
               'public_ips': None}

        __utils__['cloud.cache_node'](
            ret,
            __active_provider_name__,
            __opts__
        )
    return ret
Ejemplo n.º 20
0
def get_pv_args(name, session=None, call=None):
    """
    Get PV arguments for a VM

    .. code-block:: bash

        salt-cloud -a get_pv_args xenvm01

    """
    if call == "function":
        raise SaltCloudException("This function must be called with -a or --action.")
    if session is None:
        log.debug("New session being created")
        session = _get_session()
    vm = _get_vm(name, session=session)
    pv_args = session.xenapi.VM.get_PV_args(vm)
    if pv_args:
        return pv_args
    return None
Ejemplo n.º 21
0
Archivo: xen.py Proyecto: zxstar/salt
def vdi_list(call=None, kwargs=None):
    """
    Return available Xen VDI images

    If this function is called with the ``-f`` or ``--function`` then
    it can return a list with minimal deatil using the ``terse=True`` keyword
    argument.

    .. code-block:: bash

        salt-cloud -f vdi_list myxen terse=True

    """
    if call == "action":
        raise SaltCloudException(
            "This function must be called with -f or --function.")
    log.debug("kwargs is %s", kwargs)
    if kwargs is not None:
        if "terse" in kwargs:
            if kwargs["terse"] == "True":
                terse = True
            else:
                terse = False
        else:
            terse = False
    else:
        kwargs = {}
        terse = False
    session = _get_session()
    vdis = session.xenapi.VDI.get_all()
    ret = {}
    for vdi in vdis:
        data = session.xenapi.VDI.get_record(vdi)
        log.debug(type(terse))
        if terse is True:
            ret[data.get("name_label")] = {
                "uuid": data.get("uuid"),
                "OpqueRef": vdi
            }
        else:
            data.update({"OpaqueRef": vdi})
            ret[data.get("name_label")] = data
    return ret
Ejemplo n.º 22
0
def shutdown(name, call=None, session=None):
    '''
    Shutdown  a vm

    .. code-block:: bash

        salt-cloud -a shutdown xenvm01

    '''
    if call == 'function':
        raise SaltCloudException(
            'The show_instnce function must be called with -a or --action.')
    if session is None:
        session = _get_session()
    log.info('Starting VM {0}'.format(name))
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.shutdown(vm)
    _run_async_task(task, session)
    return show_instance(name)
Ejemplo n.º 23
0
Archivo: xen.py Proyecto: zxstar/salt
def shutdown(name, call=None, session=None):
    """
    Shutdown  a vm

    .. code-block:: bash

        salt-cloud -a shutdown xenvm01

    """
    if call == "function":
        raise SaltCloudException(
            "The show_instnce function must be called with -a or --action.")
    if session is None:
        session = _get_session()
    log.info("Starting VM %s", name)
    vm = _get_vm(name, session)
    task = session.xenapi.Async.VM.shutdown(vm)
    _run_async_task(task, session)
    return show_instance(name)
Ejemplo n.º 24
0
def reboot(name, call=None):
    """
    Reboot a Kamatera server.

    .. versionadded:: 2015.8.0

    name
        The name of the server to reboot.

    CLI Example:

    .. code-block:: bash

        salt-cloud -a reboot server_name
    """
    if call != "action":
        raise SaltCloudException(
            "The show_instance action must be called with -a or --action.")
    return _server_operation(name, "reboot")
Ejemplo n.º 25
0
def show_instance(name, call=None):
    '''
    Displays details about a particular Linode VM. Either a name or a linode_id must
    be provided.

    .. versionadded:: 2015.8.0

    name
        The name of the VM for which to display details.

    CLI Example:

    .. code-block:: bash

        salt-cloud -a show_instance vm_name

    .. note::

        The ``image`` label only displays information about the VM's distribution vendor,
        such as "Debian" or "RHEL" and does not display the actual image name. This is
        due to a limitation of the Linode API.
    '''
    if call != 'action':
        raise SaltCloudException(
            'The show_instance action must be called with -a or --action.')

    node_id = get_linode_id_from_name(name)
    node_data = get_linode(kwargs={'linode_id': node_id})
    ips = get_ips(node_id)
    state = int(node_data['STATUS'])

    ret = {
        'id': node_data['LINODEID'],
        'image': node_data['DISTRIBUTIONVENDOR'],
        'name': node_data['LABEL'],
        'size': node_data['TOTALRAM'],
        'state': _get_status_descr_by_id(state),
        'private_ips': ips['private_ips'],
        'public_ips': ips['public_ips']
    }

    return ret
Ejemplo n.º 26
0
def get_pv_args(name, session=None, call=None):
    '''
    Get PV arguments for a VM

    .. code-block:: bash

        salt-cloud -a get_pv_args xenvm01

    '''
    if call == 'function':
        raise SaltCloudException(
            'This function must be called with -a or --action.')
    if session is None:
        log.debug('New session being created')
        session = _get_session()
    vm = _get_vm(name, session=session)
    pv_args = session.xenapi.VM.get_PV_args(vm)
    if len(pv_args) > 0:
        return pv_args
    return None
Ejemplo n.º 27
0
def show_instance(name, session=None, call=None):
    """
    Show information about a specific VM or template

        .. code-block:: bash

            salt-cloud -a show_instance xenvm01

    .. note:: memory is memory_dynamic_max

    """
    if call == "function":
        raise SaltCloudException(
            "The show_instnce function must be called with -a or --action.")
    log.debug("show_instance-> name: %s session: %s", name, session)
    if session is None:
        session = _get_session()
    vm = _get_vm(name, session=session)
    record = session.xenapi.VM.get_record(vm)
    if not record["is_a_template"] and not record["is_control_domain"]:
        try:
            base_template_name = record["other_config"]["base_template_name"]
        except Exception:  # pylint: disable=broad-except
            base_template_name = None
            log.debug(
                "VM %s, does not have base_template_name attribute",
                record["name_label"],
            )
        ret = {
            "id": record["uuid"],
            "image": base_template_name,
            "name": record["name_label"],
            "size": record["memory_dynamic_max"],
            "state": record["power_state"],
            "private_ips": get_vm_ip(name, session),
            "public_ips": None,
        }

        __utils__["cloud.cache_node"](ret, _get_active_provider_name(),
                                      __opts__)
    return ret
Ejemplo n.º 28
0
def list_nodes(call=None):
    '''
    Returns a list of linodes, keeping only a brief listing.

    CLI Example:

    .. code-block:: bash

        salt-cloud -Q
        salt-cloud --query

    .. note::

        The ``image`` label only displays information about the VM's distribution vendor,
        such as "Debian" or "RHEL" and does not display the actual image name. This is
        due to a limitation of the Linode API.
    '''
    if call == 'action':
        raise SaltCloudException(
            'The list_nodes function must be called with -f or --function.')
    return _list_linodes(full=False)
Ejemplo n.º 29
0
def list_nodes(call=None):
    '''
    Returns a list of devices, keeping only a brief listing.
    CLI Example:
    .. code-block:: bash
        salt-cloud -Q
        salt-cloud --query
        salt-cloud -f list_nodes packet-provider
    ..
    '''

    if call == 'action':
        raise SaltCloudException(
            'The list_nodes function must be called with -f or --function.')

    ret = {}

    for device in get_devices_by_token():
        ret[device.hostname] = device.__dict__

    return ret
Ejemplo n.º 30
0
Archivo: xen.py Proyecto: zxstar/salt
def get_vm_ip(name=None, session=None, call=None):
    """
    Get the IP address of the VM

    .. code-block:: bash

        salt-cloud -a get_vm_ip xenvm01

    .. note:: Requires xen guest tools to be installed in VM

    """
    if call == "function":
        raise SaltCloudException(
            "This function must be called with -a or --action.")
    if session is None:
        log.debug("New session being created")
        session = _get_session()
    vm = _get_vm(name, session=session)
    ret = None
    # -- try to get ip from vif
    vifs = session.xenapi.VM.get_VIFs(vm)
    if vifs is not None:
        for vif in vifs:
            if session.xenapi.VIF.get_ipv4_addresses(vif):
                cidr = session.xenapi.VIF.get_ipv4_addresses(vif).pop()
                ret, subnet = cidr.split("/")
                log.debug("VM vif returned for instance: %s ip: %s", name, ret)
                return ret
    # -- try to get ip from get tools metrics
    vgm = session.xenapi.VM.get_guest_metrics(vm)
    try:
        net = session.xenapi.VM_guest_metrics.get_networks(vgm)
        if "0/ip" in net.keys():
            log.debug("VM guest metrics returned for instance: %s 0/ip: %s",
                      name, net["0/ip"])
            ret = net["0/ip"]
    # except Exception as ex:  # pylint: disable=broad-except
    except XenAPI.Failure:
        log.info("Could not get vm metrics at this time")
    return ret