Skip to content

Commit

Permalink
Handle disabled swap/counter failure case
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Widdis <[email protected]>
  • Loading branch information
dbwiddis committed Oct 22, 2022
1 parent 4aca85b commit 0fa7c0e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 22 deletions.
11 changes: 7 additions & 4 deletions psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,13 @@ def swap_memory():
total = total_system - total_phys
# commit total is incremented immediately (decrementing free_system)
# while the corresponding free physical value is not decremented until
# pages are accessed, so we ignore free system memory and calculate
# page file usage based on performance counter
percentswap = cext.getpercentswap()
used = int(0.01 * percentswap * total)
# pages are accessed, so we can't use free system memory for swap.
# instead, we calculate page file usage based on performance counter
if (total > 0):
percentswap = cext.getpercentswap()
used = int(0.01 * percentswap * total)
else:
used = 0
free = total - used
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, 0, 0)
Expand Down
30 changes: 12 additions & 18 deletions psutil/arch/windows/wmi.c
Original file line number Diff line number Diff line change
Expand Up @@ -155,27 +155,21 @@ psutil_get_percentswap(PyObject *self, PyObject *args) {

s = PdhCollectQueryData(hQuery);
if (s != ERROR_SUCCESS) {
PyErr_Format(PyExc_RuntimeError, "PdhCollectQueryData failed");
return NULL;
}

s = PdhGetFormattedCounterValue(
(PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue);
if (s != ERROR_SUCCESS) {
return NULL;
// If swap disabled this will fail
percentUsage = 0;
} else {
s = PdhGetFormattedCounterValue(
(PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue);
if (s != ERROR_SUCCESS) {
percentUsage = 0;
} else {
percentUsage = counterValue.doubleValue;
}
}

percentUsage = counterValue.doubleValue;
PdhRemoveCounter(hCounter);

if ((PdhRemoveCounter(hCounter)) != ERROR_SUCCESS) {
PyErr_Format(PyExc_RuntimeError, "PdhRemoveCounter failed");
return NULL;
}

if ((PdhCloseQuery(hQuery)) != ERROR_SUCCESS) {
PyErr_Format(PyExc_RuntimeError, "PdhCloseQuery failed");
return NULL;
}
PdhCloseQuery(hQuery);

return Py_BuildValue("d", percentUsage);
}

0 comments on commit 0fa7c0e

Please sign in to comment.