Exemplo n.º 1
0
def index(request):
    """
    Index page: decide which way to redirect (or what to display according to the login and permission status of the
    current session.
    If the current session has no attached user, or in other words, the user is anonymous, he will be redirected to the
     blog page, which is the only place he has access to.
    If the user is a superuser, an index page of all different apps is presented, for he has access to go anywhere.
    """
    if not request.user.is_authenticated:
        return redirect('blog-content', path='')
    if request.user.is_superuser:
        context = dict()
        try:
            context['uwsgi'] = {
                'proc_num': uwsgi.numproc,
                'workers': uwsgi.workers(),
                'started_on': datetime.fromtimestamp(uwsgi.started_on),
                'master_pid': uwsgi.masterpid(),
                'buffer_size': uwsgi.buffer_size
            }
        except NameError:
            pass
        platform = uname()
        context['system'] = {
            'system': platform.system + ' ' + platform.release,
            'version': platform.version,
            'machine': platform.node,
            'architecture': platform.machine,
            'processor': platform.processor
        }
        return render(request, 'index.html', context)
Exemplo n.º 2
0
    def content(self):
        try:
            import uwsgi
        except ImportError:
            return render_to_string('uwsgi_admin/uwsgi_panel.html', {'unavailable': True})
            
        workers = uwsgi.workers()
        total_load = time.time() - uwsgi.started_on
        for w in workers:
            w['load'] = (100 * (w['running_time'] / 1000)) / total_load
            w['last_spawn_str'] = time.ctime(w['last_spawn'])

        jobs = []
        if 'spooler' in uwsgi.opt:
            spooler_jobs = uwsgi.spooler_jobs()
            for j in spooler_jobs:
                jobs.append({'file': j, 'env': uwsgi.parsefile(j)})
        context = self.context.copy()
        context.update(csrf(self.request))
        context.update({
            'masterpid': uwsgi.masterpid(),
            'started_on': time.ctime(uwsgi.started_on),
            'buffer_size': uwsgi.buffer_size,
            'total_requests': uwsgi.total_requests(),
            'numproc': uwsgi.numproc,
            'workers': workers,
            'jobs': jobs,
        })
        return render_to_string('uwsgi_admin/uwsgi_panel.html', context)
def test_uwsgi_collector():
    registry = BaseRegistry()
    uwsgi_collector = UWSGICollector(namespace="uwsgi_namespace",
                                     labels={"env_role": "test"})

    registry.register(uwsgi_collector)

    collectors = {x.name: x for x in registry.collect()}

    metrics_count = sorted(
        map(
            lambda x: x.split(" ")[2],
            filter(lambda x: x.startswith("# HELP"),
                   [x for x in registry_to_text(registry).split("\n")])))

    assert len(metrics_count) == len(set(metrics_count))

    assert len(registry_to_text(registry).split("\n")) == 60

    assert collectors["uwsgi_namespace:buffer_size_bytes"].get_samples(
    )[0].value == uwsgi.buffer_size
    assert collectors["uwsgi_namespace:processes_total"].get_samples(
    )[0].value == uwsgi.numproc
    assert collectors["uwsgi_namespace:requests_total"].get_samples(
    )[0].value == uwsgi.total_requests()

    for name in [
            "requests", "respawn_count", "running_time", "exceptions",
            "delta_requests"
    ]:
        assert collectors["uwsgi_namespace:process:{0}".format(
            name)].get_samples()[0].value == uwsgi.workers()[0][name]

    assert uwsgi_collector.metric_name("test") == "uwsgi_namespace:test"
Exemplo n.º 4
0
    def content(self):
        workers = uwsgi.workers()
        total_load = time.time() - uwsgi.started_on
        for w in workers:
            w["load"] = (100 * (w["running_time"] / 1000)) / total_load
            w["last_spawn_str"] = time.ctime(w["last_spawn"])

        jobs = []
        if "spooler" in uwsgi.opt:
            spooler_jobs = uwsgi.spooler_jobs()
            for j in spooler_jobs:
                jobs.append({"file": j, "env": uwsgi.parsefile(j)})
        context = self.context.copy()
        context.update(
            {
                "masterpid": uwsgi.masterpid(),
                "started_on": time.ctime(uwsgi.started_on),
                "buffer_size": uwsgi.buffer_size,
                "total_requests": uwsgi.total_requests(),
                "numproc": uwsgi.numproc,
                "workers": workers,
                "jobs": jobs,
            }
        )
        return render_to_string("uwsgi_admin/uwsgi_panel.html", context)
Exemplo n.º 5
0
def reload(env, start_response):

    start_response('200 OK', [('Content-Type', 'text/html')])

    #uwsgi.sorry_i_need_to_block()
    #time.sleep(1)

    #uwsgi.reload()

#    print str(uwsgi.masterpid()) + "\n"

#    print "i am python"
    #yo()

#    yield "python"

    #print 4/0

#    yield str(uwsgi.masterpid())

    #print uwsgi.pippo

    #print 4/0
#    try:
#        print 4/0
#
#        print uwsgi.pippo
#    except:
#        print "bah"

#    print "ok"

