Esempio n. 1
0
def consult_patient():
    qs = request.query_string
    query_info = utils.parse_query_string(qs)
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(session['email'])

    email = session['email']
    email_q = utils.quote(session['email'])

    if request.method == 'GET':
        return render_template('consultation.html',
                               qs=qs,
                               provider_email=email,
                               provider_email_quote=email_q,
                               patient=query_info,
                               consult_list=pvd.query_consult(
                                   query_info['patient']))
    else:
        note = request.form["note"]
        mp = request.form["medication-prescribed"]
        pvd.consult(query_info['patient'], query_info['center'],
                    query_info['time'], note, mp)
        return render_template('consultation.html',
                               qs=qs,
                               provider_email=email,
                               provider_email_quote=email_q,
                               patient=query_info,
                               consult_list=pvd.query_consult(
                                   query_info['patient']))
Esempio n. 2
0
def serve_client(method, global_state, socket=None):
    """Runs one connection to TTS API Provider
    
    Arguments:
    method -- currently only 'socket'
    socket -- if method = 'socket', the client socket of the connection"""

    if method == 'socket':
        assert socket != None
        p = provider.Provider(logger=log,
                              configuration=conf,
                              audio=audio,
                              global_state=global_state)
        connection = ttsapi.server.TCPConnection(provider=p,
                                                 method='socket',
                                                 client_socket=socket,
                                                 logger=log)
        p.set_connection(connection)
        log.debug("Connection initialized, listening")
    else:
        raise NotImplementedError

    while True:
        try:
            connection.process_input()
        except ttsapi.server.ClientGone:
            # TODO: Better client identification in log message
            log.debug("Client on socket " + str(socket) + " gone")
            break
Esempio n. 3
0
def construct_master_client_strategy(main_db, comservice, file_server):
    metadata_requester_to_use = metadata_requester.MetadataRequester(main_db)
    file_requester_to_use = build_file_requester(main_db, comservice)
    provider_to_use = provider.Provider(main_db, file_server)

    return strategies.late_requester.LateRequester(metadata_requester_to_use, file_requester_to_use,
                                                   provider_to_use, main_db)
Esempio n. 4
0
def construct_master_server_strategy(main_db, comservice, file_server):
    metadata_requester_to_use = metadata_requester.MetadataRequester(main_db)
    file_requester_to_use = None
    if pydb.config.request_files_on_incoming_connection():
        file_requester_to_use = build_file_requester(main_db, comservice)
    provider_to_use = provider.Provider(main_db, file_server)
    return strategies.early_requester.EarlyRequester(metadata_requester_to_use, file_requester_to_use,
                                                     provider_to_use, main_db)
Esempio n. 5
0
    def __init__(self, server_address, token, RequestHandler):
        self.provider = provider.Provider()
        self.auth_token = token
        self.gamestatemanager = gamestate.GameStateManager()

        super(GSIServer, self).__init__(server_address, RequestHandler)

        self.setup_log_file()
        self.payload_parser = payloadparser.PayloadParser()
Esempio n. 6
0
def extract_provider(record):
    thedoc = provider.Provider(
        npi="",
        first_name=record['Physician_Profile_First_Name'],
        last_name=record['Physician_Profile_Last_Name'],
        middle_initial=record['Physician_Profile_Middle_Name'],
        zip_first_5=record['Physician_Profile_Zip_Code'][0:5],
        zip_ext=record['Physician_Profile_Zip_Code'][5:9],
        op_profile_id=record['Physician_Profile_ID'])
    return thedoc
Esempio n. 7
0
def index():
    if not check_login():
        return redirect(url_for('login'))
    if session['role'] != 'patient':
        return redirect('/provider_profile/' + utils.quote(session['email']))
    pt = patient.Patient(session['email'])
    center_v = ""
    provider_v = ""
    service_v = ""

    if request.method == "GET":
        results = pt.search(center=center_v,
                            provider=provider_v,
                            service=service_v)
        for res in results:
            pvd = provider.Provider(res['provider_email'])
            ct = center.Center(res['health_centre_name'])
            res['center_rate'] = ct.get_rate()
            res['provider_rate'] = pvd.get_rate()
            res['health_centre_name_quote'] = utils.quote(
                res['health_centre_name'])
            res['provider_email_quote'] = utils.quote(res['provider_email'])
        return render_template('index.html',
                               patient_email=session['email'],
                               result_list=results)

    center_v = request.form["center"]
    provider_v = request.form["provider"]
    service_v = request.form["service"]
    results = pt.search(center=center_v,
                        provider=provider_v,
                        service=service_v)
    for res in results:
        pvd = provider.Provider(res['provider_email'])
        ct = center.Center(res['health_centre_name'])
        res['center_rate'] = ct.get_rate()
        res['provider_rate'] = pvd.get_rate()
        res['health_centre_name_quote'] = utils.quote(
            res['health_centre_name'])
        res['provider_email_quote'] = utils.quote(res['provider_email'])
    return render_template('index.html',
                           patient_email=session['email'],
                           result_list=results)
