Exemple #1
0
def get_experiment_uses_by_id(reservation_ids=None):
    if isinstance(reservation_ids, basestring):
        reservation_ids = [{
            'id': reservation_id
        } for reservation_id in reservation_ids.split(',')]
    return weblab_api.ctx.user_processor.get_experiment_uses_by_id([
        SessionId(reservation_id['id']) for reservation_id in reservation_ids
    ])
Exemple #2
0
def logout():
    server_instance = weblab_api.ctx.server_instance
    if not weblab_api.ctx.session_id:
        raise coreExc.SessionNotFoundError(
            "User Processing Server session not found")

    session_id = SessionId(weblab_api.ctx.session_id)

    if server_instance._session_manager.has_session(session_id):
        session = server_instance._session_manager.get_session(session_id)

        user_processor = server_instance._load_user(session)

        reservation_id = session.get('reservation_id')
        if reservation_id is not None and not user_processor.is_access_forward_enabled(
        ):
            #
            # If "is_access_forward_enabled", the user (or more commonly, entity) can log out without
            # finishing his current reservation
            #
            # Furthermore, whenever booking is supported, this whole idea should be taken out. Even
            # with queues it might not make sense, depending on the particular type of experiment.
            #
            try:
                reservation_session = server_instance._reservations_session_manager.get_session(
                    SessionId(reservation_id))
                reservation_processor = server_instance._load_reservation(
                    reservation_session)
                reservation_processor.finish()
            except SessionNotFoundError:
                pass

            try:
                server_instance._alive_users_collection.remove_user(
                    reservation_id)
            except SessionNotFoundError:
                pass

        user_processor.logout()
        user_processor.update_latest_timestamp()

        server_instance._session_manager.delete_session(session_id)
        return {}
    else:
        raise coreExc.SessionNotFoundError(
            "User Processing Server session not found")
Exemple #3
0
    def __init__(self, status, reservation_id):
        """ __init__(status, reservation_id)

        status is Reservation.WAITING, Reservation.CONFIRMED, etc.
        reservation_id is the reservation identifier, used to interact with the experiment
        """
        super(Reservation,self).__init__()
        self.status         = status
        self.reservation_id = SessionId(reservation_id)
 def setUp(self):
     # Initialize the experiment for testing.
     # We set the archimedes_real_device setting to False so that
     # it doesn't attempt to contact the real ip.
     self.cfg_manager = ConfigurationManager()
     self.cfg_manager._set_value("archimedes_real_device", False)
     self.cfg_manager._set_value("archimedes_instances", {
         "default": "http://localhost:8000",
         "second": "http://localhost:8001"
     })
     self.experiment = Archimedes(None, None, self.cfg_manager)
     self.lab_session_id = SessionId('my-session-id')
