Exemplo n.º 1
0
def login_info(request):
    """Get information about the connected user.
    """

    login = request.authenticated_userid
    if not login:
        return {'login': login}

    # Get information about the user from the database.
    db_session = DBSession()
    user = db_session.query(User).filter(User.user_name == login).first()
    if not user:
        return {'login': login}

    email = user.email_address

    # The default avatar URL uses Gravatar <www.gravatar.com>:
    # http://www.gravatar.com/avatar/[md5 hex digest of the email]
    avatar_url = 'http://www.gravatar.com/avatar/%s' % (
        hashlib.md5(email.encode('utf-8')).hexdigest()
    )

    return {
        'avatar_url': avatar_url,
        'display_name': user.display_name,
        'email': email,
        'login': login,
    }
Exemplo n.º 2
0
def get_user_principals(login, request=None):
    """Gather security groups for the specified user.
    @return Pyramid principal list.
    """

    log.debug('Fetching principals for the user %s', login)

    principals = _DEFAULT_PRINCIPALS.copy()

    db_session = DBSession()

    user = db_session.query(User).filter(User.user_name == login).first()
    if not user:
        return principals

    # Record the ID of the user in principals.
    principals.add(user_principal(user.user_id))

    # Add actual principals.
    # TODO Probably a better way with joins / model declaration setup...
    principals.update(
        permission.permission_name
        for group in user.group_list
        for permission in group.permission_list
    )

    return list(principals)
Exemplo n.º 3
0
def login_info(request):
    """Get information about the connected user.
    """

    login = request.authenticated_userid
    if not login:
        return {'login': login}

    # Get information about the user from the database.
    db_session = DBSession()
    user = db_session.query(User).filter(User.user_name == login).first()
    if not user:
        return {'login': login}

    email = user.email_address

    # The default avatar URL uses Gravatar <www.gravatar.com>:
    # http://www.gravatar.com/avatar/[md5 hex digest of the email]
    avatar_url = 'http://www.gravatar.com/avatar/%s' % (hashlib.md5(
        email.encode('utf-8')).hexdigest())

    return {
        'avatar_url': avatar_url,
        'display_name': user.display_name,
        'email': email,
        'login': login,
    }
Exemplo n.º 4
0
        def authenticated_userid(self, request):
            """Override to change the password verifier (we don't store them as
            clear text).
            """

            login = self.unauthenticated_userid(request)
            password = self.get_password(request)
            if not login or not password:
                return None
            password = password.encode('utf-8')

            db_session = DBSession()

            # Ensure the user is in the DB and find its hashed password.
            user = db_session.query(User).filter(
                User.user_name == login).first()
            if not user:
                return None
            user_pass = user.password.encode('utf-8')

            # Verify the provided password against the hashed one.
            hashed_pass = sha1()
            hashed_pass.update(password + user_pass[:40])
            if user_pass[40:] != hashed_pass.hexdigest().encode('utf-8'):
                return None

            return user.user_name
Exemplo n.º 5
0
        def authenticated_userid(self, request):
            """Override to change the password verifier (we don't store them as
            clear text).
            """

            login = self.unauthenticated_userid(request)
            password = self.get_password(request)
            if not login or not password:
                return None
            password = password.encode('utf-8')

            db_session = DBSession()

            # Ensure the user is in the DB and find its hashed password.
            user = db_session.query(User).filter(
                User.user_name == login
            ).first()
            if not user:
                return None
            user_pass = user.password.encode('utf-8')

            # Verify the provided password against the hashed one.
            hashed_pass = sha1()
            hashed_pass.update(password + user_pass[:40])
            if user_pass[40:] != hashed_pass.hexdigest().encode('utf-8'):
                return None

            return user.user_name
Exemplo n.º 6
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from xbus.monitor.models.monitor import (
         BaseModel,
         MyModel,
         )
     DBSession.configure(bind=engine)
Exemplo n.º 7
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from xbus.monitor.models.monitor import (
         BaseModel,
         MyModel,
         )
     DBSession.configure(bind=engine)
     BaseModel.metadata.create_all(engine)
     with transaction.manager:
         model = MyModel(name='one', value=55)
         DBSession.add(model)
Exemplo n.º 8
0
def event_node_rel_add(request):

    record = get_record(request, _MODEL)
    rel_name, rid = request.matchdict.get('rel'), request.matchdict.get('rid')
    rel = record.get_mapper().get_property(rel_name)
    rel_list = getattr(record, rel_name, None)
    if rel is None or rel_list is None or not hasattr(rel_list, 'append'):
        raise HTTPBadRequest(
            json_body={
                "error": "Relationship {} does not exist".format(rel_name)
            },
        )

    query = DBSession.query(rel.mapper)
    added_record = query.get(rid)
    if added_record is None:
        raise HTTPNotFound(
            json_body={"error": "Event node ID {id} not found".format(id=rid)},
        )
    if added_record not in rel_list:
        rel_list.append(added_record)
    else:
        raise HTTPBadRequest(
            json_body={"error": "Object is already in the relationship"},
        )
    return added_record.as_dict()
Exemplo n.º 9
0
def emitter_profile_rel_delete(request):

    record = get_record(request, _MODEL)
    rel_name, rid = request.matchdict.get('rel'), request.matchdict.get('rid')
    rel = record.get_mapper().get_property(rel_name)
    rel_list = getattr(record, rel_name, None)
    if rel is None or rel_list is None or not hasattr(rel_list, 'append'):
        raise HTTPBadRequest(
            json_body={
                "error": "Relationship {} does not exist".format(rel_name)
            },
        )

    query = DBSession.query(rel.mapper)
    removed_record = query.get(rid)
    if removed_record is None:
        raise HTTPNotFound(
            json_body={"error": "Event node ID {id} not found".format(id=rid)},
        )
    if removed_record in rel_list:
        rel_list.remove(removed_record)
    else:
        raise HTTPBadRequest(
            json_body={"error": "Object is not in the relationship"},
        )
    return Response(status_int=204, json_body={})
Exemplo n.º 10
0
def upload(request):
    """View to handle file uploads. They are sent to Xbus.
    """

    # Check request parameters.
    emission_profile_id = request.params.get('emission_profile_id')
    file = request.params.get('file')
    if not emission_profile_id or file is None:
        raise HTTPBadRequest(
            json_body={'error': 'No emission profile selected'}, )

    # Get emission profile data from the database.
    emission_profile = DBSession.query(EmissionProfile).filter(
        EmissionProfile.id == emission_profile_id).first()
    if not emission_profile:
        raise HTTPBadRequest(json_body={'error': 'Invalid emission profile'}, )

    # Ensure execution of the emission profile is authorized for the current
    # user.
    if emission_profile.owner_id != get_logged_user_id(request):
        raise HTTPBadRequest(
            json_body={'error': 'Emission profile unauthorized'}, )

    # Fetch the input descriptor.
    descriptor = emission_profile.input_descriptor.descriptor.decode('utf-8')

    # TODO Use the selected encoding when decoding the file.

    front_url = request.registry.settings['xbus.broker.front.url']
    login = request.registry.settings['xbus.broker.front.login']
    password = request.registry.settings['xbus.broker.front.password']

    # Use a temporary file to store the upload.
    # TODO Use a pipe or some such?
    with NamedTemporaryFile(prefix='xbus-monitor-upload-') as f_temp:
        while True:
            buf = file.file.read(io.DEFAULT_BUFFER_SIZE)
            f_temp.write(buf)
            if len(buf) == 0:
                break

        # Open the file as text.
        f_temp.flush()
        f_temp_text = open(f_temp.name, 'r', newline='')

        # Send our data via 0mq to the Xbus front-end.
        zmq_loop = aiozmq.ZmqEventLoopPolicy().new_event_loop()
        try:
            emitter = FileEmitter(front_url,
                                  login,
                                  password, [descriptor],
                                  loop=zmq_loop)
            zmq_loop.run_until_complete(emitter.login())
            envelope_id = zmq_loop.run_until_complete(
                emitter.send_files([(f_temp_text, None)]))
        except FileEmitterException as e:
            raise HTTPBadRequest(json_body={'error': str(e)})

    return {'envelope_id': envelope_id}
Exemplo n.º 11
0
def event_tracking_create(request):
    record = EventTracking()

    record.user_id = get_logged_user_id(request)

    _update_record(request, record)

    # The object this tracking item is for.
    event = DBSession.query(Event).filter(
        Event.id == record.event_id
    ).first()

    new_state = getattr(record, 'new_state', None)
    if new_state:
        # Change the state of the event.
        event.state = new_state

    if record.user_id != event.responsible_id:
        # Update the responsible of the event.
        event.responsible_id = record.user_id

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 12
0
def event_error_tracking_create(request):
    record = EventErrorTracking()

    record.user_id = get_logged_user_id(request)

    _update_record(request, record)

    # The object this tracking item is for.
    event_error = DBSession.query(EventError).filter(
        EventError.id == record.event_error_id).first()

    new_state = getattr(record, 'new_state', None)
    if new_state:
        # Change the state of the event error.
        event_error.state = new_state

    if record.user_id != event_error.responsible_id:
        # Update the responsible of the event error.
        event_error.responsible_id = record.user_id

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 13
0
def _ensure_item_clearing_event_type(request):
    """Ensure an event type used when issuing Xbus requests related to data
    clearing items exists; otherwise, create it. It will have the "immediate
    reply" flag set.
    """

    session = DBSession()

    if session.query(EventType).filter(
            EventType.name == DATA_CLEARING_EVENT_TYPE).count() == 0:
        # Create an event type.
        event_type = EventType()
        event_type.description = (
            'Event type to carry Xbus requests related to data clearing items.'
        )
        event_type.immediate_reply = True
        event_type.name = DATA_CLEARING_EVENT_TYPE
        session.add(event_type)
        transaction.commit()
Exemplo n.º 14
0
def _ensure_item_clearing_event_type(request):
    """Ensure an event type used when issuing Xbus requests related to data
    clearing items exists; otherwise, create it. It will have the "immediate
    reply" flag set.
    """

    session = DBSession()

    if session.query(EventType).filter(
        EventType.name == DATA_CLEARING_EVENT_TYPE
    ).count() == 0:
        # Create an event type.
        event_type = EventType()
        event_type.description = (
            'Event type to carry Xbus requests related to data clearing items.'
        )
        event_type.immediate_reply = True
        event_type.name = DATA_CLEARING_EVENT_TYPE
        session.add(event_type)
        transaction.commit()
Exemplo n.º 15
0
def get_user_principals(login, request=None):
    """Gather security groups for the specified user.
    @return Pyramid principal list.
    """

    log.debug('Fetching principals for the user %s', login)

    principals = _DEFAULT_PRINCIPALS.copy()

    db_session = DBSession()

    user = db_session.query(User).filter(User.user_name == login).first()
    if not user:
        return principals

    # Record the ID of the user in principals.
    principals.add(user_principal(user.user_id))

    # Add actual principals.
    # TODO Probably a better way with joins / model declaration setup...
    principals.update(permission.permission_name for group in user.group_list
                      for permission in group.permission_list)

    return list(principals)
Exemplo n.º 16
0
def service_create(request):
    record = Service()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 17
0
def event_node_create(request):
    record = EventNode()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 18
0
def emitter_profile_create(request):
    record = EmitterProfile()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 19
0
def emitter_profile_create(request):
    record = EmitterProfile()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 20
0
def envelope_create(request):
    record = Envelope()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 21
0
def envelope_create(request):
    record = Envelope()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 22
