Support for per-task I/O statistics - $top_io
[monky] / src / top.c
1 /* Conky, a system monitor, based on torsmo
2  *
3  * Any original torsmo code is licensed under the BSD license
4  *
5  * All code written since the fork of torsmo is licensed under the GPL
6  *
7  * Please see COPYING for details
8  *
9  * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
10  *                                        Dave Clark <clarkd@skynet.ca>
11  * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
12  *      (see AUTHORS)
13  * All rights reserved.
14  *
15  * This program is free software: you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation, either version 3 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  *
27  */
28
29 #include "top.h"
30
31 static unsigned long g_time = 0;
32 static unsigned long long previous_total = 0;
33 static struct process *first_process = 0;
34
35 struct process *get_first_process(void)
36 {
37         return first_process;
38 }
39
40 void free_all_processes(void)
41 {
42         struct process *next = NULL, *pr = first_process;
43
44         while (pr) {
45                 next = pr->next;
46                 if (pr->name) {
47                         free(pr->name);
48                 }
49                 free(pr);
50                 pr = next;
51         }
52         first_process = NULL;
53 }
54
55 static struct process *find_process(pid_t pid)
56 {
57         struct process *p = first_process;
58
59         while (p) {
60                 if (p->pid == pid) {
61                         return p;
62                 }
63                 p = p->next;
64         }
65         return 0;
66 }
67
68 /* Create a new process object and insert it into the process list */
69 static struct process *new_process(int p)
70 {
71         struct process *process;
72         process = (struct process *) malloc(sizeof(struct process));
73
74         // clean up memory first
75         memset(process, 0, sizeof(struct process));
76
77         /* Do stitching necessary for doubly linked list */
78         process->name = 0;
79         process->previous = 0;
80         process->next = first_process;
81         if (process->next) {
82                 process->next->previous = process;
83         }
84         first_process = process;
85
86         process->pid = p;
87         process->time_stamp = 0;
88         process->previous_user_time = ULONG_MAX;
89         process->previous_kernel_time = ULONG_MAX;
90 #ifdef IOSTATS
91         process->previous_read_bytes = ULLONG_MAX;
92         process->previous_write_bytes = ULLONG_MAX;
93 #endif
94         process->counted = 1;
95
96         /* process_find_name(process); */
97
98         return process;
99 }
100
101 /******************************************
102  * Functions                                                      *
103  ******************************************/
104
105 /******************************************
106  * Extract information from /proc                 *
107  ******************************************/
108
109 /* These are the guts that extract information out of /proc.
110  * Anyone hoping to port wmtop should look here first. */
111 static int process_parse_stat(struct process *process)
112 {
113         struct information *cur = &info;
114         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
115         int ps;
116         unsigned long user_time = 0;
117         unsigned long kernel_time = 0;
118         int rc;
119         char *r, *q;
120         char deparenthesised_name[BUFFER_LEN];
121         int endl;
122         int nice_val;
123
124         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
125
126         ps = open(filename, O_RDONLY);
127         if (ps < 0) {
128                 /* The process must have finished in the last few jiffies! */
129                 return 1;
130         }
131
132         /* Mark process as up-to-date. */
133         process->time_stamp = g_time;
134
135         rc = read(ps, line, sizeof(line));
136         close(ps);
137         if (rc < 0) {
138                 return 1;
139         }
140
141         /* Extract cpu times from data in /proc filesystem */
142         rc = sscanf(line, "%*s %s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
143                 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", procname, &process->user_time,
144                 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
145         if (rc < 5) {
146                 return 1;
147         }
148         /* Remove parentheses from the process name stored in /proc/ under Linux */
149         r = procname + 1;
150         /* remove any "kdeinit: " */
151         if (r == strstr(r, "kdeinit")) {
152                 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
153                         process->pid);
154
155                 ps = open(filename, O_RDONLY);
156                 if (ps < 0) {
157                         /* The process must have finished in the last few jiffies! */
158                         return 1;
159                 }
160
161                 endl = read(ps, line, sizeof(line));
162                 close(ps);
163
164                 /* null terminate the input */
165                 line[endl] = 0;
166                 /* account for "kdeinit: " */
167                 if ((char *) line == strstr(line, "kdeinit: ")) {
168                         r = ((char *) line) + 9;
169                 } else {
170                         r = (char *) line;
171                 }
172
173                 q = deparenthesised_name;
174                 /* stop at space */
175                 while (*r && *r != ' ') {
176                         *q++ = *r++;
177                 }
178                 *q = 0;
179         } else {
180                 q = deparenthesised_name;
181                 while (*r && *r != ')') {
182                         *q++ = *r++;
183                 }
184                 *q = 0;
185         }
186
187         if (process->name) {
188                 free(process->name);
189         }
190         process->name = strndup(deparenthesised_name, text_buffer_size);
191         process->rss *= getpagesize();
192
193         if (!cur->memmax) {
194                 update_total_processes();
195         }
196
197         process->total_cpu_time = process->user_time + process->kernel_time;
198         process->totalmem = (float) (((float) process->rss / cur->memmax) / 10);
199         if (process->previous_user_time == ULONG_MAX) {
200                 process->previous_user_time = process->user_time;
201         }
202         if (process->previous_kernel_time == ULONG_MAX) {
203                 process->previous_kernel_time = process->kernel_time;
204         }
205
206         /* store the difference of the user_time */
207         user_time = process->user_time - process->previous_user_time;
208         kernel_time = process->kernel_time - process->previous_kernel_time;
209
210         /* backup the process->user_time for next time around */
211         process->previous_user_time = process->user_time;
212         process->previous_kernel_time = process->kernel_time;
213
214         /* store only the difference of the user_time here... */
215         process->user_time = user_time;
216         process->kernel_time = kernel_time;
217
218         return 0;
219 }
220
221 #ifdef IOSTATS
222 static int process_parse_io(struct process *process)
223 {
224         static const char *read_bytes_str="read_bytes:";
225         static const char *write_bytes_str="write_bytes:";
226
227         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
228         int ps;
229         int rc;
230         char *pos, *endpos;
231         unsigned long long read_bytes, write_bytes;
232
233         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
234
235         ps = open(filename, O_RDONLY);
236         if (ps < 0) {
237                 /* The process must have finished in the last few jiffies!
238                  * Or, the kernel doesn't support I/O accounting.
239                  */
240                 return 1;
241         }
242
243         rc = read(ps, line, sizeof(line));
244         close(ps);
245         if (rc < 0) {
246                 return 1;
247         }
248
249         pos = strstr(line, read_bytes_str);
250         if (pos == NULL) {
251                 /* these should not happen (unless the format of the file changes) */
252                 return 1;
253         }
254         pos += strlen(read_bytes_str);
255         process->read_bytes = strtoull(pos, &endpos, 10);
256         if (endpos == pos) {
257                 return 1;
258         }
259
260         pos = strstr(line, write_bytes_str);
261         if (pos == NULL) {
262                 return 1;
263         }
264         pos += strlen(write_bytes_str);
265         process->write_bytes = strtoull(pos, &endpos, 10);
266         if (endpos == pos) {
267                 return 1;
268         }
269
270         if (process->previous_read_bytes == ULLONG_MAX) {
271                 process->previous_read_bytes = process->read_bytes;
272         }
273         if (process->previous_write_bytes == ULLONG_MAX) {
274                 process->previous_write_bytes = process->write_bytes;
275         }
276
277         /* store the difference of the byte counts */
278         read_bytes = process->read_bytes - process->previous_read_bytes;
279         write_bytes = process->write_bytes - process->previous_write_bytes;
280
281         /* backup the counts for next time around */
282         process->previous_read_bytes = process->read_bytes;
283         process->previous_write_bytes = process->write_bytes;
284
285         /* store only the difference here... */
286         process->read_bytes = read_bytes;
287         process->write_bytes = write_bytes;
288
289         return 0;
290 }
291 #endif
292
293 /******************************************
294  * Get process structure for process pid  *
295  ******************************************/
296
297 /* This function seems to hog all of the CPU time.
298  * I can't figure out why - it doesn't do much. */
299 static int calculate_stats(struct process *process)
300 {
301         int rc;
302
303         /* compute each process cpu usage by reading /proc/<proc#>/stat */
304         rc = process_parse_stat(process);
305         if (rc)
306                 return 1;
307         /* rc = process_parse_statm(process); if (rc) return 1; */
308
309 #ifdef IOSTATS
310         rc = process_parse_io(process);
311         if (rc)
312                 return 1;
313 #endif
314
315         /*
316          * Check name against the exclusion list
317          */
318         /* if (process->counted && exclusion_expression &&
319          * !regexec(exclusion_expression, process->name, 0, 0, 0))
320          * process->counted = 0; */
321
322         return 0;
323 }
324
325 /******************************************
326  * Update process table                                   *
327  ******************************************/
328
329 static int update_process_table(void)
330 {
331         DIR *dir;
332         struct dirent *entry;
333
334         if (!(dir = opendir("/proc"))) {
335                 return 1;
336         }
337
338         ++g_time;
339
340         /* Get list of processes from /proc directory */
341         while ((entry = readdir(dir))) {
342                 pid_t pid;
343
344                 if (!entry) {
345                         /* Problem reading list of processes */
346                         closedir(dir);
347                         return 1;
348                 }
349
350                 if (sscanf(entry->d_name, "%d", &pid) > 0) {
351                         struct process *p;
352
353                         p = find_process(pid);
354                         if (!p) {
355                                 p = new_process(pid);
356                         }
357
358                         /* compute each process cpu usage */
359                         calculate_stats(p);
360                 }
361         }
362
363         closedir(dir);
364
365         return 0;
366 }
367
368 /******************************************
369  * Destroy and remove a process           *
370  ******************************************/
371
372 static void delete_process(struct process *p)
373 {
374 #if defined(PARANOID)
375         assert(p->id == 0x0badfeed);
376
377         /*
378          * Ensure that deleted processes aren't reused.
379          */
380         p->id = 0x007babe;
381 #endif /* defined(PARANOID) */
382
383         /*
384          * Maintain doubly linked list.
385          */
386         if (p->next)
387                 p->next->previous = p->previous;
388         if (p->previous)
389                 p->previous->next = p->next;
390         else
391                 first_process = p->next;
392
393         if (p->name) {
394                 free(p->name);
395         }
396         free(p);
397 }
398
399 /******************************************
400  * Strip dead process entries                     *
401  ******************************************/
402
403 static void process_cleanup(void)
404 {
405
406         struct process *p = first_process;
407
408         while (p) {
409                 struct process *current = p;
410
411 #if defined(PARANOID)
412                 assert(p->id == 0x0badfeed);
413 #endif /* defined(PARANOID) */
414
415                 p = p->next;
416                 /* Delete processes that have died */
417                 if (current->time_stamp != g_time) {
418                         delete_process(current);
419                 }
420         }
421 }
422
423 /******************************************
424  * Calculate cpu total                                    *
425  ******************************************/
426 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
427 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
428
429 static unsigned long long calc_cpu_total(void)
430 {
431         unsigned long long total = 0;
432         unsigned long long t = 0;
433         int rc;
434         int ps;
435         char line[BUFFER_LEN] = { 0 };
436         unsigned long long cpu = 0;
437         unsigned long long niceval = 0;
438         unsigned long long systemval = 0;
439         unsigned long long idle = 0;
440         unsigned long long iowait = 0;
441         unsigned long long irq = 0;
442         unsigned long long softirq = 0;
443         unsigned long long steal = 0;
444         const char *template =
445                 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
446
447         ps = open("/proc/stat", O_RDONLY);
448         rc = read(ps, line, sizeof(line));
449         close(ps);
450         if (rc < 0) {
451                 return 0;
452         }
453
454         sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
455                 &softirq, &steal);
456         total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
457
458         t = total - previous_total;
459         previous_total = total;
460
461         return t;
462 }
463
464 /******************************************
465  * Calculate each processes cpu                   *
466  ******************************************/
467
468 inline static void calc_cpu_each(unsigned long long total)
469 {
470         struct process *p = first_process;
471
472         while (p) {
473                 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
474                         (p->user_time + p->kernel_time) / (float) total;
475
476                 p = p->next;
477         }
478 }
479
480 #ifdef IOSTATS
481 static void calc_io_each(void)
482 {
483         struct process *p;
484         unsigned long long sum = 0;
485         
486         for (p = first_process; p; p = p->next)
487                 sum += p->read_bytes + p->write_bytes;
488
489         if(sum == 0)
490                 sum = 1; /* to avoid having NANs if no I/O occured */
491         for (p = first_process; p; p = p->next)
492                 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
493 }
494 #endif
495
496 /******************************************
497  * Find the top processes                                 *
498  ******************************************/
499
500 /* free a sp_process structure */
501 static void free_sp(struct sorted_process *sp)
502 {
503         free(sp);
504 }
505
506 /* create a new sp_process structure */
507 static struct sorted_process *malloc_sp(struct process *proc)
508 {
509         struct sorted_process *sp;
510         sp = malloc(sizeof(struct sorted_process));
511         sp->greater = NULL;
512         sp->less = NULL;
513         sp->proc = proc;
514         return sp;
515 }
516
517 /* cpu comparison function for insert_sp_element */
518 static int compare_cpu(struct process *a, struct process *b)
519 {
520         if (a->amount < b->amount) {
521                 return 1;
522         } else if (a->amount > b->amount) {
523                 return -1;
524         } else {
525                 return 0;
526         }
527 }
528
529 /* mem comparison function for insert_sp_element */
530 static int compare_mem(struct process *a, struct process *b)
531 {
532         if (a->totalmem < b->totalmem) {
533                 return 1;
534         } else if (a->totalmem > b->totalmem) {
535                 return -1;
536         } else {
537                 return 0;
538         }
539 }
540
541 /* CPU time comparision function for insert_sp_element */
542 static int compare_time(struct process *a, struct process *b)
543 {
544         return b->total_cpu_time - a->total_cpu_time;
545 }
546
547 #ifdef IOSTATS
548 /* I/O comparision function for insert_sp_element */
549 static int compare_io(struct process *a, struct process *b)
550 {
551         if (a->io_perc < b->io_perc) {
552                 return 1;
553         } else if (a->io_perc > b->io_perc) {
554                 return -1;
555         } else {
556                 return 0;
557         }
558 }
559 #endif
560
561 /* insert this process into the list in a sorted fashion,
562  * or destroy it if it doesn't fit on the list */
563 static int insert_sp_element(struct sorted_process *sp_cur,
564                 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
565                 int max_elements, int compare_funct(struct process *, struct process *))
566 {
567
568         struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
569         int did_insert = 0, x = 0;
570
571         if (*p_sp_head == NULL) {
572                 *p_sp_head = sp_cur;
573                 *p_sp_tail = sp_cur;
574                 return 1;
575         }
576         for (sp_readthru = *p_sp_head, x = 0;
577                         sp_readthru != NULL && x < max_elements;
578                         sp_readthru = sp_readthru->less, x++) {
579                 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
580                         /* sp_cur is bigger than sp_readthru
581                          * so insert it before sp_readthru */
582                         sp_cur->less = sp_readthru;
583                         if (sp_readthru == *p_sp_head) {
584                                 /* insert as the new head of the list */
585                                 *p_sp_head = sp_cur;
586                         } else {
587                                 /* insert inside the list */
588                                 sp_readthru->greater->less = sp_cur;
589                                 sp_cur->greater = sp_readthru->greater;
590                         }
591                         sp_readthru->greater = sp_cur;
592                         /* element was inserted, so increase the counter */
593                         did_insert = ++x;
594                 }
595         }
596         if (x < max_elements && sp_readthru == NULL && !did_insert) {
597                 /* sp_cur is the smallest element and list isn't full,
598                  * so insert at the end */
599                 (*p_sp_tail)->less = sp_cur;
600                 sp_cur->greater = *p_sp_tail;
601                 *p_sp_tail = sp_cur;
602                 did_insert = x;
603         } else if (x >= max_elements) {
604                 /* We inserted an element and now the list is too big by one.
605                  * Destroy the smallest element */
606                 sp_destroy = *p_sp_tail;
607                 *p_sp_tail = sp_destroy->greater;
608                 (*p_sp_tail)->less = NULL;
609                 free_sp(sp_destroy);
610         }
611         if (!did_insert) {
612                 /* sp_cur wasn't added to the sorted list, so destroy it */
613                 free_sp(sp_cur);
614         }
615         return did_insert;
616 }
617
618 /* copy the procs in the sorted list to the array, and destroy the list */
619 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
620 {
621         struct sorted_process *sp_cur, *sp_tmp;
622         int x;
623
624         sp_cur = sp_head;
625         for (x = 0; x < max_size && sp_cur != NULL; x++) {
626                 ar[x] = sp_cur->proc;
627                 sp_tmp = sp_cur;
628                 sp_cur = sp_cur->less;
629                 free_sp(sp_tmp);
630         }
631 }
632
633 /* ****************************************************************** *
634  * Get a sorted list of the top cpu hogs and top mem hogs.                        *
635  * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
636  * ****************************************************************** */
637
638 void process_find_top(struct process **cpu, struct process **mem,
639                 struct process **ptime
640 #ifdef IOSTATS
641                 , struct process **io
642 #endif
643                 )
644 {
645         struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
646         struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
647         struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
648 #ifdef IOSTATS
649         struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
650 #endif
651         struct process *cur_proc = NULL;
652         unsigned long long total = 0;
653
654         if (!top_cpu && !top_mem && !top_time
655 #ifdef IOSTATS
656                         && !top_io
657 #endif
658            ) {
659                 return;
660         }
661
662         total = calc_cpu_total();       /* calculate the total of the processor */
663         update_process_table();         /* update the table with process list */
664         calc_cpu_each(total);           /* and then the percentage for each task */
665         process_cleanup();                      /* cleanup list from exited processes */
666 #ifdef IOSTATS
667         calc_io_each();                 /* percentage of I/O for each task */
668 #endif
669
670         cur_proc = first_process;
671
672         while (cur_proc != NULL) {
673                 if (top_cpu) {
674                         spc_cur = malloc_sp(cur_proc);
675                         insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
676                                 &compare_cpu);
677                 }
678                 if (top_mem) {
679                         spm_cur = malloc_sp(cur_proc);
680                         insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
681                                 &compare_mem);
682                 }
683                 if (top_time) {
684                         spt_cur = malloc_sp(cur_proc);
685                         insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
686                                 &compare_time);
687                 }
688 #ifdef IOSTATS
689                 if (top_io) {
690                         spi_cur = malloc_sp(cur_proc);
691                         insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
692                                 &compare_io);
693                 }
694 #endif
695                 cur_proc = cur_proc->next;
696         }
697
698         if (top_cpu)
699                 sp_acopy(spc_head, cpu, MAX_SP);
700         if (top_mem)
701                 sp_acopy(spm_head, mem, MAX_SP);
702         if (top_time)
703                 sp_acopy(spt_head, ptime, MAX_SP);
704 #ifdef IOSTATS
705         if (top_io)
706                 sp_acopy(spi_head, io,MAX_SP);
707 #endif
708 }