Exemplo n.º 1
0
 def __init__(self, *args, **kwargs):
     super(ApplicationForm, self).__init__(*args, **kwargs)
     # set height for container select
     container_list_length = len(Container.get_running())
     if container_list_length > 20:
         container_list_length = 20
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Fieldset(
             None,
             'name',
             'description',
             'domain_name',
             'host_interface',
             'backend_port',
             'protocol',
             Field('containers', size=container_list_length),
         ),
         FormActions(
             Submit('save', _('Update'), css_class="btn btn-lg btn-success"),
         )
     )
     self.helper.form_id = 'form-create-application'
     self.helper.form_class = 'form-horizontal'
     self.helper.form_action = reverse('applications.views.create')
Exemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super(ApplicationForm, self).__init__(*args, **kwargs)
     # set height for container select
     container_list_length = len(Container.get_running())
     if container_list_length > 20:
         container_list_length = 20
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Fieldset(
             None,
             'name',
             'description',
             'domain_name',
             'host_interface',
             'backend_port',
             'protocol',
             Field('containers', size=container_list_length),
         ),
         FormActions(
             Submit('save', _('Update'), css_class="btn btn-lg btn-success"),
         )
     )
     self.helper.form_id = 'form-create-application'
     self.helper.form_class = 'form-horizontal'
     self.helper.form_action = reverse('applications.views.create')
Exemplo n.º 3
0
def container(container_id=None):
    container_inst = Container.query.get(
        container_id) if container_id is not None else Container()
    form = ContainerForm(obj=container_inst)
    if form.validate_on_submit():
        form.populate_obj(container_inst)
        db.session.add(container_inst)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.exception(e)
        else:
            flash(
                u'Блок контейнер успешно добавлен' if container_id is None else
                u'Блок контейнер успешно обновлен', 'success')
            return redirect(url_for('containers'))
    return render_template('container.html',
                           form=form,
                           container_id=container_id)
Exemplo n.º 4
0
def create(request):
    context = {}

    if request.method == 'GET':
        return render(request, 'containers/create.html', context)

    elif request.method == 'POST':
        print("This is a POST")
        receivedData = json.loads(request.body.decode("utf-8"))
        username = receivedData["username"]
        print(username)
        containerType = receivedData["type"]
        containerName = receivedData["name"]
        print("before user get")
        user = User.objects.get(username=username)
        print(user)

        container = Container(user_id=user.id,
                              containerType=containerType,
                              containerName=containerName)
        container.save()

        port = 8090 + container.id
        volumeName = "VolumeApi" + str(port)

        # Choosing the host
        response = requests.get(settings.HOSTS,
                                auth=(settings.RANCHER_USER,
                                      settings.RANCHER_PASS))
        jsonData = response.json()["data"]
        requestedHost = None
        bestResult = 999999
        ipAddress = None
        for x in range(0, len(jsonData)):
            infos = jsonData[x]["info"]
            memAvailable = infos["memoryInfo"]["memAvailable"]
            memTotal = infos["memoryInfo"]["memTotal"]
            percentageMem = 100.0 * memAvailable / memTotal
            percentageDisk = infos["diskInfo"]["mountPoints"]["/dev/sda1"][
                "percentage"]
            cpuPercentages = infos["cpuInfo"]["cpuCoresPercentages"]
            percentageCpu = 0
            for y in range(0, len(cpuPercentages)):
                percentageCpu += cpuPercentages[y]
            percentageCpu = 1.0 * percentageCpu / len(cpuPercentages)
            result = percentageMem + percentageCpu + percentageDisk
            if ((result < bestResult) and (percentageMem < 80)
                    and (percentageDisk < 80) and (percentageCpu < 80)):
                bestResult = result
                requestedHost = jsonData[x]["id"]
                ipAddress = jsonData[x]["publicEndpoints"][0]["ipAddress"]
        # A good host hasn't been found
        if (requestedHost == None):
            rand = random.randint(0, len(jsonData) - 1)
            requestedHost = jsonData[rand]["id"]
            ipAddress = jsonData[rand]["agentIpAddress"]

        if (containerType == "C Platform"):
            print("C platform")
            imageId = "paasinsa1617/cimage"
        elif (containerType == "Java Platform"):
            print("Java platform")
            imageId = "paasinsa1617/javaeeimage"
        elif (containerType == "Big data Platform"):
            print("Big data platform")
            imageId = "paasinsa1617/bigdataimage"
        elif (containerType == "Web Development"):
            print("Web development")
            imageId = "paasinsa1617/webdevimage"

        hash_object = hashlib.sha224(str(port).encode())
        containerPassword = hash_object.hexdigest()
        containerPassword = containerPassword[:8]
        link = "213.32.27.235:" + str(port)

        jsonMessage = {
            'message': '1',
            'password': containerPassword,
            'containerLink': link,
        }

        # Volume creation
        data = '{"description":"Description :)", "driver":"rancher-nfs", "name":"' + volumeName + '", "driverOpts": { }}'
        response = requests.post(settings.VOLUMES,
                                 auth=(settings.RANCHER_USER,
                                       settings.RANCHER_PASS),
                                 data=data)
        jsonResponse = response.json()
        container.volumeId = jsonResponse["id"]
        print(response.status_code)

        # Container creation
        data = '{"description":"Une description", "imageUuid":"docker:' + imageId + '", "name":"api-test' + str(
            port
        ) + '", "ports":["' + str(
            port
        ) + ':3000/tcp"], "requestedHostId":"' + requestedHost + '", "dataVolumes":["' + volumeName + ':/datas"], "environment":{ "DOCKER_USER": "******", "DOCKER_PASS":"******" }}'
        response = requests.post(settings.CONTAINERS,
                                 auth=(settings.RANCHER_USER,
                                       settings.RANCHER_PASS),
                                 data=data)
        print(response.status_code)
        jsonResponse = response.json()
        container.rancherId = jsonResponse["id"]
        container.save()
        subprocess.Popen([
            'iptables', '-t', 'nat', '-A', 'PREROUTING', '-p', 'tcp',
            '--dport',
            str(port), '-j', 'DNAT', '--to-destination',
            ipAddress + ':' + str(port)
        ])
        subprocess.Popen(['iptables-save'])

        return JsonResponse(jsonMessage)
