-
Notifications
You must be signed in to change notification settings - Fork 102
Make NBResuse more flexible. #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,53 +1,81 @@ | ||
from typing import NamedTuple, Optional | ||
|
||
try: | ||
import psutil | ||
except ImportError: | ||
psutil = None | ||
|
||
|
||
class MemoryMetrics(NamedTuple): | ||
current_memory: int | ||
max_memory: int | ||
|
||
|
||
class CPUMetrics(NamedTuple): | ||
cpu_max: float | ||
cpu_usage: float | ||
|
||
|
||
def memory_metrics() -> Optional[MemoryMetrics]: | ||
if psutil: | ||
cur_process = psutil.Process() | ||
all_processes = [cur_process] + cur_process.children(recursive=True) | ||
|
||
rss = sum([p.memory_info().rss for p in all_processes]) | ||
virtual_memory = psutil.virtual_memory().total | ||
|
||
else: | ||
return None | ||
|
||
return MemoryMetrics(rss, virtual_memory) | ||
|
||
|
||
def cpu_metrics() -> Optional[CPUMetrics]: | ||
if psutil: | ||
cur_process = psutil.Process() | ||
all_processes = [cur_process] + cur_process.children(recursive=True) | ||
|
||
cpu_count = psutil.cpu_count() | ||
|
||
def get_cpu_percent(p): | ||
try: | ||
return p.cpu_percent(interval=0.05) | ||
# Avoid littering logs with stack traces complaining | ||
# about dead processes having no CPU usage | ||
except BaseException: | ||
return 0 | ||
|
||
cpu_percent = sum([get_cpu_percent(p) for p in all_processes]) | ||
|
||
else: | ||
return None | ||
|
||
return CPUMetrics(cpu_count * 100.0, cpu_percent) | ||
from notebook.notebookapp import NotebookApp | ||
|
||
|
||
class PSUtilMetricsLoader: | ||
def __init__(self, nbapp: NotebookApp): | ||
self.config = nbapp.web_app.settings["nbresuse_display_config"] | ||
self.nbapp = nbapp | ||
|
||
def process_metric(self, name, kwargs={}, attribute=None): | ||
if psutil is None: | ||
return None | ||
else: | ||
current_process = psutil.Process() | ||
all_processes = [current_process] + current_process.children(recursive=True) | ||
|
||
def get_process_metric(process, name, kwargs, attribute=None): | ||
try: | ||
# psutil.Process methods will either return... | ||
metric_value = getattr(process, name)(**kwargs) | ||
if attribute is not None: # ... a named tuple | ||
return getattr(metric_value, attribute) | ||
else: # ... or a number | ||
return metric_value | ||
# Avoid littering logs with stack traces | ||
# complaining about dead processes | ||
except BaseException: | ||
return 0 | ||
|
||
process_metric_value = lambda process: get_process_metric( | ||
process, name, kwargs, attribute | ||
) | ||
|
||
return sum([process_metric_value(process) for process in all_processes]) | ||
|
||
def system_metric(self, name, kwargs={}, attribute=None): | ||
if psutil is None: | ||
return None | ||
else: | ||
# psutil functions will either return... | ||
metric_value = getattr(psutil, name)(**kwargs) | ||
if attribute is not None: # ... a named tuple | ||
return getattr(metric_value, attribute) | ||
else: # ... or a number | ||
return metric_value | ||
|
||
def get_metric_values(self, metrics, metric_type): | ||
metric_types = {"process": self.process_metric, "system": self.system_metric} | ||
metric_value = metric_types[metric_type] # Switch statement | ||
|
||
metric_values = {} | ||
for metric in metrics: | ||
name = metric["name"] | ||
if metric.get("attribute", False): | ||
name += "_" + metric.get("attribute") | ||
metric_values.update({name: metric_value(**metric)}) | ||
return metric_values | ||
|
||
def metrics(self, process_metrics, system_metrics): | ||
|
||
metric_values = self.get_metric_values(process_metrics, "process") | ||
metric_values.update(self.get_metric_values(system_metrics, "system")) | ||
|
||
if any(value is None for value in metric_values.values()): | ||
return None | ||
|
||
return metric_values | ||
|
||
def memory_metrics(self): | ||
return self.metrics( | ||
self.config.process_memory_metrics, self.config.system_memory_metrics | ||
) | ||
|
||
def cpu_metrics(self): | ||
return self.metrics( | ||
self.config.process_cpu_metrics, self.config.system_cpu_metrics | ||
) |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,56 +1,69 @@ | ||
from typing import Optional | ||
|
||
from notebook.notebookapp import NotebookApp | ||
from prometheus_client import Gauge | ||
from tornado import gen | ||
from typing import Optional | ||
|
||
from nbresuse.metrics import cpu_metrics | ||
from nbresuse.metrics import CPUMetrics | ||
from nbresuse.metrics import memory_metrics | ||
from nbresuse.metrics import MemoryMetrics | ||
from nbresuse.metrics import PSUtilMetricsLoader | ||
|
||
try: | ||
# Traitlets >= 4.3.3 | ||
from traitlets import Callable | ||
except ImportError: | ||
from .utils import Callable | ||
|
||
TOTAL_MEMORY_USAGE = Gauge("total_memory_usage", "counter for total memory usage", []) | ||
|
||
MAX_MEMORY_USAGE = Gauge("max_memory_usage", "counter for max memory usage", []) | ||
|
||
TOTAL_CPU_USAGE = Gauge("total_cpu_usage", "counter for total cpu usage", []) | ||
class PrometheusHandler(Callable): | ||
def __init__(self, metricsloader: PSUtilMetricsLoader): | ||
super().__init__() | ||
self.metricsloader = metricsloader | ||
self.config = metricsloader.config | ||
self.session_manager = metricsloader.nbapp.session_manager | ||
|
||
MAX_CPU_USAGE = Gauge("max_cpu_usage", "counter for max cpu usage", []) | ||
self.TOTAL_MEMORY_USAGE = Gauge( | ||
"total_memory_usage", "counter for total memory usage", [] | ||
) | ||
self.MAX_MEMORY_USAGE = Gauge( | ||
"max_memory_usage", "counter for max memory usage", [] | ||
) | ||
|
||
self.TOTAL_CPU_USAGE = Gauge( | ||
"total_cpu_usage", "counter for total cpu usage", [] | ||
) | ||
self.MAX_CPU_USAGE = Gauge("max_cpu_usage", "counter for max cpu usage", []) | ||
|
||
class PrometheusHandler(Callable): | ||
def __init__(self, nbapp: NotebookApp): | ||
super().__init__() | ||
self.config = nbapp.web_app.settings["nbresuse_display_config"] | ||
self.session_manager = nbapp.session_manager | ||
|
||
@gen.coroutine | ||
def __call__(self, *args, **kwargs): | ||
metrics = self.apply_memory_limits(memory_metrics()) | ||
if metrics is not None: | ||
TOTAL_MEMORY_USAGE.set(metrics.current_memory) | ||
MAX_MEMORY_USAGE.set(metrics.max_memory) | ||
async def __call__(self, *args, **kwargs): | ||
memory_metric_values = self.metricsloader.memory_metrics() | ||
if memory_metric_values is not None: | ||
self.TOTAL_MEMORY_USAGE.set(memory_metric_values["memory_info_rss"]) | ||
self.MAX_MEMORY_USAGE.set(self.apply_memory_limit(memory_metric_values)) | ||
if self.config.track_cpu_percent: | ||
metrics = self.apply_cpu_limits(cpu_metrics()) | ||
if metrics is not None: | ||
TOTAL_CPU_USAGE.set(metrics.cpu_usage) | ||
MAX_CPU_USAGE.set(metrics.cpu_max) | ||
cpu_metric_values = self.metricsloader.cpu_metrics() | ||
if cpu_metric_values is not None: | ||
self.TOTAL_CPU_USAGE.set(cpu_metric_values["cpu_percent"]) | ||
self.MAX_CPU_USAGE.set(self.apply_cpu_limit(cpu_metric_values)) | ||
|
||
def apply_memory_limits(self, metrics: Optional[MemoryMetrics]) -> Optional[MemoryMetrics]: | ||
if metrics is not None: | ||
def apply_memory_limit(self, memory_metric_values) -> Optional[int]: | ||
if memory_metric_values is None: | ||
return None | ||
else: | ||
if callable(self.config.mem_limit): | ||
metrics.max_memory = self.config.mem_limit(rss=metrics.max_memory) | ||
return self.config.mem_limit( | ||
rss=memory_metric_values["memory_info_rss"] | ||
) | ||
elif self.config.mem_limit > 0: # mem_limit is an Int | ||
metrics.max_memory = self.config.mem_limit | ||
return metrics | ||
|
||
def apply_cpu_limits(self, metrics: Optional[CPUMetrics]) -> Optional[CPUMetrics]: | ||
if metrics is not None: | ||
if self.config.cpu_limit > 0: | ||
metrics.cpu_max = self.config.cpu_limit | ||
return metrics | ||
return self.config.mem_limit | ||
else: | ||
return memory_metric_values["virtual_memory_total"] | ||
|
||
def apply_cpu_limit(self, cpu_metric_values) -> Optional[float]: | ||
if cpu_metric_values is None: | ||
return None | ||
else: | ||
if callable(self.config.cpu_limit): | ||
return self.config.cpu_limit( | ||
cpu_percent=cpu_metric_values["cpu_percent"] | ||
) | ||
elif self.config.cpu_limit > 0.0: # cpu_limit is a Float | ||
return self.config.cpu_limit | ||
else: | ||
return 100.0 * cpu_metric_values["cpu_count"] |
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would eventually like to replace these manually specified attributes and attribute names (one for each gauge) with automatically generated ones based on the user's specified configuration, using for loops similar to what was done here in NBViewer.
https://github.com/jupyter/nbviewer/blob/dda310767d9c209a985abadddfad389c404d12be/nbviewer/providers/base.py#L63
I think computing the value for the third argument of
setattr
will be more complicated than just getting an entry from a dictionary based on its key, but it should still be regular enough that it could be encompassed in a function, allowing the calls tosetattr
to still be legible.