| 1 |
/* |
| 2 |
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. |
| 3 |
* Use of this source code is governed by a BSD-style license that can be |
| 4 |
* found in the LICENSE file. |
| 5 |
*/ |
| 6 |
|
| 7 |
#include <Python.h> |
| 8 |
#include <sys/sysctl.h> |
| 9 |
#include <devstat.h> |
| 10 |
|
| 11 |
#include "../../arch/all/init.h" |
| 12 |
|
| 13 |
|
| 14 |
// convert a bintime struct to milliseconds |
| 15 |
#define PSUTIL_BT2MSEC(bt) (bt.sec * 1000 + (((uint64_t) 1000000000 * (uint32_t) \ |
| 16 |
(bt.frac >> 32) ) >> 32 ) / 1000000) |
| 17 |
|
| 18 |
|
| 19 |
PyObject * |
| 20 |
psutil_disk_io_counters(PyObject *self, PyObject *args) { |
| 21 |
int i; |
| 22 |
struct statinfo stats; |
| 23 |
|
| 24 |
PyObject *py_retdict = PyDict_New(); |
| 25 |
PyObject *py_disk_info = NULL; |
| 26 |
|
| 27 |
if (py_retdict == NULL) |
| 28 |
return NULL; |
| 29 |
if (devstat_checkversion(NULL) < 0) { |
| 30 |
PyErr_Format(PyExc_RuntimeError, |
| 31 |
"devstat_checkversion() syscall failed"); |
| 32 |
goto error; |
| 33 |
} |
| 34 |
|
| 35 |
stats.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo)); |
| 36 |
if (stats.dinfo == NULL) { |
| 37 |
PyErr_NoMemory(); |
| 38 |
goto error; |
| 39 |
} |
| 40 |
bzero(stats.dinfo, sizeof(struct devinfo)); |
| 41 |
|
| 42 |
if (devstat_getdevs(NULL, &stats) == -1) { |
| 43 |
PyErr_Format(PyExc_RuntimeError, "devstat_getdevs() syscall failed"); |
| 44 |
goto error; |
| 45 |
} |
| 46 |
|
| 47 |
for (i = 0; i < stats.dinfo->numdevs; i++) { |
| 48 |
py_disk_info = NULL; |
| 49 |
struct devstat current; |
| 50 |
char disk_name[128]; |
| 51 |
current = stats.dinfo->devices[i]; |
| 52 |
snprintf(disk_name, sizeof(disk_name), "%s%d", |
| 53 |
current.device_name, |
| 54 |
current.unit_number); |
| 55 |
|
| 56 |
py_disk_info = Py_BuildValue( |
| 57 |
"(KKKKLLL)", |
| 58 |
current.operations[DEVSTAT_READ], // no reads |
| 59 |
current.operations[DEVSTAT_WRITE], // no writes |
| 60 |
current.bytes[DEVSTAT_READ], // bytes read |
| 61 |
current.bytes[DEVSTAT_WRITE], // bytes written |
| 62 |
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_READ]), // r time |
| 63 |
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_WRITE]), // w time |
| 64 |
(long long) PSUTIL_BT2MSEC(current.busy_time) // busy time |
| 65 |
); // finished transactions |
| 66 |
if (!py_disk_info) |
| 67 |
goto error; |
| 68 |
if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info)) |
| 69 |
goto error; |
| 70 |
Py_DECREF(py_disk_info); |
| 71 |
} |
| 72 |
|
| 73 |
if (stats.dinfo->mem_ptr) |
| 74 |
free(stats.dinfo->mem_ptr); |
| 75 |
free(stats.dinfo); |
| 76 |
return py_retdict; |
| 77 |
|
| 78 |
error: |
| 79 |
Py_XDECREF(py_disk_info); |
| 80 |
Py_DECREF(py_retdict); |
| 81 |
if (stats.dinfo != NULL) |
| 82 |
free(stats.dinfo); |
| 83 |
return NULL; |
| 84 |
} |