Exemple #1
0
def block_pull(request, uuid):
    domain = libvirtUtils.get_domain_by_uuid(uuid)
    domain_name = domain.name()
    image_path = libvirtUtils.get_image_for_domain(domain.UUIDString())

    if osUtils.is_image_thin_provisioned(image_path):
        logger.debug("Found thinly provisioned image, promoting...")
        rv = libvirtUtils.promote_instance_to_image(domain_name)

        if rv is None:
            messages.info(
                request,
                "Image already promoted. Shut down the instance to perform a clone."
            )
        elif rv:
            messages.info(request, "Promoting thinly provisioned image")
        else:
            messages.info(request, "Error Promoting image!")

    else:
        messages.info(
            request,
            "Image is already promoted. You may now shutdown the image and perform a Clone"
        )
        logger.debug("Image is already promoted")

    return HttpResponseRedirect('/ajax/manageHypervisor/')
Exemple #2
0
def delete(request, topology_id):
    logger.debug('---- topology delete ----')
    topology_prefix = "t%s_" % topology_id

    if configuration.deployment_backend == "kvm":

        network_list = libvirtUtils.get_networks_for_topology(topology_prefix)
        for network in network_list:
            logger.debug("undefine network: " + network["name"])
            libvirtUtils.undefine_network(network["name"])

        domain_list = libvirtUtils.get_domains_for_topology(topology_prefix)
        for domain in domain_list:

            # remove reserved mac addresses for all domains in this topology
            mac_address = libvirtUtils.get_management_interface_mac_for_domain(domain["name"])
            libvirtUtils.release_management_ip_for_mac(mac_address)

            logger.debug("undefine domain: " + domain["name"])
            source_file = libvirtUtils.get_image_for_domain(domain["uuid"])
            if libvirtUtils.undefine_domain(domain["uuid"]):
                if source_file is not None:
                    osUtils.remove_instance(source_file)

        topology = get_object_or_404(Topology, pk=topology_id)

        osUtils.remove_instances_for_topology(topology_prefix)
        osUtils.remove_cloud_init_tmp_dirs(topology_prefix)

    topology.delete()
    messages.info(request, 'Topology %s deleted' % topology.name)
    return HttpResponseRedirect('/topologies/')
Exemple #3
0
def delete_topology(request):
    """
    DEPRECATED
    :param request:
    :return:
    """

    logger.debug("---- delete_topology ----")
    json_string = request.body
    json_body = json.loads(json_string)

    required_fields = set(['name'])
    if not required_fields.issubset(json_body[0]):
        logger.error("Invalid parameters in json body")
        return HttpResponse(status=500)

    topology_name = json_body[0]["name"]

    try:
        # get the topology by name
        topology = Topology.objects.get(name=topology_name)

    except ObjectDoesNotExist:
        return apiUtils.return_json(False, "Topology is already deleted or does not exist")

    try:
        topology_prefix = "t%s_" % topology.id

        if hasattr(configuration, "use_openvswitch") and configuration.use_openvswitch:
            use_ovs = True
        else:
            use_ovs = False

        network_list = libvirtUtils.get_networks_for_topology(topology_prefix)
        for network in network_list:
            logger.debug("undefining network: " + network["name"])
            libvirtUtils.undefine_network(network["name"])
            if use_ovs:
                ovsUtils.delete_bridge(network["name"])

        domain_list = libvirtUtils.get_domains_for_topology(topology_prefix)
        for domain in domain_list:
            logger.debug("undefining domain: " + domain["name"])
            source_file = libvirtUtils.get_image_for_domain(domain["uuid"])
            if libvirtUtils.undefine_domain(domain["uuid"]):
                if source_file is not None:
                    osUtils.remove_instance(source_file)

            # remove reserved mac addresses for all domains in this topology
            mac_address = libvirtUtils.get_management_interface_mac_for_domain(domain["name"])
            libvirtUtils.release_management_ip_for_mac(mac_address)

        topology.delete()
        return apiUtils.return_json(True, "Topology deleted!")

    except Exception as e:
        logger.error(str(e))
        return HttpResponse(status=500)
Exemple #4
0
def redeploy_topology(request):
    required_fields = set(['json', 'topologyId'])
    if not required_fields.issubset(request.POST):
        return render(request, 'ajax/ajaxError.html',
                      {'error': "No Topology Id in request"})

    topology_id = request.POST['topologyId']
    j = request.POST['json']
    try:
        topo = Topology.objects.get(pk=topology_id)
        topo.json = j
        topo.save()
    except ObjectDoesNotExist:
        return render(request, 'ajax/ajaxError.html',
                      {'error': "Topology doesn't exist"})

    try:
        domains = libvirtUtils.get_domains_for_topology(topology_id)
        config = wistarUtils.load_config_from_topology_json(
            topo.json, topology_id)

        logger.debug('checking for orphaned domains first')
        # find domains we no longer need
        for d in domains:
            logger.debug('checking domain: %s' % d['name'])
            found = False
            for config_device in config["devices"]:
                if config_device['name'] == d['name']:
                    found = True
                    continue

            if not found:
                logger.info("undefine domain: " + d["name"])
                source_file = libvirtUtils.get_image_for_domain(d["uuid"])
                if libvirtUtils.undefine_domain(d["uuid"]):
                    if source_file is not None:
                        osUtils.remove_instance(source_file)

                    osUtils.remove_cloud_init_seed_dir_for_domain(d['name'])

    except Exception as e:
        logger.debug("Caught Exception in redeploy")
        logger.debug(str(e))
        return render(request, 'ajax/ajaxError.html', {'error': str(e)})

    # forward onto deploy topo
    try:
        inline_deploy_topology(config)
        inventory = wistarUtils.get_topology_inventory(topo)
        wistarUtils.send_new_topology_event(inventory)
    except Exception as e:
        logger.debug("Caught Exception in inline_deploy")
        logger.debug(str(e))
        return render(request, 'ajax/ajaxError.html', {'error': str(e)})

    return refresh_deployment_status(request)
