Beispiel #1
0
def discover_handlers(database_name, logger_enabled):
    pool_manager = PoolManager(database_name)
    transaction = Transaction()
    logger.debug("Starting db transaction for domain:%s" % database_name)
    transaction.start(database_name, 0)
    logger.debug("Connecting to table")
    transaction_handler_table = pool_manager.get_table("hl7.transaction_handler")
    logger.debug("Preparing query for table -> %s" % transaction_handler_table)
    query = transaction_handler_table.select(*[transaction_handler_table.message_handler_module_name,
                                             transaction_handler_table.message_handler_class_name,
                                             transaction_handler_table.message_type])
    cursor = transaction.cursor
    logger.debug("Executing query:%s" % query)
    cursor.execute(*query)

    results = cursor.fetchall()  # return all results
    logger.debug("Query results: %s" % results)

    transaction.stop()

    handlers = {
        "ERR": (HL7ErrorHandler, pool_manager)
    }
    if results:
        for r in results:
            handler_module_name = r[0]
            handler_class_name = r[1]
            message_type = r[2]
            handlers[message_type] = (str_to_class(handler_module_name, handler_class_name), pool_manager,
                                      logger_enabled)

    logger.debug("handlers found: " + str(handlers))
    return handlers
Beispiel #2
0
    def wrap(self, *args, **kwargs):
        message_res = met(self, *args, **kwargs)
        if self.logger_enabled:
            message_req = self.incoming_message

            logger.debug("Saving transition:\nIN: %s\nOUT: %s\nHandler: %s\n" % (message_req, message_res,
                                                                                 self.__class__.__name__))
            transaction = Transaction()
            logger.debug("Starting db transaction for domain:%s" % self.pool_manager.get_domain())
            transaction.start(self.pool_manager.get_domain(), 0)
            logger.debug("Connecting to table")
            hl7_message_logger = self.pool_manager.get_table("hl7.message_logger")
            logger.debug("Preparing query for table:::%s" % hl7_message_logger)

            cursor = transaction.cursor

            insert_columns = [hl7_message_logger.create_uid, hl7_message_logger.create_date,
                              hl7_message_logger.creation_date, hl7_message_logger.request,
                              hl7_message_logger.response, hl7_message_logger.handler_module]
            insert_values = [transaction.user, Now(), Now(), message_req,  message_res[1:-2],  self.__class__.__name__]

            cursor.execute(*hl7_message_logger.insert(insert_columns, [insert_values]))
            cursor.execute("commit")

            logger.debug("Query executed")
            transaction.stop()

        return message_res
Beispiel #3
0
 def _get_sending_application(self):
     transaction = Transaction()
     transaction.start(self.pool.get_domain(), 0)
     query = self.hl7_conf_table.select(*[self.hl7_conf_table.application_code])
     cursor = transaction.cursor
     cursor.execute(*query)
     results = cursor.fetchall()  # return all results
     transaction.stop()
     
     if results is not None and len(results) > 0:
         return results[0][0]
     else:
         return "gnuhealth"
Beispiel #4
0
 def _get_pdq_allowed_applications(self):
     transaction = Transaction()
     transaction.start(self.pool.get_domain(), 0)
     query = self.pdq_allowed_apps_table.select(*[self.pdq_allowed_apps_table.allowed_application])
     cursor = transaction.cursor
     cursor.execute(*query)
     results = cursor.fetchall()  # return all results
     transaction.stop()  # cursor.close()
     
     if results is not None and len(results) > 0:
         allowed_apps = [res[0] for res in results]
         logger.debug("Allowed APPS:%s" % allowed_apps)
         return allowed_apps
     else:
         logger.debug("NO allowed applications found")
         return []
Beispiel #5
0
    def run(cls, db_name):
        transaction = Transaction()
        logger.info('cron started for "%s"', db_name)
        now = datetime.datetime.now()
        retry = config.getint('database', 'retry')
        with transaction.start(db_name, 0, context={'_skip_warnings': True}):
            transaction.database.lock(transaction.connection, cls._table)
            crons = cls.search(['OR',
                    ('next_call', '<=', now),
                    ('next_call', '=', None),
                    ])

            for cron in crons:
                name = '<Cron %s@%s %s>' % (cron.id, db_name, cron.method)
                logger.info("%s started", name)
                for count in range(retry, -1, -1):
                    if count != retry:
                        time.sleep(0.02 * (retry - count))
                    try:
                        with processing(name):
                            cron.run_once()
                            cron.next_call = cron.compute_next_call(now)
                            cron.save()
                            transaction.commit()
                    except Exception as e:
                        transaction.rollback()
                        if (isinstance(e, backend.DatabaseOperationalError)
                                and count):
                            continue
                        logger.error('%s failed', name, exc_info=True)
                    break
        while transaction.tasks:
            task_id = transaction.tasks.pop()
            run_task(db_name, task_id)
        logger.info('cron finished for "%s"', db_name)
