Set vshelper path correctly
[util-vserver.git] / src / vserver-stat.c
1 // $Id$
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 // based on vserver-stat.cc by Guillaum Dallaire and Jacques Gelinas
5 //  
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2, or (at your option)
9 // any later version.
10 //  
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //  
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #include "vserver.h"
25 #include "util.h"
26 #include "internal.h"
27 #include "pathconfig.h"
28
29 #include <ensc_vector/vector.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <dirent.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <syscall.h>
42 #include <time.h>
43 #include <stdbool.h>
44 #include <getopt.h>
45 #include <sys/param.h>
46 #include <sys/resource.h>
47
48 #define ENSC_WRAPPERS_DIRENT    1
49 #define ENSC_WRAPPERS_VSERVER   1
50 #define ENSC_WRAPPERS_FCNTL     1
51 #define ENSC_WRAPPERS_UNISTD    1
52 #include "wrappers.h"
53
54 #define PROC_DIR_NAME "/proc"
55 #define PROC_VIRT_DIR_NAME "/proc/virtual"
56 #define CTX_DIR_NAME "/var/run/vservers/"
57 #define CTX_NAME_MAX_LEN 50
58
59 int     wrapper_exit_code = 1;
60
61 #ifndef AT_CLKTCK
62 #define AT_CLKTCK       17    /* frequency of times() */
63 #endif
64
65 static unsigned long    hertz   =0x42;
66 static unsigned long    pagesize=0x42;
67
68 struct XidData
69 {
70     xid_t               xid;
71     unsigned int        process_count;
72     uint64_t            VmSize_total;
73     uint64_t            VmRSS_total;
74     uint64_t            start_time_oldest;
75     uint64_t            stime_total, utime_total;
76
77     vcCfgStyle          cfgstyle;
78     char const *        name;
79 };
80
81 struct process_info
82 {
83         long            VmSize;         // number of pages of virtual memory
84         long            VmRSS;          // resident set size from /proc/#/stat
85         uint64_t        start_time;     // start time of process -- milliseconds since 1-1-70
86         uint64_t        stime, utime;   // kernel & user-mode CPU time accumulated by process
87         uint64_t        cstime, cutime; // cumulative time of process and reaped children
88         xid_t           s_context;
89 };
90
91 struct ArgInfo {
92     enum { tpUNSET, tpCTX, tpPID }      type;
93     xid_t               ctx;
94     pid_t               pid;
95     unsigned int        interval;
96     bool                shutdown;
97     bool                omit_init;
98     size_t              argc;
99     char * const *      argv;
100 };
101
102 #define CMD_HELP                0x1000
103 #define CMD_VERSION             0x1001
104
105 struct option const
106 CMDLINE_OPTIONS[] = {
107   { "help",     no_argument,  0, CMD_HELP },
108   { "version",  no_argument,  0, CMD_VERSION },
109   { "sort",     required_argument, 0, 'O' },
110   {0,0,0,0}
111 };
112
113 static void
114 showHelp(char const *cmd)
115 {
116   WRITE_MSG(1, "Usage:  ");
117   WRITE_STR(1, cmd);
118   WRITE_MSG(1,
119             "\n"
120             "Show information about all active contexts.\n\n"
121             "   CTX#            Context number\n"
122             "                   #0 = root context\n"
123             "                   #1 = monitoring context\n"
124             "   PROC QTY        Quantity of processes in each context\n"
125             "   VSZ             Number of pages of virtual memory\n"
126             "   RSS             Resident set size\n"
127             "   userTIME        User-mode CPU time accumulated\n"
128             "   sysTIME         Kernel-mode CPU time accumulated\n"
129             "   UPTIME          Uptime/context\n"
130             "   NAME            Virtual server name\n"
131             "\n");
132   exit(0);
133 }
134
135 static void
136 showVersion()
137 {
138   WRITE_MSG(1,
139             "vserver-stat " VERSION " -- show virtual context statistics\n"
140             "This program is part of " PACKAGE_STRING "\n\n"
141             "Copyright (C) 2003,2005 Enrico Scholz\n"
142             VERSION_COPYRIGHT_DISCLAIMER);
143   exit(0);
144 }
145
146
147 // return uptime (in ms) from /proc/uptime
148 static uint64_t
149 getUptime()
150 {
151   int           fd;
152   char          buffer[64];
153   char *        errptr;
154   size_t        len;
155   uint64_t      secs;
156   uint32_t      msecs=0;
157
158     // open the /proc/uptime file
159   fd  = EopenD("/proc/uptime", O_RDONLY, 0);
160   len = Eread(fd, buffer, sizeof buffer);
161
162   if (len==sizeof(buffer)) {
163     WRITE_MSG(2, "Too much data in /proc/uptime; aborting...\n");
164     exit(1);
165   }
166   Eclose(fd);
167
168   while (len>0 && buffer[len-1]=='\n') --len;
169   buffer[len] = '\0';
170
171   secs = strtol(buffer, &errptr, 10);
172   if (*errptr!='.') errptr = buffer;
173   else {
174     unsigned int        mult;
175     switch (strlen(errptr+1)) {
176       case 0    :  mult = 1000; break;
177       case 1    :  mult = 100;  break;
178       case 2    :  mult = 10;   break;
179       case 3    :  mult = 1;    break;
180       default   :  mult = 0;    break;
181     }
182     msecs = strtol(errptr+1, &errptr, 10) * mult;
183   }
184
185   if ((*errptr!='\0' && *errptr!=' ') || errptr==buffer) {
186     WRITE_MSG(2, "Bad data in /proc/uptime\n");
187     exit(1);
188   }
189
190   return secs*1000 + msecs;
191 }
192
193 static inline uint64_t
194 toMsec(uint64_t v)
195 {
196   return v*1000llu/hertz;
197 }
198
199 static int
200 cmpData(void const *xid_v, void const *map_v)
201 {
202   xid_t const * const                   xid = xid_v;
203   struct XidData const * const          map = map_v;
204   int   res = *xid - map->xid;
205
206   return res;
207 }
208
209 static void
210 registerXid(struct Vector *vec, struct process_info *process)
211 {
212   struct XidData        *res;
213
214   res = Vector_search(vec, &process->s_context, cmpData);
215   if (res==0) {
216     res = Vector_insert(vec, &process->s_context, cmpData);
217     res->xid           = process->s_context;
218     res->process_count = 0;
219     res->VmSize_total  = 0;
220     res->VmRSS_total   = 0;
221     res->utime_total   = 0;
222     res->stime_total   = 0;
223     res->start_time_oldest = process->start_time;
224   }
225
226   ++res->process_count;
227   res->VmSize_total += process->VmSize;
228   res->VmRSS_total  += process->VmRSS;
229   res->utime_total  += process->utime + process->cutime;
230   res->stime_total  += process->stime + process->cstime;
231
232   res->start_time_oldest = MIN(res->start_time_oldest, process->start_time);
233 }
234
235 static void
236 registerXidVstat(struct Vector *vec, unsigned long xid_l)
237 {
238   xid_t                 xid = (xid_t) xid_l;
239   struct XidData        *res;
240   struct vc_rlimit_stat limit[3];
241   struct vc_virt_stat   vstat;
242   struct vc_sched_info  sched;
243   int                   cpu;
244
245   res = Vector_search(vec, &xid, cmpData);
246   if (res!=0) {
247     WRITE_MSG(2, "Duplicate xid found?!\n");
248     return;
249   }
250   if (vc_virt_stat(xid, &vstat) == -1) {
251     perror("vc_virt_stat()");
252     return;
253   }
254   if (vc_rlimit_stat(xid, RLIMIT_NPROC, &limit[0]) == -1) {
255     perror("vc_rlimit_stat(RLIMIT_NRPOC)");
256     return;
257   }
258   if (vc_rlimit_stat(xid, RLIMIT_AS, &limit[1]) == -1) {
259     perror("vc_rlimit_stat(RLIMIT_AS)");
260     return;
261   }
262   if (vc_rlimit_stat(xid, RLIMIT_RSS, &limit[2]) == -1) {
263     perror("vc_rlimit_stat(RLIMIT_RSS)");
264     return;
265   }
266
267   res                   = Vector_insert(vec, &xid, cmpData);
268   res->xid              = xid;
269
270   res->process_count    = limit[0].value;
271   res->VmSize_total     = limit[1].value * pagesize;
272   res->VmRSS_total      = limit[2].value;
273   res->start_time_oldest= getUptime() - vstat.uptime/1000000;
274
275   res->utime_total      = 0;
276   res->stime_total      = 0;
277   // XXX: arbitrary CPU limit.
278   for (cpu = 0; cpu < 1024; cpu++) {
279     sched.cpu_id = cpu;
280     sched.bucket_id = 0;
281     if (vc_sched_info(xid, &sched) == -1)
282       break;
283
284     res->utime_total    += sched.user_msec;
285     res->stime_total    += sched.sys_msec;
286   }
287 }
288
289 static void
290 registerXidCgroups(struct Vector *vec, struct process_info *process)
291 {
292   xid_t                         xid = (xid_t) process->s_context;
293   struct XidData                *res;
294
295   switch (vc_getXIDType(xid)) {
296     case vcTYPE_STATIC:
297     case vcTYPE_DYNAMIC:
298       break;
299     default:
300       return;
301   }
302
303   res = Vector_search(vec, &xid, cmpData);
304   if (res == 0) {
305     struct vc_rlimit_stat       limit;
306     struct vc_virt_stat         vstat;
307     struct vc_sched_info        sched;
308     int                         cpu;
309     char                        vhi_name[65],
310                                 filename[128],
311                                 cgroup[129],
312                                 name[129],
313                                 buf[30];
314     int                         fd;
315     ssize_t                     cgroup_len, name_len;
316     unsigned long long          rss = 0;
317     char                        *endptr;
318     ssize_t                     len;
319     unsigned long long          stime_total, utime_total;
320     int                         per_ss = 0;
321     FILE                        *fp;
322
323
324     if (vc_virt_stat(xid, &vstat) == -1) {
325       perror("vc_virt_stat()");
326       return;
327     }
328     if (vc_rlimit_stat(xid, RLIMIT_NPROC, &limit) == -1) {
329       perror("vc_rlimit_stat(RLIMIT_NRPOC)");
330       return;
331     }
332     if (vc_get_vhi_name(xid, vcVHI_CONTEXT, vhi_name, sizeof(vhi_name)) == -1) {
333       perror("vc_get_vhi_name(CONTEXT)");
334       return;
335     }
336
337     if ((fd = open(DEFAULTCONFDIR "/cgroup/mnt", O_RDONLY)) == -1) {
338       strcpy(cgroup, "/dev/cgroup/");
339       cgroup_len = sizeof("/dev/cgroup");
340     }
341     else {
342       cgroup_len = read(fd, cgroup, sizeof(cgroup));
343       if (cgroup_len == -1) {
344         perror("read(cgroup/mnt)");
345         return;
346       }
347       if (cgroup_len > 0) {
348         close(fd);
349         while (cgroup[cgroup_len - 1] == '\n' || cgroup[cgroup_len - 1] == '\r')
350           cgroup_len--;
351         cgroup[cgroup_len] = '/';
352         cgroup_len += 1;
353         cgroup[cgroup_len] = 0;
354       }
355     }
356
357     if ((fd = open(DEFAULTCONFDIR "/cgroup/base", O_RDONLY)) != -1) {
358       len = read(fd, cgroup + cgroup_len, sizeof(cgroup) - cgroup_len);
359       if (len == -1) {
360         perror("read(cgroup/base)");
361         return;
362       }
363       close(fd);
364       if (len > 0) {
365         while (cgroup[cgroup_len + len - 1] == '\n' || cgroup[cgroup_len + len - 1] == '\r')
366           len--;
367         cgroup_len += len;
368         if (cgroup[cgroup_len - 1] != '/') {
369           cgroup[cgroup_len] = '/';
370           cgroup_len += 1;
371         }
372         cgroup[cgroup_len] = 0;
373       }
374     }
375
376     if (access(DEFAULTCONFDIR "/cgroup/per-ss", F_OK) == 0)
377       per_ss = 1;
378
379     len = strlen(vhi_name);
380     if ((len + sizeof("/cgroup/name")) >= sizeof(filename)) {
381       WRITE_MSG(2, "too long context name: ");
382       WRITE_STR(2, vhi_name);
383       WRITE_MSG(2, "\n");
384       return;
385     }
386     strcpy(filename, vhi_name);
387     strcpy(filename + len, "/cgroup/name");
388
389     if ((fd = open(filename, O_RDONLY)) == -1) {
390       char *dir = strrchr(vhi_name, '/');
391       if (dir == NULL) {
392         WRITE_MSG(2, "invalid context name: ");
393         WRITE_STR(2, vhi_name);
394         WRITE_MSG(2, "\n");
395         return;
396       }
397       name_len = strlen(dir);
398       if (name_len >= sizeof(name)) {
399         WRITE_MSG(2, "cgroup name too long: ");
400         WRITE_STR(2, dir);
401         WRITE_MSG(2, "\n");
402         return;
403       }
404       strcpy(name, dir);
405     }
406     else {
407       name_len = read(fd, name, sizeof(name));
408       if (name_len == -1) {
409         perror("read(cgroup/name)");
410         return;
411       }
412       if (name_len > 0) {
413         while (name[name_len - 1] == '\n' || name[name_len - 1] == '\r')
414           name_len--;
415         name[name_len] = '\0';
416       }
417       close(fd);
418     }
419
420     if ((cgroup_len + name_len + sizeof("/memory/memory.stat")) > sizeof(filename)) {
421       WRITE_MSG(2, "cgroup name too long: ");
422       WRITE_STR(2, cgroup);
423       WRITE_MSG(2, "\n");
424       return;
425     }
426     snprintf(filename, sizeof(filename), "%s%s%s/memory.stat", cgroup, (per_ss ? "/memory" : ""), name);
427
428     if ((fp = fopen(filename, "r")) == -1)
429       perror("open(memory.stat)");
430     else {
431       unsigned long long _rss = 0, _mapped_file = 0;
432       while (fgets(buf, sizeof(buf), fp) != NULL) {
433         if (strncmp(buf, "rss ", 4) == 0) {
434           if ((_rss = strtoull(buf + 4, &endptr, 0)) == ULLONG_MAX ||
435               (*endptr != '\n' && *endptr != '\0')) {
436             perror("strtoull(memory.stat:rss)");
437             return;
438           }
439         }
440         else if (strncmp(buf, "mapped_file ", 12) == 0) {
441           if ((_mapped_file = strtoull(buf + 12, &endptr, 0)) == ULLONG_MAX ||
442               (*endptr != '\n' && *endptr != '\0')) {
443             perror("strtoull(memory.stat:mapped_file)");
444             return;
445           }
446         }
447       }
448       rss = _rss + _mapped_file;
449     }
450
451     snprintf(filename, sizeof(filename), "%s%s%s/cpuacct.stat", cgroup, (per_ss ? "/cpuacct" : ""), name);
452
453     if ((fd = open(filename, O_RDONLY)) == -1) {
454       utime_total       = 0;
455       stime_total       = 0;
456       // XXX: arbitrary CPU limit.
457       for (cpu = 0; cpu < 1024; cpu++) {
458         sched.cpu_id = cpu;
459         sched.bucket_id = 0;
460         if (vc_sched_info(xid, &sched) == -1)
461           break;
462
463         utime_total     += sched.user_msec;
464         stime_total     += sched.sys_msec;
465       }
466     }
467     else {
468       if (read(fd, buf, sizeof(buf)) == -1) {
469         perror("read(cpuacct.stat)");
470         return;
471       }
472       close(fd);
473
474       if (sscanf(buf, "user %llu\nsystem %llu\n", &utime_total, &stime_total) != 2) {
475         perror("sscanf(cpuacct.stat)");
476         return;
477       }
478     }
479
480     res                 = Vector_insert(vec, &xid, cmpData);
481     res->xid            = xid;
482
483     res->process_count  = limit.value;
484     res->VmRSS_total    = rss / 4096;
485     res->start_time_oldest= getUptime() - vstat.uptime/1000000;
486
487     res->utime_total    = toMsec(utime_total);
488     res->stime_total    = toMsec(stime_total);
489   }
490   
491   res->VmSize_total     += process->VmSize;
492 }
493
494
495 // shamelessly stolen from procps...
496 static unsigned long
497 find_elf_note(unsigned long findme){
498   unsigned long *ep = (unsigned long *)environ;
499   while(*ep++);
500   while(*ep){
501     if(ep[0]==findme) return ep[1];
502     ep+=2;
503   }
504   return (unsigned long)(-1);
505 }
506
507 static void initHertz()    __attribute__((__constructor__));
508 static void initPageSize() __attribute__((__constructor__));
509
510 static void
511 initHertz()
512 {
513   hertz = find_elf_note(AT_CLKTCK);
514   if (hertz==(unsigned long)(-1))
515     hertz = sysconf(_SC_CLK_TCK);
516 }
517
518 static void
519 initPageSize()
520 {
521   pagesize = sysconf(_SC_PAGESIZE);
522 }
523
524 // open the process's status file to get the ctx number, and other stat
525 struct process_info *
526 get_process_info(char *pid)
527 {
528   int                           fd;
529   char                          buffer[1024];
530   char                          *p;
531   size_t                        idx, l=strlen(pid);
532   static struct process_info    process;
533
534 #if 1
535   process.s_context = vc_get_task_xid(atoi(pid));
536 #else
537 #  warning Compiling in debug-code
538   process.s_context = random()%6;
539 #endif
540
541   if (process.s_context==VC_NOCTX) {
542     int         err=errno;
543     WRITE_MSG(2, "vc_get_task_xid(");
544     WRITE_STR(2, pid);
545     WRITE_MSG(2, "): ");
546     WRITE_STR(2, strerror(err));
547     WRITE_MSG(2, "\n");
548
549     return 0;
550   }
551   
552   memcpy(buffer,     "/proc/", 6); idx  = 6;
553   memcpy(buffer+idx, pid,      l); idx += l;
554   memcpy(buffer+idx, "/stat",  6);
555         
556     // open the /proc/#/stat file
557   if ((fd = open(buffer, O_RDONLY, 0)) == -1)
558     return NULL;
559     // put the file in a buffer
560   if (read(fd, buffer, sizeof(buffer)) < 1)
561     return NULL;
562
563   close(fd);
564
565   p   = strchr(buffer, ')');            // go after the PID (process_name)
566   for (idx = 0; idx<12 && *p!='\0'; ++p)
567     if ((*p)==' ') ++idx;
568
569   process.utime  = toMsec(strtol(p,   &p, 10));
570   process.stime  = toMsec(strtol(p+1, &p, 10));
571   process.cutime = toMsec(strtol(p+1, &p, 10));
572   process.cstime = toMsec(strtol(p+1, &p, 10));
573
574   for (idx = 0; idx<5 && *p!='\0'; ++p)
575     if ((*p)==' ') ++idx;
576
577   process.start_time = toMsec(strtol(p,   &p, 10));
578   process.VmSize     = strtol(p+1, &p, 10);
579   process.VmRSS      = strtol(p+1, &p, 10);
580
581   //printf("pid=%s, start_time=%llu\n", pid, process.start_time);
582   return &process;
583 }
584
585 static size_t
586 fillUintZero(char *buf, unsigned long val, size_t cnt)
587 {
588   size_t        l;
589   
590   l = utilvserver_fmt_ulong(buf, val);
591   if (l<cnt) {
592     memmove(buf+cnt-l, buf, l);
593     memset(buf, '0', cnt-l);
594   }
595   buf[cnt] = '\0';
596
597   return cnt;
598 }
599
600 static void
601 shortenMem(char *buf, unsigned long val)
602 {
603   char const *  SUFFIXES[] = { " ", "K", "M", "G", "T", "+" };
604   char          tmp[16];
605   char const *  suffix = "+";
606   size_t        i, l;
607   unsigned int  mod = 0;
608
609   for (i=0; i<6; ++i) {
610     if (val<1000) {
611       suffix = SUFFIXES[i];
612       break;
613     }
614     mod   = 10*(val & 1023)/1024;
615     val >>= 10;
616   }
617
618   if (val >9999) val=9999;
619   if (val>=1000) mod=0;
620
621   l = utilvserver_fmt_ulong(tmp, val);
622   if (mod!=0) {
623     tmp[l++] = '.';
624     l += utilvserver_fmt_ulong(tmp+l, mod);
625   }
626   i = 7-l-strlen(suffix);
627   
628   memcpy(buf+i,   tmp, l);
629   memcpy(buf+i+l, suffix, strlen(suffix));
630 }
631
632 static void
633 shortenTime(char *buf, uint64_t t)
634 {
635   char          tmp[32];
636   char          *ptr = tmp;
637
638   unsigned long hh, mm, ss, ms;
639
640   ms = t % 1000;
641   t /= 1000;
642
643   ss = t%60;
644   t /= 60;
645   mm = t%60;
646   t /= 60;
647   hh = t%24;
648   t /= 24;
649
650   if (t>999*999) {
651     memcpy(ptr, "INVALID", 7);
652     ptr   += 7;
653   }
654   else if (t>999) {
655     ptr   += utilvserver_fmt_ulong(ptr, t/365);
656     *ptr++ = 'y';
657     ptr   += fillUintZero(ptr, t%365, 2);
658     *ptr++ = 'd';
659     ptr   += fillUintZero(ptr, hh, 2);
660   }    
661   else if (t>0) {
662     ptr   += utilvserver_fmt_ulong(ptr, t);
663     *ptr++ = 'd';
664     ptr   += fillUintZero(ptr, hh, 2);
665     *ptr++ = 'h';
666     ptr   += fillUintZero(ptr, mm, 2);
667   }
668   else if (hh>0) {
669     ptr   += utilvserver_fmt_ulong(ptr, hh);
670     *ptr++ = 'h';
671     ptr   += fillUintZero(ptr, mm, 2);
672     *ptr++ = 'm';
673     ptr   += fillUintZero(ptr, ss, 2);    
674   }
675   else {
676     ptr   += utilvserver_fmt_ulong(ptr, mm);
677     *ptr++ = 'm';
678     ptr   += fillUintZero(ptr, ss, 2);
679     *ptr++ = 's';
680     ptr   += fillUintZero(ptr, ms, 2);
681   }
682
683   *ptr = ' ';
684   memcpy(buf+10-(ptr-tmp), tmp, ptr-tmp);
685 }
686
687 static char *
688 formatName(char *dst, vcCfgStyle style, char const *name)
689 {
690   size_t                len;
691   
692   if (name==0) name = "";
693   len = strlen(name);
694
695   switch (style) {
696     case vcCFG_LEGACY   :
697       len    = MIN(len, 18);
698       *dst++ = '[';
699       memcpy(dst, name, len);
700       dst   += len;
701       *dst++ = ']';
702       break;
703
704     default             :
705       len    = MIN(len, 20);
706       memcpy(dst, name, len);
707       dst   += len;
708       break;
709   }
710
711   return dst;
712 }
713
714 static void
715 showContexts(struct Vector const *vec)
716 {
717   uint64_t                      uptime  = getUptime();
718   struct XidData const *        ptr     = Vector_begin_const(vec);
719   struct XidData const * const  end_ptr = Vector_end_const(vec);
720   
721
722   WRITE_MSG(1, "CTX   PROC    VSZ    RSS  userTIME   sysTIME    UPTIME NAME\n");
723   for (; ptr<end_ptr; ++ptr) {
724     char        buf[sizeof(xid_t)*3 + 512];
725     char        tmp[sizeof(int)*3 + 2];
726     size_t      l;
727
728     memset(buf, ' ', sizeof(buf));
729     l = utilvserver_fmt_long(buf, ptr->xid);
730     l = utilvserver_fmt_long(tmp, ptr->process_count);
731     memcpy(buf+10-l, tmp, l);
732
733     shortenMem (buf+10, ptr->VmSize_total);
734     shortenMem (buf+17, ptr->VmRSS_total*pagesize);
735     shortenTime(buf+24, ptr->utime_total);
736     shortenTime(buf+34, ptr->stime_total);
737     //printf("%llu, %llu\n", uptime, ptr->start_time_oldest);
738     shortenTime(buf+44, uptime - ptr->start_time_oldest);
739
740     formatName(buf+55, ptr->cfgstyle, ptr->name)[0] = '\0';
741
742     Vwrite(1, buf, strlen(buf));
743     Vwrite(1, "\n", 1);
744   }
745 }
746
747 static void
748 fillName(void *obj_v, void UNUSED * a)
749 {
750   struct XidData *      obj = obj_v;
751
752   switch (obj->xid) {
753     case 0              :
754       obj->cfgstyle = vcCFG_NONE;
755       obj->name     = strdup("root server");
756       break;
757
758     case 1              :
759       obj->cfgstyle = vcCFG_NONE;
760       obj->name     = strdup("monitoring server");
761       break;
762
763     default             : {
764       char *            cfgpath;
765
766       obj->cfgstyle  = vcCFG_AUTO;
767
768       if ((cfgpath   = vc_getVserverByCtx(obj->xid, &obj->cfgstyle, 0))==0 ||
769           (obj->name = vc_getVserverName(cfgpath, obj->cfgstyle))==0) {
770         obj->name     = 0;
771         obj->cfgstyle = vcCFG_NONE;
772       }
773
774       free(cfgpath);
775
776       break;
777     }
778   }
779 }
780
781 static void UNUSED
782 freeXidData(void *obj_v, void UNUSED * a)
783 {
784   struct XidData *      obj = obj_v;
785
786   free(const_cast(char *)(obj->name));
787 }
788
789 int main(int argc, char **argv)
790 {
791   DIR *                 proc_dir;
792   struct dirent*        dir_entry;
793   pid_t                 my_pid;
794   struct Vector         xid_data;
795   char const *          errptr;
796
797   while (1) {
798     int         c = getopt_long(argc, argv, "+O:", CMDLINE_OPTIONS, 0);
799     if (c==-1) break;
800
801     switch (c) {
802       case CMD_HELP     :  showHelp(argv[0]);
803       case CMD_VERSION  :  showVersion();
804       case 'O'          :  break;
805       default           :
806         WRITE_MSG(2, "Try '");
807         WRITE_STR(2, argv[0]);
808         WRITE_MSG(2, " --help' for more information.\n");
809         return EXIT_FAILURE;
810         break;
811     }
812   }
813     
814   if (optind!=argc) {
815     WRITE_MSG(2, "Unknown parameter, use '--help' for more information\n");
816     return EXIT_FAILURE;
817   }
818
819   if (hertz==0x42)    initHertz();
820   if (pagesize==0x42) initPageSize();
821   
822   Vector_init(&xid_data, sizeof(struct XidData));
823
824   if (vc_isSupported(vcFEATURE_VSTAT)) {
825     unsigned long xid;
826     Echdir(PROC_VIRT_DIR_NAME);
827     proc_dir = Eopendir(".");
828     while ((dir_entry = readdir(proc_dir)) != NULL) {
829       if (!isNumberUnsigned(dir_entry->d_name, &xid, false))
830         continue;
831
832       registerXidVstat(&xid_data, xid);
833     }
834     closedir(proc_dir);
835   }
836   else {
837     void (*handler)(struct Vector *vec, struct process_info *process);
838
839     my_pid = getpid();
840
841     if (!switchToWatchXid(&errptr)) {
842       perror(errptr);
843       exit(1);
844     }
845
846     if (access("/proc/uptime",R_OK)==-1 && errno==ENOENT)
847       WRITE_MSG(2,
848               "WARNING: can not access /proc/uptime. Usually, this is caused by\n"
849               "         procfs-security. Please read the FAQ for more details\n"
850               "         http://linux-vserver.org/Proc-Security\n");
851
852     if (vc_isSupported(vcFEATURE_MEMCG))
853       handler = registerXidCgroups;
854     else
855       handler = registerXid;
856
857     Echdir(PROC_DIR_NAME);
858     proc_dir = Eopendir(".");
859     while ((dir_entry = readdir(proc_dir)) != NULL)
860     {
861       // select only process file
862       if (!isdigit(*dir_entry->d_name))
863         continue;
864
865       if (atoi(dir_entry->d_name) != my_pid) {
866         struct process_info *   info = get_process_info(dir_entry->d_name);
867         if (info)
868           handler(&xid_data, info);
869       }
870     }
871     closedir(proc_dir);
872   }
873
874   Vector_foreach(&xid_data, fillName, 0);
875
876     // output the ctx_list      
877   showContexts(&xid_data);
878
879 #ifndef NDEBUG
880   Vector_foreach(&xid_data, freeXidData, 0);
881   Vector_free(&xid_data);
882 #endif
883   
884   return 0;
885 }