Created
June 12, 2020 06:27
-
-
Save minrk/88952bba987825af58f5ca1b88990815 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Extension to list active kernels | |
attempting to sort by likely 'focus' | |
""" | |
from tornado import web | |
from notebook.base.handlers import IPythonHandler | |
from notebook.utils import url_path_join | |
def activity_sort_key(kernel): | |
"""Sort kernels by probable 'focus' | |
- First priority: any active connections (no connections means no connected UI) | |
- Second priority: recent activity (active tab before open but not executed in a while) | |
""" | |
# TODO: third priority: execution state (busy/idle/etc.)? | |
return (kernel["connections"], kernel["last_activity"]) | |
class LastActiveKernelHandler(IPythonHandler): | |
@web.authenticated | |
def get(self): | |
km = self.kernel_manager | |
kernel_models = sorted(self.kernel_manager.list_kernels(), key=activity_sort_key, reverse=True) | |
if not kernel_models: | |
self.write("No kernels!") | |
return | |
most_active = kernel_models[0] | |
self.write( | |
f"<p>The most active kernel is {most_active['id']} with {most_active['connections']} connections, last active on {most_active['last_activity']}</p>" | |
) | |
self.write("<p>Other kernels:</p><ul>") | |
for kernel in kernel_models[1:]: | |
self.write( | |
f"<li>{kernel['id']}: {kernel['connections']} connections, last active on {kernel['last_activity']}" | |
) | |
self.write("</ul>") | |
def load_jupyter_server_extension(nb_server_app): | |
""" | |
Called when the extension is loaded. | |
Args: | |
nb_server_app (NotebookWebApplication): handle to the Notebook webserver instance. | |
""" | |
web_app = nb_server_app.web_app | |
host_pattern = ".*$" | |
route_pattern = url_path_join(web_app.settings["base_url"], "/lastactive") | |
web_app.add_handlers(host_pattern, [(route_pattern, LastActiveKernelHandler)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment