Ejemplo n.º 1
0
def update_delay_policy(handler):
    """Record delay policy in redis to be available globally to any
    users for their sessions.
    Creates a delay policy. Examples:
        { “name”: “delay_name”,
          “delay_type”: “fixed”,
          “milliseconds”: 50}
        or
        { “name”: “delay_name”,
          “delay_type”: “normalvariate”,
          “mean”: “mean_val”,
          “stddev”: “val”}

    :return: :response: <dict> with status code (400 - bad request, 409 - something is wrong, conflict of values,
    200 - delay policy updated, 201 - delay policy created)
    """
    cache = Cache(get_hostname(handler.request))
    response = {
        'version': version
    }
    doc = handler.request.arguments
    err = None
    status_code = None
    # checking name
    if 'name' not in doc:
        err = "'name' parameter not found in request"
        status_code = 400
    else:
        if " " in doc['name']:
            err = "'name' parameter should not contain white space"
            status_code = 400

    if 'delay_type' not in doc:
        err = "'delay_type' param not found in request"
        status_code = 400
    if not err:
        # checking for fixed delays
        if doc['delay_type'] == 'fixed':
            if 'milliseconds' not in doc:
                err = "'milliseconds' param is required for 'fixed' delays"
                status_code = 409

        # checking for normalvariate delays
        elif doc['delay_type'] == 'normalvariate':
            if 'mean' not in doc or 'stddev' not in doc:
                err = "'mean' and 'stddev' params are required for " \
                      "'normalvariate' delays"
                status_code = 409

        # checking for weighted delays
        elif doc['delay_type'] == 'weighted':
            if 'delays' not in doc:
                err = "'delays' are required for 'weighted' delays"
                status_code = 409
            else:
                try:
                    Delay.parse_args(doc)
                except Exception, e:
                    err = 'Unable to parse weighted delay arguments: {0}'.format(str(e))
                    status_code = 409
        # delay_type not known, creating error
        else:
            err = 'Unknown delay type: {0}'.format(doc['delay_type'])
            status_code = 400
Ejemplo n.º 2
0
 def _get_delay(self, policy):
     from stubo.service.delay import Delay
     return Delay.parse_args(policy)
Ejemplo n.º 3
0
def update_delay_policy(handler):
    """Record delay policy in redis to be available globally to any
    users for their sessions.
    Creates a delay policy. Examples:
        { “name”: “delay_name”,
          “delay_type”: “fixed”,
          “milliseconds”: 50}
        or
        { “name”: “delay_name”,
          “delay_type”: “normalvariate”,
          “mean”: “mean_val”,
          “stddev”: “val”}

    :return: :response: <dict> with status code (400 - bad request, 409 - something is wrong, conflict of values,
    200 - delay policy updated, 201 - delay policy created)
    """
    cache = Cache(get_hostname(handler.request))
    response = {'version': version}
    doc = handler.request.arguments
    err = None
    status_code = None
    # checking name
    if 'name' not in doc:
        err = "'name' parameter not found in request"
        status_code = 400
    else:
        if " " in doc['name']:
            err = "'name' parameter should not contain white space"
            status_code = 400

    if 'delay_type' not in doc:
        err = "'delay_type' param not found in request"
        status_code = 400
    if not err:
        # checking for fixed delays
        if doc['delay_type'] == 'fixed':
            if 'milliseconds' not in doc:
                err = "'milliseconds' param is required for 'fixed' delays"
                status_code = 409

        # checking for normalvariate delays
        elif doc['delay_type'] == 'normalvariate':
            if 'mean' not in doc or 'stddev' not in doc:
                err = "'mean' and 'stddev' params are required for " \
                      "'normalvariate' delays"
                status_code = 409

        # checking for weighted delays
        elif doc['delay_type'] == 'weighted':
            if 'delays' not in doc:
                err = "'delays' are required for 'weighted' delays"
                status_code = 409
            else:
                try:
                    Delay.parse_args(doc)
                except Exception, e:
                    err = 'Unable to parse weighted delay arguments: {0}'.format(
                        str(e))
                    status_code = 409
        # delay_type not known, creating error
        else:
            err = 'Unknown delay type: {0}'.format(doc['delay_type'])
            status_code = 400