Exemplo n.º 5
0
def newContainer(challenge_id, userID=None):

    if DEBUG:
        setContainerType = 'http'
    else:
        setContainerType = 'https'

    chall_obj = Challenge.objects.get(id=challenge_id)
    if userID is not None:
        user = User.objects.get(id=userID)
        try:
            new_cont_obj = d.createContainer(imageName=chall_obj.imageName,
                                             port=chall_obj.ports,
                                             pathPrefix=chall_obj.pathPrefix,
                                             containerType=setContainerType,
                                             username=user.username)
            print("############")
            print(
                "name: {0}, \nimage: {1}, \nlabels: {2}, \nshort_id: {3}, \nstatus: {4}"
                .format(new_cont_obj.name, new_cont_obj.image,
                        new_cont_obj.labels, new_cont_obj.short_id,
                        new_cont_obj.status))
            print("############")
            rethinkUsername = user.id

        except Exception as ex:
            raise Exception('Unable to create container. Exception info: ' +
                            str(ex))
    else:

        try:
            new_cont_obj = d.createContainer(imageName=chall_obj.imageName,
                                             port=chall_obj.ports,
                                             pathPrefix=chall_obj.pathPrefix,
                                             containerType=setContainerType)
            print("############")
            print(
                "name: {0}, \nimage: {1}, \nlabels: {2}, \nshort_id: {3}, \nstatus: {4}"
                .format(new_cont_obj.name, new_cont_obj.image,
                        new_cont_obj.labels, new_cont_obj.short_id,
                        new_cont_obj.status))
            print("############")
            user = None
            rethinkUsername = None

        except Exception as ex:
            raise Exception('Unable to create container. Exception info: ' +
                            str(ex))

    # Save the container
    try:
        container = Container(name=new_cont_obj.name,
                              challenge=chall_obj,
                              user=user)
        container.save()
    except Exception as ex:
        raise Exception('Unable to save container. Exception info: ' + str(ex))

    # Push the realtime data to rethinkdb
    connection = r.connect(host=RDB_HOST, port=RDB_PORT)
    try:
        r.db(CTF_DB).table('containers').insert({
            'sid':
            container.id,
            'name':
            container.name,
            'challenge':
            container.challenge.id,
            'user':
            rethinkUsername,
            'created':
            format(container.created, 'U')
        }).run(connection)
    except RqlRuntimeError as e:
        raise Exception('Error adding container to realtime database: %s' %
                        (e))
    finally:
        connection.close()

    return new_cont_obj