Esempio n. 1
0
def install_packages(packages):
    if ask_to_install(packages):
        logger.info("Dependencies installed. Please launch Faraday Server again")
        sys.exit(0)
    else:
        logger.error("Dependencies not met")
        sys.exit(1)
Esempio n. 2
0
def is_server_running():
    pid = daemonize.is_server_running()
    if pid is not None:
        logger.error("Faraday Server is already running. PID: {}".format(pid))
        return True
    else:
        return False
Esempio n. 3
0
def setup_environment(check_deps=False):
    # Configuration files generation
    server.config.copy_default_config_to_local()

    if check_deps:

        # Check dependencies
        installed_deps, missing_deps, conflict_deps = dependencies.check_dependencies(
            requirements_file=server.config.REQUIREMENTS_FILE)

        logger.info("Checking dependencies...")

        if conflict_deps:
            logger.info("Some dependencies are old. Update them with \"pip install -r requirements_server.txt -U\"")

        if missing_deps:

            install_deps = query_yes_no("Do you want to install them?", default="no")

            if install_deps:
                dependencies.install_packages(missing_deps)
                logger.info("Dependencies installed. Please launch Faraday Server again.")
                sys.exit(0)
            else:
                logger.error("Dependencies not met. Please refer to the documentation in order to install them. [%s]",
                             ", ".join(missing_deps))

        logger.info("Dependencies met")

    # Web configuration file generation
    server.config.gen_web_config()