def extract_provider(record):
    #zip code (first 5) needs to come from "Physician Profile" record
    thedoc = provider.Provider(
        first_name = record['Physician_First_Name'],
        last_name = record['Physician_Last_Name'],
        middle_initial=record['Physician_Middle_Name'],
        zip_first_5 = record['Recipient_Zip_Code'][0:5],
        zip_ext = record['Recipient_Zip_Code'][5:9], #probably blank
        op_profile_id = record['Physician_Profile_ID']
    )
Esempio n. 9
0
def evaluate():
    with tf.device('/gpu:'+str(GPU_INDEX)):
        if '_pn' in MODEL_FILE:
            data_input = provider.Provider()
            imgs_pl, pts_pl, labels_pl = MODEL.placeholder_inputs(BATCH_SIZE)
            imgs_pl = [imgs_pl, pts_pl]
        elif '_io' in MODEL_FILE:
            data_input = provider.Provider()
            imgs_pl, labels_pl = MODEL.placeholder_inputs(BATCH_SIZE)
        else:
            raise NotImplementedError

        is_training_pl = tf.placeholder(tf.bool, shape=())
        print(is_training_pl)

        # Get model and loss
        pred = MODEL.get_model(imgs_pl, is_training_pl)

        loss = MODEL.get_loss(pred, labels_pl)

        # Add ops to save and restore all the variables.
        saver = tf.train.Saver()

    # Create a session
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    config.allow_soft_placement = True
    config.log_device_placement = True
    sess = tf.Session(config=config)

    # Restore variables from disk.
    saver.restore(sess, MODEL_PATH)
    log_string("Model restored.")

    ops = {'imgs_pl': imgs_pl,
            'labels_pl': labels_pl,
            'is_training_pl': is_training_pl,
            'pred': pred,
            'loss': loss}

    eval_one_epoch(sess, ops, data_input)
Esempio n. 10
0
def provider_profile(email):
    email = utils.unquote(email)
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(email)
    info = pvd.info()
    ptype = info['provider_type']
    rate = pvd.get_rate()
    centres = pvd.list_centers()

    for item in centres:
        item['qs'] = utils.gen_query_string({
            'center':
            item['health_centre_name'],
            'provider':
            item['provider_email']
        })
        item['health_centre_name_quote'] = utils.quote(
            item['health_centre_name'])
    if session['role'] == 'patient':
        if request.method == 'GET':
            return render_template(
                'provider_profile.html',
                provider_email_quote=utils.quote(item['provider_email']),
                success=False,
                patient_email=session['email'],
                patient_email_quote=utils.quote(session['email']),
                provider_email=email,
                provider_type=ptype,
                provider_rate=rate,
                center_list=centres,
                patient_mode=True)
        else:
            new_rate = request.form["rate"]
            flag = pvd.set_rate(session['email'], new_rate)
            return render_template('provider_profile.html',
                                   provider_email_quote=utils.quote(
                                       item['provider_email']),
                                   success=flag,
                                   provider_email=email,
                                   provider_type=ptype,
                                   provider_rate=new_rate,
                                   center_list=centres,
                                   patient_mode=True)
    elif session['email'] == email:
        return render_template('provider_profile.html',
                               provider_email=email,
                               provider_type=ptype,
                               provider_rate=rate,
                               center_list=centres,
                               patient_mode=False)
    else:
        abort(401)
Esempio n. 11
0
def extract_provider(record):
    thedoc = provider.Provider(
        npi=record['NPI'],
        first_name=record['Provider First Name'],
        last_name=record['Provider Last Name (Legal Name)'],
        middle_initial=record['Provider Middle Name'],
        zip_first_5=record[
            'Provider Business Practice Location Address Postal Code']
        [0:5],  #one other option for zip
        zip_ext=record[
            'Provider Business Practice Location Address Postal Code'][5:9],
        op_profile_id="")
    return thedoc
