Exemple #1
0
def detail(request, image_id):
    image = get_object_or_404(Image, pk=image_id)

    vm_type = "N/A"
    for vt in configuration.vm_image_types:
        if vt["name"] == image.type:
            vm_type = vt["description"]
            break

    glance_id = ""
    image_state = ""

    if configuration.deployment_backend == "openstack":
        openstackUtils.connect_to_openstack()
        glance_id = openstackUtils.get_image_id_for_name(image.name)
    elif configuration.deployment_backend == "kvm" and image.filePath != "":
        image_state = osUtils.is_image_thin_provisioned(image.filePath.path)

    return render(
        request, 'images/details.html', {
            'image': image,
            'state': image_state,
            "vm_type": vm_type,
            "settings": settings,
            "glance_id": glance_id,
            "use_openstack": configuration.use_openstack,
            "openstack_host": configuration.openstack_host
        })
Exemple #2
0
def glance_detail(request):
    """
    OpenStack specific action to get image details from Glance
    :param request: HTTPRequest
    :return: rendered HTML
    """
    required_fields = set(['imageId'])
    if not required_fields.issubset(request.POST):
        return render(request, 'ajax/ajaxError.html',
                      {'error': "Invalid Parameters in POST"})

    image_id = request.POST["imageId"]

    image = get_object_or_404(Image, pk=image_id)

    if openstackUtils.connect_to_openstack():
        glance_id = openstackUtils.get_image_id_for_name(image.name)

        glance_json = dict()
        if glance_id is not None:
            glance_json = openstackUtils.get_glance_image_detail(glance_id)
            logger.debug("glance json of %s is" % glance_id)
            logger.debug(glance_json)
            logger.debug("---")

        return render(
            request, 'images/glance_detail.html', {
                'image': glance_json,
                "image_id": image_id,
                "glance_id": glance_id,
                "openstack_host": configuration.openstack_host
            })
    else:
        return render(request, 'error.html',
                      {'error': "Could not connect to OpenStack"})
Exemple #3
0
def refresh_openstack_deployment_status(request, topology_id):
    logger.debug('---- ajax refresh_openstack_deployment_status ----')
    if not openstackUtils.connect_to_openstack():
        error_message = "Could not connect to Openstack!"
        logger.error(error_message)
        return render(request, 'ajax/ajaxError.html', {'error': error_message})

    topology = Topology.objects.get(pk=topology_id)
    stack_name = topology.name.replace(' ', '_')
    stack_details = openstackUtils.get_stack_details(stack_name)
    stack_resources = dict()
    logger.debug(stack_details)
    if stack_details is not None and 'stack_status' in stack_details and 'COMPLETE' in stack_details[
            "stack_status"]:
        stack_resources = openstackUtils.get_stack_resources(
            stack_name, stack_details["id"])

    if hasattr(configuration, 'openstack_horizon_url'):
        horizon_url = configuration.openstack_horizon_url
    else:
        horizon_url = 'http://' + configuration.openstack_host + '/dashboard'

    context = {
        "stack": stack_details,
        "topology_id": topology.id,
        "openstack_host": configuration.openstack_host,
        "openstack_horizon_url": horizon_url,
        "stack_resources": stack_resources
    }
    return render(request, 'ajax/openstackDeploymentStatus.html', context)
Exemple #4
0
def list_glance_images(request):
    if openstackUtils.connect_to_openstack():
        image_list = openstackUtils.list_glance_images()

        context = {'error': image_list}
        return render(request, 'error.html', context)

    context = {'error': "Could not connect to OpenStack"}
    return render(request, 'error.html', context)
Exemple #5
0
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")
Exemple #6
0
def upload_to_glance(request, image_id):
    if openstackUtils.connect_to_openstack():
        image = get_object_or_404(Image, pk=image_id)
        logger.debug("Uploading now!")
        if osUtils.check_path(image.filePath.path):
            openstackUtils.upload_image_to_glance(image.name,
                                                  image.filePath.path)

        logger.debug("All done")
        return HttpResponseRedirect('/images/%s' % image_id)
Exemple #7
0
def deploy_stack(request, topology_id):
    """
    :param request: Django request
    :param topology_id: id of the topology to export
    :return: renders the heat template
    """
    try:
        topology = Topology.objects.get(pk=topology_id)
    except ObjectDoesNotExist:
        return render(request, 'error.html', {'error': "Topology not found!"})

    try:
        # generate a stack name
        # FIXME should add a check to verify this is a unique name
        stack_name = topology.name.replace(' ', '_')

        # let's parse the json and convert to simple lists and dicts
        logger.debug("loading config")
        config = wistarUtils.load_config_from_topology_json(
            topology.json, topology_id)
        logger.debug("Config is loaded")
        heat_template = wistarUtils.get_heat_json_from_topology_config(
            config, parameterize=False)
        logger.debug("heat template created")
        if not openstackUtils.connect_to_openstack():
            return render(request, 'error.html',
                          {'error': "Could not connect to Openstack"})

        # get the tenant_id of the desired project
        tenant_id = openstackUtils.get_project_id(
            configuration.openstack_project)
        logger.debug("using tenant_id of: %s" % tenant_id)
        if tenant_id is None:
            raise Exception("No project found for %s" %
                            configuration.openstack_project)

        # FIXME - verify all images are in glance before jumping off here!

        ret = openstackUtils.create_stack(stack_name, heat_template)
        if ret is not None:
            inventory = wistarUtils.get_topology_inventory(topology)
            wistarUtils.send_new_topology_event(inventory)

        return HttpResponseRedirect('/topologies/' + topology_id + '/')

    except Exception as e:
        logger.debug("Caught Exception in deploy")
        logger.debug(str(e))
        return render(request, 'error.html', {'error': str(e)})
Exemple #8
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 #9
0
def delete_stack(request, topology_id):
    """
    :param request: Django request
    :param topology_id: id of the topology to remove from OpenStack
    :return: redirect to topology detail screen
    """

    try:
        topology = Topology.objects.get(pk=topology_id)
    except ObjectDoesNotExist:
        return render(request, 'error.html', {'error': "Topology not found!"})

    stack_name = topology.name.replace(' ', '_')
    if openstackUtils.connect_to_openstack():
        logger.debug(openstackUtils.delete_stack(stack_name))

    return HttpResponseRedirect('/topologies/' + topology_id + '/')
Exemple #10
0
def get_linux_startup_state(request):
    response_data = dict()
    response_data["console"] = False
    response_data["power"] = False
    response_data["network"] = False

    if not configuration.check_vm_network_state:
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")

    required_fields = set(['name'])
    if not required_fields.issubset(request.POST):
        logger.error('Invalid parameters in POST for get_linux_startup_state')
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")

    name = request.POST['name']
    # always check network if possible regardless of deployment_backend
    if "ip" in request.POST:
        # this instance is auto-configured, so we can just check for IP here
        response_data["network"] = osUtils.check_ip(request.POST["ip"])

    if configuration.deployment_backend == "openstack":
        if openstackUtils.connect_to_openstack():
            time.sleep(random.randint(0, 10) * .10)
            response_data["power"] = True
            # as of 2018-01-01 we no longer support openstack console, this is dead code
            # response_data["console"] = consoleUtils.is_linux_device_at_prompt(name)
            response_data['console'] = False
    else:
        if libvirtUtils.is_domain_running(name):
            time.sleep(random.randint(0, 10) * .10)
            response_data["power"] = True
            # let's check the console only if we do not have network available to check
            if "ip" not in request.POST:
                response_data[
                    "console"] = consoleUtils.is_linux_device_at_prompt(name)

    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
Exemple #11
0
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)