Wrap run with requests to cronitor.
543609
def cronitor(self):
        """"""
        url = f'https://cronitor.link/{self.opts.cronitor}/{{}}'

        try:
            run_url = url.format('run')
            self.logger.debug(f'Pinging {run_url}')
            requests.get(run_url, timeout=self.opts.timeout)

        except requests.exceptions.RequestException as e:
            self.logger.exception(e)

        # Cronitor may be having an outage, but we still want to run our stuff
        output, exit_status = self.run()

        endpoint = 'complete' if exit_status == 0 else 'fail'
        try:
            ping_url = url.format(endpoint)
            self.logger.debug('Pinging {}'.format(ping_url))
            requests.get(ping_url, timeout=self.opts.timeout)

        except requests.exceptions.RequestException as e:
            self.logger.exception(e)

        return output, exit_status
1352754
def run(self, func, *args, **kwargs):
        """"""
        if self.dry:
            return self.dryRun(func, *args, **kwargs)
        else:
            return self.wetRun(func, *args, **kwargs)
203397
def run(self):
    """"""
    self.close_connection = False

    try:
      while True:
        self.started_response = False
        self.status = ""
        self.outheaders = []
        self.sent_headers = False
        self.chunked_write = False
        self.write_buffer = StringIO.StringIO()
        self.content_length = None
        # Copy the class environ into self.
        ENVIRON = self.environ = self.connection_environ.copy()
        self.environ.update(self.server_environ)

        request_line = yield self.connfh.readline()
        if request_line == "\r\n":
          # RFC 2616 sec 4.1: "... it should ignore the CRLF."
          tolerance = 5
          while tolerance and request_line == "\r\n":
            request_line = yield self.connfh.readline()
            tolerance -= 1
          if not tolerance:
            return
        method, path, req_protocol = request_line.strip().split(" ", 2)
        ENVIRON["REQUEST_METHOD"] = method
        ENVIRON["CONTENT_LENGTH"] = ''

        scheme, location, path, params, qs, frag = urlparse(path)

        if frag:
          yield self.simple_response("400 Bad Request",
                      "Illegal #fragment in Request-URI.")
          return

        if scheme:
          ENVIRON["wsgi.url_scheme"] = scheme
        if params:
          path = path + ";" + params

        ENVIRON["SCRIPT_NAME"] = ""

        # Unquote the path+params (e.g. "/this%20path" -> "this path").
        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
        #
        # But note that "...a URI must be separated into its components
        # before the escaped characters within those components can be
        # safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2
        atoms = [unquote(x) for x in quoted_slash.split(path)]
        path = "%2F".join(atoms)
        ENVIRON["PATH_INFO"] = path

        # Note that, like wsgiref and most other WSGI servers,
        # we unquote the path but not the query string.
        ENVIRON["QUERY_STRING"] = qs

        # Compare request and server HTTP protocol versions, in case our
        # server does not support the requested protocol. Limit our output
        # to min(req, server). We want the following output:
        #     request    server     actual written   supported response
        #     protocol   protocol  response protocol    feature set
        # a     1.0        1.0           1.0                1.0
        # b     1.0        1.1           1.1                1.0
        # c     1.1        1.0           1.0                1.0
        # d     1.1        1.1           1.1                1.1
        # Notice that, in (b), the response will be "HTTP/1.1" even though
        # the client only understands 1.0. RFC 2616 10.5.6 says we should
        # only return 505 if the _major_ version is different.
        rp = int(req_protocol[5]), int(req_protocol[7])
        server_protocol = ENVIRON["ACTUAL_SERVER_PROTOCOL"]
        sp = int(server_protocol[5]), int(server_protocol[7])
        if sp[0] != rp[0]:
          yield self.simple_response("505 HTTP Version Not Supported")
          return
        # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
        ENVIRON["SERVER_PROTOCOL"] = req_protocol
        self.response_protocol = "HTTP/%s.%s" % min(rp, sp)

        # If the Request-URI was an absoluteURI, use its location atom.
        if location:
          ENVIRON["SERVER_NAME"] = location

        # then all the http headers
        try:
          while True:
            line = yield self.connfh.readline()

            if line == '\r\n':
              # Normal end of headers
              break

            if line[0] in ' \t':
              # It's a continuation line.
              v = line.strip()
            else:
              k, v = line.split(":", 1)
              k, v = k.strip().upper(), v.strip()
              envname = "HTTP_" + k.replace("-", "_")

            if k in comma_separated_headers:
              existing = ENVIRON.get(envname)
              if existing:
                v = ", ".join((existing, v))
            ENVIRON[envname] = v

          ct = ENVIRON.pop("HTTP_CONTENT_TYPE", None)
          if ct:
            ENVIRON["CONTENT_TYPE"] = ct
          cl = ENVIRON.pop("HTTP_CONTENT_LENGTH", None)
          if cl:
            ENVIRON["CONTENT_LENGTH"] = cl
        except ValueError, ex:
          yield self.simple_response("400 Bad Request", repr(ex.args))
          return

        creds = ENVIRON.get("HTTP_AUTHORIZATION", "").split(" ", 1)
        ENVIRON["AUTH_TYPE"] = creds[0]
        if creds[0].lower() == 'basic':
          user, pw = base64.decodestring(creds[1]).split(":", 1)
          ENVIRON["REMOTE_USER"] = user

        # Persistent connection support
        if req_protocol == "HTTP/1.1":
          if ENVIRON.get("HTTP_CONNECTION", "") == "close":
            self.close_connection = True
        else:
          # HTTP/1.0
          if ENVIRON.get("HTTP_CONNECTION", "").lower() != "keep-alive":
            self.close_connection = True


        # Transfer-Encoding support
        te = None
        if self.response_protocol == "HTTP/1.1":
          te = ENVIRON.get("HTTP_TRANSFER_ENCODING")
          if te:
            te = [x.strip().lower() for x in te.split(",") if x.strip()]


        if te:
          # reject transfer encodings for now
          yield self.simple_response("501 Unimplemented")
          self.close_connection = True
          return
        ENV_COGEN_PROXY = ENVIRON['cogen.wsgi'] = async.COGENProxy(
          content_length = int(ENVIRON.get('CONTENT_LENGTH', None) or 0) or None,
          read_count = 0,
          operation = None,
          result = None,
          exception = None
        )
        ENVIRON['cogen.http_connection'] = self
        ENVIRON['cogen.core'] = async.COGENOperationWrapper(
          ENV_COGEN_PROXY,
          core
        )
        ENVIRON['cogen.call'] = async.COGENCallWrapper(ENV_COGEN_PROXY)
        ENVIRON['cogen.input'] = async.COGENOperationWrapper(
          ENV_COGEN_PROXY,
          self.connfh
        )
        ENVIRON['cogen.yield'] = async.COGENSimpleWrapper(ENV_COGEN_PROXY)
        response = self.wsgi_app(ENVIRON, self.start_response)
        #~ print 'WSGI RESPONSE:', response
        try:
          if isinstance(response, WSGIFileWrapper):
            # set tcp_cork to pack the header with the file data
            if hasattr(socket, "TCP_CORK"):
              self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)

            assert self.started_response, "App returned the wsgi.file_wrapper but didn't call start_response."
            assert not self.sent_headers

            self.sent_headers = True
            yield sockets.SendAll(self.conn,
                    self.render_headers()+self.write_buffer.getvalue()
            )

            offset = response.filelike.tell()
            if self.chunked_write:
              fsize = os.fstat(response.filelike.fileno()).st_size
              yield sockets.SendAll(self.conn, hex(int(fsize-offset))+"\r\n")
            yield self.conn.sendfile(
              response.filelike,
              blocksize=response.blocksize,
              offset=offset,
              length=self.content_length,
              timeout=self.sendfile_timeout
            )

            if self.chunked_write:
              yield sockets.SendAll(self.conn, "\r\n")
            #  also, tcp_cork will make the file data sent on packet boundaries,
            # wich is a good thing
            if hasattr(socket, "TCP_CORK"):
              self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0)

          else:
            for chunk in response:
              if chunk:
                assert self.started_response, "App sended a value but hasn't called start_response."
                if not self.sent_headers:
                  self.sent_headers = True
                  headers = [self.render_headers(), self.write_buffer.getvalue()]
                else:
                  headers = []
                if self.chunked_write:
                  buf = [hex(len(chunk))[2:], "\r\n", chunk, "\r\n"]
                  if headers:
                    headers.extend(buf)
                    yield sockets.SendAll(self.conn, "".join(headers))
                  else:
                    yield sockets.SendAll(self.conn, "".join(buf))
                else:
                  if headers:
                    headers.append(chunk)
                    yield sockets.SendAll(self.conn, "".join(headers))
                  else:
                    yield sockets.SendAll(self.conn, chunk)
              else:
                if self.started_response:
                  if not self.sent_headers:
                    self.sent_headers = True
                    yield sockets.SendAll(self.conn,
                          self.render_headers()+self.write_buffer.getvalue())
                if ENV_COGEN_PROXY.operation:
                  op = ENV_COGEN_PROXY.operation
                  ENV_COGEN_PROXY.operation = None
                  try:
                    #~ print 'WSGI OP:', op
                    ENV_COGEN_PROXY.exception = None
                    ENV_COGEN_PROXY.result = yield op
                    #~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result
                  except:
                    #~ print 'WSGI OP EXCEPTION:', sys.exc_info()
                    ENV_COGEN_PROXY.exception = sys.exc_info()
                    ENV_COGEN_PROXY.result = ENV_COGEN_PROXY.exception[1]
                  del op
        finally:
          if hasattr(response, 'close'):
            response.close()

        if self.started_response:
          if not self.sent_headers:
            self.sent_headers = True
            yield sockets.SendAll(self.conn,
              self.render_headers()+self.write_buffer.getvalue()
            )
        else:
          import warnings
          warnings.warn("App was consumed and hasn't called start_response")

        if self.chunked_write:
          yield sockets.SendAll(self.conn, "0\r\n\r\n")
        if self.close_connection:
          return
        # TODO: consume any unread data

    except (socket.error, OSError, pywinerror), e:
      errno = e.args[0]
      if errno not in useless_socket_errors:
        yield self.simple_response("500 Internal Server Error",
                    format_exc())
      return
    except (OperationTimeout, ConnectionClosed, SocketError):
      return
    except (KeyboardInterrupt, SystemExit, GeneratorExit, MemoryError):
      raise
    except:
      if not self.started_response:
        yield self.simple_response(
          "500 Internal Server Error",
          format_exc()
        )
      else:
        print "*" * 60
        traceback.print_exc()
        print "*" * 60
      sys.exc_clear()
    finally:
      self.conn.close()
      ENVIRON = self.environ = None