Esempio n. 12
0
def test_point_provider():
    import sys
    sys.path.append('../')
    import provider
    import functools
    import time
    train_list, test_list = prepare_input_list('../data/S3DIS/point/fpfh/', 256)
    fetch_data_with_batch = functools.partial(fetch_data, batch_size=256)
    train_provider = provider.Provider(train_list, 1, fetch_data_with_batch, 'train', 4, fetch_batch, max_worker_num=1)

    print train_provider.batch_num

    begin = time.time()
    for feats, labels in train_provider:
        print feats.shape, labels.shape
        print time.time() - begin
        begin = time.time()
Esempio n. 13
0
    def __init__(self,
                 configfile='config.ini',
                 logfile='dopq.log',
                 debug=False):

        # init logging
        self.logger = log.init_log(logfile)

        # get settings from config
        if not os.path.isfile(configfile):
            self.write_default_config(configfile)

        # init member variables
        self.starttime = None
        self.client = docker.from_env()
        self.debug = debug
        self.configfile = configfile
        self.logfile = logfile
        self.config = self.parse_config(configfile)
        self.paths = self.config['paths']
        self.history_file = 'history.dill'
        self.container_list_file = 'container_list.dill'
        self.running_containers_file = 'running_containers.dill'
        self.container_list = []
        self.running_containers = []
        self.history = []
        self.mapping = self.restore('all')

        # init helper processes and classes
        self.queue = mp.Queue()
        self.gpu_handler = gh.GPUHandler()
        self.provider = provider.Provider(self.config, self.queue)

        # build all non-existent directories, except the network container share
        keys = list(self.paths.keys())
        for key in keys:
            if key != 'network_containers':
                if not os.path.isdir(self.paths[key]):
                    os.makedirs(self.paths[key])

        # initialize process variable and termination flag
        super(DopQ, self).__init__()

        # initialize interface as a thread (so that members of the queue are accessible by the interface)
        self.thread = threading.Thread(target=self.run_queue)
Esempio n. 14
0
def history():
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(session['email'])
    info = pvd.info()
    email = session['email']
    email_q = utils.quote(session['email'])

    history_list = pvd.book_history()
    for item in history_list:
        item['center_name_quote'] = utils.quote(item['center_name'])
        item['patient_email_quote'] = utils.quote(item['patient_email'])
        item['qs'] = utils.gen_query_string({
            'provider': session['email'],
            'center': item['center_name'],
            'patient': item['patient_email'],
            'time': item['service_time'],
            'comment': item['comment']
        })
    return render_template('history.html',
                           provider_email=email,
                           provider_email_quote=email_q,
                           provider_type=info['provider_type'],
                           history_list=history_list)
Esempio n. 15
0
def login():
    if request.method == "GET":
        return render_template('login.html', succeed=True)
    else:
        email = request.form["email"]
        password = request.form["password"]
        mode = request.form["role"]
        if mode == "provider":
            pvd = provider.Provider(email)
            if pvd.authenticater(password):
                session['email'] = email
                session['role'] = mode
                return redirect('/provider_profile/' +
                                utils.quote(session['email']))
            else:
                return render_template('login.html', succeed=False)
        else:
            pt = patient.Patient(email)
            if pt.authenticater(password):
                session['email'] = email
                session['role'] = mode
                return redirect(url_for('index'))
            else:
                return render_template('login.html', succeed=False)
