Handle the result of an http monitor
433801
def _handler_http(self, result):
        
        monitor = result['monitor']
        self.thread_debug("process_http", data=monitor, module='handler')
        self.stats.http_handled += 1

        # splunk will pick this up
        logargs = {
            'type':"metric",
            'endpoint': result['url'],
            'pipeline': monitor['pipeline'],
            'service': monitor['service'],
            'instance': monitor['instance'],
            'status': result['status'],
            'elapsed-ms': round(result['elapsedms'], 5),
            'code': result['code']
        }
        self.NOTIFY(result['message'], **logargs)

        # if our status has changed, also update Reflex Engine
        if result['status'] != self.instances[monitor['instance']]['status']:
            # do some retry/counter steps on failure?
            self.instances[monitor['instance']]['status'] = result['status']
            self.rcs.patch('instance',
                           monitor['instance'],
                           {'status': result['status']})
416428
function monitorHttp (ctx, req, res) {
  var stopwatch = ctx.timer.start()

  function endOfConnectionHandler () {
    // cached vars
    var stats = ctx.stats
    var histogram = ctx.histogram

    // capture duration
    var duration = stopwatch.end()
    stopwatch = null
    stats.meter('requests').mark()

    // duration is in ms as float with nanosecond precision,
    // but we use microseconds with the backend
    histogram.update(Math.round(duration * 1000), Date.now())
    if (res.getHeader) {
      ctx.resSize += ((res.getHeader('Content-Length') || 0) * 1)
    }

    if (req.headers) {
      ctx.reqSize += (req.headers['content-length'] || 0) * 1
    }

    // capture special response codes
    if (res.statusCode >= 300) {
      if (res.statusCode < 400) {
        stats.meter('3xxRate').mark()
      } else if (res.statusCode < 500) {
        stats.meter('errRate').mark()
        stats.meter('4xxRate').mark()
      } else {
        stats.meter('errRate').mark()
        stats.meter('5xxRate').mark()
      }
    }

    res.removeListener(FINISH_EVENT_NAME, endOfConnectionHandler)
    res.removeListener(ABRUPT_CLOSE_EVENT_NAME, endOfConnectionHandler)

    // this is invoked to cleanup domains from possible timers bound to it
    cleanDomainNamespace()
  }

  res.on(FINISH_EVENT_NAME, endOfConnectionHandler)
  res.on(ABRUPT_CLOSE_EVENT_NAME, endOfConnectionHandler)
}
471471
def _result_handler(self, response: Dict[str, Any]):
        
        res = response.get("MESSAGE")
        ID = res.get("ID")
        result = res.get("RESULT")
        fut = self.tasks.get(ID)
        fut.set_result(result)
        return True