0
def input_descriptor_create(request):
    record = InputDescriptor()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 23
0
def input_descriptor_create(request):
    record = InputDescriptor()

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 24
0
def role_create(request):
    record = Role()

    _update_record(request, record)
    record.password = gen_password(request.json_body['password'])

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 25
0
def emitter_create(request):
    record = Emitter()

    _update_record(request, record)
    record.password = gen_password(request.json_body['password'])

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 26
0
def emission_profile_create(request):
    record = EmissionProfile()

    record.owner_id = get_logged_user_id(request)

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 27
0
def emission_profile_create(request):
    record = EmissionProfile()

    record.owner_id = get_logged_user_id(request)

    _update_record(request, record)

    DBSession.add(record)
    DBSession.flush()
    DBSession.refresh(record)

    return record.as_dict()
Exemplo n.º 28
0
def event_type_rel_delete(request):

    record = get_record(request, _MODEL)
    rel_name, rid = request.matchdict.get('rel'), request.matchdict.get('rid')
    rel = record.get_mapper().get_property(rel_name)
    rel_list = getattr(record, rel_name, None)
    if rel is None or rel_list is None or not hasattr(rel_list, 'append'):
        raise HTTPBadRequest(json_body={
            "error":
            "Relationship {} does not exist".format(rel_name)
        }, )

    query = DBSession.query(rel.mapper)
    removed_record = query.get(rid)
    if removed_record is None:
        raise HTTPNotFound(
            json_body={"error":
                       "Event node ID {id} not found".format(id=rid)}, )
    if removed_record in rel_list:
        rel_list.remove(removed_record)
    else:
        raise HTTPBadRequest(
            json_body={"error": "Object is not in the relationship"}, )
    return Response(status_int=204, json_body={})
Exemplo n.º 29
0
def emitter_delete(request):
    record = get_record(request, _MODEL)
    DBSession.delete(record)

    return Response(status_int=204, json_body={})
Exemplo n.º 30
0
def load_config(raw_xml):

    root = ElementTree.fromstring(raw_xml)
    session = DBSession()
    services = {}
    events = {}
    profiles = {}

    for service_elem in root.findall('service'):
        name = service_elem.get('name')
        consumer = service_elem.get('consumer', False)
        desc = service_elem.text.strip()
        q = session.query(Service)
        q = q.filter(Service.name == name)
        service = q.first()
        if not service:
            service = Service(name=name)
            session.add(service)
        service.consumer = consumer
        service.description = desc
        services[name] = service

    for role_elem in root.findall('role'):
        login = role_elem.get('login')
        if not login:
            login = role_elem.get('name')
        service_name = role_elem.get('service')
        service = services.get(service_name)
        if not service:
            q1 = session.query(Service)
            q1 = q1.filter(Service.name == service_name)
            service = q1.first()
            if not service:
                raise Exception('Unknown service {}'.format(service_name))
            services[service_name] = service
        q2 = session.query(Role)
        q2 = q2.filter(Role.login == login)
        role = q2.first()
        if not role:
            role = Role(login=login)
            session.add(role)
        role.service = service

    for event_elem in root.findall('event_type'):
        name = event_elem.get('name')
        desc = event_elem.text.strip()
        q1 = session.query(EventType)
        q1 = q1.filter(EventType.name == name)
        event = q1.first()
        if not event:
            event = EventType(name=name)
            session.add(event)
        service.description = desc
        events[name] = event

        elem_levels = [iter(event_elem)]
        node_levels = [event_elem]
        while elem_levels:

            try:
                elem = next(elem_levels[-1])
            except StopIteration:
                del elem_levels[-1]
                del node_levels[-1]
                continue

            if len(node_levels) > 1:
                parents = [node_levels[-1]]
                start = False
            else:
                parents = []
                start = True

            service_name = elem.get('service')
            service = services.get(service_name)
            if not service:
                q2 = session.query(Service)
                q2 = q2.filter(Service.name == service_name)
                service = q2.first()
                if not service:
                    raise Exception('Unknown service {}'.format(service_name))
                services[service_name] = service

            node = EventNode(
                type=event, service=service, parents=parents, start=start
            )
            if elem.tag == 'worker':
                node_levels.append(node)
                elem_levels.append(iter(elem))

    for profile_elem in root.findall('profile'):
        name = profile_elem.get('name')
        desc = profile_elem.text.strip()

        event_types = []
        for type_elem in profile_elem.findall('event_type'):
            type_name = type_elem.get('name')
            event_type = events.get(type_name)
            if not event_type:
                q1 = session.query(EventType)
                q1 = q1.filter(EventType.name == type_name)
                event_type = q1.first()
                if not event_type:
                    raise Exception('Unknown event type {}'.format(type_name))
                events[type_name] = event_type
            event_types.append(event_type)

        q2 = session.query(EmitterProfile)
        q2 = q2.filter(EmitterProfile.name == name)
        profile = q2.first()
        if not profile:
            profile = EmitterProfile(name=name)
            session.add(profile)
        profile.description = desc
        profile.event_types = event_types
        profiles[name] = profile

    for emitter_elem in root.findall('emitter'):
        login = emitter_elem.get('login')
        if not login:
            login = emitter_elem.get('name')

        profile_name = emitter_elem.get('profile')
        profile = services.get(profile_name)
        if not profile:
            q1 = session.query(EmitterProfile)
            q1 = q1.filter(EmitterProfile.name == profile_name)
            profile = q1.first()
            if not profile:
                raise Exception('Unknown profile {}'.format(profile_name))
            profiles[profile_name] = profile
        q2 = session.query(Emitter)
        q2 = q2.filter(Emitter.login == login)
        emitter = q2.first()
        if not emitter:
            emitter = Emitter(login=login)
            session.add(emitter)
        emitter.profile = profile
