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.
28 #include <ensc_vector/vector.h>
35 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/resource.h>
47 #define ENSC_WRAPPERS_DIRENT 1
48 #define ENSC_WRAPPERS_VSERVER 1
49 #define ENSC_WRAPPERS_FCNTL 1
50 #define ENSC_WRAPPERS_UNISTD 1
53 #define PROC_DIR_NAME "/proc"
54 #define PROC_VIRT_DIR_NAME "/proc/virtual"
55 #define CTX_DIR_NAME "/var/run/vservers/"
56 #define CTX_NAME_MAX_LEN 50
58 int wrapper_exit_code = 1;
61 #define AT_CLKTCK 17 /* frequency of times() */
64 static unsigned long hertz =0x42;
65 static unsigned long pagesize=0x42;
70 unsigned int process_count;
71 uint64_t VmSize_total;
73 uint64_t start_time_oldest;
74 uint64_t stime_total, utime_total;
82 long VmSize; // number of pages of virtual memory
83 long VmRSS; // resident set size from /proc/#/stat
84 uint64_t start_time; // start time of process -- milliseconds since 1-1-70
85 uint64_t stime, utime; // kernel & user-mode CPU time accumulated by process
86 uint64_t cstime, cutime; // cumulative time of process and reaped children
91 enum { tpUNSET, tpCTX, tpPID } type;
94 unsigned int interval;
101 #define CMD_HELP 0x1000
102 #define CMD_VERSION 0x1001
105 CMDLINE_OPTIONS[] = {
106 { "help", no_argument, 0, CMD_HELP },
107 { "version", no_argument, 0, CMD_VERSION },
108 { "sort", required_argument, 0, 'O' },
113 showHelp(char const *cmd)
115 WRITE_MSG(1, "Usage: ");
119 "Show informations about all the active context.\n\n"
120 " CTX# Context number\n"
121 " #0 = root context\n"
122 " #1 = monitoring context\n"
123 " PROC QTY Quantity of processes in each context\n"
124 " VSZ Number of pages of virtual memory\n"
125 " RSS Resident set size\n"
126 " userTIME User-mode CPU time accumulated\n"
127 " sysTIME Kernel-mode CPU time accumulated\n"
128 " UPTIME Uptime/context\n"
129 " NAME Virtual server name\n"
138 "vserver-stat " VERSION " -- show virtual context statistics\n"
139 "This program is part of " PACKAGE_STRING "\n\n"
140 "Copyright (C) 2003,2005 Enrico Scholz\n"
141 VERSION_COPYRIGHT_DISCLAIMER);
146 // return uptime (in ms) from /proc/uptime
157 // open the /proc/uptime file
158 fd = EopenD("/proc/uptime", O_RDONLY, 0);
159 len = Eread(fd, buffer, sizeof buffer);
161 if (len==sizeof(buffer)) {
162 WRITE_MSG(2, "Too much data in /proc/uptime; aborting...\n");
167 while (len>0 && buffer[len-1]=='\n') --len;
170 secs = strtol(buffer, &errptr, 10);
171 if (*errptr!='.') errptr = buffer;
174 switch (strlen(errptr+1)) {
175 case 0 : mult = 1000; break;
176 case 1 : mult = 100; break;
177 case 2 : mult = 10; break;
178 case 3 : mult = 1; break;
179 default : mult = 0; break;
181 msecs = strtol(errptr+1, &errptr, 10) * mult;
184 if ((*errptr!='\0' && *errptr!=' ') || errptr==buffer) {
185 WRITE_MSG(2, "Bad data in /proc/uptime\n");
189 return secs*1000 + msecs;
193 cmpData(void const *xid_v, void const *map_v)
195 xid_t const * const xid = xid_v;
196 struct XidData const * const map = map_v;
197 int res = *xid - map->xid;
203 registerXid(struct Vector *vec, struct process_info *process)
207 res = Vector_search(vec, &process->s_context, cmpData);
209 res = Vector_insert(vec, &process->s_context, cmpData);
210 res->xid = process->s_context;
211 res->process_count = 0;
212 res->VmSize_total = 0;
213 res->VmRSS_total = 0;
214 res->utime_total = 0;
215 res->stime_total = 0;
216 res->start_time_oldest = process->start_time;
219 ++res->process_count;
220 res->VmSize_total += process->VmSize;
221 res->VmRSS_total += process->VmRSS;
222 res->utime_total += process->utime + process->cutime;
223 res->stime_total += process->stime + process->cstime;
225 res->start_time_oldest = MIN(res->start_time_oldest, process->start_time);
229 registerXidVstat(struct Vector *vec, unsigned long xid_l)
231 xid_t xid = (xid_t) xid_l;
233 struct vc_rlimit_stat limit[3];
234 struct vc_virt_stat vstat;
235 struct vc_sched_info sched;
238 res = Vector_search(vec, &xid, cmpData);
240 WRITE_MSG(2, "Duplicate xid found?!\n");
243 if (vc_virt_stat(xid, &vstat) == -1) {
244 perror("vc_virt_stat()");
247 if (vc_rlimit_stat(xid, RLIMIT_NPROC, &limit[0]) == -1) {
248 perror("vc_rlimit_stat(RLIMIT_NRPOC)");
251 if (vc_rlimit_stat(xid, RLIMIT_AS, &limit[1]) == -1) {
252 perror("vc_rlimit_stat(RLIMIT_AS)");
255 if (vc_rlimit_stat(xid, RLIMIT_RSS, &limit[2]) == -1) {
256 perror("vc_rlimit_stat(RLIMIT_RSS)");
260 res = Vector_insert(vec, &xid, cmpData);
263 res->process_count = limit[0].value;
264 res->VmSize_total = limit[1].value * pagesize;
265 res->VmRSS_total = limit[2].value;
266 res->start_time_oldest= getUptime() - vstat.uptime/1000000;
268 res->utime_total = 0;
269 res->stime_total = 0;
270 // XXX: arbitrary CPU limit.
271 for (cpu = 0; cpu < 1024; cpu++) {
274 if (vc_sched_info(xid, &sched) == -1)
277 res->utime_total += sched.user_msec;
278 res->stime_total += sched.sys_msec;
282 static inline uint64_t
285 return v*1000llu/hertz;
289 // shamelessly stolen from procps...
291 find_elf_note(unsigned long findme){
292 unsigned long *ep = (unsigned long *)environ;
295 if(ep[0]==findme) return ep[1];
298 return (unsigned long)(-1);
301 static void initHertz() __attribute__((__constructor__));
302 static void initPageSize() __attribute__((__constructor__));
307 hertz = find_elf_note(AT_CLKTCK);
308 if (hertz==(unsigned long)(-1))
309 hertz = sysconf(_SC_CLK_TCK);
315 pagesize = sysconf(_SC_PAGESIZE);
318 // open the process's status file to get the ctx number, and other stat
319 struct process_info *
320 get_process_info(char *pid)
325 size_t idx, l=strlen(pid);
326 static struct process_info process;
329 process.s_context = vc_get_task_xid(atoi(pid));
331 # warning Compiling in debug-code
332 process.s_context = random()%6;
335 if (process.s_context==VC_NOCTX) {
337 WRITE_MSG(2, "vc_get_task_xid(");
340 WRITE_STR(2, strerror(err));
346 memcpy(buffer, "/proc/", 6); idx = 6;
347 memcpy(buffer+idx, pid, l); idx += l;
348 memcpy(buffer+idx, "/stat", 6);
350 // open the /proc/#/stat file
351 if ((fd = open(buffer, O_RDONLY, 0)) == -1)
353 // put the file in a buffer
354 if (read(fd, buffer, sizeof(buffer)) < 1)
359 p = strchr(buffer, ')'); // go after the PID (process_name)
360 for (idx = 0; idx<12 && *p!='\0'; ++p)
361 if ((*p)==' ') ++idx;
363 process.utime = toMsec(strtol(p, &p, 10));
364 process.stime = toMsec(strtol(p+1, &p, 10));
365 process.cutime = toMsec(strtol(p+1, &p, 10));
366 process.cstime = toMsec(strtol(p+1, &p, 10));
368 for (idx = 0; idx<5 && *p!='\0'; ++p)
369 if ((*p)==' ') ++idx;
371 process.start_time = toMsec(strtol(p, &p, 10));
372 process.VmSize = strtol(p+1, &p, 10);
373 process.VmRSS = strtol(p+1, &p, 10);
375 //printf("pid=%s, start_time=%llu\n", pid, process.start_time);
380 fillUintZero(char *buf, unsigned long val, size_t cnt)
384 l = utilvserver_fmt_ulong(buf, val);
386 memmove(buf+cnt-l, buf, l);
387 memset(buf, '0', cnt-l);
395 shortenMem(char *buf, unsigned long val)
397 char const * SUFFIXES[] = { " ", "K", "M", "G", "T", "+" };
399 char const * suffix = "+";
401 unsigned int mod = 0;
403 for (i=0; i<6; ++i) {
405 suffix = SUFFIXES[i];
408 mod = 10*(val & 1023)/1024;
412 if (val >9999) val=9999;
413 if (val>=1000) mod=0;
415 l = utilvserver_fmt_ulong(tmp, val);
418 l += utilvserver_fmt_ulong(tmp+l, mod);
420 i = 7-l-strlen(suffix);
422 memcpy(buf+i, tmp, l);
423 memcpy(buf+i+l, suffix, strlen(suffix));
427 shortenTime(char *buf, uint64_t t)
432 unsigned long hh, mm, ss, ms;
445 memcpy(ptr, "INVALID", 7);
449 ptr += utilvserver_fmt_ulong(ptr, t/365);
451 ptr += fillUintZero(ptr, t%365, 2);
453 ptr += fillUintZero(ptr, hh, 2);
456 ptr += utilvserver_fmt_ulong(ptr, t);
458 ptr += fillUintZero(ptr, hh, 2);
460 ptr += fillUintZero(ptr, mm, 2);
463 ptr += utilvserver_fmt_ulong(ptr, hh);
465 ptr += fillUintZero(ptr, mm, 2);
467 ptr += fillUintZero(ptr, ss, 2);
470 ptr += utilvserver_fmt_ulong(ptr, mm);
472 ptr += fillUintZero(ptr, ss, 2);
474 ptr += fillUintZero(ptr, ms, 2);
478 memcpy(buf+10-(ptr-tmp), tmp, ptr-tmp);
482 formatName(char *dst, vcCfgStyle style, char const *name)
486 if (name==0) name = "";
493 memcpy(dst, name, len);
500 memcpy(dst, name, len);
509 showContexts(struct Vector const *vec)
511 uint64_t uptime = getUptime();
512 struct XidData const * ptr = Vector_begin_const(vec);
513 struct XidData const * const end_ptr = Vector_end_const(vec);
516 WRITE_MSG(1, "CTX PROC VSZ RSS userTIME sysTIME UPTIME NAME\n");
517 for (; ptr<end_ptr; ++ptr) {
518 char buf[sizeof(xid_t)*3 + 512];
519 char tmp[sizeof(int)*3 + 2];
522 memset(buf, ' ', sizeof(buf));
523 l = utilvserver_fmt_long(buf, ptr->xid);
524 l = utilvserver_fmt_long(tmp, ptr->process_count);
525 memcpy(buf+10-l, tmp, l);
527 shortenMem (buf+10, ptr->VmSize_total);
528 shortenMem (buf+17, ptr->VmRSS_total*pagesize);
529 shortenTime(buf+24, ptr->utime_total);
530 shortenTime(buf+34, ptr->stime_total);
531 //printf("%llu, %llu\n", uptime, ptr->start_time_oldest);
532 shortenTime(buf+44, uptime - ptr->start_time_oldest);
534 formatName(buf+55, ptr->cfgstyle, ptr->name)[0] = '\0';
536 Vwrite(1, buf, strlen(buf));
542 fillName(void *obj_v, void UNUSED * a)
544 struct XidData * obj = obj_v;
548 obj->cfgstyle = vcCFG_NONE;
549 obj->name = strdup("root server");
553 obj->cfgstyle = vcCFG_NONE;
554 obj->name = strdup("monitoring server");
560 obj->cfgstyle = vcCFG_AUTO;
562 if ((cfgpath = vc_getVserverByCtx(obj->xid, &obj->cfgstyle, 0))==0 ||
563 (obj->name = vc_getVserverName(cfgpath, obj->cfgstyle))==0) {
565 obj->cfgstyle = vcCFG_NONE;
576 freeXidData(void *obj_v, void UNUSED * a)
578 struct XidData * obj = obj_v;
580 free(const_cast(char *)(obj->name));
583 int main(int argc, char **argv)
586 struct dirent* dir_entry;
588 struct Vector xid_data;
592 int c = getopt_long(argc, argv, "+O:", CMDLINE_OPTIONS, 0);
596 case CMD_HELP : showHelp(argv[0]);
597 case CMD_VERSION : showVersion();
600 WRITE_MSG(2, "Try '");
601 WRITE_STR(2, argv[0]);
602 WRITE_MSG(2, " --help' for more information.\n");
609 WRITE_MSG(2, "Unknown parameter, use '--help' for more information\n");
613 if (hertz==0x42) initHertz();
614 if (pagesize==0x42) initPageSize();
616 Vector_init(&xid_data, sizeof(struct XidData));
618 if (vc_isSupported(vcFEATURE_VSTAT)) {
620 Echdir(PROC_VIRT_DIR_NAME);
621 proc_dir = Eopendir(".");
622 while ((dir_entry = readdir(proc_dir)) != NULL) {
623 if (!isNumberUnsigned(dir_entry->d_name, &xid, false))
626 registerXidVstat(&xid_data, xid);
633 if (!switchToWatchXid(&errptr)) {
638 if (access("/proc/uptime",R_OK)==-1 && errno==ENOENT)
640 "WARNING: can not access /proc/uptime. Usually, this is caused by\n"
641 " procfs-security. Please read the FAQ for more details\n"
642 " http://linux-vserver.org/Proc-Security\n");
644 Echdir(PROC_DIR_NAME);
645 proc_dir = Eopendir(".");
646 while ((dir_entry = readdir(proc_dir)) != NULL)
648 // select only process file
649 if (!isdigit(*dir_entry->d_name))
652 if (atoi(dir_entry->d_name) != my_pid) {
653 struct process_info * info = get_process_info(dir_entry->d_name);
655 registerXid(&xid_data, info);
661 Vector_foreach(&xid_data, fillName, 0);
663 // output the ctx_list
664 showContexts(&xid_data);
667 Vector_foreach(&xid_data, freeXidData, 0);
668 Vector_free(&xid_data);