#    yield 4/0

    yield '<h1>uWSGI status ('+env['SCRIPT_NAME']+')</h1>';
    yield 'masterpid: <b>' + str(uwsgi.masterpid()) + '</b><br/>'

    yield 'started on: <b>' + time.ctime(uwsgi.started_on) + '</b><br/>'

    yield 'buffer size: <b>' + str(uwsgi.buffer_size) + '</b><br/>'

    yield 'total_requests: <b>' + str(uwsgi.total_requests()) + '</b><br/>'

    yield 'workers: <b>' + str(uwsgi.numproc) + '</b><br/>'

    yield '<table border="1">'
    yield '<th>worker id</th><th>pid</th><th>in request</th><th>requests</th><th>running time</th><th>address space</th><th>rss</th>'

    workers = uwsgi.workers();

    yield '<h2>workers</h2>'

    for w in workers:
        #print w
        #print w['running_time']
        if w is not None:
            yield '<tr><td>'+ str(w['id']) +'</td><td>' + str(w['pid']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(w['requests']) + '</td><td>' + str(w['running_time']) + '</td><td>' + str(w['vsz']) + '</td><td>' + str(w['rss']) + '</td></tr>'
            print w

    yield '</table>'
Exemplo n.º 6
0
def reload(env, start_response):

    start_response('200 OK', [('Content-Type', 'text/html')])

    #uwsgi.sorry_i_need_to_block()
    #time.sleep(1)

    #uwsgi.reload()

#    print(str(uwsgi.masterpid()) + "\n")

#    print("i am python")
    #yo()

#    yield "python"

    #print 4/0

#    yield str(uwsgi.masterpid())

    #print(uwsgi.pippo)

    #print 4/0
#    try:
#        print 4/0
#
#        print uwsgi.pippo
#    except Exception:
#        print "bah"

#    print("ok")

#    yield 4/0

    yield '<h1>uWSGI status ('+env['SCRIPT_NAME']+')</h1>'
    yield 'masterpid: <b>' + str(uwsgi.masterpid()) + '</b><br/>'

    yield 'started on: <b>' + time.ctime(uwsgi.started_on) + '</b><br/>'

    yield 'buffer size: <b>' + str(uwsgi.buffer_size) + '</b><br/>'

    yield 'total_requests: <b>' + str(uwsgi.total_requests()) + '</b><br/>'

    yield 'workers: <b>' + str(uwsgi.numproc) + '</b><br/>'

    yield '<table border="1">'
    yield '<th>worker id</th><th>pid</th><th>in request</th><th>requests</th><th>running time</th><th>address space</th><th>rss</th>'

    workers = uwsgi.workers()

    yield '<h2>workers</h2>'

    for w in workers:
        #print(w)
        #print(w['running_time'])
        if w is not None:
            yield '<tr><td>' + str(w['id']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(w['requests']) + '</td><td>' + str(w['running_time']) + '</td><td>' + str(w['vsz']) + '</td><td>' + str(w['rss']) + '</td></tr>'
            print(w)

    yield '</table>'
Exemplo n.º 7
0
def uwsgi_context(request):
    try:
        # noinspection PyPackageRequirements
        import uwsgi

        return {
            'UWSGI': {
                'enabled': True,
                'numproc': uwsgi.numproc,
                'buffer_size': uwsgi.buffer_size,
                'started_on': datetime.fromtimestamp(uwsgi.started_on, tz=utc),
                'numworkers': len(uwsgi.workers()),
                'masterpid': uwsgi.masterpid(),
                'total_requests': uwsgi.total_requests(),
                'request_id': uwsgi.request_id(),
                'worker_id': uwsgi.worker_id(),
            }
        }

    except ImportError:
        return {
            'UWSGI': {
                'enabled': False,
            }
        }
Exemplo n.º 8
0
def info():
    if not have_uwsgi:
        return "you aren't running web2py with uwsgi"
    info = Storage()
    info.masterpid = uwsgi.masterpid()
    info.version = uwsgi.version
    info.started_on = time.ctime(uwsgi.started_on)
    info.buffer_size = uwsgi.buffer_size
    info.total_requests = uwsgi.total_requests()
    info.logsize = uwsgi.logsize()
    info.numproc = uwsgi.numproc
    try:
        info.mode = uwsgi.mode
    except:
        pass
    try:
        info.pidfile = uwsgi.pidfile
    except:
        pass
    
    workers = uwsgi.workers()
    total_load = time.time() - uwsgi.started_on
    for w in workers:
        w['load'] = (100 * (w['running_time']/1000))/total_load
        w['last_spawn_str'] = time.ctime(w['last_spawn'])
        w['vsz_str'] = do_filesizeformat(w['vsz'])
        w['rss_str'] = do_filesizeformat(w['rss'])
    
    context = dict(info=info, workers=workers)
    template = template_view('info')
    return response.render(template, context)
Exemplo n.º 9
0
    def content(self):
        try:
            import uwsgi
        except ImportError:
            return render_to_string('uwsgi_admin/uwsgi_panel.html',
                                    {'unavailable': True})

        workers = uwsgi.workers()
        total_load = time.time() - uwsgi.started_on
        for w in workers:
            w['load'] = (100 * (w['running_time'] / 1000)) / total_load
            w['last_spawn_str'] = time.ctime(w['last_spawn'])

        jobs = []
        if 'spooler' in uwsgi.opt:
            spooler_jobs = uwsgi.spooler_jobs()
            for j in spooler_jobs:
                jobs.append({'file': j, 'env': uwsgi.parsefile(j)})
        context = self.context.copy()
        context.update(csrf(self.request))
        context.update({
            'masterpid': uwsgi.masterpid(),
            'started_on': time.ctime(uwsgi.started_on),
            'buffer_size': uwsgi.buffer_size,
            'total_requests': uwsgi.total_requests(),
            'numproc': uwsgi.numproc,
            'workers': workers,
            'jobs': jobs,
        })
        return render_to_string('uwsgi_admin/uwsgi_panel.html', context)
Exemplo n.º 10
0
def info(request):
    context = {"title": "uWSGI is missing"}
    if uwsgi:
        total_time = time.time() - uwsgi.started_on
        workers = uwsgi.workers()

        def extend_worker(worker):
            worker["running_time"] = worker["running_time"] / 1000  # Get running time In miliseconds
            worker["load"] = (
                worker["running_time"] / total_time / 10 / len(workers)
            )  # In percents devided by number of workers
            worker["last_spawn_str"] = time.ctime(worker["last_spawn"])
            return worker

        context.update(
            {
                "title": "uWSGI status",
                "masterpid": uwsgi.masterpid(),
                "started_on": datetime.fromtimestamp(uwsgi.started_on),
                "buffer_size": uwsgi.buffer_size,
                "total_requests": uwsgi.total_requests(),
                "total_time": total_time,
                "numproc": uwsgi.numproc,
                "workers": map(extend_worker, workers),
            }
        )

    return render(request, "django_uwsgi/info.html", context)
Exemplo n.º 11
0
def get_status():
    """Retrieve API specific stats upon successful GET."""
    status = {"worker_status": []}
    for worker in uwsgi.workers():
        del worker["apps"]
        worker["status"] = worker["status"].decode("utf-8")
        status["worker_status"].append(worker)
    status["total_requests"] = uwsgi.total_requests()
    return jsonify(status)
Exemplo n.º 12
0
def uwsgi_info() -> Optional[dict]:
    try:
        import uwsgi
        return {
            'numproc': uwsgi.numproc,
            'worker_id': uwsgi.worker_id(),
            'workers': uwsgi.workers()
        }
    except ImportError:  # we are not under uWSGI
        return {'numproc': 0, 'worker_id': 'N/A', 'workers': []}
Exemplo n.º 13
0
def application(env, start_response):
    gc.collect()
    start_objs = len(gc.get_objects())

    for i in range(200):
        uwsgi.workers()

    gc.collect()
    end_objs = len(gc.get_objects())
    diff_objs = end_objs - start_objs

    # Sometimes there is a spurious diff of 4 objects or so.
    if diff_objs > 10:
        start_response('500 Leaking', [('Content-Type', 'text/plain')])
        yield "Leaking objects...\n".format(diff_objs).encode("utf-8")
    else:
        start_response('200 OK', [('Content-Type', 'text/plain')])

    yield "{} {} {}\n".format(start_objs, end_objs, diff_objs).encode("utf-8")
Exemplo n.º 14
0
def bootstrap():
    import uwsgi
    import os

    uwsgi.lock()
    min_pid = min([w['pid'] for w in uwsgi.workers()])
    if min_pid == os.getpid():
        from oncall.ui import build
        print 'building webassets...'
        build()
    uwsgi.unlock()
Exemplo n.º 15
0
    def collect(self):
        for name, value in [("processes", uwsgi.numproc),
                            ("total_requests", uwsgi.total_requests()),
                            ("buffer_size", uwsgi.buffer_size),
                            ("started_on", uwsgi.started_on),
                            ("cores", uwsgi.cores)]:
            yield self.get_sample(name, value)

        yield self.get_memory_samples()

        for x in self.get_workers_samples(uwsgi.workers()):
            yield x
Exemplo n.º 16
0
def uwsgi_worker_reload(worker_id):
    import uwsgi
    pid = None
    for worker in uwsgi.workers():
        if worker["id"] == int(worker_id):
            pid = worker["pid"]
    if not pid:
        response = "Worker {} doesn't exists".format(worker_id)
    else:
        os.kill(pid, signal.SIGINT)
        response = "Worker {} reloaded".format(worker_id)
    return render_template("empty.html", info=response)
Exemplo n.º 17
0
def index(request):
	workers = uwsgi.workers()
	total_load = time.time() - uwsgi.started_on
	for w in workers:
		w['load'] = (100 * (w['running_time']/1000))/total_load
		w['last_spawn_str'] = time.ctime(w['last_spawn'])

	return render_to_response('uwsgi.html', {'masterpid': uwsgi.masterpid(),
						'started_on': time.ctime(uwsgi.started_on),
						'buffer_size': uwsgi.buffer_size,
						'total_requests': uwsgi.total_requests(),
						'numproc': uwsgi.numproc,
						'workers': workers,
						}, RequestContext(request, {}))
Exemplo n.º 18
0
def all_control_queues_for_declare(config):
    """
    For in-memory routing (used by sqlalchemy-based transports), we need to be able to
    build the entire routing table in producers.

    Refactor later to actually persist this somewhere instead of building it repeatedly.
    """
    possible_uwsgi_queues = []
    if process_is_uwsgi:
        import uwsgi
        possible_uwsgi_queues = [
            Queue("control.%s.%s" %
                  (config.server_name.split('.')[0], wkr['id']),
                  galaxy_exchange,
                  routing_key='control') for wkr in uwsgi.workers()
        ]
    return possible_uwsgi_queues + [
        Queue('control.%s' % q, galaxy_exchange, routing_key='control')
        for q in config.server_names
    ]
Exemplo n.º 19
0
def index(request):
	workers = uwsgi.workers()
	total_load = time.time() - uwsgi.started_on
	for w in workers:
		w['load'] = (100 * (w['running_time']/1000))/total_load
		w['last_spawn_str'] = time.ctime(w['last_spawn'])

	jobs = []
        if 'spooler' in uwsgi.opt:
	    spooler_jobs = uwsgi.spooler_jobs()
	    for j in spooler_jobs:
	        jobs.append({'file': j, 'env': uwsgi.parsefile(j)})

	return render_to_response('uwsgi.html', {'masterpid': uwsgi.masterpid(),
						'started_on': time.ctime(uwsgi.started_on),
						'buffer_size': uwsgi.buffer_size,
						'total_requests': uwsgi.total_requests(),
						'numproc': uwsgi.numproc,
						'workers': workers,
						'jobs': jobs,
						}, RequestContext(request, {}))
Exemplo n.º 20
0
def index(request):
    try:
        import uwsgi
    except ImportError:
        return render(request, 'uwsgi_admin/uwsgi.html', {
            'unavailable': True
        })

    workers = uwsgi.workers()
    total_load = time.time() - uwsgi.started_on
    for w in workers:
        w['running_time'] = w['running_time'] / 1000
        w['load'] = w['running_time'] / total_load / 10 / len(workers)
        w['last_spawn'] = datetime.fromtimestamp(w['last_spawn'])

    jobs = []
    if 'spooler' in uwsgi.opt:
        spooler_jobs = uwsgi.spooler_jobs()
        for j in spooler_jobs:
            jobs.append({'file': j, 'env': uwsgi.parsefile(j)})

    return render(request, 'uwsgi_admin/uwsgi.html', {
        'masterpid': uwsgi.masterpid(),
        'stats': [
            ('masterpid', str(uwsgi.masterpid())),
            ('started_on', datetime.fromtimestamp(uwsgi.started_on)),
            ('now', datetime.now()),
            ('buffer_size', uwsgi.buffer_size),
            ('total_requests', uwsgi.total_requests()),
            ('numproc', uwsgi.numproc),
            ('cores', uwsgi.cores),
            ('spooler pid', uwsgi.spooler_pid()
                            if uwsgi.opt.get('spooler')
                            else 'disabled'),
            ('threads', 'enabled' if uwsgi.has_threads else 'disabled')
        ],
        'options': uwsgi.opt.items(),
        'workers': workers,
        'jobs': jobs,
    })
Exemplo n.º 21
0
def application(env, start_response):
    gc.collect()
    start_objs = len(gc.get_objects())

    for i in range(200):
        workers = uwsgi.workers()
        assert workers, "none/empty uwsgi.workers() - " + repr(workers)
        for w in workers:
            assert w["apps"], "none/empty apps in worker dict: " + repr(w)

    gc.collect()
    end_objs = len(gc.get_objects())
    diff_objs = end_objs - start_objs

    # Sometimes there is a spurious diff of 4 objects or so.
    if diff_objs > 10:
        start_response('500 Leaking', [('Content-Type', 'text/plain')])
        yield "Leaking objects...\n".encode("utf-8")
    else:
        start_response('200 OK', [('Content-Type', 'text/plain')])

    yield "{} {} {}\n".format(start_objs, end_objs, diff_objs).encode("utf-8")
Exemplo n.º 22
0
def index(request):
    try:
        import uwsgi
    except ImportError:
        return render(request, 'uwsgi_admin/uwsgi.html', {'unavailable': True})

    workers = uwsgi.workers()
    total_load = time.time() - uwsgi.started_on
    for w in workers:
        w['running_time'] = w['running_time'] / 1000
        w['load'] = w['running_time'] / total_load / 10 / len(workers)
        w['last_spawn'] = datetime.fromtimestamp(w['last_spawn'])

    jobs = []
    if 'spooler' in uwsgi.opt:
        spooler_jobs = uwsgi.spooler_jobs()
        for j in spooler_jobs:
            jobs.append({'file': j, 'env': uwsgi.parsefile(j)})

    return render(
        request, 'uwsgi_admin/uwsgi.html', {
            'masterpid':
            uwsgi.masterpid(),
            'stats':
            [('masterpid', str(uwsgi.masterpid())),
             ('started_on', datetime.fromtimestamp(uwsgi.started_on)),
             ('now', datetime.now()), ('buffer_size', uwsgi.buffer_size),
             ('total_requests', uwsgi.total_requests()),
             ('numproc', uwsgi.numproc), ('cores', uwsgi.cores),
             ('spooler pid',
              uwsgi.spooler_pid() if uwsgi.opt.get('spooler') else 'disabled'),
             ('threads', 'enabled' if uwsgi.has_threads else 'disabled')],
            'options':
            uwsgi.opt.items(),
            'workers':
            workers,
            'jobs':
            jobs,
        })
Exemplo n.º 23
0
def uwsgi_pypy_current_wsgi_req():
    wsgi_req = lib.uwsgi.current_wsgi_req()
    if wsgi_req == ffi.NULL:
        raise Exception("unable to get current wsgi_request, check your setup !!!")
    return wsgi_req

"""
uwsgi.suspend()
"""
def uwsgi_pypy_suspend():
    wsgi_req = uwsgi_pypy_current_wsgi_req()
    if lib.uwsgi.schedule_to_main:
        lib.uwsgi.schedule_to_main(wsgi_req);
uwsgi.suspend = uwsgi_pypy_suspend

"""
uwsgi.workers()
"""
def uwsgi_pypy_workers():
    workers = []
    for i in range(1, lib.uwsgi.numproc+1):
        worker = {}
        worker['id'] = lib.uwsgi.workers[i].id
        worker['pid'] = lib.uwsgi.workers[i].pid
        worker['requests'] = lib.uwsgi.workers[i].requests
        worker['delta_requests'] = lib.uwsgi.workers[i].delta_requests
        worker['signals'] = lib.uwsgi.workers[i].signals
        worker['exceptions'] = lib.uwsgi_worker_exceptions(i);
        worker['apps'] = []
        if lib.uwsgi.workers[i].cheaped:
            worker['status'] == 'cheap'
Exemplo n.º 24
0
def all_control_queues_for_declare(config):
    """
    For in-memory routing (used by sqlalchemy-based transports), we need to be able to
    build the entire routing table in producers.

    Refactor later to actually persist this somewhere instead of building it repeatedly.
    """
    possible_uwsgi_queues = []
    if config.is_uwsgi:
        import uwsgi
        possible_uwsgi_queues = [Queue("control.%s.%s" % (config.server_name.split('.')[0], wkr['id']), galaxy_exchange, routing_key='control') for wkr in uwsgi.workers()]
    return possible_uwsgi_queues + [Queue('control.%s' % q, galaxy_exchange, routing_key='control') for q in config.server_names]
Exemplo n.º 25
0
def reload(env, start_response):

    start_response('200 OK', [('Content-Type', 'text/html')])

    #uwsgi.sorry_i_need_to_block()
    #time.sleep(1)

    #uwsgi.reload()

#    print str(uwsgi.masterpid()) + "\n"

#    print "i am python"
    #yo()

#    yield "python"

    #print 4/0

#    yield str(uwsgi.masterpid())

    #print uwsgi.pippo

    #print 4/0
#    try:
#        print 4/0
#
#        print uwsgi.pippo
#    except:
#        print "bah"

#    print "ok"

#    yield 4/0

    yield '<h1>uWSGI status ('+env['SCRIPT_NAME']+')</h1>';
    yield 'masterpid: <b>' + str(uwsgi.masterpid()) + '</b><br/>'

    yield 'started on: <b>' + time.ctime(uwsgi.started_on) + '</b><br/>'

    yield 'buffer size: <b>' + str(uwsgi.buffer_size) + '</b><br/>'

    yield 'total_requests: <b>' + str(uwsgi.total_requests()) + '</b><br/>'

    yield 'workers: <b>' + str(uwsgi.numproc) + '</b><br/>'

    yield '<h2>dynamic options</h2>'

    yield '<b>logging</b>: ' + str(uwsgi.get_option(0)) + '<br/>'
    yield '<b>max_requests</b>: '  + str(uwsgi.getoption(1)) + '<br/>'
    yield '<b>socket_timeout</b>: ' + str(uwsgi.getoption(2)) + '<br/>'
    yield '<b>memory_debug</b>: ' + str(uwsgi.getoption(3)) + '<br/>'
    yield '<b>master_interval</b>: ' + str(uwsgi.getoption(4)) + '<br/>'
    yield '<b>harakiri</b>: ' + str(uwsgi.getoption(5)) + '<br/>'
    yield '<b>cgi_mode</b>: ' + str(uwsgi.get_option(6)) + '<br/>'
    yield '<b>threads</b>: ' + str(uwsgi.get_option(7)) + '<br/>'
    yield '<b>process_reaper</b>: ' + str(uwsgi.get_option(8)) + '<br/>'

    yield '<table border="1">'
    yield '<th>worker id</th><th>pid</th><th>in request</th><th>requests</th><th>running time</th><th>address space</th><th>rss</th>'

    workers = uwsgi.workers();

    yield '<h2>workers</h2>'

    for w in workers:
        #print w
        #print w['running_time']
        if w is not None:
            yield '<tr><td>'+ str(w['id']) +'</td><td>' + str(w['pid']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(w['requests']) + '</td><td>' + str(w['running_time']) + '</td><td>' + str(w['vsz']) + '</td><td>' + str(w['rss']) + '</td></tr>'
            print w

    yield '</table>'
Exemplo n.º 26
0
 def workers(self):
     return uwsgi.workers()
Exemplo n.º 27
0
def uwsgi_pypy_current_wsgi_req():
    wsgi_req = lib.uwsgi.current_wsgi_req()
    if wsgi_req == ffi.NULL:
        raise Exception("unable to get current wsgi_request, check your setup !!!")
    return wsgi_req

"""
uwsgi.suspend()
"""
def uwsgi_pypy_suspend():
    wsgi_req = uwsgi_pypy_current_wsgi_req()
    if lib.uwsgi.schedule_to_main:
        lib.uwsgi.schedule_to_main(wsgi_req);
uwsgi.suspend = uwsgi_pypy_suspend

"""
uwsgi.workers()
"""
def uwsgi_pypy_workers():
    workers = []
    for i in range(1, lib.uwsgi.numproc+1):
        worker = {}
        worker['id'] = lib.uwsgi.workers[i].id
        worker['pid'] = lib.uwsgi.workers[i].pid
        worker['requests'] = lib.uwsgi.workers[i].requests
        worker['delta_requests'] = lib.uwsgi.workers[i].delta_requests
        worker['signals'] = lib.uwsgi.workers[i].signals
        worker['exceptions'] = lib.uwsgi_worker_exceptions(i);
        worker['apps'] = []
        if lib.uwsgi.workers[i].cheaped:
            worker['status'] == 'cheap'
Exemplo n.º 28
0
def application(env, start_response):

    try:
        uwsgi.mule_msg(env["REQUEST_URI"], 1)
    except:
        pass

    req = uwsgi.workers()[uwsgi.worker_id() - 1]["requests"]

    uwsgi.setprocname("worker %d managed %d requests" % (uwsgi.worker_id(), req))

    gc.collect(2)
    if DEBUG:
        print(env["wsgi.input"].fileno())

    if routes.has_key(env["PATH_INFO"]):
        return routes[env["PATH_INFO"]](env, start_response)

    start_response("200 OK", [("Content-Type", "text/html")])

    if DEBUG:
        print(env["wsgi.input"].fileno())

    gc.collect(2)

    if DEBUG:
        print(len(gc.get_objects()))

    workers = ""
    for w in uwsgi.workers():
        apps = '<table border="1"><tr><th>id</th><th>mountpoint</th><th>requests</th></tr>'
        for app in w["apps"]:
            apps += "<tr><td>%d</td><td>%s</td><td>%d</td></tr>" % (app["id"], app["mountpoint"], app["requests"])
        apps += "</table>"
        workers += """
<tr>
<td>%d</td><td>%d</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td>
</tr>
        """ % (
            w["id"],
            w["pid"],
            w["status"],
            w["running_time"] / 1000,
            w["avg_rt"] / 1000,
            w["tx"],
            apps,
        )

    return """
<img src="/logo"/> version %s<br/>
<hr size="1"/>

Configuration<br/>
<iframe src="/config"></iframe><br/>

<br/>

Dynamic options<br/>
<iframe src="/options"></iframe><br/>

<br/>
Workers and applications<br/>
<table border="1">
<tr>
<th>wid</th><th>pid</th><th>status</th><th>running time</th><th>average</th><th>tx</th><th>apps</th>
</tr>
%s
</table>

    """ % (
        uwsgi.version,
        workers,
    )
Exemplo n.º 29
0
def reload(env, start_response):

    start_response('200 OK', [('Content-Type', 'text/html')])

    #uwsgi.sorry_i_need_to_block()
    #time.sleep(1)

    #uwsgi.reload()

    #    print str(uwsgi.masterpid()) + "\n"

    #    print "i am python"
    #yo()

    #    yield "python"

    #print 4/0

    #    yield str(uwsgi.masterpid())

    #print uwsgi.pippo

    #print 4/0
    #    try:
    #        print 4/0
    #
    #        print uwsgi.pippo
    #    except:
    #        print "bah"

    #    print "ok"

    #    yield 4/0

    yield '<h1>uWSGI status (' + env['SCRIPT_NAME'] + ')</h1>'
    yield 'masterpid: <b>' + str(uwsgi.masterpid()) + '</b><br/>'

    yield 'started on: <b>' + time.ctime(uwsgi.started_on) + '</b><br/>'

    yield 'buffer size: <b>' + str(uwsgi.buffer_size) + '</b><br/>'

    yield 'total_requests: <b>' + str(uwsgi.total_requests()) + '</b><br/>'

    yield 'workers: <b>' + str(uwsgi.numproc) + '</b><br/>'

    yield '<h2>dynamic options</h2>'

    yield '<b>logging</b>: ' + str(uwsgi.get_option(0)) + '<br/>'
    yield '<b>max_requests</b>: ' + str(uwsgi.getoption(1)) + '<br/>'
    yield '<b>socket_timeout</b>: ' + str(uwsgi.getoption(2)) + '<br/>'
    yield '<b>memory_debug</b>: ' + str(uwsgi.getoption(3)) + '<br/>'
    yield '<b>master_interval</b>: ' + str(uwsgi.getoption(4)) + '<br/>'
    yield '<b>harakiri</b>: ' + str(uwsgi.getoption(5)) + '<br/>'
    yield '<b>cgi_mode</b>: ' + str(uwsgi.get_option(6)) + '<br/>'
    yield '<b>threads</b>: ' + str(uwsgi.get_option(7)) + '<br/>'
    yield '<b>process_reaper</b>: ' + str(uwsgi.get_option(8)) + '<br/>'

    yield '<table border="1">'
    yield '<th>worker id</th><th>pid</th><th>in request</th><th>requests</th><th>running time</th><th>address space</th><th>rss</th>'

    workers = uwsgi.workers()

    yield '<h2>workers</h2>'

    for w in workers:
        #print w
        #print w['running_time']
        if w is not None:
            yield '<tr><td>' + str(w['id']) + '</td><td>' + str(
                w['pid']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(
                    w['requests']) + '</td><td>' + str(
                        w['running_time']) + '</td><td>' + str(
                            w['vsz']) + '</td><td>' + str(
                                w['rss']) + '</td></tr>'
            print w

    yield '</table>'
Exemplo n.º 30
0
import uwsgi
if uwsgi.loop == 'gevent':
    import gevent

print uwsgi.version
print uwsgi.workers()
try:
    uwsgi.cache_set('foo', "Hello World from cache")
except:
    pass


def application(env, start_response):
    print env['wsgi.input'].read()
    if uwsgi.loop == 'gevent':
        gevent.sleep()
    start_response('200 OK', [('Content-Type', 'text/html')])
    yield "foobar<br/>"
    if uwsgi.loop == 'gevent':
        gevent.sleep(3)
    yield str(env['wsgi.input'].fileno())
    yield "<h1>Hello World</h1>"
    try:
        yield uwsgi.cache_get('foo')
    except:
        pass
Exemplo n.º 31
0
 def workers(self):
     return uwsgi.workers()
Exemplo n.º 32
0
import uwsgi
if uwsgi.loop == 'gevent':
    import gevent

print uwsgi.version
print uwsgi.workers()
try:
    uwsgi.cache_set('foo', "Hello World from cache")
except:
    pass
def application(env, start_response):
    if uwsgi.loop == 'gevent':
        gevent.sleep()
    start_response('200 OK', [('Content-Type', 'text/html')])
    yield "foobar<br/>"
    if uwsgi.loop == 'gevent':
        gevent.sleep(10)
    yield str(env['wsgi.input'].fileno())
    yield "<h1>Hello World</h1>"
    try:
        yield uwsgi.cache_get('foo')
    except:
        pass
Exemplo n.º 33
0
def application(env, start_response):
    try:
        uwsgi.mule_msg(env['REQUEST_URI'], 1)
    except:
        pass

    req = uwsgi.workers()[uwsgi.worker_id() - 1]['requests']

    uwsgi.setprocname("worker %d managed %d requests" %
                      (uwsgi.worker_id(), req))

    try:
        gc.collect(2)
    except:
        pass
    if DEBUG:
        print(env['wsgi.input'].fileno())

    if env['PATH_INFO'] in routes:
        return routes[env['PATH_INFO']](env, start_response)

    if DEBUG:
        print(env['wsgi.input'].fileno())

    try:
        gc.collect(2)
    except:
        pass

    if DEBUG:
        print(len(gc.get_objects()))

    workers = ''
    for w in uwsgi.workers():
        apps = '<table border="1"><tr><th>id</th><th>mountpoint</th><th>startup time</th><th>requests</th></tr>'
        for app in w['apps']:
            apps += '<tr><td>%d</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (
                app['id'], app['mountpoint'], app['startup_time'],
                app['requests'])
        apps += '</table>'
        workers += """
<tr>
<td>%d</td><td>%d</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td>
</tr>
        """ % (w['id'], w['pid'], w['status'], w['running_time'] / 1000,
               w['avg_rt'] / 1000, w['tx'], apps)

    output = """
<img src="/logo"/> version %s running on %s (remote user: %s)<br/>
<hr size="1"/>

Configuration<br/>
<iframe src="/config"></iframe><br/>

<br/>
Workers and applications<br/>
<table border="1">
<tr>
<th>wid</th><th>pid</th><th>status</th><th>running time</th><th>average</th><th>tx</th><th>apps</th>
</tr>
%s
</table>

    """ % (uwsgi.version, uwsgi.hostname, env.get('REMOTE_USER',
                                                  'None'), workers)

    start_response('200 OK', [('Content-Type', 'text/html'),
                              ('Content-Length', str(len(output)))])

    # return bytes(output.encode('latin1'))
    return output
Exemplo n.º 34
0
def uwsgi_workers():
    import uwsgi
    target_dict = uwsgi.workers()
    return render_template("empty.html", info=target_dict)
Exemplo n.º 35
0
def application(env, start_response):
    try:
        uwsgi.mule_msg(env['REQUEST_URI'], 1)
    except:
        pass

    req = uwsgi.workers()[uwsgi.worker_id()-1]['requests']

    uwsgi.setprocname("worker %d managed %d requests" % (uwsgi.worker_id(), req))

    try:
        gc.collect(2)
    except:
        pass
    if DEBUG:
        print(env['wsgi.input'].fileno())

    if env['PATH_INFO'] in routes:
        return routes[env['PATH_INFO']](env, start_response)


    if DEBUG:
        print(env['wsgi.input'].fileno())

    try:
        gc.collect(2)
    except:
        pass

    if DEBUG:
        print(len(gc.get_objects()))

    workers = ''
    for w in uwsgi.workers():
        apps = '<table border="1"><tr><th>id</th><th>mountpoint</th><th>startup time</th><th>requests</th></tr>'
        for app in w['apps']:
            apps += '<tr><td>%d</td><td>%s</td><td>%d</td><td>%d</td></tr>' % (app['id'], app['mountpoint'], app['startup_time'], app['requests']) 
        apps += '</table>'
        workers += """
<tr>
<td>%d</td><td>%d</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td>
</tr>
        """ % (w['id'], w['pid'], w['status'], w['running_time']/1000, w['avg_rt']/1000, w['tx'], apps)

    output = """
<img src="/logo"/> version %s running on %s (remote user: %s)<br/>
<hr size="1"/>

Configuration<br/>
<iframe src="/config"></iframe><br/>

<br/>

Dynamic options<br/>
<iframe src="/options"></iframe><br/>

<br/>
Workers and applications<br/>
<table border="1">
<tr>
<th>wid</th><th>pid</th><th>status</th><th>running time</th><th>average</th><th>tx</th><th>apps</th>
</tr>
%s
</table>

    """ % (uwsgi.version, uwsgi.hostname, env.get('REMOTE_USER','None'), workers)

    start_response('200 OK', [('Content-Type', 'text/html'), ('Content-Length', str(len(output)) )])

    #return bytes(output.encode('latin1'))
    return output
Exemplo n.º 36
0
def routing(signum):
    state = getmemorystate()
    current_workers_tasks = state["current_workers_tasks"]
    workers_tasks = state["workers_tasks"]
    # reload
    if state.has_key("stoping"):
        print "seems we are reload"
        print "let's start"
        if not len(current_workers_tasks.keys()):
            print "oo there is no tasks"
            print uwsgi.workers()
            del state["stoping"]
            setmemorystate(state)
            uwsgi.reload()
        return

    # stop
    if state.has_key("stop"):
        print "seems we are stoping"
        print "let's start"
        if not len(current_workers_tasks.keys()):
            print "oo there is not tasks"
            print uwsgi.workers()
            uwsgi.stop()
        return
    # working or not
    if state.has_key("working") and state["working"]:
        print "working"
    else:
        print "idle"
        return

    # choose command to start
    tmp_commands = commands.copy()
    for working_task in current_workers_tasks.keys():
        print "delete %s " % current_workers_tasks[working_task]["comand_key"]
        del tmp_commands[current_workers_tasks[working_task]
                         ["comand_key"]]  # there is no possible exception here

    # if comman is existed in past half of length also do not start
    cmds = tmp_commands.keys()
    past_length = len(cmds) / 2
    for past_work in workers_tasks[-1 * past_length:]:
        try:
            del tmp_commands[past_work]  #but here it seems to be
        except KeyError:
            print "%s is already deleted  from possible executin" % past_work

    cmds = tmp_commands.keys()
    to_start_command = None
    if len(cmds):
        to_start_command = random.choice(cmds)
    else:
        print "it's seems that everything is working recently, do not let workers to be lazy"
        to_start_command = random.choice(commands.keys())

    workers_signal_tmp = workers_signal[:]
    for busy_worker in current_workers_tasks.keys():
        print "delete from choice busy worker %i" % busy_worker
        workers_signal_tmp.remove(busy_worker)

    if len(workers_signal_tmp) > 0:
        print "choosing from the workers"
        print workers_signal_tmp
        number_of_signal = random.choice(workers_signal_tmp)
        workers_tasks.append(to_start_command)

        # write to shard memory index of  command
        state["to_start"] = to_start_command
        current_workers_tasks[number_of_signal] = {
            "started": datetime.now(),
            "comand_key": to_start_command,
            "command": commands[to_start_command]
        }
        state["workers_tasks"] = workers_tasks[
            -300:]  # only 300 save in history
        state["current_workers_tasks"] = current_workers_tasks
        setmemorystate(state)

        try:
            print "ok sending signal %i" % number_of_signal
            print "and going start %s" % str(commands[to_start_command])
            print "and going start %s" % to_start_command
            uwsgi.signal(number_of_signal)
            print workers_tasks
        except:
            traceback.print_exc()
            print "oh no %i busy" % number_of_signal
    else:
        print "=" * 64
        print "there is no free workers ?!"
        print "=" * 64

    print "busy workers "
    nw = datetime.now()
    for working_id in current_workers_tasks.keys():
        print "%i -> %s" % (working_id, str(current_workers_tasks[working_id]))
        working_delta = nw - current_workers_tasks[working_id]["started"]
        if working_delta > dt(minutes=5):
            print "this process seems to be stuck"
            print "%i -> %s" % (
                working_id, str(current_workers_tasks[working_id]["command"]))
Exemplo n.º 37
0
def application(env, start_response):
    print env
    start_response('200 OK', [('Content-Type', 'text/html')])

    yield '<h1>uWSGI %s status</h1>' % uwsgi.version
    yield 'masterpid: <b>' + str(uwsgi.masterpid()) + '</b><br/>'

    yield 'started on: <b>' + time.ctime(uwsgi.started_on) + '</b><br/>'

    yield 'buffer size: <b>' + str(uwsgi.buffer_size) + '</b><br/>'

    yield 'total_requests: <b>' + str(uwsgi.total_requests()) + '</b><br/>'

    yield 'log size: <b>' + str(uwsgi.logsize()) + '</b><br/>'

    yield 'workers: <b>' + str(uwsgi.numproc) + '</b><br/>'

    yield "cwd: <b>%s</b><br/>" % os.getcwd()

    try:
        yield "mode: <b>%s</b><br/>" % uwsgi.mode
    except:
        pass

    try:
        yield "pidfile: <b>%s</b><br/>" % uwsgi.pidfile
    except:
        pass

    yield "<h2>Hooks</h2>"

    for h in range(0,255):
        if uwsgi.has_hook(h):
            yield "%d<br/>" % h

    yield '<h2>dynamic options</h2>'

    yield '<table border="1">'
    yield '<th>worker id</th><th>pid</th><th>in request</th><th>requests</th><th>running time</th><th>address space</th><th>rss</th>'

    workers = uwsgi.workers();

    yield '<h2>workers</h2>'

    for w in workers:
        #print w
        #print w['running_time']
        if w is not None:
            yield '<tr><td>'+ str(w['id']) +'</td><td>' + str(w['pid']) + '</td><td>' + str(w['pid']) + '</td><td>' + str(w['requests']) + '</td><td>' + str(w['running_time']) + '</td><td>' + str(w['vsz']) + '</td><td>' + str(w['rss']) + '</td></tr>'
            print w

    yield '</table>'

    yield "<h2>PYTHONPATH</h2>"

    yield "<ul>"
    for p in sys.path:
        yield "<li>%s</li>" % p

    yield "</ul>"

    yield "<i>%s</i>" % str(os.uname())
Exemplo n.º 38
0
def application(env, start_response):
    try:
        uwsgi.mule_msg(env["REQUEST_URI"], 1)
    except Exception:
        pass

    req = uwsgi.workers()[uwsgi.worker_id() - 1]["requests"]

    uwsgi.setprocname(b"worker %d managed %d requests" % (uwsgi.worker_id(), req))

    try:
        gc.collect(2)
    except Exception:
        pass
    if DEBUG:
        print(env["wsgi.input"].fileno())

    if env["PATH_INFO"] in routes:
        return routes[env["PATH_INFO"]](env, start_response)

    if DEBUG:
        print(env["wsgi.input"].fileno())

    try:
        gc.collect(2)
    except Exception:
        pass

    if DEBUG:
        print(len(gc.get_objects()))

    workers = ""
    for w in uwsgi.workers():
        apps = '<table border="1"><tr><th>id</th><th>mountpoint</th><th>startup time</th><th>requests</th></tr>'
        for app in w["apps"]:
            apps += "<tr><td>%d</td><td>%s</td><td>%d</td><td>%d</td></tr>" % (
                app["id"],
                app["mountpoint"],
                app["startup_time"],
                app["requests"],
            )
        apps += "</table>"
        workers += """
<tr>
<td>%d</td><td>%d</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td>
</tr>
        """ % (
            w["id"],
            w["pid"],
            w["status"],
            w["running_time"] / 1000,
            w["avg_rt"] / 1000,
            w["tx"],
            apps,
        )

    output = """
<img src="{script_name}/logo"/> version %s running on %s (remote user: %s)<br/>
<hr size="1"/>

Configuration<br/>
<iframe src="{script_name}/config"></iframe><br/>

<br/>
Workers and applications<br/>
<table border="1">
<tr>
<th>wid</th><th>pid</th><th>status</th><th>running time</th><th>average</th><th>tx</th><th>apps</th>
</tr>
%s
</table>

    """ % (
        uwsgi.version,
        uwsgi.hostname,
        env.get("REMOTE_USER", "None"),
        workers,
    )

    start_response(
        "200 OK", [("Content-Type", "text/html"), ("Content-Length", str(len(output)))]
    )

    return [output.format(script_name=env["SCRIPT_NAME"]).encode("utf-8")]