|
16 | 16 | import time |
17 | 17 | import uuid |
18 | 18 | import warnings |
19 | | -import psutil |
| 19 | +try: |
| 20 | + import psutil |
| 21 | +except ImportError: |
| 22 | + psutil = None |
20 | 23 |
|
21 | 24 | try: |
22 | 25 | # jupyter_client >= 5, use tz-aware now |
@@ -861,14 +864,37 @@ async def debug_request(self, stream, ident, parent): |
861 | 864 | parent, ident) |
862 | 865 | self.log.debug("%s", reply_msg) |
863 | 866 |
|
| 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 | + |
864 | 881 | async def usage_request(self, stream, ident, parent): |
865 | 882 | 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]) |
866 | 892 | cpu_percent = psutil.cpu_percent() |
867 | 893 | # https://psutil.readthedocs.io/en/latest/index.html?highlight=cpu#psutil.cpu_percent |
868 | 894 | # The first time cpu_percent is called it will return a meaningless 0.0 value which you are supposed to ignore. |
869 | 895 | 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()) |
872 | 898 | reply_msg = self.session.send(stream, 'usage_reply', reply_content, |
873 | 899 | parent, ident) |
874 | 900 | self.log.debug("%s", reply_msg) |
|
0 commit comments