3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 // based on vserver-stat.cc by Guillaum Dallaire and Jacques Gelinas
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)
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.
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.
27 #include "pathconfig.h"
29 #include <ensc_vector/vector.h>
36 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/resource.h>
48 #define ENSC_WRAPPERS_DIRENT 1
49 #define ENSC_WRAPPERS_VSERVER 1
50 #define ENSC_WRAPPERS_FCNTL 1
51 #define ENSC_WRAPPERS_UNISTD 1
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
59 int wrapper_exit_code = 1;
62 #define AT_CLKTCK 17 /* frequency of times() */
65 static unsigned long hertz =0x42;
66 static unsigned long pagesize=0x42;
71 unsigned int process_count;
72 uint64_t VmSize_total;
74 uint64_t start_time_oldest;
75 uint64_t stime_total, utime_total;
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
92 enum { tpUNSET, tpCTX, tpPID } type;
95 unsigned int interval;
102 #define CMD_HELP 0x1000
103 #define CMD_VERSION 0x1001
106 CMDLINE_OPTIONS[] = {
107 { "help", no_argument, 0, CMD_HELP },
108 { "version", no_argument, 0, CMD_VERSION },
109 { "sort", required_argument, 0, 'O' },
114 showHelp(char const *cmd)
116 WRITE_MSG(1, "Usage: ");
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"
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);
147 // return uptime (in ms) from /proc/uptime
158 // open the /proc/uptime file
159 fd = EopenD("/proc/uptime", O_RDONLY, 0);
160 len = Eread(fd, buffer, sizeof buffer);
162 if (len==sizeof(buffer)) {
163 WRITE_MSG(2, "Too much data in /proc/uptime; aborting...\n");
168 while (len>0 && buffer[len-1]=='\n') --len;
171 secs = strtol(buffer, &errptr, 10);
172 if (*errptr!='.') errptr = buffer;
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;
182 msecs = strtol(errptr+1, &errptr, 10) * mult;
185 if ((*errptr!='\0' && *errptr!=' ') || errptr==buffer) {
186 WRITE_MSG(2, "Bad data in /proc/uptime\n");
190 return secs*1000 + msecs;
194 cmpData(void const *xid_v, void const *map_v)
196 xid_t const * const xid = xid_v;
197 struct XidData const * const map = map_v;
198 int res = *xid - map->xid;
204 registerXid(struct Vector *vec, struct process_info *process)
208 res = Vector_search(vec, &process->s_context, cmpData);
210 res = Vector_insert(vec, &process->s_context, cmpData);
211 res->xid = process->s_context;
212 res->process_count = 0;
213 res->VmSize_total = 0;
214 res->VmRSS_total = 0;
215 res->utime_total = 0;
216 res->stime_total = 0;
217 res->start_time_oldest = process->start_time;
220 ++res->process_count;
221 res->VmSize_total += process->VmSize;
222 res->VmRSS_total += process->VmRSS;
223 res->utime_total += process->utime + process->cutime;
224 res->stime_total += process->stime + process->cstime;
226 res->start_time_oldest = MIN(res->start_time_oldest, process->start_time);
230 registerXidVstat(struct Vector *vec, unsigned long xid_l)
232 xid_t xid = (xid_t) xid_l;
234 struct vc_rlimit_stat limit[3];
235 struct vc_virt_stat vstat;
236 struct vc_sched_info sched;
239 res = Vector_search(vec, &xid, cmpData);
241 WRITE_MSG(2, "Duplicate xid found?!\n");
244 if (vc_virt_stat(xid, &vstat) == -1) {
245 perror("vc_virt_stat()");
248 if (vc_rlimit_stat(xid, RLIMIT_NPROC, &limit[0]) == -1) {
249 perror("vc_rlimit_stat(RLIMIT_NRPOC)");
252 if (vc_rlimit_stat(xid, RLIMIT_AS, &limit[1]) == -1) {
253 perror("vc_rlimit_stat(RLIMIT_AS)");
256 if (vc_rlimit_stat(xid, RLIMIT_RSS, &limit[2]) == -1) {
257 perror("vc_rlimit_stat(RLIMIT_RSS)");
261 res = Vector_insert(vec, &xid, cmpData);
264 res->process_count = limit[0].value;
265 res->VmSize_total = limit[1].value * pagesize;
266 res->VmRSS_total = limit[2].value;
267 res->start_time_oldest= getUptime() - vstat.uptime/1000000;
269 res->utime_total = 0;
270 res->stime_total = 0;
271 // XXX: arbitrary CPU limit.
272 for (cpu = 0; cpu < 1024; cpu++) {
275 if (vc_sched_info(xid, &sched) == -1)
278 res->utime_total += sched.user_msec;
279 res->stime_total += sched.sys_msec;
284 registerXidCgroups(struct Vector *vec, struct process_info *process)
286 xid_t xid = (xid_t) process->s_context;
289 switch (vc_getXIDType(xid)) {
297 res = Vector_search(vec, &xid, cmpData);
299 struct vc_rlimit_stat limit;
300 struct vc_virt_stat vstat;
301 struct vc_sched_info sched;
309 unsigned long long rss;
313 if (vc_virt_stat(xid, &vstat) == -1) {
314 perror("vc_virt_stat()");
317 if (vc_rlimit_stat(xid, RLIMIT_NPROC, &limit) == -1) {
318 perror("vc_rlimit_stat(RLIMIT_NRPOC)");
321 if (vc_get_vhi_name(xid, vcVHI_CONTEXT, vhi_name, sizeof(vhi_name)) == -1) {
322 perror("vc_get_vhi_name(CONTEXT)");
326 if ((fd = open(DEFAULTCONFDIR "/cgroup/mnt", O_RDONLY)) == -1) {
327 strcpy(cgroup, "/dev/cgroup/");
328 cgroup_len = sizeof("/dev/cgroup");
331 cgroup_len = read(fd, cgroup, sizeof(cgroup));
332 if (cgroup_len == -1) {
333 perror("read(cgroup/mnt)");
337 cgroup[cgroup_len] = '/';
339 cgroup[cgroup_len] = 0;
342 len = strlen(vhi_name);
343 if ((len + sizeof("/cgroup/name")) >= sizeof(filename)) {
344 WRITE_MSG(2, "too long context name: ");
345 WRITE_STR(2, vhi_name);
349 strcpy(filename, vhi_name);
350 strcpy(filename + len, "/cgroup/name");
352 if ((fd = open(filename, O_RDONLY)) == -1) {
353 char *dir = strrchr(vhi_name, '/');
355 WRITE_MSG(2, "invalid context name: ");
361 if ((len + cgroup_len) >= sizeof(cgroup)) {
362 WRITE_MSG(2, "cgroup name too long: ");
367 strcpy(cgroup + cgroup_len, dir);
372 ret = read(fd, cgroup + cgroup_len, sizeof(cgroup) - cgroup_len);
374 perror("read(cgroup/name)");
381 if ((cgroup_len + sizeof("/memory.usage_in_bytes")) > sizeof(filename)) {
382 WRITE_MSG(2, "cgroup name too long: ");
383 WRITE_STR(2, cgroup);
387 strcpy(filename, cgroup);
388 strcpy(filename + cgroup_len, "/memory.usage_in_bytes");
390 if ((fd = open(filename, O_RDONLY)) == -1) {
391 perror("open(memory.usage_in_bytes)");
394 if (read(fd, buf, sizeof(buf)) == -1) {
395 perror("read(memory.usage_in_bytes)");
399 if ((rss = strtoull(buf, &endptr, 0)) == ULLONG_MAX ||
400 (*endptr != '\n' && *endptr != '\0')) {
401 perror("strtoull(memory.usage_in_bytes)");
405 res = Vector_insert(vec, &xid, cmpData);
408 res->process_count = limit.value;
409 res->VmRSS_total = rss / 4096;
410 res->start_time_oldest= getUptime() - vstat.uptime/1000000;
412 res->utime_total = 0;
413 res->stime_total = 0;
414 // XXX: arbitrary CPU limit.
415 for (cpu = 0; cpu < 1024; cpu++) {
418 if (vc_sched_info(xid, &sched) == -1)
421 res->utime_total += sched.user_msec;
422 res->stime_total += sched.sys_msec;
426 res->VmSize_total += process->VmSize;
429 static inline uint64_t
432 return v*1000llu/hertz;
436 // shamelessly stolen from procps...
438 find_elf_note(unsigned long findme){
439 unsigned long *ep = (unsigned long *)environ;
442 if(ep[0]==findme) return ep[1];
445 return (unsigned long)(-1);
448 static void initHertz() __attribute__((__constructor__));
449 static void initPageSize() __attribute__((__constructor__));
454 hertz = find_elf_note(AT_CLKTCK);
455 if (hertz==(unsigned long)(-1))
456 hertz = sysconf(_SC_CLK_TCK);
462 pagesize = sysconf(_SC_PAGESIZE);
465 // open the process's status file to get the ctx number, and other stat
466 struct process_info *
467 get_process_info(char *pid)
472 size_t idx, l=strlen(pid);
473 static struct process_info process;
476 process.s_context = vc_get_task_xid(atoi(pid));
478 # warning Compiling in debug-code
479 process.s_context = random()%6;
482 if (process.s_context==VC_NOCTX) {
484 WRITE_MSG(2, "vc_get_task_xid(");
487 WRITE_STR(2, strerror(err));
493 memcpy(buffer, "/proc/", 6); idx = 6;
494 memcpy(buffer+idx, pid, l); idx += l;
495 memcpy(buffer+idx, "/stat", 6);
497 // open the /proc/#/stat file
498 if ((fd = open(buffer, O_RDONLY, 0)) == -1)
500 // put the file in a buffer
501 if (read(fd, buffer, sizeof(buffer)) < 1)
506 p = strchr(buffer, ')'); // go after the PID (process_name)
507 for (idx = 0; idx<12 && *p!='\0'; ++p)
508 if ((*p)==' ') ++idx;
510 process.utime = toMsec(strtol(p, &p, 10));
511 process.stime = toMsec(strtol(p+1, &p, 10));
512 process.cutime = toMsec(strtol(p+1, &p, 10));
513 process.cstime = toMsec(strtol(p+1, &p, 10));
515 for (idx = 0; idx<5 && *p!='\0'; ++p)
516 if ((*p)==' ') ++idx;
518 process.start_time = toMsec(strtol(p, &p, 10));
519 process.VmSize = strtol(p+1, &p, 10);
520 process.VmRSS = strtol(p+1, &p, 10);
522 //printf("pid=%s, start_time=%llu\n", pid, process.start_time);
527 fillUintZero(char *buf, unsigned long val, size_t cnt)
531 l = utilvserver_fmt_ulong(buf, val);
533 memmove(buf+cnt-l, buf, l);
534 memset(buf, '0', cnt-l);
542 shortenMem(char *buf, unsigned long val)
544 char const * SUFFIXES[] = { " ", "K", "M", "G", "T", "+" };
546 char const * suffix = "+";
548 unsigned int mod = 0;
550 for (i=0; i<6; ++i) {
552 suffix = SUFFIXES[i];
555 mod = 10*(val & 1023)/1024;
559 if (val >9999) val=9999;
560 if (val>=1000) mod=0;
562 l = utilvserver_fmt_ulong(tmp, val);
565 l += utilvserver_fmt_ulong(tmp+l, mod);
567 i = 7-l-strlen(suffix);
569 memcpy(buf+i, tmp, l);
570 memcpy(buf+i+l, suffix, strlen(suffix));
574 shortenTime(char *buf, uint64_t t)
579 unsigned long hh, mm, ss, ms;
592 memcpy(ptr, "INVALID", 7);
596 ptr += utilvserver_fmt_ulong(ptr, t/365);
598 ptr += fillUintZero(ptr, t%365, 2);
600 ptr += fillUintZero(ptr, hh, 2);
603 ptr += utilvserver_fmt_ulong(ptr, t);
605 ptr += fillUintZero(ptr, hh, 2);
607 ptr += fillUintZero(ptr, mm, 2);
610 ptr += utilvserver_fmt_ulong(ptr, hh);
612 ptr += fillUintZero(ptr, mm, 2);
614 ptr += fillUintZero(ptr, ss, 2);
617 ptr += utilvserver_fmt_ulong(ptr, mm);
619 ptr += fillUintZero(ptr, ss, 2);
621 ptr += fillUintZero(ptr, ms, 2);
625 memcpy(buf+10-(ptr-tmp), tmp, ptr-tmp);
629 formatName(char *dst, vcCfgStyle style, char const *name)
633 if (name==0) name = "";
640 memcpy(dst, name, len);
647 memcpy(dst, name, len);
656 showContexts(struct Vector const *vec)
658 uint64_t uptime = getUptime();
659 struct XidData const * ptr = Vector_begin_const(vec);
660 struct XidData const * const end_ptr = Vector_end_const(vec);
663 WRITE_MSG(1, "CTX PROC VSZ RSS userTIME sysTIME UPTIME NAME\n");
664 for (; ptr<end_ptr; ++ptr) {
665 char buf[sizeof(xid_t)*3 + 512];
666 char tmp[sizeof(int)*3 + 2];
669 memset(buf, ' ', sizeof(buf));
670 l = utilvserver_fmt_long(buf, ptr->xid);
671 l = utilvserver_fmt_long(tmp, ptr->process_count);
672 memcpy(buf+10-l, tmp, l);
674 shortenMem (buf+10, ptr->VmSize_total);
675 shortenMem (buf+17, ptr->VmRSS_total*pagesize);
676 shortenTime(buf+24, ptr->utime_total);
677 shortenTime(buf+34, ptr->stime_total);
678 //printf("%llu, %llu\n", uptime, ptr->start_time_oldest);
679 shortenTime(buf+44, uptime - ptr->start_time_oldest);
681 formatName(buf+55, ptr->cfgstyle, ptr->name)[0] = '\0';
683 Vwrite(1, buf, strlen(buf));
689 fillName(void *obj_v, void UNUSED * a)
691 struct XidData * obj = obj_v;
695 obj->cfgstyle = vcCFG_NONE;
696 obj->name = strdup("root server");
700 obj->cfgstyle = vcCFG_NONE;
701 obj->name = strdup("monitoring server");
707 obj->cfgstyle = vcCFG_AUTO;
709 if ((cfgpath = vc_getVserverByCtx(obj->xid, &obj->cfgstyle, 0))==0 ||
710 (obj->name = vc_getVserverName(cfgpath, obj->cfgstyle))==0) {
712 obj->cfgstyle = vcCFG_NONE;
723 freeXidData(void *obj_v, void UNUSED * a)
725 struct XidData * obj = obj_v;
727 free(const_cast(char *)(obj->name));
730 int main(int argc, char **argv)
733 struct dirent* dir_entry;
735 struct Vector xid_data;
739 int c = getopt_long(argc, argv, "+O:", CMDLINE_OPTIONS, 0);
743 case CMD_HELP : showHelp(argv[0]);
744 case CMD_VERSION : showVersion();
747 WRITE_MSG(2, "Try '");
748 WRITE_STR(2, argv[0]);
749 WRITE_MSG(2, " --help' for more information.\n");
756 WRITE_MSG(2, "Unknown parameter, use '--help' for more information\n");
760 if (hertz==0x42) initHertz();
761 if (pagesize==0x42) initPageSize();
763 Vector_init(&xid_data, sizeof(struct XidData));
765 if (vc_isSupported(vcFEATURE_VSTAT)) {
767 Echdir(PROC_VIRT_DIR_NAME);
768 proc_dir = Eopendir(".");
769 while ((dir_entry = readdir(proc_dir)) != NULL) {
770 if (!isNumberUnsigned(dir_entry->d_name, &xid, false))
773 registerXidVstat(&xid_data, xid);
778 void (*handler)(struct Vector *vec, struct process_info *process);
782 if (!switchToWatchXid(&errptr)) {
787 if (access("/proc/uptime",R_OK)==-1 && errno==ENOENT)
789 "WARNING: can not access /proc/uptime. Usually, this is caused by\n"
790 " procfs-security. Please read the FAQ for more details\n"
791 " http://linux-vserver.org/Proc-Security\n");
793 if (vc_isSupported(vcFEATURE_MEMCG))
794 handler = registerXidCgroups;
796 handler = registerXid;
798 Echdir(PROC_DIR_NAME);
799 proc_dir = Eopendir(".");
800 while ((dir_entry = readdir(proc_dir)) != NULL)
802 // select only process file
803 if (!isdigit(*dir_entry->d_name))
806 if (atoi(dir_entry->d_name) != my_pid) {
807 struct process_info * info = get_process_info(dir_entry->d_name);
809 handler(&xid_data, info);
815 Vector_foreach(&xid_data, fillName, 0);
817 // output the ctx_list
818 showContexts(&xid_data);
821 Vector_foreach(&xid_data, freeXidData, 0);
822 Vector_free(&xid_data);