Exemple #5
0
    def finish_reservation(self, reservation_id):
        session = self.session_maker()
        try:
            reservation = session.query(ExternalWebLabDeustoReservation).filter_by(local_reservation_id = reservation_id).first()
            if reservation is not None:
                remote_reservation_id = reservation.remote_reservation_id
                serialized_cookies = reservation.cookies
            else:
                log.log(ExternalWebLabDeustoScheduler, log.level.Info, "Not finishing reservation %s since somebody already did it" % reservation_id)
                return
        finally:
            session.close()

        cookies = pickle.loads(str(serialized_cookies))
        client = self._create_client(cookies)
        client.finished_experiment(SessionId(remote_reservation_id))
        try:
            client.get_reservation_status(SessionId(remote_reservation_id))
        except:
            # TODO: Actually check that the reservation was expired
            pass # Expired reservation
        else:
            now = self.time_provider.get_datetime()
            self.post_reservation_data_manager.create(reservation_id, now, now + self.expiration_delta, json.dumps("''"))

        session = self.session_maker()
        try:
            reservation = session.query(ExternalWebLabDeustoReservation).filter_by(local_reservation_id = reservation_id).first()
            if reservation is not None:
                try:
                    session.delete(reservation)
                    session.commit()
                except StaleDataError:
                    log.log(ExternalWebLabDeustoScheduler, log.level.Info, "Could not remove reservation_id %s from ExternalWebLabDeustoReservation since somebody already did it" % reservation_id)
            else:
                log.log(ExternalWebLabDeustoScheduler, log.level.Info, "Not deleting reservation %s from ExternalWebLabDeustoReservation since somebody already did it" % reservation_id)
                return
        finally:
            session.close()
    def get_experiment_uses_by_id(self, reservation_ids):
        db_session_id = self._session['db_session_id']
        experiment_uses = self._db_manager.get_experiment_uses_by_id(
            db_session_id, [
                SessionId(reservation_id.id.split(';')[0])
                for reservation_id in reservation_ids
            ])

        results = []
        cancelled_results = []
        for pos, (experiment_use, reservation_id) in enumerate(
                zip(experiment_uses, reservation_ids)):
            result = self._process_use(experiment_use, reservation_id)
            results.append(result)
            if result.is_cancelled():
                cancelled_results.append((pos, reservation_id))

        if len(cancelled_results) > 0:
            # Sometimes, the system recognizes as cancelled a reservation which was removed
            # between the moment we asked for results and the moment we stored the results.
            # Just in case, we check again those results

            tentatively_cancelled_experiment_uses = self._db_manager.get_experiment_uses_by_id(
                db_session_id, [
                    SessionId(reservation_id.id.split(';')[0])
                    for pos, reservation_id in cancelled_results
                ])
            for (pos, reservation_id), tentatively_cancelled_use in zip(
                    cancelled_results, tentatively_cancelled_experiment_uses):
                # Only process the use if the use is now not None
                if tentatively_cancelled_use is not None:
                    tentatively_cancelled_result = self._process_use(
                        tentatively_cancelled_use, reservation_id)
                    if not tentatively_cancelled_result.is_cancelled():
                        # If it is not cancelled anymore, then we replace the previous value
                        results[pos] = tentatively_cancelled_result

        return results
