Пример #1
0
    def upload_image(cls, context, session, instance, vdi_uuids, image_id,
                     options=None):
        """ Requests that the Glance plugin bundle the specified VDIs and
        push them into Glance using the specified human-friendly name.
        """
        # NOTE(sirp): Currently we only support uploading images as VHD, there
        # is no RAW equivalent (yet)
        logging.debug(_("Asking xapi to upload %(vdi_uuids)s as"
                " ID %(image_id)s") % locals())

        os_type = instance.os_type or FLAGS.default_os_type

        glance_host, glance_port = glance.pick_glance_api_server()
        params = {'vdi_uuids': vdi_uuids,
                  'image_id': image_id,
                  'glance_host': glance_host,
                  'glance_port': glance_port,
                  'sr_path': cls.get_sr_path(session),
                  'os_type': os_type,
                  'auth_token': getattr(context, 'auth_token', None),
                  'options': options}

        kwargs = {'params': pickle.dumps(params)}
        task = session.async_call_plugin('glance', 'upload_vhd', kwargs)
        session.wait_for_task(task, instance.id)
Пример #2
0
    def upload_image(cls, context, session, instance, vdi_uuids, image_id):
        """ Requests that the Glance plugin bundle the specified VDIs and
        push them into Glance using the specified human-friendly name.
        """
        # NOTE(sirp): Currently we only support uploading images as VHD, there
        # is no RAW equivalent (yet)
        logging.debug(
            _("Asking xapi to upload %(vdi_uuids)s as"
              " ID %(image_id)s") % locals())

        os_type = instance.os_type or FLAGS.default_os_type

        glance_host, glance_port = \
            glance_image_service.pick_glance_api_server()
        params = {
            'vdi_uuids': vdi_uuids,
            'image_id': image_id,
            'glance_host': glance_host,
            'glance_port': glance_port,
            'sr_path': cls.get_sr_path(session),
            'os_type': os_type,
            'auth_token': getattr(context, 'auth_token', None)
        }

        kwargs = {'params': pickle.dumps(params)}
        task = session.async_call_plugin('glance', 'upload_vhd', kwargs)
        session.wait_for_task(task, instance.id)
Пример #3
0
def get_glance_client(image_href):
    """Get the correct glance client and id for the given image_href.

    The image_href param can be an href of the form
    http://myglanceserver:9292/images/42, or just an int such as 42. If the
    image_href is an int, then flags are used to create the default
    glance client.

    :param image_href: image ref/id for an image
    :returns: a tuple of the form (glance_client, image_id)

    """
    image_href = image_href or 0
    if str(image_href).isdigit():
        glance_host, glance_port = \
            glance_image_service.pick_glance_api_server()
        glance_client = GlanceClient(glance_host, glance_port)
        return (glance_client, int(image_href))

    try:
        (image_id, host, port) = _parse_image_ref(image_href)
    except ValueError:
        raise exception.InvalidImageRef(image_href=image_href)
    glance_client = GlanceClient(host, port)
    return (glance_client, image_id)
Пример #4
0
def get_glance_client(image_href):
    """Get the correct glance client and id for the given image_href.

    The image_href param can be an href of the form
    http://myglanceserver:9292/images/42, or just an int such as 42. If the
    image_href is an int, then flags are used to create the default
    glance client.

    :param image_href: image ref/id for an image
    :returns: a tuple of the form (glance_client, image_id)

    """
    image_href = image_href or 0
    if str(image_href).isdigit():
        glance_host, glance_port = \
            glance_image_service.pick_glance_api_server()
        glance_client = GlanceClient(glance_host, glance_port)
        return (glance_client, int(image_href))

    try:
        (image_id, host, port) = _parse_image_ref(image_href)
    except ValueError:
        raise exception.InvalidImageRef(image_href=image_href)
    glance_client = GlanceClient(host, port)
    return (glance_client, image_id)
Пример #5
0
    def _fetch_image_glance_vhd(cls, context, session, instance, image,
                                image_type):
        """Tell glance to download an image and put the VHDs into the SR

        Returns: A list of dictionaries that describe VDIs
        """
        instance_id = instance.id
        LOG.debug(_("Asking xapi to fetch vhd image %(image)s") % locals())
        sr_ref = safe_find_sr(session)

        # NOTE(sirp): The Glance plugin runs under Python 2.4
        # which does not have the `uuid` module. To work around this,
        # we generate the uuids here (under Python 2.6+) and
        # pass them as arguments
        uuid_stack = [str(uuid.uuid4()) for i in xrange(2)]

        glance_host, glance_port = glance.pick_glance_api_server()
        params = {
            'image_id': image,
            'glance_host': glance_host,
            'glance_port': glance_port,
            'uuid_stack': uuid_stack,
            'sr_path': cls.get_sr_path(session),
            'auth_token': getattr(context, 'auth_token', None)
        }

        kwargs = {'params': pickle.dumps(params)}
        task = session.async_call_plugin('glance', 'download_vhd', kwargs)
        result = session.wait_for_task(task, instance_id)
        # 'download_vhd' will return a json encoded string containing
        # a list of dictionaries describing VDIs.  The dictionary will
        # contain 'vdi_type' and 'vdi_uuid' keys.  'vdi_type' can be
        # 'os' or 'swap' right now.
        vdis = json.loads(result)
        for vdi in vdis:
            LOG.debug(
                _("xapi 'download_vhd' returned VDI of "
                  "type '%(vdi_type)s' with UUID '%(vdi_uuid)s'" % vdi))

        cls.scan_sr(session, instance_id, sr_ref)

        # Pull out the UUID of the first VDI (which is the os VDI)
        os_vdi_uuid = vdis[0]['vdi_uuid']

        # Set the name-label to ease debugging
        vdi_ref = session.get_xenapi().VDI.get_by_uuid(os_vdi_uuid)
        primary_name_label = get_name_label_for_image(image)
        session.get_xenapi().VDI.set_name_label(vdi_ref, primary_name_label)

        cls._check_vdi_size(context, session, instance, os_vdi_uuid)
        return vdis
Пример #6
0
    def _fetch_image_glance_vhd(cls, context, session, instance, image,
                                image_type):
        """Tell glance to download an image and put the VHDs into the SR

        Returns: A list of dictionaries that describe VDIs
        """
        instance_id = instance.id
        LOG.debug(_("Asking xapi to fetch vhd image %(image)s")
                    % locals())
        sr_ref = safe_find_sr(session)

        # NOTE(sirp): The Glance plugin runs under Python 2.4
        # which does not have the `uuid` module. To work around this,
        # we generate the uuids here (under Python 2.6+) and
        # pass them as arguments
        uuid_stack = [str(uuid.uuid4()) for i in xrange(2)]

        glance_host, glance_port = \
            glance_image_service.pick_glance_api_server()
        params = {'image_id': image,
                  'glance_host': glance_host,
                  'glance_port': glance_port,
                  'uuid_stack': uuid_stack,
                  'sr_path': cls.get_sr_path(session),
                  'auth_token': getattr(context, 'auth_token', None)}

        kwargs = {'params': pickle.dumps(params)}
        task = session.async_call_plugin('glance', 'download_vhd', kwargs)
        result = session.wait_for_task(task, instance_id)
        # 'download_vhd' will return a json encoded string containing
        # a list of dictionaries describing VDIs.  The dictionary will
        # contain 'vdi_type' and 'vdi_uuid' keys.  'vdi_type' can be
        # 'os' or 'swap' right now.
        vdis = json.loads(result)
        for vdi in vdis:
            LOG.debug(_("xapi 'download_vhd' returned VDI of "
                    "type '%(vdi_type)s' with UUID '%(vdi_uuid)s'" % vdi))

        cls.scan_sr(session, instance_id, sr_ref)

        # Pull out the UUID of the first VDI (which is the os VDI)
        os_vdi_uuid = vdis[0]['vdi_uuid']

        # Set the name-label to ease debugging
        vdi_ref = session.get_xenapi().VDI.get_by_uuid(os_vdi_uuid)
        primary_name_label = get_name_label_for_image(image)
        session.get_xenapi().VDI.set_name_label(vdi_ref, primary_name_label)

        cls._check_vdi_size(context, session, instance, os_vdi_uuid)
        return vdis
Пример #7
0
    def upload_image(cls, session, instance, vdi_uuids, image_id):
        """ Requests that the Glance plugin bundle the specified VDIs and
        push them into Glance using the specified human-friendly name.
        """
        # NOTE(sirp): Currently we only support uploading images as VHD, there
        # is no RAW equivalent (yet)
        logging.debug(_("Asking xapi to upload %(vdi_uuids)s as" " ID %(image_id)s") % locals())

        os_type = instance.os_type or FLAGS.default_os_type

        glance_host, glance_port = glance_image_service.pick_glance_api_server()
        params = {
            "vdi_uuids": vdi_uuids,
            "image_id": image_id,
            "glance_host": glance_host,
            "glance_port": glance_port,
            "sr_path": cls.get_sr_path(session),
            "os_type": os_type,
        }

        kwargs = {"params": pickle.dumps(params)}
        task = session.async_call_plugin("glance", "upload_vhd", kwargs)
        session.wait_for_task(task, instance.id)
Пример #8
0
def images_on_interval(period_start, period_stop, auth_tok, tenant_id=None):
    """
    Retrieve images statistics for the given interval [``period_start``, ``period_stop``]. 
    ``tenant_id=None`` means all projects.

    Example of the returned value:

    .. code-block:: python

        {
            "1": {
                12: {
                    "created_at": datetime.datetime(2011, 1, 1),
                    "destroyed_at": datetime.datetime(2011, 1, 2),
                    "name": "Gentoo initrd",
                    "usage": {"local_gb": 0.1},
                },
                14: {
                    "created_at": datetime.datetime(2011, 1, 4),
                    "destroyed_at": datetime.datetime(2011, 2, 1),
                    "name": "Ubuntu vmlinuz",
                    "usage": {"local_gb": 2.5},
                },
            },
            "2": {
                24: {
                    "created_at": datetime.datetime(2011, 1, 1),
                    "destroyed_at": datetime.datetime(2011, 1, 2),
                    "name": "RHEL vmlinuz",
                    "usage": {"local_gb": 6.1},
                },
            }
        }

    :returns: a dictionary where keys are project ids and values are project statistics.
    """

    glance_host, glance_port = pick_glance_api_server()
    client = glance_client.Client(glance_host, glance_port, auth_tok=auth_tok)
    images = client.get_images_detailed(filters={"is_public": "none"})
    if tenant_id:
        images = [image for image in images if image["owner"] == tenant_id]
    else:
        images = [image for image in images if image["owner"] is not None]
    report_by_id = {}
    now = utils.now()
    for image in images:
        created_at = utils.str_to_datetime(image["created_at"])
        if created_at >= period_stop:
            continue
        deleted_at = utils.str_to_datetime(image["deleted_at"])
        if deleted_at and deleted_at <= period_start:
            continue
        lifetime = utils.total_seconds(
            min(deleted_at or now, period_stop) -
            max(created_at, period_start))
        if lifetime < 0:
            lifetime = 0
        try:
            tenant_statistics = report_by_id[image["owner"]]
        except KeyError:
            tenant_statistics = {}
            report_by_id[image["owner"]] = tenant_statistics
        tenant_statistics[image["id"]] = {
            "name": image["name"],
            "created_at": created_at,
            "destroyed_at": deleted_at,
            "usage": {"local_gb": image["size"] * lifetime / 2 ** 30}
        }

    return report_by_id