Esempio n. 1
0
    def post(self, id):
        """
        Create snapshot
        """
        data = request.get_json()['data']

        current_identity = import_user()
        instance = Instance.query.get(id)
        lxdserver = Server.query.filter_by(name=instance.location).first()

        if instance.name and (id in current_identity.instances
                              or current_identity.admin):
            app.logger.info('User: %s creating snapshot on container %s',
                            current_identity.username, instance.name)

            if not instance:
                api.abort(code=409, message='Snapshot name already exists')
            else:
                res = lgw.lxd_api_post(lxdserver, 'instances/' +
                                       instance.name + '/snapshots', {
                                           'name': data['name'],
                                           'stateful': False
                                       })  # recursion=1 returns objects
                # print(res.json())
                return {'data': res.json()['metadata']}

        api.abort(code=500, message='Can\'t create instance')
Esempio n. 2
0
    def post(self):
        """
        Create container based on POST data with image from linuxcontainers.org

        Example:
        data = {'name': 'vpsX', 'source': {'type': 'image', 'mode': 'pull',
            'server': 'https://uk.images.linuxcontainers.org', 'protocol': 'simplestreams',
            'alias': 'ubuntu/16.04'}, 'config': {'limits.cpu': '2', 'limits.memory': '256MB'}}
        :return: status code
        """

        current_identity = import_user()
        data = request.get_json()['data']
        print(data)

        if 'name' in data['attributes']:
            c = Container.query.filter_by(
                name=data['attributes']['name']).first()
            if not c:
                config = {
                    'name': data['attributes']['name'],
                    'source': {
                        'type': 'image',
                        'mode': 'pull',
                        'server': 'https://uk.images.linuxcontainers.org',
                        'protocol': 'simplestreams',
                        'alias': data['attributes']['source']['alias']
                    },
                    'config': {
                        'limits.cpu':
                        str(data['attributes']['config']['limits_cpu']),
                        'limits.memory':
                        data['attributes']['config']['limits_memory']
                    }
                }
                #'devices': {'root': {'path': '/', 'pool': 'lxd','type': 'disk', 'size': '10GB'}}}
                try:
                    res = lgw.lxd_api_post('containers', data=config)
                    print(res.text)
                except Exception as e:
                    api.abort(code=500, message='Can\'t create container')

                if res.status_code == 202:
                    # Add container to database
                    container = Container(name=data['attributes']['name'])
                    db.session.add(container)
                    db.session.commit()
                    # Get container ID
                    container = Container.query.filter_by(
                        name=data['attributes']['name']).first()
                    # Add container to allowed user's containers
                    user = User.query.get(current_identity.id)
                    user.containers.append(container.id)
                    db.session.commit()
                else:
                    api.abort(code=res.status_code,
                              message='Error when creating container')
                return res.json()
            api.abort(code=409, message='Container already exists')
Esempio n. 3
0
 def post(self, server):
     """
     create image on server x
     """
     data = request.get_json()['data']
     current_identity = import_user()
     lxdserver = Server.query.filter_by(name=server).first()
     if current_identity.admin:
         app.logger.info('User: %s creating new image',
                         current_identity.username)
         res = lgw.lxd_api_post(lxdserver, 'images', data=data)
         return res.json()
Esempio n. 4
0
 def post(self, url, server):
     """
     Create 'universal'
     """
     data = request.get_json()['data']
     lxdserver = Server.query.filter_by(name=server).first()
     # print(data)
     current_identity = import_user()
     if current_identity.admin and lxdserver:
         app.logger.info('User: %s creating something on %s',
                         import_user().username, url)
         res = lgw.lxd_api_post(lxdserver, url, data=data)
         return res.json()
Esempio n. 5
0
    def post(self, server, alias, d=None):
        """
        Rename image alias
        """
        if d:
            data = d
        else:
            data = request.get_json()['data']

        lxdserver = Server.query.filter_by(name=server).first()
        app.logger.info('User: %s rename image alias %s',
                        import_user().username, alias)
        res = lgw.lxd_api_post(lxdserver, 'images/aliases/' + alias, data=data)
        return res.json()['metadata']
Esempio n. 6
0
    def post(self, url, server, name, d=None):
        """
        Rename 'universal'
        """
        if d:
            data = d
        else:
            data = request.get_json()['data']

        lxdserver = Server.query.filter_by(name=server).first()
        app.logger.info('User: %s renaming something on %s',
                        import_user().username, url)
        res = lgw.lxd_api_post(lxdserver, url + '/' + name, data=data)
        return res.json()['metadata']
