def import_glance_image(request): """ Imports Openstack Glance image into Wistar. :param request: JSON payload that contains a single object with the following properties: image_name, image_type, image_descr :return: a JSON object with at least the following properties: status (boolean) and message """ logger.debug("<---- API call import_glance_images ---->") if openstackUtils.connect_to_openstack(): json_string = request.body try: json_body = json.loads(json_string) except ValueError as ve: logger.error( 'Could not parse json payload with error <{0}>'.format( ve.message)) return apiUtils.return_json(False, "Could not parse json payload!") logger.debug(json_body) required_fields = {'image_name', 'image_type', 'image_descr'} if not required_fields.issubset(json_body): logger.error("Invalid parameters in json body") return apiUtils.return_json(False, "Invalid parameters in json payload") image_name = json_body["image_name"] image_type = json_body["image_type"] image_decr = json_body["image_descr"] logger.debug( "<---- API call import_glance_image: <{0}> START ---->".format( image_name)) if Image.objects.filter(name=image_name).exists(): logger.info('image with name %s already exists' % image_name) return apiUtils.return_json(True, "Glance images already imported") image = Image() image.description = image_decr + ' image imported from Glance' image.name = image_name image.type = image_type image.save() logger.debug( "<---- API call import_glance_image: <{0}> DONE ---->".format( image_name)) return apiUtils.return_json(True, "Glance images successfully imported") else: return apiUtils.return_json(False, "Failed to authenticate")
def create_from_instance(request, uuid): logger.debug("Creating new image from instance") domain = libvirtUtils.get_domain_by_uuid(uuid) logger.debug("got domain " + domain.name()) domain_image = libvirtUtils.get_image_for_domain(uuid) logger.debug("got domain_image: " + domain_image) if osUtils.is_image_thin_provisioned(domain_image): logger.error( "Cannot clone disk that is thinly provisioned! Please perform a block pull before continuing" ) context = { 'error': "Cannot Clone thinly provisioned disk! Please perform a block pull!" } return render(request, 'error.html', context) domain_name = domain.name() # FIXME - make these variable names a bit more clear about their meaning # we need to get the path of the image relative to the MEDIA_ROOT media_root = settings.MEDIA_ROOT media_root_array = media_root.split("/") len_media_root = len(media_root_array) full_path_array = domain_image.split("/") full_path = "/".join(full_path_array[:full_path_array.index('instances')]) # grab the file path of the domain image without the MEDIA_ROOT prepended file_path_array = domain_image.split('/')[len_media_root:] images_dir = "/".join(file_path_array[:file_path_array.index('instances')]) new_relative_image_path = images_dir + "/image_" + str( domain.UUIDString()) + ".img" new_full_image_path = full_path + "/image_" + str( domain.UUIDString()) + ".img" if osUtils.check_path(new_full_image_path): logger.info("Image has already been cloned") context = {'error': "Instance has already been cloned!"} return render(request, 'error.html', context) logger.debug("Copying image from " + domain_image) logger.debug("To " + new_full_image_path) osUtils.copy_image_to_clone(domain_image, new_full_image_path) image = Image() image.name = "image_" + str(domain.UUIDString()) image.description = "Clone of " + domain_name image.filePath = new_relative_image_path image.save() return HttpResponseRedirect('/images/')
def import_from_glance(request, glance_id): """ Creates a local db entry for the glance image Everything in Wistar depends on a db entry in the Images table If you have an existing openstack cluster, you may want to import those images here without having to physically copy the images to local disk :param request: HTTPRequest object :param glance_id: id of the glance image to import :return: redirect to /images/image_id """ if openstackUtils.connect_to_openstack(): image_details = openstackUtils.get_glance_image_detail(glance_id) image = Image() image.description = "Imported from Glance" image.name = image_details["name"] image.type = 'blank' image.save() logger.debug("All done") return HttpResponseRedirect('/images/%s' % image.id) context = {'error': "Could not connect to OpenStack"} return render(request, 'error.html', context)
def create_blank(request): image_form = ImageBlankForm(request.POST) logger.debug(image_form) logger.debug(str(image_form)) if image_form.is_valid(): name = request.POST["name"] size = request.POST["size"] description = request.POST["description"] file_path = 'user_images/' + name if ".img" not in file_path: file_path += ".img" full_path = settings.MEDIA_ROOT + "/" + file_path if osUtils.create_blank_image(full_path, size + 'G'): image = Image() image.description = description image.name = name image.filePath = file_path image.type = 'blank' image.save() # if not osUtils.checkPath(image_form.cleaned_data['path']): # logger.debug("PATH DOESN'T EXIST") # context = {'error' : "PATH DOESNT EXIST"} # return render(request, 'error.html', context) logger.debug("Saving form") # image_form.save() return HttpResponseRedirect('/images') else: context = {'image_form': image_form} return render(request, 'images/new_blank.html', context)
def image_add(request): """ View for simple creating image. """ if request.method == 'POST': # form sended form = ImageAddForm(data=request.POST, files=request.FILES) if form.is_valid(): imag = form.save(commit=False) new_item = Image(image=request.FILES['image'], user=request.user, title=form.cleaned_data['title']) new_item.description = form.cleaned_data['description'] new_item.tags = form.cleaned_data['tags'] request.user.profile.rating += 3 request.user.profile.save() new_item.save() imag.user = request.user imag.save() tags = form.cleaned_data['tags'] for tag in tags: imag.tags.add(tag) imag.save() # Without this next line the tags won't be saved. form.save_m2m() create_action(request.user, 'bookmarked image', new_item) messages.success(request, 'Image added successfully') return redirect(new_item.get_absolute_url()) else: form = ImageAddForm() return render(request, 'images/image/addnew.html', {'form': form})
def create_local_image(name, description, file_path, image_type): """ Register a local (server-side) image with Wistar :param name: name of the image :param description: Description of the image :param file_path: full path to the where the file exists on the server :param image_type: The wistar type of the image, this type must already be registered in Wistar :return: The local id of the image """ if image_exists(name): logger.info('Image with this name already exists!') try: existing_image = Image.objects.get(name=name) return existing_image.id except Image.DoesNotExist: logger.error('Image already exists but we cannot get it locally!') pass if osUtils.check_path(file_path): logger.debug("path exists") if settings.MEDIA_ROOT not in file_path: raise Exception("Image must in in path: %s" % settings.MEDIA_ROOT) else: logger.debug("removing media_root") file_path = file_path.replace(settings.MEDIA_ROOT + '/', '') logger.debug(file_path) else: raise Exception("Invalid image path") try: logger.debug(file_path) image = Image() image.description = description image.name = name image.filePath = file_path image.type = image_type image.save() full_path = image.filePath.path if re.match(".*\.vmdk$", full_path): # we need to convert this for KVM based deployments! converted_image_path = re.sub("\.vmdk$", ".qcow2", full_path) converted_image_file_name = converted_image_path.split('/')[-1] if osUtils.convert_vmdk_to_qcow2(full_path, converted_image_path): logger.info("Converted vmdk image to qcow2!") image.filePath = "user_images/%s" % converted_image_file_name image.save() logger.debug("Removing original vmdk") osUtils.remove_instance(full_path) else: logger.error("Could not convert vmdk!") if image_type == "junos_vre" and "jinstall64-vmx-15.1" in full_path: logger.debug("Creating RIOT image for Junos vMX 15.1") # lets replace the last "." with "_riot." if '.' in file_path: new_image_path = re.sub(r"(.*)\.(.*)$", r"\1_riot.\2", full_path) else: # if there is no '.', let's just add one new_image_path = full_path + "_riot.img" new_image_file_name = new_image_path.split('/')[-1] new_image_name = name + ' Riot PFE' if osUtils.copy_image_to_clone(full_path, new_image_path): logger.debug("Copied from %s" % full_path) logger.debug("Copied to %s" % new_image_path) n_image = Image() n_image.name = new_image_name n_image.type = "junos_riot" n_image.description = image.description + "\nRiot PFE" n_image.filePath = "user_images/" + new_image_file_name n_image.save() return image.id except Exception as e: logger.error("Caught Error in create_local_image") logger.error(str(e)) raise
def create_local_image(name, description, file_path, image_type): if osUtils.check_path(file_path): logger.debug("path exists") if settings.MEDIA_ROOT not in file_path: raise Exception("Image must in in path: %s" % settings.MEDIA_ROOT) else: logger.debug("removing media_root") file_path = file_path.replace(settings.MEDIA_ROOT + '/', '') logger.debug(file_path) else: raise Exception("Invalid image path") try: logger.debug(file_path) image = Image() image.description = description image.name = name image.filePath = file_path image.type = image_type image.save() full_path = image.filePath.path if re.match(".*\.vmdk$", full_path): # we need to convert this for KVM based deployments! converted_image_path = re.sub("\.vmdk$", ".qcow2", full_path) converted_image_file_name = converted_image_path.split('/')[-1] if osUtils.convert_vmdk_to_qcow2(full_path, converted_image_path): logger.info("Converted vmdk image to qcow2!") image.filePath = "user_images/%s" % converted_image_file_name image.save() logger.debug("Removing original vmdk") osUtils.remove_instance(full_path) else: logger.error("Could not convert vmdk!") if image_type == "junos_vre" and "jinstall64-vmx-15.1" in full_path: logger.debug("Creating RIOT image for Junos vMX 15.1") # lets replace the last "." with "_riot." if '.' in file_path: new_image_path = re.sub(r"(.*)\.(.*)$", r"\1_riot.\2", full_path) else: # if there is no '.', let's just add one new_image_path = full_path + "_riot.img" new_image_file_name = new_image_path.split('/')[-1] new_image_name = name + ' Riot PFE' if osUtils.copy_image_to_clone(full_path, new_image_path): logger.debug("Copied from %s" % full_path) logger.debug("Copied to %s" % new_image_path) n_image = Image() n_image.name = new_image_name n_image.type = "junos_riot" n_image.description = image.description + "\nRiot PFE" n_image.filePath = "user_images/" + new_image_file_name n_image.save() return image.id except Exception as e: logger.error("Caught Error in create_local_image") logger.error(str(e)) raise
def create(request): try: logger.debug('---- Create Image ----') image_form = ImageForm(request.POST, request.FILES) if not image_form.is_valid(): logger.error("Could not save image for some reason!") context = {'image_form': image_form} return render(request, 'images/new.html', context) # if not osUtils.checkPath(image_form.cleaned_data['path']): # logger.debug("PATH DOESN'T EXIST") # context = {'error' : "PATH DOESNT EXIST"} # return render(request, 'error.html', context) logger.debug("Saving form") orig_image = image_form.save() messages.info(request, "Image uploaded successfully") image_type = request.POST["type"] image_name = request.POST["name"] full_path = orig_image.filePath.path if re.match(".*\.vmdk$", full_path): # we need to convert this for KVM based deployments! converted_image_path = re.sub("\.vmdk$", ".qcow2", full_path) converted_image_file_name = converted_image_path.split('/')[-1] if osUtils.convert_vmdk_to_qcow2(full_path, converted_image_path): logger.info("Converted vmdk image to qcow2!") orig_image.filePath = "user_images/%s" % converted_image_file_name orig_image.save() logger.debug("Removing original vmdk") osUtils.remove_instance(full_path) else: logger.error("Could not convert vmdk!") if image_type == "junos_vre_15" and "jinstall64-vmx-15.1" in full_path: logger.debug("Creating RIOT image for Junos vMX 15.1") # lets replace the last "." with "_riot." if '.' in full_path: new_image_path = re.sub(r"(.*)\.(.*)$", r"\1_riot.\2", full_path) else: # if there is no '.', let's just add one new_image_path = full_path + "_riot.img" new_image_file_name = new_image_path.split('/')[-1] new_image_name = image_name + ' Riot PFE' if osUtils.copy_image_to_clone(full_path, new_image_path): logger.debug("Copied from %s" % full_path) logger.debug("Copied to %s" % new_image_path) image = Image() image.name = new_image_name image.type = "junos_riot" image.description = orig_image.description + "\nRiot PFE" image.filePath = "user_images/" + new_image_file_name image.save() return HttpResponseRedirect('/images') except Exception as e: logger.error(e) messages.info(request, "Could not create image!") return HttpResponseRedirect('/images/')