giampaolo / psutil

Cross-platform lib for process and system monitoring in Python
BSD 3-Clause "New" or "Revised" License
10.08k stars 1.37k forks source link

Expose parameter to return partial results in case of EPERM / AccessDenied #2329

Open giampaolo opened 8 months ago

giampaolo commented 8 months ago

Problem

psutil provides different APIs that return multiple results (a list or a dict of elements), like psutil.Process.open_files() or psutil.net_connections(). It can happen that these API raise AccessDenied because of insufficient permissions, despite the fact that internally some information is collected (and discarded). Over the years there has been some demand to ignore AccessDenied and return a partial result instead:

In the past I explained why letting AccessDenied propagate is a good thing (see https://github.com/giampaolo/psutil/issues/2124#issuecomment-1195925438). Nevertheless, the use case to be able to retrieve a partial result instead of AccessDenied appears justified.

Proposal

The proposal is to identify for which APIs it make sense to do this, and either:

1) introduce an ignore_eperm (or similar) parameter to the function signatures that require it, e.g.

p = psutil.Process(pid)
files = p.open_files(ignore_eperm=True)

2) add a partial_result attribute to the AccessDenied instance, so that one can do:

p = psutil.Process(pid)
try:
    files = p.open_files()
except psutil.AccessDenied as err:
    files = err.partial_result

The first approach seems shorter and cleaner, but it requires changing the signature of multiple APIs (and the doc must reflect that). The second approach appears more generic, but it's probably harder to understand for non-experts. Also, I guess it's too generic, because only certain APIs will set partial_result, so one may erroneously use the try/except idiom above and expect some result for an API which does not implement this contract.

It must be noted that also gopsutil project is puzzled by these sort of API design questions:

APIs

Potential API candidates are:

Process:

System: