Exemple #1
0
def get_location(vm_):
    """
    Return the VM's location
    """
    locations = avail_locations()
    vm_location = six.text_type(
        config.get_cloud_config_value("location",
                                      vm_,
                                      __opts__,
                                      search_global=False))

    for location in locations:
        if vm_location in (locations[location]["name"],
                           locations[location]["slug"]):
            return locations[location]["slug"]
    raise SaltCloudNotFound(
        "The specified location, '{0}', could not be found.".format(
            vm_location))
Exemple #2
0
def get_linode_id_from_name(name):
    '''
    Returns the Linode ID for a VM from the provided name.

    name
        The name of the Linode from which to get the Linode ID. Required.
    '''
    nodes = _query('linode', 'list')['DATA']

    linode_id = ''
    for node in nodes:
        if name == node['LABEL']:
            linode_id = node['LINODEID']
            return linode_id

    if not linode_id:
        raise SaltCloudNotFound(
            'The specified name, {0}, could not be found.'.format(name))
def get_location(vm_):
    '''
    Return the VM's location
    '''
    locations = avail_locations()
    vm_location = str(
        config.get_cloud_config_value('location',
                                      vm_,
                                      __opts__,
                                      search_global=False))

    for location in locations:
        if vm_location in (locations[location]['name'],
                           locations[location]['slug']):
            return locations[location]['slug']
    raise SaltCloudNotFound(
        'The specified location, \'{0}\', could not be found.'.format(
            vm_location))
def get_image(vm_):
    '''
    Return the image object to use
    '''
    images = avail_images()
    vm_image = str(
        config.get_cloud_config_value('image',
                                      vm_,
                                      __opts__,
                                      search_global=False))
    for image in images:
        if vm_image in (images[image]['name'], images[image]['slug'],
                        images[image]['id']):
            if images[image]['slug'] is not None:
                return images[image]['slug']
            return int(images[image]['id'])
    raise SaltCloudNotFound(
        'The specified image, {0!r}, could not be found.'.format(vm_image))
Exemple #5
0
def _get_node(name):
    attempts = 5
    while attempts >= 0:
        try:
            return list_nodes_full()[name]
        except KeyError:
            attempts -= 1
            log.debug(
                'Failed to get the data for node \'{0}\'. Remaining '
                'attempts: {1}'.format(
                    name, attempts
                )
            )
            # Just a little delay between attempts...
            time.sleep(0.5)
    raise SaltCloudNotFound(
        'The specified instance {0} not found'.format(name)
    )
def __get_securitygroups(vm_):
    vm_securitygroups = config.get_cloud_config_value("securitygroups",
                                                      vm_,
                                                      __opts__,
                                                      search_global=False)

    if not vm_securitygroups:
        return []

    securitygroups = list_securitygroups()
    for i in range(len(vm_securitygroups)):
        vm_securitygroups[i] = six.text_type(vm_securitygroups[i])
        if vm_securitygroups[i] not in securitygroups:
            raise SaltCloudNotFound(
                "The specified securitygroups '{0}' could not be found.".
                format(vm_securitygroups[i]))

    return vm_securitygroups
def __get_securitygroups(vm_):
    vm_securitygroups = config.get_cloud_config_value("securitygroups",
                                                      vm_,
                                                      __opts__,
                                                      search_global=False)

    if not vm_securitygroups:
        return []

    securitygroups = list_securitygroups()
    for idx, value in enumerate(vm_securitygroups):
        vm_securitygroups[idx] = str(value)
        if vm_securitygroups[idx] not in securitygroups:
            raise SaltCloudNotFound(
                "The specified securitygroups '{}' could not be found.".format(
                    vm_securitygroups[idx]))

    return vm_securitygroups
Exemple #8
0
def get_vm_size(vm_):
    r'''
    Returns the VM's size.

    vm\_
        The VM to get the size for.
    '''
    vm_size = config.get_cloud_config_value('size', vm_, __opts__)
    ram = avail_sizes()[vm_size]['RAM']

    if vm_size.startswith('Linode'):
        vm_size = vm_size.replace('Linode ', '')

    if ram == int(vm_size):
        return ram
    else:
        raise SaltCloudNotFound(
            'The specified size, {0}, could not be found.'.format(vm_size))
