コード例 #1
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
 def wrap(request, *args, **kwargs):
     response = f(request, *args, **kwargs)
     pretty = str_to_bool(request.GET.get('pretty', 'false'))
     if response.status_code == 200 and pretty:
         try:
             content_json = json.loads(response.content)
             pretty_json = json.dumps(content_json, indent=4, separators=(',', ': '))
             response.content = pretty_json
         except:
             pass
     return response
コード例 #2
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def instance_resource(request, domain_id, instance_id):
    if request.method == "GET":
        username = request.user.username
        response = get_domain_instances(username, domain_id)
        if response is None:
            return HttpResponseNotFound('domain %s not found' % domain_id, mimetype='application/javascript')

        wanted_instance = None
        for instance in response:
            if instance.get('id') == instance_id:
                wanted_instance = instance
                break

        if wanted_instance is None:
            return HttpResponseNotFound('instance %s not found' % instance_id, mimetype='application/javascript')

        wanted_instance['owner'] = username
        wanted_instance['cloud'] = "/api/%s/sites/%s" % (API_VERSION, wanted_instance.get('cloud'))
        wanted_instance['uri'] = "/api/%s/domains/%s/instances/%s" % (
            API_VERSION, domain_id, wanted_instance.get('id'))

        return HttpResponse(json.dumps(wanted_instance), mimetype='application/javascript')

    elif request.method == "DELETE":
        username = request.user.username
        adjust_policy = str_to_bool(request.GET.get('adjust_policy', 'false'))
        instance = get_domain_instance(username, domain_id, instance_id)
        if instance is None:
            return HttpResponseNotFound('instance %s not found' % domain_id, mimetype='application/javascript')

        try:
            terminate_domain_instance(username, domain_id, instance_id)
        except PhantomWebException:
            return HttpResponseServerError("Couldn't remove instance %s" % instance_id)

        if adjust_policy:
            domain = get_domain(username, domain_id)
            adjusted_domain = None
            if 'vm_count' in domain:
                if int(domain['vm_count']) >= 1:
                    domain['vm_count'] = int(domain['vm_count']) - 1
                    adjusted_domain = domain
            elif 'sensor_minimum_vms' in domain and 'sensor_maximum_vms' in domain:
                if int(domain['sensor_minimum_vms']) >= 1:
                    domain['sensor_minimum_vms'] = int(domain['sensor_minimum_vms']) - 1
                domain['sensor_maximum_vms'] = domain['sensor_minimum_vms']
                adjusted_domain = domain

            if adjusted_domain:
                response = modify_domain(username, domain_id, adjusted_domain)

        h = HttpResponse(status=204)
        return h
コード例 #3
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def sites(request):
    user_obj = get_user_object(request.user.username)
    details = str_to_bool(request.GET.get('details', 'false'))
    all_sites = phantom_get_sites(request.GET, user_obj, details=details)
    response_list = []
    for site_name, site_dict in all_sites.iteritems():
        site_dict["credentials"] = "/api/%s/credentials/sites/%s" % (API_VERSION, site_name)
        site_dict["uri"] = "/api/%s/sites/%s" % (API_VERSION, site_name)
        if details:
            if site_dict.get('user_images') is None:
                site_dict['user_images'] = []
            if site_dict.get('public_images') is None:
                site_dict['public_images'] = []
        response_list.append(site_dict)
    h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')
    return h
コード例 #4
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def site_resource(request, site):
    user_obj = get_user_object(request.user.username)
    details = str_to_bool(request.GET.get('details', 'false'))
    all_sites = phantom_get_sites(request.GET, user_obj, details=details)
    if site in all_sites:
        response_dict = {
            "id": site,
            "credentials": "/api/%s/credentials/sites/%s" % (API_VERSION, site),
            "instance_types": all_sites[site].get('instance_types', []),
            "uri": "/api/%s/sites/%s" % (API_VERSION, site)
        }
        if details:
            if response_dict.get('user_images') is None:
                response_dict['user_images'] = []
            if response_dict.get('public_images') is None:
                response_dict['public_images'] = []
        h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
    else:
        h = HttpResponseNotFound('Site %s not found' % site, mimetype='application/javascript')
    return h
