Example #1
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)
Example #2
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)
Example #3
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>'
Example #4
0
def is_master_process():
    # currently only recognizes uwsgi master process
    try:
        import uwsgi
        return os.getpid() == uwsgi.masterpid()
    except ImportError:
        return False
Example #5
0
    def exit(self, environ=None):
        import uwsgi
        import signal

        resp = WbResponse.json_response({})
        os.kill(uwsgi.masterpid(), signal.SIGTERM)
        return resp
Example #6
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)
Example #7
0
def print_with_color(msg: str, **kwargs):
    bold = kwargs.pop('bold', False)
    if bold:
        opts = kwargs.setdefault('opts', [])
        if 'bold' not in opts:
            opts.append('bold')

    pid = os.getpid()
    try:
        # noinspection PyPackageRequirements,PyUnresolvedReferences
        import uwsgi
        master = uwsgi.masterpid()
        worker = uwsgi.worker_id()
        mule = uwsgi.mule_id()
    except ImportError:
        uwsgi = None
        master = 0
        worker = 0
        mule = 0

    if mule:
        print(colorize('[mule {}] {}'.format(mule, msg), **kwargs))
    elif worker:
        print(colorize('[worker {}] {}'.format(worker, msg), **kwargs))
    elif pid == master:
        print(colorize('[master] {}'.format(msg), **kwargs))
    elif uwsgi:
        print(colorize('[spooler {}] {}'.format(pid, msg), **kwargs))
    else:
        print(colorize(msg, **kwargs))
Example #8
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)
Example #9
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)
Example #10
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)
Example #11
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,
            }
        }
Example #12
0
def is_master_process():
    # currently only recognizes uwsgi master process
    try:
        import uwsgi
        return os.getpid() == uwsgi.masterpid()
    except ImportError:
        return False
Example #13
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>'
Example #14
0
def reload(request):
	if uwsgi.masterpid() > 0:
		uwsgi.reload()
		request.user.message_set.create(message="uWSGI reloaded")
	else:
		request.user.message_set.create(message="The uWSGI master process is not active")

	return HttpResponseRedirect(reverse(index))
Example #15
0
    def get_application_name(self):
        # One environment variable to rule them all
        if "INSTANA_SERVICE_NAME" in os.environ:
            return os.environ["INSTANA_SERVICE_NAME"]

        # Now best effort in naming this process.  No nice package.json like in Node.js
        # so we do best effort detection here.

        basename = os.path.basename(sys.argv[0])
        if basename == "gunicorn":
            # gunicorn renames their processes to pretty things - we use those by default
            # gunicorn: master [djface.wsgi]
            # gunicorn: worker [djface.wsgi]
            app_name = self.get_proc_cmdline()

            if app_name is None:
                app_name = basename
        elif "FLASK_APP" in os.environ:
            app_name = os.environ["FLASK_APP"]
        elif "DJANGO_SETTINGS_MODULE" in os.environ:
            app_name = os.environ["DJANGO_SETTINGS_MODULE"].split('.')[0]
        elif basename == '':
            if sys.stdout.isatty():
                app_name = "Interactive Console"
            else:
                # No arguments.  Take executable as app_name
                app_name = os.path.basename(sys.executable)
        else:
            # Last chance.  app_name for "python main.py" would be "main.py" here.
            app_name = basename

        # We should have a good app_name by this point.
        # Last conditional, if uwsgi, then wrap the name
        # with the uwsgi process type
        if basename == "uwsgi":
            # We have an app name by this point.  Now if running under
            # uwsgi, augment the appname
            try:
                import uwsgi

                if app_name == "uwsgi":
                    app_name = ""
                else:
                    app_name = " [%s]" % app_name

                if os.getpid() == uwsgi.masterpid():
                    uwsgi_type = "uWSGI master%s"
                else:
                    uwsgi_type = "uWSGI worker%s"

                app_name = uwsgi_type % app_name
            except ImportError:
                pass

        return app_name
Example #16
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,
    })
Example #17
0
def reload_uwsgi():
    if not have_uwsgi:
        return "you aren't running web2py with uwsgi"
    masterpid = uwsgi.masterpid()
    if masterpid > 0:
        form = FORM(INPUT(_type="submit", _value="Reload uWSGI"))
        if form.process().accepted:
            uwsgi.reload()
            response.flash = "uWSGI reloaded correctly"
    else:
        form = ''
        response.flash = "The uWSGI master process is not active"
    return form
Example #18
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,
        })
Example #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'])

	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, {}))
Example #20
0
def reload(request):
    if uwsgi.masterpid() > 0:
        uwsgi.reload()
        messages.add_message(request,
                             messages.SUCCESS,
                             _('uWSGI reloaded'),
                             fail_silently=True)
    else:
        messages.add_message(request,
                             messages.ERROR,
                             _('The uWSGI master process is not active'),
                             fail_silently=True)

    return HttpResponseRedirect(reverse(index))