55193
def run(self):
        """"""
        ret = eventlet.spawn(self.context(self.func))
        eventlet.sleep(self.seconds)
        try:
            ret.wait()
        except Exception:  # pylint: disable=broad-except
            traceback.print_exc()
        self.thread = eventlet.spawn(self.run)
1256581
def run():
    """"""
    parser = OptionParser(version='%prog {0}'.format(__version__))
    parser.add_option('-a', '--addr', default='localhost',
                      help=('The address or host to listen on. Specify -a '
                            '0.0.0.0 to listen on all addresses. '
                            'Default: localhost'))
    parser.add_option('-p', '--port', type='int', default='10101',
                      help=('The port to listen for requests on. '
                            'Default: 10101'))
    options, _ = parser.parse_args()
    try:
        server = ThreadingTCPServer((options.addr, options.port),
                                    RequestHandler)
    except (socket.error, socket.gaierror) as exc:  # Handle bind errors
        print(exc)
        sys.exit(1)
    print('Listening on {0} port {1}'.format(options.addr, options.port))
    try:
        server.serve_forever()  # pylint: disable=E1101
    except KeyboardInterrupt:
        server.socket.close()  # pylint: disable=E1101
        RequestHandler.http.close()
        print('Goodbye!')
564438
def _run_callbacks(self):
        """"""
        for i in range(len(self._callbacks)):
            callback, args = self._callbacks.popleft()
            try:
                callback(*args)
            except Exception:
                self._log.exception('Ignoring exception in callback:')