Exemple #7
0
def reserve_experiment(experiment_id=None,
                       client_initial_data=None,
                       consumer_data=None):
    server = weblab_api.ctx.server_instance
    client_address = weblab_api.ctx.client_address
    # core_server_universal_id should be copied
    experiment_id = ExperimentId(experiment_id['exp_name'],
                                 experiment_id['cat_name'])
    status = weblab_api.ctx.user_processor.reserve_experiment(
        experiment_id, client_initial_data, consumer_data, client_address,
        server.core_server_universal_id)

    if status == 'replicated':
        return Reservation.NullReservation()

    reservation_id = status.reservation_id.split(';')[0]
    reservation_session_id = SessionId(reservation_id)

    server._alive_users_collection.add_user(reservation_session_id)

    session_id = server._reservations_session_manager.create_session(
        reservation_id)

    initial_session = {
        'session_polling':
        (time.time(), ReservationProcessor.EXPIRATION_TIME_NOT_SET),
        'latest_timestamp':
        0,
        'experiment_id':
        experiment_id,
        'creator_session_id':
        weblab_api.ctx.
        user_session['session_id'],  # Useful for monitor; should not be used
        'reservation_id':
        reservation_session_id,
        'federated':
        False,
    }
    reservation_processor = server._load_reservation(initial_session)
    reservation_processor.update_latest_timestamp()

    if status.status == WebLabSchedulingStatus.WebLabSchedulingStatus.RESERVED_LOCAL:
        reservation_processor.process_reserved_status(status)

    if status.status == WebLabSchedulingStatus.WebLabSchedulingStatus.RESERVED_REMOTE:
        reservation_processor.process_reserved_remote_status(status)

    server._reservations_session_manager.modify_session(
        session_id, initial_session)
    return Reservation.Reservation.translate_reservation(status)
    def finish_reservation(self, reservation_id):
        redis_client = self.redis_maker()
        reservation_str = redis_client.hget(
            self.external_weblabdeusto_reservations, reservation_id)
        if reservation_str is not None:
            reservation = json.loads(reservation_str)
            remote_reservation_id = reservation['remote_reservation_id']
            serialized_cookies = reservation['cookies']
        else:
            log.log(
                ExternalWebLabDeustoScheduler, log.level.Info,
                "Not finishing reservation %s since somebody already did it" %
                reservation_id)
            return

        cookies = pickle.loads(str(serialized_cookies))
        client = self._create_client(cookies)
        client.finished_experiment(SessionId(remote_reservation_id))
        try:
            client.get_reservation_status(SessionId(remote_reservation_id))
        except:
            # TODO: Actually check that the reservation was expired
            pass  # Expired reservation
        else:
            now = self.time_provider.get_datetime()
            self.post_reservation_data_manager.create(
                reservation_id, now, now + self.expiration_delta,
                json.dumps("''"))

        result = redis_client.hdel(self.external_weblabdeusto_reservations,
                                   reservation_id)
        if not result:
            log.log(
                ExternalWebLabDeustoScheduler, log.level.Info,
                "Not deleting reservation %s from ExternalWebLabDeustoReservation since somebody already did it"
                % reservation_id)
            return
    def get_reservation_status(self, reservation_id):

        reservation_found = False
        max_iterations = 15

        while not reservation_found and max_iterations >= 0:
            session = self.session_maker()
            try:
                reservation = session.query(
                    ExternalWebLabDeustoReservation).filter_by(
                        local_reservation_id=reservation_id).first()
                if reservation is None:
                    pending_result = session.query(
                        ExternalWebLabDeustoReservationPendingResults
                    ).filter_by(resource_type_name=self.resource_type_name,
                                server_route=self.core_server_route,
                                reservation_id=reservation_id).first()
                    if pending_result is None:
                        # reservation not yet stored in local database
                        pass
                    else:
                        return WSS.PostReservationStatus(
                            reservation_id, False, '', '')
                else:
                    reservation_found = True
                    remote_reservation_id = reservation.remote_reservation_id
                    serialized_cookies = reservation.cookies
            finally:
                session.close()

            # Introduce a delay to let the system store the reservation in the local database
            if not reservation_found:
                time_mod.sleep(0.1)
                max_iterations -= 1

        if not reservation_found:
            return WSS.PostReservationStatus(reservation_id, False, '', '')

        cookies = pickle.loads(str(serialized_cookies))
        client = self._create_client(cookies)

        reservation = client.get_reservation_status(
            SessionId(remote_reservation_id))

        return self._convert_reservation_to_status(reservation, reservation_id,
                                                   remote_reservation_id)
 def finish_reservation(self, reservation_id):
     reservation_id = reservation_id.split(';')[0]
     if self.reservations_manager.initialize_deletion(reservation_id):
         self.finished_reservations_store.put(SessionId(reservation_id))
         try:
             aggregator = self._get_scheduler_aggregator_per_reservation(
                 reservation_id)
             aggregator.finish_reservation(reservation_id)
             # The reservations_manager must remove the session once (not once per scheduler)
             self._delete_reservation(reservation_id)
         except CoordExc.ExpiredSessionError:
             log.log(
                 AbstractCoordinator, log.level.Info,
                 "Ignore finish_reservation(%r), given that it had already expired"
                 % reservation_id)
         finally:
             self.reservations_manager.clean_deletion(reservation_id)
    def setUp(self):
        from voodoo.configuration import ConfigurationManager
        from voodoo.sessions.session_id import SessionId

        self.cfg_manager = ConfigurationManager()
        self.cfg_manager.append_module(configuration_module)
        self.cfg_manager._set_value("webcam", "http://localhost")
        self.cfg_manager._set_value("weblab_xilinx_experiment_xilinx_device",
                                    "FPGA")
        self.cfg_manager._set_value("xilinx_max_use_time", "3600")
        self.cfg_manager._set_value("xilinx_bit_allowed", False)

        UdXilinxCommandSenders._SerialPort = FakeSerialPort
        UdXilinxCommandSenders._HttpDevice = FakeHttpDevice

        self.experiment = UdXilinxExperiment.UdXilinxExperiment(
            None, None, self.cfg_manager)
        self.lab_session_id = SessionId('my-session-id')
    def get_reservation_status(self, reservation_id):

        reservation_found = False
        max_iterations = 15

        while not reservation_found and max_iterations >= 0:
            client = self.redis_maker()

            reservation_str = client.hget(
                self.external_weblabdeusto_reservations, reservation_id)
            if reservation_str is None:
                external_weblabdeusto_pending_results = self.EXTERNAL_WEBLABDEUSTO_PENDING_RESULTS % (
                    self.resource_type_name, self.core_server_route)
                pending_result = client.hget(
                    external_weblabdeusto_pending_results, reservation_id)
                if pending_result is None:
                    # reservation not yet stored in local database
                    pass
                else:
                    return WSS.PostReservationStatus(reservation_id, False, '',
                                                     '')
            else:
                reservation = json.loads(reservation_str)
                reservation_found = True
                remote_reservation_id = reservation['remote_reservation_id']
                serialized_cookies = reservation['cookies']

            # Introduce a delay to let the system store the reservation in the local database
            if not reservation_found:
                time_mod.sleep(0.1)
                max_iterations -= 1

        if not reservation_found:
            return WSS.PostReservationStatus(reservation_id, False, '', '')

        cookies = pickle.loads(str(serialized_cookies))
        client = self._create_client(cookies)

        reservation = client.get_reservation_status(
            SessionId(remote_reservation_id))

        return self._convert_reservation_to_status(reservation, reservation_id,
                                                   remote_reservation_id)