Esempio n. 4
0
def get_prescriptions(patientid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    logger.debug('in get_prescriptions')
    resp_list = []
    try:
        patient = PatientModel.get(PatientModel.email==patientid)

        for prescription in PrescriptionModel.select().where(PrescriptionModel.patient==patient):
            logger.debug('drug_id: %s, descrip: %s' % (prescription.drug_id, prescription.description))
            resp_dict = {}
            resp_dict['drug_name'] = prescription.drug_name
            resp_dict['after_meal'] = prescription.after_meal
            resp_dict['description'] = prescription.description
            resp_dict['datetime'] = prescription.datetime
            resp_dict['amount'] = prescription.amount
            resp_dict['dosage_per_day'] = prescription.dosage_per_day
            resp_dict['response_doctor'] = prescription.response_doctor
            resp_list.append(resp_dict)
        logger.debug('prescriptions:{}'.format(resp_list))

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get prescriptions failed'}

    else:
        return 1, resp_list
Esempio n. 5
0
def setup_environment(check_deps=False):
    # Configuration files generation
    server.config.copy_default_config_to_local()

    if check_deps:

        # Check dependencies
        installed_deps, missing_deps = dependencies.check_dependencies(
            requirements_file=server.config.REQUIREMENTS_FILE)

        logger.info("Checking dependencies...")

        if missing_deps:

            install_deps = query_yes_no("Do you want to install them?", default="no")

            if install_deps:
                dependencies.install_packages(missing_deps)
                logger.info("Dependencies installed. Please launch Faraday Server again.")
                sys.exit(0)
            else:
                logger.error("Dependencies not met. Please refer to the documentation in order to install them. [%s]",
                             ", ".join(missing_deps))

        logger.info("Dependencies met")

    # Web configuration file generation
    server.config.gen_web_config()

    # Reports DB creation
    server.couchdb.push_reports()
Esempio n. 6
0
def get_discharges(patientid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    logger.debug('in get_discharges')
    resp_list = []
    try:
        patient = PatientModel.get(PatientModel.email==patientid)

        for discharge in DischargeModel.select().where(DischargeModel.patient==patient):
            logger.debug('discharge_id: %s, indate: %s' % (discharge.discharge_id, discharge.indate))
            resp_dict = {}
            resp_dict['indate'] = discharge.indate
            resp_dict['outdate'] = discharge.outdate
            resp_dict['response_doctor'] = discharge.response_doctor
            resp_dict['description'] = discharge.description
            resp_dict['datetime'] = discharge.datetime
            resp_list.append(resp_dict)
        logger.debug('discharges:{}'.format(resp_list))

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get discharges failed'}

    else:
        return 1, resp_list
Esempio n. 7
0
def is_server_running():
    pid = daemonize.is_server_running()
    if pid is not None:
        logger.error("Faraday Server is already running. PID: {}".format(pid))
        return True
    else:
        return False
Esempio n. 8
0
    def run(self):
        for change_doc in self.__stream:
            try:
                if self.CHANGE_CLS.validate(change_doc):
                    self.__changes_callback(self.CHANGE_CLS(change_doc))
                else:
                    logger.debug(u'Ignoring change: {}'.format(change_doc))

            except Exception, e:
                import traceback
                logger.debug(traceback.format_exc())
                logger.warning(
                    u"Error while processing change. Ignoring. Offending change: {}"
                    .format(change_doc))

                if change_doc.get('error', None):
                    if change_doc.get('error') == 'unauthorized':
                        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
                            " configuration file has CouchDB admin's credentials set")
                        thread.interrupt_main()

                    # TODO: A proper fix is needed here
                    elif change_doc.get('reason') == 'no_db_file':
                        self.__stream.stop()
                        break
Esempio n. 9
0
def check_appointment(doctorid, date):
    """
    Get info of appointments for a doctor on a date in the system.

    :param appointment_url: appointment's url
    :returns: a status, a str ( appointments timeslots info on success,
                                    err info on failure)
    """
    # print(doctorid, date)
    # info = {}
    try:
        logger.debug('in check_appointment')
        schedule = rediscli.get_data(doctorid+'/'+date)
    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, 'check_appointment failed'
    else:
        logger.debug('in check_appointment schedule data:{}'.format(schedule))
        if schedule:
            logger.debug('in check_appointment schedule data:{}'.format(schedule))
            # appointments_json = json.dumps(schedule)
            return 1, compatible(schedule)
        # no appointment for this doctor on this date
        else:
            return 1, compatible('{}')
Esempio n. 10
0
def get_obj(patientid, objid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    info = {}
    try:
        resp_dict = {}
        obj = ObjectModel.get(ObjectModel.objid==objid)

        storage_url, auth_token = swiftclient.client.get_auth(
                                        conf.auth_url,
                                        conf.account_username,
                                      conf.password,
                                      auth_version=conf.auth_version)
        resp_dict['auth_token'] = auth_token
        resp_dict['storage_url'] = storage_url + '/' + \
                        conf.container + '/' + patientid + '/' + objid

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get obj failed'}

    else:
        return 1, resp_dict
Esempio n. 11
0
def get_objs(patientid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    logger.debug('in get_objs')
    resp_list = []
    try:
        patient = PatientModel.get(PatientModel.email==patientid)

        for obj in ObjectModel.select().where(ObjectModel.patient==patient):
            logger.debug('objid: %s, descrip: %s' % (obj.objid, obj.description))
            resp_dict = {}
            resp_dict['objid'] = obj.objid
            resp_dict['objname'] = obj.objname
            resp_dict['description'] = obj.description
            resp_dict['datetime'] = obj.datetime
            resp_list.append(resp_dict)
        logger.debug('objs:{}'.format(resp_list))

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get objs failed'}

    else:
        return 1, resp_list
Esempio n. 12
0
def get_comments(patientid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    logger.debug('in get_comments')
    resp_list = []
    try:
        patient = PatientModel.get(PatientModel.email==patientid)

        for comment in CommentModel.select().where(CommentModel.patient==patient):
            logger.debug('comment_id: %s, comment: %s' % (comment.comment_id, comment.comment))
            resp_dict = {}
            resp_dict['comment'] = comment.comment
            resp_dict['datetime'] = comment.datetime
            resp_dict['response_doctor'] = comment.response_doctor
            resp_list.append(resp_dict)
        logger.debug('comments:{}'.format(resp_list))

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get comments failed'}

    else:
        return 1, resp_list
Esempio n. 13
0
def get_doctors():
    """
    Get info of doctors in the system.

    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    logger.debug('in get_doctors')
    resp_list = []
    try:
        # patient = DoctorModel.get(DoctorModel.email==patientid)
        doctors = DoctorModel.select()
        print(doctors)
        for doc in doctors:
            print('doc')
            logger.debug('docid: %s' % (doc))
            resp_dict = {}
            resp_dict['doctorid'] = doc.email
            resp_dict['last_name'] = doc.last_name
            resp_dict['first_name'] = doc.first_name
            resp_list.append(resp_dict)
        logger.debug('doctors:{}'.format(resp_list))

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'get doctors failed'}

    else:
        return 1, resp_list
Esempio n. 14
0
def authentication(role, post_data):
    """
    Register a patient in the system. The post data is in json format.
    :param post_data: dict
    :returns: a status, a str( patient's info on success, err info on failure)
    """
    # print(post_data)
    auth_dict = {}
    try:
        logger.debug('in authentication')

        user = LoginModel.get(LoginModel.username==post_data['username'],
                                LoginModel.role==role)
    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, 'auth failed'
    else:
        logger.debug("user.password:{}, post_data['password']:{}".format(
            user.password, post_data['password']))
        if user.password==post_data['password']:
            try:
                # auth_dict['token'] = get_token(post_data['username'], role)
                token = get_token(post_data['username'], role)
            except Exception as ex:
                logger.error('Exception: ', ex)
                return 0, 'auth failed, get token failed'
            else:
                # auth_json = json.dumps(auth_dict)
                logger.debug(token)
                return 1, token
        else:
            return 0, 'auth failed, password not match'
Esempio n. 15
0
def edit_doctor(doctorid, post_data):
    """
    Edit a doctor in the system. The post data is a dict.

    :param post_data: dict
    :returns: a status, a str( doctor's info on success, err info on failure)
    """
    # print(post_data)
    try:
        logger.debug('in edit_doctor')
        DoctorModel.update_by_dict(doctorid, post_data)
        logger.debug('executed')
    # except peewee.IntegrityError:
    #     logger.warning('in doctor model create except')

        # # `username` is a unique column, so this username already exists,
        # # making it safe to call .get().
        # old_user = AccountModel.get(AccountModel.username == username)
        # logger.warning('user exists...')
        # resp_dict['info'] = 'user exists, did not create user:%s' % username
        # resp.status = falcon.HTTP_409
        # try:
        #     change_user = AccountModel.get(AccountModel.username==username,
        #                     AccountModel.password==password)
        # except:
        #     logger.debug('change user data failed...')
    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, 'edit_doctor failed, did not edit doctor'
    else:
        return 1, str(doctorid)
Esempio n. 16
0
def install_packages(packages):
    if ask_to_install(packages):
        logger.info(
            "Dependencies installed. Please launch Faraday Server again")
        sys.exit(0)
    else:
        logger.error("Dependencies not met")
        sys.exit(1)
Esempio n. 17
0
 def __process_new_workspace(self, ws_name):
     if ws_name in self.__workspaces:
         logger.info(u"Workspace {} already exists. Ignoring change.".format(ws_name))
     elif not server.couchdb.server_has_access_to(ws_name):
         logger.error(u"Unauthorized access to CouchDB for Workspace {}. Make sure faraday-server's"\
                      " configuration file has CouchDB admin's credentials set".format(ws_name))
     else:
         self.__create_and_import_workspace(ws_name)
Esempio n. 18
0
    def log_exception(self, *exc_info):
        if isinstance(exc_info[1], tornado.web.HTTPError):
            # Delegate HTTPError's to the base class
            # We don't want these through normal exception handling
            return super(ContextHandler, self).log_exception(*exc_info)

        msg = traceback.format_exception(*exc_info)
        logger.error('ERROR: %s' % "".join(msg))
Esempio n. 19
0
 def __process_new_workspace(self, ws_name):
     if ws_name in self.__workspaces:
         logger.info(
             u"Workspace {} already exists. Ignoring change.".format(
                 ws_name))
     elif not server.couchdb.server_has_access_to(ws_name):
         logger.error(u"Unauthorized access to CouchDB for Workspace {}. Make sure faraday-server's"\
                      " configuration file has CouchDB admin's credentials set".format(ws_name))
     else:
         self.__create_and_import_workspace(ws_name)
Esempio n. 20
0
    def get_config(self, option):
        query = self.database.session.query(server.models.DatabaseMetadata)
        query = query.filter(server.models.DatabaseMetadata.option == option)

        try:
            result = query.one_or_none()
        except MultipleResultsFound:
            msg = u'Database {} should not have the option {} defined multiple times'.format(self.__workspace, option)
            logger.error(msg)
            raise RuntimeError(msg)

        return result
Esempio n. 21
0
def import_workspaces():
    couchdb_server_conn, workspaces_list = _open_couchdb_conn()

    for workspace_name in workspaces_list:
        logger.info(u'Setting up workspace {}'.format(workspace_name))

        if not server.couchdb.server_has_access_to(workspace_name):
            logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
                         " configuration file has CouchDB admin's credentials set")
            sys.exit(1)

        import_workspace_into_database(workspace_name, couchdb_server_conn=couchdb_server_conn)
Esempio n. 22
0
def upload_obj(patientid, post_data):
    """
    Upload an obj in the system. The post data is a dict.

    :param post_data: dict
    :returns: a status, a str( obj's info on success, err info on failure)
    """
    # print(post_data)
    obj = ''
    try:
        logger.debug('in upload_obj')
        logger.debug('auth_url:{}, account_username:{}, password:{}'.format(
            conf.auth_url, conf.account_username, conf.password))

        resp_dict = {}
        storage_url, auth_token = swiftclient.client.get_auth(
                                        conf.auth_url,
                                        conf.account_username,
                                      conf.password,
                                      auth_version=conf.auth_version)
        resp_dict['auth_token'] = auth_token
        resp_dict['storage_url'] = storage_url + '/' + \
                        conf.container + '/' + patientid + '/' + \
                        patientid + '-' + post_data['objname'] + '-' + post_data['datetime']
        with database.atomic():
            obj = ObjectModel.create_by_dict(patientid, post_data)
            logger.debug(obj)
            logger.debug('in database.atomic')
    # except peewee.IntegrityError:
    #     logger.warning('in doctor model create except')

        # # `username` is a unique column, so this username already exists,
        # # making it safe to call .get().
        # old_user = AccountModel.get(AccountModel.username == username)
        # logger.warning('user exists...')
        # resp_dict['info'] = 'user exists, did not create user:%s' % username
        # resp.status = falcon.HTTP_409
        # try:
        #     change_user = AccountModel.get(AccountModel.username==username,
        #                     AccountModel.password==password)
        # except:
        #     logger.debug('change user data failed...')
    except Exception as ex:
        logger.error('Exception: ', ex)
        q = ObjectModel.delete().where(ObjectModel.objid==
            patientid + '-' + post_data['objname'] + '-' + post_data['datetime'])
        q.execute()
        return 0, {'errinfo':'create obj failed, did not create obj'}

    else:
        resp_dict['info'] = 'make PUT request to storage_url with auth_token as "x-storage-token" in headers'
        return 1, resp_dict
Esempio n. 23
0
def _create_and_import_db(db_conn, couchdb_conn):
    db_conn.create()
    db_conf = server.database.Configuration(db_conn)
    db_conf.set_last_seq(couchdb_conn.get_last_seq())

    try:
        _import_from_couchdb(db_conn, couchdb_conn)
    except Exception, e:
        import traceback
        logger.debug(traceback.format_exc())
        logger.error(u'Error while importing workspace {}: {!s}'.format(db_conn.db_name, e))
        db_conn.delete()
        raise e
Esempio n. 24
0
    def get_config(self, option):
        query = self.database.session.query(server.models.DatabaseMetadata)
        query = query.filter(server.models.DatabaseMetadata.option == option)

        try:
            result = query.one_or_none()
        except MultipleResultsFound:
            msg = u'Database {} should not have the option {} defined multiple times'.format(
                self.__workspace, option)
            logger.error(msg)
            raise RuntimeError(msg)

        return result
Esempio n. 25
0
    def __get_config(self, option):
        try:
            result = self.__db_conn.session\
                        .query(server.models.DatabaseMetadata)\
                        .filter(server.models.DatabaseMetadata.option == option)\
                        .one_or_none()

        except MultipleResultsFound:
            msg = u'Database {} should not have the option {} defined multiple times'.format(self.__db_conn.db_name, option)
            logger.error(msg)
            raise RuntimeError(msg)

        return result
Esempio n. 26
0
def make_appointment(post_data):
    """
    make_appointment in the system. The post data is in json format.

    :param post_data: dict
    :returns: a status, a str( appointment's url on success, err info on failure)

    with database.atomic():
                doctor = DoctorModel.create_by_dict(post_data)
                logger.debug(doctor)
                logger.debug('in database.atomic')
        except peewee.IntegrityError:
            logger.warning('in doctor model create except')

    1. check if patient and doctor exist in db
    2. check if the appointment exist in redis
    3. make appointment if 1 and 2 ok
    3.2 add the appointment to the doctor's that day's schedule
    4. return if appointment exists, with reason if fail

    """
    # print(post_data)
    try:
        logger.debug('in make_appointment')

    # check db when patient is ok
        rediscli.set_data(
            post_data['doctorid']+'/'+post_data['datetimeslot']+'/'+
                post_data['patientid'], post_data)
        schedule = rediscli.get_data(post_data['doctorid']+'/'+
            post_data['datetimeslot'][:8])
        if schedule:
            schedule = ast.literal_eval(schedule)
            schedule[post_data['datetimeslot'][8:]] = '1'
            rediscli.set_data(post_data['doctorid']+'/'+post_data['datetimeslot'][:8],
                json.dumps(schedule))
        else:
            schedule = {post_data['datetimeslot'][8:]:'1'}
            logger.debug('in make_appointment, schedule:{}'.format(json.dumps(schedule)))
            rediscli.set_data(post_data['doctorid']+'/'+post_data['datetimeslot'][:8],
                json.dumps(schedule))

    except Exception as ex:
        logger.error('Exception: ', ex)
        # q = DoctorModel.delete().where(DoctorModel.uid==doctor)
        # q.execute()
        return 0, 'make_appointment failed, did not make_appointment'

    else:
        return 1, str(post_data['doctorid']+'/'+post_data['datetimeslot']+'/'+
                        post_data['patientid'])
Esempio n. 27
0
def check_postgresql():
    with app.app_context():
        try:
            if not db.session.query(Workspace).count():
                logger.warn('No workspaces found. Remember to execute CouchDB importer')
        except sqlalchemy.exc.ArgumentError:
            logger.error(
                '\n\b{RED}Please check your PostgreSQL connection string in the file ~/.faraday/config/server.ini on your home directory.{WHITE} \n'.format(RED=Fore.RED, WHITE=Fore.WHITE)
            )
            sys.exit(1)
        except sqlalchemy.exc.OperationalError:
            logger.error(
                    '\n\n{RED}Could not connect to PostgreSQL.\n{WHITE}Please check: \n{YELLOW}  * if database is running \n  * configuration settings are correct. \n\n{WHITE}For first time installations execute{WHITE}: \n\n {GREEN} python manage.py initdb\n\n'.format(GREEN=Fore.GREEN, YELLOW=Fore.YELLOW, WHITE=Fore.WHITE, RED=Fore.RED))
            sys.exit(1)
Esempio n. 28
0
    def __get_config(self, option):
        try:
            result = self.__db_conn.session\
                        .query(server.models.DatabaseMetadata)\
                        .filter(server.models.DatabaseMetadata.option == option)\
                        .one_or_none()

        except MultipleResultsFound:
            msg = u'Database {} should not have the option {} defined multiple times'.format(
                self.__db_conn.db_name, option)
            logger.error(msg)
            raise RuntimeError(msg)

        return result
Esempio n. 29
0
def check_postgresql():
    with app.app_context():
        try:
            if not db.session.query(Workspace).count():
                logger.warn('No workspaces found. Remeber to execute couchdb importer')
        except sqlalchemy.exc.ArgumentError:
            logger.error(
                '\n\b{RED}Please check you postgresql connection string in server.ini at .faraday on your ohme directory.{WHITE} \n'.format(RED=Fore.RED, WHITE=Fore.WHITE)
            )
            sys.exit(1)
        except sqlalchemy.exc.OperationalError:
            logger.error(
                    '\n\n{RED}Could not connect to postgresql.\n{WHITE}Please check: \n{YELLOW}  * if database is running \n  * configuration settings are correct. \n\n{WHITE}For first time installations execute{WHITE}: \n\n {GREEN} python manage.py initdb\n\n'.format(GREEN=Fore.GREEN, YELLOW=Fore.YELLOW, WHITE=Fore.WHITE, RED=Fore.RED))
            sys.exit(1)
Esempio n. 30
0
def _open_couchdb_conn():
    try:
        couchdb_server_conn = server.couchdb.CouchDBServer()
        workspaces_list = couchdb_server_conn.list_workspaces()

    except RequestError:
        logger.error(u"CouchDB is not running at {}. Check faraday-server's"\
            " configuration and make sure CouchDB is running".format(
            server.couchdb.get_couchdb_url()))
        sys.exit(1)

    except Unauthorized:
        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
            " configuration file has CouchDB admin's credentials set")
        sys.exit(1)

    return couchdb_server_conn, workspaces_list
Esempio n. 31
0
def _open_couchdb_conn():
    try:
        couchdb_server_conn = server.couchdb.CouchDBServer()
        workspaces_list = couchdb_server_conn.list_workspaces()

    except RequestError:
        logger.error(u"CouchDB is not running at {}. Check faraday-server's"\
            " configuration and make sure CouchDB is running".format(
            server.couchdb.get_couchdb_url()))
        sys.exit(1)

    except Unauthorized:
        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
            " configuration file has CouchDB admin's credentials set")
        sys.exit(1)

    return couchdb_server_conn, workspaces_list
Esempio n. 32
0
def setup_workspaces():
    try:
        couchdb = server.couchdb.CouchDBServer()
        workspaces_list = couchdb.list_workspaces()
    except RequestError:
        logger.error(u"CouchDB is not running at {}. Check faraday-server's"\
            " configuration and make sure CouchDB is running".format(
            server.couchdb.get_couchdb_url()))
        sys.exit(1)
    except Unauthorized:
        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
            " configuration file has CouchDB admin's credentials set")
        sys.exit(1)

    for ws in workspaces_list:
        setup_workspace(ws)

    atexit.register(server.database.close_databases)
Esempio n. 33
0
def setup_workspaces():
    try:
        couchdb = server.couchdb.CouchDBServer()
        workspaces_list = couchdb.list_workspaces()
    except RequestError:
        logger.error(u"CouchDB is not running at {}. Check faraday-server's"\
            " configuration and make sure CouchDB is running".format(
            server.couchdb.get_couchdb_url()))
        sys.exit(1)
    except Unauthorized:
        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
            " configuration file has CouchDB admin's credentials set")
        sys.exit(1)

    for ws in workspaces_list:
        setup_workspace(ws)

    atexit.register(server.database.close_databases)
Esempio n. 34
0
    def run(self):
        def signal_handler(*args):
            logger.info('Received SIGTERM, shutting down.')
            logger.info("Stopping threads, please wait...")
            # teardown()
            self.raw_report_processor.stop()

        site = twisted.web.server.Site(self.__root_resource)
        if self.__ssl_enabled:
            ssl_context = self.__load_ssl_certs()
            self.__listen_func = functools.partial(reactor.listenSSL,
                                                   contextFactory=ssl_context)
        else:
            self.__listen_func = reactor.listenTCP

        try:
            self.install_signal()
            # start threads and processes
            self.raw_report_processor = RawReportProcessor()
            self.raw_report_processor.start()
            # web and static content
            self.__listen_func(self.__listen_port,
                               site,
                               interface=self.__bind_address)
            # websockets
            try:
                listenWS(self.__build_websockets_resource(),
                         interface=self.__bind_address)
            except:
                logger.warn(
                    'Could not start websockets, address already open. This is ok is you wan to run multiple instances.'
                )
            logger.info('Faraday Server is ready')
            reactor.addSystemEventTrigger('before', 'shutdown', signal_handler)
            reactor.run()

        except error.CannotListenError as e:
            logger.error(str(e))
            sys.exit(1)
        except Exception as e:
            logger.error(
                'Something went wrong when trying to setup the Web UI')
            logger.exception(e)
            sys.exit(1)
Esempio n. 35
0
    def run(self):
        for change_doc in self.__stream:
            try:
                self.__changes_callback(self.CHANGE_CLS(change_doc))
            except Exception, e:
                import traceback
                logger.debug(traceback.format_exc())
                logger.warning(u"Error while processing change. Ignoring. Offending change: {}".format(change_doc))

                if change_doc.get('error', None):
                    if change_doc.get('error') == 'unauthorized':
                        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
                            " configuration file has CouchDB admin's credentials set")
                        thread.interrupt_main()

                    # TODO: A proper fix is needed here
                    elif change_doc.get('reason') == 'no_db_file':
                        self.__stream.stop()
                        break
Esempio n. 36
0
def upload_comment(patientid, doctorid, post_data):
    """
    Upload an comment in the system. The post data is a dict.

    :param post_data: dict
    :returns: a status, a str( comment's info on success, err info on failure)
    """
    # print(post_data)
    comment = ''
    try:
        logger.debug('in upload_comment')

        resp_dict = {}
        with database.atomic():
            comment = CommentModel.create_by_dict(patientid, doctorid, post_data)
            logger.debug('comment:{}'.format(comment))
            logger.debug('in database.atomic')
    # except peewee.IntegrityError:
    #     logger.warning('in doctor model create except')

        # # `username` is a unique column, so this username already exists,
        # # making it safe to call .get().
        # old_user = AccountModel.get(AccountModel.username == username)
        # logger.warning('user exists...')
        # resp_dict['info'] = 'user exists, did not create user:%s' % username
        # resp.status = falcon.HTTP_409
        # try:
        #     change_user = AccountModel.get(AccountModel.username==username,
        #                     AccountModel.password==password)
        # except:
        #     logger.debug('change user data failed...')
    except Exception as ex:
        logger.error('Exception: ', ex)
        q = CommentModel.delete().where(CommentModel.drug_id==
            patientid + '-' + doctorid + '-' + post_data['datetime'])
        q.execute()
        return 0, {'errinfo':'create comment failed, did not create comment'}

    else:
        # resp_dict['info'] = 'make PUT request to storage_url with auth_token as "x-storage-token" in headers'
        resp_dict['comment_id'] = comment.comment_id
        return 1, resp_dict
Esempio n. 37
0
def restart_server(args_port):
    devnull = open('/dev/null', 'w')

    if args_port:
        ports = [args_port]
    else:
        ports = daemonize.get_ports_running()

    if not ports:
        logger.error('Faraday Server is not running')
        sys.exit(1)

    for port in ports:
        stop_server(port)
        params = ['/usr/bin/env', 'python2.7',\
            os.path.join(server.config.FARADAY_BASE, __file__), '--no-setup', '--port', str(port)]

        logger.info('Restarting Faraday Server...')
        subprocess.Popen(params, stdout=devnull, stderr=devnull)
        logger.info('Faraday Server is running as a daemon in port {}'.format(port))
Esempio n. 38
0
def restart_server(args_port):
    devnull = open('/dev/null', 'w')

    if args_port:
        ports = [args_port]
    else:
        ports = daemonize.get_ports_running()

    if not ports:
        logger.error('Faraday Server is not running')
        sys.exit(1)

    for port in ports:
        stop_server(port)
        params = ['/usr/bin/env', 'python2.7',\
            os.path.join(server.config.FARADAY_BASE, __file__), '--no-setup', '--port', str(port)]

        logger.info('Restarting Faraday Server...')
        subprocess.Popen(params, stdout=devnull, stderr=devnull)
        logger.info('Faraday Server is running as a daemon in port {}'.format(port))
Esempio n. 39
0
    def run(self):
        def signal_handler(*args):
            logger.info("Stopping threads, please wait...")
            # teardown()
            self.raw_report_processor.stop()
            reactor.stop()

        site = twisted.web.server.Site(self.__root_resource)
        if self.__ssl_enabled:
            ssl_context = self.__load_ssl_certs()
            self.__listen_func = functools.partial(
                reactor.listenSSL,
                contextFactory=ssl_context)
        else:
            self.__listen_func = reactor.listenTCP

        try:
            self.install_signal()
            # start threads and processes
            self.raw_report_processor = RawReportProcessor()
            self.raw_report_processor.start()
            # web and static content
            self.__listen_func(
                self.__listen_port, site,
                interface=self.__bind_address)
            # websockets
            try:
                listenWS(self.__build_websockets_resource(), interface=self.__bind_address)
            except :
                logger.warn('Could not start websockets, address already open. This is ok is you wan to run multiple instances.')
            logger.info('Faraday Server is ready')
            reactor.addSystemEventTrigger('before', 'shutdown', signal_handler)
            reactor.run()

        except error.CannotListenError as e:
            logger.error(str(e))
            sys.exit(1)
        except Exception as e:
            logger.error('Something went wrong when trying to setup the Web UI')
            logger.exception(e)
            sys.exit(1)
Esempio n. 40
0
def update_discharge(patientid, doctorid, indate, post_data):
    """
    Upload an discharge in the system. The post data is a dict.

    :param post_data: dict
    :returns: a status, a str( discharge's info on success, err info on failure)
    """
    # print(post_data)
    discharge = ''
    try:
        logger.debug('in update_discharge')

        resp_dict = {}

        DischargeModel.update_by_dict(patientid, doctorid,
                indate, post_data)
    # except peewee.IntegrityError:
    #     logger.warning('in doctor model create except')

        # # `username` is a unique column, so this username already exists,
        # # making it safe to call .get().
        # old_user = AccountModel.get(AccountModel.username == username)
        # logger.warning('user exists...')
        # resp_dict['info'] = 'user exists, did not create user:%s' % username
        # resp.status = falcon.HTTP_409
        # try:
        #     change_user = AccountModel.get(AccountModel.username==username,
        #                     AccountModel.password==password)
        # except:
        #     logger.debug('change user data failed...')
    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'update discharge failed, did not create discharge'}

    else:
        # resp_dict['info'] = 'make PUT request to storage_url with auth_token as "x-storage-token" in headers'
        resp_dict['discharge_id'] = patientid + '-' + doctorid + '-' + \
            indate
        return 1, resp_dict
Esempio n. 41
0
    def create_database(self):
        logger.info(u'Creating database for workspace {}'.format(self.__workspace))
        self.database.create()
        self.database.open_session()

        try:
            # Add metadata information to database
            self.set_last_seq(self.couchdb.get_last_seq())
            self.set_migration_status(False)
            self.set_schema_version()

            self.import_from_couchdb()

            # Reaching this far without errors means a successful migration
            self.set_migration_status(True)

        except Exception, e:
            import traceback
            logger.debug(traceback.format_exc())
            logger.error(u'Error while importing workspace {}: {!s}'.format(self.__workspace, e))
            self.delete()
            raise e
Esempio n. 42
0
def delete_obj(patientid, objid):
    """
    Get info of a doctor in the system.

    :param doctorid: doctor's uid
    :returns: a status, a str ( doctor's info on success, err info on failure)
    """
    # print(doctorid)
    info = {}
    try:
        resp_dict = {}

        conn = swiftclient.client.Connection(conf.auth_url,
                        conf.account_username,
                        conf.password,
                        auth_version=conf.auth_version)
        meta, objects = conn.get_container(conf.container,
            prefix=patientid + '/' + objid)
        logger.debug('meta: %s,  \n objects: %s' % (meta, objects))
        if objects:
            for obj in objects:
                conn.delete_object(conf.container, obj['name'])
                resp_dict['description_'+obj['name']] = \
                    '{} have been deleted'.format(obj['name'])
        else:
            resp_dict['description'] = 'There is no file to be deleted'
        logger.debug('resp_dict:%s' % resp_dict)

        q = ObjectModel.delete().where(ObjectModel.objid==objid)
        q.execute()
        resp_dict[objid] = 'deleted from db'
        logger.debug('resp_dict:%s' % resp_dict)

    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, {'errinfo':'delete obj failed, did not delete obj'}

    else:
        return 1, resp_dict
Esempio n. 43
0
def get_appointment(appointment_url):
    """
    Get info of an appointment in the system.

    :param appointment_url: appointment's url
    :returns: a status, a str ( appointment's info on success, err info on failure)
    """
    # print(appointment_url)
    info = {}
    try:
        logger.debug('in get_appointment')
        # check redis
        appointment = str(rediscli.get_data(appointment_url))
        logger.debug(appointment)
    # except UserNotExistException:
    #     logger.debug('in UserNotExistException')
    #     return 0, 'get doctor failed, the required Doctor Did Not Exist'
    except Exception as ex:
        logger.error('Exception: ', ex)
        return 0, 'get appointment failed'
    else:
        # appointment_json = json.dumps({'illness':appointment})
        return 1, appointment
Esempio n. 44
0
    def create_database(self):
        logger.info(u'Creating database for workspace {}'.format(
            self.__workspace))
        self.database.create()
        self.database.open_session()

        try:
            # Add metadata information to database
            self.set_last_seq(self.couchdb.get_last_seq())
            self.set_migration_status(False)
            self.set_schema_version()

            self.import_from_couchdb()

            # Reaching this far without errors means a successful migration
            self.set_migration_status(True)

        except Exception, e:
            import traceback
            logger.debug(traceback.format_exc())
            logger.error(u'Error while importing workspace {}: {!s}'.format(
                self.__workspace, e))
            self.delete()
            raise e
Esempio n. 45
0
def main():
    os.chdir(FARADAY_BASE)
    check_alembic_version()
    check_postgresql()
    parser = argparse.ArgumentParser()
    parser.add_argument('--ssl', action='store_true', help='enable HTTPS')
    parser.add_argument('--debug',
                        action='store_true',
                        help='run Faraday Server in debug mode')
    parser.add_argument('--start',
                        action='store_true',
                        help='run Faraday Server in background')
    parser.add_argument('--stop',
                        action='store_true',
                        help='stop Faraday Server')
    parser.add_argument('--restart',
                        action='store_true',
                        help='Restart Faraday Server')
    parser.add_argument('--nodeps',
                        action='store_true',
                        help='Skip dependency check')
    parser.add_argument('--no-setup',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--port',
                        help='Overides server.ini port configuration')
    parser.add_argument(
        '--websocket_port',
        help='Overides server.ini websocket port configuration')
    parser.add_argument('--bind_address',
                        help='Overides server.ini bind_address configuration')

    f = open(server.config.VERSION_FILE)
    f_version = f.read().strip()

    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='Faraday v{version}'.format(version=f_version))

    args = parser.parse_args()
    setUpLogger(args.debug)

    if args.debug:
        server.utils.logger.set_logging_level(server.config.DEBUG)

    if args.restart:
        restart_server(args.port)
        sys.exit()

    if args.stop:
        if args.port:
            sys.exit(0 if stop_server(args.port) else 1)
        else:
            ports = daemonize.get_ports_running()
            if not ports:
                logger.info('Faraday Server is not running')
            exit_code = 0
            for port in ports:
                exit_code += 0 if stop_server(port) else 1
            sys.exit(exit_code)

    else:
        if not args.port:
            args.port = '5985'

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(
        (args.bind_address or server.config.faraday_server.bind_address,
         int(args.port or server.config.faraday_server.port)))

    if is_server_running(args.port) and result == 0:
        sys.exit(1)

    if result == 0:
        logger.error(
            "Faraday Server port in use. Check your processes and run the server again..."
        )
        sys.exit(1)

    # Overwrites config option if SSL is set by argument
    if args.ssl:
        server.config.ssl.enabled = 'true'

    if not args.no_setup:
        setup_environment(not args.nodeps)

    if args.port:
        server.config.faraday_server.port = args.port

    if args.bind_address:
        server.config.faraday_server.bind_address = args.bind_address

    if args.websocket_port:
        server.config.faraday_server.websocket_port = args.websocket_port

    if args.start:
        # Starts a new process on background with --ignore-setup
        # and without --start nor --stop
        devnull = open('/dev/null', 'w')
        params = [
            '/usr/bin/env', 'python2.7',
            os.path.join(server.config.FARADAY_BASE, __file__), '--no-setup'
        ]
        arg_dict = vars(args)
        for arg in arg_dict:
            if arg not in ["start", "stop"] and arg_dict[arg]:
                params.append('--' + arg)
                if arg_dict[arg] != True:
                    params.append(arg_dict[arg])
        logger.info('Faraday Server is running as a daemon')
        subprocess.Popen(params, stdout=devnull, stderr=devnull)

    elif not args.start:
        run_server(args)
Esempio n. 46
0
def check_admin_access_to(ws_name):
    if not server.couchdb.has_permissions_for(
            ws_name, credentials=server.couchdb.get_auth_info()):
        logger.error(u"Unauthorized access to CouchDB. Make sure faraday-server's"\
            " configuration file has CouchDB admin's credentials set")
        sys.exit(1)