218786
def run(self, order=None):
    
    for event in self.runner.run(order=order):
      self.receive(event)
132007
def wraps_with_context(func, context):
    """"""
    wrapped = functools.partial(func, context)
    wrapped = functools.wraps(func)(wrapped)
    if asyncio.iscoroutinefunction(func):
        wrapped = asyncio.coroutine(wrapped)
    return wrapped
1113955
def run(addr, *commands, **kwargs):
    
    results = []
    handler = VarnishHandler(addr, **kwargs)
    for cmd in commands:
        if isinstance(cmd, tuple) and len(cmd)>1:
            results.extend([getattr(handler, c[0].replace('.','_'))(*c[1:]) for c in cmd])
        else:
            results.append(getattr(handler, cmd.replace('.','_'))(*commands[1:]))
            break
    handler.close()
    return results
1347817
def wrap(function, *args, **kwargs):
    ''''''
    try:
        req = function(*args, **kwargs)
        logger.debug('Got %s: %s', req.status_code, req.content)
        if req.status_code == 200:
            return req
        else:
            raise ClientException(req.reason, req.content)
    except ClientException:
        raise
    except Exception as exc:
        raise ClientException(exc)
25468
def run(self):
        """"""
        while (self._run_thread):
            (mode, version, packet) = self._read_packet()
            if (mode == PROP_PACKET_SENSE):
                self._decode_sense_packet(version, packet)
            elif (mode == PROP_PACKET_CTRL):
                self._decode_ctrl_packet(version, packet)