Exemple #13
0
    def run(self):
        """
        run()
        Handles file uploading. It will extract the required parameters FILE_SENT, FILE_INFO,
        SESSION_ID, and the optional parameter IS_ASYNC, and call either send_file or
        send_async_file depending on this last one.
        @return HTML defined above, with the success or failure response.
        """
        try:
            file_info, file_sent, session_id, is_async = self._check_arguments()
            file_content = Util.serialize(file_sent)
            sid = SessionId(session_id)

            if(not is_async):
                result = self.server.send_file(sid, file_content, file_info)
            else:
                result = self.server.send_async_file(sid, file_content, file_info)

        except FileUploadError as fue:
            code, message = fue.args
            return FAULT_HTML_TEMPLATE % {
                        'THE_FAULT_CODE' : code,
                        'THE_FAULT_MESSAGE' : message
                    }
        except Exception as e:
            message = e.args[0]
            return FAULT_HTML_TEMPLATE % {
                        'THE_FAULT_CODE' : PYTHON_GENERAL_EXCEPTION_CODE,
                        'THE_FAULT_MESSAGE' : message
                    }
        else:

            if not is_async:
                resultstr = result.commandstring
            else:
                resultstr = result

            print "[DBG] Returning result from file upload: " + resultstr

            return SUCCESS_HTML_TEMPLATE % {
                            'RESULT' : resultstr
                    }
Exemple #14
0
    def wrapper(*args, **kwargs):
        server = weblab_api.ctx.server_instance
        if weblab_api.ctx.session_id is None:
            raise coreExc.SessionNotFoundError("Core Users session not found")

        session_id = SessionId(weblab_api.ctx.session_id)
        try:
            session = server._session_manager.get_session_locking(session_id)
        except SessionNotFoundError:
            raise coreExc.SessionNotFoundError("Core Users session not found")

        try:
            weblab_api.ctx.user_session = session
            weblab_api.ctx.user_processor = server._load_user(session)
            try:
                return func(*args, **kwargs)
            finally:
                weblab_api.ctx.user_processor.update_latest_timestamp()
        finally:
            server._session_manager.modify_session_unlocking(session_id, session)
    def setUp(self):
        from voodoo.configuration import ConfigurationManager
        from voodoo.sessions.session_id import SessionId

        self.cfg_manager = ConfigurationManager()
        self.cfg_manager.append_module(configuration_module)
        self.cfg_manager._set_value("webcam", "http://localhost")

        # For later.
        self.cfg_manager._set_value("weblab_xilinx_experiment_xilinx_device",
                                    "FPGA")

        UdXilinxCommandSenders._SerialPort = FakeSerialPort
        UdXilinxCommandSenders._HttpDevice = FakeHttpDevice

        self.experiment = UdXilinxExperiment.UdXilinxExperiment(
            None, None, self.cfg_manager)

        self.configjson = self.experiment.do_start_experiment()

        self.lab_session_id = SessionId('my-session-id')
    def run(self):
        experiment_id_str = self.get_argument(EXPERIMENT_ID)
        if experiment_id_str is None:
            return "%s argument is missing" % EXPERIMENT_ID
        session_id_str = self.get_argument(SESSION_ID)
        if session_id_str is None:
            return "%s argument is missing" % EXPERIMENT_ID

        experiment_id = ExperimentId.parse(experiment_id_str)
        session_id = SessionId(session_id_str)

        address = RemoteFacadeContext.get_context().get_ip_address()
        client_address = ClientAddress.ClientAddress(address)
        try:
            reservation_id = self.server.reserve_experiment(
                session_id, experiment_id, "{}", "{}", client_address)
        except Exception:
            return HTML_ERROR_TEMPLATE

        new_location = "../../client/federated.html#reservation_id=%s" % reservation_id.reservation_id.id
        self.set_status(302)
        self.add_other_header('Location', new_location)
        return """<html><body><a href="%s">Click here</a></body></html>""" % new_location