Exemple #9
0
def show_image(kwargs, call=None):
    """
    Show the details of Tencent Cloud image

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f show_image tencentcloud image=img-31tjrtph
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_image function must be called with -f or --function")

    if not isinstance(kwargs, dict):
        kwargs = {}

    if "image" not in kwargs:
        raise SaltCloudSystemExit("No image specified.")

    image = kwargs["image"]

    client = get_provider_client("cvm_client")
    req = cvm_models.DescribeImagesRequest()
    req.ImageIds = [image]
    resp = client.DescribeImages(req)

    if not resp.ImageSet:
        raise SaltCloudNotFound(
            "The specified image '{}' could not be found.".format(image))

    ret = {}
    for image in resp.ImageSet:
        ret[image.ImageId] = {
            "ImageName": image.ImageName,
            "ImageType": image.ImageType,
            "ImageSource": image.ImageSource,
            "Platform": image.Platform,
            "Architecture": image.Architecture,
            "ImageSize": "{}GB".format(image.ImageSize),
            "ImageState": image.ImageState,
        }

    return ret
Exemple #10
0
def get_vm_size(vm_):
    r"""
    Returns the VM's size.

    vm\_
        The VM to get the size for.
    """
    vm_size = config.get_cloud_config_value("size", vm_, __opts__)
    ram = avail_sizes()[vm_size]["RAM"]

    if vm_size.startswith("Linode"):
        vm_size = vm_size.replace("Linode ", "")

    if ram == int(vm_size):
        return ram
    else:
        raise SaltCloudNotFound(
            "The specified size, {0}, could not be found.".format(vm_size)
        )
Exemple #11
0
def show_pricing(kwargs=None, call=None):
    '''
    Show pricing for a particular profile. This is only an estimate, based on
    unofficial pricing sources.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_pricing my-linode-config profile=my-linode-profile
    '''
    if call != 'function':
        raise SaltCloudException(
            'The show_instance action must be called with -f or --function.'
        )

    profile = __opts__['profiles'].get(kwargs['profile'], {})
    if not profile:
        raise SaltCloudNotFound(
            'The requested profile was not found.'
        )

    # Make sure the profile belongs to Linode
    provider = profile.get('provider', '0:0')
    comps = provider.split(':')
    if len(comps) < 2 or comps[1] != 'linode':
        raise SaltCloudException(
            'The requested profile does not belong to Linode.'
        )

    plan_id = get_plan_id(kwargs={'label': profile['size']})
    response = _query('avail', 'linodeplans', args={'PlanID': plan_id})['DATA'][0]

    ret = {}
    ret['per_hour'] = response['HOURLY']
    ret['per_day'] = ret['per_hour'] * 24
    ret['per_week'] = ret['per_day'] * 7
    ret['per_month'] = response['PRICE']
    ret['per_year'] = ret['per_month'] * 12

    return {profile['profile']: ret}
Exemple #12
0
def get_linode_id_from_name(name):
    """
    Returns the Linode ID for a VM from the provided name.

    name
        The name of the Linode from which to get the Linode ID. Required.
    """
    nodes = _query("linode", "list")["DATA"]

    linode_id = ""
    for node in nodes:
        if name == node["LABEL"]:
            linode_id = node["LINODEID"]
            return linode_id

    if not linode_id:
        raise SaltCloudNotFound(
            "The specified name, {0}, could not be found.".format(name)
        )
Exemple #13
0
def show_image(kwargs, call=None):
    '''
    Show the details from QingCloud concerning an image.

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f show_image my-qingcloud image=trustysrvx64c
        salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
        salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_images function must be called with '
            '-f or --function'
        )

    if not isinstance(kwargs, dict):
        kwargs = {}

    images = kwargs['image']
    images = images.split(',')

    params = {
        'action': 'DescribeImages',
        'images': images,
        'zone': _get_specified_zone(kwargs, get_configured_provider()),
    }

    items = query(params=params)

    if len(items['image_set']) == 0:
        raise SaltCloudNotFound('The specified image could not be found.')

    result = {}
    for image in items['image_set']:
        result[image['image_id']] = {}
        for key in image:
            result[image['image_id']][key] = image[key]

    return result
Exemple #14
0
def show_image(kwargs, call=None):
    '''
    Show the details from aliyun image
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_images function must be called with '
            '-f or --function'
        )

    if not isinstance(kwargs, dict):
        kwargs = {}

    location = get_location()
    if 'location' in kwargs:
        location = kwargs['location']

    params = {
        'Action': 'DescribeImages',
        'RegionId': location,
        'ImageId': kwargs['image']
    }

    ret = {}
    items = query(params=params)
    # DescribeImages so far support input multi-image. And
    # if not found certain image, the response will include
    # blank image list other than 'not found' error message
    if 'Code' in items or len(items['Images']['Image']) == 0:
        raise SaltCloudNotFound('The specified image could not be found.')

    log.debug(
        'Total %s image found in Region %s',
        items['TotalCount'], location
    )

    for image in items['Images']['Image']:
        ret[image['ImageId']] = {}
        for item in image:
            ret[image['ImageId']][item] = six.text_type(image[item])

    return ret
Exemple #15
0
def get_image(conn, vm_):
    '''
    Return the image object to use
    '''
    image_list = conn.image_list()

    vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
        'ascii', 'salt-cloud-force-ascii')

    for img in image_list:
        if vm_image in (image_list[img]['id'], img):
            return image_list[img]['id']

    try:
        image = conn.image_show(vm_image)
        return image['id']
    except novaclient.exceptions.NotFound as exc:
        raise SaltCloudNotFound(
            'The specified image, {0!r}, could not be found: {1}'.format(
                vm_image, str(exc)))
Exemple #16
0
def __get_location(vm_):
    '''
    Return the Tencent Cloud region to use, in this order:
        - CLI parameter
        - VM parameter
        - Cloud profile setting
    '''
    vm_location = six.text_type(
        __opts__.get(
            'location',
            config.get_cloud_config_value('location',
                                          vm_ or get_configured_provider(),
                                          __opts__,
                                          default=DEFAULT_REGION,
                                          search_global=False)))

    if not vm_location:
        raise SaltCloudNotFound('No location specified.')

    return vm_location
Exemple #17
0
def _get_node(name):
    '''
    Return Tencent Cloud instance detail by name
    '''
    attempts = 5
    while attempts >= 0:
        try:
            client = get_provider_client("cvm_client")
            req = cvm_models.DescribeInstancesRequest()
            req.Filters = [{"Name": "instance-name", "Values": [name]}]
            resp = client.DescribeInstances(req)
            return resp.InstanceSet[0]
        except Exception as ex:
            attempts -= 1
            log.debug(
                'Failed to get data for node \'%s\': %s. Remaining attempts: %d',
                name, ex, attempts)
            time.sleep(0.5)

    raise SaltCloudNotFound('Failed to get instance info {0}'.format(name))
Exemple #18
0
def get_image(vm_):
    '''
    Return the image object to use
    '''
    images = avail_images()
    vm_image = config.get_cloud_config_value('image',
                                             vm_,
                                             __opts__,
                                             search_global=False)
    if not isinstance(vm_image, six.string_types):
        vm_image = six.text_type(vm_image)

    for image in images:
        if vm_image in (images[image]['name'], images[image]['slug'],
                        images[image]['id']):
            if images[image]['slug'] is not None:
                return images[image]['slug']
            return int(images[image]['id'])
    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image))
Exemple #19
0
def show_image(kwargs, call=None):
    """
    Show the details from QingCloud concerning an image.

    CLI Examples:

    .. code-block:: bash

        salt-cloud -f show_image my-qingcloud image=trustysrvx64c
        salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
        salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_images function must be called with " "-f or --function"
        )

    if not isinstance(kwargs, dict):
        kwargs = {}

    images = kwargs["image"]
    images = images.split(",")

    params = {
        "action": "DescribeImages",
        "images": images,
        "zone": _get_specified_zone(kwargs, get_configured_provider()),
    }

    items = query(params=params)

    if not items["image_set"]:
        raise SaltCloudNotFound("The specified image could not be found.")

    result = {}
    for image in items["image_set"]:
        result[image["image_id"]] = {}
        for key in image:
            result[image["image_id"]][key] = image[key]

    return result
