From 0a157b1205482e163f91032cddf1e40eb8942056 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Wed, 17 Feb 2021 14:43:56 +1100 Subject: [PATCH 01/20] Add a platform for Performance Co-Pilot (PCP) metrics This introduces an initial platform for extracting metrics using the PCP performance metrics API - PMAPI(3). It can be used via the --enable-pcp=yes configure option. So far I've added support for live localhost metrics only, and only using pre-defined metrics already found in htop. If available, all sampling is performed by pmcd(1) - else, we fallback to htop doing the metric sampling itself (all below the PMAPI). When pmcd is used, it may be configured to run children with elevated privileges, so htop does not need to be setuid (authentication with pmcd is available). Additionally, the PMAPI allows us to support archives (for historical analysis and for automated regression tests in htop). We'll need platform-specific command line argument additions, which isn't yet feasible in htop (not difficult to add though). The goal of this first version is minimal impact in terms of modifying the htop codebase, to introduce key ideas in PCP (metric namespace, metadata, APIs and so on) and give us something to discuss, experiment with and build on. --- Makefile.am | 23 ++ configure.ac | 26 ++ pcp/PCPProcess.c | 517 ++++++++++++++++++++++++++++ pcp/PCPProcess.h | 140 ++++++++ pcp/PCPProcessList.c | 779 +++++++++++++++++++++++++++++++++++++++++++ pcp/PCPProcessList.h | 68 ++++ pcp/Platform.c | 687 ++++++++++++++++++++++++++++++++++++++ pcp/Platform.h | 214 ++++++++++++ pcp/ProcessField.h | 50 +++ 9 files changed, 2504 insertions(+) create mode 100644 pcp/PCPProcess.c create mode 100644 pcp/PCPProcess.h create mode 100644 pcp/PCPProcessList.c create mode 100644 pcp/PCPProcessList.h create mode 100644 pcp/Platform.c create mode 100644 pcp/Platform.h create mode 100644 pcp/ProcessField.h diff --git a/Makefile.am b/Makefile.am index f9b9a7d47..c66aa46c6 100644 --- a/Makefile.am +++ b/Makefile.am @@ -328,6 +328,29 @@ myhtopplatheaders = $(solaris_platform_headers) myhtopplatsources = $(solaris_platform_sources) endif +# Performance Co-Pilot (PCP) +# -------------------------- + +pcp_platform_headers = \ + pcp/PCPProcess.h \ + pcp/PCPProcessList.h \ + pcp/Platform.h \ + pcp/ProcessField.h \ + linux/PressureStallMeter.h \ + linux/ZramMeter.h \ + linux/ZramStats.h + +if HTOP_PCP +myhtopplatsources = \ + pcp/PCPProcess.c \ + pcp/PCPProcessList.c \ + pcp/Platform.c \ + linux/PressureStallMeter.c \ + linux/ZramMeter.c + +myhtopplatheaders = $(pcp_platform_headers) +endif + # Unsupported # ----------- diff --git a/configure.ac b/configure.ac index 78250621e..f9cfa914c 100644 --- a/configure.ac +++ b/configure.ac @@ -95,6 +95,31 @@ esac # ---------------------------------------------------------------------- +# ---------------------------------------------------------------------- +# Checks for a PCP-based htop build. (https://pcp.io) +# ---------------------------------------------------------------------- + +AC_ARG_ENABLE([pcp], + [AS_HELP_STRING([--enable-pcp], + [build a pcp htop binary @<:@default=no@:>@])], + [], + [enable_pcp=no]) +case "$enable_pcp" in + no) + ;; + yes) + AC_CHECK_HEADERS([pcp/pmapi.h], [my_htop_platform=pcp], + [AC_MSG_ERROR([can not find PCP header file])]) + AC_SEARCH_LIBS([pmNewContext], [pcp], [], [AC_MSG_ERROR([can not find pcp library])]) + AC_DEFINE([HTOP_PCP], [1], [Define if building pcp htop binary.]) + ;; + *) + AC_MSG_ERROR([bad value '$enable_static' for --enable-static option]) + ;; +esac + +# ---------------------------------------------------------------------- + # ---------------------------------------------------------------------- # Checks for generic header files. @@ -608,6 +633,7 @@ AM_CONDITIONAL([HTOP_DRAGONFLYBSD], [test "$my_htop_platform" = dragonflybsd]) AM_CONDITIONAL([HTOP_OPENBSD], [test "$my_htop_platform" = openbsd]) AM_CONDITIONAL([HTOP_DARWIN], [test "$my_htop_platform" = darwin]) AM_CONDITIONAL([HTOP_SOLARIS], [test "$my_htop_platform" = solaris]) +AM_CONDITIONAL([HTOP_PCP], [test "$my_htop_platform" = pcp]) AM_CONDITIONAL([HTOP_UNSUPPORTED], [test "$my_htop_platform" = unsupported]) AC_SUBST(my_htop_platform) diff --git a/pcp/PCPProcess.c b/pcp/PCPProcess.c new file mode 100644 index 000000000..7e8f59aef --- /dev/null +++ b/pcp/PCPProcess.c @@ -0,0 +1,517 @@ +/* +htop - PCPProcess.c +(C) 2014 Hisham H. Muhammad +(C) 2020 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "PCPProcess.h" + +#include +#include +#include +#include +#include +#include + +#include "CRT.h" +#include "Process.h" +#include "ProvideCurses.h" +#include "XUtils.h" + +/* Used to identify kernel threads in Comm column */ +static const char *const kthreadID = "KTHREAD"; + +const ProcessFieldData Process_fields[] = { + [0] = { .name = "", .title = NULL, .description = NULL, .flags = 0, }, + [PID] = { .name = "PID", .title = "PID", .description = "Process/thread ID", .flags = 0, .pidColumn = true, }, + [COMM] = { .name = "Command", .title = "Command ", .description = "Command line", .flags = 0, }, + [STATE] = { .name = "STATE", .title = "S ", .description = "Process state (S sleeping, R running, D disk, Z zombie, T traced, W paging, I idle)", .flags = 0, }, + [PPID] = { .name = "PPID", .title = "PPID", .description = "Parent process ID", .flags = 0, }, + [PGRP] = { .name = "PGRP", .title = "PGRP", .description = "Process group ID", .flags = 0, }, + [SESSION] = { .name = "SESSION", .title = "SID", .description = "Process's session ID", .flags = 0, }, + [TTY_NR] = { .name = "TTY_NR", .title = "TTY ", .description = "Controlling terminal", .flags = 0, }, + [TPGID] = { .name = "TPGID", .title = "TPGID", .description = "Process ID of the fg process group of the controlling terminal", .flags = 0, }, + [MINFLT] = { .name = "MINFLT", .title = " MINFLT ", .description = "Number of minor faults which have not required loading a memory page from disk", .flags = 0, .defaultSortDesc = true, }, + [CMINFLT] = { .name = "CMINFLT", .title = " CMINFLT ", .description = "Children processes' minor faults", .flags = 0, .defaultSortDesc = true, }, + [MAJFLT] = { .name = "MAJFLT", .title = " MAJFLT ", .description = "Number of major faults which have required loading a memory page from disk", .flags = 0, .defaultSortDesc = true, }, + [CMAJFLT] = { .name = "CMAJFLT", .title = " CMAJFLT ", .description = "Children processes' major faults", .flags = 0, .defaultSortDesc = true, }, + [UTIME] = { .name = "UTIME", .title = " UTIME+ ", .description = "User CPU time - time the process spent executing in user mode", .flags = 0, .defaultSortDesc = true, }, + [STIME] = { .name = "STIME", .title = " STIME+ ", .description = "System CPU time - time the kernel spent running system calls for this process", .flags = 0, .defaultSortDesc = true, }, + [CUTIME] = { .name = "CUTIME", .title = " CUTIME+ ", .description = "Children processes' user CPU time", .flags = 0, .defaultSortDesc = true, }, + [CSTIME] = { .name = "CSTIME", .title = " CSTIME+ ", .description = "Children processes' system CPU time", .flags = 0, .defaultSortDesc = true, }, + [PRIORITY] = { .name = "PRIORITY", .title = "PRI ", .description = "Kernel's internal priority for the process", .flags = 0, }, + [NICE] = { .name = "NICE", .title = " NI ", .description = "Nice value (the higher the value, the more it lets other processes take priority)", .flags = 0, }, + [STARTTIME] = { .name = "STARTTIME", .title = "START ", .description = "Time the process was started", .flags = 0, }, + [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "If of the CPU the process last executed on", .flags = 0, }, + [M_VIRT] = { .name = "M_VIRT", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, .defaultSortDesc = true, }, + [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, .defaultSortDesc = true, }, + [M_SHARE] = { .name = "M_SHARE", .title = " SHR ", .description = "Size of the process's shared pages", .flags = 0, .defaultSortDesc = true, }, + [M_TRS] = { .name = "M_TRS", .title = " CODE ", .description = "Size of the text segment of the process", .flags = 0, .defaultSortDesc = true, }, + [M_DRS] = { .name = "M_DRS", .title = " DATA ", .description = "Size of the data segment plus stack usage of the process", .flags = 0, .defaultSortDesc = true, }, + [M_LRS] = { .name = "M_LRS", .title = " LIB ", .description = "The library size of the process (unused since Linux 2.6; always 0)", .flags = 0, .defaultSortDesc = true, }, + [M_DT] = { .name = "M_DT", .title = " DIRTY ", .description = "Size of the dirty pages of the process (unused since Linux 2.6; always 0)", .flags = 0, .defaultSortDesc = true, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, .defaultSortDesc = true, }, + [PERCENT_NORM_CPU] = { .name = "PERCENT_NORM_CPU", .title = "NCPU%", .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", .flags = 0, .defaultSortDesc = true, }, + [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, .defaultSortDesc = true, }, + [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, + [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", .flags = 0, .defaultSortDesc = true, }, + [NLWP] = { .name = "NLWP", .title = "NLWP ", .description = "Number of threads in the process", .flags = 0, .defaultSortDesc = true, }, + [TGID] = { .name = "TGID", .title = "TGID", .description = "Thread group ID (i.e. process ID)", .flags = 0, }, + [RCHAR] = { .name = "RCHAR", .title = "RCHAR ", .description = "Number of bytes the process has read", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [WCHAR] = { .name = "WCHAR", .title = "WCHAR ", .description = "Number of bytes the process has written", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [SYSCR] = { .name = "SYSCR", .title = " READ_SYSC ", .description = "Number of read(2) syscalls for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [SYSCW] = { .name = "SYSCW", .title = " WRITE_SYSC ", .description = "Number of write(2) syscalls for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [RBYTES] = { .name = "RBYTES", .title = " IO_R ", .description = "Bytes of read(2) I/O for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [WBYTES] = { .name = "WBYTES", .title = " IO_W ", .description = "Bytes of write(2) I/O for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [CNCLWB] = { .name = "CNCLWB", .title = " IO_C ", .description = "Bytes of cancelled write(2) I/O", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [IO_READ_RATE] = { .name = "IO_READ_RATE", .title = " DISK READ ", .description = "The I/O rate of read(2) in bytes per second for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [IO_WRITE_RATE] = { .name = "IO_WRITE_RATE", .title = " DISK WRITE ", .description = "The I/O rate of write(2) in bytes per second for the process", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [IO_RATE] = { .name = "IO_RATE", .title = " DISK R/W ", .description = "Total I/O rate in bytes per second", .flags = PROCESS_FLAG_IO, .defaultSortDesc = true, }, + [CGROUP] = { .name = "CGROUP", .title = " CGROUP ", .description = "Which cgroup the process is in", .flags = PROCESS_FLAG_LINUX_CGROUP, }, + [OOM] = { .name = "OOM", .title = " OOM ", .description = "OOM (Out-of-Memory) killer score", .flags = PROCESS_FLAG_LINUX_OOM, .defaultSortDesc = true, }, + [PERCENT_CPU_DELAY] = { .name = "PERCENT_CPU_DELAY", .title = "CPUD% ", .description = "CPU delay %", .flags = 0, .defaultSortDesc = true, }, + [PERCENT_IO_DELAY] = { .name = "PERCENT_IO_DELAY", .title = "IOD% ", .description = "Block I/O delay %", .flags = 0, .defaultSortDesc = true, }, + [PERCENT_SWAP_DELAY] = { .name = "PERCENT_SWAP_DELAY", .title = "SWAPD% ", .description = "Swapin delay %", .flags = 0, .defaultSortDesc = true, }, + [M_PSS] = { .name = "M_PSS", .title = " PSS ", .description = "proportional set size, same as M_RESIDENT but each page is divided by the number of processes sharing it.", .flags = PROCESS_FLAG_LINUX_SMAPS, .defaultSortDesc = true, }, + [M_SWAP] = { .name = "M_SWAP", .title = " SWAP ", .description = "Size of the process's swapped pages", .flags = PROCESS_FLAG_LINUX_SMAPS, .defaultSortDesc = true, }, + [M_PSSWP] = { .name = "M_PSSWP", .title = " PSSWP ", .description = "shows proportional swap share of this mapping, Unlike \"Swap\", this does not take into account swapped out page of underlying shmem objects.", .flags = PROCESS_FLAG_LINUX_SMAPS, .defaultSortDesc = true, }, + [CTXT] = { .name = "CTXT", .title = " CTXT ", .description = "Context switches (incremental sum of voluntary_ctxt_switches and nonvoluntary_ctxt_switches)", .flags = PROCESS_FLAG_LINUX_CTXT, .defaultSortDesc = true, }, + [SECATTR] = { .name = "SECATTR", .title = " Security Attribute ", .description = "Security attribute of the process (e.g. SELinux or AppArmor)", .flags = PROCESS_FLAG_LINUX_SECATTR, }, + [PROC_COMM] = { .name = "COMM", .title = "COMM ", .description = "comm string of the process from /proc/[pid]/comm", .flags = 0, }, +}; + +/* This function returns the string displayed in Command column, so that sorting + * happens on what is displayed - whether comm, full path, basename, etc.. So + * this follows PCPProcess_writeField(COMM) and PCPProcess_writeCommand */ +static const char* PCPProcess_getCommandStr(const Process *this) { + const PCPProcess *pp = (const PCPProcess *)this; + if ((Process_isUserlandThread(this) && this->settings->showThreadNames) || !pp->mergedCommand.str) { + return this->comm; + } + return pp->mergedCommand.str; +} + +Process* PCPProcess_new(const Settings* settings) { + PCPProcess* this = xCalloc(1, sizeof(PCPProcess)); + Object_setClass(this, Class(PCPProcess)); + Process_init(&this->super, settings); + return &this->super; +} + +void Process_delete(Object* cast) { + PCPProcess* this = (PCPProcess*) cast; + Process_done((Process*)cast); + free(this->cgroup); + free(this->secattr); + free(this->ttyDevice); + free(this->procComm); + free(this->mergedCommand.str); + free(this); +} + +static void PCPProcess_printDelay(float delay_percent, char* buffer, int n) { + if (isnan(delay_percent)) { + xSnprintf(buffer, n, " N/A "); + } else { + xSnprintf(buffer, n, "%4.1f ", delay_percent); + } +} + +/* +TASK_COMM_LEN is defined to be 16 for /proc/[pid]/comm in man proc(5), but is +not available in an userspace header - so define it. Note: when colorizing a +basename with the comm prefix, the entire basename (not just the comm prefix) +is colorized for better readability, and it is implicit that only up to +(TASK_COMM_LEN - 1) could be comm. +*/ +#define TASK_COMM_LEN 16 + +/* +This function makes the merged Command string. It also stores the offsets of +the basename, comm w.r.t the merged Command string - these offsets will be used +by PCPProcess_writeCommand() for coloring. The merged Command string is also +returned by PCPProcess_getCommandStr() for searching, sorting and filtering. +*/ +void PCPProcess_makeCommandStr(Process* this) { + PCPProcess *pp = (PCPProcess *)this; + PCPProcessMergedCommand *mc = &pp->mergedCommand; + + bool showMergedCommand = this->settings->showMergedCommand; + bool showProgramPath = this->settings->showProgramPath; + bool searchCommInCmdline = this->settings->findCommInCmdline; + + /* pp->mergedCommand.str needs updating only if its state or contents + * changed. Its content is based on the fields cmdline and comm. */ + if ( + mc->prevMergeSet == showMergedCommand && + mc->prevPathSet == showProgramPath && + mc->prevCommSet == searchCommInCmdline && + !mc->cmdlineChanged && + !mc->commChanged + ) { + return; + } + + /* The field separtor "│" has been chosen such that it will not match any + * valid string used for searching or filtering */ + const char *SEPARATOR = CRT_treeStr[TREE_STR_VERT]; + const int SEPARATOR_LEN = strlen(SEPARATOR); + + /* Check for any changed fields since we last built this string */ + if (mc->cmdlineChanged || mc->commChanged) { + free(mc->str); + /* Accommodate the column text, two field separators and terminating NUL */ + mc->str = xCalloc(1, mc->maxLen + 2*SEPARATOR_LEN + 1); + } + + /* Preserve the settings used in this run */ + mc->prevMergeSet = showMergedCommand; + mc->prevPathSet = showProgramPath; + mc->prevCommSet = searchCommInCmdline; + + /* Mark everything as unchanged */ + mc->cmdlineChanged = false; + mc->commChanged = false; + + /* Clear any separators */ + mc->sep1 = 0; + mc->sep2 = 0; + /* Clear any highlighting locations */ + mc->baseStart = 0; + mc->baseEnd = 0; + mc->commStart = 0; + mc->commEnd = 0; + + const char *cmdline = this->comm; + const char *procComm = pp->procComm; + + char *strStart = mc->str; + char *str = strStart; + + int cmdlineBasenameOffset = pp->procCmdlineBasenameOffset; + int cmdlineBasenameEnd = pp->procCmdlineBasenameEnd; + + if (!cmdline) { + cmdlineBasenameOffset = 0; + cmdlineBasenameEnd = 0; + cmdline = "(zombie)"; + } + + assert(cmdlineBasenameOffset >= 0); + assert(cmdlineBasenameOffset <= (int)strlen(cmdline)); + + if (showMergedCommand && procComm && strlen(procComm)) { /* Prefix column with comm */ + if (strncmp(cmdline + cmdlineBasenameOffset, procComm, MINIMUM(TASK_COMM_LEN - 1, strlen(procComm))) != 0) { + mc->commStart = 0; + mc->commEnd = strlen(procComm); + + str = stpcpy(str, procComm); + + mc->sep1 = str - strStart; + str = stpcpy(str, SEPARATOR); + } + } + + if (showProgramPath) { + (void) stpcpy(str, cmdline); + mc->baseStart = cmdlineBasenameOffset; + mc->baseEnd = cmdlineBasenameEnd; + } else { + (void) stpcpy(str, cmdline + cmdlineBasenameOffset); + mc->baseStart = 0; + mc->baseEnd = cmdlineBasenameEnd - cmdlineBasenameOffset; + } + + if (mc->sep1) { + mc->baseStart += str - strStart - SEPARATOR_LEN + 1; + mc->baseEnd += str - strStart - SEPARATOR_LEN + 1; + } +} + +static void PCPProcess_writeCommand(const Process* this, int attr, int baseAttr, RichString* str) { + const PCPProcess *pp = (const PCPProcess *)this; + const PCPProcessMergedCommand *mc = &pp->mergedCommand; + + int strStart = RichString_size(str); + + int baseStart = strStart + pp->mergedCommand.baseStart; + int baseEnd = strStart + pp->mergedCommand.baseEnd; + int commStart = strStart + pp->mergedCommand.commStart; + int commEnd = strStart + pp->mergedCommand.commEnd; + + int commAttr = CRT_colors[Process_isUserlandThread(this) ? PROCESS_THREAD_COMM : PROCESS_COMM]; + + bool highlightBaseName = this->settings->highlightBaseName; + + RichString_appendWide(str, attr, pp->mergedCommand.str); + + if (pp->mergedCommand.commEnd) { + if (!pp->mergedCommand.separateComm && commStart == baseStart && highlightBaseName) { + /* If it was matched with binaries basename, make it bold if needed */ + if (commEnd > baseEnd) { + RichString_setAttrn(str, A_BOLD | baseAttr, baseStart, baseEnd - baseStart); + RichString_setAttrn(str, A_BOLD | commAttr, baseEnd, commEnd - baseEnd); + } else if (commEnd < baseEnd) { + RichString_setAttrn(str, A_BOLD | commAttr, commStart, commEnd - commStart); + RichString_setAttrn(str, A_BOLD | baseAttr, commEnd, baseEnd - commEnd); + } else { + // Actually should be highlighted commAttr, but marked baseAttr to reduce visual noise + RichString_setAttrn(str, A_BOLD | baseAttr, commStart, commEnd - commStart); + } + + baseStart = baseEnd; + } else { + RichString_setAttrn(str, commAttr, commStart, commEnd - commStart); + } + } + + if (baseStart < baseEnd && highlightBaseName) { + RichString_setAttrn(str, baseAttr, baseStart, baseEnd - baseStart); + } + + if (mc->sep1) + RichString_setAttrn(str, CRT_colors[FAILED_READ], strStart + mc->sep1, 1); + if (mc->sep2) + RichString_setAttrn(str, CRT_colors[FAILED_READ], strStart + mc->sep2, 1); +} + +static void PCPProcess_writeCommandField(const Process *this, RichString *str, char *buffer, int n, int attr) { + /* This code is from Process_writeField for COMM, but we invoke + * PCPProcess_writeCommand to display the full binary path + * (or its basename)│/proc/pid/comm│/proc/pid/cmdline */ + int baseattr = CRT_colors[PROCESS_BASENAME]; + if (this->settings->highlightThreads && Process_isThread(this)) { + attr = CRT_colors[PROCESS_THREAD]; + baseattr = CRT_colors[PROCESS_THREAD_BASENAME]; + } + if (!this->settings->treeView || this->indent == 0) { + PCPProcess_writeCommand(this, attr, baseattr, str); + } else { + char* buf = buffer; + int maxIndent = 0; + bool lastItem = (this->indent < 0); + int indent = (this->indent < 0 ? -this->indent : this->indent); + int vertLen = strlen(CRT_treeStr[TREE_STR_VERT]); + + for (int i = 0; i < 32; i++) { + if (indent & (1U << i)) { + maxIndent = i+1; + } + } + for (int i = 0; i < maxIndent - 1; i++) { + if (indent & (1 << i)) { + if (buf - buffer + (vertLen + 3) > n) { + break; + } + buf = stpcpy(buf, CRT_treeStr[TREE_STR_VERT]); + buf = stpcpy(buf, " "); + } else { + if (buf - buffer + 4 > n) { + break; + } + buf = stpcpy(buf, " "); + } + } + + n -= (buf - buffer); + const char* draw = CRT_treeStr[lastItem ? TREE_STR_BEND : TREE_STR_RTEE]; + xSnprintf(buf, n, "%s%s ", draw, this->showChildren ? CRT_treeStr[TREE_STR_SHUT] : CRT_treeStr[TREE_STR_OPEN] ); + RichString_appendWide(str, CRT_colors[PROCESS_TREE], buffer); + PCPProcess_writeCommand(this, attr, baseattr, str); + } +} + +static void PCPProcess_writeField(const Process* this, RichString* str, ProcessField field) { + const PCPProcess* pp = (const PCPProcess*) this; + bool coloring = this->settings->highlightMegabytes; + char buffer[256]; buffer[255] = '\0'; + int attr = CRT_colors[DEFAULT_COLOR]; + int n = sizeof(buffer) - 1; + switch ((int)field) { + case TTY_NR: + if (pp->ttyDevice) { + xSnprintf(buffer, n, "%-8s", pp->ttyDevice + 5 /* skip "/dev/" */); + break; + } + Process_writeField(this, str, field); + break; + case CMINFLT: Process_colorNumber(str, pp->cminflt, coloring); return; + case CMAJFLT: Process_colorNumber(str, pp->cmajflt, coloring); return; + case M_DRS: Process_humanNumber(str, pp->m_drs, coloring); return; + case M_DT: Process_humanNumber(str, pp->m_dt, coloring); return; + case M_LRS: Process_humanNumber(str, pp->m_lrs, coloring); return; + case M_TRS: Process_humanNumber(str, pp->m_trs, coloring); return; + case M_SHARE: Process_humanNumber(str, pp->m_share, coloring); return; + case M_PSS: Process_humanNumber(str, pp->m_pss, coloring); return; + case M_SWAP: Process_humanNumber(str, pp->m_swap, coloring); return; + case M_PSSWP: Process_humanNumber(str, pp->m_psswp, coloring); return; + case UTIME: Process_printTime(str, pp->utime); return; + case STIME: Process_printTime(str, pp->stime); return; + case CUTIME: Process_printTime(str, pp->cutime); return; + case CSTIME: Process_printTime(str, pp->cstime); return; + case RCHAR: Process_humanNumber(str, pp->io_rchar, coloring); return; + case WCHAR: Process_humanNumber(str, pp->io_wchar, coloring); return; + case SYSCR: Process_colorNumber(str, pp->io_syscr, coloring); return; + case SYSCW: Process_colorNumber(str, pp->io_syscw, coloring); return; + case RBYTES: Process_humanNumber(str, pp->io_read_bytes, coloring); return; + case WBYTES: Process_humanNumber(str, pp->io_write_bytes, coloring); return; + case CNCLWB: Process_humanNumber(str, pp->io_cancelled_write_bytes, coloring); return; + case IO_READ_RATE: Process_outputRate(str, buffer, n, pp->io_rate_read_bps, coloring); return; + case IO_WRITE_RATE: Process_outputRate(str, buffer, n, pp->io_rate_write_bps, coloring); return; + case IO_RATE: { + double totalRate = NAN; + if (!isnan(pp->io_rate_read_bps) && !isnan(pp->io_rate_write_bps)) + totalRate = pp->io_rate_read_bps + pp->io_rate_write_bps; + else if (!isnan(pp->io_rate_read_bps)) + totalRate = pp->io_rate_read_bps; + else if (!isnan(pp->io_rate_write_bps)) + totalRate = pp->io_rate_write_bps; + else + totalRate = NAN; + Process_outputRate(str, buffer, n, totalRate, coloring); return; + } + case CGROUP: xSnprintf(buffer, n, "%-10s ", pp->cgroup ? pp->cgroup : ""); break; + case OOM: xSnprintf(buffer, n, "%4u ", pp->oom); break; + case PERCENT_CPU_DELAY: + PCPProcess_printDelay(pp->cpu_delay_percent, buffer, n); + break; + case PERCENT_IO_DELAY: + PCPProcess_printDelay(pp->blkio_delay_percent, buffer, n); + break; + case PERCENT_SWAP_DELAY: + PCPProcess_printDelay(pp->swapin_delay_percent, buffer, n); + break; + case CTXT: + if (pp->ctxt_diff > 1000) { + attr |= A_BOLD; + } + xSnprintf(buffer, n, "%5lu ", pp->ctxt_diff); + break; + case SECATTR: snprintf(buffer, n, "%-30s ", pp->secattr ? pp->secattr : "?"); break; + case COMM: { + if ((Process_isUserlandThread(this) && this->settings->showThreadNames) || !pp->mergedCommand.str) { + Process_writeField(this, str, field); + } else { + PCPProcess_writeCommandField(this, str, buffer, n, attr); + } + return; + } + case PROC_COMM: { + const char* procComm; + if (pp->procComm) { + attr = CRT_colors[Process_isUserlandThread(this) ? PROCESS_THREAD_COMM : PROCESS_COMM]; + procComm = pp->procComm; + } else { + attr = CRT_colors[PROCESS_SHADOW]; + procComm = Process_isKernelThread(this) ? kthreadID : "N/A"; + } + /* 15 being (TASK_COMM_LEN - 1) */ + Process_printLeftAlignedField(str, attr, procComm, 15); + return; + } + default: + Process_writeField(this, str, field); + return; + } + RichString_appendWide(str, attr, buffer); +} + +static double adjustNaN(double num) { + if (isnan(num)) + return -0.0005; + + return num; +} + +static int PCPProcess_compareByKey(const Process* v1, const Process* v2, ProcessField key) { + const PCPProcess* p1 = (const PCPProcess*)v1; + const PCPProcess* p2 = (const PCPProcess*)v2; + + switch (key) { + case M_DRS: + return SPACESHIP_NUMBER(p1->m_drs, p2->m_drs); + case M_DT: + return SPACESHIP_NUMBER(p1->m_dt, p2->m_dt); + case M_LRS: + return SPACESHIP_NUMBER(p1->m_lrs, p2->m_lrs); + case M_TRS: + return SPACESHIP_NUMBER(p1->m_trs, p2->m_trs); + case M_SHARE: + return SPACESHIP_NUMBER(p1->m_share, p2->m_share); + case M_PSS: + return SPACESHIP_NUMBER(p1->m_pss, p2->m_pss); + case M_SWAP: + return SPACESHIP_NUMBER(p1->m_swap, p2->m_swap); + case M_PSSWP: + return SPACESHIP_NUMBER(p1->m_psswp, p2->m_psswp); + case UTIME: + return SPACESHIP_NUMBER(p1->utime, p2->utime); + case CUTIME: + return SPACESHIP_NUMBER(p1->cutime, p2->cutime); + case STIME: + return SPACESHIP_NUMBER(p1->stime, p2->stime); + case CSTIME: + return SPACESHIP_NUMBER(p1->cstime, p2->cstime); + case RCHAR: + return SPACESHIP_NUMBER(p1->io_rchar, p2->io_rchar); + case WCHAR: + return SPACESHIP_NUMBER(p1->io_wchar, p2->io_wchar); + case SYSCR: + return SPACESHIP_NUMBER(p1->io_syscr, p2->io_syscr); + case SYSCW: + return SPACESHIP_NUMBER(p1->io_syscw, p2->io_syscw); + case RBYTES: + return SPACESHIP_NUMBER(p1->io_read_bytes, p2->io_read_bytes); + case WBYTES: + return SPACESHIP_NUMBER(p1->io_write_bytes, p2->io_write_bytes); + case CNCLWB: + return SPACESHIP_NUMBER(p1->io_cancelled_write_bytes, p2->io_cancelled_write_bytes); + case IO_READ_RATE: + return SPACESHIP_NUMBER(adjustNaN(p1->io_rate_read_bps), adjustNaN(p2->io_rate_read_bps)); + case IO_WRITE_RATE: + return SPACESHIP_NUMBER(adjustNaN(p1->io_rate_write_bps), adjustNaN(p2->io_rate_write_bps)); + case IO_RATE: + return SPACESHIP_NUMBER(adjustNaN(p1->io_rate_read_bps) + adjustNaN(p1->io_rate_write_bps), adjustNaN(p2->io_rate_read_bps) + adjustNaN(p2->io_rate_write_bps)); + case CGROUP: + return SPACESHIP_NULLSTR(p1->cgroup, p2->cgroup); + case OOM: + return SPACESHIP_NUMBER(p1->oom, p1->oom); + case PERCENT_CPU_DELAY: + return SPACESHIP_NUMBER(p1->cpu_delay_percent, p1->cpu_delay_percent); + case PERCENT_IO_DELAY: + return SPACESHIP_NUMBER(p1->blkio_delay_percent, p1->blkio_delay_percent); + case PERCENT_SWAP_DELAY: + return SPACESHIP_NUMBER(p1->swapin_delay_percent, p1->swapin_delay_percent); + case CTXT: + return SPACESHIP_NUMBER(p1->ctxt_diff, p1->ctxt_diff); + case SECATTR: + return SPACESHIP_NULLSTR(p1->secattr, p2->secattr); + case PROC_COMM: { + const char *comm1 = p1->procComm ? p1->procComm : (Process_isKernelThread(v1) ? kthreadID : ""); + const char *comm2 = p2->procComm ? p2->procComm : (Process_isKernelThread(v2) ? kthreadID : ""); + return strcmp(comm1, comm2); + } + default: + return Process_compareByKey_Base(v1, v2, key); + } +} + +bool Process_isThread(const Process* this) { + return (Process_isUserlandThread(this) || Process_isKernelThread(this)); +} + +const ProcessClass PCPProcess_class = { + .super = { + .extends = Class(Process), + .display = Process_display, + .delete = Process_delete, + .compare = Process_compare + }, + .writeField = PCPProcess_writeField, + .getCommandStr = PCPProcess_getCommandStr, + .compareByKey = PCPProcess_compareByKey +}; diff --git a/pcp/PCPProcess.h b/pcp/PCPProcess.h new file mode 100644 index 000000000..9819f5c91 --- /dev/null +++ b/pcp/PCPProcess.h @@ -0,0 +1,140 @@ +#ifndef HEADER_PCPProcess +#define HEADER_PCPProcess +/* +htop - PCPProcess.h +(C) 2014 Hisham H. Muhammad +(C) 2020 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" + +#include +#include + +#include "Object.h" +#include "Process.h" +#include "RichString.h" +#include "Settings.h" + +#define PROCESS_FLAG_LINUX_CGROUP 0x0800 +#define PROCESS_FLAG_LINUX_OOM 0x1000 +#define PROCESS_FLAG_LINUX_SMAPS 0x2000 +#define PROCESS_FLAG_LINUX_CTXT 0x4000 +#define PROCESS_FLAG_LINUX_SECATTR 0x8000 + +/* PCPProcessMergedCommand is populated by PCPProcess_makeCommandStr: It + * contains the merged Command string, and the information needed by + * PCPProcess_writeCommand to color the string. str will be NULL for kernel + * threads and zombies */ +typedef struct PCPProcessMergedCommand_ { + char *str; /* merged Command string */ + int maxLen; /* maximum expected length of Command string */ + int baseStart; /* basename's start offset */ + int baseEnd; /* basename's end offset */ + int commStart; /* comm's start offset */ + int commEnd; /* comm's end offset */ + int sep1; /* first field separator, used if non-zero */ + int sep2; /* second field separator, used if non-zero */ + bool separateComm; /* whether comm is a separate field */ + bool cmdlineChanged; /* whether cmdline changed */ + bool commChanged; /* whether comm changed */ + bool prevMergeSet; /* whether showMergedCommand was set */ + bool prevPathSet; /* whether showProgramPath was set */ + bool prevCommSet; /* whether findCommInCmdline was set */ + bool prevCmdlineSet; /* whether findCommInCmdline was set */ +} PCPProcessMergedCommand; + +typedef struct PCPProcess_ { + Process super; + char *procComm; + int procCmdlineBasenameOffset; + int procCmdlineBasenameEnd; + PCPProcessMergedCommand mergedCommand; + bool isKernelThread; + unsigned long int cminflt; + unsigned long int cmajflt; + unsigned long long int utime; + unsigned long long int stime; + unsigned long long int cutime; + unsigned long long int cstime; + long m_share; + long m_pss; + long m_swap; + long m_psswp; + long m_trs; + long m_drs; + long m_lrs; + long m_dt; + + /* Data read (in kilobytes) */ + unsigned long long io_rchar; + + /* Data written (in kilobytes) */ + unsigned long long io_wchar; + + /* Number of read(2) syscalls */ + unsigned long long io_syscr; + + /* Number of write(2) syscalls */ + unsigned long long io_syscw; + + /* Storage data read (in kilobytes) */ + unsigned long long io_read_bytes; + + /* Storage data written (in kilobytes) */ + unsigned long long io_write_bytes; + + /* Storage data cancelled (in kilobytes) */ + unsigned long long io_cancelled_write_bytes; + + /* Point in time of last io scan (in seconds elapsed since the Epoch) */ + unsigned long long io_last_scan_time; + + double io_rate_read_bps; + double io_rate_write_bps; + char* cgroup; + unsigned int oom; + char* ttyDevice; + unsigned long long int delay_read_time; + unsigned long long cpu_delay_total; + unsigned long long blkio_delay_total; + unsigned long long swapin_delay_total; + float cpu_delay_percent; + float blkio_delay_percent; + float swapin_delay_percent; + unsigned long ctxt_total; + unsigned long ctxt_diff; + char* secattr; + unsigned long long int last_mlrs_calctime; +} PCPProcess; + +static inline void Process_setKernelThread(Process* this, bool truth) { + ((PCPProcess*)this)->isKernelThread = truth; +} + +static inline bool Process_isKernelThread(const Process* this) { + return ((const PCPProcess*)this)->isKernelThread; +} + +static inline bool Process_isUserlandThread(const Process* this) { + return this->pid != this->tgid; +} + +extern const ProcessFieldData Process_fields[LAST_PROCESSFIELD]; + +extern const ProcessClass PCPProcess_class; + +Process* PCPProcess_new(const Settings* settings); + +void Process_delete(Object* cast); + +/* This function constructs the string that is displayed by + * PCPProcess_writeCommand and also returned by PCPProcess_getCommandStr */ +void PCPProcess_makeCommandStr(Process *this); + +bool Process_isThread(const Process* this); + +#endif diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c new file mode 100644 index 000000000..0e608b1de --- /dev/null +++ b/pcp/PCPProcessList.c @@ -0,0 +1,779 @@ +/* +htop - PCPProcessList.c +(C) 2014 Hisham H. Muhammad +(C) 2020 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include "PCPProcessList.h" + +#include + +#include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "PCPProcess.h" +#include "Process.h" +#include "Settings.h" +#include "XUtils.h" + + +static int PCPProcessList_computeCPUcount(void) { + int cpus; + if ((cpus = Platform_getMaxCPU()) <= 0) + cpus = Metric_instanceCount(PCP_PERCPU_SYSTEM); + return cpus > 1 ? cpus : 1; +} + +static void PCPProcessList_updateCPUcount(PCPProcessList* this) { + ProcessList* pl = &(this->super); + int cpus = PCPProcessList_computeCPUcount(); + if (cpus == pl->cpuCount) + return; + + pl->cpuCount = cpus; + free(this->percpu); + free(this->values); + + this->percpu = xCalloc(cpus, sizeof(pmAtomValue *)); + for (int i = 0; i < cpus; i++) + this->percpu[i] = xCalloc(CPU_METRIC_COUNT, sizeof(pmAtomValue)); + this->values = xCalloc(cpus, sizeof(pmAtomValue)); +} + +static char* setUser(UsersTable* this, unsigned int uid, int pid, int offset) { + char* name = Hashtable_get(this->users, uid); + if (name) + return name; + + pmAtomValue value; + if (Metric_instance(PCP_PROC_ID_USER, pid, offset, &value, PM_TYPE_STRING)) { + Hashtable_put(this->users, uid, value.cp); + name = value.cp; + } + return name; +} + +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { + PCPProcessList* this = xCalloc(1, sizeof(PCPProcessList)); + ProcessList* super = &(this->super); + + ProcessList_init(super, Class(PCPProcess), usersTable, pidMatchList, userId); + + struct timeval timestamp; + gettimeofday(×tamp, NULL); + this->timestamp = pmtimevalToReal(×tamp); + + this->cpu = xCalloc(CPU_METRIC_COUNT, sizeof(pmAtomValue)); + PCPProcessList_updateCPUcount(this); + + return super; +} + +void ProcessList_delete(ProcessList* pl) { + PCPProcessList* this = (PCPProcessList*) pl; + ProcessList_done(pl); + free(this->values); + for (int i = 0; i < pl->cpuCount; i++) + free(this->percpu[i]); + free(this->percpu); + free(this->cpu); + free(this); +} + +static inline unsigned long long PCPProcessList_adjustTime(unsigned long long t) { + return t / 10; +} + +static void PCPProcessList_updateID(Process* process, int pid, int offset) { + pmAtomValue value; + + if (Metric_instance(PCP_PROC_TGID, pid, offset, &value, PM_TYPE_U32)) + process->tgid = value.ul; + else + process->tgid = 1; + + if (Metric_instance(PCP_PROC_PPID, pid, offset, &value, PM_TYPE_U32)) + process->ppid = value.ul; + else + process->ppid = 1; + + if (Metric_instance(PCP_PROC_STATE, pid, offset, &value, PM_TYPE_STRING)) { + process->state = value.cp[0]; + free(value.cp); + } else { + process->state = 'X'; + } +} + +static void PCPProcessList_updateInfo(Process* process, int pid, int offset, char* command, size_t commLen) { + PCPProcess* pp = (PCPProcess*) process; + pmAtomValue value; + + if (!Metric_instance(PCP_PROC_CMD, pid, offset, &value, PM_TYPE_STRING)) + value.cp = xStrdup(""); + String_safeStrncpy(command, value.cp, commLen); + free(value.cp); + + if (Metric_instance(PCP_PROC_PGRP, pid, offset, &value, PM_TYPE_U32)) + process->pgrp = value.ul; + else + process->pgrp = 0; + + if (Metric_instance(PCP_PROC_SESSION, pid, offset, &value, PM_TYPE_U32)) + process->session = value.ul; + else + process->session = 0; + + if (Metric_instance(PCP_PROC_TTY, pid, offset, &value, PM_TYPE_U32)) + process->tty_nr = value.ul; + else + process->tty_nr = 0; + + if (Metric_instance(PCP_PROC_TTYPGRP, pid, offset, &value, PM_TYPE_U32)) + process->tpgid = value.ul; + else + process->tpgid = 0; + + if (Metric_instance(PCP_PROC_MINFLT, pid, offset, &value, PM_TYPE_U32)) + process->minflt = value.ul; + else + process->minflt = 0; + + if (Metric_instance(PCP_PROC_CMINFLT, pid, offset, &value, PM_TYPE_U32)) + pp->cminflt = value.ul; + else + pp->cminflt = 0; + + if (Metric_instance(PCP_PROC_MAJFLT, pid, offset, &value, PM_TYPE_U32)) + process->majflt = value.ul; + else + process->majflt = 0; + + if (Metric_instance(PCP_PROC_CMAJFLT, pid, offset, &value, PM_TYPE_U32)) + pp->cmajflt = value.ul; + else + pp->cmajflt = 0; + + if (Metric_instance(PCP_PROC_UTIME, pid, offset, &value, PM_TYPE_U64)) + pp->utime = PCPProcessList_adjustTime(value.ull); + else + pp->utime = 0; + + if (Metric_instance(PCP_PROC_STIME, pid, offset, &value, PM_TYPE_U64)) + pp->stime = PCPProcessList_adjustTime(value.ull); + else + pp->stime = 0; + + if (Metric_instance(PCP_PROC_CUTIME, pid, offset, &value, PM_TYPE_U64)) + pp->cutime = PCPProcessList_adjustTime(value.ull); + else + pp->cutime = 0; + + if (Metric_instance(PCP_PROC_CSTIME, pid, offset, &value, PM_TYPE_U64)) + pp->cstime = PCPProcessList_adjustTime(value.ull); + else + pp->cstime = 0; + + if (Metric_instance(PCP_PROC_PRIORITY, pid, offset, &value, PM_TYPE_U32)) + process->priority = value.ul; + else + process->priority = 0; + + if (Metric_instance(PCP_PROC_NICE, pid, offset, &value, PM_TYPE_32)) + process->nice = value.l; + else + process->nice = 0; + + if (Metric_instance(PCP_PROC_THREADS, pid, offset, &value, PM_TYPE_U32)) + process->nlwp = value.ul; + else + process->nlwp = 0; + + if (Metric_instance(PCP_PROC_STARTTIME, pid, offset, &value, PM_TYPE_U64)) + process->starttime_ctime = PCPProcessList_adjustTime(value.ull); + else + process->starttime_ctime = 0; + + if (Metric_instance(PCP_PROC_PROCESSOR, pid, offset, &value, PM_TYPE_U32)) + process->processor = value.ul; + else + process->processor = 0; + + process->time = pp->utime + pp->stime; +} + +static void PCPProcessList_updateIO(PCPProcess* process, int pid, int offset, unsigned long long now) { + pmAtomValue value; + + if (Metric_instance(PCP_PROC_IO_RCHAR, pid, offset, &value, PM_TYPE_U64)) + process->io_rchar = value.ull / ONE_K; + else + process->io_rchar = ULLONG_MAX; + + if (Metric_instance(PCP_PROC_IO_WCHAR, pid, offset, &value, PM_TYPE_U64)) + process->io_wchar = value.ull / ONE_K; + else + process->io_wchar = ULLONG_MAX; + + if (Metric_instance(PCP_PROC_IO_SYSCR, pid, offset, &value, PM_TYPE_U64)) + process->io_syscr = value.ull; + else + process->io_syscr = ULLONG_MAX; + + if (Metric_instance(PCP_PROC_IO_SYSCW, pid, offset, &value, PM_TYPE_U64)) + process->io_syscw = value.ull; + else + process->io_syscw = ULLONG_MAX; + + if (Metric_instance(PCP_PROC_IO_CANCELLED, pid, offset, &value, PM_TYPE_U64)) + process->io_cancelled_write_bytes = value.ull / ONE_K; + else + process->io_cancelled_write_bytes = ULLONG_MAX; + + if (Metric_instance(PCP_PROC_IO_READB, pid, offset, &value, PM_TYPE_U64)) { + unsigned long long last_read = process->io_read_bytes; + process->io_read_bytes = value.ull / ONE_K; + process->io_rate_read_bps = + ONE_K * (process->io_read_bytes - last_read) / + (now - process->io_last_scan_time); + } else { + process->io_read_bytes = ULLONG_MAX; + process->io_rate_read_bps = NAN; + } + + if (Metric_instance(PCP_PROC_IO_WRITEB, pid, offset, &value, PM_TYPE_U64)) { + unsigned long long last_write = process->io_write_bytes; + process->io_write_bytes = value.ull; + process->io_rate_write_bps = + ONE_K * (process->io_write_bytes - last_write) / + (now - process->io_last_scan_time); + } else { + process->io_write_bytes = ULLONG_MAX; + process->io_rate_write_bps = NAN; + } + + process->io_last_scan_time = now; +} + +static void PCPProcessList_updateMemory(PCPProcess* process, int pid, int offset) { + pmAtomValue value; + + if (Metric_instance(PCP_PROC_MEM_SIZE, pid, offset, &value, PM_TYPE_U32)) + process->super.m_virt = value.ul; + else + process->super.m_virt = 0; + + if (Metric_instance(PCP_PROC_MEM_RSS, pid, offset, &value, PM_TYPE_U32)) + process->super.m_resident = value.ul; + else + process->super.m_resident = 0; + + if (Metric_instance(PCP_PROC_MEM_SHARE, pid, offset, &value, PM_TYPE_U32)) + process->m_share = value.ul; + else + process->m_share = 0; + + if (Metric_instance(PCP_PROC_MEM_TEXTRS, pid, offset, &value, PM_TYPE_U32)) + process->m_trs = value.ul; + else + process->m_trs = 0; + + if (Metric_instance(PCP_PROC_MEM_LIBRS, pid, offset, &value, PM_TYPE_U32)) + process->m_lrs = value.ul; + else + process->m_lrs = 0; + + if (Metric_instance(PCP_PROC_MEM_DATRS, pid, offset, &value, PM_TYPE_U32)) + process->m_drs = value.ul; + else + process->m_drs = 0; + + if (Metric_instance(PCP_PROC_MEM_DIRTY, pid, offset, &value, PM_TYPE_U32)) + process->m_dt = value.ul; + else + process->m_dt = 0; +} + +static void PCPProcessList_updateSmaps(PCPProcess* process, pid_t pid, int offset) { + pmAtomValue value; + + if (Metric_instance(PCP_PROC_SMAPS_PSS, pid, offset, &value, PM_TYPE_U64)) + process->m_pss = value.ull; + else + process->m_pss = 0LL; + + if (Metric_instance(PCP_PROC_SMAPS_SWAP, pid, offset, &value, PM_TYPE_U64)) + process->m_swap = value.ull; + else + process->m_swap = 0LL; + + if (Metric_instance(PCP_PROC_SMAPS_SWAPPSS, pid, offset, &value, PM_TYPE_U64)) + process->m_psswp = value.ull; + else + process->m_psswp = 0LL; +} + +static void PCPProcessList_readOomData(PCPProcess* process, int pid, int offset) { + pmAtomValue value; + if (Metric_instance(PCP_PROC_OOMSCORE, pid, offset, &value, PM_TYPE_U32)) + process->oom = value.ul; + else + process->oom = 0; +} + +static void PCPProcessList_readCtxtData(PCPProcess* process, int pid, int offset) { + pmAtomValue value; + unsigned long ctxt = 0; + + if (Metric_instance(PCP_PROC_VCTXSW, pid, offset, &value, PM_TYPE_U32)) + ctxt += value.ul; + if (Metric_instance(PCP_PROC_NVCTXSW, pid, offset, &value, PM_TYPE_U32)) + ctxt += value.ul; + if (ctxt > process->ctxt_total) + process->ctxt_diff = ctxt - process->ctxt_total; + else + process->ctxt_diff = 0; + process->ctxt_total = ctxt; +} + +static char* setString(Metric metric, int pid, int offset, char* string) { + if (string) + free(string); + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_STRING)) + string = value.cp; + else + string = NULL; + return string; +} + +static void PCPProcessList_updateTTY(PCPProcess* process, int pid, int offset) { + process->ttyDevice = setString(PCP_PROC_TTYNAME, pid, offset, process->ttyDevice); +} + +static void PCPProcessList_readCGroups(PCPProcess* process, int pid, int offset) { + process->cgroup = setString(PCP_PROC_CGROUPS, pid, offset, process->cgroup); +} + +static void PCPProcessList_readSecattrData(PCPProcess* process, int pid, int offset) { + process->secattr = setString(PCP_PROC_LABELS, pid, offset, process->secattr); +} + +static void PCPProcessList_updateUsername(Process* process, int pid, int offset, UsersTable* users) { + unsigned int uid = 0; + pmAtomValue value; + if (Metric_instance(PCP_PROC_ID_UID, pid, offset, &value, PM_TYPE_U32)) + uid = value.ul; + process->st_uid = uid; + process->user = setUser(users, uid, pid, offset); +} + +static void PCPProcessList_updateCmdline(Process* process, int pid, int offset, const char* comm) { + pmAtomValue value; + if (!Metric_instance(PCP_PROC_PSARGS, pid, offset, &value, PM_TYPE_STRING)) { + if (process->state != 'Z') + Process_setKernelThread(process, true); + else + process->basenameOffset = 0; + return; + } + + char *command = value.cp; + int length = strlen(command); + if (command[0] != '(') { + Process_setKernelThread(process, false); + } else { + ++command; + --length; + if (command[length-1] == ')') + command[length-1] = '\0'; + Process_setKernelThread(process, true); + } + + int tokenEnd = 0; + int tokenStart = 0; + int lastChar = 0; + for (int i = 0; i < length; i++) { + /* htop considers the next character after the last / that is before + * basenameOffset, as the start of the basename in cmdline - see + * Process_writeCommand */ + if (command[i] == '/') + tokenStart = i + 1; + lastChar = i; + } + tokenEnd = length; + + PCPProcess *pp = (PCPProcess *)process; + pp->mergedCommand.maxLen = lastChar + 1; /* accommodate cmdline */ + if (!process->comm || !String_eq(command, process->comm)) { + process->basenameOffset = tokenEnd; + free_and_xStrdup(&process->comm, command); + pp->procCmdlineBasenameOffset = tokenStart; + pp->procCmdlineBasenameEnd = tokenEnd; + pp->mergedCommand.cmdlineChanged = true; + } + + /* comm could change, so should be updated */ + if ((length = strlen(comm)) > 0) { + pp->mergedCommand.maxLen += length; + if (!pp->procComm || !String_eq(command, pp->procComm)) { + free_and_xStrdup(&pp->procComm, command); + pp->mergedCommand.commChanged = true; + } + } else if (pp->procComm) { + free(pp->procComm); + pp->procComm = NULL; + pp->mergedCommand.commChanged = true; + } + + free(value.cp); +} + +static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, struct timeval* tv) { + ProcessList* pl = (ProcessList*) this; + const Settings* settings = pl->settings; + + bool hideKernelThreads = settings->hideKernelThreads; + bool hideUserlandThreads = settings->hideUserlandThreads; + + unsigned long long now = tv->tv_sec * 1000LL + tv->tv_usec / 1000LL; + int pid = -1, offset = -1; + + /* for every process ... */ + while (Metric_iterate(PCP_PROC_PID, &pid, &offset)) { + + bool preExisting; + Process* proc = ProcessList_getProcess(pl, pid, &preExisting, PCPProcess_new); + PCPProcess* pp = (PCPProcess*) proc; + PCPProcessList_updateID(proc, pid, offset); + + /* + * These conditions will not trigger on first occurrence, cause we need to + * add the process to the ProcessList and do all one time scans + * (e.g. parsing the cmdline to detect a kernel thread) + * But it will short-circuit subsequent scans. + */ + if (preExisting && hideKernelThreads && Process_isKernelThread(proc)) { + proc->updated = true; + proc->show = false; + if (proc->state == 'R') + pl->runningTasks++; + pl->kernelThreads++; + pl->totalTasks++; + continue; + } + if (preExisting && hideUserlandThreads && Process_isUserlandThread(proc)) { + proc->updated = true; + proc->show = false; + if (proc->state == 'R') + pl->runningTasks++; + pl->userlandThreads++; + pl->totalTasks++; + continue; + } + + if (settings->flags & PROCESS_FLAG_IO) + PCPProcessList_updateIO(pp, pid, offset, now); + + PCPProcessList_updateMemory(pp, pid, offset); + + if ((settings->flags & PROCESS_FLAG_LINUX_SMAPS) && + (Process_isKernelThread(proc) == false)) { + if (Metric_enabled(PCP_PROC_SMAPS_PSS)) + PCPProcessList_updateSmaps(pp, pid, offset); + } + + char command[MAX_NAME + 1]; + unsigned int tty_nr = proc->tty_nr; + unsigned long long int lasttimes = pp->utime + pp->stime; + + PCPProcessList_updateInfo(proc, pid, offset, command, sizeof(command)); + proc->starttime_ctime += Platform_getBootTime(); + if (tty_nr != proc->tty_nr) + PCPProcessList_updateTTY(pp, pid, offset); + + float percent_cpu = (pp->utime + pp->stime - lasttimes) / period * 100.0; + proc->percent_cpu = isnan(percent_cpu) ? + 0.0 : CLAMP(percent_cpu, 0.0, pl->cpuCount * 100.0); + proc->percent_mem = proc->m_resident / (double)pl->totalMem * 100.0; + + if (!preExisting) { + PCPProcessList_updateUsername(proc, pid, offset, pl->usersTable); + PCPProcessList_updateCmdline(proc, pid, offset, command); + Process_fillStarttimeBuffer(proc); + ProcessList_add(pl, proc); + } else if (settings->updateProcessNames && proc->state != 'Z') { + PCPProcessList_updateCmdline(proc, pid, offset, command); + } + + /* (Re)Generate the Command string, but only if the process is: + * - not a kernel thread, and + * - not a zombie or it became zombie under htop's watch, and + * - not a user thread or if showThreadNames is not set */ + if (!Process_isKernelThread(proc) && + (proc->state != 'Z' || pp->mergedCommand.str) && + (!Process_isUserlandThread(proc) || !settings->showThreadNames)) { + PCPProcess_makeCommandStr(proc); + } + + if (settings->flags & PROCESS_FLAG_LINUX_CGROUP) + PCPProcessList_readCGroups(pp, pid, offset); + + if (settings->flags & PROCESS_FLAG_LINUX_OOM) + PCPProcessList_readOomData(pp, pid, offset); + + if (settings->flags & PROCESS_FLAG_LINUX_CTXT) + PCPProcessList_readCtxtData(pp, pid, offset); + + if (settings->flags & PROCESS_FLAG_LINUX_SECATTR) + PCPProcessList_readSecattrData(pp, pid, offset); + + if (proc->state == 'Z' && proc->basenameOffset == 0) { + proc->basenameOffset = -1; + free_and_xStrdup(&proc->comm, command); + pp->procCmdlineBasenameOffset = 0; + pp->procCmdlineBasenameEnd = 0; + pp->mergedCommand.commChanged = true; + } else if (Process_isThread(proc)) { + if (settings->showThreadNames || Process_isKernelThread(proc)) { + proc->basenameOffset = -1; + free_and_xStrdup(&proc->comm, command); + pp->procCmdlineBasenameOffset = 0; + pp->procCmdlineBasenameEnd = 0; + pp->mergedCommand.commChanged = true; + } + if (Process_isKernelThread(proc)) { + pl->kernelThreads++; + } else { + pl->userlandThreads++; + } + } + + /* Set at the end when we know if a new entry is a thread */ + proc->show = ! ((hideKernelThreads && Process_isKernelThread(proc)) || + (hideUserlandThreads && Process_isUserlandThread(proc))); +//fprintf(stderr, "Updated PID %d [%s] show=%d user=%d[%d] kern=%d[%d]\n", pid, command, proc->show, Process_isUserlandThread(proc), hideUserlandThreads, Process_isKernelThread(proc), hideKernelThreads); + + pl->totalTasks++; + if (proc->state == 'R') + pl->runningTasks++; + proc->updated = true; + } +//fprintf(stderr, "Total tasks %d, running=%d\n", pl->totalTasks, pl->runningTasks); + return true; +} + +static void PCPProcessList_updateMemoryInfo(ProcessList* super) { + unsigned long long int freeMem = 0; + unsigned long long int swapFreeMem = 0; + unsigned long long int sreclaimableMem = 0; + super->totalMem = super->usedMem = super->cachedMem = 0; + super->usedSwap = super->totalSwap = 0; + + pmAtomValue value; + if (Metric_values(PCP_MEM_TOTAL, &value, 1, PM_TYPE_U64) != NULL) + super->totalMem = value.ull; + if (Metric_values(PCP_MEM_FREE, &value, 1, PM_TYPE_U64) != NULL) + freeMem = value.ull; + if (Metric_values(PCP_MEM_BUFFERS, &value, 1, PM_TYPE_U64) != NULL) + super->buffersMem = value.ull; + if (Metric_values(PCP_MEM_SRECLAIM, &value, 1, PM_TYPE_U64) != NULL) + sreclaimableMem = value.ull; + if (Metric_values(PCP_MEM_CACHED, &value, 1, PM_TYPE_U64) != NULL) { + super->cachedMem = value.ull; + super->cachedMem += sreclaimableMem; + } + unsigned long long int usedDiff; + usedDiff = freeMem + super->cachedMem + super->buffersMem; + super->usedMem = (super->totalMem >= usedDiff) ? + super->totalMem - usedDiff : super->totalMem - freeMem; + if (Metric_values(PCP_MEM_AVAILABLE, &value, 1, PM_TYPE_U64) != NULL) + super->availableMem = MINIMUM(value.ull, super->totalMem); + else + super->availableMem = freeMem; + if (Metric_values(PCP_MEM_SWAPFREE, &value, 1, PM_TYPE_U64) != NULL) + swapFreeMem = value.ull; + if (Metric_values(PCP_MEM_SWAPTOTAL, &value, 1, PM_TYPE_U64) != NULL) + super->totalSwap = value.ull; + if (Metric_values(PCP_MEM_SWAPCACHED, &value, 1, PM_TYPE_U64) != NULL) + super->cachedSwap = value.ull; + super->usedSwap = super->totalSwap - swapFreeMem - super->cachedSwap; +} + +/* make copies of previously sampled values to avoid overwrite */ +static inline void PCPProcessList_backupCPUTime(pmAtomValue* values) { + /* the PERIOD fields (must) mirror the TIME fields */ + for (int metric = CPU_TOTAL_TIME; metric < CPU_TOTAL_PERIOD; metric++) { + values[metric + CPU_TOTAL_PERIOD] = values[metric]; + } +} + +static inline void PCPProcessList_saveCPUTimePeriod(pmAtomValue* values, CPUMetric previous, pmAtomValue* latest) { + pmAtomValue *value; + + /* new value for period */ + value = &values[previous]; + if (latest->ull > value->ull) + value->ull = latest->ull - value->ull; + else + value->ull = 0; + + /* new value for time */ + value = &values[previous - CPU_TOTAL_PERIOD]; + value->ull = latest->ull; +} + +/* using copied sampled values and new values, calculate derivations */ +static void PCPProcessList_deriveCPUTime(pmAtomValue* values) { + + pmAtomValue* usertime = &values[CPU_USER_TIME]; + pmAtomValue* guesttime = &values[CPU_GUEST_TIME]; + usertime->ull -= guesttime->ull; + + pmAtomValue* nicetime = &values[CPU_NICE_TIME]; + pmAtomValue* guestnicetime = &values[CPU_GUESTNICE_TIME]; + nicetime->ull -= guestnicetime->ull; + + pmAtomValue* idletime = &values[CPU_IDLE_TIME]; + pmAtomValue* iowaittime = &values[CPU_IOWAIT_TIME]; + pmAtomValue* idlealltime = &values[CPU_IDLE_ALL_TIME]; + idlealltime->ull = idletime->ull + iowaittime->ull; + + pmAtomValue* systemtime = &values[CPU_SYSTEM_TIME]; + pmAtomValue* irqtime = &values[CPU_IRQ_TIME]; + pmAtomValue* softirqtime = &values[CPU_SOFTIRQ_TIME]; + pmAtomValue* systalltime = &values[CPU_SYSTEM_ALL_TIME]; + systalltime->ull = systemtime->ull + irqtime->ull + softirqtime->ull; + + pmAtomValue* virtalltime = &values[CPU_GUEST_TIME]; + virtalltime->ull = guesttime->ull + guestnicetime->ull; + + pmAtomValue* stealtime = &values[CPU_STEAL_TIME]; + pmAtomValue* totaltime = &values[CPU_TOTAL_TIME]; + totaltime->ull = usertime->ull + nicetime->ull + systalltime->ull + + idlealltime->ull + stealtime->ull + virtalltime->ull; + + PCPProcessList_saveCPUTimePeriod(values, CPU_USER_PERIOD, usertime); + PCPProcessList_saveCPUTimePeriod(values, CPU_NICE_PERIOD, nicetime); + PCPProcessList_saveCPUTimePeriod(values, CPU_SYSTEM_PERIOD, systemtime); + PCPProcessList_saveCPUTimePeriod(values, CPU_SYSTEM_ALL_PERIOD, systalltime); + PCPProcessList_saveCPUTimePeriod(values, CPU_IDLE_ALL_PERIOD, idlealltime); + PCPProcessList_saveCPUTimePeriod(values, CPU_IDLE_PERIOD, idletime); + PCPProcessList_saveCPUTimePeriod(values, CPU_IOWAIT_PERIOD, iowaittime); + PCPProcessList_saveCPUTimePeriod(values, CPU_IRQ_PERIOD, irqtime); + PCPProcessList_saveCPUTimePeriod(values, CPU_SOFTIRQ_PERIOD, softirqtime); + PCPProcessList_saveCPUTimePeriod(values, CPU_STEAL_PERIOD, stealtime); + PCPProcessList_saveCPUTimePeriod(values, CPU_GUEST_PERIOD, virtalltime); + PCPProcessList_saveCPUTimePeriod(values, CPU_TOTAL_PERIOD, totaltime); +} + +static void PCPProcessList_updateAllCPUTime(PCPProcessList* this, Metric metric, CPUMetric cpumetric) +{ + pmAtomValue* value = &this->cpu[cpumetric]; + if (Metric_values(metric, value, 1, PM_TYPE_U64) == NULL) + memset(&value, 0, sizeof(pmAtomValue)); +} + +static void PCPProcessList_updatePerCPUTime(PCPProcessList* this, Metric metric, CPUMetric cpumetric) +{ + int cpus = this->super.cpuCount; + if (Metric_values(metric, this->values, cpus, PM_TYPE_U64) == NULL) + memset(this->values, 0, cpus * sizeof(pmAtomValue)); + for (int i = 0; i < cpus; i++) + this->percpu[i][cpumetric].ull = this->values[i].ull; +} + +static void PCPProcessList_updatePerCPUReal(PCPProcessList* this, Metric metric, CPUMetric cpumetric) +{ + int cpus = this->super.cpuCount; + if (Metric_values(metric, this->values, cpus, PM_TYPE_DOUBLE) == NULL) + memset(this->values, 0, cpus * sizeof(pmAtomValue)); + for (int i = 0; i < cpus; i++) + this->percpu[i][cpumetric].d = this->values[i].d; +} + +static void PCPProcessList_updateHeader(ProcessList* super, const Settings* settings) { + PCPProcessList_updateMemoryInfo(super); + + PCPProcessList* this = (PCPProcessList*) super; + PCPProcessList_updateCPUcount(this); + + PCPProcessList_backupCPUTime(this->cpu); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_USER, CPU_USER_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_NICE, CPU_NICE_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_SYSTEM, CPU_SYSTEM_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_IDLE, CPU_IDLE_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_IOWAIT, CPU_IOWAIT_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_IRQ, CPU_IRQ_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_SOFTIRQ, CPU_SOFTIRQ_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_STEAL, CPU_STEAL_TIME); + PCPProcessList_updateAllCPUTime(this, PCP_CPU_GUEST, CPU_GUEST_TIME); + PCPProcessList_deriveCPUTime(this->cpu); + + for (int i = 0; i < super->cpuCount; i++) + PCPProcessList_backupCPUTime(this->percpu[i]); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_USER, CPU_USER_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_NICE, CPU_NICE_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_SYSTEM, CPU_SYSTEM_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_IDLE, CPU_IDLE_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_IOWAIT, CPU_IOWAIT_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_IRQ, CPU_IRQ_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_SOFTIRQ, CPU_SOFTIRQ_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_STEAL, CPU_STEAL_TIME); + PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_GUEST, CPU_GUEST_TIME); + for (int i = 0; i < super->cpuCount; i++) + PCPProcessList_deriveCPUTime(this->percpu[i]); + + if (settings->showCPUFrequency) + PCPProcessList_updatePerCPUReal(this, PCP_HINV_CPUCLOCK, CPU_FREQUENCY); +} + +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + PCPProcessList* this = (PCPProcessList*) super; + const Settings* settings = super->settings; + bool enabled = !pauseProcessUpdate; + + bool flagged = settings->showCPUFrequency; + Metric_enable(PCP_HINV_CPUCLOCK, flagged); + + /* In pause mode do not sample per-process metric values at all */ + for (int metric = PCP_PROC_PID; metric < PCP_METRIC_COUNT; metric++) + Metric_enable(metric, enabled); + + flagged = settings->flags & PROCESS_FLAG_LINUX_CGROUP; + Metric_enable(PCP_PROC_CGROUPS, flagged && enabled); + flagged = settings->flags & PROCESS_FLAG_LINUX_OOM; + Metric_enable(PCP_PROC_OOMSCORE, flagged && enabled); + flagged = settings->flags & PROCESS_FLAG_LINUX_CTXT; + Metric_enable(PCP_PROC_VCTXSW, flagged && enabled); + Metric_enable(PCP_PROC_NVCTXSW, flagged && enabled); + flagged = settings->flags & PROCESS_FLAG_LINUX_SECATTR; + Metric_enable(PCP_PROC_LABELS, flagged && enabled); + + /* Sample smaps metrics on every second pass to improve performance */ + static int smaps_flag; + smaps_flag = !!smaps_flag; + Metric_enable(PCP_PROC_SMAPS_PSS, smaps_flag && enabled); + Metric_enable(PCP_PROC_SMAPS_SWAP, smaps_flag && enabled); + Metric_enable(PCP_PROC_SMAPS_SWAPPSS, smaps_flag && enabled); + + struct timeval timestamp; + Metric_fetch(×tamp); + + double sample = this->timestamp; + this->timestamp = pmtimevalToReal(×tamp); + + PCPProcessList_updateHeader(super, settings); + + /* In pause mode only update global data for meters (CPU, memory, etc) */ + if (pauseProcessUpdate) + return; + + double period = (this->timestamp - sample) * 100; + PCPProcessList_updateProcesses(this, period, ×tamp); +} diff --git a/pcp/PCPProcessList.h b/pcp/PCPProcessList.h new file mode 100644 index 000000000..28f1d9cee --- /dev/null +++ b/pcp/PCPProcessList.h @@ -0,0 +1,68 @@ +#ifndef HEADER_PCPProcessList +#define HEADER_PCPProcessList +/* +htop - PCPProcessList.h +(C) 2014 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" + +#include +#include + +#include "Hashtable.h" +#include "ProcessList.h" +#include "pcp/Platform.h" +#include "UsersTable.h" + +typedef enum CPUMetric_ { + CPU_TOTAL_TIME, + CPU_USER_TIME, + CPU_SYSTEM_TIME, + CPU_SYSTEM_ALL_TIME, + CPU_IDLE_ALL_TIME, + CPU_IDLE_TIME, + CPU_NICE_TIME, + CPU_IOWAIT_TIME, + CPU_IRQ_TIME, + CPU_SOFTIRQ_TIME, + CPU_STEAL_TIME, + CPU_GUEST_TIME, + CPU_GUESTNICE_TIME, + + CPU_TOTAL_PERIOD, + CPU_USER_PERIOD, + CPU_SYSTEM_PERIOD, + CPU_SYSTEM_ALL_PERIOD, + CPU_IDLE_ALL_PERIOD, + CPU_IDLE_PERIOD, + CPU_NICE_PERIOD, + CPU_IOWAIT_PERIOD, + CPU_IRQ_PERIOD, + CPU_SOFTIRQ_PERIOD, + CPU_STEAL_PERIOD, + CPU_GUEST_PERIOD, + CPU_GUESTNICE_PERIOD, + + CPU_FREQUENCY, + + CPU_METRIC_COUNT +} CPUMetric; + +typedef struct PCPProcessList_ { + ProcessList super; + double timestamp; /* previous sample timestamp */ + pmAtomValue* cpu; /* aggregate values for each metric */ + pmAtomValue** percpu; /* per-processor values for each metric */ + pmAtomValue* values; /* per-processor buffer for just one metric */ +} PCPProcessList; + +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); + +void ProcessList_delete(ProcessList* pl); + +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); + +#endif diff --git a/pcp/Platform.c b/pcp/Platform.c new file mode 100644 index 000000000..4ac7c701d --- /dev/null +++ b/pcp/Platform.c @@ -0,0 +1,687 @@ +/* +htop - linux/Platform.c +(C) 2014 Hisham H. Muhammad +(C) 2020 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" + +#include "Platform.h" + +#include + +#include "BatteryMeter.h" +#include "ClockMeter.h" +#include "Compat.h" +#include "CPUMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" +#include "DiskIOMeter.h" +#include "HostnameMeter.h" +#include "LoadAverageMeter.h" +#include "Macros.h" +#include "MainPanel.h" +#include "MemoryMeter.h" +#include "Meter.h" +#include "NetworkIOMeter.h" +#include "Object.h" +#include "Panel.h" +#include "PCPProcess.h" +#include "PCPProcessList.h" +#include "ProcessList.h" +#include "ProvideCurses.h" +#include "Settings.h" +#include "SwapMeter.h" +#include "TasksMeter.h" +#include "UptimeMeter.h" +#include "XUtils.h" + +#include "linux/PressureStallMeter.h" +#include "linux/ZramMeter.h" +#include "linux/ZramStats.h" + +typedef struct Platform_ { + int context; /* PMAPI(3) context identifier */ + unsigned int total; /* total number of all metrics */ + const char** names; /* name array indexed by Metric */ + pmID* pmids; /* all known metric identifiers */ + pmID* fetch; /* enabled identifiers for sampling */ + pmDesc* descs; /* metric desc array indexed by Metric */ + pmResult* result; /* sample values result indexed by Metric */ + + long long btime; /* boottime in seconds since the epoch */ + int pidmax; /* maximum platform process identifier */ + int ncpu; /* maximum processor count configured */ +} Platform; + +Platform* pcp; + +ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_VIRT, M_RESIDENT, (int)M_SHARE, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; + +int Platform_numberOfFields = LAST_PROCESSFIELD; + +const SignalItem Platform_signals[] = { + { .name = " 0 Cancel", .number = 0 }, +}; + +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); + +const MeterClass* const Platform_meterTypes[] = { + &CPUMeter_class, + &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, + &LoadAverageMeter_class, + &LoadMeter_class, + &MemoryMeter_class, + &SwapMeter_class, + &TasksMeter_class, + &UptimeMeter_class, + &BatteryMeter_class, + &HostnameMeter_class, + &AllCPUsMeter_class, + &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, + &LeftCPUsMeter_class, + &RightCPUsMeter_class, + &LeftCPUs2Meter_class, + &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, + &BlankMeter_class, + &PressureStallCPUSomeMeter_class, + &PressureStallIOSomeMeter_class, + &PressureStallIOFullMeter_class, + &PressureStallMemorySomeMeter_class, + &PressureStallMemoryFullMeter_class, + &ZramMeter_class, + &DiskIOMeter_class, + &NetworkIOMeter_class, + NULL +}; + +static const char *Platform_metricNames[] = { + [PCP_CONTROL_THREADS] = "proc.control.perclient.threads", + + [PCP_HINV_NCPU] = "hinv.ncpu", + [PCP_HINV_CPUCLOCK] = "hinv.cpu.clock", + [PCP_UNAME_SYSNAME] = "kernel.uname.sysname", + [PCP_UNAME_RELEASE] = "kernel.uname.release", + [PCP_UNAME_MACHINE] = "kernel.uname.machine", + [PCP_LOAD_AVERAGE] = "kernel.all.load", + [PCP_PID_MAX] = "kernel.all.pid_max", + [PCP_UPTIME] = "kernel.all.uptime", + [PCP_BOOTTIME] = "kernel.all.boottime", + [PCP_CPU_USER] = "kernel.all.cpu.user", + [PCP_CPU_NICE] = "kernel.all.cpu.nice", + [PCP_CPU_SYSTEM] = "kernel.all.cpu.sys", + [PCP_CPU_IDLE] = "kernel.all.cpu.idle", + [PCP_CPU_IOWAIT] = "kernel.all.cpu.wait.total", + [PCP_CPU_IRQ] = "kernel.all.cpu.intr", + [PCP_CPU_SOFTIRQ] = "kernel.all.cpu.irq.soft", + [PCP_CPU_STEAL] = "kernel.all.cpu.steal", + [PCP_CPU_GUEST] = "kernel.all.cpu.guest", + [PCP_CPU_GUESTNICE] = "kernel.all.cpu.guest_nice", + [PCP_PERCPU_USER] = "kernel.percpu.cpu.user", + [PCP_PERCPU_NICE] = "kernel.percpu.cpu.nice", + [PCP_PERCPU_SYSTEM] = "kernel.percpu.cpu.sys", + [PCP_PERCPU_IDLE] = "kernel.percpu.cpu.idle", + [PCP_PERCPU_IOWAIT] = "kernel.percpu.cpu.wait.total", + [PCP_PERCPU_IRQ] = "kernel.percpu.cpu.intr", + [PCP_PERCPU_SOFTIRQ] = "kernel.percpu.cpu.irq.soft", + [PCP_PERCPU_STEAL] = "kernel.percpu.cpu.steal", + [PCP_PERCPU_GUEST] = "kernel.percpu.cpu.guest", + [PCP_PERCPU_GUESTNICE] = "kernel.percpu.cpu.guest_nice", + [PCP_MEM_TOTAL] = "mem.physmem", + [PCP_MEM_FREE] = "mem.util.free", + [PCP_MEM_AVAILABLE] = "mem.util.available", + [PCP_MEM_BUFFERS] = "mem.util.bufmem", + [PCP_MEM_CACHED] = "mem.util.cached", + [PCP_MEM_SRECLAIM] = "mem.util.slabReclaimable", + [PCP_MEM_SWAPCACHED] = "mem.util.swapCached", + [PCP_MEM_SWAPTOTAL] = "mem.util.swapTotal", + [PCP_MEM_SWAPFREE] = "mem.util.swapFree", + [PCP_DISK_READB] = "disk.all.read_bytes", + [PCP_DISK_WRITEB] = "disk.all.write_bytes", + [PCP_DISK_ACTIVE] = "disk.all.avactive", + [PCP_NET_RECVB] = "network.all.in.bytes", + [PCP_NET_SENDB] = "network.all.out.bytes", + [PCP_NET_RECVP] = "network.all.in.packets", + [PCP_NET_SENDP] = "network.all.out.packets", + + [PCP_PSI_CPUSOME] = "kernel.all.pressure.cpu.some.avg", + [PCP_PSI_IOSOME] = "kernel.all.pressure.io.some.avg", + [PCP_PSI_IOFULL] = "kernel.all.pressure.io.full.avg", + [PCP_PSI_MEMSOME] = "kernel.all.pressure.memory.some.avg", + [PCP_PSI_MEMFULL] = "kernel.all.pressure.memory.full.avg", + + [PCP_ZRAM_CAPACITY] = "zram.capacity", + [PCP_ZRAM_ORIGINAL] = "zram.mm_stat.data_size.original", + [PCP_ZRAM_COMPRESSED] = "zram.mm_stat.data_size.compressed", + + [PCP_PROC_PID] = "proc.psinfo.pid", + [PCP_PROC_PPID] = "proc.psinfo.ppid", + [PCP_PROC_TGID] = "proc.psinfo.tgid", + [PCP_PROC_PGRP] = "proc.psinfo.pgrp", + [PCP_PROC_SESSION] = "proc.psinfo.session", + [PCP_PROC_STATE] = "proc.psinfo.sname", + [PCP_PROC_TTY] = "proc.psinfo.tty", + [PCP_PROC_TTYPGRP] = "proc.psinfo.tty_pgrp", + [PCP_PROC_MINFLT] = "proc.psinfo.minflt", + [PCP_PROC_MAJFLT] = "proc.psinfo.maj_flt", + [PCP_PROC_CMINFLT] = "proc.psinfo.cmin_flt", + [PCP_PROC_CMAJFLT] = "proc.psinfo.cmaj_flt", + [PCP_PROC_UTIME] = "proc.psinfo.utime", + [PCP_PROC_STIME] = "proc.psinfo.stime", + [PCP_PROC_CUTIME] = "proc.psinfo.cutime", + [PCP_PROC_CSTIME] = "proc.psinfo.cstime", + [PCP_PROC_PRIORITY] = "proc.psinfo.priority", + [PCP_PROC_NICE] = "proc.psinfo.nice", + [PCP_PROC_THREADS] = "proc.psinfo.threads", + [PCP_PROC_STARTTIME] = "proc.psinfo.start_time", + [PCP_PROC_PROCESSOR] = "proc.psinfo.processor", + [PCP_PROC_CMD] = "proc.psinfo.cmd", + [PCP_PROC_PSARGS] = "proc.psinfo.psargs", + [PCP_PROC_CGROUPS] = "proc.psinfo.cgroups", + [PCP_PROC_OOMSCORE] = "proc.psinfo.oom_score", + [PCP_PROC_VCTXSW] = "proc.psinfo.vctxsw", + [PCP_PROC_NVCTXSW] = "proc.psinfo.nvctxsw", + [PCP_PROC_LABELS] = "proc.psinfo.labels", + [PCP_PROC_ENVIRON] = "proc.psinfo.environ", + [PCP_PROC_TTYNAME] = "proc.psinfo.ttyname", + [PCP_PROC_ID_UID] = "proc.id.uid", + [PCP_PROC_ID_USER] = "proc.id.uid_nm", + [PCP_PROC_IO_RCHAR] = "proc.io.rchar", + [PCP_PROC_IO_WCHAR] = "proc.io.wchar", + [PCP_PROC_IO_SYSCR] = "proc.io.syscr", + [PCP_PROC_IO_SYSCW] = "proc.io.syscw", + [PCP_PROC_IO_READB] = "proc.io.read_bytes", + [PCP_PROC_IO_WRITEB] = "proc.io.write_bytes", + [PCP_PROC_IO_CANCELLED] = "proc.io.cancelled_write_bytes", + [PCP_PROC_MEM_SIZE] = "proc.memory.size", + [PCP_PROC_MEM_RSS] = "proc.memory.rss", + [PCP_PROC_MEM_SHARE] = "proc.memory.share", + [PCP_PROC_MEM_TEXTRS] = "proc.memory.textrss", + [PCP_PROC_MEM_LIBRS] = "proc.memory.librss", + [PCP_PROC_MEM_DATRS] = "proc.memory.datrss", + [PCP_PROC_MEM_DIRTY] = "proc.memory.dirty", + [PCP_PROC_SMAPS_PSS] = "proc.smaps.pss", + [PCP_PROC_SMAPS_SWAP] = "proc.smaps.swap", + [PCP_PROC_SMAPS_SWAPPSS] = "proc.smaps.swappss", + + [PCP_METRIC_COUNT] = NULL +}; + +pmAtomValue* Metric_values(Metric metric, pmAtomValue *atom, int count, int type) { + + pmValueSet* vset = pcp->result->vset[metric]; + if (!vset || vset->numval <= 0) + return NULL; + + /* allocate space for atom if needed */ + if (!atom || !count) { + if (!count) + count = vset->numval; + atom = xCalloc(count, sizeof(pmAtomValue)); + } + + /* extract requested number of values as requested type */ + const pmDesc* desc = &pcp->descs[metric]; + for (int i = 0; i < vset->numval; i++) { + if (i == count) + break; + const pmValue *value = &vset->vlist[i]; + int sts = pmExtractValue(vset->valfmt, value, desc->type, &atom[i], type); + if (sts < 0) { + if (pmDebugOptions.appl0) + fprintf(stderr, "Error: cannot extract metric value: %s\n", + pmErrStr(sts)); + memset(&atom[i], 0, sizeof(pmAtomValue)); + } + } + return atom; +} + +int Metric_instanceCount(Metric metric) { + pmValueSet* vset = pcp->result->vset[metric]; + if (vset) + return vset->numval; + return 0; +} + +int Metric_instanceOffset(Metric metric, int inst) { + pmValueSet* vset = pcp->result->vset[metric]; + if (!vset || vset->numval <= 0) + return 0; + + /* search for optimal offset for subsequent inst lookups to begin */ + for (int i = 0; i < vset->numval; i++) { + if (inst == vset->vlist[i].inst) + return i; + } + return 0; +} + +static pmAtomValue *Metric_extract(Metric metric, int inst, int offset, pmValueSet *vset, pmAtomValue *atom, int type) { + + /* extract value (using requested type) of given metric instance */ + const pmDesc* desc = &pcp->descs[metric]; + const pmValue *value = &vset->vlist[offset]; + int sts = pmExtractValue(vset->valfmt, value, desc->type, atom, type); + if (sts < 0) { + if (pmDebugOptions.appl0) + fprintf(stderr, "Error: cannot extract %s instance %d value: %s\n", + pcp->names[metric], inst, pmErrStr(sts)); + memset(atom, 0, sizeof(pmAtomValue)); + } + return atom; +} + +pmAtomValue *Metric_instance(Metric metric, int inst, int offset, pmAtomValue *atom, int type) { + + pmValueSet* vset = pcp->result->vset[metric]; + if (!vset || vset->numval <= 0) + return NULL; + + /* fast-path using heuristic offset based on expected location */ + if (offset >= 0 && offset < vset->numval && inst == vset->vlist[offset].inst) + return Metric_extract(metric, inst, offset, vset, atom, type); + + /* slow-path using a linear search for the requested instance */ + for (int i = 0; i < vset->numval; i++) { + if (inst == vset->vlist[i].inst) + return Metric_extract(metric, inst, i, vset, atom, type); + } + return NULL; +} + +/* + * Iterate over a set of instances (incl PM_IN_NULL) + * returning the next instance identifier and offset. + * + * Start it off by passing offset -1 into the routine. + */ +bool Metric_iterate(Metric metric, int* instp, int* offsetp) { + pmValueSet* vset = pcp->result->vset[metric]; + if (!vset || vset->numval <= 0) + return false; + + int offset = *offsetp; + offset = (offset < 0) ? 0 : offset + 1; + if (offset > vset->numval - 1) + return false; + + *offsetp = offset; + *instp = vset->vlist[offset].inst; + return true; +} + +/* Switch on/off a metric for value fetching (sampling) */ +void Metric_enable(Metric metric, bool enable) { + pcp->fetch[metric] = enable ? pcp->pmids[metric] : PM_ID_NULL; +} + +bool Metric_enabled(Metric metric) { + return pcp->fetch[metric] != PM_ID_NULL; +} + +void Metric_enableThreads(void) { + pmValueSet* vset = xCalloc(1, sizeof(pmValueSet)); + vset->vlist[0].inst = PM_IN_NULL; + vset->vlist[0].value.lval = 1; + vset->valfmt = PM_VAL_INSITU; + vset->numval = 1; + vset->pmid = pcp->pmids[PCP_CONTROL_THREADS]; + + pmResult* result = xCalloc(1, sizeof(pmResult)); + result->vset[0] = vset; + result->numpmid = 1; + + int sts = pmStore(result); + if (sts < 0 && pmDebugOptions.appl0) + fprintf(stderr, "Error: cannot enable threads: %s\n", pmErrStr(sts)); + + pmFreeResult(result); +} + +bool Metric_fetch(struct timeval *timestamp) { + int sts = pmFetch(pcp->total, pcp->fetch, &pcp->result); + if (sts < 0) { + if (pmDebugOptions.appl0) + fprintf(stderr, "Error: cannot fetch metric values): %s\n", + pmErrStr(sts)); + return false; + } + if (timestamp) + *timestamp = pcp->result->timestamp; + return true; +} + +static int Platform_addMetric(Metric id, const char *name) { + unsigned int i = (unsigned int)id; + + if (i >= PCP_METRIC_COUNT && i >= pcp->total) { + /* added via configuration files */ + unsigned int j = pcp->total + 1; + pcp->fetch = xRealloc(pcp->fetch, j * sizeof(pmID)); + pcp->pmids = xRealloc(pcp->pmids, j * sizeof(pmID)); + pcp->names = xRealloc(pcp->names, j * sizeof(char*)); + pcp->descs = xRealloc(pcp->descs, j * sizeof(pmDesc)); + memset(&pcp->descs[i], 0, sizeof(pmDesc)); + } + + pcp->pmids[i] = pcp->fetch[i] = PM_ID_NULL; + pcp->names[i] = name; + return ++pcp->total; +} + +void Platform_init(void) { + int sts = pmNewContext(PM_CONTEXT_HOST, "local:"); + if (sts < 0) + sts = pmNewContext(PM_CONTEXT_LOCAL, NULL); + if (sts < 0) { + fprintf(stderr, "Cannot setup PCP metric source: %s\n", pmErrStr(sts)); + exit(1); + } + pcp = xCalloc(1, sizeof(Platform)); + pcp->context = sts; + pcp->fetch = xCalloc(PCP_METRIC_COUNT, sizeof(pmID)); + pcp->pmids = xCalloc(PCP_METRIC_COUNT, sizeof(pmID)); + pcp->names = xCalloc(PCP_METRIC_COUNT, sizeof(char*)); + pcp->descs = xCalloc(PCP_METRIC_COUNT, sizeof(pmDesc)); + + for (unsigned int i = 0; i < PCP_METRIC_COUNT; i++) + Platform_addMetric(i, Platform_metricNames[i]); + + sts = pmLookupName(pcp->total, pcp->names, pcp->pmids); + if (sts < 0) { + fprintf(stderr, "Error: cannot lookup metric names: %s\n", pmErrStr(sts)); + exit(1); + } + + for (unsigned int i = 0; i < pcp->total; i++) { + pcp->fetch[i] = PM_ID_NULL; /* default is to not sample */ + + /* expect some metrics to be missing - e.g. PMDA not available */ + if (pcp->pmids[i] == PM_ID_NULL) + continue; + + sts = pmLookupDesc(pcp->pmids[i], &pcp->descs[i]); + if (sts < 0) { + if (pmDebugOptions.appl0) + fprintf(stderr, "Error: cannot lookup metric %s(%s): %s\n", + pcp->names[i], pmIDStr(pcp->pmids[i]), pmErrStr(sts)); + pcp->pmids[i] = PM_ID_NULL; + continue; + } + } + + /* set proc.control.perclient.threads to 1 for live contexts */ + Metric_enableThreads(); + + /* extract values needed for setup - e.g. cpu count, pid_max */ + Metric_enable(PCP_PID_MAX, true); + Metric_enable(PCP_BOOTTIME, true); + Metric_enable(PCP_HINV_NCPU, true); + Metric_enable(PCP_PERCPU_SYSTEM, true); + Metric_enable(PCP_UNAME_SYSNAME, true); + Metric_enable(PCP_UNAME_RELEASE, true); + Metric_enable(PCP_UNAME_MACHINE, true); + + Metric_fetch(NULL); + + for (Metric metric = 0; metric < PCP_PROC_PID; metric++) + Metric_enable(metric, true); + Metric_enable(PCP_PID_MAX, false); /* needed one time only */ + Metric_enable(PCP_BOOTTIME, false); + Metric_enable(PCP_UNAME_SYSNAME, false); + Metric_enable(PCP_UNAME_RELEASE, false); + Metric_enable(PCP_UNAME_MACHINE, false); + + /* first sample (fetch) performed above, save constants */ + Platform_getBootTime(); + Platform_getMaxCPU(); + Platform_getMaxPid(); +} + +void Platform_done(void) { + pmDestroyContext(pcp->context); + free(pcp->fetch); + free(pcp->pmids); + free(pcp->names); + free(pcp->descs); + free(pcp); +} + +void Platform_setBindings(Htop_Action* keys) { + /* no platform-specific key bindings */ + (void)keys; +} + +int Platform_getUptime(void) { + pmAtomValue value; + if (Metric_values(PCP_UPTIME, &value, 1, PM_TYPE_32) == NULL) + return 0; + return value.l; +} + +void Platform_getLoadAverage(double* one, double* five, double* fifteen) { + *one = *five = *fifteen = 0.0; + + pmAtomValue values[3] = {0}; + if (Metric_values(PCP_LOAD_AVERAGE, values, 3, PM_TYPE_DOUBLE) != NULL) { + *one = values[0].d; + *five = values[1].d; + *fifteen = values[2].d; + } +} + +int Platform_getMaxCPU(void) { + if (pcp->ncpu) + return pcp->ncpu; + + pmAtomValue value; + if (Metric_values(PCP_HINV_NCPU, &value, 1, PM_TYPE_32) != NULL) + pcp->ncpu = value.l; + else + pcp->ncpu = -1; + return pcp->ncpu; +} + +int Platform_getMaxPid(void) { + if (pcp->pidmax) + return pcp->pidmax; + + pmAtomValue value; + if (Metric_values(PCP_PID_MAX, &value, 1, PM_TYPE_32) == NULL) + return -1; + pcp->pidmax = value.l; + return pcp->pidmax; +} + +long long Platform_getBootTime(void) { + if (pcp->btime) + return pcp->btime; + + pmAtomValue value; + if (Metric_values(PCP_BOOTTIME, &value, 1, PM_TYPE_64) != NULL) + pcp->btime = value.ll; + return pcp->btime; +} + +static double Platform_setOneCPUValues(Meter* this, pmAtomValue* values) { + + unsigned long long value = values[CPU_TOTAL_PERIOD].ull; + double total = (double) (value == 0 ? 1 : value); + double percent; + + double* v = this->values; + v[CPU_METER_NICE] = values[CPU_NICE_PERIOD].ull / total * 100.0; + v[CPU_METER_NORMAL] = values[CPU_USER_PERIOD].ull / total * 100.0; + if (this->pl->settings->detailedCPUTime) { + v[CPU_METER_KERNEL] = values[CPU_SYSTEM_PERIOD].ull / total * 100.0; + v[CPU_METER_IRQ] = values[CPU_IRQ_PERIOD].ull / total * 100.0; + v[CPU_METER_SOFTIRQ] = values[CPU_SOFTIRQ_PERIOD].ull / total * 100.0; + v[CPU_METER_STEAL] = values[CPU_STEAL_PERIOD].ull / total * 100.0; + v[CPU_METER_GUEST] = values[CPU_GUEST_PERIOD].ull / total * 100.0; + v[CPU_METER_IOWAIT] = values[CPU_IOWAIT_PERIOD].ull / total * 100.0; + this->curItems = 8; + if (this->pl->settings->accountGuestInCPUMeter) + percent = v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6]; + else + percent = v[0] + v[1] + v[2] + v[3] + v[4]; + } else { + v[2] = values[CPU_SYSTEM_ALL_PERIOD].ull / total * 100.0; + value = values[CPU_STEAL_PERIOD].ull + values[CPU_GUEST_PERIOD].ull; + v[3] = value / total * 100.0; + this->curItems = 4; + percent = v[0] + v[1] + v[2] + v[3]; + } + percent = CLAMP(percent, 0.0, 100.0); + if (isnan(percent)) + percent = 0.0; + + v[CPU_METER_FREQUENCY] = values[CPU_FREQUENCY].d; + v[CPU_METER_TEMPERATURE] = NAN; + + return percent; +} + +double Platform_setCPUValues(Meter* this, int cpu) { + const PCPProcessList* pl = (const PCPProcessList*) this->pl; + if (cpu <= 0) /* use aggregate values */ + return Platform_setOneCPUValues(this, pl->cpu); + return Platform_setOneCPUValues(this, pl->percpu[cpu - 1]); +} + +void Platform_setMemoryValues(Meter* this) { + const ProcessList* pl = this->pl; + long int usedMem = pl->usedMem; + long int buffersMem = pl->buffersMem; + long int cachedMem = pl->cachedMem; + usedMem -= buffersMem + cachedMem; + this->total = pl->totalMem; + this->values[0] = usedMem; + this->values[1] = buffersMem; + this->values[2] = cachedMem; +} + +void Platform_setSwapValues(Meter* this) { + const ProcessList* pl = this->pl; + this->total = pl->totalSwap; + this->values[0] = pl->usedSwap; + this->values[1] = pl->cachedSwap; +} + +void Platform_setZramValues(Meter* this) { + (void)this; + + int i, count = Metric_instanceCount(PCP_ZRAM_CAPACITY); + pmAtomValue *values = xCalloc(count, sizeof(pmAtomValue)); + ZramStats stats = {0}; + + if (Metric_values(PCP_ZRAM_CAPACITY, values, count, PM_TYPE_U64)) { + for (i = 0; i < count; i++) + stats.totalZram += values[i].ull; + } + if (Metric_values(PCP_ZRAM_ORIGINAL, values, count, PM_TYPE_U64)) { + for (i = 0; i < count; i++) + stats.usedZramOrig += values[i].ull; + } + if (Metric_values(PCP_ZRAM_COMPRESSED, values, count, PM_TYPE_U64)) { + for (i = 0; i < count; i++) + stats.usedZramComp += values[i].ull; + } + + free(values); + + this->total = stats.totalZram; + this->values[0] = stats.usedZramComp; + this->values[1] = stats.usedZramOrig; +} + +char* Platform_getProcessEnv(pid_t pid) { + pmAtomValue value; + if (!Metric_instance(PCP_PROC_ENVIRON, pid, 0, &value, PM_TYPE_STRING)) + return NULL; + return value.cp; +} + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +void Platform_getPressureStall(const char* file, bool some, double* ten, double* sixty, double* threehundred) { + *ten = *sixty = *threehundred = 0; + + Metric metric; + if (String_eq(file, "cpu")) + metric = PCP_PSI_CPUSOME; + else if (String_eq(file, "io")) + metric = some ? PCP_PSI_IOSOME : PCP_PSI_IOFULL; + else if (String_eq(file, "mem")) + metric = some ? PCP_PSI_MEMSOME : PCP_PSI_MEMFULL; + else + return; + + pmAtomValue values[3] = {0}; + if (Metric_values(metric, values, 3, PM_TYPE_DOUBLE) != NULL) { + *ten = values[0].d; + *sixty = values[1].d; + *threehundred = values[2].d; + } +} + +bool Platform_getDiskIO(DiskIOData* data) { + data->totalBytesRead = 0; + data->totalBytesWritten = 0; + data->totalMsTimeSpend = 0; + + pmAtomValue value; + if (Metric_values(PCP_DISK_READB, &value, 1, PM_TYPE_U64) != NULL) + data->totalBytesRead = value.ull; + if (Metric_values(PCP_DISK_WRITEB, &value, 1, PM_TYPE_U64) != NULL) + data->totalBytesWritten = value.ull; + if (Metric_values(PCP_DISK_ACTIVE, &value, 1, PM_TYPE_U64) != NULL) + data->totalMsTimeSpend = value.ull; + return true; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + + pmAtomValue value; + if (Metric_values(PCP_NET_RECVB, &value, 1, PM_TYPE_U64) != NULL) + *bytesReceived = value.ull; + if (Metric_values(PCP_NET_SENDB, &value, 1, PM_TYPE_U64) != NULL) + *bytesTransmitted = value.ull; + if (Metric_values(PCP_NET_RECVP, &value, 1, PM_TYPE_U64) != NULL) + *packetsReceived = value.ull; + if (Metric_values(PCP_NET_SENDP, &value, 1, PM_TYPE_U64) != NULL) + *packetsTransmitted = value.ull; + return true; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + *level = NAN; + *isOnAC = AC_ERROR; +} diff --git a/pcp/Platform.h b/pcp/Platform.h new file mode 100644 index 000000000..c9e46b800 --- /dev/null +++ b/pcp/Platform.h @@ -0,0 +1,214 @@ +#ifndef HEADER_Platform +#define HEADER_Platform +/* +htop - pcp/Platform.h +(C) 2014 Hisham H. Muhammad +(C) 2020 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include +#include +#include + +#undef PACKAGE_URL +#undef PACKAGE_NAME +#undef PACKAGE_STRING +#undef PACKAGE_TARNAME +#undef PACKAGE_VERSION +#undef PACKAGE_BUGREPORT + +#include "Action.h" +#include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "Meter.h" +#include "Process.h" +#include "ProcessLocksScreen.h" +#include "SignalsPanel.h" + +extern ProcessField Platform_defaultFields[]; + +extern int Platform_numberOfFields; + +extern const SignalItem Platform_signals[]; + +extern const unsigned int Platform_numberOfSignals; + +extern const MeterClass* const Platform_meterTypes[]; + +void Platform_init(void); + +void Platform_done(void); + +void Platform_setBindings(Htop_Action* keys); + +int Platform_getUptime(void); + +void Platform_getLoadAverage(double* one, double* five, double* fifteen); + +long long Platform_getBootTime(void); + +int Platform_getMaxCPU(void); + +int Platform_getMaxPid(void); + +double Platform_setCPUValues(Meter* this, int cpu); + +void Platform_setMemoryValues(Meter* this); + +void Platform_setSwapValues(Meter* this); + +void Platform_setZramValues(Meter* this); + +char* Platform_getProcessEnv(pid_t pid); + +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +void Platform_getPressureStall(const char *file, bool some, double* ten, double* sixty, double* threehundred); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double *percent, ACPresence *isOnAC); + +typedef enum Metric_ { + PCP_CONTROL_THREADS, /* proc.control.perclient.threads */ + + PCP_HINV_NCPU, /* hinv.ncpu */ + PCP_HINV_CPUCLOCK, /* hinv.cpu.clock */ + PCP_UNAME_SYSNAME, /* kernel.uname.sysname */ + PCP_UNAME_RELEASE, /* kernel.uname.release */ + PCP_UNAME_MACHINE, /* kernel.uname.machine */ + PCP_LOAD_AVERAGE, /* kernel.all.load */ + PCP_PID_MAX, /* kernel.all.pid_max */ + PCP_UPTIME, /* kernel.all.uptime */ + PCP_BOOTTIME, /* kernel.all.boottime */ + PCP_CPU_USER, /* kernel.all.cpu.user */ + PCP_CPU_NICE, /* kernel.all.cpu.nice */ + PCP_CPU_SYSTEM, /* kernel.all.cpu.sys */ + PCP_CPU_IDLE, /* kernel.all.cpu.idle */ + PCP_CPU_IOWAIT, /* kernel.all.cpu.wait.total */ + PCP_CPU_IRQ, /* kernel.all.cpu.intr */ + PCP_CPU_SOFTIRQ, /* kernel.all.cpu.irq.soft */ + PCP_CPU_STEAL, /* kernel.all.cpu.steal */ + PCP_CPU_GUEST, /* kernel.all.cpu.guest */ + PCP_CPU_GUESTNICE, /* kernel.all.cpu.guest_nice */ + PCP_PERCPU_USER, /* kernel.percpu.cpu.user */ + PCP_PERCPU_NICE, /* kernel.percpu.cpu.nice */ + PCP_PERCPU_SYSTEM, /* kernel.percpu.cpu.sys */ + PCP_PERCPU_IDLE, /* kernel.percpu.cpu.idle */ + PCP_PERCPU_IOWAIT, /* kernel.percpu.cpu.wait.total */ + PCP_PERCPU_IRQ, /* kernel.percpu.cpu.intr */ + PCP_PERCPU_SOFTIRQ, /* kernel.percpu.cpu.irq.soft */ + PCP_PERCPU_STEAL, /* kernel.percpu.cpu.steal */ + PCP_PERCPU_GUEST, /* kernel.percpu.cpu.guest */ + PCP_PERCPU_GUESTNICE, /* kernel.percpu.cpu.guest_nice */ + PCP_MEM_TOTAL, /* mem.physmem */ + PCP_MEM_FREE, /* mem.util.free */ + PCP_MEM_BUFFERS, /* mem.util.bufmem */ + PCP_MEM_CACHED, /* mem.util.cached */ + PCP_MEM_AVAILABLE, /* mem.util.available */ + PCP_MEM_SRECLAIM, /* mem.util.slabReclaimable */ + PCP_MEM_SWAPCACHED, /* mem.util.swapCached */ + PCP_MEM_SWAPTOTAL, /* mem.util.swapTotal */ + PCP_MEM_SWAPFREE, /* mem.util.swapFree */ + PCP_DISK_READB, /* disk.all.read_bytes */ + PCP_DISK_WRITEB, /* disk.all.write_bytes */ + PCP_DISK_ACTIVE, /* disk.all.avactive */ + PCP_NET_RECVB, /* network.all.in.bytes */ + PCP_NET_SENDB, /* network.all.out.bytes */ + PCP_NET_RECVP, /* network.all.in.packets */ + PCP_NET_SENDP, /* network.all.out.packets */ + PCP_PSI_CPUSOME, /* kernel.all.pressure.cpu.some.avg */ + PCP_PSI_IOSOME, /* kernel.all.pressure.io.some.avg */ + PCP_PSI_IOFULL, /* kernel.all.pressure.io.full.avg */ + PCP_PSI_MEMSOME, /* kernel.all.pressure.memory.some.avg */ + PCP_PSI_MEMFULL, /* kernel.all.pressure.memory.full.avg */ + PCP_ZRAM_CAPACITY, /* zram.capacity */ + PCP_ZRAM_ORIGINAL, /* zram.mm_stat.data_size.original */ + PCP_ZRAM_COMPRESSED, /* zram.mm_stat.data_size.compressed */ + + PCP_PROC_PID, /* proc.psinfo.pid */ + PCP_PROC_PPID, /* proc.psinfo.ppid */ + PCP_PROC_TGID, /* proc.psinfo.tgid */ + PCP_PROC_PGRP, /* proc.psinfo.pgrp */ + PCP_PROC_SESSION, /* proc.psinfo.session */ + PCP_PROC_STATE, /* proc.psinfo.sname */ + PCP_PROC_TTY, /* proc.psinfo.tty */ + PCP_PROC_TTYPGRP, /* proc.psinfo.tty_pgrp */ + PCP_PROC_MINFLT, /* proc.psinfo.minflt */ + PCP_PROC_MAJFLT, /* proc.psinfo.maj_flt */ + PCP_PROC_CMINFLT, /* proc.psinfo.cmin_flt */ + PCP_PROC_CMAJFLT, /* proc.psinfo.cmaj_flt */ + PCP_PROC_UTIME, /* proc.psinfo.utime */ + PCP_PROC_STIME, /* proc.psinfo.stime */ + PCP_PROC_CUTIME, /* proc.psinfo.cutime */ + PCP_PROC_CSTIME, /* proc.psinfo.cstime */ + PCP_PROC_PRIORITY, /* proc.psinfo.priority */ + PCP_PROC_NICE, /* proc.psinfo.nice */ + PCP_PROC_THREADS, /* proc.psinfo.threads */ + PCP_PROC_STARTTIME, /* proc.psinfo.start_time */ + PCP_PROC_PROCESSOR, /* proc.psinfo.processor */ + PCP_PROC_CMD, /* proc.psinfo.cmd */ + PCP_PROC_PSARGS, /* proc.psinfo.psargs */ + PCP_PROC_CGROUPS, /* proc.psinfo.cgroups */ + PCP_PROC_OOMSCORE, /* proc.psinfo.oom_score */ + PCP_PROC_VCTXSW, /* proc.psinfo.vctxsw */ + PCP_PROC_NVCTXSW, /* proc.psinfo.nvctxsw */ + PCP_PROC_LABELS, /* proc.psinfo.labels */ + PCP_PROC_ENVIRON, /* proc.psinfo.environ */ + PCP_PROC_TTYNAME, /* proc.psinfo.ttyname */ + + PCP_PROC_ID_UID, /* proc.id.uid */ + PCP_PROC_ID_USER, /* proc.id.uid_nm */ + + PCP_PROC_IO_RCHAR, /* proc.io.rchar */ + PCP_PROC_IO_WCHAR, /* proc.io.wchar */ + PCP_PROC_IO_SYSCR, /* proc.io.syscr */ + PCP_PROC_IO_SYSCW, /* proc.io.syscw */ + PCP_PROC_IO_READB, /* proc.io.read_bytes */ + PCP_PROC_IO_WRITEB, /* proc.io.write_bytes */ + PCP_PROC_IO_CANCELLED, /* proc.io.cancelled_write_bytes */ + + PCP_PROC_MEM_SIZE, /* proc.memory.size */ + PCP_PROC_MEM_RSS, /* proc.memory.rss */ + PCP_PROC_MEM_SHARE, /* proc.memory.share */ + PCP_PROC_MEM_TEXTRS, /* proc.memory.textrss */ + PCP_PROC_MEM_LIBRS, /* proc.memory.librss */ + PCP_PROC_MEM_DATRS, /* proc.memory.datrss */ + PCP_PROC_MEM_DIRTY, /* proc.memory.dirty */ + + PCP_PROC_SMAPS_PSS, /* proc.smaps.pss */ + PCP_PROC_SMAPS_SWAP, /* proc.smaps.swap */ + PCP_PROC_SMAPS_SWAPPSS, /* proc.smaps.swappss */ + + PCP_METRIC_COUNT /* total metric count */ +} Metric; + +void Metric_enable(Metric metric, bool enable); + +bool Metric_enabled(Metric metric); + +void Metric_enableThreads(void); + +bool Metric_fetch(struct timeval *timestamp); + +bool Metric_iterate(Metric metric, int* instp, int* offsetp); + +pmAtomValue* Metric_values(Metric metric, pmAtomValue *atom, int count, int type); + +int Metric_instanceCount(Metric metric); + +int Metric_instanceOffset(Metric metric, int inst); + +pmAtomValue *Metric_instance(Metric metric, int inst, int offset, pmAtomValue *atom, int type); + +#endif diff --git a/pcp/ProcessField.h b/pcp/ProcessField.h new file mode 100644 index 000000000..ee03cbafb --- /dev/null +++ b/pcp/ProcessField.h @@ -0,0 +1,50 @@ +#ifndef HEADER_PCPProcessField +#define HEADER_PCPProcessField +/* +htop - pcp/ProcessField.h +(C) 2014 Hisham H. Muhammad +(C) 2021 htop dev team +(C) 2020-2021 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + + +#define PLATFORM_PROCESS_FIELDS \ + CMINFLT = 11, \ + CMAJFLT = 13, \ + UTIME = 14, \ + STIME = 15, \ + CUTIME = 16, \ + CSTIME = 17, \ + M_SHARE = 41, \ + M_TRS = 42, \ + M_DRS = 43, \ + M_LRS = 44, \ + M_DT = 45, \ + CTID = 100, \ + RCHAR = 103, \ + WCHAR = 104, \ + SYSCR = 105, \ + SYSCW = 106, \ + RBYTES = 107, \ + WBYTES = 108, \ + CNCLWB = 109, \ + IO_READ_RATE = 110, \ + IO_WRITE_RATE = 111, \ + IO_RATE = 112, \ + CGROUP = 113, \ + OOM = 114, \ + PERCENT_CPU_DELAY = 116, \ + PERCENT_IO_DELAY = 117, \ + PERCENT_SWAP_DELAY = 118, \ + M_PSS = 119, \ + M_SWAP = 120, \ + M_PSSWP = 121, \ + CTXT = 122, \ + SECATTR = 123, \ + PROC_COMM = 124, \ + // End of list + + +#endif /* HEADER_PCPProcessField */ From 5fe18609084a776fda1c9432623fb6a54d9a1976 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Wed, 17 Feb 2021 15:47:17 +1100 Subject: [PATCH 02/20] Add new CI workflow to check pcp-enabled builds --- .github/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index afc9db886..ea9f4b681 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,24 @@ jobs: - name: Distcheck run: make distcheck DISTCHECK_CONFIGURE_FLAGS='--enable-static --enable-werror --enable-openvz --enable-vserver --enable-ancient-vserver --enable-unicode --disable-hwloc --disable-delayacct --enable-sensors --enable-capabilities' + build-ubuntu-latest-pcp: + # Turns out 'ubuntu-latest' can be older than 20.04, we want PCP v5+ + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - name: Install Dependencies + run: sudo apt-get install libpcp3-dev libncursesw5-dev libtinfo-dev libgpm-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + # Until Ubuntu catches up with pcp-5.2.3+, cannot use -werror due to: + # passing argument 2 of ‘pmLookupName’ from incompatible pointer type + run: ./configure --enable-pcp --enable-unicode + - name: Build + run: make -k + - name: Distcheck + run: make distcheck DISTCHECK_CONFIGURE_FLAGS="--enable-pcp --enable-unicode" + build-ubuntu-latest-clang-analyzer: runs-on: ubuntu-latest env: From 26e85d3229fb2bd3554ecd776b21c8dbab7a5eb4 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Fri, 19 Feb 2021 14:13:27 +1100 Subject: [PATCH 03/20] Fix cut+paste typo in --enable-pcp error message --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index f9cfa914c..39567fad1 100644 --- a/configure.ac +++ b/configure.ac @@ -114,7 +114,7 @@ case "$enable_pcp" in AC_DEFINE([HTOP_PCP], [1], [Define if building pcp htop binary.]) ;; *) - AC_MSG_ERROR([bad value '$enable_static' for --enable-static option]) + AC_MSG_ERROR([bad value '$enable_pcp' for --enable-pcp option]) ;; esac From d3dda299705d3046200abf23990ae7b1d1bee931 Mon Sep 17 00:00:00 2001 From: Sohaib Date: Mon, 22 Feb 2021 16:45:44 +1100 Subject: [PATCH 04/20] Add ZFS ARC statistics and meters to the PCP platform --- Makefile.am | 9 +++++++-- pcp/PCPProcessList.c | 40 ++++++++++++++++++++++++++++++++++++++++ pcp/PCPProcessList.h | 2 ++ pcp/Platform.c | 36 +++++++++++++++++++++++++++++++++++- pcp/Platform.h | 15 +++++++++++++++ 5 files changed, 99 insertions(+), 3 deletions(-) diff --git a/Makefile.am b/Makefile.am index c66aa46c6..8ae0e1f9a 100644 --- a/Makefile.am +++ b/Makefile.am @@ -338,7 +338,10 @@ pcp_platform_headers = \ pcp/ProcessField.h \ linux/PressureStallMeter.h \ linux/ZramMeter.h \ - linux/ZramStats.h + linux/ZramStats.h \ + zfs/ZfsArcMeter.h \ + zfs/ZfsArcStats.h \ + zfs/ZfsCompressedArcMeter.h if HTOP_PCP myhtopplatsources = \ @@ -346,7 +349,9 @@ myhtopplatsources = \ pcp/PCPProcessList.c \ pcp/Platform.c \ linux/PressureStallMeter.c \ - linux/ZramMeter.c + linux/ZramMeter.c \ + zfs/ZfsArcMeter.c \ + zfs/ZfsCompressedArcMeter.c myhtopplatheaders = $(pcp_platform_headers) endif diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 0e608b1de..0e7b26d5d 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -733,6 +733,45 @@ static void PCPProcessList_updateHeader(ProcessList* super, const Settings* sett PCPProcessList_updatePerCPUReal(this, PCP_HINV_CPUCLOCK, CPU_FREQUENCY); } +static inline void PCPProcessList_scanZfsArcstats(PCPProcessList* this) { + unsigned long long int dbufSize = 0; + unsigned long long int dnodeSize = 0; + unsigned long long int bonusSize = 0; + pmAtomValue value, + comp, + uncomp; + + if (Metric_values(PCP_ZFS_ARC_ANON_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.anon = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_C_MAX, &value, 1, PM_TYPE_U64)) + this->zfs.max = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_BONUS_SIZE, &value, 1, PM_TYPE_U64)) + bonusSize = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_DBUF_SIZE, &value, 1, PM_TYPE_U64)) + dbufSize = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_DNODE_SIZE, &value, 1, PM_TYPE_U64)) + dnodeSize = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_COMPRESSED_SIZE, &comp, 1, PM_TYPE_U64)) { + this->zfs.isCompressed = 1; + } + if (Metric_values(PCP_ZFS_ARC_UNCOMPRESSED_SIZE, &uncomp, 1, PM_TYPE_U64)) + if (Metric_values(PCP_ZFS_ARC_HDR_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.header = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_MFU_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.MFU = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_MRU_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.MRU = value.ull / 1024; + if (Metric_values(PCP_ZFS_ARC_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.size = value.ull / 1024; + + this->zfs.enabled = (this->zfs.size > 0 ? 1 : 0); + this->zfs.other = (dbufSize + dnodeSize + bonusSize) / 1024; + if ( this->zfs.isCompressed ) { + this->zfs.compressed = comp.ull /1024; + this->zfs.uncompressed = uncomp.ull /1024; + } +} + void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { PCPProcessList* this = (PCPProcessList*) super; const Settings* settings = super->settings; @@ -769,6 +808,7 @@ void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { this->timestamp = pmtimevalToReal(×tamp); PCPProcessList_updateHeader(super, settings); + PCPProcessList_scanZfsArcstats(this); /* In pause mode only update global data for meters (CPU, memory, etc) */ if (pauseProcessUpdate) diff --git a/pcp/PCPProcessList.h b/pcp/PCPProcessList.h index 28f1d9cee..70ddfb755 100644 --- a/pcp/PCPProcessList.h +++ b/pcp/PCPProcessList.h @@ -16,6 +16,7 @@ in the source distribution for its full text. #include "ProcessList.h" #include "pcp/Platform.h" #include "UsersTable.h" +#include "zfs/ZfsArcStats.h" typedef enum CPUMetric_ { CPU_TOTAL_TIME, @@ -57,6 +58,7 @@ typedef struct PCPProcessList_ { pmAtomValue* cpu; /* aggregate values for each metric */ pmAtomValue** percpu; /* per-processor values for each metric */ pmAtomValue* values; /* per-processor buffer for just one metric */ + ZfsArcStats zfs; } PCPProcessList; ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); diff --git a/pcp/Platform.c b/pcp/Platform.c index 4ac7c701d..37074cc2e 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -38,10 +38,12 @@ in the source distribution for its full text. #include "TasksMeter.h" #include "UptimeMeter.h" #include "XUtils.h" - #include "linux/PressureStallMeter.h" #include "linux/ZramMeter.h" #include "linux/ZramStats.h" +#include "zfs/ZfsArcMeter.h" +#include "zfs/ZfsArcStats.h" +#include "zfs/ZfsCompressedArcMeter.h" typedef struct Platform_ { int context; /* PMAPI(3) context identifier */ @@ -100,6 +102,8 @@ const MeterClass* const Platform_meterTypes[] = { &PressureStallIOFullMeter_class, &PressureStallMemorySomeMeter_class, &PressureStallMemoryFullMeter_class, + &ZfsArcMeter_class, + &ZfsCompressedArcMeter_class, &ZramMeter_class, &DiskIOMeter_class, &NetworkIOMeter_class, @@ -161,6 +165,18 @@ static const char *Platform_metricNames[] = { [PCP_PSI_MEMSOME] = "kernel.all.pressure.memory.some.avg", [PCP_PSI_MEMFULL] = "kernel.all.pressure.memory.full.avg", + [PCP_ZFS_ARC_ANON_SIZE] = "zfs.arc.anon_size", + [PCP_ZFS_ARC_BONUS_SIZE] = "zfs.arc.bonus_size", + [PCP_ZFS_ARC_COMPRESSED_SIZE] = "zfs.arc.compressed_size", + [PCP_ZFS_ARC_UNCOMPRESSED_SIZE] = "zfs.arc.uncompressed_size", + [PCP_ZFS_ARC_C_MAX] = "zfs.arc.c_max", + [PCP_ZFS_ARC_DBUF_SIZE] = "zfs.arc.dbuf_size", + [PCP_ZFS_ARC_DNODE_SIZE] = "zfs.arc.dnode_size", + [PCP_ZFS_ARC_HDR_SIZE] = "zfs.arc.hdr_size", + [PCP_ZFS_ARC_MFU_SIZE] = "zfs.arc.mfu.size", + [PCP_ZFS_ARC_MRU_SIZE] = "zfs.arc.mru.size", + [PCP_ZFS_ARC_SIZE] = "zfs.arc.size", + [PCP_ZRAM_CAPACITY] = "zram.capacity", [PCP_ZRAM_ORIGINAL] = "zram.mm_stat.data_size.original", [PCP_ZRAM_COMPRESSED] = "zram.mm_stat.data_size.compressed", @@ -562,6 +578,7 @@ double Platform_setCPUValues(Meter* this, int cpu) { void Platform_setMemoryValues(Meter* this) { const ProcessList* pl = this->pl; + const PCPProcessList* ppl = (const PCPProcessList*) pl; long int usedMem = pl->usedMem; long int buffersMem = pl->buffersMem; long int cachedMem = pl->cachedMem; @@ -570,6 +587,11 @@ void Platform_setMemoryValues(Meter* this) { this->values[0] = usedMem; this->values[1] = buffersMem; this->values[2] = cachedMem; + + if (ppl->zfs.enabled != 0) { + this->values[0] -= ppl->zfs.size; + this->values[2] += ppl->zfs.size; + } } void Platform_setSwapValues(Meter* this) { @@ -606,6 +628,18 @@ void Platform_setZramValues(Meter* this) { this->values[1] = stats.usedZramOrig; } +void Platform_setZfsArcValues(Meter* this) { + const PCPProcessList* ppl = (const PCPProcessList*) this->pl; + + ZfsArcMeter_readStats(this, &(ppl->zfs)); +} + +void Platform_setZfsCompressedArcValues(Meter* this) { + const PCPProcessList* ppl = (const PCPProcessList*) this->pl; + + ZfsCompressedArcMeter_readStats(this, &(ppl->zfs)); +} + char* Platform_getProcessEnv(pid_t pid) { pmAtomValue value; if (!Metric_instance(PCP_PROC_ENVIRON, pid, 0, &value, PM_TYPE_STRING)) diff --git a/pcp/Platform.h b/pcp/Platform.h index c9e46b800..eb6b3f105 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -62,6 +62,10 @@ void Platform_setSwapValues(Meter* this); void Platform_setZramValues(Meter* this); +void Platform_setZfsArcValues(Meter* this); + +void Platform_setZfsCompressedArcValues(Meter* this); + char* Platform_getProcessEnv(pid_t pid); char* Platform_getInodeFilename(pid_t pid, ino_t inode); @@ -132,6 +136,17 @@ typedef enum Metric_ { PCP_PSI_IOFULL, /* kernel.all.pressure.io.full.avg */ PCP_PSI_MEMSOME, /* kernel.all.pressure.memory.some.avg */ PCP_PSI_MEMFULL, /* kernel.all.pressure.memory.full.avg */ + PCP_ZFS_ARC_ANON_SIZE, /* zfs.arc.anon_size */ + PCP_ZFS_ARC_BONUS_SIZE, /* zfs.arc.bonus_size */ + PCP_ZFS_ARC_COMPRESSED_SIZE, /* zfs.arc.compressed_size */ + PCP_ZFS_ARC_UNCOMPRESSED_SIZE, /* zfs.arc.uncompressed_size */ + PCP_ZFS_ARC_C_MAX, /* zfs.arc.c_max */ + PCP_ZFS_ARC_DBUF_SIZE, /* zfs.arc.dbuf_size */ + PCP_ZFS_ARC_DNODE_SIZE, /* zfs.arc.dnode_size */ + PCP_ZFS_ARC_HDR_SIZE, /* zfs.arc.hdr_size */ + PCP_ZFS_ARC_MFU_SIZE, /* zfs.arc.mfu_size */ + PCP_ZFS_ARC_MRU_SIZE, /* zfs.arc.mru_size */ + PCP_ZFS_ARC_SIZE, /* zfs.arc.size */ PCP_ZRAM_CAPACITY, /* zram.capacity */ PCP_ZRAM_ORIGINAL, /* zram.mm_stat.data_size.original */ PCP_ZRAM_COMPRESSED, /* zram.mm_stat.data_size.compressed */ From 7e5d24ef7eebcd7689882e6a2168f97907821b9a Mon Sep 17 00:00:00 2001 From: Sohaib Date: Mon, 22 Feb 2021 16:50:39 +1100 Subject: [PATCH 05/20] Fix PCP ZramMeter in presense of missing zram metrics --- pcp/Platform.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pcp/Platform.c b/pcp/Platform.c index 37074cc2e..5882338b7 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -605,6 +605,9 @@ void Platform_setZramValues(Meter* this) { (void)this; int i, count = Metric_instanceCount(PCP_ZRAM_CAPACITY); + if(!count) + return; + pmAtomValue *values = xCalloc(count, sizeof(pmAtomValue)); ZramStats stats = {0}; From 6f2f3f42bab0fdebc0a2c16919b0e7c364c7a5c2 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Mon, 22 Feb 2021 16:52:32 +1100 Subject: [PATCH 06/20] Ensure PCP platform ZramMeter always uses initialized data --- pcp/Platform.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pcp/Platform.c b/pcp/Platform.c index 5882338b7..ebb705491 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -602,11 +602,13 @@ void Platform_setSwapValues(Meter* this) { } void Platform_setZramValues(Meter* this) { - (void)this; - int i, count = Metric_instanceCount(PCP_ZRAM_CAPACITY); - if(!count) + if (!count) { + this->total = 0; + this->values[0] = 0; + this->values[1] = 0; return; + } pmAtomValue *values = xCalloc(count, sizeof(pmAtomValue)); ZramStats stats = {0}; From 9978e43ea6709fffa0b1aaa82caaf14587a91446 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Mon, 22 Feb 2021 16:54:33 +1100 Subject: [PATCH 07/20] Fixes and cleanups for ZFS Meters and metrics --- pcp/PCPProcessList.c | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 0e7b26d5d..a823695e5 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -737,39 +737,35 @@ static inline void PCPProcessList_scanZfsArcstats(PCPProcessList* this) { unsigned long long int dbufSize = 0; unsigned long long int dnodeSize = 0; unsigned long long int bonusSize = 0; - pmAtomValue value, - comp, - uncomp; + pmAtomValue value; + memset(&this->zfs, 0, sizeof(ZfsArcStats)); if (Metric_values(PCP_ZFS_ARC_ANON_SIZE, &value, 1, PM_TYPE_U64)) - this->zfs.anon = value.ull / 1024; + this->zfs.anon = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_C_MAX, &value, 1, PM_TYPE_U64)) - this->zfs.max = value.ull / 1024; + this->zfs.max = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_BONUS_SIZE, &value, 1, PM_TYPE_U64)) - bonusSize = value.ull / 1024; + bonusSize = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_DBUF_SIZE, &value, 1, PM_TYPE_U64)) - dbufSize = value.ull / 1024; + dbufSize = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_DNODE_SIZE, &value, 1, PM_TYPE_U64)) - dnodeSize = value.ull / 1024; - if (Metric_values(PCP_ZFS_ARC_COMPRESSED_SIZE, &comp, 1, PM_TYPE_U64)) { - this->zfs.isCompressed = 1; - } - if (Metric_values(PCP_ZFS_ARC_UNCOMPRESSED_SIZE, &uncomp, 1, PM_TYPE_U64)) + dnodeSize = value.ull / ONE_K; + if (Metric_values(PCP_ZFS_ARC_COMPRESSED_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.compressed = value.ull / ONE_K; + if (Metric_values(PCP_ZFS_ARC_UNCOMPRESSED_SIZE, &value, 1, PM_TYPE_U64)) + this->zfs.uncompressed = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_HDR_SIZE, &value, 1, PM_TYPE_U64)) - this->zfs.header = value.ull / 1024; + this->zfs.header = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_MFU_SIZE, &value, 1, PM_TYPE_U64)) - this->zfs.MFU = value.ull / 1024; + this->zfs.MFU = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_MRU_SIZE, &value, 1, PM_TYPE_U64)) - this->zfs.MRU = value.ull / 1024; + this->zfs.MRU = value.ull / ONE_K; if (Metric_values(PCP_ZFS_ARC_SIZE, &value, 1, PM_TYPE_U64)) - this->zfs.size = value.ull / 1024; + this->zfs.size = value.ull / ONE_K; - this->zfs.enabled = (this->zfs.size > 0 ? 1 : 0); - this->zfs.other = (dbufSize + dnodeSize + bonusSize) / 1024; - if ( this->zfs.isCompressed ) { - this->zfs.compressed = comp.ull /1024; - this->zfs.uncompressed = uncomp.ull /1024; - } + this->zfs.other = (dbufSize + dnodeSize + bonusSize) / ONE_K; + this->zfs.enabled = (this->zfs.size > 0); + this->zfs.isCompressed = (this->zfs.compressed > 0); } void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { From 7003a98cde9ceec46692c62983ba22af857ab549 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Fri, 5 Mar 2021 16:35:32 +1100 Subject: [PATCH 08/20] Update PCP platform to match latest API changes Updates for recent NetworkIO Meter changes, adds support for the SysArch and HostName Meters. The SysArch change is based on work originally by Sohaib Mohamed. --- pcp/Platform.c | 100 +++++++++++++++++++++++++++++++++++++++++-------- pcp/Platform.h | 14 +++++-- 2 files changed, 95 insertions(+), 19 deletions(-) diff --git a/pcp/Platform.c b/pcp/Platform.c index ebb705491..4fcf3db1e 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -35,6 +35,7 @@ in the source distribution for its full text. #include "ProvideCurses.h" #include "Settings.h" #include "SwapMeter.h" +#include "SysArchMeter.h" #include "TasksMeter.h" #include "UptimeMeter.h" #include "XUtils.h" @@ -45,6 +46,7 @@ in the source distribution for its full text. #include "zfs/ZfsArcStats.h" #include "zfs/ZfsCompressedArcMeter.h" + typedef struct Platform_ { int context; /* PMAPI(3) context identifier */ unsigned int total; /* total number of all metrics */ @@ -55,6 +57,7 @@ typedef struct Platform_ { pmResult* result; /* sample values result indexed by Metric */ long long btime; /* boottime in seconds since the epoch */ + char *release; /* uname and distro from this context */ int pidmax; /* maximum platform process identifier */ int ncpu; /* maximum processor count configured */ } Platform; @@ -107,6 +110,7 @@ const MeterClass* const Platform_meterTypes[] = { &ZramMeter_class, &DiskIOMeter_class, &NetworkIOMeter_class, + &SysArchMeter_class, NULL }; @@ -118,6 +122,7 @@ static const char *Platform_metricNames[] = { [PCP_UNAME_SYSNAME] = "kernel.uname.sysname", [PCP_UNAME_RELEASE] = "kernel.uname.release", [PCP_UNAME_MACHINE] = "kernel.uname.machine", + [PCP_UNAME_DISTRO] = "kernel.uname.distro", [PCP_LOAD_AVERAGE] = "kernel.all.load", [PCP_PID_MAX] = "kernel.all.pid_max", [PCP_UPTIME] = "kernel.all.uptime", @@ -449,6 +454,7 @@ void Platform_init(void) { Metric_enable(PCP_UNAME_SYSNAME, true); Metric_enable(PCP_UNAME_RELEASE, true); Metric_enable(PCP_UNAME_MACHINE, true); + Metric_enable(PCP_UNAME_DISTRO, true); Metric_fetch(NULL); @@ -459,9 +465,11 @@ void Platform_init(void) { Metric_enable(PCP_UNAME_SYSNAME, false); Metric_enable(PCP_UNAME_RELEASE, false); Metric_enable(PCP_UNAME_MACHINE, false); + Metric_enable(PCP_UNAME_DISTRO, false); /* first sample (fetch) performed above, save constants */ Platform_getBootTime(); + Platform_getRelease(0); Platform_getMaxCPU(); Platform_getMaxPid(); } @@ -645,6 +653,76 @@ void Platform_setZfsCompressedArcValues(Meter* this) { ZfsCompressedArcMeter_readStats(this, &(ppl->zfs)); } +void Platform_getHostname(char* buffer, size_t size) { + pmGetHostName(pcp->context, buffer, size); +} + +void Platform_getRelease(char** string) { + /* fast-path - previously-formatted string */ + if (string) { + *string = pcp->release; + return; + } + + /* first call, extract just-sampled values */ + pmAtomValue value; + + char* name = NULL; + if (Metric_values(PCP_UNAME_SYSNAME, &value, 1, PM_TYPE_STRING)) + name = value.cp; + char* release = NULL; + if (Metric_values(PCP_UNAME_RELEASE, &value, 1, PM_TYPE_STRING)) + release = value.cp; + char* machine = NULL; + if (Metric_values(PCP_UNAME_MACHINE, &value, 1, PM_TYPE_STRING)) + machine = value.cp; + char* distro = NULL; + if (Metric_values(PCP_UNAME_DISTRO, &value, 1, PM_TYPE_STRING)) + distro = value.cp; + + size_t length = 16; /* padded for formatting characters */ + if (name) + length += strlen(name); + if (release) + length += strlen(release); + if (machine) + length += strlen(machine); + if (distro) + length += strlen(distro); + pcp->release = xCalloc(1, length); + + if (name) { + strcat(pcp->release, name); + strcat(pcp->release, " "); + } + if (release) { + strcat(pcp->release, release); + strcat(pcp->release, " "); + } + if (machine) { + strcat(pcp->release, "["); + strcat(pcp->release, machine); + strcat(pcp->release, "] "); + } + if (distro) { + if (pcp->release[0] != '\0') { + strcat(pcp->release, "@ "); + strcat(pcp->release, distro); + } else { + strcat(pcp->release, distro); + } + strcat(pcp->release, " "); + } + + if (pcp->release) /* cull trailing space */ + pcp->release[strlen(pcp->release)] = '\0'; + + free(distro); + free(machine); + free(release); + free(name); +} + char* Platform_getProcessEnv(pid_t pid) { pmAtomValue value; if (!Metric_instance(PCP_PROC_ENVIRON, pid, 0, &value, PM_TYPE_STRING)) @@ -685,9 +763,7 @@ void Platform_getPressureStall(const char* file, bool some, double* ten, double* } bool Platform_getDiskIO(DiskIOData* data) { - data->totalBytesRead = 0; - data->totalBytesWritten = 0; - data->totalMsTimeSpend = 0; + memset(data, 0, sizeof(*data)); pmAtomValue value; if (Metric_values(PCP_DISK_READB, &value, 1, PM_TYPE_U64) != NULL) @@ -699,24 +775,18 @@ bool Platform_getDiskIO(DiskIOData* data) { return true; } -bool Platform_getNetworkIO(unsigned long int* bytesReceived, - unsigned long int* packetsReceived, - unsigned long int* bytesTransmitted, - unsigned long int* packetsTransmitted) { - *bytesReceived = 0; - *packetsReceived = 0; - *bytesTransmitted = 0; - *packetsTransmitted = 0; +bool Platform_getNetworkIO(NetworkIOData* data) { + memset(data, 0, sizeof(*data)); pmAtomValue value; if (Metric_values(PCP_NET_RECVB, &value, 1, PM_TYPE_U64) != NULL) - *bytesReceived = value.ull; + data->bytesReceived = value.ull; if (Metric_values(PCP_NET_SENDB, &value, 1, PM_TYPE_U64) != NULL) - *bytesTransmitted = value.ull; + data->bytesTransmitted = value.ull; if (Metric_values(PCP_NET_RECVP, &value, 1, PM_TYPE_U64) != NULL) - *packetsReceived = value.ull; + data->packetsReceived = value.ull; if (Metric_values(PCP_NET_SENDP, &value, 1, PM_TYPE_U64) != NULL) - *packetsTransmitted = value.ull; + data->packetsTransmitted = value.ull; return true; } diff --git a/pcp/Platform.h b/pcp/Platform.h index eb6b3f105..4d66d8880 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -24,9 +24,12 @@ in the source distribution for its full text. #include "BatteryMeter.h" #include "DiskIOMeter.h" #include "Meter.h" +#include "NetworkIOMeter.h" #include "Process.h" #include "ProcessLocksScreen.h" #include "SignalsPanel.h" +#include "SysArchMeter.h" + extern ProcessField Platform_defaultFields[]; @@ -76,13 +79,15 @@ void Platform_getPressureStall(const char *file, bool some, double* ten, double* bool Platform_getDiskIO(DiskIOData* data); -bool Platform_getNetworkIO(unsigned long int* bytesReceived, - unsigned long int* packetsReceived, - unsigned long int* bytesTransmitted, - unsigned long int* packetsTransmitted); +bool Platform_getNetworkIO(NetworkIOData* data); void Platform_getBattery(double *percent, ACPresence *isOnAC); +void Platform_getHostname(char* buffer, size_t size); + +void Platform_getRelease(char** string); + + typedef enum Metric_ { PCP_CONTROL_THREADS, /* proc.control.perclient.threads */ @@ -91,6 +96,7 @@ typedef enum Metric_ { PCP_UNAME_SYSNAME, /* kernel.uname.sysname */ PCP_UNAME_RELEASE, /* kernel.uname.release */ PCP_UNAME_MACHINE, /* kernel.uname.machine */ + PCP_UNAME_DISTRO, /* kernel.uname.distro */ PCP_LOAD_AVERAGE, /* kernel.all.load */ PCP_PID_MAX, /* kernel.all.pid_max */ PCP_UPTIME, /* kernel.all.uptime */ From 2beb3763cdcc81156ab6d27fbaa3d3ddbb6e68cb Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Fri, 5 Mar 2021 16:54:30 +1100 Subject: [PATCH 09/20] Update PCP platform to use the old hostname API call Fixes CI builds which are on an old version of PCP. --- pcp/Platform.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pcp/Platform.c b/pcp/Platform.c index 4fcf3db1e..91b926732 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -654,7 +654,8 @@ void Platform_setZfsCompressedArcValues(Meter* this) { } void Platform_getHostname(char* buffer, size_t size) { - pmGetHostName(pcp->context, buffer, size); + const char* hostname = pmGetContextHostName(pcp->context); + String_safeStrncpy(buffer, hostname, size); } void Platform_getRelease(char** string) { From 7b9588544f7c840d3275d63e2be135599f7c6970 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Wed, 17 Mar 2021 09:54:15 +1100 Subject: [PATCH 10/20] Implement shared memory support on the PCP platform Uses the mem.util.shared metric (Shmem from meminfo). --- pcp/PCPProcessList.c | 7 ++++--- pcp/Platform.c | 20 ++++++++++---------- pcp/Platform.h | 3 ++- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index a823695e5..780862b34 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -1,7 +1,7 @@ /* htop - PCPProcessList.c (C) 2014 Hisham H. Muhammad -(C) 2020 htop dev team +(C) 2020-2021 htop dev team (C) 2020-2021 Red Hat, Inc. All Rights Reserved. Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. @@ -584,12 +584,13 @@ static void PCPProcessList_updateMemoryInfo(ProcessList* super) { super->buffersMem = value.ull; if (Metric_values(PCP_MEM_SRECLAIM, &value, 1, PM_TYPE_U64) != NULL) sreclaimableMem = value.ull; + if (Metric_values(PCP_MEM_SHARED, &value, 1, PM_TYPE_U64) != NULL) + super->sharedMem = value.ull; if (Metric_values(PCP_MEM_CACHED, &value, 1, PM_TYPE_U64) != NULL) { super->cachedMem = value.ull; super->cachedMem += sreclaimableMem; } - unsigned long long int usedDiff; - usedDiff = freeMem + super->cachedMem + super->buffersMem; + const memory_t usedDiff = freeMem + super->cachedMem + sreclaimableMem + super->buffersMem + super->sharedMem; super->usedMem = (super->totalMem >= usedDiff) ? super->totalMem - usedDiff : super->totalMem - freeMem; if (Metric_values(PCP_MEM_AVAILABLE, &value, 1, PM_TYPE_U64) != NULL) diff --git a/pcp/Platform.c b/pcp/Platform.c index 91b926732..70af0a851 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -1,7 +1,7 @@ /* htop - linux/Platform.c (C) 2014 Hisham H. Muhammad -(C) 2020 htop dev team +(C) 2020-2021 htop dev team (C) 2020-2021 Red Hat, Inc. All Rights Reserved. Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. @@ -152,6 +152,7 @@ static const char *Platform_metricNames[] = { [PCP_MEM_AVAILABLE] = "mem.util.available", [PCP_MEM_BUFFERS] = "mem.util.bufmem", [PCP_MEM_CACHED] = "mem.util.cached", + [PCP_MEM_SHARED] = "mem.util.shared", [PCP_MEM_SRECLAIM] = "mem.util.slabReclaimable", [PCP_MEM_SWAPCACHED] = "mem.util.swapCached", [PCP_MEM_SWAPTOTAL] = "mem.util.swapTotal", @@ -587,18 +588,17 @@ double Platform_setCPUValues(Meter* this, int cpu) { void Platform_setMemoryValues(Meter* this) { const ProcessList* pl = this->pl; const PCPProcessList* ppl = (const PCPProcessList*) pl; - long int usedMem = pl->usedMem; - long int buffersMem = pl->buffersMem; - long int cachedMem = pl->cachedMem; - usedMem -= buffersMem + cachedMem; - this->total = pl->totalMem; - this->values[0] = usedMem; - this->values[1] = buffersMem; - this->values[2] = cachedMem; + + this->total = pl->totalMem; + this->values[0] = pl->usedMem; + this->values[1] = pl->buffersMem; + this->values[2] = pl->sharedMem; + this->values[3] = pl->cachedMem; + this->values[4] = pl->availableMem; if (ppl->zfs.enabled != 0) { this->values[0] -= ppl->zfs.size; - this->values[2] += ppl->zfs.size; + this->values[3] += ppl->zfs.size; } } diff --git a/pcp/Platform.h b/pcp/Platform.h index 4d66d8880..1661be77b 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -3,7 +3,7 @@ /* htop - pcp/Platform.h (C) 2014 Hisham H. Muhammad -(C) 2020 htop dev team +(C) 2020-2021 htop dev team (C) 2020-2021 Red Hat, Inc. All Rights Reserved. Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. @@ -125,6 +125,7 @@ typedef enum Metric_ { PCP_MEM_FREE, /* mem.util.free */ PCP_MEM_BUFFERS, /* mem.util.bufmem */ PCP_MEM_CACHED, /* mem.util.cached */ + PCP_MEM_SHARED, /* mem.util.shared */ PCP_MEM_AVAILABLE, /* mem.util.available */ PCP_MEM_SRECLAIM, /* mem.util.slabReclaimable */ PCP_MEM_SWAPCACHED, /* mem.util.swapCached */ From ee909976a5007b933eb59010a7ffea8e14090e9d Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 25 Mar 2021 17:24:14 +1100 Subject: [PATCH 11/20] Implement command line and environment handling for pcp htop. --- .gitignore | 3 ++- Makefile.am | 7 +++-- pcp-htop.c | 26 ++++++++++++++++++ pcp/PCPProcessList.c | 10 +++---- pcp/Platform.c | 64 +++++++++++++++++++++++++++++++++++++++++--- pcp/Platform.h | 17 ++++++++++++ 6 files changed, 116 insertions(+), 11 deletions(-) create mode 100644 pcp-htop.c diff --git a/.gitignore b/.gitignore index 4aebe4c93..fe0279fed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ -# the binary: +# the binaries: htop +pcp-htop # all object files *.o diff --git a/Makefile.am b/Makefile.am index 8ae0e1f9a..52c421570 100644 --- a/Makefile.am +++ b/Makefile.am @@ -343,8 +343,7 @@ pcp_platform_headers = \ zfs/ZfsArcStats.h \ zfs/ZfsCompressedArcMeter.h -if HTOP_PCP -myhtopplatsources = \ +pcp_platform_sources = \ pcp/PCPProcess.c \ pcp/PCPProcessList.c \ pcp/Platform.c \ @@ -353,7 +352,11 @@ myhtopplatsources = \ zfs/ZfsArcMeter.c \ zfs/ZfsCompressedArcMeter.c +if HTOP_PCP +myhtopplatprogram = pcp-htop myhtopplatheaders = $(pcp_platform_headers) +myhtopplatsources = $(pcp_platform_sources) +pcp_htop_SOURCES = $(htop_SOURCES) endif # Unsupported diff --git a/pcp-htop.c b/pcp-htop.c new file mode 100644 index 000000000..eb81cfaa3 --- /dev/null +++ b/pcp-htop.c @@ -0,0 +1,26 @@ +/* +htop - pcp-htop.c +(C) 2004-2011 Hisham H. Muhammad +(C) 2020-2021 htop dev team +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include + +#include "CommandLine.h" +#include "Platform.h" + + +int main(int argc, char** argv) { + const char* name = "pcp-htop"; + pmSetProgname(name); + + /* extract environment variables */ + opts.flags |= PM_OPTFLAG_ENV_ONLY; + pmGetOptions(argc, argv, &opts); + + return CommandLine_run(name, argc, argv); +} diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 780862b34..847765a23 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -31,7 +31,7 @@ static int PCPProcessList_computeCPUcount(void) { static void PCPProcessList_updateCPUcount(PCPProcessList* this) { ProcessList* pl = &(this->super); - int cpus = PCPProcessList_computeCPUcount(); + unsigned int cpus = PCPProcessList_computeCPUcount(); if (cpus == pl->cpuCount) return; @@ -40,7 +40,7 @@ static void PCPProcessList_updateCPUcount(PCPProcessList* this) { free(this->values); this->percpu = xCalloc(cpus, sizeof(pmAtomValue *)); - for (int i = 0; i < cpus; i++) + for (unsigned int i = 0; i < cpus; i++) this->percpu[i] = xCalloc(CPU_METRIC_COUNT, sizeof(pmAtomValue)); this->values = xCalloc(cpus, sizeof(pmAtomValue)); } @@ -78,7 +78,7 @@ void ProcessList_delete(ProcessList* pl) { PCPProcessList* this = (PCPProcessList*) pl; ProcessList_done(pl); free(this->values); - for (int i = 0; i < pl->cpuCount; i++) + for (unsigned int i = 0; i < pl->cpuCount; i++) free(this->percpu[i]); free(this->percpu); free(this->cpu); @@ -716,7 +716,7 @@ static void PCPProcessList_updateHeader(ProcessList* super, const Settings* sett PCPProcessList_updateAllCPUTime(this, PCP_CPU_GUEST, CPU_GUEST_TIME); PCPProcessList_deriveCPUTime(this->cpu); - for (int i = 0; i < super->cpuCount; i++) + for (unsigned int i = 0; i < super->cpuCount; i++) PCPProcessList_backupCPUTime(this->percpu[i]); PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_USER, CPU_USER_TIME); PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_NICE, CPU_NICE_TIME); @@ -727,7 +727,7 @@ static void PCPProcessList_updateHeader(ProcessList* super, const Settings* sett PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_SOFTIRQ, CPU_SOFTIRQ_TIME); PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_STEAL, CPU_STEAL_TIME); PCPProcessList_updatePerCPUTime(this, PCP_PERCPU_GUEST, CPU_GUEST_TIME); - for (int i = 0; i < super->cpuCount; i++) + for (unsigned int i = 0; i < super->cpuCount; i++) PCPProcessList_deriveCPUTime(this->percpu[i]); if (settings->showCPUFrequency) diff --git a/pcp/Platform.c b/pcp/Platform.c index 70af0a851..2a591deec 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -57,7 +57,7 @@ typedef struct Platform_ { pmResult* result; /* sample values result indexed by Metric */ long long btime; /* boottime in seconds since the epoch */ - char *release; /* uname and distro from this context */ + char* release; /* uname and distro from this context */ int pidmax; /* maximum platform process identifier */ int ncpu; /* maximum processor count configured */ } Platform; @@ -403,14 +403,28 @@ static int Platform_addMetric(Metric id, const char *name) { return ++pcp->total; } +/* global state from the environment and command line arguments */ +pmOptions opts; + void Platform_init(void) { - int sts = pmNewContext(PM_CONTEXT_HOST, "local:"); - if (sts < 0) + const char* host = opts.nhosts > 0 ? opts.hosts[0] : "local:"; + + int sts; + sts = pmNewContext(PM_CONTEXT_HOST, host); + /* with no host requested, fallback to PM_CONTEXT_LOCAL shared libraries */ + if (sts < 0 && opts.nhosts == 0) sts = pmNewContext(PM_CONTEXT_LOCAL, NULL); if (sts < 0) { fprintf(stderr, "Cannot setup PCP metric source: %s\n", pmErrStr(sts)); exit(1); } + /* setup timezones and other general startup preparation completion */ + pmGetContextOptions(sts, &opts); + if (opts.errors) { + pmflush(); + exit(1); + } + pcp = xCalloc(1, sizeof(Platform)); pcp->context = sts; pcp->fetch = xCalloc(PCP_METRIC_COUNT, sizeof(pmID)); @@ -795,3 +809,47 @@ void Platform_getBattery(double* level, ACPresence* isOnAC) { *level = NAN; *isOnAC = AC_ERROR; } + +void Platform_longOptionsUsage(ATTR_UNUSED const char* name) { + printf( +" --host=HOSTSPEC metrics source is PMCD at HOSTSPEC [see PCPIntro(1)]\n" +" --hostzone set reporting timezone to local time of metrics source\n" +" --timezone=TZ set reporting timezone\n"); +} + +bool Platform_getLongOption(int opt, ATTR_UNUSED int argc, char** argv) { + /* libpcp export without a header definition */ + extern void __pmAddOptHost(pmOptions *, char *); + + switch (opt) { + case PLATFORM_LONGOPT_HOST: /* --host=HOSTSPEC */ + if (argv[optind][0] == '\0') + return false; + __pmAddOptHost(&opts, optarg); + return true; + + case PLATFORM_LONGOPT_HOSTZONE: /* --hostzone */ + if (opts.timezone) { + pmprintf("%s: at most one of -Z and -z allowed\n", pmGetProgname()); + opts.errors++; + } else { + opts.tzflag = 1; + } + return true; + + case PLATFORM_LONGOPT_TIMEZONE: /* --timezone=TZ */ + if (argv[optind][0] == '\0') + return false; + if (opts.tzflag) { + pmprintf("%s: at most one of -Z and -z allowed\n", pmGetProgname()); + opts.errors++; + } else { + opts.timezone = optarg; + } + return true; + + default: + break; + } + return false; +} diff --git a/pcp/Platform.h b/pcp/Platform.h index 1661be77b..33ea0db70 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -87,6 +87,23 @@ void Platform_getHostname(char* buffer, size_t size); void Platform_getRelease(char** string); +enum { + PLATFORM_LONGOPT_HOST = 128, + PLATFORM_LONGOPT_TIMEZONE, + PLATFORM_LONGOPT_HOSTZONE, +}; + +#define PLATFORM_LONG_OPTIONS \ + {PMLONGOPT_HOST, optional_argument, 0, PLATFORM_LONGOPT_HOST}, \ + {PMLONGOPT_TIMEZONE, optional_argument, 0, PLATFORM_LONGOPT_TIMEZONE}, \ + {PMLONGOPT_HOSTZONE, optional_argument, 0, PLATFORM_LONGOPT_HOSTZONE}, \ + +void Platform_longOptionsUsage(const char* name); + +bool Platform_getLongOption(int opt, int argc, char** argv); + +extern pmOptions opts; + typedef enum Metric_ { PCP_CONTROL_THREADS, /* proc.control.perclient.threads */ From 4971253f3c8f24f8a95657017adabbfbdffd23eb Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 8 Apr 2021 10:13:43 +1000 Subject: [PATCH 12/20] Add time handling interfaces for the pcp platform Related to https://github.com/htop-dev/htop/pull/574 --- Makefile.am | 5 ++--- pcp/Platform.c | 52 ++++++++++++++++++++++++++++++++++++++++---------- pcp/Platform.h | 4 ++++ 3 files changed, 48 insertions(+), 13 deletions(-) diff --git a/Makefile.am b/Makefile.am index 52c421570..ca687d4c5 100644 --- a/Makefile.am +++ b/Makefile.am @@ -44,7 +44,6 @@ myhtopsources = \ Hashtable.c \ Header.c \ HostnameMeter.c \ - htop.c \ IncSet.c \ InfoScreen.c \ ListItem.c \ @@ -356,7 +355,7 @@ if HTOP_PCP myhtopplatprogram = pcp-htop myhtopplatheaders = $(pcp_platform_headers) myhtopplatsources = $(pcp_platform_sources) -pcp_htop_SOURCES = $(htop_SOURCES) +pcp_htop_SOURCES = $(myhtopplatprogram).c $(myhtopheaders) $(myhtopplatheaders) $(myhtopsources) $(myhtopplatsources) endif # Unsupported @@ -384,7 +383,7 @@ endif # ---- bin_PROGRAMS = $(myhtopplatprogram) -htop_SOURCES = $(myhtopheaders) $(myhtopplatheaders) $(myhtopsources) $(myhtopplatsources) +htop_SOURCES = $(myhtopplatprogram).c $(myhtopheaders) $(myhtopplatheaders) $(myhtopsources) $(myhtopplatsources) nodist_htop_SOURCES = config.h target: diff --git a/pcp/Platform.c b/pcp/Platform.c index 2a591deec..e4675d716 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -9,8 +9,6 @@ in the source distribution for its full text. #include "config.h" -#include "Platform.h" - #include #include "BatteryMeter.h" @@ -31,6 +29,7 @@ in the source distribution for its full text. #include "Panel.h" #include "PCPProcess.h" #include "PCPProcessList.h" +#include "Platform.h" #include "ProcessList.h" #include "ProvideCurses.h" #include "Settings.h" @@ -55,6 +54,7 @@ typedef struct Platform_ { pmID* fetch; /* enabled identifiers for sampling */ pmDesc* descs; /* metric desc array indexed by Metric */ pmResult* result; /* sample values result indexed by Metric */ + struct timeval offset; /* time offset used in archive mode only */ long long btime; /* boottime in seconds since the epoch */ char* release; /* uname and distro from this context */ @@ -381,7 +381,7 @@ bool Metric_fetch(struct timeval *timestamp) { return false; } if (timestamp) - *timestamp = pcp->result->timestamp; + *timestamp = pcp->result->timestamp; return true; } @@ -407,13 +407,23 @@ static int Platform_addMetric(Metric id, const char *name) { pmOptions opts; void Platform_init(void) { - const char* host = opts.nhosts > 0 ? opts.hosts[0] : "local:"; + const char* source; + if (opts.context == PM_CONTEXT_ARCHIVE) { + source = opts.archives[0]; + } else if (opts.context == PM_CONTEXT_HOST) { + source = opts.nhosts > 0 ? opts.hosts[0] : "local:"; + } else { + opts.context = PM_CONTEXT_HOST; + source = "local:"; + } int sts; - sts = pmNewContext(PM_CONTEXT_HOST, host); + sts = pmNewContext(opts.context, source); /* with no host requested, fallback to PM_CONTEXT_LOCAL shared libraries */ - if (sts < 0 && opts.nhosts == 0) - sts = pmNewContext(PM_CONTEXT_LOCAL, NULL); + if (sts < 0 && opts.context == PM_CONTEXT_HOST && opts.nhosts == 0) { + opts.context = PM_CONTEXT_LOCAL; + sts = pmNewContext(opts.context, NULL); + } if (sts < 0) { fprintf(stderr, "Cannot setup PCP metric source: %s\n", pmErrStr(sts)); exit(1); @@ -432,6 +442,11 @@ void Platform_init(void) { pcp->names = xCalloc(PCP_METRIC_COUNT, sizeof(char*)); pcp->descs = xCalloc(PCP_METRIC_COUNT, sizeof(pmDesc)); + if (opts.context == PM_CONTEXT_ARCHIVE) { + gettimeofday(&pcp->offset, NULL); + pmtimevalDec(&pcp->offset, &opts.start); + } + for (unsigned int i = 0; i < PCP_METRIC_COUNT; i++) Platform_addMetric(i, Platform_metricNames[i]); @@ -825,7 +840,7 @@ bool Platform_getLongOption(int opt, ATTR_UNUSED int argc, char** argv) { case PLATFORM_LONGOPT_HOST: /* --host=HOSTSPEC */ if (argv[optind][0] == '\0') return false; - __pmAddOptHost(&opts, optarg); + __pmAddOptHost(&opts, optarg); return true; case PLATFORM_LONGOPT_HOSTZONE: /* --hostzone */ @@ -843,9 +858,9 @@ bool Platform_getLongOption(int opt, ATTR_UNUSED int argc, char** argv) { if (opts.tzflag) { pmprintf("%s: at most one of -Z and -z allowed\n", pmGetProgname()); opts.errors++; - } else { + } else { opts.timezone = optarg; - } + } return true; default: @@ -853,3 +868,20 @@ bool Platform_getLongOption(int opt, ATTR_UNUSED int argc, char** argv) { } return false; } + +void Platform_gettime_realtime(struct timeval* tv, uint64_t* msec) { + if (gettimeofday(tv, NULL) == 0) { + /* shift by start offset to stay in lock-step with realtime (archives) */ + if (pcp->offset.tv_sec || pcp->offset.tv_usec) + pmtimevalDec(tv, &pcp->offset); + *msec = ((uint64_t)tv->tv_sec * 1000) + ((uint64_t)tv->tv_usec / 1000); + } else { + memset(tv, 0, sizeof(struct timeval)); + *msec = 0; + } +} + +void Platform_gettime_monotonic(uint64_t* msec) { + struct timeval* tv = &pcp->result->timestamp; + *msec = ((uint64_t)tv->tv_sec * 1000) + ((uint64_t)tv->tv_usec / 1000); +} diff --git a/pcp/Platform.h b/pcp/Platform.h index 33ea0db70..5abe339aa 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -250,4 +250,8 @@ int Metric_instanceOffset(Metric metric, int inst); pmAtomValue *Metric_instance(Metric metric, int inst, int offset, pmAtomValue *atom, int type); +void Platform_gettime_realtime(struct timeval* tv, uint64_t* msec); + +void Platform_gettime_monotonic(uint64_t* msec); + #endif From 5be45a157b354e318d848492f5764b1a38d598eb Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 8 Apr 2021 10:24:34 +1000 Subject: [PATCH 13/20] Drop CI distcheck on pcp build as pcp-htop.c now contains main --- .github/workflows/ci.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea9f4b681..8f198a2f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,8 +125,6 @@ jobs: run: ./configure --enable-pcp --enable-unicode - name: Build run: make -k - - name: Distcheck - run: make distcheck DISTCHECK_CONFIGURE_FLAGS="--enable-pcp --enable-unicode" build-ubuntu-latest-clang-analyzer: runs-on: ubuntu-latest From 6ae96c0f01cc11e2e525145b0bba9d9a7bbb9f00 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 8 Apr 2021 11:04:07 +1000 Subject: [PATCH 14/20] Remove dynamic allocation of PCP metric atomvalues expansion This is no longer used and confuses Coverity scans, drop it. --- pcp/Platform.c | 7 ------- 1 file changed, 7 deletions(-) diff --git a/pcp/Platform.c b/pcp/Platform.c index e4675d716..6519342b1 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -246,13 +246,6 @@ pmAtomValue* Metric_values(Metric metric, pmAtomValue *atom, int count, int type if (!vset || vset->numval <= 0) return NULL; - /* allocate space for atom if needed */ - if (!atom || !count) { - if (!count) - count = vset->numval; - atom = xCalloc(count, sizeof(pmAtomValue)); - } - /* extract requested number of values as requested type */ const pmDesc* desc = &pcp->descs[metric]; for (int i = 0; i < vset->numval; i++) { From 229109e243a588e9e1d751b375ab0a205076dccd Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 8 Apr 2021 13:15:59 +1000 Subject: [PATCH 15/20] Resolve some Coverity scan misfires in PCP platform code --- pcp-htop.c | 2 +- pcp/Platform.c | 68 +++++++++++++++++++++++--------------------------- 2 files changed, 32 insertions(+), 38 deletions(-) diff --git a/pcp-htop.c b/pcp-htop.c index eb81cfaa3..855bb3f90 100644 --- a/pcp-htop.c +++ b/pcp-htop.c @@ -20,7 +20,7 @@ int main(int argc, char** argv) { /* extract environment variables */ opts.flags |= PM_OPTFLAG_ENV_ONLY; - pmGetOptions(argc, argv, &opts); + (void)pmGetOptions(argc, argv, &opts); return CommandLine_run(name, argc, argv); } diff --git a/pcp/Platform.c b/pcp/Platform.c index 6519342b1..4dd60243d 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -422,8 +422,7 @@ void Platform_init(void) { exit(1); } /* setup timezones and other general startup preparation completion */ - pmGetContextOptions(sts, &opts); - if (opts.errors) { + if (pmGetContextOptions(sts, &opts) < 0 || opts.errors) { pmflush(); exit(1); } @@ -688,51 +687,46 @@ void Platform_getRelease(char** string) { } /* first call, extract just-sampled values */ - pmAtomValue value; - - char* name = NULL; - if (Metric_values(PCP_UNAME_SYSNAME, &value, 1, PM_TYPE_STRING)) - name = value.cp; - char* release = NULL; - if (Metric_values(PCP_UNAME_RELEASE, &value, 1, PM_TYPE_STRING)) - release = value.cp; - char* machine = NULL; - if (Metric_values(PCP_UNAME_MACHINE, &value, 1, PM_TYPE_STRING)) - machine = value.cp; - char* distro = NULL; - if (Metric_values(PCP_UNAME_DISTRO, &value, 1, PM_TYPE_STRING)) - distro = value.cp; + pmAtomValue sysname, release, machine, distro; + if (!Metric_values(PCP_UNAME_SYSNAME, &sysname, 1, PM_TYPE_STRING)) + sysname.cp = NULL; + if (!Metric_values(PCP_UNAME_RELEASE, &release, 1, PM_TYPE_STRING)) + release.cp = NULL; + if (!Metric_values(PCP_UNAME_MACHINE, &machine, 1, PM_TYPE_STRING)) + machine.cp = NULL; + if (!Metric_values(PCP_UNAME_DISTRO, &distro, 1, PM_TYPE_STRING)) + distro.cp = NULL; size_t length = 16; /* padded for formatting characters */ - if (name) - length += strlen(name); - if (release) - length += strlen(release); - if (machine) - length += strlen(machine); - if (distro) - length += strlen(distro); + if (sysname.cp) + length += strlen(sysname.cp); + if (release.cp) + length += strlen(release.cp); + if (machine.cp) + length += strlen(machine.cp); + if (distro.cp) + length += strlen(distro.cp); pcp->release = xCalloc(1, length); - if (name) { - strcat(pcp->release, name); + if (sysname.cp) { + strcat(pcp->release, sysname.cp); strcat(pcp->release, " "); } - if (release) { - strcat(pcp->release, release); + if (release.cp) { + strcat(pcp->release, release.cp); strcat(pcp->release, " "); } - if (machine) { + if (machine.cp) { strcat(pcp->release, "["); - strcat(pcp->release, machine); + strcat(pcp->release, machine.cp); strcat(pcp->release, "] "); } - if (distro) { + if (distro.cp) { if (pcp->release[0] != '\0') { strcat(pcp->release, "@ "); - strcat(pcp->release, distro); + strcat(pcp->release, distro.cp); } else { - strcat(pcp->release, distro); + strcat(pcp->release, distro.cp); } strcat(pcp->release, " "); } @@ -740,10 +734,10 @@ void Platform_getRelease(char** string) { if (pcp->release) /* cull trailing space */ pcp->release[strlen(pcp->release)] = '\0'; - free(distro); - free(machine); - free(release); - free(name); + free(distro.cp); + free(machine.cp); + free(release.cp); + free(sysname.cp); } char* Platform_getProcessEnv(pid_t pid) { From 18c0d3f324b2bc64927b4b310af9ae87962c9dd3 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Wed, 14 Apr 2021 11:34:47 +1000 Subject: [PATCH 16/20] Various code tidyups based on review commentary from BenBE --- configure.ac | 2 +- pcp/PCPProcess.h | 3 +- pcp/PCPProcessList.h | 6 +- pcp/Platform.c | 6 +- pcp/Platform.h | 249 ++++++++++++++++++++++--------------------- 5 files changed, 136 insertions(+), 130 deletions(-) diff --git a/configure.ac b/configure.ac index 39567fad1..739b7b2d5 100644 --- a/configure.ac +++ b/configure.ac @@ -101,7 +101,7 @@ esac AC_ARG_ENABLE([pcp], [AS_HELP_STRING([--enable-pcp], - [build a pcp htop binary @<:@default=no@:>@])], + [build a pcp-htop binary @<:@default=no@:>@])], [], [enable_pcp=no]) case "$enable_pcp" in diff --git a/pcp/PCPProcess.h b/pcp/PCPProcess.h index 9819f5c91..d3d1abe0f 100644 --- a/pcp/PCPProcess.h +++ b/pcp/PCPProcess.h @@ -9,7 +9,7 @@ Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "config.h" +#include "config.h" // IWYU pragma: keep #include #include @@ -19,6 +19,7 @@ in the source distribution for its full text. #include "RichString.h" #include "Settings.h" + #define PROCESS_FLAG_LINUX_CGROUP 0x0800 #define PROCESS_FLAG_LINUX_OOM 0x1000 #define PROCESS_FLAG_LINUX_SMAPS 0x2000 diff --git a/pcp/PCPProcessList.h b/pcp/PCPProcessList.h index 70ddfb755..23da66372 100644 --- a/pcp/PCPProcessList.h +++ b/pcp/PCPProcessList.h @@ -7,17 +7,19 @@ Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "config.h" +#include "config.h" // IWYU pragma: keep #include #include #include "Hashtable.h" #include "ProcessList.h" -#include "pcp/Platform.h" #include "UsersTable.h" + +#include "pcp/Platform.h" #include "zfs/ZfsArcStats.h" + typedef enum CPUMetric_ { CPU_TOTAL_TIME, CPU_USER_TIME, diff --git a/pcp/Platform.c b/pcp/Platform.c index 4dd60243d..1caa3e092 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -7,7 +7,9 @@ Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "config.h" +#include "config.h" // IWYU pragma: keep + +#include "Platform.h" #include @@ -29,7 +31,6 @@ in the source distribution for its full text. #include "Panel.h" #include "PCPProcess.h" #include "PCPProcessList.h" -#include "Platform.h" #include "ProcessList.h" #include "ProvideCurses.h" #include "Settings.h" @@ -38,6 +39,7 @@ in the source distribution for its full text. #include "TasksMeter.h" #include "UptimeMeter.h" #include "XUtils.h" + #include "linux/PressureStallMeter.h" #include "linux/ZramMeter.h" #include "linux/ZramStats.h" diff --git a/pcp/Platform.h b/pcp/Platform.h index 5abe339aa..2a1bd3b40 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -13,6 +13,7 @@ in the source distribution for its full text. #include #include +/* use htop config.h values for these macros, not pcp values */ #undef PACKAGE_URL #undef PACKAGE_NAME #undef PACKAGE_STRING @@ -106,130 +107,130 @@ extern pmOptions opts; typedef enum Metric_ { - PCP_CONTROL_THREADS, /* proc.control.perclient.threads */ - - PCP_HINV_NCPU, /* hinv.ncpu */ - PCP_HINV_CPUCLOCK, /* hinv.cpu.clock */ - PCP_UNAME_SYSNAME, /* kernel.uname.sysname */ - PCP_UNAME_RELEASE, /* kernel.uname.release */ - PCP_UNAME_MACHINE, /* kernel.uname.machine */ - PCP_UNAME_DISTRO, /* kernel.uname.distro */ - PCP_LOAD_AVERAGE, /* kernel.all.load */ - PCP_PID_MAX, /* kernel.all.pid_max */ - PCP_UPTIME, /* kernel.all.uptime */ - PCP_BOOTTIME, /* kernel.all.boottime */ - PCP_CPU_USER, /* kernel.all.cpu.user */ - PCP_CPU_NICE, /* kernel.all.cpu.nice */ - PCP_CPU_SYSTEM, /* kernel.all.cpu.sys */ - PCP_CPU_IDLE, /* kernel.all.cpu.idle */ - PCP_CPU_IOWAIT, /* kernel.all.cpu.wait.total */ - PCP_CPU_IRQ, /* kernel.all.cpu.intr */ - PCP_CPU_SOFTIRQ, /* kernel.all.cpu.irq.soft */ - PCP_CPU_STEAL, /* kernel.all.cpu.steal */ - PCP_CPU_GUEST, /* kernel.all.cpu.guest */ - PCP_CPU_GUESTNICE, /* kernel.all.cpu.guest_nice */ - PCP_PERCPU_USER, /* kernel.percpu.cpu.user */ - PCP_PERCPU_NICE, /* kernel.percpu.cpu.nice */ - PCP_PERCPU_SYSTEM, /* kernel.percpu.cpu.sys */ - PCP_PERCPU_IDLE, /* kernel.percpu.cpu.idle */ - PCP_PERCPU_IOWAIT, /* kernel.percpu.cpu.wait.total */ - PCP_PERCPU_IRQ, /* kernel.percpu.cpu.intr */ - PCP_PERCPU_SOFTIRQ, /* kernel.percpu.cpu.irq.soft */ - PCP_PERCPU_STEAL, /* kernel.percpu.cpu.steal */ - PCP_PERCPU_GUEST, /* kernel.percpu.cpu.guest */ - PCP_PERCPU_GUESTNICE, /* kernel.percpu.cpu.guest_nice */ - PCP_MEM_TOTAL, /* mem.physmem */ - PCP_MEM_FREE, /* mem.util.free */ - PCP_MEM_BUFFERS, /* mem.util.bufmem */ - PCP_MEM_CACHED, /* mem.util.cached */ - PCP_MEM_SHARED, /* mem.util.shared */ - PCP_MEM_AVAILABLE, /* mem.util.available */ - PCP_MEM_SRECLAIM, /* mem.util.slabReclaimable */ - PCP_MEM_SWAPCACHED, /* mem.util.swapCached */ - PCP_MEM_SWAPTOTAL, /* mem.util.swapTotal */ - PCP_MEM_SWAPFREE, /* mem.util.swapFree */ - PCP_DISK_READB, /* disk.all.read_bytes */ - PCP_DISK_WRITEB, /* disk.all.write_bytes */ - PCP_DISK_ACTIVE, /* disk.all.avactive */ - PCP_NET_RECVB, /* network.all.in.bytes */ - PCP_NET_SENDB, /* network.all.out.bytes */ - PCP_NET_RECVP, /* network.all.in.packets */ - PCP_NET_SENDP, /* network.all.out.packets */ - PCP_PSI_CPUSOME, /* kernel.all.pressure.cpu.some.avg */ - PCP_PSI_IOSOME, /* kernel.all.pressure.io.some.avg */ - PCP_PSI_IOFULL, /* kernel.all.pressure.io.full.avg */ - PCP_PSI_MEMSOME, /* kernel.all.pressure.memory.some.avg */ - PCP_PSI_MEMFULL, /* kernel.all.pressure.memory.full.avg */ - PCP_ZFS_ARC_ANON_SIZE, /* zfs.arc.anon_size */ - PCP_ZFS_ARC_BONUS_SIZE, /* zfs.arc.bonus_size */ - PCP_ZFS_ARC_COMPRESSED_SIZE, /* zfs.arc.compressed_size */ - PCP_ZFS_ARC_UNCOMPRESSED_SIZE, /* zfs.arc.uncompressed_size */ - PCP_ZFS_ARC_C_MAX, /* zfs.arc.c_max */ - PCP_ZFS_ARC_DBUF_SIZE, /* zfs.arc.dbuf_size */ - PCP_ZFS_ARC_DNODE_SIZE, /* zfs.arc.dnode_size */ - PCP_ZFS_ARC_HDR_SIZE, /* zfs.arc.hdr_size */ - PCP_ZFS_ARC_MFU_SIZE, /* zfs.arc.mfu_size */ - PCP_ZFS_ARC_MRU_SIZE, /* zfs.arc.mru_size */ - PCP_ZFS_ARC_SIZE, /* zfs.arc.size */ - PCP_ZRAM_CAPACITY, /* zram.capacity */ - PCP_ZRAM_ORIGINAL, /* zram.mm_stat.data_size.original */ - PCP_ZRAM_COMPRESSED, /* zram.mm_stat.data_size.compressed */ - - PCP_PROC_PID, /* proc.psinfo.pid */ - PCP_PROC_PPID, /* proc.psinfo.ppid */ - PCP_PROC_TGID, /* proc.psinfo.tgid */ - PCP_PROC_PGRP, /* proc.psinfo.pgrp */ - PCP_PROC_SESSION, /* proc.psinfo.session */ - PCP_PROC_STATE, /* proc.psinfo.sname */ - PCP_PROC_TTY, /* proc.psinfo.tty */ - PCP_PROC_TTYPGRP, /* proc.psinfo.tty_pgrp */ - PCP_PROC_MINFLT, /* proc.psinfo.minflt */ - PCP_PROC_MAJFLT, /* proc.psinfo.maj_flt */ - PCP_PROC_CMINFLT, /* proc.psinfo.cmin_flt */ - PCP_PROC_CMAJFLT, /* proc.psinfo.cmaj_flt */ - PCP_PROC_UTIME, /* proc.psinfo.utime */ - PCP_PROC_STIME, /* proc.psinfo.stime */ - PCP_PROC_CUTIME, /* proc.psinfo.cutime */ - PCP_PROC_CSTIME, /* proc.psinfo.cstime */ - PCP_PROC_PRIORITY, /* proc.psinfo.priority */ - PCP_PROC_NICE, /* proc.psinfo.nice */ - PCP_PROC_THREADS, /* proc.psinfo.threads */ - PCP_PROC_STARTTIME, /* proc.psinfo.start_time */ - PCP_PROC_PROCESSOR, /* proc.psinfo.processor */ - PCP_PROC_CMD, /* proc.psinfo.cmd */ - PCP_PROC_PSARGS, /* proc.psinfo.psargs */ - PCP_PROC_CGROUPS, /* proc.psinfo.cgroups */ - PCP_PROC_OOMSCORE, /* proc.psinfo.oom_score */ - PCP_PROC_VCTXSW, /* proc.psinfo.vctxsw */ - PCP_PROC_NVCTXSW, /* proc.psinfo.nvctxsw */ - PCP_PROC_LABELS, /* proc.psinfo.labels */ - PCP_PROC_ENVIRON, /* proc.psinfo.environ */ - PCP_PROC_TTYNAME, /* proc.psinfo.ttyname */ - - PCP_PROC_ID_UID, /* proc.id.uid */ - PCP_PROC_ID_USER, /* proc.id.uid_nm */ - - PCP_PROC_IO_RCHAR, /* proc.io.rchar */ - PCP_PROC_IO_WCHAR, /* proc.io.wchar */ - PCP_PROC_IO_SYSCR, /* proc.io.syscr */ - PCP_PROC_IO_SYSCW, /* proc.io.syscw */ - PCP_PROC_IO_READB, /* proc.io.read_bytes */ - PCP_PROC_IO_WRITEB, /* proc.io.write_bytes */ - PCP_PROC_IO_CANCELLED, /* proc.io.cancelled_write_bytes */ - - PCP_PROC_MEM_SIZE, /* proc.memory.size */ - PCP_PROC_MEM_RSS, /* proc.memory.rss */ - PCP_PROC_MEM_SHARE, /* proc.memory.share */ - PCP_PROC_MEM_TEXTRS, /* proc.memory.textrss */ - PCP_PROC_MEM_LIBRS, /* proc.memory.librss */ - PCP_PROC_MEM_DATRS, /* proc.memory.datrss */ - PCP_PROC_MEM_DIRTY, /* proc.memory.dirty */ - - PCP_PROC_SMAPS_PSS, /* proc.smaps.pss */ - PCP_PROC_SMAPS_SWAP, /* proc.smaps.swap */ - PCP_PROC_SMAPS_SWAPPSS, /* proc.smaps.swappss */ - - PCP_METRIC_COUNT /* total metric count */ + PCP_CONTROL_THREADS, /* proc.control.perclient.threads */ + + PCP_HINV_NCPU, /* hinv.ncpu */ + PCP_HINV_CPUCLOCK, /* hinv.cpu.clock */ + PCP_UNAME_SYSNAME, /* kernel.uname.sysname */ + PCP_UNAME_RELEASE, /* kernel.uname.release */ + PCP_UNAME_MACHINE, /* kernel.uname.machine */ + PCP_UNAME_DISTRO, /* kernel.uname.distro */ + PCP_LOAD_AVERAGE, /* kernel.all.load */ + PCP_PID_MAX, /* kernel.all.pid_max */ + PCP_UPTIME, /* kernel.all.uptime */ + PCP_BOOTTIME, /* kernel.all.boottime */ + PCP_CPU_USER, /* kernel.all.cpu.user */ + PCP_CPU_NICE, /* kernel.all.cpu.nice */ + PCP_CPU_SYSTEM, /* kernel.all.cpu.sys */ + PCP_CPU_IDLE, /* kernel.all.cpu.idle */ + PCP_CPU_IOWAIT, /* kernel.all.cpu.wait.total */ + PCP_CPU_IRQ, /* kernel.all.cpu.intr */ + PCP_CPU_SOFTIRQ, /* kernel.all.cpu.irq.soft */ + PCP_CPU_STEAL, /* kernel.all.cpu.steal */ + PCP_CPU_GUEST, /* kernel.all.cpu.guest */ + PCP_CPU_GUESTNICE, /* kernel.all.cpu.guest_nice */ + PCP_PERCPU_USER, /* kernel.percpu.cpu.user */ + PCP_PERCPU_NICE, /* kernel.percpu.cpu.nice */ + PCP_PERCPU_SYSTEM, /* kernel.percpu.cpu.sys */ + PCP_PERCPU_IDLE, /* kernel.percpu.cpu.idle */ + PCP_PERCPU_IOWAIT, /* kernel.percpu.cpu.wait.total */ + PCP_PERCPU_IRQ, /* kernel.percpu.cpu.intr */ + PCP_PERCPU_SOFTIRQ, /* kernel.percpu.cpu.irq.soft */ + PCP_PERCPU_STEAL, /* kernel.percpu.cpu.steal */ + PCP_PERCPU_GUEST, /* kernel.percpu.cpu.guest */ + PCP_PERCPU_GUESTNICE, /* kernel.percpu.cpu.guest_nice */ + PCP_MEM_TOTAL, /* mem.physmem */ + PCP_MEM_FREE, /* mem.util.free */ + PCP_MEM_BUFFERS, /* mem.util.bufmem */ + PCP_MEM_CACHED, /* mem.util.cached */ + PCP_MEM_SHARED, /* mem.util.shared */ + PCP_MEM_AVAILABLE, /* mem.util.available */ + PCP_MEM_SRECLAIM, /* mem.util.slabReclaimable */ + PCP_MEM_SWAPCACHED, /* mem.util.swapCached */ + PCP_MEM_SWAPTOTAL, /* mem.util.swapTotal */ + PCP_MEM_SWAPFREE, /* mem.util.swapFree */ + PCP_DISK_READB, /* disk.all.read_bytes */ + PCP_DISK_WRITEB, /* disk.all.write_bytes */ + PCP_DISK_ACTIVE, /* disk.all.avactive */ + PCP_NET_RECVB, /* network.all.in.bytes */ + PCP_NET_SENDB, /* network.all.out.bytes */ + PCP_NET_RECVP, /* network.all.in.packets */ + PCP_NET_SENDP, /* network.all.out.packets */ + PCP_PSI_CPUSOME, /* kernel.all.pressure.cpu.some.avg */ + PCP_PSI_IOSOME, /* kernel.all.pressure.io.some.avg */ + PCP_PSI_IOFULL, /* kernel.all.pressure.io.full.avg */ + PCP_PSI_MEMSOME, /* kernel.all.pressure.memory.some.avg */ + PCP_PSI_MEMFULL, /* kernel.all.pressure.memory.full.avg */ + PCP_ZFS_ARC_ANON_SIZE, /* zfs.arc.anon_size */ + PCP_ZFS_ARC_BONUS_SIZE, /* zfs.arc.bonus_size */ + PCP_ZFS_ARC_COMPRESSED_SIZE, /* zfs.arc.compressed_size */ + PCP_ZFS_ARC_UNCOMPRESSED_SIZE, /* zfs.arc.uncompressed_size */ + PCP_ZFS_ARC_C_MAX, /* zfs.arc.c_max */ + PCP_ZFS_ARC_DBUF_SIZE, /* zfs.arc.dbuf_size */ + PCP_ZFS_ARC_DNODE_SIZE, /* zfs.arc.dnode_size */ + PCP_ZFS_ARC_HDR_SIZE, /* zfs.arc.hdr_size */ + PCP_ZFS_ARC_MFU_SIZE, /* zfs.arc.mfu_size */ + PCP_ZFS_ARC_MRU_SIZE, /* zfs.arc.mru_size */ + PCP_ZFS_ARC_SIZE, /* zfs.arc.size */ + PCP_ZRAM_CAPACITY, /* zram.capacity */ + PCP_ZRAM_ORIGINAL, /* zram.mm_stat.data_size.original */ + PCP_ZRAM_COMPRESSED, /* zram.mm_stat.data_size.compressed */ + + PCP_PROC_PID, /* proc.psinfo.pid */ + PCP_PROC_PPID, /* proc.psinfo.ppid */ + PCP_PROC_TGID, /* proc.psinfo.tgid */ + PCP_PROC_PGRP, /* proc.psinfo.pgrp */ + PCP_PROC_SESSION, /* proc.psinfo.session */ + PCP_PROC_STATE, /* proc.psinfo.sname */ + PCP_PROC_TTY, /* proc.psinfo.tty */ + PCP_PROC_TTYPGRP, /* proc.psinfo.tty_pgrp */ + PCP_PROC_MINFLT, /* proc.psinfo.minflt */ + PCP_PROC_MAJFLT, /* proc.psinfo.maj_flt */ + PCP_PROC_CMINFLT, /* proc.psinfo.cmin_flt */ + PCP_PROC_CMAJFLT, /* proc.psinfo.cmaj_flt */ + PCP_PROC_UTIME, /* proc.psinfo.utime */ + PCP_PROC_STIME, /* proc.psinfo.stime */ + PCP_PROC_CUTIME, /* proc.psinfo.cutime */ + PCP_PROC_CSTIME, /* proc.psinfo.cstime */ + PCP_PROC_PRIORITY, /* proc.psinfo.priority */ + PCP_PROC_NICE, /* proc.psinfo.nice */ + PCP_PROC_THREADS, /* proc.psinfo.threads */ + PCP_PROC_STARTTIME, /* proc.psinfo.start_time */ + PCP_PROC_PROCESSOR, /* proc.psinfo.processor */ + PCP_PROC_CMD, /* proc.psinfo.cmd */ + PCP_PROC_PSARGS, /* proc.psinfo.psargs */ + PCP_PROC_CGROUPS, /* proc.psinfo.cgroups */ + PCP_PROC_OOMSCORE, /* proc.psinfo.oom_score */ + PCP_PROC_VCTXSW, /* proc.psinfo.vctxsw */ + PCP_PROC_NVCTXSW, /* proc.psinfo.nvctxsw */ + PCP_PROC_LABELS, /* proc.psinfo.labels */ + PCP_PROC_ENVIRON, /* proc.psinfo.environ */ + PCP_PROC_TTYNAME, /* proc.psinfo.ttyname */ + + PCP_PROC_ID_UID, /* proc.id.uid */ + PCP_PROC_ID_USER, /* proc.id.uid_nm */ + + PCP_PROC_IO_RCHAR, /* proc.io.rchar */ + PCP_PROC_IO_WCHAR, /* proc.io.wchar */ + PCP_PROC_IO_SYSCR, /* proc.io.syscr */ + PCP_PROC_IO_SYSCW, /* proc.io.syscw */ + PCP_PROC_IO_READB, /* proc.io.read_bytes */ + PCP_PROC_IO_WRITEB, /* proc.io.write_bytes */ + PCP_PROC_IO_CANCELLED, /* proc.io.cancelled_write_bytes */ + + PCP_PROC_MEM_SIZE, /* proc.memory.size */ + PCP_PROC_MEM_RSS, /* proc.memory.rss */ + PCP_PROC_MEM_SHARE, /* proc.memory.share */ + PCP_PROC_MEM_TEXTRS, /* proc.memory.textrss */ + PCP_PROC_MEM_LIBRS, /* proc.memory.librss */ + PCP_PROC_MEM_DATRS, /* proc.memory.datrss */ + PCP_PROC_MEM_DIRTY, /* proc.memory.dirty */ + + PCP_PROC_SMAPS_PSS, /* proc.smaps.pss */ + PCP_PROC_SMAPS_SWAP, /* proc.smaps.swap */ + PCP_PROC_SMAPS_SWAPPSS, /* proc.smaps.swappss */ + + PCP_METRIC_COUNT /* total metric count */ } Metric; void Metric_enable(Metric metric, bool enable); From b8ddc41b6b339573476ef7a6f5f98eaed19b6915 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 15 Apr 2021 09:03:12 +1000 Subject: [PATCH 17/20] Rework TTY column for the PCP platform --- pcp/PCPProcess.c | 10 +--------- pcp/PCPProcess.h | 1 - pcp/PCPProcessList.c | 6 +++--- 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/pcp/PCPProcess.c b/pcp/PCPProcess.c index 7e8f59aef..4a5cdb326 100644 --- a/pcp/PCPProcess.c +++ b/pcp/PCPProcess.c @@ -32,7 +32,7 @@ const ProcessFieldData Process_fields[] = { [PPID] = { .name = "PPID", .title = "PPID", .description = "Parent process ID", .flags = 0, }, [PGRP] = { .name = "PGRP", .title = "PGRP", .description = "Process group ID", .flags = 0, }, [SESSION] = { .name = "SESSION", .title = "SID", .description = "Process's session ID", .flags = 0, }, - [TTY_NR] = { .name = "TTY_NR", .title = "TTY ", .description = "Controlling terminal", .flags = 0, }, + [TTY] = { .name = "TTY", .title = "TTY ", .description = "Controlling terminal", .flags = 0, }, [TPGID] = { .name = "TPGID", .title = "TPGID", .description = "Process ID of the fg process group of the controlling terminal", .flags = 0, }, [MINFLT] = { .name = "MINFLT", .title = " MINFLT ", .description = "Number of minor faults which have not required loading a memory page from disk", .flags = 0, .defaultSortDesc = true, }, [CMINFLT] = { .name = "CMINFLT", .title = " CMINFLT ", .description = "Children processes' minor faults", .flags = 0, .defaultSortDesc = true, }, @@ -107,7 +107,6 @@ void Process_delete(Object* cast) { Process_done((Process*)cast); free(this->cgroup); free(this->secattr); - free(this->ttyDevice); free(this->procComm); free(this->mergedCommand.str); free(this); @@ -332,13 +331,6 @@ static void PCPProcess_writeField(const Process* this, RichString* str, ProcessF int attr = CRT_colors[DEFAULT_COLOR]; int n = sizeof(buffer) - 1; switch ((int)field) { - case TTY_NR: - if (pp->ttyDevice) { - xSnprintf(buffer, n, "%-8s", pp->ttyDevice + 5 /* skip "/dev/" */); - break; - } - Process_writeField(this, str, field); - break; case CMINFLT: Process_colorNumber(str, pp->cminflt, coloring); return; case CMAJFLT: Process_colorNumber(str, pp->cmajflt, coloring); return; case M_DRS: Process_humanNumber(str, pp->m_drs, coloring); return; diff --git a/pcp/PCPProcess.h b/pcp/PCPProcess.h index d3d1abe0f..946d38315 100644 --- a/pcp/PCPProcess.h +++ b/pcp/PCPProcess.h @@ -98,7 +98,6 @@ typedef struct PCPProcess_ { double io_rate_write_bps; char* cgroup; unsigned int oom; - char* ttyDevice; unsigned long long int delay_read_time; unsigned long long cpu_delay_total; unsigned long long blkio_delay_total; diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 847765a23..3755c9bc2 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -352,8 +352,8 @@ static char* setString(Metric metric, int pid, int offset, char* string) { return string; } -static void PCPProcessList_updateTTY(PCPProcess* process, int pid, int offset) { - process->ttyDevice = setString(PCP_PROC_TTYNAME, pid, offset, process->ttyDevice); +static void PCPProcessList_updateTTY(Process* process, int pid, int offset) { + process->tty_name = setString(PCP_PROC_TTYNAME, pid, offset, process->tty_name); } static void PCPProcessList_readCGroups(PCPProcess* process, int pid, int offset) { @@ -495,7 +495,7 @@ static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, PCPProcessList_updateInfo(proc, pid, offset, command, sizeof(command)); proc->starttime_ctime += Platform_getBootTime(); if (tty_nr != proc->tty_nr) - PCPProcessList_updateTTY(pp, pid, offset); + PCPProcessList_updateTTY(proc, pid, offset); float percent_cpu = (pp->utime + pp->stime - lasttimes) / period * 100.0; proc->percent_cpu = isnan(percent_cpu) ? From 7538a52041bc48f144f69fcc88455a36a5fedf13 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Thu, 27 May 2021 16:05:48 +1000 Subject: [PATCH 18/20] Update the PCP platform to use common Process fields and code Remove code now that we have common platform-independent command line wrangling (thanks BenBE!). Add PCP platform support for a handful of other recently arriving odds and ends - ELAPSED time, CWD, and so on. --- pcp/PCPProcess.c | 304 ++++--------------------------------------- pcp/PCPProcess.h | 43 ------ pcp/PCPProcessList.c | 81 ++++-------- pcp/Platform.c | 2 + pcp/Platform.h | 2 + pcp/ProcessField.h | 3 +- 6 files changed, 59 insertions(+), 376 deletions(-) diff --git a/pcp/PCPProcess.c b/pcp/PCPProcess.c index 4a5cdb326..3b66a3013 100644 --- a/pcp/PCPProcess.c +++ b/pcp/PCPProcess.c @@ -21,9 +21,6 @@ in the source distribution for its full text. #include "ProvideCurses.h" #include "XUtils.h" -/* Used to identify kernel threads in Comm column */ -static const char *const kthreadID = "KTHREAD"; - const ProcessFieldData Process_fields[] = { [0] = { .name = "", .title = NULL, .description = NULL, .flags = 0, }, [PID] = { .name = "PID", .title = "PID", .description = "Process/thread ID", .flags = 0, .pidColumn = true, }, @@ -45,6 +42,7 @@ const ProcessFieldData Process_fields[] = { [PRIORITY] = { .name = "PRIORITY", .title = "PRI ", .description = "Kernel's internal priority for the process", .flags = 0, }, [NICE] = { .name = "NICE", .title = " NI ", .description = "Nice value (the higher the value, the more it lets other processes take priority)", .flags = 0, }, [STARTTIME] = { .name = "STARTTIME", .title = "START ", .description = "Time the process was started", .flags = 0, }, + [ELAPSED] = { .name = "ELAPSED", .title = "ELAPSED ", .description = "Time since the process was started", .flags = 0, }, [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "If of the CPU the process last executed on", .flags = 0, }, [M_VIRT] = { .name = "M_VIRT", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, .defaultSortDesc = true, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, .defaultSortDesc = true, }, @@ -81,20 +79,11 @@ const ProcessFieldData Process_fields[] = { [M_PSSWP] = { .name = "M_PSSWP", .title = " PSSWP ", .description = "shows proportional swap share of this mapping, Unlike \"Swap\", this does not take into account swapped out page of underlying shmem objects.", .flags = PROCESS_FLAG_LINUX_SMAPS, .defaultSortDesc = true, }, [CTXT] = { .name = "CTXT", .title = " CTXT ", .description = "Context switches (incremental sum of voluntary_ctxt_switches and nonvoluntary_ctxt_switches)", .flags = PROCESS_FLAG_LINUX_CTXT, .defaultSortDesc = true, }, [SECATTR] = { .name = "SECATTR", .title = " Security Attribute ", .description = "Security attribute of the process (e.g. SELinux or AppArmor)", .flags = PROCESS_FLAG_LINUX_SECATTR, }, - [PROC_COMM] = { .name = "COMM", .title = "COMM ", .description = "comm string of the process from /proc/[pid]/comm", .flags = 0, }, + [PROC_COMM] = { .name = "COMM", .title = "COMM ", .description = "comm string of the process", .flags = 0, }, + [PROC_EXE] = { .name = "EXE", .title = "EXE ", .description = "Basename of exe of the process", .flags = 0, }, + [CWD] = { .name = "CWD", .title = "CWD ", .description = "The current working directory of the process", .flags = PROCESS_FLAG_CWD, }, }; -/* This function returns the string displayed in Command column, so that sorting - * happens on what is displayed - whether comm, full path, basename, etc.. So - * this follows PCPProcess_writeField(COMM) and PCPProcess_writeCommand */ -static const char* PCPProcess_getCommandStr(const Process *this) { - const PCPProcess *pp = (const PCPProcess *)this; - if ((Process_isUserlandThread(this) && this->settings->showThreadNames) || !pp->mergedCommand.str) { - return this->comm; - } - return pp->mergedCommand.str; -} - Process* PCPProcess_new(const Settings* settings) { PCPProcess* this = xCalloc(1, sizeof(PCPProcess)); Object_setClass(this, Class(PCPProcess)); @@ -107,8 +96,6 @@ void Process_delete(Object* cast) { Process_done((Process*)cast); free(this->cgroup); free(this->secattr); - free(this->procComm); - free(this->mergedCommand.str); free(this); } @@ -120,210 +107,6 @@ static void PCPProcess_printDelay(float delay_percent, char* buffer, int n) { } } -/* -TASK_COMM_LEN is defined to be 16 for /proc/[pid]/comm in man proc(5), but is -not available in an userspace header - so define it. Note: when colorizing a -basename with the comm prefix, the entire basename (not just the comm prefix) -is colorized for better readability, and it is implicit that only up to -(TASK_COMM_LEN - 1) could be comm. -*/ -#define TASK_COMM_LEN 16 - -/* -This function makes the merged Command string. It also stores the offsets of -the basename, comm w.r.t the merged Command string - these offsets will be used -by PCPProcess_writeCommand() for coloring. The merged Command string is also -returned by PCPProcess_getCommandStr() for searching, sorting and filtering. -*/ -void PCPProcess_makeCommandStr(Process* this) { - PCPProcess *pp = (PCPProcess *)this; - PCPProcessMergedCommand *mc = &pp->mergedCommand; - - bool showMergedCommand = this->settings->showMergedCommand; - bool showProgramPath = this->settings->showProgramPath; - bool searchCommInCmdline = this->settings->findCommInCmdline; - - /* pp->mergedCommand.str needs updating only if its state or contents - * changed. Its content is based on the fields cmdline and comm. */ - if ( - mc->prevMergeSet == showMergedCommand && - mc->prevPathSet == showProgramPath && - mc->prevCommSet == searchCommInCmdline && - !mc->cmdlineChanged && - !mc->commChanged - ) { - return; - } - - /* The field separtor "│" has been chosen such that it will not match any - * valid string used for searching or filtering */ - const char *SEPARATOR = CRT_treeStr[TREE_STR_VERT]; - const int SEPARATOR_LEN = strlen(SEPARATOR); - - /* Check for any changed fields since we last built this string */ - if (mc->cmdlineChanged || mc->commChanged) { - free(mc->str); - /* Accommodate the column text, two field separators and terminating NUL */ - mc->str = xCalloc(1, mc->maxLen + 2*SEPARATOR_LEN + 1); - } - - /* Preserve the settings used in this run */ - mc->prevMergeSet = showMergedCommand; - mc->prevPathSet = showProgramPath; - mc->prevCommSet = searchCommInCmdline; - - /* Mark everything as unchanged */ - mc->cmdlineChanged = false; - mc->commChanged = false; - - /* Clear any separators */ - mc->sep1 = 0; - mc->sep2 = 0; - /* Clear any highlighting locations */ - mc->baseStart = 0; - mc->baseEnd = 0; - mc->commStart = 0; - mc->commEnd = 0; - - const char *cmdline = this->comm; - const char *procComm = pp->procComm; - - char *strStart = mc->str; - char *str = strStart; - - int cmdlineBasenameOffset = pp->procCmdlineBasenameOffset; - int cmdlineBasenameEnd = pp->procCmdlineBasenameEnd; - - if (!cmdline) { - cmdlineBasenameOffset = 0; - cmdlineBasenameEnd = 0; - cmdline = "(zombie)"; - } - - assert(cmdlineBasenameOffset >= 0); - assert(cmdlineBasenameOffset <= (int)strlen(cmdline)); - - if (showMergedCommand && procComm && strlen(procComm)) { /* Prefix column with comm */ - if (strncmp(cmdline + cmdlineBasenameOffset, procComm, MINIMUM(TASK_COMM_LEN - 1, strlen(procComm))) != 0) { - mc->commStart = 0; - mc->commEnd = strlen(procComm); - - str = stpcpy(str, procComm); - - mc->sep1 = str - strStart; - str = stpcpy(str, SEPARATOR); - } - } - - if (showProgramPath) { - (void) stpcpy(str, cmdline); - mc->baseStart = cmdlineBasenameOffset; - mc->baseEnd = cmdlineBasenameEnd; - } else { - (void) stpcpy(str, cmdline + cmdlineBasenameOffset); - mc->baseStart = 0; - mc->baseEnd = cmdlineBasenameEnd - cmdlineBasenameOffset; - } - - if (mc->sep1) { - mc->baseStart += str - strStart - SEPARATOR_LEN + 1; - mc->baseEnd += str - strStart - SEPARATOR_LEN + 1; - } -} - -static void PCPProcess_writeCommand(const Process* this, int attr, int baseAttr, RichString* str) { - const PCPProcess *pp = (const PCPProcess *)this; - const PCPProcessMergedCommand *mc = &pp->mergedCommand; - - int strStart = RichString_size(str); - - int baseStart = strStart + pp->mergedCommand.baseStart; - int baseEnd = strStart + pp->mergedCommand.baseEnd; - int commStart = strStart + pp->mergedCommand.commStart; - int commEnd = strStart + pp->mergedCommand.commEnd; - - int commAttr = CRT_colors[Process_isUserlandThread(this) ? PROCESS_THREAD_COMM : PROCESS_COMM]; - - bool highlightBaseName = this->settings->highlightBaseName; - - RichString_appendWide(str, attr, pp->mergedCommand.str); - - if (pp->mergedCommand.commEnd) { - if (!pp->mergedCommand.separateComm && commStart == baseStart && highlightBaseName) { - /* If it was matched with binaries basename, make it bold if needed */ - if (commEnd > baseEnd) { - RichString_setAttrn(str, A_BOLD | baseAttr, baseStart, baseEnd - baseStart); - RichString_setAttrn(str, A_BOLD | commAttr, baseEnd, commEnd - baseEnd); - } else if (commEnd < baseEnd) { - RichString_setAttrn(str, A_BOLD | commAttr, commStart, commEnd - commStart); - RichString_setAttrn(str, A_BOLD | baseAttr, commEnd, baseEnd - commEnd); - } else { - // Actually should be highlighted commAttr, but marked baseAttr to reduce visual noise - RichString_setAttrn(str, A_BOLD | baseAttr, commStart, commEnd - commStart); - } - - baseStart = baseEnd; - } else { - RichString_setAttrn(str, commAttr, commStart, commEnd - commStart); - } - } - - if (baseStart < baseEnd && highlightBaseName) { - RichString_setAttrn(str, baseAttr, baseStart, baseEnd - baseStart); - } - - if (mc->sep1) - RichString_setAttrn(str, CRT_colors[FAILED_READ], strStart + mc->sep1, 1); - if (mc->sep2) - RichString_setAttrn(str, CRT_colors[FAILED_READ], strStart + mc->sep2, 1); -} - -static void PCPProcess_writeCommandField(const Process *this, RichString *str, char *buffer, int n, int attr) { - /* This code is from Process_writeField for COMM, but we invoke - * PCPProcess_writeCommand to display the full binary path - * (or its basename)│/proc/pid/comm│/proc/pid/cmdline */ - int baseattr = CRT_colors[PROCESS_BASENAME]; - if (this->settings->highlightThreads && Process_isThread(this)) { - attr = CRT_colors[PROCESS_THREAD]; - baseattr = CRT_colors[PROCESS_THREAD_BASENAME]; - } - if (!this->settings->treeView || this->indent == 0) { - PCPProcess_writeCommand(this, attr, baseattr, str); - } else { - char* buf = buffer; - int maxIndent = 0; - bool lastItem = (this->indent < 0); - int indent = (this->indent < 0 ? -this->indent : this->indent); - int vertLen = strlen(CRT_treeStr[TREE_STR_VERT]); - - for (int i = 0; i < 32; i++) { - if (indent & (1U << i)) { - maxIndent = i+1; - } - } - for (int i = 0; i < maxIndent - 1; i++) { - if (indent & (1 << i)) { - if (buf - buffer + (vertLen + 3) > n) { - break; - } - buf = stpcpy(buf, CRT_treeStr[TREE_STR_VERT]); - buf = stpcpy(buf, " "); - } else { - if (buf - buffer + 4 > n) { - break; - } - buf = stpcpy(buf, " "); - } - } - - n -= (buf - buffer); - const char* draw = CRT_treeStr[lastItem ? TREE_STR_BEND : TREE_STR_RTEE]; - xSnprintf(buf, n, "%s%s ", draw, this->showChildren ? CRT_treeStr[TREE_STR_SHUT] : CRT_treeStr[TREE_STR_OPEN] ); - RichString_appendWide(str, CRT_colors[PROCESS_TREE], buffer); - PCPProcess_writeCommand(this, attr, baseattr, str); - } -} - static void PCPProcess_writeField(const Process* this, RichString* str, ProcessField field) { const PCPProcess* pp = (const PCPProcess*) this; bool coloring = this->settings->highlightMegabytes; @@ -331,29 +114,29 @@ static void PCPProcess_writeField(const Process* this, RichString* str, ProcessF int attr = CRT_colors[DEFAULT_COLOR]; int n = sizeof(buffer) - 1; switch ((int)field) { - case CMINFLT: Process_colorNumber(str, pp->cminflt, coloring); return; - case CMAJFLT: Process_colorNumber(str, pp->cmajflt, coloring); return; - case M_DRS: Process_humanNumber(str, pp->m_drs, coloring); return; - case M_DT: Process_humanNumber(str, pp->m_dt, coloring); return; - case M_LRS: Process_humanNumber(str, pp->m_lrs, coloring); return; - case M_TRS: Process_humanNumber(str, pp->m_trs, coloring); return; - case M_SHARE: Process_humanNumber(str, pp->m_share, coloring); return; - case M_PSS: Process_humanNumber(str, pp->m_pss, coloring); return; - case M_SWAP: Process_humanNumber(str, pp->m_swap, coloring); return; - case M_PSSWP: Process_humanNumber(str, pp->m_psswp, coloring); return; - case UTIME: Process_printTime(str, pp->utime); return; - case STIME: Process_printTime(str, pp->stime); return; - case CUTIME: Process_printTime(str, pp->cutime); return; - case CSTIME: Process_printTime(str, pp->cstime); return; - case RCHAR: Process_humanNumber(str, pp->io_rchar, coloring); return; - case WCHAR: Process_humanNumber(str, pp->io_wchar, coloring); return; - case SYSCR: Process_colorNumber(str, pp->io_syscr, coloring); return; - case SYSCW: Process_colorNumber(str, pp->io_syscw, coloring); return; - case RBYTES: Process_humanNumber(str, pp->io_read_bytes, coloring); return; - case WBYTES: Process_humanNumber(str, pp->io_write_bytes, coloring); return; - case CNCLWB: Process_humanNumber(str, pp->io_cancelled_write_bytes, coloring); return; - case IO_READ_RATE: Process_outputRate(str, buffer, n, pp->io_rate_read_bps, coloring); return; - case IO_WRITE_RATE: Process_outputRate(str, buffer, n, pp->io_rate_write_bps, coloring); return; + case CMINFLT: Process_printCount(str, pp->cminflt, coloring); return; + case CMAJFLT: Process_printCount(str, pp->cmajflt, coloring); return; + case M_DRS: Process_printBytes(str, pp->m_drs, coloring); return; + case M_DT: Process_printBytes(str, pp->m_dt, coloring); return; + case M_LRS: Process_printBytes(str, pp->m_lrs, coloring); return; + case M_TRS: Process_printBytes(str, pp->m_trs, coloring); return; + case M_SHARE: Process_printBytes(str, pp->m_share, coloring); return; + case M_PSS: Process_printKBytes(str, pp->m_pss, coloring); return; + case M_SWAP: Process_printKBytes(str, pp->m_swap, coloring); return; + case M_PSSWP: Process_printKBytes(str, pp->m_psswp, coloring); return; + case UTIME: Process_printTime(str, pp->utime, coloring); return; + case STIME: Process_printTime(str, pp->stime, coloring); return; + case CUTIME: Process_printTime(str, pp->cutime, coloring); return; + case CSTIME: Process_printTime(str, pp->cstime, coloring); return; + case RCHAR: Process_printBytes(str, pp->io_rchar, coloring); return; + case WCHAR: Process_printBytes(str, pp->io_wchar, coloring); return; + case SYSCR: Process_printCount(str, pp->io_syscr, coloring); return; + case SYSCW: Process_printCount(str, pp->io_syscw, coloring); return; + case RBYTES: Process_printBytes(str, pp->io_read_bytes, coloring); return; + case WBYTES: Process_printBytes(str, pp->io_write_bytes, coloring); return; + case CNCLWB: Process_printBytes(str, pp->io_cancelled_write_bytes, coloring); return; + case IO_READ_RATE: Process_printRate(str, pp->io_rate_read_bps, coloring); return; + case IO_WRITE_RATE: Process_printRate(str, pp->io_rate_write_bps, coloring); return; case IO_RATE: { double totalRate = NAN; if (!isnan(pp->io_rate_read_bps) && !isnan(pp->io_rate_write_bps)) @@ -364,7 +147,7 @@ static void PCPProcess_writeField(const Process* this, RichString* str, ProcessF totalRate = pp->io_rate_write_bps; else totalRate = NAN; - Process_outputRate(str, buffer, n, totalRate, coloring); return; + Process_printRate(str, totalRate, coloring); return; } case CGROUP: xSnprintf(buffer, n, "%-10s ", pp->cgroup ? pp->cgroup : ""); break; case OOM: xSnprintf(buffer, n, "%4u ", pp->oom); break; @@ -384,27 +167,6 @@ static void PCPProcess_writeField(const Process* this, RichString* str, ProcessF xSnprintf(buffer, n, "%5lu ", pp->ctxt_diff); break; case SECATTR: snprintf(buffer, n, "%-30s ", pp->secattr ? pp->secattr : "?"); break; - case COMM: { - if ((Process_isUserlandThread(this) && this->settings->showThreadNames) || !pp->mergedCommand.str) { - Process_writeField(this, str, field); - } else { - PCPProcess_writeCommandField(this, str, buffer, n, attr); - } - return; - } - case PROC_COMM: { - const char* procComm; - if (pp->procComm) { - attr = CRT_colors[Process_isUserlandThread(this) ? PROCESS_THREAD_COMM : PROCESS_COMM]; - procComm = pp->procComm; - } else { - attr = CRT_colors[PROCESS_SHADOW]; - procComm = Process_isKernelThread(this) ? kthreadID : "N/A"; - } - /* 15 being (TASK_COMM_LEN - 1) */ - Process_printLeftAlignedField(str, attr, procComm, 15); - return; - } default: Process_writeField(this, str, field); return; @@ -482,20 +244,11 @@ static int PCPProcess_compareByKey(const Process* v1, const Process* v2, Process return SPACESHIP_NUMBER(p1->ctxt_diff, p1->ctxt_diff); case SECATTR: return SPACESHIP_NULLSTR(p1->secattr, p2->secattr); - case PROC_COMM: { - const char *comm1 = p1->procComm ? p1->procComm : (Process_isKernelThread(v1) ? kthreadID : ""); - const char *comm2 = p2->procComm ? p2->procComm : (Process_isKernelThread(v2) ? kthreadID : ""); - return strcmp(comm1, comm2); - } default: return Process_compareByKey_Base(v1, v2, key); } } -bool Process_isThread(const Process* this) { - return (Process_isUserlandThread(this) || Process_isKernelThread(this)); -} - const ProcessClass PCPProcess_class = { .super = { .extends = Class(Process), @@ -504,6 +257,5 @@ const ProcessClass PCPProcess_class = { .compare = Process_compare }, .writeField = PCPProcess_writeField, - .getCommandStr = PCPProcess_getCommandStr, .compareByKey = PCPProcess_compareByKey }; diff --git a/pcp/PCPProcess.h b/pcp/PCPProcess.h index 946d38315..25707f2b0 100644 --- a/pcp/PCPProcess.h +++ b/pcp/PCPProcess.h @@ -26,35 +26,8 @@ in the source distribution for its full text. #define PROCESS_FLAG_LINUX_CTXT 0x4000 #define PROCESS_FLAG_LINUX_SECATTR 0x8000 -/* PCPProcessMergedCommand is populated by PCPProcess_makeCommandStr: It - * contains the merged Command string, and the information needed by - * PCPProcess_writeCommand to color the string. str will be NULL for kernel - * threads and zombies */ -typedef struct PCPProcessMergedCommand_ { - char *str; /* merged Command string */ - int maxLen; /* maximum expected length of Command string */ - int baseStart; /* basename's start offset */ - int baseEnd; /* basename's end offset */ - int commStart; /* comm's start offset */ - int commEnd; /* comm's end offset */ - int sep1; /* first field separator, used if non-zero */ - int sep2; /* second field separator, used if non-zero */ - bool separateComm; /* whether comm is a separate field */ - bool cmdlineChanged; /* whether cmdline changed */ - bool commChanged; /* whether comm changed */ - bool prevMergeSet; /* whether showMergedCommand was set */ - bool prevPathSet; /* whether showProgramPath was set */ - bool prevCommSet; /* whether findCommInCmdline was set */ - bool prevCmdlineSet; /* whether findCommInCmdline was set */ -} PCPProcessMergedCommand; - typedef struct PCPProcess_ { Process super; - char *procComm; - int procCmdlineBasenameOffset; - int procCmdlineBasenameEnd; - PCPProcessMergedCommand mergedCommand; - bool isKernelThread; unsigned long int cminflt; unsigned long int cmajflt; unsigned long long int utime; @@ -111,18 +84,6 @@ typedef struct PCPProcess_ { unsigned long long int last_mlrs_calctime; } PCPProcess; -static inline void Process_setKernelThread(Process* this, bool truth) { - ((PCPProcess*)this)->isKernelThread = truth; -} - -static inline bool Process_isKernelThread(const Process* this) { - return ((const PCPProcess*)this)->isKernelThread; -} - -static inline bool Process_isUserlandThread(const Process* this) { - return this->pid != this->tgid; -} - extern const ProcessFieldData Process_fields[LAST_PROCESSFIELD]; extern const ProcessClass PCPProcess_class; @@ -131,10 +92,6 @@ Process* PCPProcess_new(const Settings* settings); void Process_delete(Object* cast); -/* This function constructs the string that is displayed by - * PCPProcess_writeCommand and also returned by PCPProcess_getCommandStr */ -void PCPProcess_makeCommandStr(Process *this); - bool Process_isThread(const Process* this); #endif diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 3755c9bc2..0985ad2c3 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -364,6 +364,10 @@ static void PCPProcessList_readSecattrData(PCPProcess* process, int pid, int off process->secattr = setString(PCP_PROC_LABELS, pid, offset, process->secattr); } +static void PCPProcessList_readCwd(PCPProcess* process, int pid, int offset) { + process->super.procCwd = setString(PCP_PROC_CWD, pid, offset, process->super.procCwd); +} + static void PCPProcessList_updateUsername(Process* process, int pid, int offset, UsersTable* users) { unsigned int uid = 0; pmAtomValue value; @@ -377,61 +381,42 @@ static void PCPProcessList_updateCmdline(Process* process, int pid, int offset, pmAtomValue value; if (!Metric_instance(PCP_PROC_PSARGS, pid, offset, &value, PM_TYPE_STRING)) { if (process->state != 'Z') - Process_setKernelThread(process, true); - else - process->basenameOffset = 0; + process->isKernelThread = true; + Process_updateCmdline(process, NULL, 0, 0); return; } char *command = value.cp; int length = strlen(command); if (command[0] != '(') { - Process_setKernelThread(process, false); + process->isKernelThread = false; } else { ++command; --length; if (command[length-1] == ')') command[length-1] = '\0'; - Process_setKernelThread(process, true); + process->isKernelThread = true; } - int tokenEnd = 0; int tokenStart = 0; - int lastChar = 0; for (int i = 0; i < length; i++) { /* htop considers the next character after the last / that is before * basenameOffset, as the start of the basename in cmdline - see * Process_writeCommand */ if (command[i] == '/') tokenStart = i + 1; - lastChar = i; - } - tokenEnd = length; - - PCPProcess *pp = (PCPProcess *)process; - pp->mergedCommand.maxLen = lastChar + 1; /* accommodate cmdline */ - if (!process->comm || !String_eq(command, process->comm)) { - process->basenameOffset = tokenEnd; - free_and_xStrdup(&process->comm, command); - pp->procCmdlineBasenameOffset = tokenStart; - pp->procCmdlineBasenameEnd = tokenEnd; - pp->mergedCommand.cmdlineChanged = true; - } - - /* comm could change, so should be updated */ - if ((length = strlen(comm)) > 0) { - pp->mergedCommand.maxLen += length; - if (!pp->procComm || !String_eq(command, pp->procComm)) { - free_and_xStrdup(&pp->procComm, command); - pp->mergedCommand.commChanged = true; - } - } else if (pp->procComm) { - free(pp->procComm); - pp->procComm = NULL; - pp->mergedCommand.commChanged = true; } + int tokenEnd = length; + Process_updateCmdline(process, command, tokenStart, tokenEnd); free(value.cp); + + Process_updateComm(process, comm); + + if (Metric_instance(PCP_PROC_EXE, pid, offset, &value, PM_TYPE_STRING)) { + Process_updateExe(process, value.cp); + free(value.cp); + } } static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, struct timeval* tv) { @@ -511,16 +496,6 @@ static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, PCPProcessList_updateCmdline(proc, pid, offset, command); } - /* (Re)Generate the Command string, but only if the process is: - * - not a kernel thread, and - * - not a zombie or it became zombie under htop's watch, and - * - not a user thread or if showThreadNames is not set */ - if (!Process_isKernelThread(proc) && - (proc->state != 'Z' || pp->mergedCommand.str) && - (!Process_isUserlandThread(proc) || !settings->showThreadNames)) { - PCPProcess_makeCommandStr(proc); - } - if (settings->flags & PROCESS_FLAG_LINUX_CGROUP) PCPProcessList_readCGroups(pp, pid, offset); @@ -533,20 +508,16 @@ static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, if (settings->flags & PROCESS_FLAG_LINUX_SECATTR) PCPProcessList_readSecattrData(pp, pid, offset); - if (proc->state == 'Z' && proc->basenameOffset == 0) { - proc->basenameOffset = -1; - free_and_xStrdup(&proc->comm, command); - pp->procCmdlineBasenameOffset = 0; - pp->procCmdlineBasenameEnd = 0; - pp->mergedCommand.commChanged = true; + if (settings->flags & PROCESS_FLAG_CWD) + PCPProcessList_readCwd(pp, pid, offset); + + if (proc->state == 'Z' && !proc->cmdline && command[0]) { + Process_updateCmdline(proc, command, 0, strlen(command)); } else if (Process_isThread(proc)) { - if (settings->showThreadNames || Process_isKernelThread(proc)) { - proc->basenameOffset = -1; - free_and_xStrdup(&proc->comm, command); - pp->procCmdlineBasenameOffset = 0; - pp->procCmdlineBasenameEnd = 0; - pp->mergedCommand.commChanged = true; + if ((settings->showThreadNames || Process_isKernelThread(proc)) && command[0]) { + Process_updateCmdline(proc, command, 0, strlen(command)); } + if (Process_isKernelThread(proc)) { pl->kernelThreads++; } else { @@ -557,14 +528,12 @@ static bool PCPProcessList_updateProcesses(PCPProcessList* this, double period, /* Set at the end when we know if a new entry is a thread */ proc->show = ! ((hideKernelThreads && Process_isKernelThread(proc)) || (hideUserlandThreads && Process_isUserlandThread(proc))); -//fprintf(stderr, "Updated PID %d [%s] show=%d user=%d[%d] kern=%d[%d]\n", pid, command, proc->show, Process_isUserlandThread(proc), hideUserlandThreads, Process_isKernelThread(proc), hideKernelThreads); pl->totalTasks++; if (proc->state == 'R') pl->runningTasks++; proc->updated = true; } -//fprintf(stderr, "Total tasks %d, running=%d\n", pl->totalTasks, pl->runningTasks); return true; } diff --git a/pcp/Platform.c b/pcp/Platform.c index 1caa3e092..f4d538df1 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -219,6 +219,8 @@ static const char *Platform_metricNames[] = { [PCP_PROC_LABELS] = "proc.psinfo.labels", [PCP_PROC_ENVIRON] = "proc.psinfo.environ", [PCP_PROC_TTYNAME] = "proc.psinfo.ttyname", + [PCP_PROC_EXE] = "proc.psinfo.exe", + [PCP_PROC_CWD] = "proc.psinfo.cwd", [PCP_PROC_ID_UID] = "proc.id.uid", [PCP_PROC_ID_USER] = "proc.id.uid_nm", [PCP_PROC_IO_RCHAR] = "proc.io.rchar", diff --git a/pcp/Platform.h b/pcp/Platform.h index 2a1bd3b40..cd90bc002 100644 --- a/pcp/Platform.h +++ b/pcp/Platform.h @@ -206,6 +206,8 @@ typedef enum Metric_ { PCP_PROC_LABELS, /* proc.psinfo.labels */ PCP_PROC_ENVIRON, /* proc.psinfo.environ */ PCP_PROC_TTYNAME, /* proc.psinfo.ttyname */ + PCP_PROC_EXE, /* proc.psinfo.exe */ + PCP_PROC_CWD, /* proc.psinfo.cwd */ PCP_PROC_ID_UID, /* proc.id.uid */ PCP_PROC_ID_USER, /* proc.id.uid_nm */ diff --git a/pcp/ProcessField.h b/pcp/ProcessField.h index ee03cbafb..3d5cb743d 100644 --- a/pcp/ProcessField.h +++ b/pcp/ProcessField.h @@ -43,7 +43,8 @@ in the source distribution for its full text. M_PSSWP = 121, \ CTXT = 122, \ SECATTR = 123, \ - PROC_COMM = 124, \ + \ + DUMMY_BUMP_FIELD = CWD, \ // End of list From 591fc78e8f562c68f8a8af0787bebb990553a07a Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Mon, 7 Jun 2021 13:46:29 +1000 Subject: [PATCH 19/20] Update platform-specific header includes to use pcp paths. Resolves a couple of remaining review notes from @BenBE. --- pcp/PCPProcess.c | 2 +- pcp/PCPProcessList.c | 5 +++-- pcp/Platform.c | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/pcp/PCPProcess.c b/pcp/PCPProcess.c index 3b66a3013..5947ee128 100644 --- a/pcp/PCPProcess.c +++ b/pcp/PCPProcess.c @@ -7,7 +7,7 @@ Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "PCPProcess.h" +#include "pcp/PCPProcess.h" #include #include diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index 0985ad2c3..c7582ff62 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -9,18 +9,19 @@ in the source distribution for its full text. #include "config.h" // IWYU pragma: keep -#include "PCPProcessList.h" +#include "pcp/PCPProcessList.h" #include #include "CRT.h" #include "Macros.h" #include "Object.h" -#include "PCPProcess.h" #include "Process.h" #include "Settings.h" #include "XUtils.h" +#include "pcp/PCPProcess.h" + static int PCPProcessList_computeCPUcount(void) { int cpus; diff --git a/pcp/Platform.c b/pcp/Platform.c index f4d538df1..1c2432ca4 100644 --- a/pcp/Platform.c +++ b/pcp/Platform.c @@ -9,7 +9,7 @@ in the source distribution for its full text. #include "config.h" // IWYU pragma: keep -#include "Platform.h" +#include "pcp/Platform.h" #include @@ -29,8 +29,6 @@ in the source distribution for its full text. #include "NetworkIOMeter.h" #include "Object.h" #include "Panel.h" -#include "PCPProcess.h" -#include "PCPProcessList.h" #include "ProcessList.h" #include "ProvideCurses.h" #include "Settings.h" @@ -43,6 +41,8 @@ in the source distribution for its full text. #include "linux/PressureStallMeter.h" #include "linux/ZramMeter.h" #include "linux/ZramStats.h" +#include "pcp/PCPProcess.h" +#include "pcp/PCPProcessList.h" #include "zfs/ZfsArcMeter.h" #include "zfs/ZfsArcStats.h" #include "zfs/ZfsCompressedArcMeter.h" From 7653e15c9bde53e74eae25fec215ec474ce83c36 Mon Sep 17 00:00:00 2001 From: Nathan Scott Date: Tue, 8 Jun 2021 09:46:02 +1000 Subject: [PATCH 20/20] Use macros to PCPProcessList value extraction, tweak configure.ac Resolves a couple of remaining review notes from @BenBE. --- configure.ac | 4 +- pcp/PCPProcessList.c | 320 ++++++++++++++----------------------------- 2 files changed, 105 insertions(+), 219 deletions(-) diff --git a/configure.ac b/configure.ac index 739b7b2d5..1ab0c8fbb 100644 --- a/configure.ac +++ b/configure.ac @@ -110,8 +110,8 @@ case "$enable_pcp" in yes) AC_CHECK_HEADERS([pcp/pmapi.h], [my_htop_platform=pcp], [AC_MSG_ERROR([can not find PCP header file])]) - AC_SEARCH_LIBS([pmNewContext], [pcp], [], [AC_MSG_ERROR([can not find pcp library])]) - AC_DEFINE([HTOP_PCP], [1], [Define if building pcp htop binary.]) + AC_SEARCH_LIBS([pmNewContext], [pcp], [], [AC_MSG_ERROR([can not find PCP library])]) + AC_DEFINE([HTOP_PCP], [1], [Define if building pcp-htop binary.]) ;; *) AC_MSG_ERROR([bad value '$enable_pcp' for --enable-pcp option]) diff --git a/pcp/PCPProcessList.c b/pcp/PCPProcessList.c index c7582ff62..b479ce67e 100644 --- a/pcp/PCPProcessList.c +++ b/pcp/PCPProcessList.c @@ -86,29 +86,55 @@ void ProcessList_delete(ProcessList* pl) { free(this); } -static inline unsigned long long PCPProcessList_adjustTime(unsigned long long t) { - return t / 10; +static inline unsigned long Metric_instance_s32(int metric, int pid, int offset, unsigned long fallback) { + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_32)) + return value.l; + return fallback; } -static void PCPProcessList_updateID(Process* process, int pid, int offset) { +static inline unsigned long Metric_instance_u32(int metric, int pid, int offset, unsigned long fallback) { pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_U32)) + return value.ul; + return fallback; +} - if (Metric_instance(PCP_PROC_TGID, pid, offset, &value, PM_TYPE_U32)) - process->tgid = value.ul; - else - process->tgid = 1; +static inline unsigned long long Metric_instance_u64(int metric, int pid, int offset, unsigned long long fallback) { + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_U64)) + return value.ull; + return fallback; +} - if (Metric_instance(PCP_PROC_PPID, pid, offset, &value, PM_TYPE_U32)) - process->ppid = value.ul; - else - process->ppid = 1; +static inline unsigned long long Metric_instance_time(int metric, int pid, int offset) { + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_U64)) + return value.ull / 10; + return 0; +} + +static inline unsigned long long Metric_instance_ONE_K(int metric, int pid, int offset) { + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_U64)) + return value.ull / ONE_K; + return ULLONG_MAX; +} - if (Metric_instance(PCP_PROC_STATE, pid, offset, &value, PM_TYPE_STRING)) { - process->state = value.cp[0]; +static inline char Metric_instance_char(int metric, int pid, int offset, char fallback) { + pmAtomValue value; + if (Metric_instance(metric, pid, offset, &value, PM_TYPE_STRING)) { + char uchar = value.cp[0]; free(value.cp); - } else { - process->state = 'X'; + return uchar; } + return fallback; +} + +static void PCPProcessList_updateID(Process* process, int pid, int offset) { + process->tgid = Metric_instance_u32(PCP_PROC_TGID, pid, offset, 1); + process->ppid = Metric_instance_u32(PCP_PROC_PPID, pid, offset, 1); + process->state = Metric_instance_char(PCP_PROC_STATE, pid, offset, '?'); } static void PCPProcessList_updateInfo(Process* process, int pid, int offset, char* command, size_t commLen) { @@ -120,214 +146,80 @@ static void PCPProcessList_updateInfo(Process* process, int pid, int offset, cha String_safeStrncpy(command, value.cp, commLen); free(value.cp); - if (Metric_instance(PCP_PROC_PGRP, pid, offset, &value, PM_TYPE_U32)) - process->pgrp = value.ul; - else - process->pgrp = 0; - - if (Metric_instance(PCP_PROC_SESSION, pid, offset, &value, PM_TYPE_U32)) - process->session = value.ul; - else - process->session = 0; - - if (Metric_instance(PCP_PROC_TTY, pid, offset, &value, PM_TYPE_U32)) - process->tty_nr = value.ul; - else - process->tty_nr = 0; - - if (Metric_instance(PCP_PROC_TTYPGRP, pid, offset, &value, PM_TYPE_U32)) - process->tpgid = value.ul; - else - process->tpgid = 0; - - if (Metric_instance(PCP_PROC_MINFLT, pid, offset, &value, PM_TYPE_U32)) - process->minflt = value.ul; - else - process->minflt = 0; - - if (Metric_instance(PCP_PROC_CMINFLT, pid, offset, &value, PM_TYPE_U32)) - pp->cminflt = value.ul; - else - pp->cminflt = 0; - - if (Metric_instance(PCP_PROC_MAJFLT, pid, offset, &value, PM_TYPE_U32)) - process->majflt = value.ul; - else - process->majflt = 0; - - if (Metric_instance(PCP_PROC_CMAJFLT, pid, offset, &value, PM_TYPE_U32)) - pp->cmajflt = value.ul; - else - pp->cmajflt = 0; - - if (Metric_instance(PCP_PROC_UTIME, pid, offset, &value, PM_TYPE_U64)) - pp->utime = PCPProcessList_adjustTime(value.ull); - else - pp->utime = 0; - - if (Metric_instance(PCP_PROC_STIME, pid, offset, &value, PM_TYPE_U64)) - pp->stime = PCPProcessList_adjustTime(value.ull); - else - pp->stime = 0; - - if (Metric_instance(PCP_PROC_CUTIME, pid, offset, &value, PM_TYPE_U64)) - pp->cutime = PCPProcessList_adjustTime(value.ull); - else - pp->cutime = 0; - - if (Metric_instance(PCP_PROC_CSTIME, pid, offset, &value, PM_TYPE_U64)) - pp->cstime = PCPProcessList_adjustTime(value.ull); - else - pp->cstime = 0; - - if (Metric_instance(PCP_PROC_PRIORITY, pid, offset, &value, PM_TYPE_U32)) - process->priority = value.ul; - else - process->priority = 0; - - if (Metric_instance(PCP_PROC_NICE, pid, offset, &value, PM_TYPE_32)) - process->nice = value.l; - else - process->nice = 0; - - if (Metric_instance(PCP_PROC_THREADS, pid, offset, &value, PM_TYPE_U32)) - process->nlwp = value.ul; - else - process->nlwp = 0; - - if (Metric_instance(PCP_PROC_STARTTIME, pid, offset, &value, PM_TYPE_U64)) - process->starttime_ctime = PCPProcessList_adjustTime(value.ull); - else - process->starttime_ctime = 0; - - if (Metric_instance(PCP_PROC_PROCESSOR, pid, offset, &value, PM_TYPE_U32)) - process->processor = value.ul; - else - process->processor = 0; + process->pgrp = Metric_instance_u32(PCP_PROC_PGRP, pid, offset, 0); + process->session = Metric_instance_u32(PCP_PROC_SESSION, pid, offset, 0); + process->tty_nr = Metric_instance_u32(PCP_PROC_TTY, pid, offset, 0); + process->tpgid = Metric_instance_u32(PCP_PROC_TTYPGRP, pid, offset, 0); + process->minflt = Metric_instance_u32(PCP_PROC_MINFLT, pid, offset, 0); + pp->cminflt = Metric_instance_u32(PCP_PROC_CMINFLT, pid, offset, 0); + process->majflt = Metric_instance_u32(PCP_PROC_MAJFLT, pid, offset, 0); + pp->cmajflt = Metric_instance_u32(PCP_PROC_CMAJFLT, pid, offset, 0); + pp->utime = Metric_instance_u64(PCP_PROC_UTIME, pid, offset, 0); + pp->stime = Metric_instance_u64(PCP_PROC_STIME, pid, offset, 0); + pp->cutime = Metric_instance_time(PCP_PROC_CUTIME, pid, offset); + pp->cstime = Metric_instance_time(PCP_PROC_CSTIME, pid, offset); + process->priority = Metric_instance_u32(PCP_PROC_PRIORITY, pid, offset, 0); + process->nice = Metric_instance_s32(PCP_PROC_NICE, pid, offset, 0); + process->nlwp = Metric_instance_u32(PCP_PROC_THREADS, pid, offset, 0); + process->starttime_ctime = Metric_instance_time(PCP_PROC_STARTTIME, pid, offset); + process->processor = Metric_instance_u32(PCP_PROC_PROCESSOR, pid, offset, 0); process->time = pp->utime + pp->stime; } -static void PCPProcessList_updateIO(PCPProcess* process, int pid, int offset, unsigned long long now) { +static void PCPProcessList_updateIO(PCPProcess* pp, int pid, int offset, unsigned long long now) { pmAtomValue value; - if (Metric_instance(PCP_PROC_IO_RCHAR, pid, offset, &value, PM_TYPE_U64)) - process->io_rchar = value.ull / ONE_K; - else - process->io_rchar = ULLONG_MAX; - - if (Metric_instance(PCP_PROC_IO_WCHAR, pid, offset, &value, PM_TYPE_U64)) - process->io_wchar = value.ull / ONE_K; - else - process->io_wchar = ULLONG_MAX; - - if (Metric_instance(PCP_PROC_IO_SYSCR, pid, offset, &value, PM_TYPE_U64)) - process->io_syscr = value.ull; - else - process->io_syscr = ULLONG_MAX; - - if (Metric_instance(PCP_PROC_IO_SYSCW, pid, offset, &value, PM_TYPE_U64)) - process->io_syscw = value.ull; - else - process->io_syscw = ULLONG_MAX; - - if (Metric_instance(PCP_PROC_IO_CANCELLED, pid, offset, &value, PM_TYPE_U64)) - process->io_cancelled_write_bytes = value.ull / ONE_K; - else - process->io_cancelled_write_bytes = ULLONG_MAX; + pp->io_rchar = Metric_instance_ONE_K(PCP_PROC_IO_RCHAR, pid, offset); + pp->io_wchar = Metric_instance_ONE_K(PCP_PROC_IO_WCHAR, pid, offset); + pp->io_syscr = Metric_instance_u64(PCP_PROC_IO_SYSCR, pid, offset, ULLONG_MAX); + pp->io_syscw = Metric_instance_u64(PCP_PROC_IO_SYSCW, pid, offset, ULLONG_MAX); + pp->io_cancelled_write_bytes = Metric_instance_ONE_K(PCP_PROC_IO_CANCELLED, pid, offset); if (Metric_instance(PCP_PROC_IO_READB, pid, offset, &value, PM_TYPE_U64)) { - unsigned long long last_read = process->io_read_bytes; - process->io_read_bytes = value.ull / ONE_K; - process->io_rate_read_bps = - ONE_K * (process->io_read_bytes - last_read) / - (now - process->io_last_scan_time); + unsigned long long last_read = pp->io_read_bytes; + pp->io_read_bytes = value.ull / ONE_K; + pp->io_rate_read_bps = ONE_K * (pp->io_read_bytes - last_read) / + (now - pp->io_last_scan_time); } else { - process->io_read_bytes = ULLONG_MAX; - process->io_rate_read_bps = NAN; + pp->io_read_bytes = ULLONG_MAX; + pp->io_rate_read_bps = NAN; } if (Metric_instance(PCP_PROC_IO_WRITEB, pid, offset, &value, PM_TYPE_U64)) { - unsigned long long last_write = process->io_write_bytes; - process->io_write_bytes = value.ull; - process->io_rate_write_bps = - ONE_K * (process->io_write_bytes - last_write) / - (now - process->io_last_scan_time); + unsigned long long last_write = pp->io_write_bytes; + pp->io_write_bytes = value.ull; + pp->io_rate_write_bps = ONE_K * (pp->io_write_bytes - last_write) / + (now - pp->io_last_scan_time); } else { - process->io_write_bytes = ULLONG_MAX; - process->io_rate_write_bps = NAN; + pp->io_write_bytes = ULLONG_MAX; + pp->io_rate_write_bps = NAN; } - process->io_last_scan_time = now; + pp->io_last_scan_time = now; } -static void PCPProcessList_updateMemory(PCPProcess* process, int pid, int offset) { - pmAtomValue value; - - if (Metric_instance(PCP_PROC_MEM_SIZE, pid, offset, &value, PM_TYPE_U32)) - process->super.m_virt = value.ul; - else - process->super.m_virt = 0; - - if (Metric_instance(PCP_PROC_MEM_RSS, pid, offset, &value, PM_TYPE_U32)) - process->super.m_resident = value.ul; - else - process->super.m_resident = 0; - - if (Metric_instance(PCP_PROC_MEM_SHARE, pid, offset, &value, PM_TYPE_U32)) - process->m_share = value.ul; - else - process->m_share = 0; - - if (Metric_instance(PCP_PROC_MEM_TEXTRS, pid, offset, &value, PM_TYPE_U32)) - process->m_trs = value.ul; - else - process->m_trs = 0; - - if (Metric_instance(PCP_PROC_MEM_LIBRS, pid, offset, &value, PM_TYPE_U32)) - process->m_lrs = value.ul; - else - process->m_lrs = 0; - - if (Metric_instance(PCP_PROC_MEM_DATRS, pid, offset, &value, PM_TYPE_U32)) - process->m_drs = value.ul; - else - process->m_drs = 0; - - if (Metric_instance(PCP_PROC_MEM_DIRTY, pid, offset, &value, PM_TYPE_U32)) - process->m_dt = value.ul; - else - process->m_dt = 0; +static void PCPProcessList_updateMemory(PCPProcess* pp, int pid, int offset) { + pp->super.m_virt = Metric_instance_u32(PCP_PROC_MEM_SIZE, pid, offset, 0); + pp->super.m_resident = Metric_instance_u32(PCP_PROC_MEM_RSS, pid, offset, 0); + pp->m_share = Metric_instance_u32(PCP_PROC_MEM_SHARE, pid, offset, 0); + pp->m_trs = Metric_instance_u32(PCP_PROC_MEM_TEXTRS, pid, offset, 0); + pp->m_lrs = Metric_instance_u32(PCP_PROC_MEM_LIBRS, pid, offset, 0); + pp->m_drs = Metric_instance_u32(PCP_PROC_MEM_DATRS, pid, offset, 0); + pp->m_dt = Metric_instance_u32(PCP_PROC_MEM_DIRTY, pid, offset, 0); } -static void PCPProcessList_updateSmaps(PCPProcess* process, pid_t pid, int offset) { - pmAtomValue value; - - if (Metric_instance(PCP_PROC_SMAPS_PSS, pid, offset, &value, PM_TYPE_U64)) - process->m_pss = value.ull; - else - process->m_pss = 0LL; - - if (Metric_instance(PCP_PROC_SMAPS_SWAP, pid, offset, &value, PM_TYPE_U64)) - process->m_swap = value.ull; - else - process->m_swap = 0LL; - - if (Metric_instance(PCP_PROC_SMAPS_SWAPPSS, pid, offset, &value, PM_TYPE_U64)) - process->m_psswp = value.ull; - else - process->m_psswp = 0LL; +static void PCPProcessList_updateSmaps(PCPProcess* pp, pid_t pid, int offset) { + pp->m_pss = Metric_instance_u64(PCP_PROC_SMAPS_PSS, pid, offset, 0); + pp->m_swap = Metric_instance_u64(PCP_PROC_SMAPS_SWAP, pid, offset, 0); + pp->m_psswp = Metric_instance_u64(PCP_PROC_SMAPS_SWAPPSS, pid, offset, 0); } -static void PCPProcessList_readOomData(PCPProcess* process, int pid, int offset) { - pmAtomValue value; - if (Metric_instance(PCP_PROC_OOMSCORE, pid, offset, &value, PM_TYPE_U32)) - process->oom = value.ul; - else - process->oom = 0; +static void PCPProcessList_readOomData(PCPProcess* pp, int pid, int offset) { + pp->oom = Metric_instance_u32(PCP_PROC_OOMSCORE, pid, offset, 0); } -static void PCPProcessList_readCtxtData(PCPProcess* process, int pid, int offset) { +static void PCPProcessList_readCtxtData(PCPProcess* pp, int pid, int offset) { pmAtomValue value; unsigned long ctxt = 0; @@ -335,11 +227,9 @@ static void PCPProcessList_readCtxtData(PCPProcess* process, int pid, int offset ctxt += value.ul; if (Metric_instance(PCP_PROC_NVCTXSW, pid, offset, &value, PM_TYPE_U32)) ctxt += value.ul; - if (ctxt > process->ctxt_total) - process->ctxt_diff = ctxt - process->ctxt_total; - else - process->ctxt_diff = 0; - process->ctxt_total = ctxt; + + pp->ctxt_diff = ctxt > pp->ctxt_total ? ctxt - pp->ctxt_total : 0; + pp->ctxt_total = ctxt; } static char* setString(Metric metric, int pid, int offset, char* string) { @@ -357,25 +247,21 @@ static void PCPProcessList_updateTTY(Process* process, int pid, int offset) { process->tty_name = setString(PCP_PROC_TTYNAME, pid, offset, process->tty_name); } -static void PCPProcessList_readCGroups(PCPProcess* process, int pid, int offset) { - process->cgroup = setString(PCP_PROC_CGROUPS, pid, offset, process->cgroup); +static void PCPProcessList_readCGroups(PCPProcess* pp, int pid, int offset) { + pp->cgroup = setString(PCP_PROC_CGROUPS, pid, offset, pp->cgroup); } -static void PCPProcessList_readSecattrData(PCPProcess* process, int pid, int offset) { - process->secattr = setString(PCP_PROC_LABELS, pid, offset, process->secattr); +static void PCPProcessList_readSecattrData(PCPProcess* pp, int pid, int offset) { + pp->secattr = setString(PCP_PROC_LABELS, pid, offset, pp->secattr); } -static void PCPProcessList_readCwd(PCPProcess* process, int pid, int offset) { - process->super.procCwd = setString(PCP_PROC_CWD, pid, offset, process->super.procCwd); +static void PCPProcessList_readCwd(PCPProcess* pp, int pid, int offset) { + pp->super.procCwd = setString(PCP_PROC_CWD, pid, offset, pp->super.procCwd); } static void PCPProcessList_updateUsername(Process* process, int pid, int offset, UsersTable* users) { - unsigned int uid = 0; - pmAtomValue value; - if (Metric_instance(PCP_PROC_ID_UID, pid, offset, &value, PM_TYPE_U32)) - uid = value.ul; - process->st_uid = uid; - process->user = setUser(users, uid, pid, offset); + process->st_uid = Metric_instance_u32(PCP_PROC_ID_UID, pid, offset, 0); + process->user = setUser(users, process->st_uid, pid, offset); } static void PCPProcessList_updateCmdline(Process* process, int pid, int offset, const char* comm) {