Exemple #17
0
    from voodoo.configuration import ConfigurationManager
    from voodoo.sessions.session_id import SessionId

    cfg_manager = ConfigurationManager()
    try:
        cfg_manager.append_path(
            "../../../launch/sample/main_machine/main_instance/experiment_fpga/server_config.py"
        )
    except:
        cfg_manager.append_path(
            "../launch/sample/main_machine/main_instance/experiment_fpga/server_config.py"
        )

    experiment = ElevatorExperiment(None, None, cfg_manager)

    lab_session_id = SessionId('my-session-id')
    experiment.do_start_experiment()

    experiment._max_use_time = 10
    print experiment.do_send_command_to_device("REPORT_USE_TIME_LEFT")
    print experiment.do_send_command_to_device("STATE")
    print experiment.do_send_command_to_device("STATE")
    print experiment.do_should_finish()
    print experiment.do_send_command_to_device("STATE")
    print experiment.do_should_finish()

if __name__ == "__main__":
    from voodoo.configuration import ConfigurationManager
    from voodoo.sessions.session_id import SessionId

    cfg_manager = ConfigurationManager()
 def get_experiment_use_by_id(self, reservation_id):
     experiment_uses = self._db_manager.get_experiment_uses_by_id(self.username, [SessionId(reservation_id.id.split(';')[0])])
     experiment_use  = experiment_uses[0]
     return self._process_use(experiment_use, reservation_id)
    def _process(self):
        redis_client = self.redis_maker()
        pending_results = []
        for reservation_id in redis_client.hkeys(
                self.external_weblabdeusto_pending):
            pending_result_str = redis_client.hget(
                self.external_weblabdeusto_pending, reservation_id)
            if pending_result_str is not None:
                pending_result = json.loads(pending_result_str)
                pending_result['reservation_id'] = reservation_id
                pending_results.append(pending_result)

        if len(pending_results) > 0:
            try:
                session_id, client = self.create_client_func(None)
            except urllib2.URLError:
                # Remote server is down, try later
                return

            remote_reservation_ids = [
                SessionId(pending_result['remote_reservation_id'])
                for pending_result in pending_results
            ]

            results = client.get_experiment_uses_by_id(session_id,
                                                       remote_reservation_ids)

            for pending_result, result in zip(pending_results, results):
                if result.is_alive():
                    continue

                username = pending_result['username']
                try:
                    request_info = pickle.loads(
                        pending_result['serialized_request_info'].encode(
                            'utf-8'))
                except Exception as e:
                    log.log(
                        ResultsRetriever, log.level.Critical,
                        "Probably serialized_request_info was truncated in %s"
                        % pending_result)
                    log.log_exc(ResultsRetriever, log.level.Error)
                    request_info = {'error': 'could not be stored: %s' % e}
                reservation_id = pending_result['reservation_id']
                remote_reservation_id = pending_result['remote_reservation_id']

                if not redis_client.hdel(self.external_weblabdeusto_pending,
                                         reservation_id):
                    log.log(
                        ResultsRetriever, log.level.Info,
                        "Pending reservation %r not found. Assuming it is managed by other thread"
                        % pending_result)
                    continue

                if result.is_finished():
                    use = result.experiment_use
                    use.experiment_id = ExperimentId.parse(
                        pending_result['experiment_id_str'])
                    use.remote_reservation_id = remote_reservation_id
                    use.reservation_id = reservation_id

                    for key in [key for key in request_info]:
                        if not isinstance(request_info[key],
                                          (basestring, numbers.Number)):
                            request_info.pop(key)
                    use.request_info = request_info
                    callback = lambda: self.post_reservation_data_manager.delete(
                        reservation_id)
                    self.completed_store.put(username, use, callback)
                else:
                    log.log(
                        ResultsRetriever, log.level.Info,
                        "Reservation id %s was cancelled and therefore not stored"
                        % reservation_id)