Exemple #20
0
def get_size(vm_):
    '''
    Return the VM's size object
    '''
    vm_size = config.get_cloud_config_value(
        'fixed_instance_size', vm_, __opts__, default=None,
        search_global=False
    )
    sizes = avail_sizes()

    if not vm_size:
        size = next((item for item in sizes if item['name'] == 'S'), None)
        return size

    size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
    if size:
        return size

    raise SaltCloudNotFound(
        'The specified size, \'{0}\', could not be found.'.format(vm_size)
    )
Exemple #21
0
def show_pricing(kwargs=None, call=None):
    """
    Show pricing for a particular profile. This is only an estimate, based on
    unofficial pricing sources.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt-cloud -f show_pricing my-linode-config profile=my-linode-profile
    """
    if call != "function":
        raise SaltCloudException(
            "The show_instance action must be called with -f or --function.")

    profile = __opts__["profiles"].get(kwargs["profile"], {})
    if not profile:
        raise SaltCloudNotFound("The requested profile was not found.")

    # Make sure the profile belongs to Linode
    provider = profile.get("provider", "0:0")
    comps = provider.split(":")
    if len(comps) < 2 or comps[1] != "linode":
        raise SaltCloudException(
            "The requested profile does not belong to Linode.")

    plan_id = get_plan_id(kwargs={"label": profile["size"]})
    response = _query("avail", "linodeplans", args={"PlanID":
                                                    plan_id})["DATA"][0]

    ret = {}
    ret["per_hour"] = response["HOURLY"]
    ret["per_day"] = ret["per_hour"] * 24
    ret["per_week"] = ret["per_day"] * 7
    ret["per_month"] = response["PRICE"]
    ret["per_year"] = ret["per_month"] * 12

    return {profile["profile"]: ret}
