def launch(request):
    """Configure and launch CloudBioLinux and CloudMan servers.
    """
    if request.method == "POST":
        form = forms.CloudManForm(request.POST)
        if form.is_valid():
            print form.cleaned_data
            ec2_error = None
            try:
                # Create security group & key pair used when starting an instance
                ec2_conn = connect_ec2(form.cleaned_data['access_key'],
                                       form.cleaned_data['secret_key'],
                                       form.cleaned_data['cloud'])
                sg_name = create_cm_security_group(ec2_conn, form.cleaned_data['cloud'])
                kp_name, kp_material = create_key_pair(ec2_conn)
            except EC2ResponseError, err:
                ec2_error = err.error_message
            # associate form data with session for starting instance
            # and supplying download files
            if ec2_error is None:
                form.cleaned_data["kp_name"] = kp_name
                form.cleaned_data["kp_material"] = kp_material
                form.cleaned_data["sg_name"] = sg_name
                form.cleaned_data["cloud_type"] = form.cleaned_data['cloud'].cloud_type
                form.cleaned_data["cloud_name"] = form.cleaned_data['cloud'].name
                request.session["ec2data"] = form.cleaned_data
                if runinstance(request):
                    return redirect("/monitor")
                else:
                    form.non_field_errors = "A problem starting your instance. " \
                                            "Check the {0} cloud's console."\
                                            .format(form.cleaned_data['cloud'].name)
            else:
                form.non_field_errors = ec2_error
def api_instancestate(request):
    access_key = request.GET.get('access_key')
    secret_key = request.GET.get('secret_key')
    cloud_type = request.GET.get('cloud_type')
    instance_id = request.GET.get('instance_id')

    if access_key == None or secret_key == None or cloud_type == None or instance_id == None:
            return HttpResponse(simplejson.dumps({'error': 'Please provide correct parameters'}))

    cloud = models.Cloud.objects.get(cloud_type=cloud_type)

    ec2_conn = connect_ec2(access_key, secret_key, cloud)
    state = instance_state(ec2_conn, instance_id)
    return HttpResponse(simplejson.dumps(state), mimetype="application/json")
def api_get_regions(request):
    cloud_name = request.GET.get('cloud_name', '')
    access_key = request.GET.get('access_key', '')
    secret_key = request.GET.get('secret_key', '')
    instance_type = request.GET.get('instance_type', '')
    regions = []
    if (cloud_name != '' and access_key != '' and secret_key != '' and instance_type != ''):
        cloud = models.Cloud.objects.get(name=cloud_name)
        ec2_conn = connect_ec2(access_key, secret_key, cloud)
        regions = _find_placement(ec2_conn, instance_type, cloud.cloud_type, get_all=True)
        result_text = simplejson.dumps(regions)
    else:
        result_text = "{'error': 'Please provide correct parameters'}" #STUB
    result = HttpResponse(result_text)
    return result
def api_launch(request):
    params = copy.deepcopy(request.POST)

    ec2_error = None
    cloud = models.Cloud.objects.get(cloud_type=params['cloud'])
    params['cloud'] = cloud
    try:
        # Create security group & key pair used when starting an instance
        ec2_conn = connect_ec2(params['access_key'],
                               params['secret_key'],
                               cloud)
        sg_name = create_cm_security_group(ec2_conn, cloud)
        kp_name, kp_material = create_key_pair(ec2_conn)
    except EC2ResponseError, err:
        ec2_error = err.error_message