Exemplo n.º 31
0
def load_config(raw_xml):

    root = ElementTree.fromstring(raw_xml)
    session = DBSession()
    services = {}
    events = {}
    profiles = {}

    for service_elem in root.findall('service'):
        name = service_elem.get('name')
        consumer = service_elem.get('consumer', False)
        desc = service_elem.text.strip()
        q = session.query(Service)
        q = q.filter(Service.name == name)
        service = q.first()
        if not service:
            service = Service(name=name)
            session.add(service)
        service.consumer = consumer
        service.description = desc
        services[name] = service

    for role_elem in root.findall('role'):
        login = role_elem.get('login')
        if not login:
            login = role_elem.get('name')
        service_name = role_elem.get('service')
        service = services.get(service_name)
        if not service:
            q1 = session.query(Service)
            q1 = q1.filter(Service.name == service_name)
            service = q1.first()
            if not service:
                raise Exception('Unknown service {}'.format(service_name))
            services[service_name] = service
        q2 = session.query(Role)
        q2 = q2.filter(Role.login == login)
        role = q2.first()
        if not role:
            role = Role(login=login)
            session.add(role)
        role.service = service

    for event_elem in root.findall('event_type'):
        name = event_elem.get('name')
        desc = event_elem.text.strip()
        q1 = session.query(EventType)
        q1 = q1.filter(EventType.name == name)
        event = q1.first()
        if not event:
            event = EventType(name=name)
            session.add(event)
        service.description = desc
        events[name] = event

        elem_levels = [iter(event_elem)]
        node_levels = [event_elem]
        while elem_levels:

            try:
                elem = next(elem_levels[-1])
            except StopIteration:
                del elem_levels[-1]
                del node_levels[-1]
                continue

            if len(node_levels) > 1:
                parents = [node_levels[-1]]
                start = False
            else:
                parents = []
                start = True

            service_name = elem.get('service')
            service = services.get(service_name)
            if not service:
                q2 = session.query(Service)
                q2 = q2.filter(Service.name == service_name)
                service = q2.first()
                if not service:
                    raise Exception('Unknown service {}'.format(service_name))
                services[service_name] = service

            node = EventNode(type=event,
                             service=service,
                             parents=parents,
                             start=start)
            if elem.tag == 'worker':
                node_levels.append(node)
                elem_levels.append(iter(elem))

    for profile_elem in root.findall('profile'):
        name = profile_elem.get('name')
        desc = profile_elem.text.strip()

        event_types = []
        for type_elem in profile_elem.findall('event_type'):
            type_name = type_elem.get('name')
            event_type = events.get(type_name)
            if not event_type:
                q1 = session.query(EventType)
                q1 = q1.filter(EventType.name == type_name)
                event_type = q1.first()
                if not event_type:
                    raise Exception('Unknown event type {}'.format(type_name))
                events[type_name] = event_type
            event_types.append(event_type)

        q2 = session.query(EmitterProfile)
        q2 = q2.filter(EmitterProfile.name == name)
        profile = q2.first()
        if not profile:
            profile = EmitterProfile(name=name)
            session.add(profile)
        profile.description = desc
        profile.event_types = event_types
        profiles[name] = profile

    for emitter_elem in root.findall('emitter'):
        login = emitter_elem.get('login')
        if not login:
            login = emitter_elem.get('name')

        profile_name = emitter_elem.get('profile')
        profile = services.get(profile_name)
        if not profile:
            q1 = session.query(EmitterProfile)
            q1 = q1.filter(EmitterProfile.name == profile_name)
            profile = q1.first()
            if not profile:
                raise Exception('Unknown profile {}'.format(profile_name))
            profiles[profile_name] = profile
        q2 = session.query(Emitter)
        q2 = q2.filter(Emitter.login == login)
        emitter = q2.first()
        if not emitter:
            emitter = Emitter(login=login)
            session.add(emitter)
        emitter.profile = profile