Exemple #5
0
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/')
Exemple #6
0
def delete(request, topology_id):
    logger.debug('---- topology delete ----')
    topology_prefix = "t%s_" % topology_id

    topology = get_object_or_404(Topology, pk=topology_id)

    if configuration.deployment_backend == "kvm":

        if hasattr(configuration,
                   "use_openvswitch") and configuration.use_openvswitch:
            use_ovs = True
        else:
            use_ovs = False

        network_list = libvirtUtils.get_networks_for_topology(topology_prefix)
        for network in network_list:
            logger.debug("undefine network: " + network["name"])
            libvirtUtils.undefine_network(network["name"])

            if use_ovs:
                ovsUtils.delete_bridge(network["name"])

        domain_list = libvirtUtils.get_domains_for_topology(topology_prefix)
        for domain in domain_list:

            # remove reserved mac addresses for all domains in this topology
            mac_address = libvirtUtils.get_management_interface_mac_for_domain(
                domain["name"])
            libvirtUtils.release_management_ip_for_mac(mac_address)

            logger.debug("undefine domain: " + domain["name"])
            source_file = libvirtUtils.get_image_for_domain(domain["uuid"])
            if libvirtUtils.undefine_domain(domain["uuid"]):
                if source_file is not None:
                    osUtils.remove_instance(source_file)

        osUtils.remove_instances_for_topology(topology_prefix)
        osUtils.remove_cloud_init_tmp_dirs(topology_prefix)

    elif configuration.deployment_backend == "openstack":
        stack_name = topology.name.replace(' ', '_')
        if openstackUtils.connect_to_openstack():
            logger.debug(openstackUtils.delete_stack(stack_name))

    topology.delete()
    messages.info(request, 'Topology %s deleted' % topology.name)
    return HttpResponseRedirect('/topologies/')
Exemple #7
0
def manage_domain(request):
    required_fields = set(['domainId', 'action', 'topologyId'])
    if not required_fields.issubset(request.POST):
        return render(request, 'ajax/ajaxError.html',
                      {'error': "Invalid Parameters in POST"})

    domain_id = request.POST['domainId']
    action = request.POST['action']
    topology_id = request.POST["topologyId"]

    if action == "start":
        # force all networks to be up before we start a topology
        # potential minor optimization here to only start networks attached to domain
        networks = libvirtUtils.get_networks_for_topology(topology_id)
        for network in networks:
            if network["state"] != "running":
                libvirtUtils.start_network(network["name"])

        # prevent start up errors by missing ISO files - i.e cloud-init seed files
        domain = libvirtUtils.get_domain_by_uuid(domain_id)
        iso = libvirtUtils.get_iso_for_domain(domain.name())
        # if we have an ISO file configured, and it doesn't actually exist
        # just remove it completely
        if iso is not None and not osUtils.check_path(iso):
            logger.debug("Removing non-existent ISO from domain")
            libvirtUtils.detach_iso_from_domain(domain.name())

        # now we should be able to safely start the domain
        if libvirtUtils.start_domain(domain_id):
            return refresh_deployment_status(request)
        else:
            return render(request, 'ajax/ajaxError.html',
                          {'error': "Could not start domain!"})

    elif action == "stop":
        if libvirtUtils.stop_domain(domain_id):
            return refresh_deployment_status(request)
        else:
            return render(request, 'ajax/ajaxError.html',
                          {'error': "Could not stop domain!"})

    elif action == "suspend":
        if libvirtUtils.suspend_domain(domain_id):
            return refresh_deployment_status(request)
        else:
            return render(request, 'ajax/ajaxError.html',
                          {'error': "Could not suspend domain!"})

    elif action == "undefine":

        domain = libvirtUtils.get_domain_by_uuid(domain_id)
        domain_name = domain.name()

        source_file = libvirtUtils.get_image_for_domain(domain_id)
        if libvirtUtils.undefine_domain(domain_id):
            if source_file is not None:
                osUtils.remove_instance(source_file)
                osUtils.remove_cloud_init_seed_dir_for_domain(domain_name)

            return refresh_deployment_status(request)
        else:
            return render(request, 'ajax/ajaxError.html',
                          {'error': "Could not stop domain!"})
    else:
        return render(request, 'ajax/ajaxError.html',
                      {'error': "Unknown Parameters in POST!"})