Exemple #22
0
def show_image(kwargs, call=None):
    """
    Show the details from aliyun image
    """
    if call != "function":
        raise SaltCloudSystemExit(
            "The show_images function must be called with "
            "-f or --function")

    if not isinstance(kwargs, dict):
        kwargs = {}

    location = get_location()
    if "location" in kwargs:
        location = kwargs["location"]

    params = {
        "Action": "DescribeImages",
        "RegionId": location,
        "ImageId": kwargs["image"],
    }

    ret = {}
    items = query(params=params)
    # DescribeImages so far support input multi-image. And
    # if not found certain image, the response will include
    # blank image list other than 'not found' error message
    if "Code" in items or not items["Images"]["Image"]:
        raise SaltCloudNotFound("The specified image could not be found.")

    log.debug("Total %s image found in Region %s", items["TotalCount"],
              location)

    for image in items["Images"]["Image"]:
        ret[image["ImageId"]] = {}
        for item in image:
            ret[image["ImageId"]][item] = str(image[item])

    return ret
Exemple #23
0
def get_distribution_id(vm_):
    r'''
    Returns the distribution ID for a VM

    vm\_
        The VM to get the distribution ID for
    '''
    distributions = _query('avail', 'distributions')['DATA']
    vm_image_name = config.get_cloud_config_value('image', vm_, __opts__)

    distro_id = ''

    for distro in distributions:
        if vm_image_name == distro['LABEL']:
            distro_id = distro['DISTRIBUTIONID']
            return distro_id

    if not distro_id:
        raise SaltCloudNotFound(
            'The DistributionID for the \'{0}\' profile could not be found.\n'
            'The \'{1}\' instance could not be provisioned.'.format(
                vm_image_name, vm_['name']))
Exemple #24
0
def _get_node(name):
    """
    Return Tencent Cloud instance detail by name
    """
    attempts = 5
    while attempts >= 0:
        try:
            client = get_provider_client("cvm_client")
            req = cvm_models.DescribeInstancesRequest()
            req.Filters = [{"Name": "instance-name", "Values": [name]}]
            resp = client.DescribeInstances(req)
            return resp.InstanceSet[0]
        except Exception as ex:  # pylint: disable=broad-except
            attempts -= 1
            log.debug(
                "Failed to get data for node '%s': %s. Remaining attempts: %d",
                name,
                ex,
                attempts,
            )
            time.sleep(0.5)

    raise SaltCloudNotFound("Failed to get instance info {}".format(name))