Exemplo n.º 32
0
 def tearDown(self):
     DBSession.remove()
     testing.tearDown()
Exemplo n.º 33
0
def main(global_config, **settings):
    """Initiate a Pyramid WSGI application.
    """

    db_url = settings.get('fig.sqlalchemy.url')
    if db_url:
        pg_socket_var = os.getenv('XBUS_POSTGRESQL_1_PORT')
        if pg_socket_var is not None:
            pg_socket = pg_socket_var.split('://', 1)[-1]
        else:
            pg_socket = settings.get('fig.sqlalchemy.default.socket')
        settings['sqlalchemy.url'] = db_url.format(socket=pg_socket)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    config = Configurator(
        session_factory=session_factory_from_settings(settings),
        settings=settings,
        root_factory=RootFactory,
    )

    config.include('pyramid_chameleon')

    # Determine the kind of auth to use based on settings; store it so others
    # can access the setting via "request.registry.settings.auth_kind").
    config.add_settings(auth_kind=(
        'saml2' if bool_setting(config.get_settings(), 'saml2.enabled')
        else 'http'
    ))

    if config.get_settings().auth_kind == 'http':
        http_auth.setup(config)
        config.include('pyramid_httpauth')

    elif config.get_settings().auth_kind == 'saml2':
        saml2_auth.setup(config)

    config.set_authorization_policy(ACLAuthorizationPolicy())

    # All views are protected by default; to provide an anonymous view, use
    # permission=pyramid.security.NO_PERMISSION_REQUIRED.
    config.set_default_permission('view')

    init_i18n(config)

    config.add_static_view('static', 'static', cache_max_age=3600)

    # Pages.

    config.add_route('home', '/')
    config.add_route('xml_config_ui', '/xml_config')
    config.add_route(
        'event_type_graph', API_PREFIX + 'event_type/{id}/graph',
        factory=RECORD_FACTORY_LOC.format(
            model='monitor', collection='event_type',
        ),
    )

    # Other routes.

    config.add_route('login_info', 'login_info')

    # REST API exposed with JSON.

    _add_api_routes(config, 'data_clearing', 'cl_event_type')
    _add_api_routes(config, 'data_clearing', 'cl_item')
    _add_api_routes(config, 'data_clearing', 'cl_item_column')
    _add_api_routes(config, 'data_clearing', 'cl_item_join')
    _add_api_routes(config, 'data_clearing', 'cl_item_type')

    _add_api_routes(config, 'monitor', 'emission_profile')
    _add_api_routes(config, 'monitor', 'emitter')
    _add_api_routes(config, 'monitor', 'emitter_profile')
    _add_api_routes(config, 'monitor', 'envelope')
    _add_api_routes(config, 'monitor', 'event')
    _add_api_routes(config, 'monitor', 'event_error')
    _add_api_routes(config, 'monitor', 'event_error_tracking')
    _add_api_routes(config, 'monitor', 'event_node')
    _add_api_routes(config, 'monitor', 'event_tracking')
    _add_api_routes(config, 'monitor', 'event_type')
    _add_api_routes(config, 'monitor', 'input_descriptor')
    _add_api_routes(config, 'monitor', 'role')
    _add_api_routes(config, 'monitor', 'service')
    _add_api_routes(config, 'monitor', 'user')

    # Other parts of the API.

    config.add_route('consumer_list', API_PREFIX + 'consumer')
    config.add_route('replay_envelope', API_PREFIX + 'replay_envelope')
    config.add_route('upload', API_PREFIX + 'upload')
    config.add_route('xml_config', API_PREFIX + 'xml_config')

    # Process view declarations.
    config.scan()

    # Run!
    return config.make_wsgi_app()
Exemplo n.º 34
0
def main(global_config, **settings):
    """Initiate a Pyramid WSGI application.
    """

    db_url = settings.get('fig.sqlalchemy.url')
    if db_url:
        pg_socket_var = os.getenv('XBUS_POSTGRESQL_1_PORT')
        if pg_socket_var is not None:
            pg_socket = pg_socket_var.split('://', 1)[-1]
        else:
            pg_socket = settings.get('fig.sqlalchemy.default.socket')
        settings['sqlalchemy.url'] = db_url.format(socket=pg_socket)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    config = Configurator(
        session_factory=session_factory_from_settings(settings),
        settings=settings,
        root_factory=RootFactory,
    )

    config.include('pyramid_chameleon')

    # Determine the kind of auth to use based on settings; store it so others
    # can access the setting via "request.registry.settings.auth_kind").
    config.add_settings(auth_kind=('saml2' if bool_setting(
        config.get_settings(), 'saml2.enabled') else 'http'))

    if config.get_settings().auth_kind == 'http':
        http_auth.setup(config)
        config.include('pyramid_httpauth')

    elif config.get_settings().auth_kind == 'saml2':
        saml2_auth.setup(config)

    config.set_authorization_policy(ACLAuthorizationPolicy())

    # All views are protected by default; to provide an anonymous view, use
    # permission=pyramid.security.NO_PERMISSION_REQUIRED.
    config.set_default_permission('view')

    init_i18n(config)

    config.add_static_view('static', 'static', cache_max_age=3600)

    # Pages.

    config.add_route('home', '/')
    config.add_route('xml_config_ui', '/xml_config')
    config.add_route(
        'event_type_graph',
        API_PREFIX + 'event_type/{id}/graph',
        factory=RECORD_FACTORY_LOC.format(
            model='monitor',
            collection='event_type',
        ),
    )

    # Other routes.

    config.add_route('login_info', 'login_info')

    # REST API exposed with JSON.

    _add_api_routes(config, 'data_clearing', 'cl_event_type')
    _add_api_routes(config, 'data_clearing', 'cl_item')
    _add_api_routes(config, 'data_clearing', 'cl_item_column')
    _add_api_routes(config, 'data_clearing', 'cl_item_join')
    _add_api_routes(config, 'data_clearing', 'cl_item_type')

    _add_api_routes(config, 'monitor', 'emission_profile')
    _add_api_routes(config, 'monitor', 'emitter')
    _add_api_routes(config, 'monitor', 'emitter_profile')
    _add_api_routes(config, 'monitor', 'envelope')
    _add_api_routes(config, 'monitor', 'event')
    _add_api_routes(config, 'monitor', 'event_error')
    _add_api_routes(config, 'monitor', 'event_error_tracking')
    _add_api_routes(config, 'monitor', 'event_node')
    _add_api_routes(config, 'monitor', 'event_tracking')
    _add_api_routes(config, 'monitor', 'event_type')
    _add_api_routes(config, 'monitor', 'input_descriptor')
    _add_api_routes(config, 'monitor', 'role')
    _add_api_routes(config, 'monitor', 'service')
    _add_api_routes(config, 'monitor', 'user')

    # Other parts of the API.

    config.add_route('consumer_list', API_PREFIX + 'consumer')
    config.add_route('replay_envelope', API_PREFIX + 'replay_envelope')
    config.add_route('upload', API_PREFIX + 'upload')
    config.add_route('xml_config', API_PREFIX + 'xml_config')

    # Process view declarations.
    config.scan()

    # Run!
    return config.make_wsgi_app()