549574
def handle_get_request(self, environ, start_response):
        """"""
        connections = [
            s.strip()
            for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        transport = environ.get('HTTP_UPGRADE', '').lower()
        if 'upgrade' in connections and transport in self.upgrade_protocols:
            self.server.logger.info('%s: Received request to upgrade to %s',
                                    self.sid, transport)
            return getattr(self, '_upgrade_' + transport)(environ,
                                                          start_response)
        try:
            packets = self.poll()
        except exceptions.QueueEmpty:
            exc = sys.exc_info()
            self.close(wait=False)
            six.reraise(*exc)
        return packets
1199693
def _handle_response(self, response):
        """"""
        if isinstance(response, Exception):
            logging.error("dropped chunk %s" % response)
        elif response.json().get("limits"):
            parsed = response.json()
            self._api.dynamic_settings.update(parsed["limits"])
1144845
function done( error ) {
				if ( error ) {
					next( error );
					return;
				}
				if ( !request.hasOwnProperty( 'locals' ) ) {
					request.locals = {};
				}
				request.locals.monitor = metrics;
				next();
			}
402741
def monitor(app):
    """"""
    heroku_app = HerokuApp(dallinger_uid=app)
    webbrowser.open(heroku_app.dashboard_url)
    webbrowser.open("https://requester.mturk.com/mturk/manageHITs")
    heroku_app.open_logs()
    check_call(["open", heroku_app.db_uri])
    while _keep_running():
        summary = get_summary(app)
        click.clear()
        click.echo(header)
        click.echo("\nExperiment {}\n".format(app))
        click.echo(summary)
        time.sleep(10)
1168149
def process_response(self, req, resp, resource):
        
        if 'result' not in req.context:
            return
        req.context['result']['is_login'] = 'user_id' in req.env['session']
        if settings.DEBUG:
            req.context['result']['_debug_queries'] = sys._debug_db_queries
            sys._debug_db_queries = []
        if resp.body is None and req.context['result']:
            resp.body = json.dumps(req.context['result'])

        try:
            log.debug("RESPONSE: %s" % resp.body)
        except:
            log.exception("ERR: RESPONSE CANT BE LOGGED ")
679109
def monitor():
    """"""
    log = logging.getLogger(__name__)
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(console(loop, log))
    loop.run_forever()
1262815
def update_monitor(self):
        """"""
        result = self._client.get_state(self._monitor_url)
        self._raw_result = result['monitor']
1006111
def preview():  # pragma: no coverage
    """"""
    Handler = http.server.SimpleHTTPRequestHandler
    socketserver.TCPServer.allow_reuse_address = True
    port = CONFIG['http_port']
    httpd = socketserver.TCPServer(("", port), Handler)
    os.chdir(CONFIG['output_to'])
    try:
        logger.info("and ready to test at "
                    "http://127.0.0.1:%d" % CONFIG['http_port'])
        logger.info("Hit Ctrl+C to exit")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.shutdown()
595343
def monitor(self):
        """"""
        if self._monitor_api is None:
            self._monitor_api = self.get_monitor_api()
        return self._monitor_api
1354014
def _server_end_response_callback(self, respoonse: Response):
        ''''''
        request = self._item_session.request
        response = self._item_session.response

        _logger.info(__(
            _('Fetched ‘{url}’: {status_code} {reason}. '
              'Length: {content_length} [{content_type}].'),
            url=request.url,
            status_code=response.status_code,
            reason=wpull.string.printable_str(response.reason),
            content_length=wpull.string.printable_str(
                response.fields.get('Content-Length', _('none'))),
            content_type=wpull.string.printable_str(
                response.fields.get('Content-Type', _('none'))),
        ))

        self._result_rule.handle_response(self._item_session)

        if response.status_code in WebProcessor.DOCUMENT_STATUS_CODES:
            filename = self._file_writer_session.save_document(response)
            self._processing_rule.scrape_document(self._item_session)
            self._result_rule.handle_document(self._item_session, filename)

        elif response.status_code in WebProcessor.NO_DOCUMENT_STATUS_CODES:
            self._file_writer_session.discard_document(response)
            self._result_rule.handle_no_document(self._item_session)
        else:
            self._file_writer_session.discard_document(response)
            self._result_rule.handle_document_error(self._item_session)
207606
def handle_response stdout, stderr, thread
      unless thread.value.success?
        dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n"
        raise dump
      end
    end
1371952
def on_result(self, task, result):
        ''''''
        if not result:
            return
        if 'taskid' in task and 'project' in task and 'url' in task:
            logger.info('result %s:%s %s -> %.30r' % (
                task['project'], task['taskid'], task['url'], result))
            print(json.dumps({
                'taskid': task['taskid'],
                'project': task['project'],
                'url': task['url'],
                'result': result,
                'updatetime': time.time()
            }))
        else:
            logger.warning('result UNKNOW -> %.30r' % result)
            return
76007
function handle_checkUrl(result)
			{
				maybeCallback(thisObj.handlers.link)(result, input.data.customData);
				
				// Auto-starts next queue item, if any
				// If not, fires "end"
				done();
			}
450286
def handle(self, sock, read_data, path, headers):
        ""
        if "://" not in self.redirect_to:
            destination = "http%s://%s" % (
                "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "",
                self.redirect_to
            )
        else:
            destination = self.redirect_to
        try:
            sock.sendall("HTTP/1.0 302 Found\r\nLocation: %s/%s\r\n\r\n" % (
                destination.rstrip("/"),
                path.lstrip("/"),
            ))
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise