Beispiel #1
0
def management(container_id):
    """
    this function will restart/stop/kill an instace
    curl -i -H 'secretkey:1234' -H "Content-Type: application/json" -X POST -d
    '{"action":"start" }' http://localhost:5000/api/seedboxes/management/b90ea5517564
    :param container_id:
    :return:
    """
    content = request.json
    app.logger.info('Do action {0} for container{1}'.format(content['action'], container_id))
    #stop container
    if content['action'] == 'stop':
        make_connection.connect_docker_server().stop(container_id, timeout=10)
    #restart container
    if content['action'] == 'restart':
        make_connection.connect_docker_server().restart(container_id, timeout=10)
    #start container after stop
    if content['action'] == 'start':
        make_connection.connect_docker_server().start(container_id)
    #kill container, main process
    if content['action'] == 'kill':
        make_connection.connect_docker_server().kill(container_id, timeout=10)
    #delete container, force
    if content['action'] == 'delete':
        make_connection.connect_docker_server().remove_container(container_id, force=True)
        assert isinstance(my_sql_stuff.ContainerNames.query.filter_by(name_of_container=container_id).delete, object)
        my_sql_stuff.ContainerNames.query.filter_by(name_of_container=container_id).delete()
        db.session.commit()
    dat = '{0}"container_id": "{1}", "action": "{2}"{3}'.format('{', container_id, content['action'], '}')
    resp = Response(response=dat, status=200, mimetype="application/json")
    return resp
Beispiel #2
0
def give_me_mount_point(owner, size_plan):
    """
    this function will generate a shared tmpfs volume, the size should always be in M
    let's insert mount points into table, user is unique, every user will have unique mount points
    """
    if db.session.query(exists().where(my_sql_stuff.MountPoints.owner == owner)).scalar():
        #if user exists we will reuse the same volume
        new_volume = my_sql_stuff.MountPoints.query.filter_by(owner=owner).first()
        new_volume_str = str(new_volume)
        app.logger.info('This user has already a volume assigned {0}'.format(new_volume_str[21:]))
        return new_volume_str[21:]
    else:
        # seems this is a new user and we will create a new mount point for him
        my_random = random_generator_function.generator_instance.random_volume()
        size = 'size=' + size_plan
        # this will create a new volume
        new_volume = make_connection.connect_docker_server().create_volume(name=owner + my_random, driver='local',
                                                                           driver_opts={'type': 'tmpfs',
                                                                                        'device': 'tmpfs',
                                                                                        'o': size})

        new_volume_created = new_volume['Mountpoint'][:-6]
        new_volume_name = new_volume['Name']
        app.logger.info('new volume created:{0} for user:{1} with name {2}'.format(new_volume_created, owner, new_volume_name))
        db.session.add(my_sql_stuff.MountPoints(owner, new_volume_created, new_volume_name, size_plan))
        db.session.commit()
        return str(new_volume['Name'])
Beispiel #3
0
def executecommands(name_id):
    """
    this function will execute commands on the container
    curl -i -H "secretkey:1234" -H "Content-Type: application/json" -X POST -d
    '{"command":"htpasswd -b -c /etc/nginx/.htpasswd test test"}' http://arisvm:5000/api/seedboxes/execute/rtorrent

    :param name_id:
    :return:
    """
    try:
        content = request.json
        app.logger.info('executing command:{0} for container:{1}'.format(content['command'], name_id))
        exec_command = make_connection.connect_docker_server().exec_create(name_id, content['command'], tty=False, stderr=True, privileged=True)
        make_connection.connect_docker_server().exec_start(exec_command)
        exec_inspect = make_connection.connect_docker_server().exec_inspect(exec_command)
        return jsonify(exec_inspect)
    except:
         raise InvalidUsage('can\'t execute command on non existing/not running container', status_code=404)
Beispiel #4
0
def killuser():
    """
    :return:
    this function will delete all user containers and volume attached to the containers
    curl -i -H "secretkey:1234" -H "Content-Type: application/json" -X POST  -d '{"username":"******"}' http://localhost:5000/api/seedboxes/killuser
    """

    content = request.json
    user_to_be_deleted = format(content['username'])
    dat = 'All containers and volumes of username {0} have been deleted'.format(user_to_be_deleted)

    #let's do some checks

    if not db.session.query(exists().where(my_sql_stuff.ContainerNames.owner == user_to_be_deleted)).scalar():
        app.logger.info('There is no such username {0}'.format(user_to_be_deleted))
        raise InvalidUsage('there is no such username, nothing to delete, go away', status_code=404)
    else:
        try:
            #let's stop the containers
            for instance in db.session.query(my_sql_stuff.ContainerNames).group_by(
                    my_sql_stuff.ContainerNames.name_of_container).filter_by(owner=user_to_be_deleted).all():
                app.logger.info('Username {0} containers {1} will be deleted'.format(user_to_be_deleted, instance.name_of_container))
                make_connection.connect_docker_server().remove_container(instance.name_of_container, force=True)

            #remove container names from db
            my_sql_stuff.ContainerNames.query.filter_by(owner=user_to_be_deleted).delete()

            #let's delete volume
            for volume in db.session.query(my_sql_stuff.MountPoints).filter_by(owner=user_to_be_deleted).limit(1):
                app.logger.info('Username {0} volume {1} will be deleted'.format(user_to_be_deleted, volume.volume_name))
                make_connection.connect_docker_server().remove_volume(volume.volume_name)

            #let's delete volume from db
            my_sql_stuff.MountPoints.query.filter_by(owner=user_to_be_deleted).delete()
            #commit db
            db.session.commit()

            resp = Response(response=dat, status=200)
        except:
            app.logger.info('something bad happened')
            raise InvalidUsage('something bad happened ', status_code=500)

    return resp