Ejemplo n.º 4
0
def get_response_v2(handler, full_scenario_name, session_name):
    # main result dictionary that will be returned
    result_dict = {}

    request = handler.request
    stubo_request = StuboRequest(request)
    cache = Cache(get_hostname(request))

    scenario_name = full_scenario_name.partition(':')[-1]
    handler.track.scenario = scenario_name
    request_id = stubo_request.id()
    module_system_date = handler.get_argument('system_date', None)
    url_args = handler.track.request_params

    # trace_matcher = TrackTrace(handler.track, 'matcher')
    user_cache = handler.settings['ext_cache']
    # check cached requests
    cached_request = cache.get_request(scenario_name, session_name, request_id)
    if cached_request:
        response_ids, delay_policy_name, recorded, system_date, module_info, request_index_key = cached_request
    else:
        retry_count = 5 if handler.settings.get('is_cluster', False) else 1
        session, retries = cache.get_session_with_delay(
            scenario_name,
            session_name,
            retry_count=retry_count,
            retry_interval=1)
        if retries > 0:
            log.warn(
                "replication was slow for session: {0} {1}, it took {2} secs!".
                format(full_scenario_name, session_name, retries + 1))
        if session['status'] != 'playback':
            result_dict[
                "error"] = 'cache status != playback. session={0}'.format(
                    session)
            result_dict["statusCode"] = 412
            return result_dict

        system_date = session['system_date']
        if not system_date:
            result_dict[
                "error"] = "slave session {0} not available for scenario {1}".format(
                    session_name, full_scenario_name)
            result_dict["statusCode"] = 412
            return result_dict

        trace_matcher = TrackTrace(handler.track, 'matcher')
        session['ext_cache'] = user_cache
        result = match(stubo_request,
                       session,
                       trace_matcher,
                       as_date(system_date),
                       url_args=url_args,
                       hooks=handler.settings['hooks'],
                       module_system_date=module_system_date)
        # matching request not found
        if not result[0]:
            result_dict["error"] = "Not matching request found"
            result_dict["statusCode"] = 404
            return result_dict

        _, stub_number, stub = result
        response_ids = stub.response_ids()
        delay_policy_name = stub.delay_policy_name()
        recorded = stub.recorded()
        module_info = stub.module()
        request_index_key = add_request(
            session, request_id, stub, system_date, stub_number,
            handler.settings['request_cache_limit'])

        if not stub.response_body():
            _response = stub.get_response_from_cache(request_index_key)
            stub.set_response_body(_response['body'])

        if delay_policy_name:
            stub.load_delay_from_cache(delay_policy_name)

    if cached_request:
        stub = StubCache({}, full_scenario_name, session_name)
        stub.load_from_cache(response_ids, delay_policy_name, recorded,
                             system_date, module_info, request_index_key)
    trace_response = TrackTrace(handler.track, 'response')
    if module_info:
        trace_response.info('module used', str(module_info))
    response_text = stub.response_body()

    if not response_text:
        result_dict[
            "error"] = 'Unable to find response in cache using session: {0}:{1}, '
        'response_ids: {2}'.format(full_scenario_name, session_name,
                                   response_ids)
        result_dict["statusCode"] = 400
        return result_dict

    # get latest delay policy
    delay_policy = stub.delay_policy()
    if delay_policy:
        delay = Delay.parse_args(delay_policy)
        if delay:
            delay = delay.calculate()
            msg = 'apply delay: {0} => {1}'.format(delay_policy, delay)
            log.debug(msg)
            handler.track['delay'] = delay
            trace_response.info(msg)

    trace_response.info('found response')
    module_system_date = as_date(module_system_date) if module_system_date \
        else module_system_date
    stub, _ = transform(stub,
                        stubo_request,
                        module_system_date=module_system_date,
                        system_date=as_date(system_date),
                        function='get/response',
                        cache=user_cache,
                        hooks=handler.settings['hooks'],
                        stage='response',
                        trace=trace_response,
                        url_args=url_args)
    transfomed_response_text = stub.response_body()[0]
    # Note transformed_response_text can be encoded in utf8
    if response_text[0] != transfomed_response_text:
        trace_response.diff('response:transformed',
                            dict(response=response_text[0]),
                            dict(response=transfomed_response_text))

    result_dict["body"] = transfomed_response_text
    result_dict["headers"] = stub.response_headers()
    result_dict["statusCode"] = stub.response_status()

    return result_dict
Ejemplo n.º 5
0
 def _get_delay(self, policy):
     from stubo.service.delay import Delay
     return Delay.parse_args(policy)