402397
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type="auto"):
    """"""
    import signal

    reloader = reloader_loops[reloader_type](extra_files, interval)
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
    try:
        if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
            ensure_echo_on()
            t = threading.Thread(target=main_func, args=())
            t.setDaemon(True)
            t.start()
            reloader.run()
        else:
            sys.exit(reloader.restart_with_reloader())
    except KeyboardInterrupt:
        pass
664116
def new_run(self):
        """"""
        self.current_run += 1
        self.runs.append(RunData(self.current_run + 1))
889868
public Runnable wrap(Throwing.Runnable runnable) {
		return () -> {
			try {
				runnable.run();
			} catch (Throwable e) {
				handler.accept(e);
			}
		};
	}
166799
def run(self):
        """"""
        for wsock in self.wsocks:
            wsock.run()
        for api in self.apis:
            api.run()
5212
def wrap_submit(submit_func):
    """"""

    def call(self, func, *args, **kwargs):
        wrapped_func = wrap_task_func(func)
        _tracer = execution_context.get_opencensus_tracer()
        propagator = binary_format.BinaryFormatPropagator()

        wrapped_kwargs = {}
        wrapped_kwargs["span_context_binary"] = propagator.to_header(
            _tracer.span_context
        )
        wrapped_kwargs["kwds"] = kwargs
        wrapped_kwargs["sampler"] = _tracer.sampler
        wrapped_kwargs["exporter"] = _tracer.exporter
        wrapped_kwargs["propagator"] = _tracer.propagator

        return submit_func(self, wrapped_func, *args, **wrapped_kwargs)

    return call
575411
def _run_pants(self, sock, arguments, environment):
    """"""
    self.server.runner_factory(sock, arguments, environment).run()