Esempio n. 1
0
def create_provider_image():
    try:
        _request_data = RESTtools.form_data_for_content_type(request.headers.get("Content-Type"))
        image_id = _request_data.get("image_id")
        build_id = _request_data.get("build_id")
        target_image_id = _request_data.get("target_image_id")
        return push_image(image_id, build_id, target_image_id)
    except KeyError as e:
        log.exception(e)
        raise HTTPResponse(
            status=400, output="Missing one or more of 'image_id', 'build_id', or 'target_image_id': %s" % e
        )
    except Exception as e:
        log.exception(e)
        raise HTTPResponse(status=500, output=e)
Esempio n. 2
0
def push_image(image_id, build_id, target_image_id):
    try:
        _request_data = RESTtools.form_data_for_content_type(request.headers.get("Content-Type"))
        provider = _request_data["provider"]
        credentials = _request_data["credentials"]
        job = BuildDispatcher().push_image_to_providers(image_id, build_id, (provider,), credentials)[0]
        provider_image_id = job.new_image_id
        response.status = 202
        return {"_type": "provider_image", "id": provider_image_id, "href": "%s/%s" % (request.url, provider_image_id)}

    except KeyError as e:
        log.exception(e)
        raise HTTPResponse(status=400, output="Missing either 'provider' or 'credentials' in request: %s" % e)
    except Exception as e:
        log.exception(e)
        raise HTTPResponse(status=500, output=e)
Esempio n. 3
0
def create_image(image_collection, base_image_id=None, target_image_id=None):
    try:
        request_data = RESTtools.form_data_for_content_type(request.headers.get('Content-Type'))
        req_base_img_id = request_data.get('base_image_id')
        req_target_img_id = request_data.get('target_image_id')
        base_img_id = req_base_img_id if req_base_img_id else base_image_id
        target_img_id = req_target_img_id if req_target_img_id else target_image_id

        if(image_collection == 'base_images'):
            builder = BuildDispatcher().builder_for_base_image(template=request_data.get('template'),
                                                               parameters=request_data.get('parameters'))
            image = builder.base_image
        elif(image_collection == 'target_images'):
            builder = BuildDispatcher().builder_for_target_image(target=request_data.get('target'),
                                                                 image_id=base_img_id,
                                                                 template=request_data.get('template'),
                                                                 parameters=request_data.get('parameters'))
            image = builder.target_image
        elif(image_collection == 'provider_images'):
            builder = BuildDispatcher().builder_for_provider_image(provider=request_data.get('provider'),
                                                                   credentials=request_data.get('credentials'),
                                                                   target=request_data.get('target'),
                                                                   image_id=target_img_id,
                                                                   template=request_data.get('template'),
                                                                   parameters=request_data.get('parameters'))
            image = builder.provider_image
        else:
            raise HTTPResponse(status=400, output="'image_collection' is None")

        _response = {'_type':type(image).__name__,
                     'id':image.identifier,
                     'href':'%s/%s' % (request.url, image.identifier)}
        for key in image.metadata():
            if key not in ('identifier', 'data'):
                _response[key] = getattr(image, key, None)

        response.status = 202
        return _response
    except Exception as e:
        log.exception(e)
        raise HTTPResponse(status=500, output=e)
Esempio n. 4
0
def operate_on_image_with_id(image_collection, image_id):
    log.debug("In the generic route (%s)" % request.method)
    image_type = image_collection[0:-1]

    if image_type not in [ 'target_image', 'provider_image' ]:
        raise HTTPResponse(status=500, output='Attempt to access invalid image type: %s' % image_type)

    if request.method == "GET":
        log.debug("In the generic GET")
	try:
	    image = PersistentImageManager.default_manager().image_with_id(image_id)
	    if(not image):
                log.error("Did search for image with id (%s) and got (%s)" % (image_id, image))
		raise HTTPResponse(status=404, output='No image found with id: %s' % (image_id))
            else:
                log.debug("Found image id (%s). Constructing response" % (image_id))
	    _type = type(image).__name__
	    _response = {'_type':_type,
			 'id':image.identifier,
			 'href':request.url}
	    for key in image.metadata():
		if key not in ('identifier', 'data', 'base_image_id', 'target_image_id'):
		    _response[key] = getattr(image, key, None)

	    api_url = '%s://%s/imagefactory' % (request.urlparts[0], request.urlparts[1])

	    if(_type == "TargetImage"):
		_objtype = 'target_image'
	    elif(_type == "ProviderImage"):
		_objtype = 'provider_image'
	    else:
		log.error("Returning HTTP status 500 due to unknown image type: %s" % _type)
		raise HTTPResponse(status=500, output='Bad type for found object: %s' % _type) 

            if _objtype != image_type:
                raise HTTPResponse(status=500, output='Requested image type %s got image of type %s' % (image_type, _objtype))

	    response.status = 200
	    return {_objtype:_response}
	except Exception as e:
	    log.exception(e)
	    raise HTTPResponse(status=500, output=e)

#@rest_api.get('/imagefactory/<image_collection>')
#@rest_api.get('/imagefactory/target_images/<target_image_id>/<image_collection>')
#@log_request
#@oauth_protect
#def list_images(image_collection, base_image_id=None, target_image_id=None, list_url=None):
#    try:
#        fetch_spec = {}
#        if(image_collection == 'target_images'):
#            fetch_spec['type'] = 'TargetImage'
#        elif(image_collection == 'provider_images'):
#            fetch_spec['type'] = 'ProviderImage'
#            if target_image_id:
#                fetch_spec['target_image_id'] = target_image_id
#        else:
#            raise HTTPResponse(status=404, output='%s not found' % image_collection)
#
#        fetched_images = PersistentImageManager.default_manager().images_from_query(fetch_spec)
#        images = list()
#        _url = list_url if list_url else request.url
#        for image in fetched_images:
#            resp_item = {image_collection[0:-1]:
#                            {'_type':type(image).__name__,
#                            'id':image.identifier,
#                            'href':'%s/%s' % (_url, image.identifier)}
#                        }
#            images.append(resp_item)
#
#        return images
#    except Exception as e:
#        log.exception(e)
#        raise HTTPResponse(status=500, output=e)