Exemplo n.º 35
0
def envelope_delete(request):
    record = get_record(request, _MODEL)
    DBSession.delete(record)

    return Response(status_int=204, json_body={})
Exemplo n.º 36
0
def upload(request):
    """View to handle file uploads. They are sent to Xbus.
    """

    # Check request parameters.
    emission_profile_id = request.params.get('emission_profile_id')
    file = request.params.get('file')
    if not emission_profile_id or file is None:
        raise HTTPBadRequest(
            json_body={'error': 'No emission profile selected'},
        )

    # Get emission profile data from the database.
    emission_profile = DBSession.query(EmissionProfile).filter(
        EmissionProfile.id == emission_profile_id
    ).first()
    if not emission_profile:
        raise HTTPBadRequest(
            json_body={'error': 'Invalid emission profile'},
        )

    # Ensure execution of the emission profile is authorized for the current
    # user.
    if emission_profile.owner_id != get_logged_user_id(request):
        raise HTTPBadRequest(
            json_body={'error': 'Emission profile unauthorized'},
        )

    # Fetch the input descriptor.
    descriptor = emission_profile.input_descriptor.descriptor.decode('utf-8')

    # TODO Use the selected encoding when decoding the file.

    front_url = request.registry.settings['xbus.broker.front.url']
    login = request.registry.settings['xbus.broker.front.login']
    password = request.registry.settings['xbus.broker.front.password']

    # Use a temporary file to store the upload.
    # TODO Use a pipe or some such?
    with NamedTemporaryFile(prefix='xbus-monitor-upload-') as f_temp:
        while True:
            buf = file.file.read(io.DEFAULT_BUFFER_SIZE)
            f_temp.write(buf)
            if len(buf) == 0:
                break

        # Open the file as text.
        f_temp.flush()
        f_temp_text = open(f_temp.name, 'r', newline='')

        # Send our data via 0mq to the Xbus front-end.
        zmq_loop = aiozmq.ZmqEventLoopPolicy().new_event_loop()
        try:
            emitter = FileEmitter(
                front_url, login, password, [descriptor], loop=zmq_loop
            )
            zmq_loop.run_until_complete(emitter.login())
            envelope_id = zmq_loop.run_until_complete(
                emitter.send_files([(f_temp_text, None)])
            )
        except FileEmitterException as e:
            raise HTTPBadRequest(json_body={'error': str(e)})

    return {'envelope_id': envelope_id}
Exemplo n.º 37
0
def input_descriptor_delete(request):
    record = get_record(request, _MODEL)
    DBSession.delete(record)

    return Response(status_int=204, json_body={})