Exemple #20
0
VDC+6V_1 VDC+6V_1_1
</circuitlist></circuit><multimeter id="1"><dmm_function value="dc current"></dmm_function><dmm_resolution value="3.5"></dmm_resolution><dmm_range value="-1"></dmm_range><dmm_autozero value="1"></dmm_autozero></multimeter><functiongenerator id="1"><fg_waveform value="sine"></fg_waveform><fg_frequency value="1000"></fg_frequency><fg_amplitude value="0.5"></fg_amplitude><fg_offset value="0"></fg_offset></functiongenerator><oscilloscope id="1"><horizontal><horz_samplerate value="500"></horz_samplerate><horz_refpos value="50"></horz_refpos><horz_recordlength value="500"></horz_recordlength></horizontal><channels><channel number="1"><chan_enabled value="1"></chan_enabled><chan_coupling value="dc"></chan_coupling><chan_range value="1"></chan_range><chan_offset value="0"></chan_offset><chan_attenuation value="1"></chan_attenuation></channel><channel number="2"><chan_enabled value="1"></chan_enabled><chan_coupling value="dc"></chan_coupling><chan_range value="1"></chan_range><chan_offset value="0"></chan_offset><chan_attenuation value="1"></chan_attenuation></channel></channels><trigger><trig_source value="channel 1"></trig_source><trig_slope value="positive"></trig_slope><trig_coupling value="dc"></trig_coupling><trig_level value="0"></trig_level><trig_mode value="autolevel"></trig_mode><trig_timeout value="1"></trig_timeout><trig_delay value="0"></trig_delay></trigger><measurements><measurement number="1"><meas_channel value="channel 1"></meas_channel><meas_selection value="none"></meas_selection></measurement><measurement number="2"><meas_channel value="channel 1"></meas_channel><meas_selection value="none"></meas_selection></measurement><measurement number="3"><meas_channel value="channel 1"></meas_channel><meas_selection value="none"></meas_selection></measurement></measurements><osc_autoscale value="0"></osc_autoscale></oscilloscope><dcpower id="1"><dc_outputs><dc_output channel="6V+"><dc_voltage value="2.5"></dc_voltage><dc_current value="0.5"></dc_current></dc_output><dc_output channel="25V+"><dc_voltage value="0"></dc_voltage><dc_current value="0.5"></dc_current></dc_output><dc_output channel="25V-"><dc_voltage value="0"></dc_voltage><dc_current value="0.5"></dc_current></dc_output></dc_outputs></dcpower></request></protocol>"""
    from voodoo.configuration import ConfigurationManager
    from voodoo.sessions.session_id import SessionId
    cfg_manager = ConfigurationManager()
    try:
        cfg_manager.append_path(
            "../../launch/sample/main_machine/main_instance/experiment_testvisir/server_config.py"
        )
    except:
        cfg_manager.append_path(
            "../launch/sample/main_machine/main_instance/experiment_testvisir/server_config.py"
        )

    experiment = VisirExperiment(None, None, cfg_manager)
    lab_session_id = SessionId('sess1')
    experiment.do_start_experiment(lab_session_id)

    login_response = json.loads(
        experiment.do_send_command_to_device(lab_session_id, "login"))
    sessionkey = login_response['sessionkey']
    request = regular_request % sessionkey
    experiment.do_send_command_to_device(lab_session_id, request)

    time.sleep(1)

    lab_session_id2 = SessionId('sess2')
    experiment.do_start_experiment(lab_session_id2)

    login_response2 = json.loads(
        experiment.do_send_command_to_device(lab_session_id2, "login"))
Exemple #21
0
def get_multiple_reservation_status(reservation_ids, timeout):
    server = weblab_api.ctx.server_instance
    status = {}
    t0 = time.time()

    if timeout > 0:
        random.shuffle(reservation_ids)

    for reservation_id in reservation_ids:
        if timeout > 0 and time.time() > (t0 + timeout):
            break

        current_reservation_id = SessionId(reservation_id.split(';')[0])
        try:
            session = server._reservations_session_manager.get_session(
                current_reservation_id)
        except (SessionNotFoundError, coreExc.NoCurrentReservationError):
            status[reservation_id] = {
                'success': False,
                'reason': "session-not-found",
                'reason-human': "reservation id not found",
            }
            continue
        except Exception as err:
            status[reservation_id] = {
                'success': False,
                'reason': "error-checking-reservation-1",
                'reason-human': str(err),
            }
            traceback.print_exc()
            continue

        try:
            weblab_api.ctx.reservation_session = session
            reservation_processor = server._load_reservation(session)
            try:
                status[reservation_id] = reservation_processor.get_status()
            except Exception as err:
                status[reservation_id] = {
                    'success': False,
                    'reason': "error-checking-reservation-2",
                    'reason-human': str(err),
                }
                traceback.print_exc()
                continue
        except (SessionNotFoundError, coreExc.NoCurrentReservationError):
            status[reservation_id] = {
                'success': False,
                'reason': "session-not-found",
                'reason-human': "reservation id not found",
            }
            continue
        except Exception as err2:
            status[reservation_id] = {
                'success': False,
                'reason': "error-checking-reservation-3",
                'reason-human': str(err2),
            }
            traceback.print_exc()
            continue

    tf = time.time()

    return dict(status=status, time=tf - t0)
Exemple #22
0
 def login(self, username, password):
     session_holder = self._login_call('login',
                                       username=username,
                                       password=password)
     return SessionId(session_holder['id'])
Exemple #23
0
def get_reservation_id(ups_session_id):
    ups = _find_ups()
    sid = SessionId(ups_session_id)
    session = ups._session_manager.get_session(sid)
    return session.get('reservation_id')
Exemple #24
0
    def _process(self):
        session = self.session_maker()
        try:
            pending_results = [
                pending_result.to_dto() for pending_result in session.query(
                    ExternalWebLabDeustoReservationPendingResults).filter_by(
                        resource_type_name=self.resource_type_name,
                        server_route=self.server_route).all()
            ]
        finally:
            session.close()

        if len(pending_results) > 0:
            try:
                session_id, client = self.create_client_func(None)
            except urllib2.URLError:
                # Remote server is down, try later
                return

            remote_reservation_ids = [
                SessionId(pending_result.remote_reservation_id)
                for pending_result in pending_results
            ]

            results = client.get_experiment_uses_by_id(session_id,
                                                       remote_reservation_ids)

            for pending_result, result in zip(pending_results, results):
                if result.is_alive():
                    continue

                username = pending_result.username
                try:
                    request_info = pickle.loads(
                        pending_result.serialized_request_info.encode('utf-8'))
                except Exception as e:
                    log.log(
                        ResultsRetriever, log.level.Critical,
                        "Probably serialized_request_info was truncated in %s"
                        % pending_result)
                    log.log_exc(ResultsRetriever, log.level.Error)
                    request_info = {'error': 'could not be stored: %s' % e}
                reservation_id = pending_result.reservation_id
                remote_reservation_id = pending_result.remote_reservation_id

                session = self.session_maker()
                try:
                    db_pending_result = session.query(
                        ExternalWebLabDeustoReservationPendingResults
                    ).filter_by(id=pending_result.id).first()
                    if db_pending_result is not None:
                        session.delete(db_pending_result)
                        session.commit()
                    else:
                        log.log(
                            ResultsRetriever, log.level.Info,
                            "Pending reservation %r not found. Assuming it is managed by other thread"
                            % pending_result)
                        continue
                except (IntegrityError, ConcurrentModificationError,
                        StaleDataError):
                    log.log(
                        ResultsRetriever, log.level.Info,
                        "Pending reservation %r deletion failed. Assuming it is managed by other thread"
                        % pending_result)
                    log.log_exc(ResultsRetriever, log.level.Debug)
                    # Somebody else is already handling this
                    continue
                finally:
                    session.close()

                if result.is_finished():
                    use = result.experiment_use
                    use.experiment_id = ExperimentId.parse(
                        pending_result.experiment_id_str)
                    use.remote_reservation_id = remote_reservation_id
                    use.reservation_id = reservation_id

                    for key in [key for key in request_info]:
                        if not isinstance(request_info[key],
                                          (basestring, numbers.Number)):
                            request_info.pop(key)
                    use.request_info = request_info
                    callback = lambda: self.post_reservation_data_manager.delete(
                        reservation_id)
                    self.completed_store.put(username, use, callback)
                else:
                    log.log(
                        ResultsRetriever, log.level.Info,
                        "Reservation id %s was cancelled and therefore not stored"
                        % reservation_id)
Exemple #25
0
def kickout_from_ups(session_id):
    ups = _find_ups()
    sid = SessionId(session_id)
    ups._alive_users_collection.remove_user(sid.id)
    ups._session_manager.delete_session(sid)
Exemple #26
0
    def run(self):
        """ run()

        If there is a GET argument named %(reservation_id)s, it will take it and resend it as a
        POST argument. If it was passed through the history, then it will be again sent as a
        POST argument. Finally, if it is received as a POST argument, it will generate a redirect
        to the client, using the proper current structure.
        """ % {
            'reservation_id': RESERVATION_ID
        }

        # If it is passed as a GET argument, send it as POST
        reservation_id = self.get_GET_argument(RESERVATION_ID)
        if reservation_id is not None:
            return REDIRECT_CODE % {
                'reason': 'GET performed',
                'reservation_id': urllib.unquote(reservation_id)
            }

        # If it is passed as History (i.e. it was not passed by GET neither POST),
        # pass it as a POST argument
        reservation_id = self.get_POST_argument(RESERVATION_ID)
        if reservation_id is None:
            return LABEL_CODE

        reservation_id = urllib.unquote(reservation_id)

        if self.req.server_route is not None:
            # If the request should not go to the current server
            if reservation_id.find('.') >= 0 and not reservation_id.endswith(
                    self.req.server_route):
                if reservation_id.find(';') >= 0:
                    partial_reservation_id = reservation_id.split(';')[1]
                else:
                    partial_reservation_id = reservation_id
                self.req.weblab_cookie = 'weblabsessionid=%s' % partial_reservation_id
                self.req.login_weblab_cookie = 'loginweblabsessionid=%s' % partial_reservation_id
                return REDIRECT_CODE % {
                    'reason':
                    'reservation_id %s does not end in server_route %s' %
                    (reservation_id, self.req.server_route),
                    'reservation_id':
                    reservation_id
                }

        if reservation_id.find(';') >= 0:
            partial_reservation_id = reservation_id.split(';')[1]
        else:
            partial_reservation_id = reservation_id

        self.req.weblab_cookie = 'weblabsessionid=%s' % partial_reservation_id
        self.req.login_weblab_cookie = 'loginweblabsessionid=%s' % partial_reservation_id

        # Finally, if it was passed as a POST argument, generate the proper client address
        reservation_session_id = SessionId(reservation_id.split(';')[0])
        try:
            experiment_id = self.server.get_reservation_info(
                reservation_session_id)
        except SessionNotFoundError:
            return ERROR_CODE % reservation_id

        client_address = "../../client/index.html#exp.name=%(exp_name)s&exp.category=%(exp_cat)s&reservation_id=%(reservation_id)s&header.visible=false&page=experiment" % {
            'reservation_id': reservation_id,
            'exp_name': experiment_id.exp_name,
            'exp_cat': experiment_id.cat_name
        }

        format_parameter = self.get_POST_argument(FORMAT_PARAMETER)
        if format_parameter is not None and format_parameter == 'text':
            return client_address

        return FINAL_REDIRECT % {'URL': client_address}
Exemple #27
0
def get_experiment_use_by_id(reservation_id = None):
    return weblab_api.ctx.user_processor.get_experiment_use_by_id(SessionId(reservation_id['id']))
Exemple #28
0
 def __init__(self, reservation_id, time, initial_configuration, url, remote_reservation_id):
     super(ConfirmedReservation,self).__init__(Reservation.CONFIRMED, reservation_id)
     self.time                  = time
     self.initial_configuration = initial_configuration
     self.url                   = url
     self.remote_reservation_id = SessionId(remote_reservation_id)