Skip to content

Commit 4c47154

Browse files
echarlesCarreau
authored andcommitted
Add kernel cpu and memory usage information
1 parent 28172a1 commit 4c47154

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

ipykernel/kernelbase.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@
1616
import time
1717
import uuid
1818
import warnings
19-
import psutil
19+
try:
20+
import psutil
21+
except ImportError:
22+
psutil = None
2023

2124
try:
2225
# jupyter_client >= 5, use tz-aware now
@@ -861,14 +864,37 @@ async def debug_request(self, stream, ident, parent):
861864
parent, ident)
862865
self.log.debug("%s", reply_msg)
863866

867+
# Taken from https://github.com/jupyter-server/jupyter-resource-usage/blob/e6ec53fa69fdb6de8e878974bcff006310658408/jupyter_resource_usage/metrics.py#L16
868+
def get_process_metric_value(self, process, name, attribute=None):
869+
try:
870+
# psutil.Process methods will either return...
871+
metric_value = getattr(process, name)()
872+
if attribute is not None: # ... a named tuple
873+
return getattr(metric_value, attribute)
874+
else: # ... or a number
875+
return metric_value
876+
# Avoid littering logs with stack traces
877+
# complaining about dead processes
878+
except BaseException:
879+
return 0
880+
864881
async def usage_request(self, stream, ident, parent):
865882
reply_content = {}
883+
if psutil is None:
884+
return reply_content
885+
current_process = psutil.Process()
886+
all_processes = [current_process] + current_process.children(recursive=True)
887+
process_metric_value = lambda process, name, attribute: self.get_process_metric_value(
888+
process, name, attribute
889+
)
890+
reply_content['kernel_cpu'] = sum([process_metric_value(process, 'cpu_percent', None) for process in all_processes])
891+
reply_content['kernel_memory'] = sum([process_metric_value(process, 'memory_info', 'rss') for process in all_processes])
866892
cpu_percent = psutil.cpu_percent()
867893
# https://psutil.readthedocs.io/en/latest/index.html?highlight=cpu#psutil.cpu_percent
868894
# The first time cpu_percent is called it will return a meaningless 0.0 value which you are supposed to ignore.
869895
if cpu_percent != None and cpu_percent != 0.0:
870-
reply_content['cpu_percent'] = cpu_percent
871-
reply_content['virtual_memory'] = dict(psutil.virtual_memory()._asdict())
896+
reply_content['host_cpu_percent'] = cpu_percent
897+
reply_content['host_virtual_memory'] = dict(psutil.virtual_memory()._asdict())
872898
reply_msg = self.session.send(stream, 'usage_reply', reply_content,
873899
parent, ident)
874900
self.log.debug("%s", reply_msg)

0 commit comments

Comments
 (0)