Beispiel #5
0
def stats(container_id):
    """
    get statistics from container
    curl -i -H 'secretkey:1234'  http://localhost:5000/api/seedboxes/stats/vm6690_ssh
    :param container_id:
    :return:
    """
    app.logger.info('Received request for container stats for container {0}'.format(container_id))
    try:
        stats_obj = make_connection.connect_docker_server().stats(container_id, decode=True, stream=False)
        return jsonify(stats_obj)
    except:
        raise InvalidUsage('There is no container with this name', status_code=200)
Beispiel #6
0
def logs(container_id):
    """
    this function will retunr logs of started container, useful for softether to get the vpn keys
    curl -i -H 'secretkey:1234'  http://localhost:5000/api/seedboxes/logs/vm6690_ssh
    :param container_id:
    :return:
    """
    app.logger.info('Received request for container logs for container {0}'.format(container_id))
    try:
        logs_obj = make_connection.connect_docker_server().logs(container_id, stream=False)
        resp = Response(response=logs_obj, status=200, mimetype="application/txt")
        return resp
    except:
        raise InvalidUsage('There is no container with this name', status_code=200)
Beispiel #7
0
def docker_create(name_id, username, password, service, diskspace, image_name, internal_port, exec_this, cap_add_value,
                  privileged, plex_secret_token, plex_server_name):
    """
    this function will create the container
    :rtype : object
    :return:
    """
    #check if there is a container with the same name, anyway useless because docker is doing same thing
    #we can remove this in the future
    if db.session.query(exists().where(my_sql_stuff.ContainerNames.name_of_container == name_id)).scalar():
        raise InvalidUsage('there is a vm already with this name', status_code=404)


    #to the magic, generate unique port, make the shared volume
    my_new_volume = give_me_mount_point(username, diskspace)

    #making the list of ports from config
    #appending random values
    #making a dict of port from config and random ports

    my_new_list = [x + ':' + str(give_me_something_unique(name_id, name_id, username, password, service)) for x in internal_port]
    my_dict_port_list = dict(map(str, x.split(':')) for x in my_new_list)

    try:
        app.logger.info('Generating and inserting in db a new allocated port {0}'.format(my_new_list))
        where_to_mount = my_new_volume + parser.config_params('mount')['where_to_mount_dir']
        app.logger.info('We will mount in this location {0}'.format(where_to_mount))

        #here we make the list of ports from confing into a string
        #and remove / tcp udp
        #make removed string into a list and use it in ports
        internal_port_udp_tcp_removed = ''.join(c for c in ' '.join(internal_port) if c not in '/;udp;tcp').split()

        #creating the container
        response = make_connection.connect_docker_server().create_container(image=image_name, hostname=name_id,
                                                                            ports=internal_port_udp_tcp_removed,
                                                                            environment={'ACCESS_TOKEN': plex_secret_token,
                                                                                         'SERVER_NAME': plex_server_name,
                                                                                         'MANUAL_PORT': my_dict_port_list.values()[0]},
                                                                            host_config=make_connection.connect_docker_server().create_host_config(
                                                                                cap_add=[cap_add_value],
                                                                                binds=[where_to_mount],
                                                                                port_bindings=my_dict_port_list,
                                                                                privileged=privileged, cpuset_cpus='0', cpu_period=100000,
                                                                                mem_limit=parser.config_params('container_settings')['memory']),
                                                                            command=exec_this, name=name_id)
        #starting the container
        make_connection.connect_docker_server().start(container=response.get('Id'))

        result_new_container = make_connection.connect.inspect_container(response.get('Id'))
        new_hostname = result_new_container['Config']['Hostname']
        new_name = result_new_container['Name']
        new_exposed_ports = result_new_container['Config']['ExposedPorts']
        app.logger.info('New container with hostname {0} and name {1} exposed ports {2} created'.format(new_hostname,
                                                                                                        new_name,
                                                                                                        new_exposed_ports))
        app.logger.info('New container created with id {0}'.format(name_id))
        return result_new_container
    except:
            #this will delete the table raw where added port and name in ContainerNames
            my_sql_stuff.ContainerNames.query.filter_by(name_of_container=name_id).delete()
            db.session.commit()
            app.logger.error('An error occurred creating the container')
            raise InvalidUsage('can\'t make this container', status_code=404)