コード例 #5
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def launchconfigurations(request):
    if request.method == "GET":
        public = str_to_bool(request.GET.get('public', 'false'))

        all_launch_configurations = get_all_launch_configurations(request.user.username, public=public)
        response_list = []
        for lc_id, lc in all_launch_configurations.iteritems():
            lc_dict = get_launch_configuration(lc_id)
            lc_dict['uri'] = "/api/%s/launchconfigurations/%s" % (API_VERSION, lc_dict.get('id'))
            if 'description' in lc:
                lc_dict['description'] = lc['description']
            response_list.append(lc_dict)

        h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')

    elif request.method == "POST":
        try:
            content = json.loads(request.body)
        except:
            return HttpResponseBadRequest("Couldn't load json from body")

        required_params = ['name', 'cloud_params']
        if not has_all_required_params(required_params, content):
            return HttpResponseBadRequest("Request must have %s params" % ", ".join(required_params))
        name = content['name']
        cloud_params = content['cloud_params']
        username = request.user.username

        required_cloud_params = ['image_id', 'instance_type', 'max_vms', 'common', 'rank']
        for cloud_name, cloud_p in cloud_params.iteritems():
            if not has_all_required_params(required_cloud_params, cloud_p):
                missing = list(set(required_params) - set(cloud_p))
                return HttpResponseBadRequest("Missing parameters. %s needs: %s." % (
                    cloud_name, ", ".join(missing)))

        if re.search("^%s+$" % ACCEPTED_RESOURCE_PATTERN, name) is None:
            return HttpResponseBadRequest("%s isn't an acceptable id. Must match %s" % (
                name, ACCEPTED_RESOURCE_PATTERN))

        lc = get_launch_configuration_by_name(username, name)
        if lc is not None:
            # LC already exists, redirect to existing one
            return HttpResponseRedirect("/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id))

        contextualization_method = content.get('contextualization_method', 'None')
        user_data = content.get('user_data')
        chef_runlist = content.get('chef_runlist')
        chef_attributes = content.get('chef_attributes')
        appliance = content.get('appliance')

        if (contextualization_method is 'none' and
                (user_data, chef_runlist, chef_attributes) is not (None, None, None)):
            msg = "Your contextualization_method is 'none', but you have provided "
            "'user_data', 'chef_runlist' or 'chef_attributes'?"
            return HttpResponseBadRequest(msg)
        elif (contextualization_method is 'user_data' and
                (chef_runlist, chef_attributes) is not (None, None)):
            msg = "Your contextualization_method is 'user_data', but you have provided "
            "'chef_runlist' or 'chef_attributes'?"
            return HttpResponseBadRequest(msg)
        elif contextualization_method is 'chef' and user_data is not None:
            msg = "Your contextualization_method is 'chef', but you have provided "
            "'user_data'?"
            return HttpResponseBadRequest(msg)

        context_params = {
            'contextualization_method': contextualization_method,
            'user_data': user_data,
            'chef_runlist': chef_runlist,
            'chef_attributes': chef_attributes,
        }

        lc = create_launch_configuration(username, name, cloud_params, context_params, appliance)

        response_dict = {
            "id": lc.id,
            "name": name,
            "owner": username,
            'appliance': appliance,
            'contextualization_method': contextualization_method,
            "cloud_params": cloud_params,
            "uri": "/api/%s/launchconfigurations/%s" % (API_VERSION, lc.id),
        }

        if contextualization_method == "user_data":
            response_dict['user_data'] = content.get('user_data')
        elif contextualization_method == "chef":
            response_dict['chef_runlist'] = content.get('chef_runlist')
            response_dict['chef_attributes'] = content.get('chef_attributes')

        h = HttpResponse(json.dumps(response_dict), status=201, mimetype='application/javascript')
    return h
コード例 #6
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def credentials_resource(request, site):
    user_obj = get_user_object(request.user.username)

    if request.method == "GET":
        all_clouds = user_obj.get_clouds()
        cloud = all_clouds.get(site)
        details = str_to_bool(request.GET.get('details', 'false'))
        if details is True:
            keys = get_all_keys([cloud])

        if cloud is not None:
            response_dict = {
                "id": cloud.cloudname,
                "access_key": cloud.iaas_key,
                "secret_key": cloud.iaas_secret,
                "key_name": cloud.keyname,
                "uri": "/api/%s/credentials/sites/%s" % (API_VERSION, cloud.cloudname)
            }
            if details is True:
                response_dict["available_keys"] = keys[cloud.cloudname]
            h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
        else:
            h = HttpResponseNotFound('Credentials for site %s not found' % site, mimetype='application/javascript')
    elif request.method == "PUT":
        try:
            content = json.loads(request.body)
        except:
            return HttpResponseBadRequest()

        required_params = ["id", "access_key", "secret_key", "key_name"]
        if not has_all_required_params(required_params, content):
            return HttpResponseBadRequest()

        if site != content["id"]:
            return HttpResponseBadRequest()

        access_key = content["access_key"]
        secret_key = content["secret_key"]
        key_name = content["key_name"]

        # Check that the site exists
        all_sites = phantom_get_sites(request.REQUEST, user_obj)
        if site not in all_sites:
            return HttpResponseBadRequest()

        # Check that credentials exist
        if site not in user_obj.get_clouds():
            return HttpResponseBadRequest()

        response_dict = {
            "id": site,
            "access_key": access_key,
            "secret_key": secret_key,
            "key_name": key_name,
            "uri": "/api/%s/credentials/sites/%s" % (API_VERSION, site)
        }

        # Add credentials to DTRS
        try:
            user_obj.add_site(site, access_key, secret_key, key_name)
        except:
            log.exception("Failed to add credentials for site %s" % site)
            return HttpResponseServerError()

        h = HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
    elif request.method == "DELETE":
        # Check that credentials exist
        clouds = user_obj.get_clouds()
        if site not in clouds:
            return HttpResponseBadRequest("Site %s not available. Choose from %s" % (site, clouds.keys()))

        # Remove credentials from DTRS
        try:
            user_obj.delete_site(site)
        except:
            msg = "Failed to remove credentials for site %s" % site
            log.exception(msg)
            return HttpResponseServerError(msg)

        h = HttpResponse(status=204)

    return h
コード例 #7
0
ファイル: dev.py プロジェクト: lelou6666/PhantomWebApp
def credentials(request):
    user_obj = get_user_object(request.user.username)

    if request.method == "GET":
        all_clouds = user_obj.get_clouds()
        details = str_to_bool(request.GET.get('details', 'false'))
        if details is True:
            keys = get_all_keys(all_clouds)
            packer_credentials = get_all_packer_credentials(request.user.username, all_clouds)

        response_list = []
        for cloud in all_clouds.values():
            credentials_name = cloud.cloudname
            credentials_dict = {
                "id": credentials_name,
                "access_key": cloud.iaas_key,
                "secret_key": cloud.iaas_secret,
                "key_name": cloud.keyname,
                "uri": "/api/%s/credentials/sites/%s" % (API_VERSION, credentials_name)
            }
            if details is True:
                credentials_dict["available_keys"] = keys[cloud.cloudname]
                packer_cloud_creds = packer_credentials[cloud.cloudname]
                if "usercert" in packer_cloud_creds:
                    credentials_dict["nimbus_user_cert"] = packer_cloud_creds["usercert"]
                if "userkey" in packer_cloud_creds:
                    credentials_dict["nimbus_user_key"] = packer_cloud_creds["userkey"]
                if "canonical_id" in packer_cloud_creds:
                    credentials_dict["nimbus_canonical_id"] = packer_cloud_creds["canonical_id"]
                if "openstack_username" in packer_cloud_creds:
                    credentials_dict["openstack_username"] = packer_cloud_creds["openstack_username"]
                if "openstack_password" in packer_cloud_creds:
                    credentials_dict["openstack_password"] = packer_cloud_creds["openstack_password"]
                if "openstack_project" in packer_cloud_creds:
                    credentials_dict["openstack_project"] = packer_cloud_creds["openstack_project"]
            response_list.append(credentials_dict)
        log.info(response_list)
        h = HttpResponse(json.dumps(response_list), mimetype='application/javascript')
    elif request.method == "POST":
        try:
            content = json.loads(request.body)
        except:
            msg = "Bad request (%s). No JSON. See API docs: %s" % (request.body, DOC_URI)
            return HttpResponseBadRequest(msg)

        required_params = ["id", "access_key", "secret_key", "key_name"]
        if not has_all_required_params(required_params, content):
            return HttpResponseBadRequest("Bad request. Do not have all required parameters (%s)" % required_params)

        site = content["id"]
        access_key = content["access_key"]
        secret_key = content["secret_key"]
        key_name = content["key_name"]
        nimbus_user_cert = content.get("nimbus_user_cert")
        nimbus_user_key = content.get("nimbus_user_key")
        nimbus_canonical_id = content.get("nimbus_canonical_id")
        openstack_username = content.get("openstack_username")
        openstack_password = content.get("openstack_password")
        openstack_project = content.get("openstack_project")

        # Check that the site exists
        all_sites = phantom_get_sites(request.POST, user_obj)
        if site not in all_sites:
            return HttpResponseBadRequest("%s doesn't seem to exist. I know about %s" % (
                site, all_sites))

        if re.search("^%s+$" % ACCEPTED_RESOURCE_PATTERN, site) is None:
            return HttpResponseBadRequest("%s isn't an acceptable id. Must match %s" % (
                site, ACCEPTED_RESOURCE_PATTERN))

        response_dict = {
            "id": site,
            "access_key": access_key,
            "secret_key": secret_key,
            "key_name": key_name,
            "uri": "/api/%s/credentials/sites/%s" % (API_VERSION, site)
        }

        # Add credentials to DTRS
        try:
            user_obj.add_site(site, access_key, secret_key, key_name)
        except:
            log.exception("Failed to add credentials for site %s" % site)
            return HttpResponseServerError()

        # Add image generation credentials to DB
        if nimbus_user_cert is not None:
            add_packer_credentials(username=request.user.username, cloud=site, nimbus_user_cert=nimbus_user_cert,
                    nimbus_user_key=nimbus_user_key, nimbus_canonical_id=nimbus_canonical_id)

        if openstack_username is not None:
            add_packer_credentials(username=request.user.username, cloud=site, openstack_username=openstack_username,
                    openstack_password=openstack_password, openstack_project=openstack_project)

        response_dict["nimbus_user_cert"] = nimbus_user_cert
        response_dict["nimbus_user_key"] = nimbus_user_key
        response_dict["nimbus_canonical_id"] = nimbus_canonical_id
        response_dict["openstack_username"] = openstack_username
        response_dict["openstack_password"] = openstack_password
        response_dict["openstack_project"] = openstack_project

        h = HttpResponse(json.dumps(response_dict), status=201, mimetype='application/javascript')

    return h