From 9119c3d4eda96829b1736f16e51d2f37e4d77824 Mon Sep 17 00:00:00 2001 From: Zhang Qiang Date: Fri, 1 Jun 2012 14:59:52 +0800 Subject: [PATCH] Sync code from Tizen:Mobile --- COPYING | 341 +++++++++++++++ Makefile | 39 ++ README | 82 ++++ bootchart.c | 306 +++++++++++++ bootchart.h | 113 +++++ bootchartd.conf.example | 83 ++++ log.c | 380 ++++++++++++++++ packaging/bootchart.spec | 33 ++ svg.c | 1076 ++++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 2453 insertions(+) create mode 100644 COPYING create mode 100644 Makefile create mode 100644 README create mode 100644 bootchart.c create mode 100644 bootchart.h create mode 100644 bootchartd.conf.example create mode 100644 log.c create mode 100644 packaging/bootchart.spec create mode 100644 svg.c diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..10828e0 --- /dev/null +++ b/COPYING @@ -0,0 +1,341 @@ + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..566a848 --- /dev/null +++ b/Makefile @@ -0,0 +1,39 @@ + +VERSION = 1.15 + +CC := gcc + +all: bootchartd + +install: bootchartd + mkdir -p $(DESTDIR)/sbin + mkdir -p $(DESTDIR)/etc + mkdir -p $(DESTDIR)/usr/share/doc/bootchart/ + install -m0755 bootchartd $(DESTDIR)/sbin/ + install -m0644 bootchartd.conf.example $(DESTDIR)/usr/share/doc/bootchart/ + install -m0644 README COPYING $(DESTDIR)/usr/share/doc/bootchart/ + +OBJS := log.o svg.o bootchart.o + +CFLAGS += -Wall -W -Os -g -fstack-protector -D_FORTIFY_SOURCE=2 -Wformat -fno-common \ + -Wimplicit-function-declaration -Wimplicit-int -fstack-protector \ + -DBOOTCHARTVERSION=\"v$(VERSION)\" + +LDADD += -lrt + +%.o: %.c Makefile bootchart.h + @echo " CC $<" + @$(CC) $(CFLAGS) -c -o $@ $< + +bootchartd: $(OBJS) Makefile + @echo " LD $@" + @$(CC) -o $@ $(OBJS) $(LDADD) $(LDFLAGS) + +clean: + rm -rf *.o *~ bootchartd + +dist: + git tag v$(VERSION) + git archive --format=tar --prefix="bootchart-$(VERSION)/" v$(VERSION) | \ + gzip > bootchart-$(VERSION).tar.gz + diff --git a/README b/README new file mode 100644 index 0000000..fa1d730 --- /dev/null +++ b/README @@ -0,0 +1,82 @@ + +Bootchart - a 'startup' graphing tool + +-- + +Bootchart is a tool, usually run at system startup, that collects and graphs +the CPU and disk load of the system as it works. The output of bootchart is +an SVG graph. Normally, bootchart is invoked as `bootchartd` by the kernel +by passing "init=/sbin/bootchartd" to the kernel. Bootchart will then fork +init off to resume normal system startup, while monitoring and logging +startup information in the background. + +After collecting a certain amount of data (usually 15-30 seconds) the logging +stops and a graph is generated from the logged information. This graph +contains vital clues to which resources are being used, in which order, and +where possible problems exist in the startup sequence of the system. + +Of course, bootchart can also be used at any moment in time to collect and +graph some data for an amount of time. Bootchart does not even require root +privileges to do so, and will happily run as a normal user. Bootchart graphs +are by default written time-stamped in /var/log. + +-- + +This version of bootchart was implemented from scratch and inspired by former +incantations of bootchart: + +- The original bash/shell code implemented bootchart. This version logged all +data into a compressed tarball for later processing, and did not create a graph +on it's own. + +- The C-code implementation found in Ubuntu. This version replaced above shell +code version with a faster and efficient data logger, but still did not graph +code itself. + +- the original Java-based bootchart, the original graphing program that created +a bootchart graph from logged data. + +- the pybootchartgui.py program, which created a graph based on the data logged +by either standalone data logger. + +The version you are looking at combines these 2 parts into a single program, +which makes running it and creating graphs a bit more efficient and simple. +You can now run a single program at startup instead of 2. There are no timing +problems (the graphing stage will never run if the logging stage didn't +finish). The logged data isn't being written to disc first, then read again. +Also, the data kept in memory is reduced to the absolute minimum needed to +keep memory use low. + +-- + +Requirements: glibc. Your kernel must have procfs support and several +proc output options enabled: + CONFIG_PROC_FS + CONFIG_SCHEDSTATS + CONFIG_SCHED_DEBUG +at a minimum. bootchartd itself does not require any graphics library +to generate the SVG output file. + +-- + +Configuration: please see bootchartd --help, as well as /etc/bootchartd.conf +and/or /usr/share/doc/bootchart/bootchartd.conf.example for a list of +configurable options. + +-- + +Many thanks to those who contributed ideas and code: + - Ziga Mahkovec - Original bootchart author + - Anders Norgaard - PyBootchartgui + - Michael Meeks - bootchart2 + - Scott James Remnant - Ubuntu C-based logger + - Arjan van der Ven - for the idea to merge bootgraph.pl functionality + +-- + +For bugs, please contact the author or current maintainer: +Auke Kok + +-- + +Download bootchart releases here: http://foo-projects.org/~sofar/bootchart/ diff --git a/bootchart.c b/bootchart.c new file mode 100644 index 0000000..1adfa1c --- /dev/null +++ b/bootchart.c @@ -0,0 +1,306 @@ +/* + * bootchart.c + * + * Copyright (c) 2009 Intel Coproration + * Authors: + * Auke Kok + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "bootchart.h" + +double graph_start; +double log_start; +double sampletime[MAXSAMPLES]; +struct ps_struct *ps[MAXPIDS]; /* ll */ +struct block_stat_struct blockstat[MAXSAMPLES]; +struct cpu_stat_struct cpustat[MAXCPUS]; +int pscount; +int cpus; +double interval; +FILE *of; +int overrun = 0; +static int exiting = 0; + +/* graph defaults */ +int initcall = 1; +int relative; +int filter = 1; +int pss = 0; +int samples; +int len = 500; /* we record len+1 (1 start sample) */ +int hz = 25; /* 20 seconds log time */ +int scale_x = 100; /* 100px = 1sec */ +int scale_y = 20; /* 16px = 1 process bar */ + +char init_path[PATH_MAX] = "/sbin/init"; +char output_path[PATH_MAX] = "/var/log"; + +static struct rlimit rlim; + +static void signal_handler(int sig) +{ + if (sig++) + sig--; + exiting = 1; +} + + +int main(int argc, char *argv[]) +{ + struct sigaction sig; + char output_file[PATH_MAX]; + char datestr[200]; + time_t t; + FILE *f; + int i; + + memset(&t, 0, sizeof(time_t)); + + rlim.rlim_cur = 4096; + rlim.rlim_max = 4096; + (void) setrlimit(RLIMIT_NOFILE, &rlim); + + f = fopen("/etc/bootchartd.conf", "r"); + if (f) { + char buf[256]; + char *key; + char *val; + + while (fgets(buf, 80, f) != NULL) { + char *c; + + c = strchr(buf, '\n'); + if (c) *c = 0; /* remove trailing \n */ + + if (buf[0] == '#') + continue; /* comment line */ + + key = strtok(buf, "="); + if (!key) + continue; + val = strtok(NULL, "="); + if (!val) + continue; + + // todo: filter leading/trailing whitespace + + if (!strcmp(key, "samples")) + len = atoi(val); + if (!strcmp(key, "freq")) + hz = atoi(val); + if (!strcmp(key, "rel")) + relative = atoi(val); + if (!strcmp(key, "filter")) + filter = atoi(val); + if (!strcmp(key, "pss")) + pss = atoi(val); + if (!strcmp(key, "output")) + strncpy(output_path, val, PATH_MAX - 1); + if (!strcmp(key, "init")) + strncpy(init_path, val, PATH_MAX - 1); + if (!strcmp(key, "scale_x")) + scale_x = atoi(val); + if (!strcmp(key, "scale_y")) + scale_y = atoi(val); + } + fclose(f); + } + + while (1) { + static struct option opts[] = { + {"rel", 0, NULL, 'r'}, + {"freq", 1, NULL, 'f'}, + {"samples", 1, NULL, 'n'}, + {"pss", 0, NULL, 'p'}, + {"output", 1, NULL, 'o'}, + {"init", 1, NULL, 'i'}, + {"filter", 0, NULL, 'F'}, + {"help", 0, NULL, 'h'}, + {"scale-x", 1, NULL, 'x'}, + {"scale-y", 1, NULL, 'y'}, + {NULL, 0, NULL, 0} + }; + + int index = 0, c; + + c = getopt_long(argc, argv, "rpf:n:o:i:Fhx:y:", opts, &index); + if (c == -1) + break; + switch (c) { + case 'r': + relative = 1; + break; + case 'f': + hz = atoi(optarg); + break; + case 'F': + filter = 0; + break; + case 'n': + len = atoi(optarg); + break; + case 'o': + strncpy(output_path, optarg, PATH_MAX - 1); + break; + case 'i': + strncpy(init_path, optarg, PATH_MAX - 1); + break; + case 'p': + pss = 1; + break; + case 'x': + scale_x = atoi(optarg); + break; + case 'y': + scale_y = atoi(optarg); + break; + case 'h': + fprintf(stderr, "Usage: %s [OPTIONS]\n", argv[0]); + fprintf(stderr, " --rel, -r Record time relative to recording\n"); + fprintf(stderr, " --freq, -f N Sample frequency [%d]\n", hz); + fprintf(stderr, " --samples, -n N Stop sampling at [%d] samples\n", len); + fprintf(stderr, " --scale-x, -x N Scale the graph horizontally [%d] \n", scale_x); + fprintf(stderr, " --scale-y, -y N Scale the graph vertically [%d] \n", scale_y); + fprintf(stderr, " --pss, -p Enable PSS graph (CPU intensive)\n"); + fprintf(stderr, " --output, -o [PATH] Path to output files [%s]\n", output_path); + fprintf(stderr, " --init, -i [PATH] Path to init executable [%s]\n", init_path); + fprintf(stderr, " --filter, -F Disable filtering of processes from the graph\n"); + fprintf(stderr, " that are of less importance or short-lived\n"); + fprintf(stderr, " --help, -h Display this message\n"); + fprintf(stderr, "See the installed README and bootchartd.conf.example for more information.\n"); + exit (EXIT_SUCCESS); + break; + default: + break; + } + } + + if (len > MAXSAMPLES) { + fprintf(stderr, "Error: samples exceeds maximum\n"); + exit(EXIT_FAILURE); + } + + /* + * If the kernel executed us through init=/sbin/bootchartd, then + * fork: + * - parent execs executable specified via init_path[] (/sbin/init by default) as pid=1 + * - child logs data + */ + if (getpid() == 1) { + if (fork()) { + /* parent */ + execl(init_path, init_path, NULL); + } + } + + /* handle TERM/INT nicely */ + memset(&sig, 0, sizeof(struct sigaction)); + sig.sa_handler = signal_handler; + sigaction(SIGTERM, &sig, NULL); + sigaction(SIGINT, &sig, NULL); + + interval = (1.0 / hz) * 1000000000.0; + + log_uptime(); + + /* main program loop */ + while (!exiting) { + int res; + double sample_stop; + struct timespec req; + long newint_ns; + + sampletime[samples] = gettime_ns(); + + /* wait for /proc to become available, discarding samples */ + if (!graph_start) + log_uptime(); + else + log_sample(samples); + + sample_stop = gettime_ns(); + + req.tv_sec = 0; + newint_ns = interval - ((sample_stop - sampletime[samples]) * 1000000000); + + /* + * check if we have not consumed our entire timeslice. If we + * do, don't sleep and take a new sample right away. + * we'll lose all the missed samples and overrun our total + * time + */ + if (newint_ns > 0) { + req.tv_nsec = newint_ns; + + res = nanosleep(&req, NULL); + if (res) { + perror("nanosleep()"); + exit (EXIT_FAILURE); + } + } else { + overrun++; + /* calculate how many samples we lost and scrap them */ + len = len + ((int)(newint_ns / interval)); + } + + samples++; + + if (samples > len) + break; + + } + + /* do some cleanup, close fd's */ + for ( i = 0; i < MAXPIDS ; i++) { + if (!ps[i]) + continue; + /* + if (ps[i]->schedstat) + close(ps[i]->schedstat); + if (ps[i]->sched) + close(ps[i]->sched); + if (ps[i]->smaps) + fclose(ps[i]->smaps); + */ + } + + t = time(NULL); + strftime(datestr, sizeof(datestr), "%Y%m%d-%H%M", localtime(&t)); + sprintf(output_file, "%s/bootchart-%s.svg", output_path, datestr); + + of = fopen(output_file, "w"); + if (!of) { + perror("open output_file"); + exit (EXIT_FAILURE); + } + + svg_do(); + + fprintf(stderr, "bootchartd: Wrote %s\n", output_file); + fclose(of); + + /* don't complain when overrun once, happens most commonly on 1st sample */ + if (overrun > 1) + fprintf(stderr, "bootchartd: Warning: sample time overrun %i times\n", overrun); + + return 0; +} diff --git a/bootchart.h b/bootchart.h new file mode 100644 index 0000000..ca22114 --- /dev/null +++ b/bootchart.h @@ -0,0 +1,113 @@ +/* + * bootchart.h + * + * Copyright (c) 2009 Intel Coproration + * Authors: + * Auke Kok + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + + +#define VERSION "0.1" + +#define MAXCPUS 8 +#define MAXPIDS 65535 +#define MAXSAMPLES 8192 + + +struct block_stat_struct { + /* /proc/vmstat pgpgin & pgpgout */ + int bi; + int bo; +}; + +struct cpu_stat_sample_struct { + /* /proc/schedstat fields 10 & 11 (after name) */ + double runtime; + double waittime; +}; + +struct cpu_stat_struct { + /* per cpu array */ + struct cpu_stat_sample_struct sample[MAXSAMPLES]; +}; + +/* per process, per sample data we will log */ +struct ps_sched_struct { + /* /proc//schedstat fields 1 & 2 */ + double runtime; + double waittime; + int pss; +}; + +/* process info */ +struct ps_struct { + struct ps_struct *children; + struct ps_struct *next; + + /* must match - otherwise it's a new process with same PID */ + char name[16]; + int pid; + int ppid; + + /* cache fd's */ + int sched; + int schedstat; + FILE *smaps; + + /* index to first/last seen timestamps */ + int first; + int last; + + /* records actual start time, may be way before bootchart runs */ + double starttime; + + /* record human readable total cpu time */ + double total; + + /* largest PSS size found */ + int pss_max; + + /* for drawing connection lines later */ + double pos_x; + double pos_y; + + struct ps_sched_struct sample[MAXSAMPLES]; +}; + + +extern double graph_start; +extern double log_start; +extern double sampletime[]; +extern struct ps_struct *ps[]; /* ll */ +extern struct block_stat_struct blockstat[]; +extern struct cpu_stat_struct cpustat[]; +extern int pscount; +extern int relative; +extern int filter; +extern int pss; +extern int initcall; +extern int samples; +extern int cpus; +extern int len; +extern int hz; +extern int scale_x; +extern int scale_y; +extern int overrun; +extern double interval; + +extern char output_path[PATH_MAX]; +extern char init_path[PATH_MAX]; + +extern FILE *of; + +extern double gettime_ns(void); +extern void log_uptime(void); +extern void log_sample(int sample); + +extern void svg_do(void); + diff --git a/bootchartd.conf.example b/bootchartd.conf.example new file mode 100644 index 0000000..ed1c559 --- /dev/null +++ b/bootchartd.conf.example @@ -0,0 +1,83 @@ +# +# bootchartd configuration - /etc/bootchartd.conf +# + +# +# How long do I make my graph? +# +# Preferably, you record enough time so that the entire boot process +# is recorded in the bootchart, plus some extra. The default recording +# samples/freq is 20secs. So, if you want to record 30secs instead of +# 20secs, you'll have to increase the amount of samples to 30*25 = 750. + + +# +# samples - how many samples total to record +# +#samples=500 + +# +# freq - how many samples per second to record +# +#freq=25 + +# +# rel - do not graph anything before the first sample is recorded. +# +# This is useful when running bootchart if the system is already up for +# a long time, in which case the monotonic clock will be so large that +# the graph would be unworkably large, as by default the graph starts +# at 0 (kernel boot start). Set this to 1 if you run bootchart from +# the cmdline. +# +#rel=0 + +# +# filter +# +# filter out insignificant processes from the process chart. This makes +# the process chart a lot more compact, but you'll not be able to see +# shortlived processes or processes that don't actually use any +# measurable (< 0.001sec) CPU time. +# +#filter=1 + +# +# alternative output folder +# +#output= + +# +# path to non-standard init +# +#init=/path/to/init + +# +# PSS graph - memory usage graph +# +# Enabling this option will make bootchart log PSS usage from /proc/*/smaps +# for each process, which is highly CPU intensive. You're advised to +# lower the 'freq' value. Expect many dropped samples - PSS measurement +# can take up to 1sec of time on an average Atom platform. +# +#pss=0 + +# +# scale_x - horizontal graph scale +# +# Modifies the default horizontal (time) scale factor. The number given +# specifies the amount of pixels that one second worth of time is wide +# in the graph. So, a higher value equals longer graph. +# +#scale_x=100 + +# +# scale_y - vertical graph scale +# +# Modifies the default vertical scale factor. The number given specifies +# the amount of pixels given in the graph to vertical aspects of the +# elements. In the PS graph, 16px equals scale_y=20. A higher value +# equals a taller graph. +# +#scale_y=20 + diff --git a/log.c b/log.c new file mode 100644 index 0000000..5e72f11 --- /dev/null +++ b/log.c @@ -0,0 +1,380 @@ +/* + * log.c + * + * Copyright (c) 2009 Intel Coproration + * Authors: + * Auke Kok + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "bootchart.h" + +/* + * Alloc a static 4k buffer for stdio - primarily used to increase + * PSS buffering from the default 1k stdin buffer to reduce + * read() overhead. + */ +char smaps_buf[4096]; + + +double gettime_ns(void) +{ + struct timespec now; + + clock_gettime(CLOCK_MONOTONIC, &now); + + return (now.tv_sec + (now.tv_nsec / 1000000000.0)); +} + + +void log_uptime(void) +{ + FILE *f; + char str[32]; + double uptime; + + f = fopen("/proc/uptime", "r"); + if (!f) + return; + if (!fscanf(f, "%s %*s", str)) { + fclose(f); + return; + } + fclose(f); + uptime = strtod(str, NULL); + + log_start = gettime_ns(); + + /* start graph at kernel boot time */ + if (relative) + graph_start = log_start; + else + graph_start = log_start - uptime; +} + + +static char *bufgetline(char *buf) +{ + char *c; + + if (!buf) + return NULL; + + c = strchr(buf, '\n'); + if (c) + c++; + return c; +} + + +void log_sample(int sample) +{ + static int vmstat; + static int schedstat; + static DIR *proc; + FILE *stat; + char buf[4095]; + char key[256]; + char val[256]; + char rt[256]; + char wt[256]; + char *m; + int c; + int p; + int s; + int n; + struct dirent *ent; + + if (!vmstat) { + /* block stuff */ + vmstat = open("/proc/vmstat", O_RDONLY); + if (vmstat == -1) { + perror("open /proc/vmstat"); + exit (EXIT_FAILURE); + } + } + + n = pread(vmstat, buf, sizeof(buf) - 1, 0); + if (n <= 0) { + close(vmstat); + return; + } + buf[n] = '\0'; + + m = buf; + while (m) { + if (sscanf(m, "%s %s", key, val) < 2) + goto vmstat_next; + if (!strcmp(key, "pgpgin")) + blockstat[sample].bi = atoi(val); + if (!strcmp(key, "pgpgout")) { + blockstat[sample].bo = atoi(val); + break; + } +vmstat_next: + m = bufgetline(m); + if (!m) + break; + } + + if (!schedstat) { + /* overall CPU utilization */ + schedstat = open("/proc/schedstat", O_RDONLY); + if (schedstat == -1) { + perror("open /proc/schedstat"); + exit (EXIT_FAILURE); + } + } + + n = pread(schedstat, buf, sizeof(buf) - 1, 0); + if (n <= 0) { + close(schedstat); + return; + } + buf[n] = '\0'; + + m = buf; + while (m) { + if (sscanf(m, "%s %*s %*s %*s %*s %*s %*s %s %s", key, rt, wt) < 3) + goto schedstat_next; + + if (strstr(key, "cpu")) { + c = atoi((const char*)(key+3)); + if (c > MAXCPUS) + /* Oops, we only have room for MAXCPUS data */ + break; + cpustat[c].sample[sample].runtime = atoll(rt); + cpustat[c].sample[sample].waittime = atoll(wt); + + if (c == cpus) + cpus = c + 1; + } +schedstat_next: + m = bufgetline(m); + if (!m) + break; + } + + /* all the per-process stuff goes here */ + if (!proc) { + /* find all processes */ + proc = opendir("/proc"); + if (!proc) + return; + } else { + rewinddir(proc); + } + + while ((ent = readdir(proc)) != NULL) { + char filename[PATH_MAX]; + int pid; + + if ((ent->d_name[0] < '0') || (ent->d_name[0] > '9')) + continue; + + pid = atoi(ent->d_name); + + if (pid >= MAXPIDS) + continue; + + if (!ps[pid]) { + char t[32]; + struct ps_struct *parent; + + pscount++; + + /* alloc & insert */ + ps[pid] = malloc(sizeof(struct ps_struct)); + if (!ps[pid]) { + perror("malloc ps[pid]"); + exit (EXIT_FAILURE); + } + memset(ps[pid], 0, sizeof(struct ps_struct)); + + /* mark our first sample */ + ps[pid]->first = sample; + + /* get name, start time */ + if (!ps[pid]->sched) { + sprintf(filename, "/proc/%d/sched", pid); + ps[pid]->sched = open(filename, O_RDONLY); + if (ps[pid]->sched == -1) + continue; + } + + s = pread(ps[pid]->sched, buf, sizeof(buf) - 1, 0); + if (s <= 0) { + close(ps[pid]->sched); + continue; + } + + if (!sscanf(buf, "%s %*s %*s", key)) + continue; + + strncpy(ps[pid]->name, key, 16); + /* discard line 2 */ + m = bufgetline(buf); + if (!m) + continue; + + m = bufgetline(m); + if (!m) + continue; + + if (!sscanf(m, "%*s %*s %s", t)) + continue; + + ps[pid]->starttime = strtod(t, NULL) / 1000.0; + + /* ppid */ + sprintf(filename, "/proc/%d/stat", pid); + stat = fopen(filename, "r"); + if (!stat) + continue; + if (!fscanf(stat, "%*s %*s %*s %i", &p)) { + fclose(stat); + continue; + } + fclose(stat); + ps[pid]->ppid = p; + + /* + * setup child pointers + * + * these are used to paint the tree coherently later + * each parent has a LL of children, and a LL of siblings + */ + if (pid == 1) + continue; /* nothing to do for init atm */ + + parent = ps[ps[pid]->ppid]; + + if (!parent) { + /* fix this asap */ + ps[pid]->ppid = 1; + parent = ps[1]; + } + + if (!parent->children) { + /* it's the first child */ + parent->children = ps[pid]; + } else { + /* walk all children and append */ + struct ps_struct *children; + children = parent->children; + while (children->next) + children = children->next; + children->next = ps[pid]; + } + + ps[pid]->pid = pid; + } + + /* below here is all continuous logging parts - we get here on every + * iteration */ + + /* rt, wt */ + if (!ps[pid]->schedstat) { + sprintf(filename, "/proc/%d/schedstat", pid); + ps[pid]->schedstat = open(filename, O_RDONLY); + if (ps[pid]->schedstat == -1) + continue; + } + + if (pread(ps[pid]->schedstat, buf, sizeof(buf) - 1, 0) <= 0) { + /* clean up our file descriptors - assume that the process exited */ + close(ps[pid]->schedstat); + if (ps[pid]->sched) + close(ps[pid]->sched); + //if (ps[pid]->smaps) + // fclose(ps[pid]->smaps); + continue; + } + if (!sscanf(buf, "%s %s %*s", rt, wt)) + continue; + + ps[pid]->pid = pid; + ps[pid]->last = sample; + ps[pid]->sample[sample].runtime = atoll(rt); + ps[pid]->sample[sample].waittime = atoll(wt); + + ps[pid]->total = (ps[pid]->sample[ps[pid]->last].runtime + - ps[pid]->sample[ps[pid]->first].runtime) + / 1000000000.0; + + if (!pss) + goto catch_rename; + /* Pss */ + if (!ps[pid]->smaps) { + sprintf(filename, "/proc/%d/smaps", pid); + ps[pid]->smaps = fopen(filename, "r"); + setvbuf(ps[pid]->smaps, smaps_buf, _IOFBF, sizeof(smaps_buf)); + if (!ps[pid]->smaps) + continue; + } else { + rewind(ps[pid]->smaps); + } + + while (1) { + /* skip one line, this contains the object mapped */ + if (fgets(buf, sizeof(buf) -1, ps[pid]->smaps) == NULL) + break; + /* then there's a 28 char 14 line block */ + if (fread(buf, 1, 28 * 14, ps[pid]->smaps) != 28 * 14) + break; + + int p; + p = atoi(&buf[61]); + ps[pid]->sample[sample].pss += p; + } + + if (ps[pid]->sample[sample].pss > ps[pid]->pss_max) + ps[pid]->pss_max = ps[pid]->sample[sample].pss; + +catch_rename: + /* catch process rename, try to randomize time */ + if (((samples - ps[pid]->first) + pid) % (hz / 4) == 0) { + + /* re-fetch name */ + /* get name, start time */ + if (!ps[pid]->sched) { + sprintf(filename, "/proc/%d/sched", pid); + ps[pid]->sched = open(filename, O_RDONLY); + if (ps[pid]->sched == -1) + continue; + } + if (pread(ps[pid]->sched, buf, sizeof(buf) - 1, 0) <= 0) { + /* clean up file descriptors */ + close(ps[pid]->sched); + if (ps[pid]->schedstat) + close(ps[pid]->schedstat); + //if (ps[pid]->smaps) + // fclose(ps[pid]->smaps); + continue; + } + + if (!sscanf(buf, "%s %*s %*s", key)) + continue; + + strncpy(ps[pid]->name, key, 16); + } + } +} + diff --git a/packaging/bootchart.spec b/packaging/bootchart.spec new file mode 100644 index 0000000..45b9dc5 --- /dev/null +++ b/packaging/bootchart.spec @@ -0,0 +1,33 @@ + +Name: bootchart +Summary: Boot time graph generator +Version: 1.15 +Release: 1 +Group: Development/Tools +License: GPLv2 +URL: http://meego.gitorious.org/ +Source0: bootchart-%{version}.tar.gz + +%description +Monitors where the system spends its time at start, creating a graph +of all processes, disk utilization, and wait time. + +%prep +%setup -q -n %{name}-%{version} + +%build +make %{?jobs:-j%jobs} + +%install +rm -rf %{buildroot} +%make_install + +%files +%defattr(-,root,root,-) +/sbin/bootchartd +%{_datadir}/doc/bootchart/bootchartd.conf.example +%{_datadir}/doc/bootchart/COPYING +%{_datadir}/doc/bootchart/README + +%changelog + diff --git a/svg.c b/svg.c new file mode 100644 index 0000000..6f81751 --- /dev/null +++ b/svg.c @@ -0,0 +1,1076 @@ +/* + * svg.c + * + * Copyright (c) 2009 Intel Coproration + * Authors: + * Auke Kok + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bootchart.h" + + +#define time_to_graph(t) ((t) * scale_x) +#define ps_to_graph(n) ((n) * scale_y) +#define kb_to_graph(m) ((m) * scale_y * 0.0001) +#define to_color(n) (192.0 - ((n) * 192.0)) + +#define max(x, y) (((x) > (y)) ? (x) : (y)) +#define min(x, y) (((x) < (y)) ? (x) : (y)) + +static char str[8092]; + +#define svg(a...) do { sprintf(str, ## a); fputs(str, of); fflush(of); } while (0) + +static char *colorwheel[12] = { + "rgb(255,32,32)", // red + "rgb(32,192,192)", // cyan + "rgb(255,128,32)", // orange + "rgb(128,32,192)", // blue-violet + "rgb(255,255,32)", // yellow + "rgb(192,32,128)", // red-violet + "rgb(32,255,32)", // green + "rgb(255,64,32)", // red-orange + "rgb(32,32,255)", // blue + "rgb(255,192,32)", // yellow-orange + "rgb(192,32,192)", // violet + "rgb(32,192,32)" // yellow-green +}; + +static double idletime = -1.0; +static int pfiltered = 0; +static int pcount = 0; +static int kcount = 0; +static int psize = 0; +static int ksize = 0; + + +void svg_header(void) +{ + float w; + int h; + + /* min width is about 1600px due to the label */ + w = 150 + 10 + time_to_graph(sampletime[samples-1] - graph_start); + w = ((w < 1600.0) ? 1600.0 : w); + + /* height is variable based on pss, psize, ksize */ + h = 400 + (scale_y * 30) /* base graphs and title */ + + (pss ? (100 * scale_y) + (scale_y * 7) : 0) /* pss estimate */ + + psize + ksize; + + svg("\n"); + svg("\n"); + + //svg("\n", 1000 + 150 + (pcount * 20)); + svg("\n\n"); + + /* write some basic info as a comment, including some help */ + svg("\n"); + svg("\n"); + svg("\n"); + svg("\n"); + svg("\n\n"); + + svg("\n", BOOTCHARTVERSION); + svg("\n", hz, len); + svg("\n", scale_x, scale_y); + svg("\n", relative, filter, pss); + svg("\n\n", output_path, init_path); + + /* style sheet */ + svg("\n \n\n\n"); + +} + + +void svg_title(void) +{ + char cmdline[256] = ""; + char filename[PATH_MAX]; + char buf[256]; + char rootbdev[16] = "Unknown"; + char model[256] = "Unknown"; + char date[256] = "Unknown"; + char cpu[256] = "Unknown"; + char build[256] = "Unknown"; + char *c; + FILE *f; + time_t t; + struct utsname uts; + + /* grab /proc/cmdline */ + f = fopen("/proc/cmdline", "r"); + if (f) { + if (!fgets(cmdline, 255, f)) + sprintf(cmdline, "Unknown"); + fclose(f); + } + + /* extract root fs so we can find disk model name in sysfs */ + c = strstr(cmdline, "root=/dev/"); + if (c) { + strncpy(rootbdev, &c[10], 3); + rootbdev[3] = '\0'; + } + sprintf(filename, "/sys/block/%s/device/model", rootbdev); + f = fopen(filename, "r"); + if (f) { + if (!fgets(model, 255, f)) + fprintf(stderr, "Error reading disk model for %s\n", rootbdev); + fclose(f); + } + + /* various utsname parameters */ + if (uname(&uts)) + fprintf(stderr, "Error getting uname info\n"); + + /* date */ + t = time(NULL); + strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", localtime(&t)); + + /* CPU type */ + f = fopen("/proc/cpuinfo", "r"); + if (f) { + while (fgets(buf, 255, f)) { + if (strstr(buf, "model name")) { + strncpy(cpu, &buf[13], 255); + break; + } + } + fclose(f); + } + + /* Build - 1st line from /etc/system-release */ + f = fopen("/etc/system-release", "r"); + if (f) { + if (fgets(buf, 255, f)) + strncpy(build, buf, 255); + fclose(f); + } + + svg("Bootchart for %s - %s\n", + uts.nodename, date); + svg("System: %s %s %s %s\n", + uts.sysname, uts.release, uts.version, uts.machine); + svg("CPU: %s\n", + cpu); + svg("Disk: %s\n", + model); + svg("Boot options: %s\n", + cmdline); + svg("Build: %s\n", + build); + svg("Log start time: %.03fs\n", log_start); + svg("Idle time: "); + + if (idletime >= 0.0) + svg("%.03fs", idletime); + else + svg("Not detected"); + svg("\n"); + svg("Graph data: %i samples/sec, recorded %i total, dropped %i samples, %i processes, %i filtered\n", + hz, len, overrun, pscount, pfiltered); +} + + +void svg_graph_box(int height) +{ + double d = 0.0; + int i = 0; + + /* outside box, fill */ + svg("\n", + time_to_graph(.0), + time_to_graph(sampletime[samples-1] - graph_start), + ps_to_graph(height)); + + for (d = graph_start; d <= sampletime[samples-1]; d += 0.1) { + /* lines for each second */ + if (i % 50 == 0) + svg(" \n", + time_to_graph(d - graph_start), + time_to_graph(d - graph_start), + ps_to_graph(height)); + else if (i % 10 == 0) + svg(" \n", + time_to_graph(d - graph_start), + time_to_graph(d - graph_start), + ps_to_graph(height)); + else + svg(" \n", + time_to_graph(d - graph_start), + time_to_graph(d - graph_start), + ps_to_graph(height)); + + /* time label */ + if (i % 10 == 0) + svg(" %.01fs\n", + time_to_graph(d - graph_start), + -5, + d - graph_start); + + i++; + } +} + + +void svg_pss_graph(void) +{ + int i; + int p; + + svg("\n\n\n"); + + svg("\n Memory allocation - Pss\n"); + + /* vsize 1000 == 1000mb */ + svg_graph_box(100); + /* draw some hlines for usable memory sizes */ + for (i = 100000; i < 1000000; i += 100000) { + svg(" \n", + time_to_graph(.0), + kb_to_graph(i), + time_to_graph(sampletime[samples-1] - graph_start), + kb_to_graph(i)); + svg(" %dM\n", + time_to_graph(sampletime[samples-1] - graph_start) + 5, + kb_to_graph(i), (1000000 - i) / 1000); + } + svg("\n"); + + /* now plot the graph itself */ + for (i = 1; i < samples ; i++) { + int bottom; + int top; + + bottom = 0; + top = 0; + + /* put all the small pss blocks into the bottom */ + for (p = 0; p < MAXPIDS ; p++) { + if (!ps[p]) + continue; + if (ps[p]->sample[i].pss <= (100 * scale_y)) + top += ps[p]->sample[i].pss; + }; + svg(" \n", + "rgb(64,64,64)", + time_to_graph(sampletime[i - 1] - graph_start), + kb_to_graph(1000000.0 - top), + time_to_graph(sampletime[i] - sampletime[i - 1]), + kb_to_graph(top - bottom)); + + bottom = top; + + /* now plot the ones that are of significant size */ + for (p = 0; p < MAXPIDS ; p++) { + if (!ps[p]) + continue; + /* don't draw anything smaller than 2mb */ + if (ps[p]->sample[i].pss > (100 * scale_y)) { + top = bottom + ps[p]->sample[i].pss; + svg(" \n", + colorwheel[p % 12], + time_to_graph(sampletime[i - 1] - graph_start), + kb_to_graph(1000000.0 - top), + time_to_graph(sampletime[i] - sampletime[i - 1]), + kb_to_graph(top - bottom)); + bottom = top; + } + } + } + + /* overlay all the text labels */ + for (i = 1; i < samples ; i++) { + int bottom; + int top; + + bottom = 0; + top = 0; + + /* put all the small pss blocks into the bottom */ + for (p = 0; p < MAXPIDS ; p++) { + if (!ps[p]) + continue; + if (ps[p]->sample[i].pss <= (100 * scale_y)) + top += ps[p]->sample[i].pss; + }; + + bottom = top; + + /* now plot the ones that are of significant size */ + for (p = 0; p < MAXPIDS ; p++) { + if (!ps[p]) + continue; + /* don't draw anything smaller than 2mb */ + if (ps[p]->sample[i].pss > (100 * scale_y)) { + top = bottom + ps[p]->sample[i].pss; + /* draw a label with the process / PID */ + if ((i == 1) || (ps[p]->sample[i - 1].pss <= (100 * scale_y))) + svg(" %s [%i]\n", + time_to_graph(sampletime[i] - graph_start), + kb_to_graph(1000000.0 - bottom - ((top - bottom) / 2)), + ps[p]->name, + ps[p]->pid); + bottom = top; + } + } + } + + /* debug output - full data dump */ + svg("\n\n\n"); + for (p = 0; p < MAXPIDS ; p++) { + if (!ps[p]) + continue; + svg("\n"); + } + +} + +void svg_io_bi_bar(void) +{ + double max = 0.0; + double range; + int max_here = 0; + int i; + + svg("\n"); + + svg("IO utilization - read\n"); + + /* + * calculate rounding range + * + * We need to round IO data since IO block data is not updated on + * each poll. Applying a smoothing function loses some burst data, + * so keep the smoothing range short. + */ + range = 0.25 / (1.0 / hz); + if (range < 2.0) + range = 2.0; /* no smoothing */ + + /* surrounding box */ + svg_graph_box(5); + + /* find the max IO first */ + for (i = 1; i < samples; i++) { + int start; + int stop; + double tot; + + start = max(i - ((range / 2) - 1), 0); + stop = min(i + (range / 2), samples - 1); + + tot = (double)(blockstat[stop].bi - blockstat[start].bi) + / (stop - start); + if (tot > max) { + max = tot; + max_here = i; + } + tot = (double)(blockstat[stop].bo - blockstat[start].bo) + / (stop - start); + if (tot > max) + max = tot; + } + + /* plot bi */ + for (i = 1; i < samples; i++) { + int start; + int stop; + double tot; + double pbi; + + start = max(i - ((range / 2) - 1), 0); + stop = min(i + (range / 2), samples); + + tot = (double)(blockstat[stop].bi - blockstat[start].bi) + / (stop - start); + pbi = tot / max; + + if (pbi > 0.001) + svg("\n", + time_to_graph(sampletime[i - 1] - graph_start), + (scale_y * 5) - (pbi * (scale_y * 5)), + time_to_graph(sampletime[i] - sampletime[i - 1]), + pbi * (scale_y * 5)); + + /* labels around highest value */ + if (i == max_here) { + svg(" %0.2fmb/sec\n", + time_to_graph(sampletime[i] - graph_start) + 5, + ((scale_y * 5) - (pbi * (scale_y * 5))) + 15, + max / 1024.0 / (interval / 1000000000.0)); + } + } +} + +void svg_io_bo_bar(void) +{ + double max = 0.0; + double range; + int max_here = 0; + int i; + + svg("\n"); + + svg("IO utilization - write\n"); + + /* + * calculate rounding range + * + * We need to round IO data since IO block data is not updated on + * each poll. Applying a smoothing function loses some burst data, + * so keep the smoothing range short. + */ + range = 0.25 / (1.0 / hz); + if (range < 2.0) + range = 2.0; /* no smoothing */ + + /* surrounding box */ + svg_graph_box(5); + + /* find the max IO first */ + for (i = 1; i < samples; i++) { + int start; + int stop; + double tot; + + start = max(i - ((range / 2) - 1), 0); + stop = min(i + (range / 2), samples - 1); + + tot = (double)(blockstat[stop].bi - blockstat[start].bi) + / (stop - start); + if (tot > max) + max = tot; + tot = (double)(blockstat[stop].bo - blockstat[start].bo) + / (stop - start); + if (tot > max) { + max = tot; + max_here = i; + } + } + + /* plot bo */ + for (i = 1; i < samples; i++) { + int start; + int stop; + double tot; + double pbo; + + start = max(i - ((range / 2) - 1), 0); + stop = min(i + (range / 2), samples); + + tot = (double)(blockstat[stop].bo - blockstat[start].bo) + / (stop - start); + pbo = tot / max; + + if (pbo > 0.001) + svg("\n", + time_to_graph(sampletime[i - 1] - graph_start), + (scale_y * 5) - (pbo * (scale_y * 5)), + time_to_graph(sampletime[i] - sampletime[i - 1]), + pbo * (scale_y * 5)); + + /* labels around highest bo value */ + if (i == max_here) { + svg(" %0.2fmb/sec\n", + time_to_graph(sampletime[i] - graph_start) + 5, + ((scale_y * 5) - (pbo * (scale_y * 5))), + max / 1024.0 / (interval / 1000000000.0)); + } + } +} + + +void svg_cpu_bar(void) +{ + int i; + + svg("\n"); + + svg("CPU utilization\n"); + /* surrounding box */ + svg_graph_box(5); + + /* bars for each sample, proportional to the CPU util. */ + for (i = 1; i < samples; i++) { + int c; + double trt; + double ptrt; + + ptrt = trt = 0.0; + + for (c = 0; c < cpus; c++) + trt += cpustat[c].sample[i].runtime - cpustat[c].sample[i - 1].runtime; + + trt = trt / 1000000000.0; + + trt = trt / (double)cpus; + + if (trt > 0.0) + ptrt = trt / (sampletime[i] - sampletime[i - 1]); + + if (ptrt > 1.0) + ptrt = 1.0; + + if (ptrt > 0.001) { + svg("\n", + time_to_graph(sampletime[i - 1] - graph_start), + (scale_y * 5) - (ptrt * (scale_y * 5)), + time_to_graph(sampletime[i] - sampletime[i - 1]), + ptrt * (scale_y * 5)); + } + } +} + +void svg_wait_bar(void) +{ + int i; + + svg("\n"); + + svg("CPU wait\n"); + + /* surrounding box */ + svg_graph_box(5); + + /* bars for each sample, proportional to the CPU util. */ + for (i = 1; i < samples; i++) { + int c; + double twt; + double ptwt; + + ptwt = twt = 0.0; + + for (c = 0; c < cpus; c++) + twt += cpustat[c].sample[i].waittime - cpustat[c].sample[i - 1].waittime; + + twt = twt / 1000000000.0; + + twt = twt / (double)cpus; + + if (twt > 0.0) + ptwt = twt / (sampletime[i] - sampletime[i - 1]); + + if (ptwt > 1.0) + ptwt = 1.0; + + if (ptwt > 0.001) { + svg("\n", + time_to_graph(sampletime[i - 1] - graph_start), + ((scale_y * 5) - (ptwt * (scale_y * 5))), + time_to_graph(sampletime[i] - sampletime[i - 1]), + ptwt * (scale_y * 5)); + } + } +} + + +int get_next_ps(int start) +{ + /* + * walk the list of processes and return the next one to be + * painted + */ + + int here = start; + struct ps_struct *children; + struct ps_struct *siblings; + + /* start with init [1] */ + if (here == 0) { + here = 1; + return here; + } + + children = ps[here]->children; + + /* go deep */ + if (children) { + here = ps[here]->children->pid; + return here; + } + + /* find siblings */ + siblings = ps[here]->next; + if (siblings) { + here = ps[here]->next->pid; + return here; + } + + /* go back for parent siblings */ + while (ps[ps[here]->ppid]) { + here = ps[ps[here]->ppid]->pid; + /* go to sibling of parent */ + if (ps[here]->next) { + here = ps[here]->next->pid; + return here; + } + } + + return 0; +} + + +int ps_filter(int pid) +{ + if (!filter) + return 0; + + /* can't draw data when there is only 1 sample (need start + stop) */ + if (ps[pid]->first == ps[pid]->last) + return -1; + + /* don't filter kthreadd */ + if (pid == 2) + return 0; + + /* drop stuff that doesn't use any real CPU time */ + if (ps[pid]->total <= 0.001) + return -1; + + return 0; +} + + +void svg_do_initcall(int count_only) +{ + FILE *f; + double t; + char func[256]; + int ret; + int usecs; + + /* can't plot initcall when disabled or in relative mode */ + if (!initcall || relative) { + kcount = 0; + return; + } + + if (!count_only) { + svg("\n"); + + svg("Kernel init threads\n"); + /* surrounding box */ + svg_graph_box(kcount); + } + + kcount = 0; + + /* + * Initcall graphing - parses dmesg buffer and displays kernel threads + * This somewhat uses the same methods and scaling to show processes + * but looks a lot simpler. It's overlaid entirely onto the PS graph + * when appropriate. + */ + + f = popen("dmesg", "r"); + if (!f) + return; + + while (!feof(f)) { + int c; + int z = 0; + char l[256]; + + if (fgets(l, sizeof(l) - 1, f) == NULL) + continue; + + c = sscanf(l, "[%lf] initcall %s %*s %d %*s %d %*s", + &t, func, &ret, &usecs); + if (c != 4) + continue; + + /* chop the +0xXX/0xXX stuff */ + while(func[z] != '+') + z++; + func[z] = 0; + + if (count_only) { + /* filter out irrelevant stuff */ + if (usecs >= 1000) + kcount++; + continue; + } + + svg("\n", + func, t, usecs, ret); + + if (usecs < 1000) + continue; + + /* rect */ + svg(" \n", + time_to_graph(t - (usecs / 1000000.0)), + ps_to_graph(kcount), + time_to_graph(usecs / 1000000.0), + ps_to_graph(1)); + + /* label */ + svg(" %s %.03fs\n", + time_to_graph(t - (usecs / 1000000.0)) + 5, + ps_to_graph(kcount) + 15, + func, + usecs / 1000000.0); + + kcount++; + } + + fclose(f); +} + + +void svg_ps_bars(void) +{ + int i = 0; + int j = 0; + int wt; + int pid; + + svg("\n"); + + svg("Processes\n"); + + /* surrounding box */ + svg_graph_box(pcount); + + /* pass 2 - ps boxes */ + i = 0; + while ((i = get_next_ps(i))) { + double starttime; + int t; + + if (!ps[i]) + continue; + + /* leave some trace of what we actually filtered etc. */ + svg("\n", ps[i]->name, i, + ps[i]->ppid, ps[i]->total); + + /* it would be nice if we could use exec_start from /proc/pid/sched, + * but it's unreliable and gives bogus numbers */ + starttime = sampletime[ps[i]->first]; + + if (!ps_filter(i)) { + /* remember where _to_ our children need to draw a line */ + ps[i]->pos_x = time_to_graph(starttime - graph_start); + ps[i]->pos_y = ps_to_graph(j+1); /* bottom left corner */ + } else { + /* hook children to our parent coords instead */ + ps[i]->pos_x = ps[ps[i]->ppid]->pos_x; + ps[i]->pos_y = ps[ps[i]->ppid]->pos_y; + + /* if this is the last child, we might still need to draw a connecting line */ + if ((!ps[i]->next) && (ps[ps[i]->ppid])) + svg(" \n", + ps[ps[i]->ppid]->pos_x, + ps_to_graph(j-1) + 10, /* whee, use the last value here */ + ps[ps[i]->ppid]->pos_x, + ps[ps[i]->ppid]->pos_y); + continue; + } + + svg(" \n", + time_to_graph(starttime - graph_start), + ps_to_graph(j), + time_to_graph(sampletime[ps[i]->last] - starttime), + ps_to_graph(1)); + + /* paint cpu load over these */ + for (t = ps[i]->first + 1; t < ps[i]->last; t++) { + double rt, prt; + double wt, wrt; + + /* calculate over interval */ + rt = ps[i]->sample[t].runtime - ps[i]->sample[t-1].runtime; + wt = ps[i]->sample[t].waittime - ps[i]->sample[t-1].waittime; + + prt = (rt / 1000000000) / (sampletime[t] - sampletime[t-1]); + wrt = (wt / 1000000000) / (sampletime[t] - sampletime[t-1]); + + /* this can happen if timekeeping isn't accurate enough */ + if (prt > 1.0) + prt = 1.0; + if (wrt > 1.0) + wrt = 1.0; + + if ((prt < 0.1) && (wrt < 0.1)) /* =~ 26 (color threshold) */ + continue; + + svg(" \n", + time_to_graph(sampletime[t - 1] - graph_start), + ps_to_graph(j), + time_to_graph(sampletime[t] - sampletime[t - 1]), + ps_to_graph(wrt)); + + /* draw cpu over wait - TODO figure out how/why run + wait > interval */ + svg(" \n", + time_to_graph(sampletime[t - 1] - graph_start), + ps_to_graph(j + (1.0 - prt)), + time_to_graph(sampletime[t] - sampletime[t - 1]), + ps_to_graph(prt)); + } + + /* determine where to display the process name */ + if (sampletime[ps[i]->last] - sampletime[ps[i]->first] < 1.5) + /* too small to fit label inside the box */ + wt = ps[i]->last; + else + wt = ps[i]->first; + + /* text label of process name */ + svg(" %s [%i] %.03fs\n", + time_to_graph(sampletime[wt] - graph_start) + 5, + ps_to_graph(j) + 14, + ps[i]->name, + ps[i]->pid, + (ps[i]->sample[ps[i]->last].runtime - ps[i]->sample[ps[i]->first].runtime) / 1000000000.0); + + /* paint lines to the parent process */ + if (ps[ps[i]->ppid]) { + /* horizontal part */ + svg(" \n", + time_to_graph(starttime - graph_start), + ps_to_graph(j) + 10, + ps[ps[i]->ppid]->pos_x, + ps_to_graph(j) + 10); + + /* one vertical line connecting all the horizontal ones up */ + if (!ps[i]->next) + svg(" \n", + ps[ps[i]->ppid]->pos_x, + ps_to_graph(j) + 10, + ps[ps[i]->ppid]->pos_x, + ps[ps[i]->ppid]->pos_y); + } + + j++; /* count boxes */ + + svg("\n"); + } + + /* last pass - determine when idle */ + pid = getpid(); + /* make sure we start counting from the point where we actually have + * data: assume that bootchart's first sample is when data started + */ + for (i = ps[pid]->first; i < samples - (hz / 2); i++) { + double crt; + double brt; + int c; + + /* subtract bootchart cpu utilization from total */ + crt = 0.0; + for (c = 0; c < cpus; c++) + crt += cpustat[c].sample[i + (hz / 2)].runtime - cpustat[c].sample[i].runtime; + brt = ps[pid]->sample[i + (hz / 2)].runtime - ps[pid]->sample[i].runtime; + + /* + * our definition of "idle": + * + * if for (hz / 2) we've used less CPU than (interval / 2) ... + * defaults to 4.0%, which experimentally, is where atom idles + */ + if ((crt - brt) < (interval / 2)) { + idletime = sampletime[i] - graph_start; + svg("\n\n", + idletime); + svg("\n", + time_to_graph(idletime), + -scale_y, + time_to_graph(idletime), + ps_to_graph(pcount) + scale_y); + svg("%.01fs\n", + time_to_graph(idletime) + 5, + ps_to_graph(pcount) + scale_y, + idletime); + break; + } + } +} + + +void svg_top_ten_cpu(void) +{ + struct ps_struct *top[10]; + struct ps_struct emptyps; + int i, n, m; + + memset(&emptyps, 0, sizeof(emptyps)); + for (n=0; n < 10; n++) + top[n] = &emptyps; + + /* walk all ps's and setup ptrs */ + i = 0; + while ((i = get_next_ps(i))) { + for (n = 0; n < 10; n++) { + if (ps[i]->total <= top[n]->total) + continue; + /* cascade insert */ + for (m = 9; m > n; m--) + top[m] = top[m-1]; + top[n] = ps[i]; + break; + } + } + + svg("Top CPU consumers:\n"); + for (n = 0; n < 10; n++) + svg("%3.03fs - %s[%d]\n", + 20 + (n * 13), + top[n]->total, + top[n]->name, + top[n]->pid); +} + + +void svg_top_ten_pss(void) +{ + struct ps_struct *top[10]; + struct ps_struct emptyps; + int i, n, m; + + memset(&emptyps, 0, sizeof(emptyps)); + for (n=0; n < 10; n++) + top[n] = &emptyps; + + /* walk all ps's and setup ptrs */ + i = 0; + while ((i = get_next_ps(i))) { + for (n = 0; n < 10; n++) { + if (ps[i]->pss_max <= top[n]->pss_max) + continue; + /* cascade insert */ + for (m = 9; m > n; m--) + top[m] = top[m-1]; + top[n] = ps[i]; + break; + } + } + + svg("Top PSS consumers:\n"); + for (n = 0; n < 10; n++) + svg("%dK - %s[%d]\n", + 20 + (n * 13), + top[n]->pss_max, + top[n]->name, + top[n]->pid); +} + + +void svg_do(void) +{ + int i = 0; + + memset(&str, 0, sizeof(str)); + + /* count initcall thread count first */ + svg_do_initcall(1); + ksize = (kcount ? ps_to_graph(kcount) + (scale_y * 2) : 0); + + /* then count processes */ + while ((i = get_next_ps(i))) { + if (!ps_filter(i)) + pcount++; + else + pfiltered++; + } + psize = ps_to_graph(pcount) + (scale_y * 2); + + /* after this, we can draw the header with proper sizing */ + svg_header(); + + svg("\n"); + svg_io_bi_bar(); + svg("\n\n"); + + svg("\n", 400 + (scale_y * 7)); + svg_io_bo_bar(); + svg("\n\n"); + + svg("\n", 400 + (scale_y * 14)); + svg_cpu_bar(); + svg("\n\n"); + + svg("\n", 400 + (scale_y * 21)); + svg_wait_bar(); + svg("\n\n"); + + if (kcount) { + svg("\n", 400 + (scale_y * 28)); + svg_do_initcall(0); + svg("\n\n"); + } + + svg("\n", 400 + (scale_y * 28) + ksize); + svg_ps_bars(); + svg("\n\n"); + + svg("\n"); + svg_title(); + svg("\n\n"); + + svg("\n"); + svg_top_ten_cpu(); + svg("\n\n"); + + if (pss) { + svg("\n", 400 + (scale_y * 28) + ksize + psize); + svg_pss_graph(); + svg("\n\n"); + + svg("\n"); + svg_top_ten_pss(); + svg("\n\n"); + } + + /* svg footer */ + svg("\n\n"); +} + -- 2.7.4