Esempio n. 7
0
    def post(self, id):
        """
        Open instance terminal
        :param id
        :return terminal data
        """
        data = {
            'command': ['/bin/bash'],  # Command and arguments
            'environment': {},  # Optional extra environment variables to set
            'wait-for-websocket':
            True,  # Whether to wait for a connection before starting the process
            'record-output':
            False,  # Whether to store stdout and stderr (only valid with wait-for-websocket=false) (requires API extension instance_exec_recording)
            'interactive':
            True,  # Whether to allocate a pts device instead of PIPEs
            'width': 80,  # Initial width of the terminal (optional)
            'height': 25,  # Initial height of the terminal (optional)
        }

        current_identity = import_user()
        try:
            # c = Instance.query.filter_by(name=name).first()  # USE FOR QUERY BY NAME
            c = Instance.query.filter_by(id=id).first()
            lxdserver = Server.query.filter_by(name=c.location).first()
            if c and (c.id in current_identity.instances
                      or current_identity.admin):

                app.logger.info('User: %s starting console on container %s',
                                current_identity.username, c.name)

                #res = lgw.lxd_api_post('instances/' + c.name + '/console', {}) #bug with closing console
                res = lgw.lxd_api_post(lxdserver,
                                       'instances/' + c.name + '/exec', data)

                relationships = lxdserver.get_as_relationships_exec()

                res_meta = res.json()['metadata']
                res_meta.update({'relationships': relationships})

                #print(res_meta)
                return {'data': res_meta}
            else:
                api.abort(code=403, message='Unauthorized access')
        except:
            api.abort(code=404, message='Instance doesn\'t exists')
Esempio n. 8
0
    def post(self, id):
        """
        Open container terminal
        :param id
        :return terminal data
        """
        # this part working for /exec api
        data = {
            'command': ['/bin/bash'],  # Command and arguments
            'environment': {},  # Optional extra environment variables to set
            'wait-for-websocket':
            True,  # Whether to wait for a connection before starting the process
            'record-output':
            False,  # Whether to store stdout and stderr (only valid with wait-for-websocket=false) (requires API extension container_exec_recording)
            'interactive':
            True,  # Whether to allocate a pts device instead of PIPEs
            'width': 80,  # Initial width of the terminal (optional)
            'height': 25,  # Initial height of the terminal (optional)
        }
        # this part working for /console api
        # data = {
        #    'width': 80,
        #    'height': 25
        # }

        current_identity = import_user()
        try:
            # c = Container.query.filter_by(name=name).first()  # USE FOR QUERY BY NAME
            c = Container.query.filter_by(id=id).first()
            if c and (c.id in current_identity.containers
                      or current_identity.admin):
                res = lgw.lxd_api_post('containers/' + c.name + '/exec', data)
                # return res.json()
                return {
                    'data': {
                        'type': 'terminal',
                        'id': id,
                        'attributes': res.json()
                    }
                }, 201
            else:
                api.abort(code=403, message='Unauthorized access')
        except:
            api.abort(code=404, message='Container doesn\'t exists')
Esempio n. 9
0
    def post(self):
        """
        Create instance based on POST data with image from linuxcontainers.org

        :return: status code
        """

        current_identity = import_user()
        data = request.get_json()['data']

        try:
            servers_id = list(id['id']
                              for id in data['relationships']['servers'])
            lxdserver = Server.query.get(servers_id[0])
        except KeyError as e:
            app.logger.error('Error when creating new container %s', e)
            pass
        except AttributeError as e:
            app.logger.error('Error when creating new container %s', e)
            api.abort(code=500, message='Server doesn\'t exists')

        if 'name' in data:
            c = Instance.query.filter_by(name=data['name']).first()
            if not c:
                app.logger.info('User: %s creating new container %s',
                                current_identity.username, data['name'])
                config = data['instance']
                try:
                    res = lgw.lxd_api_post(lxdserver, 'instances', data=config)
                except Exception as e:
                    app.logger.error('Error when creating new container %s', e)
                    api.abort(code=500, message='Can\'t create instance')

                if res.status_code == 202:
                    # Add instance to database
                    instance = Instance(name=data['name'],
                                        location=lxdserver.name)
                    db.session.add(instance)
                    db.session.commit()
                    # Get instance ID
                    instance = Instance.query.filter_by(
                        name=data['name']).first()

                    # Add instance to server instances
                    lxdserver.instances.append(instance.id)
                    db.session.commit()

                    # Add instance to allowed users
                    if current_identity.admin:
                        try:
                            users_id = list(
                                id['id']
                                for id in data['relationships']['users'])
                            for user_id in users_id:
                                user = User.query.get(user_id)
                                user.instances.append(instance.id)
                                db.session.commit()
                        except KeyError as e:
                            app.logger.error(
                                'Error when creating new container %s', e)
                            pass
                        except AttributeError:
                            app.logger.error(
                                'Error when creating new container %s', e)
                            api.abort(code=500, message='User doesn\'t exists')
                    # Add instance to current user
                    else:
                        user = User.query.get(current_identity.id)
                        user.instances.append(instance.id)
                        db.session.commit()
                else:
                    app.logger.error(
                        'Error from lxd when creating new container %s',
                        res.text)
                    api.abort(code=res.status_code,
                              message='Error when creating instance')

                return res.json()
            app.logger.error('Conflict - instance already exists: %s',
                             data['name'])
            api.abort(code=409, message='Instance already exists')