Example #21
0
def reload(request):
    import uwsgi
    if uwsgi.masterpid() > 0:
        uwsgi.reload()
        messages.add_message(request,
                             messages.SUCCESS,
                             _('uWSGI reloaded'),
                             fail_silently=True)
    else:
        messages.add_message(request,
                             messages.ERROR,
                             _('The uWSGI master process is not active'),
                             fail_silently=True)

    return HttpResponseRedirect(reverse("admin:uwsgi_status_changelist"))
Example #22
0
def reload(request):
    import uwsgi
    if uwsgi.masterpid() > 0:
        uwsgi.reload()
        messages.add_message(request,
                             messages.SUCCESS,
                             _('uWSGI reloaded'),
                             fail_silently=True)
    else:
        messages.add_message(request,
                             messages.ERROR,
                             _('The uWSGI master process is not active'),
                             fail_silently=True)

    return HttpResponseRedirect(reverse("admin:uwsgi_status_changelist"))
Example #23
0
 def log_startup(self):
     msg = ["Galaxy server instance '%s' is running" % self.app.config.server_name]
     # Log the next messages when the first worker finishes starting. This
     # may not be the first to finish (so Galaxy could be serving already),
     # but it's a good approximation and gives the correct root_pid below
     # when there is no master process.
     if not self._is_mule and self.instance_id == 1:
         # We use the same text printed by Paste to not break scripts
         # grepping for this line. Here root_pid is the same that gets
         # written to file when using the --pidfile option of uwsgi
         root_pid = uwsgi.masterpid() or os.getpid()
         msg.append('Starting server in PID %d.' % root_pid)
         for s in UWSGIApplicationStack._serving_on():
             msg.append('serving on ' + s)
         if len(msg) == 1:
             msg.append('serving on unknown URL')
     log.info('\n'.join(msg))
Example #24
0
 def log_startup(self):
     msg = ["Galaxy server instance '%s' is running" % self.config.server_name]
     # Log the next messages when the first worker finishes starting. This
     # may not be the first to finish (so Galaxy could be serving already),
     # but it's a good approximation and gives the correct root_pid below
     # when there is no master process.
     if not self._is_mule and self.instance_id == 1:
         # We use the same text printed by Paste to not break scripts
         # grepping for this line. Here root_pid is the same that gets
         # written to file when using the --pidfile option of uwsgi
         root_pid = uwsgi.masterpid() or os.getpid()
         msg.append('Starting server in PID %d.' % root_pid)
         for s in UWSGIApplicationStack._serving_on():
             msg.append('serving on ' + s)
         if len(msg) == 1:
             msg.append('serving on unknown URL')
     log.info('\n'.join(msg))
Example #25
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, {}))
Example #26
0
def reload(request):
    if not uwsgi:
        messages.error(request, "This server is not an uWSGI server!")

    elif uwsgi.masterpid() > 0:
        # Atach to request_finished signal and try to restart the server
        @receiver(request_finished, weak=False)
        def request_callback(sender, **kwargs):
            """
            Try to reload as later as possible
            """
            try:
                thread.start_new_thread(_restart_uwsgi, (0.1,))  # start_new_thread must accept tuple as second argumet
            except:
                # For some reason can not start thread
                _restart_uwsgi()

        messages.success(request, "Server was successfully reloaded.")
        return HttpResponse("true")

    else:
        messages.error(request, "There is no master proccess. Gracefull reload is not Possible!")

    return HttpResponse("false")
Example #27
0
 def pid(self):
     return uwsgi.masterpid()
Example #28
0
import signal, sys
import time
import uwsgi
import os

print(uwsgi.opt)

sig_timeout = uwsgi.opt.get('test_mule_timeout', 10)
sig_to_send = uwsgi.opt.get('test_signal', signal.SIGINT)

def sig_handler(signum, frame):
    print('Hello from signal', signum)
    time.sleep(int(sig_timeout))
    sys.exit(0)

signal.signal(signal.SIGINT, sig_handler)
signal.signal(signal.SIGHUP, sig_handler)

time.sleep(1)

os.kill(uwsgi.masterpid(), int(sig_to_send))

while True:
    uwsgi.farm_get_msg()