Esempio n. 16
0
def train():
    with tf.Graph().as_default():
        with tf.device('/gpu:' + str(GPU_INDEX)):
            if '_pn' in MODEL_FILE:
                data_input = provider.Provider()
                imgs_pl, pts_pl, labels_pl = MODEL.placeholder_inputs(
                    BATCH_SIZE)
                imgs_pl = [imgs_pl, pts_pl]
            elif '_io' in MODEL_FILE:
                data_input = provider.Provider()
                imgs_pl, labels_pl = MODEL.placeholder_inputs(BATCH_SIZE)
            else:
                raise NotImplementedError

            is_training_pl = tf.placeholder(tf.bool, shape=())
            print(is_training_pl)

            # Note the global_step=batch parameter to minimize.
            # That tells the optimizer to helpfully increment the 'batch'
            # parameter for you every time it trains.
            batch = tf.Variable(0)
            bn_decay = get_bn_decay(batch)
            tf.summary.scalar('bn_decay', bn_decay)

            # Get model and loss
            pred = MODEL.get_model(imgs_pl, is_training_pl, bn_decay=bn_decay)

            loss = MODEL.get_loss(pred, labels_pl)
            MODEL.summary_scalar(pred, labels_pl)

            # Get training operator
            learning_rate = get_learning_rate(batch)
            tf.summary.scalar('learning_rate', learning_rate)
            if OPTIMIZER == 'momentum':
                optimizer = tf.train.MomentumOptimizer(learning_rate,
                                                       momentum=MOMENTUM)
            elif OPTIMIZER == 'adam':
                optimizer = tf.train.AdamOptimizer(learning_rate)
            train_op = optimizer.minimize(loss, global_step=batch)
            # Add ops to save and restore all the variables.
            saver = tf.train.Saver()

        # Create a session
        config = tf.ConfigProto()
        config.gpu_options.allow_growth = True
        config.allow_soft_placement = True
        config.log_device_placement = False
        sess = tf.Session(config=config)

        # Add summary writers
        # merged = tf.merge_all_summaries()
        merged = tf.summary.merge_all()
        train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'),
                                             sess.graph)
        test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'))

        # Init variables
        init = tf.global_variables_initializer()
        sess.run(init, {is_training_pl: True})

        ops = {
            'imgs_pl': imgs_pl,
            'labels_pl': labels_pl,
            'is_training_pl': is_training_pl,
            'pred': pred,
            'loss': loss,
            'train_op': train_op,
            'merged': merged,
            'step': batch
        }

        eval_acc_max = 0
        for epoch in range(MAX_EPOCH):
            log_string('**** EPOCH %03d ****' % (epoch))
            sys.stdout.flush()

            train_one_epoch(sess, ops, train_writer, data_input)
            eval_acc = eval_one_epoch(sess, ops, test_writer, data_input)
            if eval_acc > eval_acc_max:
                eval_acc_max = eval_acc
                save_path = saver.save(
                    sess, os.path.join(LOG_DIR, "model_best.ckpt"))
                log_string("Model saved in file: %s" % save_path)

            # Save the variables to disk.
            if epoch % 10 == 0:
                save_path = saver.save(sess,
                                       os.path.join(LOG_DIR, "model.ckpt"))
                log_string("Model saved in file: %s" % save_path)
Esempio n. 17
0
import provider
import consumer


class ProviderSubclassOnHeap(provider.Provider):
    pass