#@rest_api.post('/imagefactory/target_images/<target_image_id>')
#@log_request
#@oauth_protect
#def clone_target_image(target_image_id):
    elif request.method == "POST":
        try:
	    if image_type == 'target_image':
		request_data = RESTtools.form_data_for_content_type(request.headers.get('Content-Type'))    

		(target_image, upload_id) = SecondaryDispatcher().prep_target_image_clone(request_data, image_id)

		_response = { }
		_response['target_image'] = {'_type':type(target_image).__name__,
					     'id':target_image.identifier,
					     'href':'%s' % (request.url)}
		for key in target_image.metadata():
		    if key not in ('identifier', 'data'):
			_response['target_image'][key] = getattr(target_image, key, None)
		
		if upload_id:
		    _response['upload_id'] = upload_id

		response.status = 202
		return _response
	    else:
		request_data = RESTtools.form_data_for_content_type(request.headers.get('Content-Type'))
		if(not request_data):
		    raise HTTPResponse(status=400, output='%s not found in request.' % (image_type))

		req_target_img_id = request_data.get('target_image_id')
		target_img_id = req_target_img_id if req_target_img_id else target_image_id

		builder = BuildDispatcher().builder_for_provider_image(provider=request_data.get('provider'),
								       credentials=request_data.get('credentials'),
								       target=request_data.get('target'),
								       image_id=target_img_id,
								       template=request_data.get('template'),
								       parameters=request_data.get('parameters'),
								       my_image_id=image_id)
		image = builder.provider_image

		_response = {'_type':type(image).__name__,
			     'id':image.identifier,
			     'href':'%s/%s' % (request.url, image.identifier)}
		for key in image.metadata():
		    if key not in ('identifier', 'data'):
			_response[key] = getattr(image, key, None)

		response.status = 202
		return {image_collection[0:-1]:_response}
        except Exception as e:
            log.exception(e)
	    raise HTTPResponse(status=500, output=e)
    else:
	raise HTTPResponse(status=405)
Esempio n. 5
0
def build_image(image_id=None):
    help_txt = """To build a new target image, supply a template and list of targets to build for.
To import an image, supply target_name, provider_name, target_identifier, and image_descriptor."""

    _request_data = RESTtools.form_data_for_content_type(request.headers.get("Content-Type"))
    # build image arguments
    template = _request_data.get("template")
    targets = _request_data.get("targets")
    build_id = _request_data.get("build_id")  # optional
    # import image arguments
    target_name = _request_data.get("target_name")
    provider_name = _request_data.get("provider_name")
    target_identifier = _request_data.get("target_identifier")
    image_descriptor = _request_data.get("image_descriptor")

    if template and targets:
        try:
            if build_id and not image_id:
                raise Exception("The parameter build_id must be used with a specific image_id...")
            jobs = BuildDispatcher().build_image_for_targets(image_id, build_id, template, targets.split(","))
            if image_id:
                base_url = request.url
            else:
                image_id = jobs[0].image_id
                base_url = "%s/%s" % (request.url, image_id)

            image = {"_type": "image", "id": image_id, "href": base_url}
            if not build_id:
                build_id = jobs[0].build_id
            build = {"_type": "build", "id": build_id, "href": "%s/builds/%s" % (base_url, build_id)}
            target_images = []
            for job in jobs:
                target_image_id = job.new_image_id
                target_images.append(
                    {
                        "_type": "target_image",
                        "id": target_image_id,
                        "href": "%s/builds/%s/target_images/%s" % (base_url, build_id, target_image_id),
                    }
                )
            build["target_images"] = target_images
            image["build"] = build

            response.status = 202
            return image
        except Exception as e:
            log.exception(e)
            raise HTTPResponse(status=500, output=e)

    elif target_name and provider_name and target_identifier and image_descriptor:
        image_id = _request_data.get("image_id")
        build_id = _request_data.get("build_id")
        try:
            import_result = BuildDispatcher().import_image(
                image_id, build_id, target_identifier, image_descriptor, target_name, provider_name
            )
            image_id = import_result[0]
            base_url = "%s/%s" % (request.url, image_id)
            image = {"_type": "image", "id": image_id, "href": base_url}
            build_id = import_result[1]
            build = {"_type": "build", "id": build_id, "href": "%s/builds/%s" % (base_url, build_id)}
            target_image_id = import_result[2]
            target_image = {
                "_type": "target_image",
                "id": target_image_id,
                "href": "%s/builds/%s/target_images/%s" % (base_url, build_id, target_image_id),
            }
            provider_image_id = import_result[3]
            provider_image = {
                "_type": "provider_image",
                "id": provider_image_id,
                "href": "%s/builds/%s/target_images/%s/provider_images/%s"
                % (base_url, build_id, target_image_id, provider_image_id),
            }

            target_image["provider_images"] = (provider_image,)
            build["target_images"] = (target_image,)
            image["build"] = build

            response.status = 200
            return image
        except Exception as e:
            log.exception(e)
            raise HTTPResponse(status=500, output=e)
    else:
        raise HTTPResponse(status=400, output=help_txt)