Example #29
0
def determine_service_name():
    """ This function makes a best effort to name this application process. """

    # One environment variable to rule them all
    if "INSTANA_SERVICE_NAME" in os.environ:
        return os.environ["INSTANA_SERVICE_NAME"]

    try:
        # Now best effort in naming this process.  No nice package.json like in Node.js
        # so we do best effort detection here.
        app_name = "python"  # the default name

        if not hasattr(sys, 'argv'):
            proc_cmdline = get_proc_cmdline(as_string=False)
            return os.path.basename(proc_cmdline[0])

        basename = os.path.basename(sys.argv[0])
        if basename == "gunicorn":
            if 'setproctitle' in sys.modules:
                # With the setproctitle package, gunicorn renames their processes
                # to pretty things - we use those by default
                # gunicorn: master [djface.wsgi]
                # gunicorn: worker [djface.wsgi]
                app_name = get_proc_cmdline(as_string=True)
            else:
                app_name = basename
        elif "FLASK_APP" in os.environ:
            app_name = os.environ["FLASK_APP"]
        elif "DJANGO_SETTINGS_MODULE" in os.environ:
            app_name = os.environ["DJANGO_SETTINGS_MODULE"].split('.')[0]
        elif basename == '':
            if sys.stdout.isatty():
                app_name = "Interactive Console"
            else:
                # No arguments.  Take executable as app_name
                app_name = os.path.basename(sys.executable)
        else:
            # Last chance.  app_name for "python main.py" would be "main.py" here.
            app_name = basename

        # We should have a good app_name by this point.
        # Last conditional, if uwsgi, then wrap the name
        # with the uwsgi process type
        if basename == "uwsgi":
            # We have an app name by this point.  Now if running under
            # uwsgi, augment the app name
            try:
                import uwsgi

                if app_name == "uwsgi":
                    app_name = ""
                else:
                    app_name = " [%s]" % app_name

                if os.getpid() == uwsgi.masterpid():
                    uwsgi_type = "uWSGI master%s"
                else:
                    uwsgi_type = "uWSGI worker%s"

                app_name = uwsgi_type % app_name
            except ImportError:
                pass
        return app_name
    except Exception:
        logger.debug("get_application_name: ", exc_info=True)
        return app_name
Example #30
0
def server_restart(**kwargs):
    if uwsgi is not None and uwsgi.masterpid() > 0:
        uwsgi.reload()
Example #31
0
 def masterpid(self):
     ''' '''
     return uwsgi.masterpid()
Example #32
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>'
Example #33
0
 def should_start_http_server(self):
     import uwsgi
     return os.getpid() == uwsgi.masterpid()
Example #34
0
import inspect
import logging
import pickle

from django.utils.module_loading import autodiscover_modules

logger = logging.getLogger('mtp')

try:
    import uwsgi
    import uwsgidecorators

    if uwsgi.masterpid() == 0 or 'spooler' not in uwsgi.opt:
        logger.warning(
            'uWSGI master and spooler need to be enabled to use spooling')
        raise ImportError
except ImportError:
    uwsgi = None
    uwsgidecorators = None


class Context:
    __slots__ = ('spooled', )

    def __init__(self, spooled):
        """
        Defines the context in which a spoolable task is running
        :param spooled: whether it is running in the spooler asynchronously
        """
        self.spooled = spooled
Example #35
0
def isUwsgiMaster():
    if not IS_UWSGI_SUPPORTED:
        return False
    import os, uwsgi
    return os.getpid() == uwsgi.masterpid()
Example #36
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())
Example #37
0
import signal, sys
import time
import uwsgi
import os

print(uwsgi.opt)

sig_timeout = uwsgi.opt.get('test_mule_timeout', 10)
sig_to_send = uwsgi.opt.get('test_signal', signal.SIGINT)


def sig_handler(signum, frame):
    print('Hello from signal', signum)
    time.sleep(int(sig_timeout))
    sys.exit(0)


signal.signal(signal.SIGINT, sig_handler)
signal.signal(signal.SIGHUP, sig_handler)

time.sleep(1)

os.kill(uwsgi.masterpid(), int(sig_to_send))

while True:
    uwsgi.farm_get_msg()
Example #38
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>'
Example #39
0
def getUwsgiMasterPid():
    if not IS_UWSGI_SUPPORTED:
        return None
    import uwsgi
    return uwsgi.masterpid()
Example #40
0
            return [r"*\lib\*"]
        return ["*/lib/python%s.%s/*" % python_version[:2], "*/lib64/python%s.%s/*" % python_version[:2]]


def multidict_to_dict(d):
    """
    Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with
    list values
    :param d: a MultiDict or MultiValueDict instance
    :return: a dict instance
    """
    return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))


try:
    import uwsgi

    # check if a master is running before importing postfork
    if uwsgi.masterpid() != 0:
        from uwsgidecorators import postfork
    else:

        def postfork(f):
            return f


except (ImportError, AttributeError):

    def postfork(f):
        return f
Example #41
0
from functools import partial
import sys
from threading import Thread

try:
    import cPickle as pickle
except:
    import pickle

import uwsgi

if uwsgi.masterpid() == 0:
    raise Exception(
        "you have to enable the uWSGI master process to use this module")

spooler_functions = {}
mule_functions = {}
postfork_chain = []


# Python3 compatibility
def _encode1(val):
    if sys.version_info >= (3, 0) and isinstance(val, str):
        return val.encode('utf-8')
    else:
        return val


def _decode1(val):
    if sys.version_info >= (3, 0) and isinstance(val, bytes):
        return val.decode('utf-8')
Example #42
0
def uwsgi_workers_reload():
    import uwsgi
    os.kill(uwsgi.masterpid(), signal.SIGHUP)
    response = "Workers reloaded"
    return render_template("empty.html", info=response)