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