Exemple #25
0
def __get_location(vm_):
    """
    Return the Tencent Cloud region to use, in this order:
        - CLI parameter
        - VM parameter
        - Cloud profile setting
    """
    vm_location = str(
        __opts__.get(
            "location",
            config.get_cloud_config_value(
                "location",
                vm_ or get_configured_provider(),
                __opts__,
                default=DEFAULT_REGION,
                search_global=False,
            ),
        ))

    if not vm_location:
        raise SaltCloudNotFound("No location specified.")

    return vm_location
Exemple #26
0
def get_image(vm_):
    """
    Return the image object to use
    """
    images = avail_images()
    vm_image = config.get_cloud_config_value("image",
                                             vm_,
                                             __opts__,
                                             search_global=False)
    if not isinstance(vm_image, six.string_types):
        vm_image = six.text_type(vm_image)

    for image in images:
        if vm_image in (
                images[image]["name"],
                images[image]["slug"],
                images[image]["id"],
        ):
            if images[image]["slug"] is not None:
                return images[image]["slug"]
            return int(images[image]["id"])
    raise SaltCloudNotFound(
        "The specified image, '{0}', could not be found.".format(vm_image))
Exemple #27
0
def get_size(vm_):
    """
    Return the VM's size object
    """
    vm_size = config.get_cloud_config_value(
        "fixed_instance_size", vm_, __opts__, default=None, search_global=False
    )
    sizes = avail_sizes()

    if not vm_size:
        size = next((item for item in sizes if item["name"] == "S"), None)
        return size

    size = next(
        (item for item in sizes if item["name"] == vm_size or item["id"] == vm_size),
        None,
    )
    if size:
        return size

    raise SaltCloudNotFound(
        "The specified size, '{}', could not be found.".format(vm_size)
    )
Exemple #28
0
def get_location(vm_):
    '''
    Return the VM's location.

    vm_
        The VM for which to obtain a location.
    '''
    locations = avail_locations()
    vm_location = str(
        config.get_cloud_config_value('location',
                                      vm_,
                                      __opts__,
                                      search_global=False))

    if vm_location == 'None':
        return None

    for location in locations:
        if vm_location in (locations[location]['name'],
                           locations[location]['id']):
            return locations[location]['id']
    raise SaltCloudNotFound(
        'The specified location, {0!r}, could not be found.'.format(
            vm_location))
Exemple #29
0
def show_instance(instance_id, call=None, kwargs=None):
    '''
    Show the details from QingCloud concerning an instance.

    CLI Examples:

    .. code-block:: bash

        salt-cloud -a show_instance i-2f733r5n
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.')

    params = {
        'action':
        'DescribeInstances',
        'instances.1':
        instance_id,
        'zone':
        _get_specified_zone(kwargs=None, provider=get_configured_provider()),
    }
    items = query(params=params)

    if items['total_count'] == 0:
        raise SaltCloudNotFound(
            'The specified instance, \'{0}\', could not be found.'.format(
                instance_id))

    full_node = items['instance_set'][0]
    normalized_node = _show_normalized_node(full_node)
    full_node.update(normalized_node)

    result = full_node

    return result
Exemple #30
0
def show_instance(instance_id, call=None, kwargs=None):
    """
    Show the details from QingCloud concerning an instance.

    CLI Examples:

    .. code-block:: bash

        salt-cloud -a show_instance i-2f733r5n
    """
    if call != "action":
        raise SaltCloudSystemExit(
            "The show_instance action must be called with -a or --action.")

    params = {
        "action":
        "DescribeInstances",
        "instances.1":
        instance_id,
        "zone":
        _get_specified_zone(kwargs=None, provider=get_configured_provider()),
    }
    items = query(params=params)

    if items["total_count"] == 0:
        raise SaltCloudNotFound(
            "The specified instance, '{}', could not be found.".format(
                instance_id))

    full_node = items["instance_set"][0]
    normalized_node = _show_normalized_node(full_node)
    full_node.update(normalized_node)

    result = full_node

    return result