Beispiel #6
0
 def wrapper(*args, **kwargs):
     transaction = Transaction()
     with transaction.start(DB_NAME, user, context=context):
         result = func(*args, **kwargs)
         transaction.rollback()
         # Drop the cache as the transaction is rollbacked
         Cache.drop(DB_NAME)
         return result
Beispiel #7
0
 def wrapper(*args, **kwargs):
     transaction = Transaction()
     with transaction.start(DB_NAME, user, context=context):
         result = func(*args, **kwargs)
         transaction.cursor.rollback()
         # Drop the cache as the transaction is rollbacked
         Cache.drop(DB_NAME)
         return result
Beispiel #8
0
   def _load_pdq_configuration_dict(self):
       """
       Load the pdq configuration dict from the database, based on the current content of the hl7 and pdq tables
       """
 
       conf = {
           "ENABLED": False,
           "ALLOWED_APPLICATIONS": [],
           "FILTER_BY_ALLOWED_APP": False,
           "SENDING_FACILITY": "gnuhealth",
           "SENDING_APPLICATION": "gnuhealth",
           "CHARACTER_SET": CHARACTER_SET,
           "LANGUAGE": LANGUAGE,
           "COUNTRY": COUNTRY_CODE
       }
       
       transaction = Transaction()
       transaction.start(self.pool.get_domain(), 0)
       query = self.pdq_conf_table.select(*[self.pdq_conf_table.enabled, self.pdq_conf_table.facility_name,
                                          self.pdq_conf_table.filter_by_allowed_app, self.pdq_conf_table.encoding_char,
                                          self.pdq_conf_table.country, self.pdq_conf_table.language])
       cursor = transaction.cursor
       cursor.execute(*query)
       results = cursor.fetchall()  # return all results
       logger.debug("PDQ CONFIGURATION Query results: %s" % results)
       
       transaction.stop()
       
       if results:
           conf["ENABLED"] = results[0][0]   
           conf["SENDING_FACILITY"] = results[0][1]   
           conf["FILTER_BY_ALLOWED_APP"] = results[0][2]
           conf["CHARACTER_SET"] = results[0][3]
           conf["COUNTRY"] = results[0][4]
           conf["LANGUAGE"] = results[0][5]
           conf["ALLOWED_APPLICATIONS"] = self._get_pdq_allowed_applications()
           conf["SENDING_APPLICATION"] = self._get_sending_application()
           
       return conf
def transaction(request):
    """Yields transaction with installed module.
    """

    # Importing transaction directly causes cyclic dependency in 3.6
    from trytond.tests.test_tryton import USER, CONTEXT, DB_NAME, POOL
    from trytond.tools.singleton import Singleton  # noqa
    from trytond.transaction import Transaction
    from trytond.cache import Cache

    # Inject helper functions in instance on which test function was collected.
    request.instance.POOL = POOL
    request.instance.USER = USER
    request.instance.CONTEXT = CONTEXT
    request.instance.DB_NAME = DB_NAME

    transaction = Transaction()

    with transaction.start(DB_NAME, USER, context=CONTEXT) as txn:
        yield txn
        transaction.rollback()
        Cache.drop(DB_NAME)
Beispiel #10
0
    def test_subscribe_message(self):
        "Test subscribe with message"
        Bus.subscribe(DB_NAME, ['user:1'])

        transaction = Transaction()
        with transaction.start(DB_NAME, 1):
            notify("Test", "Message", user=1)
            transaction.commit()
        # Let the listen thread registers the message
        time.sleep(1)
        response = Bus.subscribe(DB_NAME, ['user:1'])

        self.assertTrue(response['message'].pop('message_id'))
        self.assertEqual(response, {
                'message': {
                    'type': 'notification',
                    'title': "Test",
                    'body': "Message",
                    'priority': 1,
                    },
                'channel': 'user:1',
                })
def transaction(request):
    """Yields transaction with installed module.
    """

    # Importing transaction directly causes cyclic dependency in 3.6
    from trytond.tests.test_tryton import USER, CONTEXT, DB_NAME, POOL
    from trytond.tools.singleton import Singleton  # noqa
    from trytond.transaction import Transaction
    from trytond.cache import Cache

    # Inject helper functions in instance on which test function was collected.
    request.instance.POOL = POOL
    request.instance.USER = USER
    request.instance.CONTEXT = CONTEXT
    request.instance.DB_NAME = DB_NAME

    transaction = Transaction()

    with transaction.start(DB_NAME, USER, context=CONTEXT) as txn:
        yield txn
        transaction.rollback()
        Cache.drop(DB_NAME)