def runinstance(request):
    """Run a CloudBioLinux/CloudMan instance with current session credentials.
    """
    form = request.session["ec2data"]
    rs = None
    instance_type = form['instance_type']
    # Create EC2 connection with provided creds
    ec2_conn = connect_ec2(form["access_key"], form["secret_key"],
                           form['cloud'])
    form["freenxpass"] = form["password"]
    if form['image_id']:
        image = models.Image.objects.get(pk=form['image_id'])
    else:
        try:
            image = models.Image.objects.get(cloud=form['cloud'], default=True)
        except models.Image.DoesNotExist:
            log.error("Cannot find an image to launch for cloud {0}".format(
                form['cloud']))
            return False
    rs = run_instance(
        ec2_conn=ec2_conn,
        user_provided_data=form,
        image_id=image.image_id,
        kernel_id=image.kernel_id if image.kernel_id != '' else None,
        ramdisk_id=image.ramdisk_id if image.ramdisk_id != '' else None,
        key_name=form["kp_name"],
        security_groups=[form["sg_name"]],
        placement=form['placement'])
    if rs is not None:
        request.session['ec2data']['instance_id'] = rs.instances[0].id
        request.session['ec2data']['public_dns'] = rs.instances[
            0].public_dns_name
        request.session['ec2data']['image_id'] = rs.instances[0].image_id
        # Add an entry to the Usage table
        try:
            u = models.Usage(cloud_name=form["cloud_name"],
                             cloud_type=form["cloud_type"],
                             image_id=image.image_id,
                             instance_type=instance_type,
                             user_id=form["access_key"])
            u.save()
        except Exception, e:
            log.debug("Trouble saving Usage data: {0}".format(e))
        return True
def get_placements(request):
    if request.is_ajax():
        if request.method == 'POST':
            cloud_id = request.POST.get('cloud_id', '')
            a_key = request.POST.get('a_key', '')
            s_key = request.POST.get('s_key', '')
            inst_type = request.POST.get('instance_type', '')
            placements = []
            if cloud_id != '' and a_key != '' and s_key != '' and inst_type != '':
                # Needed to get the cloud connection
                cloud = models.Cloud.objects.get(pk=cloud_id)
                ec2_conn = connect_ec2(a_key, s_key, cloud)
                placements = _find_placement(ec2_conn, inst_type, cloud.cloud_type, get_all=True)
                state = {'placements': placements}
        else:
            log.error("Not a POST request")
    else:
        log.error("No XHR")
    return HttpResponse(simplejson.dumps(state), mimetype="application/json")
def runinstance(request):
    """Run a CloudBioLinux/CloudMan instance with current session credentials.
    """
    form = request.session["ec2data"]
    rs = None
    instance_type = form['instance_type']
    # Create EC2 connection with provided creds
    ec2_conn = connect_ec2(form["access_key"], form["secret_key"], form['cloud'])
    form["freenxpass"] = form["password"]
    if form['image_id']:
        image = models.Image.objects.get(pk=form['image_id'])
    else:
        try:
            image = models.Image.objects.get(cloud=form['cloud'], default=True)
        except models.Image.DoesNotExist:
            log.error("Cannot find an image to launch for cloud {0}".format(form['cloud']))
            return False
    rs = run_instance(ec2_conn=ec2_conn,
                      user_provided_data=form,
                      image_id=image.image_id,
                      kernel_id=image.kernel_id if image.kernel_id != '' else None,
                      ramdisk_id=image.ramdisk_id if image.ramdisk_id != '' else None,
                      key_name=form["kp_name"],
                      security_groups=[form["sg_name"]],
                      placement=form['placement'])
    if rs is not None:
        request.session['ec2data']['instance_id'] = rs.instances[0].id
        request.session['ec2data']['public_dns'] = rs.instances[0].public_dns_name
        request.session['ec2data']['image_id'] = rs.instances[0].image_id
        # Add an entry to the Usage table
        try:
            u = models.Usage(cloud_name=form["cloud_name"],
                             cloud_type=form["cloud_type"],
                             image_id=image.image_id,
                             instance_type=instance_type,
                             user_id=form["access_key"])
            u.save()
        except Exception, e:
            log.debug("Trouble saving Usage data: {0}".format(e))
        return True
def get_placements(request):
    if request.is_ajax():
        if request.method == 'POST':
            cloud_id = request.POST.get('cloud_id', '')
            a_key = request.POST.get('a_key', '')
            s_key = request.POST.get('s_key', '')
            inst_type = request.POST.get('instance_type', '')
            placements = []
            if cloud_id != '' and a_key != '' and s_key != '' and inst_type != '':
                # Needed to get the cloud connection
                cloud = models.Cloud.objects.get(pk=cloud_id)
                ec2_conn = connect_ec2(a_key, s_key, cloud)
                placements = _find_placement(ec2_conn,
                                             inst_type,
                                             cloud.cloud_type,
                                             get_all=True)
                state = {'placements': placements}
        else:
            log.error("Not a POST request")
    else:
        log.error("No XHR")
    return HttpResponse(simplejson.dumps(state), mimetype="application/json")
def launch(request):
    """Configure and launch CloudBioLinux and CloudMan servers.
    """
    if request.method == "POST":
        form = forms.CloudManForm(request.POST)
        if form.is_valid():
            print form.cleaned_data
            ec2_error = None
            try:
                # Create security group & key pair used when starting an instance
                ec2_conn = connect_ec2(form.cleaned_data['access_key'],
                                       form.cleaned_data['secret_key'],
                                       form.cleaned_data['cloud'])
                sg_name = create_cm_security_group(ec2_conn,
                                                   form.cleaned_data['cloud'])
                kp_name, kp_material = create_key_pair(ec2_conn)
            except EC2ResponseError, err:
                ec2_error = err.error_message
            # associate form data with session for starting instance
            # and supplying download files
            if ec2_error is None:
                form.cleaned_data["kp_name"] = kp_name
                form.cleaned_data["kp_material"] = kp_material
                form.cleaned_data["sg_name"] = sg_name
                form.cleaned_data["cloud_type"] = form.cleaned_data[
                    'cloud'].cloud_type
                form.cleaned_data["cloud_name"] = form.cleaned_data[
                    'cloud'].name
                request.session["ec2data"] = form.cleaned_data
                if runinstance(request):
                    return redirect("/monitor")
                else:
                    form.non_field_errors = "A problem starting your instance. " \
                                            "Check the {0} cloud's console."\
                                            .format(form.cleaned_data['cloud'].name)
            else:
                form.non_field_errors = ec2_error
def instancestate(request):
    form = request.session["ec2data"]
    ec2_conn = connect_ec2(form["access_key"], form["secret_key"], form['cloud'])
    state = instance_state(ec2_conn, form["instance_id"])
    return HttpResponse(simplejson.dumps(state), mimetype="application/json")
def instancestate(request):
    form = request.session["ec2data"]
    ec2_conn = connect_ec2(form["access_key"], form["secret_key"],
                           form['cloud'])
    state = instance_state(ec2_conn, form["instance_id"])
    return HttpResponse(simplejson.dumps(state), mimetype="application/json")
        params["kp_material"] = kp_material
        params["sg_name"] = sg_name
        params["cloud_type"] = cloud.cloud_type #"OpenStack" #cloud.cloud_type
        params["cloud_name"] = cloud.name #"NeCTAR" #cloud.name
        request.session["ec2data"] = params
        if params['image_id']:
            image = models.Image.objects.get(pk=params['image_id'])
        else:
            try:
                image = models.Image.objects.get(cloud=params['cloud'], default=True)
            except models.Image.DoesNotExist:
                log.error("Cannot find an image to launch for cloud {0}".format(params['cloud']))
                result = HttpResponse(simplejson.dumps("ERROR"))
                return result

        ec2_conn = connect_ec2(params["access_key"], params["secret_key"], cloud)
        rs = run_instance(ec2_conn=ec2_conn,
                      user_provided_data=params,
                      image_id=image.image_id,
                      kernel_id=image.kernel_id if image.kernel_id != '' else None,
                      ramdisk_id=image.ramdisk_id if image.ramdisk_id != '' else None,
                      key_name=params["kp_name"],
                      security_groups=[params["sg_name"]])#,
                      #placement=params['placement'])
        ## TODO: Save usage file?
        instance_id = rs.instances[0].id
        public_dns = rs.instances[0].public_dns_name
        image_id = rs.instances[0].image_id
        result_dict = {
                "instance_id": instance_id,
                "public_dns": public_dns,