print consumer.sum_baseline(provider.Provider(), 4)
print consumer.sum_baseline(object(), 4)
print consumer.sum_baseline(ProviderSubclassOnHeap(), 4)
Esempio n. 18
0
def main():
    CONF_FILE='setup.conf'
    if os.geteuid() != 0:
        sys.exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")

    if not os.path.exists("/var/log/apporbit"):
       os.makedirs("/var/log/apporbit")

    logging.basicConfig(filename='/var/log/apporbit/apporbit-server.log', level=logging.DEBUG,
                         format='[ %(asctime)s  %(levelname)s ] %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')

    # arguments parser
    parser = argparse.ArgumentParser(description='apporbit-server to manage apporbit server')
    parser.add_argument("-d","--deploychef",action='store_true', help='Deploy chef enable flag')
    parser.add_argument("-c","--consul", action='store_true', help='Deploy consul')
    parser.add_argument("--setuponly", action='store_true', help='Setup appOrbit Server')
    parser.add_argument("--start", action='store_true', help='Start appOrbit Server')
    parser.add_argument("--stop", action='store_true', help='Stop appOrbit Server')
    parser.add_argument("--kill", action='store_true', help='Forcefully stop appOrbit Server')
    parser.add_argument("--restart", action='store_true', help='Restart appOrbit Server')
    parser.add_argument("--pullimages", action='store_true', help='Pull new versions of appOrbit Server images')
    parser.add_argument("--removedata", action='store_true', help='Remove Data in appOrbit Server')
    parser.add_argument("--removeconfig", action='store_true', help='Remove Config in appOrbit Server')
    parser.add_argument("--removeall", action='store_true', help='Remove Data, Config and Keys in appOrbit Server')
    parser.add_argument("--upgrade", action='store_true', help='Upgrade Setup')
    parser.add_argument("--buildpackages", action='store_true', help='Fetch resources for offline installation')
    parser.add_argument("--setupprovider", action='store_true', help='Set up provider machine for offline installation')
    parser.add_argument("--deployoffline", action='store_true', help='Deploy apporbit on an offline host')
    parser.add_argument("--offline", action='store_true', help='Install apporbit host offline (guided)')
    parser.add_argument("--status", action='store_true', help='Show status of appOrbit Server')
    parser.add_argument("list",  nargs='*', help='List of components')
    args = parser.parse_args()
    if args.deploychef:
        chef_dep_obj = action.DeployChef()
        chef_dep_obj.deploy_chef()
        print "Chef Deployed"
        sys.exit(0)
    if args.consul:
        consul_obj = action.DeployConsul()
        consul_obj.deploy_consul()
        print "Consul Deployed"
        sys.exit(0)

    config_obj = config.Config()
    userinteract_obj = userinteract.UserInteract()
    utility_obj = utility.Utility()
    action_obj = action.Action()

    setupDone = False
    try:
      if (os.path.isfile(config_obj.apporbit_serverconf) 
           and os.path.isfile(config_obj.composeFile)
           and utility_obj.isPreviousInstallSuccess()
           ):
          setupRequired = False
          logging.info("Setup not required. Loading existing setup config")
          config_obj.loadConfig(config_obj.apporbit_serverconf)
      else:
          # This is the only visual clue that the product is not installed.
          print ("appOrbit server is not installed.")
          setupRequired = True
          if os.path.isfile(CONF_FILE):
              logging.info('Using ' + CONF_FILE + ' file for deployment')
              config_obj.loadConfig(CONF_FILE)
    except:
          #setupRequired = True
          raise
    skipSetup = False
    if args.upgrade and not setupRequired:
        logging.info("Requesting to upgrade configuration")
        if action_obj.showStatus(config_obj,show=False):
            logging.info("Stopping Server")
            action_obj.removeCompose(config_obj, show=True)
            logging.info("Stopped Server")
        logging.warning("Backing  appOrbit server setup configuration.")
        action_obj.backupSetupConfig(config_obj)
        action_obj.removeSetupConfig(config_obj)
        config_obj.upgrade = True
        setupRequired = True
    elif not args.setuponly and (args.stop or args.kill or args.status or args.removedata or args.removeconfig or args.removeall or args.buildpackages or args.setupprovider or args.deployoffline or args.offline):
       skipSetup = True

    if  args.setuponly or (setupRequired and not skipSetup):
        print ("apporbit-server will install/upgrade the appOrbit server in this machine")
        print ("Installation log will be in : /var/log/apporbit/apporbit-server.log")
        logging.info("Starting appOrbit Installation/upgrade")

        # Will check all the System Requirements
        # Fail and exit if Not fixable Requirements like
        # Hardware Requirements are not satisfied
        # Fail but not exit with Fixable Reqruiements
        utility_obj.loadTempFile(config_obj)
        if not config_obj.systemreqs:
            print "Verifying system information."
            with utility.DotProgress("Verify"):
                utility_obj.progressBar(0)
                utility_obj.preSysRequirements(config_obj)
                utility_obj.verifySystemInfo()
                logging.info("System info verification is completed!")

                # Will Fix all the Fixable Software Requriements
                # Will Fix Docker startup and
                # Seliux settings.
                if not utility_obj.fixSysRequirements():
                    logging.error("Unable to auto fix System Requirements.")
                    print "Unable to auto fix system Requirements. Check Log for details and fix it"
                    sys.exit(1)
                utility_obj.progressBar(20)
            logging.info("fix System Requirements is completed!")
            #config_obj.systemreqs = True
            print "   -- [Done]"
            utility_obj.createTempFile(config_obj)


        # If CONF_FILE file is available it would have already been loaded
        # else will proceed with the Customer Deployment.
        # In Regular customer Deployment case we will not provide any config file.

        if not os.path.isfile(CONF_FILE):
            logging.info("Starting to get user configuration.")
            # Get User Configuration for Customer Deployment
            # and write to a config file apporbit_deploy.conf
            userinteract_obj.getUserConfigInfo(config_obj, utility_obj)
            utility_obj.createTempFile(config_obj)

        # Validate that the apporbit_domain is not a hostname
        if config_obj.apporbit_domain and not utility_obj.validateDomain(config_obj.apporbit_domain):
            print "ERROR: Apporbit Domain cannot be ip or hostname"
            sys.exit(1)

        # Validate that the apporbit_host chosen during configuration belongs to the current host machine.
        if not utility_obj.validateHostIP(config_obj.apporbit_host):
            print "WARNING: Given Name/IP is not accessible publicly or on private network"
            if os.path.isfile(CONF_FILE):
                print "apporbit-server will proceed in 5 seconds with that Name/IP.. Break CTRL-C to stop"
                time.sleep(5)
            else:
                user_input = raw_input("Do you want to Abort(a) or continue(c) installation[c]:") or 'c'
                if user_input == "a" or user_input != "c":
                    sys.exit(1)
            print "Continuing .."

        # Setup configuration files
        print "\nConfiguring appOrbit setup"
        max_api_users = action_obj.calcMaxPhusionProcess()
        config_obj.setupConfig(utility_obj, max_api_users)

        print "Preparing and removing old containers for appOrbit server."
        with utility.DotProgress("Prepare"):
            utility_obj.progressBar(0)
            action_obj.predeployAppOrbit(config_obj)
            utility_obj.progressBar(20)
        print "   -- [Done]"

        if config_obj.remove_data:
            logging.warning("Removing old data")
            print "Removing old data for appOrbit server."
            action_obj.removeData(config_obj)

        try:
            if os.stat(config_obj.APPORBIT_DATA) and os.listdir(config_obj.APPORBIT_DATA):
                config_obj.initial_install = False
            else:
                config_obj.initial_install = True
        except:
            config_obj.initial_install = True

        if args.setuponly:
            utility_obj.removeTempFile()
            print "Requested setup only."
            print "Use apporbit-server --pullimages to pull images."
            print "Then use apporbit-server --start to start appOrbit server."
            return

        print "Download appOrbit Server container images"
        logging.info("Updating Images")
        with utility.DotProgress("Pull"):
            utility_obj.progressBar(0)
            action_obj.pullImages(config_obj)
            utility_obj.progressBar(20)
        print "   -- [Done]"


        print "Deploying appOrbit server."
        if 'update' in args.list or 'upgrade' in args.list:
           config_obj.upgrade = True
        with utility.DotProgress("Deploy"):
            utility_obj.progressBar(0)
            action_obj.deployAppOrbitCompose(config_obj)
            utility_obj.progressBar(20)
	    utility_obj.removeTempFile()
        print "   -- [Done]"

        print "Waiting for appOrbit server to be active"
        with utility.DotProgress("Waiting"):
            utility_obj.progressBar(0)
            action_obj.waitForDeployment(config_obj,utility_obj)
            utility_obj.progressBar(20)
        print "   -- [Done]"

        print "Now login to the appOrbit server using"
        print "https://" + config_obj.apporbit_host 
        if args.upgrade:
            print "Please login using existing credentials"
        else:
            print "Login: "******"and default password 'admin1234'"
        logging.info("END OF DEPLOYMENT")

        logtimestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        shutil.move('/var/log/apporbit/apporbit-server.log', '/var/log/apporbit/apporbit-server-' + logtimestamp + '.log')
        print "Server logs moved to /var/log/apporbit/apporbit-server-" + logtimestamp + '.log'

    elif args.pullimages:
        print "Update  appOrbit Server images"
        logging.info("Updating Images")
        with utility.DotProgress("PullImages"):
            utility_obj.progressBar(0)
            action_obj.pullImages(config_obj)
            utility_obj.progressBar(20)
        print "   -- [Done]"
    elif args.start: 
        print "Start appOrbit Server containers"
        if 'update' in args.list or 'upgrade' in args.list:
           config_obj.upgrade = True
        logging.info("Starting Server")
        action_obj.deployAppOrbitCompose(config_obj, show=True)
        print "[Done]"
        print "Waiting for appOrbit server to be active"
        with utility.DotProgress("Waiting"):
            utility_obj.progressBar(0)
            action_obj.waitForDeployment(config_obj,utility_obj)
            utility_obj.progressBar(20)
        print "   -- [Done]"
        print "Now login to the appOrbit server using"
        print "https://" + config_obj.apporbit_host 
    elif args.stop:
        print "Stop appOrbit Server containers"
        logging.info("Stopping Server")
        action_obj.removeCompose(config_obj, show=True)
        logging.info("Stopped Server")
        print " [Done]"
    elif args.kill:
        print "Stop and kill appOrbit Server containers"
        logging.info("Stopping and killing Server")
        action_obj.removeRunningContainers(config_obj, show=True)
        logging.info("Killed appOrbit Server")
        print "   -- [Done]"
    elif args.restart:
        complist = ' '.join(args.list)
        print "Restart appOrbit Server components:", complist
        logging.info("Restarting appOrbit Server components: %s" %complist)
        action_obj.restartAppOrbitCompose(config_obj, complist, show=True)
        logging.info("Restarted appOrbit Server")
        print " [Done]"
    elif args.removedata:
        logging.info("Requesting to remove data")
        if action_obj.showStatus(config_obj,show=False):
            print "Run apporbit-server --stop to stop containers before deleting data."
            logging.error("appOrbit server is running. Cannot delete data")
            return False
        else:
            logging.warning("REMOVING appOrbit server Volume data.")
            action_obj.removeData(config_obj)
            print "Removing appOrbit server data."
    elif args.removeconfig:
        logging.info("Requesting to remove setup configuration")
        if action_obj.showStatus(config_obj,show=False):
            print "Run apporbit-server --stop to stop containers before deleting setup configuration."
            logging.error("appOrbit server is running. Cannot delete setup configuration")
            return False
        else:
            logging.warning("REMOVING appOrbit server setup configuration.")
            action_obj.removeSetupConfig(config_obj)
            print "Removing appOrbit server setup configuration."
    elif args.removeall:
        logging.info("Requesting to remove all data, configuration, keys")
        if action_obj.showStatus(config_obj,show=False):
            print "Run apporbit-server --stop to stop containers before deleting setup configuration."
            logging.error("appOrbit server is running. Cannot delete all data, keys and configuration")
            return False
        else:
            logging.warning("REMOVING appOrbit server setup configuration, data and keys.")
            action_obj.removeSetupConfig(config_obj)
            action_obj.removeData(config_obj)
            action_obj.removeKeys(config_obj)
            print "Removing appOrbit server setup configuration, data and keys."
    elif args.status:
        # If product is not installed it will show above that it is not installed.
        # If it is installed then the next block will show the status of containers
        if os.path.isfile(config_obj.apporbit_serverconf):
            print "Showing status of appOrbit Server"
            action_obj.showStatus(config_obj, show=True)
    elif args.buildpackages:
        import resourcefetcher
        rf = resourcefetcher.ResourceFetcher()
        rf.fetch_resources()
    elif args.setupprovider:
        import provider
        ps = provider.Provider()
        ps.setup_provider()
        finalMessage = ("Copy apporbit-server and appOrbitPackages.tar.gz to "
              "appOrbit host\nand execute ./apporbit-server --deploy-offline")
        print finalMessage
    elif args.deployoffline:
        import offlinedeploy
        od = offlinedeploy.OfflineDeploy()
        od.deploy_apporbit()
    elif args.offline:
        import resourcefetcher, provider, offlinedeploy
        opt = raw_input("Are the resources fetched [y]/n : ") or "y"
        if str(opt).lower() in ['n', 'no']:
            rf = resourcefetcher.ResourceFetcher()
            rf.fetch_resources()
            sys.exit(1)
        opt = raw_input("Is the provider set up done [y]/n : ") or "y"
        if str(opt).lower() in ['n', 'no']:
            ps = provider.Provider()
            ps.setup_provider()
        opt = raw_input("Do you want to install appOrbit on this host [y]/n : ") or "y"
        if str(opt).lower() in ['y', 'yes']:
            od = offlinedeploy.OfflineDeploy()
            od.deploy_apporbit()
    elif args.list:
        # if I am here I have not given any valid option but did enter a list argument
        complist = ' '.join(args.list)
        print 'Invalid arguments: ' + complist + '\n\n'
        parser.print_help()
    else:
        # No options and no list and product is already installed. Just show the status and help command
        print "appOrbit server is already configured.\n"
        print "Run the installer again with --upgrade if you wish to upgrade.\n"
        print "For example:\n" 
        print "bash <(curl -s  http://repos.apporbit.com/install" +\
	    "/appOrbitKit/install.sh) --upgrade OR"
        print "/opt/apporbit/bin/apporbit-server --upgrade\n"
        action_obj.showStatus(config_obj,show=True)
        print ""
        parser.print_help()

    return
Esempio n. 19
0
def access_tt():
    p = provider.Provider()
    p.public()
    p._package_public()
#     p.__private()    # access fail
    p.call__private()