Beispiel #1
0
def login():
    logger.debug('Autenticando usuario')
    try:
        auth = request.authorization
        if not auth or not auth.username or not auth.password:
            logger.error(
                'No se ha podido autenticar al usuario: faltan las credenciales!'
            )
            return json_response(status=400)

        p = pam.pam()
        # user = p.authenticate(username=auth.username, password=auth.password, service='dvls')
        user = p.authenticate(username=auth.username, password=auth.password)

        if user and (auth.username == app.config['CONN_USER']):
            token = jwt.encode(
                dict(username=auth.username,
                     exp=datetime.utcnow() + timedelta(minutes=60)),
                app.config['SECRET_KEY'])
            return json_response(data=dict(token=token.decode('UTF-8')))

        logger.error(
            'No se ha podido autenticar al usuario: las credenciales son incorrectas!'
        )
        return json_response(status=403)
    except Exception as e:
        logger.error('No se ha podido autenticar al usuario: %s', str(e))
        return json_response(status=500)
Beispiel #2
0
def num_found_worker(arg):
    mc_key, keywords, date, filter_query = arg
    mc = mcapi.MediaCloud(mc_key)
    query = "%s AND (%s)" % (keywords_to_solr(keywords), filter_query)
    logger.debug("query: sentenceList: %s" % query)
    res = mc.sentenceList(query, '', 0, 0)
    return {
        'date': date
        , 'numFound': res['response']['numFound']
    }
Beispiel #3
0
def media_to_solr(media):
    d = json.loads(media)
    sources = ['media_id:%s' % i for i in d.get('sources', [])]
    source_query = join_query_clauses(sources, 'OR')
    tag_queries = []
    
    #for tag in d['tags']:
    #    parts = ['tags_id_media:%s' % i for i in tag['tags_id']]
    #    tag_queries.append(join_query_clauses(parts, 'OR'))
    if 'sets' in d:
        parts = ['tags_id_media:%s' % i for i in d['sets']] + ['tags_id_stories:%s' % i for i in d['sets']]
        tag_queries.append(join_query_clauses(parts, 'OR'))

    tag_query = join_query_clauses(tag_queries, 'OR')
    queries = []
    if len(source_query) > 0:
        queries.append(source_query)
    if len(tag_query) > 0:
        queries.append(tag_query)
    query = join_query_clauses(queries, 'OR')
    logger.debug("media_to_solr: "+query)
    return query
Beispiel #4
0
def clone_template(self, template_uuid, data):
    logger.info("Desplegando nueva plantilla")
    socketio = SocketIO(message_queue=app.config['CELERY_BROKER_URL'])
    try:
        template = Template.get(template_uuid).to_dict()
        domain_name = data['domain_name']
        lab_uuid = data['lab_uuid']

        lab = Lab.get(lab_uuid)
        hosts = lab.hosts

        if hosts.__len__() == 0:
            logger.error('El laboratorio no tiene ningún host asociado')
            socketio.emit('task-finished', {
                'task_type': 'clone-template',
                'task_id': self.request.id.__str__(),
                'status': -1
            })
            return -1

        cmd = ['virt-clone',
               '--connect', app.config['LOCAL_QEMU_URI'],
               '--original-xml', template['xml_path'],
               '--name', domain_name]

        for count in range(template['images_path'].__len__()):
            cmd.append('--file')
            cmd.append(app.config['DOMAIN_IMAGES_DIR'] + domain_name + '-disk' + str(count) + '.qcow2')

        ssh = paramiko.SSHClient()
        # Surrounds 'known_hosts' error
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        k = paramiko.RSAKey.from_private_key_file("/home/dvls/.ssh/id_rsa")
        errors = list()
        for h in hosts:
            host = h.ip_address
            username = h.conn_user
            logger.debug('Desplegando en el host %s, IP: %s', h.code, h.ip_address)
            try:
                # NO PASSWORD!! Server SSH key is previously distributed among lab PCs
                logger.debug('Conectando al equipo')
                ssh.connect(hostname=host.compressed, username=username, timeout=4, pkey=k)
                ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(' '.join(cmd))
                errors = [b.rstrip() for b in ssh_stderr.readlines()]
                if len(errors) > 0:
                    logger.error('No se pudo desplegar la plantilla en el host %s (%s)', h.code, h.ip_address.compressed)
                    logger.error(cmd)
                    logger.error(errors)
            except Exception as e:
                logger.error('No se pudo desplegar la plantilla en el host %s (%s): %s', h.code, h.ip_address.compressed, str(e))
                errors = True
            finally:
                logger.debug('Desplegado en el equipo %s', h.code)
                ssh.close()
        if errors or len(errors) > 0:
            socketio.emit('task-finished', {
                'task_type': 'clone-template',
                'task_id': self.request.id.__str__(),
                'status': -1
            })
            return -1

        socketio.emit('task-finished', {
            'task_type': 'clone-template',
            'task_id': self.request.id.__str__(),
            'status': 0
        })
        logger.info("Plantilla desplegada correctamente")
        return 0
    except Exception as e:
        logger.error('No se pudo desplegar la plantilla: %s', str(e))
        socketio.emit('task-finished', {
            'task_type': 'clone-template',
            'task_id': self.request.id.__str__(),
            'status': -1
        })
        return -1
Beispiel #5
0
def socketio_connect():
    logger.debug('Iniciada una conexión de WebSockets')
Beispiel #6
0
def socketio_disconnect():
    logger.debug('Acabada una conexión de WebSockets')