1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
|
/*
* $Id: _psutil_osx.c 1360 2012-06-25 22:52:54Z jcscoobyrs@gmail.com $
*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* OS X platform-specific module methods for _psutil_osx
*/
#include <Python.h>
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <utmpx.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <libproc.h>
#include <sys/proc_info.h>
#include <netinet/tcp_fsm.h>
#include <arpa/inet.h>
#include <net/if_dl.h>
#include <pwd.h>
#include <mach/mach.h>
#include <mach/task.h>
#include <mach/mach_init.h>
#include <mach/host_info.h>
#include <mach/mach_host.h>
#include <mach/mach_traps.h>
#include <mach/mach_vm.h>
#include <mach/shared_memory_server.h>
#include <mach-o/loader.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/IOBSD.h>
#include "_psutil_osx.h"
#include "_psutil_common.h"
#include "arch/osx/process_info.h"
/*
* Return a Python list of all the PIDs running on the system.
*/
static PyObject*
get_pid_list(PyObject* self, PyObject* args)
{
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
size_t idx;
PyObject *pid;
PyObject *retlist = PyList_New(0);
if (get_proc_list(&proclist, &num_processes) != 0) {
Py_DECREF(retlist);
PyErr_SetString(PyExc_RuntimeError, "failed to retrieve process list.");
return NULL;
}
if (num_processes > 0) {
// save the address of proclist so we can free it later
orig_address = proclist;
for (idx=0; idx < num_processes; idx++) {
pid = Py_BuildValue("i", proclist->kp_proc.p_pid);
PyList_Append(retlist, pid);
Py_XDECREF(pid);
proclist++;
}
free(orig_address);
}
return retlist;
}
/*
* Return process name from kinfo_proc as a Python string.
*/
static PyObject*
get_process_name(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("s", kp.kp_proc.p_comm);
}
/*
* Return process cmdline as a Python list of cmdline arguments.
*/
static PyObject*
get_process_cmdline(PyObject* self, PyObject* args)
{
long pid;
PyObject* arglist = NULL;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
// get the commandline, defined in arch/osx/process_info.c
arglist = get_arg_list(pid);
return arglist;
}
/*
* Return process parent pid from kinfo_proc as a Python integer.
*/
static PyObject*
get_process_ppid(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("l", (long)kp.kp_eproc.e_ppid);
}
/*
* Return process real uid from kinfo_proc as a Python integer.
*/
static PyObject*
get_process_uids(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("lll", (long)kp.kp_eproc.e_pcred.p_ruid,
(long)kp.kp_eproc.e_ucred.cr_uid,
(long)kp.kp_eproc.e_pcred.p_svuid);
}
/*
* Return process real group id from ki_comm as a Python integer.
*/
static PyObject*
get_process_gids(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("lll", (long)kp.kp_eproc.e_pcred.p_rgid,
(long)kp.kp_eproc.e_ucred.cr_groups[0],
(long)kp.kp_eproc.e_pcred.p_svgid);
}
/*
* Return process controlling terminal number as an integer.
*/
static PyObject*
get_process_tty_nr(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("i", kp.kp_eproc.e_tdev);
}
/*
* Return a list of tuples for every process memory maps.
* 'procstat' cmdline utility has been used as an example.
*/
static PyObject*
get_process_memory_maps(PyObject* self, PyObject* args)
{
char buf[PATH_MAX];
char addr_str[34];
char perms[8];
int pagesize = getpagesize();
long pid;
kern_return_t err = KERN_SUCCESS;
mach_port_t task;
uint32_t depth = 1;
vm_address_t address = 0;
vm_size_t size = 0;
PyObject* py_tuple = NULL;
PyObject* py_list = PyList_New(0);
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
err = task_for_pid(mach_task_self(), pid, &task);
if (err != KERN_SUCCESS) {
if (! pid_exists(pid)) {
return NoSuchProcess();
}
// pid exists, so return AccessDenied error since task_for_pid() failed
return AccessDenied();
}
while (1) {
struct vm_region_submap_info_64 info;
mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
err = vm_region_recurse_64(task, &address, &size, &depth,
(vm_region_info_64_t)&info, &count);
if (err == KERN_INVALID_ADDRESS) {
break;
}
if (info.is_submap) {
depth++;
}
else {
// Free/Reset the char[]s to avoid weird paths
memset(buf, 0, sizeof(buf));
memset(addr_str, 0, sizeof(addr_str));
memset(perms, 0, sizeof(perms));
sprintf(addr_str, "%016x-%016x", address, address + size);
sprintf(perms, "%c%c%c/%c%c%c",
(info.protection & VM_PROT_READ) ? 'r' : '-',
(info.protection & VM_PROT_WRITE) ? 'w' : '-',
(info.protection & VM_PROT_EXECUTE) ? 'x' : '-',
(info.max_protection & VM_PROT_READ) ? 'r' : '-',
(info.max_protection & VM_PROT_WRITE) ? 'w' : '-',
(info.max_protection & VM_PROT_EXECUTE) ? 'x' : '-');
address += size;
err = proc_regionfilename(pid, address, buf, sizeof(buf));
if (info.share_mode == SM_COW && info.ref_count == 1) {
// Treat single reference SM_COW as SM_PRIVATE
info.share_mode = SM_PRIVATE;
}
if (strlen(buf) == 0) {
switch(info.share_mode) {
/*
case SM_LARGE_PAGE:
// Treat SM_LARGE_PAGE the same as SM_PRIVATE
// since they are not shareable and are wired.
*/
case SM_COW:
strcpy(buf, "[cow]");
break;
case SM_PRIVATE:
strcpy(buf, "[prv]");
break;
case SM_EMPTY:
strcpy(buf, "[nul]");
break;
case SM_SHARED:
case SM_TRUESHARED:
strcpy(buf, "[shm]");
break;
case SM_PRIVATE_ALIASED:
strcpy(buf, "[ali]");
break;
case SM_SHARED_ALIASED:
strcpy(buf, "[s/a]");
break;
default:
strcpy(buf, "[???]");
}
}
py_tuple = Py_BuildValue("sssIIIIIH",
addr_str, // "start-end" address
perms, // "rwx" permissions
buf, // path
info.pages_resident * pagesize, // rss
info.pages_shared_now_private * pagesize, // private
info.pages_swapped_out * pagesize, // swapped
info.pages_dirtied * pagesize, // dirtied
info.ref_count, // ref count
info.shadow_depth // shadow depth
);
PyList_Append(py_list, py_tuple);
Py_XDECREF(py_tuple);
}
}
return py_list;
}
/*
* Return a Python integer indicating the number of CPUs on the system.
*/
static PyObject*
get_num_cpus(PyObject* self, PyObject* args)
{
int mib[2];
int ncpu;
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
return Py_BuildValue("i", ncpu);
}
#define TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
/*
* Return a Python tuple (user_time, kernel_time)
*/
static PyObject*
get_cpu_times(PyObject* self, PyObject* args)
{
long pid;
int err;
unsigned int info_count = TASK_BASIC_INFO_COUNT;
task_port_t task; // = (task_port_t)NULL;
time_value_t user_time, system_time;
struct task_basic_info tasks_info;
struct task_thread_times_info task_times;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
/* task_for_pid() requires special privileges
* "This function can be called only if the process is owned by the
* procmod group or if the caller is root."
* - http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_19.html */
err = task_for_pid(mach_task_self(), pid, &task);
if ( err == KERN_SUCCESS) {
info_count = TASK_BASIC_INFO_COUNT;
err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count);
if (err != KERN_SUCCESS) {
// errcode 4 is "invalid argument" (access denied)
if (err == 4) {
return AccessDenied();
}
// otherwise throw a runtime error with appropriate error code
return PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) failed");
}
info_count = TASK_THREAD_TIMES_INFO_COUNT;
err = task_info(task, TASK_THREAD_TIMES_INFO,
(task_info_t)&task_times, &info_count);
if (err != KERN_SUCCESS) {
// errcode 4 is "invalid argument" (access denied)
if (err == 4) {
return AccessDenied();
}
return PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) failed");
}
}
else { // task_for_pid failed
if (! pid_exists(pid) ) {
return NoSuchProcess();
}
// pid exists, so return AccessDenied error since task_for_pid() failed
return AccessDenied();
}
float user_t = -1.0;
float sys_t = -1.0;
user_time = tasks_info.user_time;
system_time = tasks_info.system_time;
time_value_add(&user_time, &task_times.user_time);
time_value_add(&system_time, &task_times.system_time);
user_t = (float)user_time.seconds + ((float)user_time.microseconds / 1000000.0);
sys_t = (float)system_time.seconds + ((float)system_time.microseconds / 1000000.0);
return Py_BuildValue("(dd)", user_t, sys_t);
}
/*
* Return a Python float indicating the process create time expressed in
* seconds since the epoch.
*/
static PyObject*
get_process_create_time(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("d", TV2DOUBLE(kp.kp_proc.p_starttime));
}
/*
* Return a tuple of RSS and VMS memory usage.
*/
static PyObject*
get_memory_info(PyObject* self, PyObject* args)
{
long pid;
int err;
unsigned int info_count = TASK_BASIC_INFO_COUNT;
mach_port_t task;
struct task_basic_info tasks_info;
vm_region_basic_info_data_64_t b_info;
vm_address_t address = GLOBAL_SHARED_TEXT_SEGMENT;
vm_size_t size;
mach_port_t object_name;
// the argument passed should be a process id
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
/* task_for_pid() requires special privileges
* "This function can be called only if the process is owned by the
* procmod group or if the caller is root."
* - http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_19.html */
err = task_for_pid(mach_task_self(), pid, &task);
if ( err == KERN_SUCCESS) {
info_count = TASK_BASIC_INFO_COUNT;
err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count);
if (err != KERN_SUCCESS) {
if (err == 4) {
// errcode 4 is "invalid argument" (access denied)
return AccessDenied();
}
// otherwise throw a runtime error with appropriate error code
return PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) failed");
}
/* Issue #73 http://code.google.com/p/psutil/issues/detail?id=73
* adjust the virtual memory size down to account for
* shared memory that task_info.virtual_size includes w/every process
*/
info_count = VM_REGION_BASIC_INFO_COUNT_64;
err = vm_region_64(task, &address, &size, VM_REGION_BASIC_INFO,
(vm_region_info_t)&b_info, &info_count, &object_name);
if (err == KERN_SUCCESS) {
if (b_info.reserved && size == (SHARED_TEXT_REGION_SIZE) &&
tasks_info.virtual_size > (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE))
{
tasks_info.virtual_size -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE);
}
}
}
else {
if (! pid_exists(pid) ) {
return NoSuchProcess();
}
// pid exists, so return AccessDenied error since task_for_pid() failed
return AccessDenied();
}
return Py_BuildValue("(ll)", tasks_info.resident_size, tasks_info.virtual_size);
}
/*
* Return number of threads used by process as a Python integer.
*/
static PyObject*
get_process_num_threads(PyObject* self, PyObject* args)
{
long pid;
int err, ret;
unsigned int info_count = TASK_BASIC_INFO_COUNT;
mach_port_t task;
struct task_basic_info tasks_info;
thread_act_port_array_t thread_list;
mach_msg_type_number_t thread_count;
// the argument passed should be a process id
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
/* task_for_pid() requires special privileges
* "This function can be called only if the process is owned by the
* procmod group or if the caller is root."
* - http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_19.html
*/
err = task_for_pid(mach_task_self(), pid, &task);
if ( err == KERN_SUCCESS) {
info_count = TASK_BASIC_INFO_COUNT;
err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count);
if (err != KERN_SUCCESS) {
// errcode 4 is "invalid argument" (access denied)
if (err == 4) {
return AccessDenied();
}
// otherwise throw a runtime error with appropriate error code
return PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) failed");
}
err = task_threads(task, &thread_list, &thread_count);
if (err == KERN_SUCCESS) {
ret = vm_deallocate(task, (vm_address_t)thread_list,
thread_count * sizeof(int));
if (ret != KERN_SUCCESS) {
printf("vm_deallocate() failed\n");
}
return Py_BuildValue("l", (long)thread_count);
}
else {
return PyErr_Format(PyExc_RuntimeError, "task_thread() failed");
}
}
else {
if (! pid_exists(pid) ) {
return NoSuchProcess();
}
// pid exists, so return AccessDenied error since task_for_pid() failed
return AccessDenied();
}
return NULL;
}
/*
* Return a Python integer indicating the total amount of physical memory
* in bytes.
*/
static PyObject*
get_total_phymem(PyObject* self, PyObject* args)
{
int mib[2];
uint64_t total_phymem;
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
len = sizeof(total_phymem);
if (sysctl(mib, 2, &total_phymem, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
return Py_BuildValue("L", total_phymem);
}
/*
* Return a Python long indicating the amount of available physical memory in
* bytes.
*/
static PyObject*
get_avail_phymem(PyObject* self, PyObject* args)
{
vm_statistics_data_t vm_stat;
mach_msg_type_number_t count;
kern_return_t error;
unsigned long long mem_free;
int pagesize = getpagesize();
mach_port_t mport = mach_host_self();
count = sizeof(vm_stat) / sizeof(natural_t);
error = host_statistics(mport, HOST_VM_INFO, (host_info_t)&vm_stat, &count);
if (error != KERN_SUCCESS) {
return PyErr_Format(PyExc_RuntimeError,
"Error in host_statistics(): %s", mach_error_string(error));
}
mem_free = (unsigned long long) vm_stat.free_count * pagesize;
return Py_BuildValue("L", mem_free);
}
/*
* Return a Python integer indicating the total amount of virtual memory
* in bytes.
*/
static PyObject*
get_total_virtmem(PyObject* self, PyObject* args)
{
int mib[2];
size_t size;
struct xsw_usage totals;
mib[0] = CTL_VM;
mib[1] = VM_SWAPUSAGE;
size = sizeof(totals);
if (sysctl(mib, 2, &totals, &size, NULL, 0) == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
return Py_BuildValue("L", totals.xsu_total);
}
/*
* Return a Python integer indicating the avail amount of virtual memory
* in bytes.
*/
static PyObject*
get_avail_virtmem(PyObject* self, PyObject* args)
{
int mib[2];
size_t size;
struct xsw_usage totals;
mib[0] = CTL_VM;
mib[1] = VM_SWAPUSAGE;
size = sizeof(totals);
if (sysctl(mib, 2, &totals, &size, NULL, 0) == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
return Py_BuildValue("L", totals.xsu_avail);
}
/*
* Return a Python tuple representing user, kernel and idle CPU times
*/
static PyObject*
get_system_cpu_times(PyObject* self, PyObject* args)
{
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
kern_return_t error;
host_cpu_load_info_data_t r_load;
error = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&r_load, &count);
if (error != KERN_SUCCESS) {
return PyErr_Format(PyExc_RuntimeError,
"Error in host_statistics(): %s", mach_error_string(error));
}
return Py_BuildValue("(dddd)",
(double)r_load.cpu_ticks[CPU_STATE_USER] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
(double)r_load.cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
);
}
/*
* Return a Python list of tuple representing per-cpu times
*/
static PyObject*
get_system_per_cpu_times(PyObject* self, PyObject* args)
{
natural_t cpu_count;
processor_info_array_t info_array;
mach_msg_type_number_t info_count;
kern_return_t error;
processor_cpu_load_info_data_t* cpu_load_info;
PyObject* py_retlist = PyList_New(0);
PyObject* py_cputime;
int i, ret;
error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO,
&cpu_count, &info_array, &info_count);
if (error != KERN_SUCCESS) {
return PyErr_Format(PyExc_RuntimeError,
"Error in host_processor_info(): %s", mach_error_string(error));
}
cpu_load_info = (processor_cpu_load_info_data_t*) info_array;
for (i = 0; i < cpu_count; i++) {
py_cputime = Py_BuildValue("(dddd)",
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_USER] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] / CLK_TCK,
(double)cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE] / CLK_TCK
);
PyList_Append(py_retlist, py_cputime);
Py_XDECREF(py_cputime);
}
ret = vm_deallocate(mach_task_self(), (vm_address_t)info_array,
info_count * sizeof(int));
if (ret != KERN_SUCCESS) {
printf("vm_deallocate() failed\n");
}
return py_retlist;
}
/*
* Return a Python float indicating the system boot time expressed in
* seconds since the epoch.
*/
static PyObject*
get_system_boot_time(PyObject* self, PyObject* args)
{
/* fetch sysctl "kern.boottime" */
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval result;
size_t result_len = sizeof result;
time_t boot_time = 0;
if (sysctl(request, 2, &result, &result_len, NULL, 0) == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
boot_time = result.tv_sec;
return Py_BuildValue("f", (float)boot_time);
}
/*
* Return a list of tuples including device, mount point and fs type
* for all partitions mounted on the system.
*/
static PyObject*
get_disk_partitions(PyObject* self, PyObject* args)
{
int num;
int i;
long len;
uint64_t flags;
char opts[400];
struct statfs *fs;
PyObject* py_retlist = PyList_New(0);
PyObject* py_tuple;
// get the number of mount points
Py_BEGIN_ALLOW_THREADS
num = getfsstat(NULL, 0, MNT_NOWAIT);
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(0);
return NULL;
}
len = sizeof(*fs) * num;
fs = malloc(len);
Py_BEGIN_ALLOW_THREADS
num = getfsstat(fs, len, MNT_NOWAIT);
Py_END_ALLOW_THREADS
if (num == -1) {
free(fs);
PyErr_SetFromErrno(0);
return NULL;
}
for (i = 0; i < num; i++) {
opts[0] = 0;
flags = fs[i].f_flags;
// see sys/mount.h
if (flags & MNT_RDONLY)
strlcat(opts, "ro", sizeof(opts));
else
strlcat(opts, "rw", sizeof(opts));
if (flags & MNT_SYNCHRONOUS)
strlcat(opts, ",sync", sizeof(opts));
if (flags & MNT_NOEXEC)
strlcat(opts, ",noexec", sizeof(opts));
if (flags & MNT_NOSUID)
strlcat(opts, ",nosuid", sizeof(opts));
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_ASYNC)
strlcat(opts, ",async", sizeof(opts));
if (flags & MNT_EXPORTED)
strlcat(opts, ",exported", sizeof(opts));
if (flags & MNT_QUARANTINE)
strlcat(opts, ",quarantine", sizeof(opts));
if (flags & MNT_LOCAL)
strlcat(opts, ",local", sizeof(opts));
if (flags & MNT_QUOTA)
strlcat(opts, ",quota", sizeof(opts));
if (flags & MNT_ROOTFS)
strlcat(opts, ",rootfs", sizeof(opts));
if (flags & MNT_DOVOLFS)
strlcat(opts, ",dovolfs", sizeof(opts));
if (flags & MNT_DONTBROWSE)
strlcat(opts, ",dontbrowse", sizeof(opts));
if (flags & MNT_IGNORE_OWNERSHIP)
strlcat(opts, ",ignore-ownership", sizeof(opts));
if (flags & MNT_AUTOMOUNTED)
strlcat(opts, ",automounted", sizeof(opts));
if (flags & MNT_JOURNALED)
strlcat(opts, ",journaled", sizeof(opts));
if (flags & MNT_NOUSERXATTR)
strlcat(opts, ",nouserxattr", sizeof(opts));
if (flags & MNT_DEFWRITE)
strlcat(opts, ",defwrite", sizeof(opts));
if (flags & MNT_MULTILABEL)
strlcat(opts, ",multilabel", sizeof(opts));
if (flags & MNT_NOATIME)
strlcat(opts, ",noatime", sizeof(opts));
if (flags & MNT_UPDATE)
strlcat(opts, ",update", sizeof(opts));
if (flags & MNT_RELOAD)
strlcat(opts, ",reload", sizeof(opts));
if (flags & MNT_FORCE)
strlcat(opts, ",force", sizeof(opts));
if (flags & MNT_CMDFLAGS)
strlcat(opts, ",cmdflags", sizeof(opts));
py_tuple = Py_BuildValue("(ssss)", fs[i].f_mntfromname, // device
fs[i].f_mntonname, // mount point
fs[i].f_fstypename, // fs type
opts); // options
PyList_Append(py_retlist, py_tuple);
Py_XDECREF(py_tuple);
}
free(fs);
return py_retlist;
}
/*
* Return process status as a Python integer.
*/
static PyObject*
get_process_status(PyObject* self, PyObject* args)
{
long pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
if (get_kinfo_proc(pid, &kp) == -1) {
return NULL;
}
return Py_BuildValue("i", (int)kp.kp_proc.p_stat);
}
/*
* Return process threads
*/
static PyObject*
get_process_threads(PyObject* self, PyObject* args)
{
long pid;
int err, j, ret;
kern_return_t kr;
unsigned int info_count = TASK_BASIC_INFO_COUNT;
mach_port_t task;
struct task_basic_info tasks_info;
thread_act_port_array_t thread_list;
thread_info_data_t thinfo;
thread_basic_info_t basic_info_th;
mach_msg_type_number_t thread_count, thread_info_count;
PyObject* retList = PyList_New(0);
PyObject* pyTuple = NULL;
// the argument passed should be a process id
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
// task_for_pid() requires special privileges
err = task_for_pid(mach_task_self(), pid, &task);
if (err != KERN_SUCCESS) {
if (! pid_exists(pid) ) {
return NoSuchProcess();
}
return AccessDenied();
}
info_count = TASK_BASIC_INFO_COUNT;
err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count);
if (err != KERN_SUCCESS) {
// errcode 4 is "invalid argument" (access denied)
if (err == 4) {
return AccessDenied();
}
// otherwise throw a runtime error with appropriate error code
return PyErr_Format(PyExc_RuntimeError,
"task_info(TASK_BASIC_INFO) failed");
}
err = task_threads(task, &thread_list, &thread_count);
if (err != KERN_SUCCESS) {
return PyErr_Format(PyExc_RuntimeError, "task_threads() failed");
}
for (j = 0; j < thread_count; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return PyErr_Format(PyExc_RuntimeError, "thread_info() failed");
}
basic_info_th = (thread_basic_info_t)thinfo;
// XXX - thread_info structure does not provide any process id;
// the best we can do is assigning an incremental bogus value
pyTuple = Py_BuildValue("Iff", j + 1,
(float)basic_info_th->user_time.microseconds / 1000000.0,
(float)basic_info_th->system_time.microseconds / 1000000.0
);
PyList_Append(retList, pyTuple);
Py_XDECREF(pyTuple);
}
ret = vm_deallocate(task, (vm_address_t)thread_list,
thread_count * sizeof(int));
if (ret != KERN_SUCCESS) {
printf("vm_deallocate() failed\n");
}
return retList;
}
/*
* Return process open files as a Python tuple.
* References:
* - lsof source code: http://goo.gl/SYW79 and http://goo.gl/m78fd
* - /usr/include/sys/proc_info.h
*/
static PyObject*
get_process_open_files(PyObject* self, PyObject* args)
{
long pid;
int pidinfo_result;
int iterations;
int i;
int nb;
struct proc_fdinfo *fds_pointer;
struct proc_fdinfo *fdp_pointer;
struct vnode_fdinfowithpath vi;
PyObject *retList = PyList_New(0);
PyObject *tuple = NULL;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
if (pidinfo_result <= 0) {
goto error;
}
fds_pointer = malloc(pidinfo_result);
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer,
pidinfo_result);
if (pidinfo_result <= 0) {
free(fds_pointer);
goto error;
}
iterations = (pidinfo_result / PROC_PIDLISTFD_SIZE);
for (i = 0; i < iterations; i++) {
fdp_pointer = &fds_pointer[i];
//
if (fdp_pointer->proc_fdtype == PROX_FDTYPE_VNODE)
{
nb = proc_pidfdinfo(pid,
fdp_pointer->proc_fd,
PROC_PIDFDVNODEPATHINFO,
&vi,
sizeof(vi));
// --- errors checking
if (nb <= 0) {
if ((errno == ENOENT) || (errno == EBADF)) {
// no such file or directory or bad file descriptor;
// let's assume the file has been closed or removed
continue;
}
if (errno != 0) {
free(fds_pointer);
return PyErr_SetFromErrno(PyExc_OSError);
}
else
free(fds_pointer);
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDFDVNODEPATHINFO) failed");
}
if (nb < sizeof(vi)) {
free(fds_pointer);
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDFDVNODEPATHINFO) failed (buffer mismatch)");
}
// --- /errors checking
// --- construct python list
tuple = Py_BuildValue("(si)", vi.pvip.vip_path,
(int)fdp_pointer->proc_fd);
PyList_Append(retList, tuple);
Py_DECREF(tuple);
// --- /construct python list
}
}
free(fds_pointer);
return retList;
error:
if (errno != 0) {
return PyErr_SetFromErrno(PyExc_OSError);
}
else if (! pid_exists(pid) ) {
return NoSuchProcess();
}
else {
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDLISTFDS) failed");
}
}
/*
* mathes Linux net/tcp_states.h:
* http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
*/
static char *
get_connection_status(int st) {
switch (st) {
case TCPS_CLOSED:
return "CLOSE";
case TCPS_CLOSING:
return "CLOSING";
case TCPS_CLOSE_WAIT:
return "CLOSE_WAIT";
case TCPS_LISTEN:
return "LISTEN";
case TCPS_ESTABLISHED:
return "ESTABLISHED";
case TCPS_SYN_SENT:
return "SYN_SENT";
case TCPS_SYN_RECEIVED:
return "SYN_RECV";
case TCPS_FIN_WAIT_1:
return "FIN_WAIT_1";
case TCPS_FIN_WAIT_2:
return "FIN_WAIT_2";
case TCPS_LAST_ACK:
return "LAST_ACK";
case TCPS_TIME_WAIT:
return "TIME_WAIT";
default:
return "";
}
}
/*
* Return process TCP and UDP connections as a list of tuples.
* References:
* - lsof source code: http://goo.gl/SYW79 and http://goo.gl/wNrC0
* - /usr/include/sys/proc_info.h
*/
static PyObject*
get_process_connections(PyObject* self, PyObject* args)
{
long pid;
int pidinfo_result;
int iterations;
int i;
int nb;
struct proc_fdinfo *fds_pointer;
struct proc_fdinfo *fdp_pointer;
struct socket_fdinfo si;
PyObject *retList = PyList_New(0);
PyObject *tuple = NULL;
PyObject *laddr = NULL;
PyObject *raddr = NULL;
PyObject *af_filter = NULL;
PyObject *type_filter = NULL;
if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter)) {
return NULL;
}
if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
return NULL;
}
if (pid == 0) {
return retList;
}
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
if (pidinfo_result <= 0) {
goto error;
}
fds_pointer = malloc(pidinfo_result);
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer,
pidinfo_result);
if (pidinfo_result <= 0) {
free(fds_pointer);
goto error;
}
iterations = (pidinfo_result / PROC_PIDLISTFD_SIZE);
for (i = 0; i < iterations; i++) {
errno = 0;
fdp_pointer = &fds_pointer[i];
//
if (fdp_pointer->proc_fdtype == PROX_FDTYPE_SOCKET)
{
nb = proc_pidfdinfo(pid, fdp_pointer->proc_fd, PROC_PIDFDSOCKETINFO,
&si, sizeof(si));
// --- errors checking
if (nb <= 0) {
if (errno == EBADF) {
// let's assume socket has been closed
continue;
}
if (errno != 0) {
free(fds_pointer);
return PyErr_SetFromErrno(PyExc_OSError);
}
else {
free(fds_pointer);
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDFDVNODEPATHINFO) failed");
}
}
if (nb < sizeof(si)) {
free(fds_pointer);
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDFDVNODEPATHINFO) failed (buffer mismatch)");
}
// --- /errors checking
//
int fd, family, type, lport, rport;
char lip[200], rip[200];
char *state;
int inseq;
PyObject* _family;
PyObject* _type;
fd = (int)fdp_pointer->proc_fd;
family = si.psi.soi_family;
type = si.psi.soi_kind;
if (type == 2) {
type = SOCK_STREAM;
}
else if (type == 1) {
type = SOCK_DGRAM;
}
else {
continue;
}
// apply filters
_family = PyLong_FromLong((long)family);
inseq = PySequence_Contains(af_filter, _family);
Py_DECREF(_family);
if (inseq == 0) {
continue;
}
_type = PyLong_FromLong((long)type);
inseq = PySequence_Contains(type_filter, _type);
Py_DECREF(_type);
if (inseq == 0) {
continue;
}
if (errno != 0) {
free(fds_pointer);
return PyErr_SetFromErrno(PyExc_OSError);
}
if (family == AF_INET) {
inet_ntop(AF_INET,
&si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_46.i46a_addr4,
lip,
sizeof(lip));
inet_ntop(AF_INET,
&si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_46.i46a_addr4,
rip,
sizeof(rip));
}
else {
inet_ntop(AF_INET6,
&si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_6,
lip, sizeof(lip));
inet_ntop(AF_INET6,
&si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_6,
rip, sizeof(rip));
}
// check for inet_ntop failures
if (errno != 0) {
free(fds_pointer);
return PyErr_SetFromErrno(PyExc_OSError);
}
lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
if (type == SOCK_STREAM) {
state = get_connection_status((int)si.psi.soi_proto.pri_tcp.tcpsi_state);
}
else {
state = "";
}
laddr = Py_BuildValue("(si)", lip, lport);
if (rport != 0) {
raddr = Py_BuildValue("(si)", rip, rport);
}
else {
raddr = PyTuple_New(0);
}
// --- construct python list
tuple = Py_BuildValue("(iiiNNs)", fd, family, type, laddr, raddr,
state);
PyList_Append(retList, tuple);
Py_DECREF(tuple);
// --- /construct python list
}
}
free(fds_pointer);
return retList;
error:
if (errno != 0) {
return PyErr_SetFromErrno(PyExc_OSError);
}
else if (! pid_exists(pid) ) {
return NoSuchProcess();
}
else {
return PyErr_Format(PyExc_RuntimeError,
"proc_pidinfo(PROC_PIDLISTFDS) failed");
}
}
/*
* Return number of file descriptors opened by process.
*/
static PyObject*
get_process_num_fds(PyObject* self, PyObject* args)
{
long pid;
int pidinfo_result;
int num;
struct proc_fdinfo *fds_pointer;
if (! PyArg_ParseTuple(args, "l", &pid)) {
return NULL;
}
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
if (pidinfo_result <= 0) {
return PyErr_SetFromErrno(PyExc_OSError);
}
fds_pointer = malloc(pidinfo_result);
pidinfo_result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer,
pidinfo_result);
if (pidinfo_result <= 0) {
free(fds_pointer);
return PyErr_SetFromErrno(PyExc_OSError);
}
num = (pidinfo_result / PROC_PIDLISTFD_SIZE);
return Py_BuildValue("i", num);
}
/*
* Return a Python list of named tuples with overall network I/O information
*/
static PyObject*
get_network_io_counters(PyObject* self, PyObject* args)
{
PyObject* py_retdict = PyDict_New();
PyObject* py_ifc_info;
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
size_t len;
mib[0] = CTL_NET; // networking subsystem
mib[1] = PF_ROUTE; // type of information
mib[2] = 0; // protocol (IPPROTO_xxx)
mib[3] = 0; // address family
mib[4] = NET_RT_IFLIST2; // operation
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
Py_DECREF(py_retdict);
PyErr_SetFromErrno(0);
return NULL;
}
buf = malloc(len);
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
if (buf) {
free(buf);
}
Py_DECREF(py_retdict);
PyErr_SetFromErrno(0);
return NULL;
}
lim = buf + len;
for (next = buf; next < lim; ) {
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_type == RTM_IFINFO2) {
struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
char ifc_name[32];
strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
ifc_name[sdl->sdl_nlen] = 0;
py_ifc_info = Py_BuildValue("(KKKK)",
if2m->ifm_data.ifi_obytes,
if2m->ifm_data.ifi_ibytes,
if2m->ifm_data.ifi_opackets,
if2m->ifm_data.ifi_ipackets);
PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info);
Py_XDECREF(py_ifc_info);
}
else {
continue;
}
}
free(buf);
return py_retdict;
}
/*
* Return a Python dict of tuples for disk I/O information
*/
static PyObject*
get_disk_io_counters(PyObject* self, PyObject* args)
{
PyObject* py_retdict = PyDict_New();
PyObject* py_disk_info;
CFDictionaryRef parent_dict;
CFDictionaryRef props_dict;
CFDictionaryRef stats_dict;
io_registry_entry_t parent;
io_registry_entry_t disk;
io_iterator_t disk_list;
/* Get list of disks */
if (IOServiceGetMatchingServices(kIOMasterPortDefault,
IOServiceMatching(kIOMediaClass),
&disk_list) != kIOReturnSuccess) {
Py_DECREF(py_retdict);
PyErr_SetString(PyExc_RuntimeError, "Unable to get the list of disks.");
return NULL;
}
/* Iterate over disks */
while ((disk = IOIteratorNext(disk_list)) != 0) {
parent_dict = NULL;
props_dict = NULL;
stats_dict = NULL;
if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent) != kIOReturnSuccess) {
PyErr_SetString(PyExc_RuntimeError, "Unable to get the disk's parent.");
Py_DECREF(py_retdict);
IOObjectRelease(disk);
return NULL;
}
if (IOObjectConformsTo(parent, "IOBlockStorageDriver")) {
if(IORegistryEntryCreateCFProperties(
disk,
(CFMutableDictionaryRef *) &parent_dict,
kCFAllocatorDefault,
kNilOptions) != kIOReturnSuccess)
{
PyErr_SetString(PyExc_RuntimeError,
"Unable to get the parent's properties.");
Py_DECREF(py_retdict);
IOObjectRelease(disk);
IOObjectRelease(parent);
return NULL;
}
if (IORegistryEntryCreateCFProperties(parent,
(CFMutableDictionaryRef *) &props_dict,
kCFAllocatorDefault,
kNilOptions) != kIOReturnSuccess)
{
PyErr_SetString(PyExc_RuntimeError,
"Unable to get the disk properties.");
Py_DECREF(py_retdict);
IOObjectRelease(disk);
return NULL;
}
const int kMaxDiskNameSize = 64;
CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue(
parent_dict,
CFSTR(kIOBSDNameKey));
char disk_name[kMaxDiskNameSize];
CFStringGetCString(disk_name_ref,
disk_name,
kMaxDiskNameSize,
CFStringGetSystemEncoding());
stats_dict = (CFDictionaryRef)CFDictionaryGetValue(
props_dict,
CFSTR(kIOBlockStorageDriverStatisticsKey));
if (stats_dict == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Unable to get disk stats.");
Py_DECREF(py_retdict);
CFRelease(props_dict);
IOObjectRelease(disk);
IOObjectRelease(parent);
return NULL;
}
CFNumberRef number;
int64_t reads, writes, read_bytes, write_bytes, read_time, write_time = 0;
/* Get disk reads/writes */
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsReadsKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &reads);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsWritesKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &writes);
}
/* Get disk bytes read/written */
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes);
}
/* Get disk time spent reading/writing (nanoseconds) */
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey))))
{
CFNumberGetValue(number, kCFNumberSInt64Type, &read_time);
}
if ((number = (CFNumberRef)CFDictionaryGetValue(
stats_dict,
CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey)))) {
CFNumberGetValue(number, kCFNumberSInt64Type, &write_time);
}
// Read/Write time on OS X comes back in nanoseconds and in psutil
// we've standardized on milliseconds so do the conversion.
py_disk_info = Py_BuildValue("(KKKKKK)",
reads, writes,
read_bytes, write_bytes,
read_time / 1000, write_time / 1000);
PyDict_SetItemString(py_retdict, disk_name, py_disk_info);
Py_XDECREF(py_disk_info);
CFRelease(parent_dict);
IOObjectRelease(parent);
CFRelease(props_dict);
IOObjectRelease(disk);
}
}
IOObjectRelease (disk_list);
return py_retdict;
}
/*
* Return currently connected users as a list of tuples.
*/
static PyObject*
get_system_users(PyObject* self, PyObject* args)
{
PyObject *ret_list = PyList_New(0);
PyObject *tuple = NULL;
struct utmpx ut;
FILE *fp;
fp = fopen(_PATH_UTMPX, "r");
if (fp == NULL) {
// man fopen says errno is set but it seems it's not (OSX 10.6)
return PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMPX);
}
while (fread(&ut, sizeof(ut), 1, fp) == 1) {
if (*ut.ut_user == '\0') {
continue;
}
#ifdef UTMPX_USER_PROCESS
if (ut.ut_type != UTMPX_USER_PROCESS) {
continue;
}
#endif
tuple = Py_BuildValue("(sssf)",
ut.ut_user, // username
ut.ut_line, // tty
ut.ut_host, // hostname
(float)ut.ut_tv.tv_sec // login time
);
PyList_Append(ret_list, tuple);
Py_DECREF(tuple);
}
fclose(fp);
return ret_list;
}
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef
PsutilMethods[] =
{
// --- per-process functions
{"get_process_name", get_process_name, METH_VARARGS,
"Return process name"},
{"get_process_cmdline", get_process_cmdline, METH_VARARGS,
"Return process cmdline as a list of cmdline arguments"},
{"get_process_ppid", get_process_ppid, METH_VARARGS,
"Return process ppid as an integer"},
{"get_process_uids", get_process_uids, METH_VARARGS,
"Return process real user id as an integer"},
{"get_process_gids", get_process_gids, METH_VARARGS,
"Return process real group id as an integer"},
{"get_cpu_times", get_cpu_times, METH_VARARGS,
"Return tuple of user/kern time for the given PID"},
{"get_process_create_time", get_process_create_time, METH_VARARGS,
"Return a float indicating the process create time expressed in "
"seconds since the epoch"},
{"get_memory_info", get_memory_info, METH_VARARGS,
"Return a tuple of RSS/VMS memory information"},
{"get_process_num_threads", get_process_num_threads, METH_VARARGS,
"Return number of threads used by process"},
{"get_process_status", get_process_status, METH_VARARGS,
"Return process status as an integer"},
{"get_process_threads", get_process_threads, METH_VARARGS,
"Return process threads as a list of tuples"},
{"get_process_open_files", get_process_open_files, METH_VARARGS,
"Return files opened by process as a list of tuples"},
{"get_process_num_fds", get_process_num_fds, METH_VARARGS,
"Return the number of fds opened by process."},
{"get_process_connections", get_process_connections, METH_VARARGS,
"Get process TCP and UDP connections as a list of tuples"},
{"get_process_tty_nr", get_process_tty_nr, METH_VARARGS,
"Return process tty number as an integer"},
{"get_process_memory_maps", get_process_memory_maps, METH_VARARGS,
"Return a list of tuples for every process's memory map"},
// --- system-related functions
{"get_pid_list", get_pid_list, METH_VARARGS,
"Returns a list of PIDs currently running on the system"},
{"get_num_cpus", get_num_cpus, METH_VARARGS,
"Return number of CPUs on the system"},
{"get_total_phymem", get_total_phymem, METH_VARARGS,
"Return the total amount of physical memory, in bytes"},
{"get_avail_phymem", get_avail_phymem, METH_VARARGS,
"Return the amount of available physical memory, in bytes"},
{"get_total_virtmem", get_total_virtmem, METH_VARARGS,
"Return the total amount of virtual memory, in bytes"},
{"get_avail_virtmem", get_avail_virtmem, METH_VARARGS,
"Return the amount of available virtual memory, in bytes"},
{"get_system_cpu_times", get_system_cpu_times, METH_VARARGS,
"Return system cpu times as a tuple (user, system, nice, idle, irc)"},
{"get_system_per_cpu_times", get_system_per_cpu_times, METH_VARARGS,
"Return system per-cpu times as a list of tuples"},
{"get_system_boot_time", get_system_boot_time, METH_VARARGS,
"Return a float indicating the system boot time expressed in "
"seconds since the epoch"},
{"get_disk_partitions", get_disk_partitions, METH_VARARGS,
"Return a list of tuples including device, mount point and "
"fs type for all partitions mounted on the system."},
{"get_network_io_counters", get_network_io_counters, METH_VARARGS,
"Return dict of tuples of networks I/O information."},
{"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
"Return dict of tuples of disks I/O information."},
{"get_system_users", get_system_users, METH_VARARGS,
"Return currently connected users as a list of tuples"},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
#endif
#if PY_MAJOR_VERSION >= 3
static int
psutil_osx_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int
psutil_osx_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef
moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_osx",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_osx_traverse,
psutil_osx_clear,
NULL
};
#define INITERROR return NULL
PyObject *
PyInit__psutil_osx(void)
#else
#define INITERROR return
void
init_psutil_osx(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_osx", PsutilMethods);
#endif
// process status constants, defined in:
// http://fxr.watson.org/fxr/source/bsd/sys/proc.h?v=xnu-792.6.70#L149
PyModule_AddIntConstant(module, "SIDL", SIDL);
PyModule_AddIntConstant(module, "SRUN", SRUN);
PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
PyModule_AddIntConstant(module, "SSTOP", SSTOP);
PyModule_AddIntConstant(module, "SZOMB", SZOMB);
if (module == NULL) {
INITERROR;
}
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
|