trend-1.4/0000755000000000000000000000000012742657152011203 5ustar rootroottrend-1.4/examples/0000755000000000000000000000000012742657152013021 5ustar rootroottrend-1.4/examples/tstimes0000755000000000000000000000030711454047245014432 0ustar rootroot#!/bin/sh # ts execution times if [ -z "$1" ] then file=/as2d1/Logs/TS.9999.err host=as2 else file="$1" host="$2" fi ssh "$host" tail -f "'$file'" | sed -une 's/^.* time \([0-9]*\), .*$/\1/p' trend-1.4/examples/imem0000755000000000000000000000021111454047245013663 0ustar rootroot#!/bin/sh # print out memory usage using PCP # sleep time sec="$1" [ -z "$sec" ] && sec=1 # get the data pmval -t "$sec" mem.util.user trend-1.4/examples/mem0000755000000000000000000000121311454047245013515 0ustar rootroot#!/usr/bin/env perl # memory + swap usage for trend use strict; use warnings; use Time::HiRes "usleep"; # be sure to flush right away! $| = 1; # sleep time my $ms = ($ARGV[0]? $ARGV[0]: 0.1) * 1000000; # main loop while() { open FD, "/proc/meminfo" or die; while() { # 2.4 kernel my ($tot, $used, $free, $buf, $cache) = /^Mem: *(\d+) +(\d+) +(\d+) +\d+ +(\d+) +(\d+)$/; if($tot) { print(($tot - $free - $buf - $cache) / 1024. . "\n"); last; } # 2.6 kernel my ($active) = /^Active: *(\d+) kB$/; if($active) { print "$active\n"; last; } } close FD; usleep $ms; } trend-1.4/examples/net0000755000000000000000000000132511454047245013531 0ustar rootroot#!/usr/bin/env perl # network usage for trend use strict; use warnings; use Time::HiRes "usleep"; # be sure to flush right away! $| = 1; # arguments my $oldIn = 0; my $oldOut = 0; my $ms = ($ARGV[0]? $ARGV[0]: 0.1) * 1000000; my $if = ($ARGV[1]? $ARGV[1]: "eth0"); # main loop while() { open FD, "/proc/net/dev" or die; while() { my ($ent, $in, $out) = /^\s*([^\s:]+):\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)/; if($ent and $ent eq $if) { $oldIn = $in if($oldIn == 0); $oldOut = $out if($oldOut == 0); print(($in - $oldIn) . " " . ($out - $oldOut) . "\n"); $oldIn = $in; $oldOut = $out; last; } } close FD; usleep $ms; } trend-1.4/examples/timeq0000755000000000000000000000241611454047245014064 0ustar rootroot#!/usr/bin/env perl # a very basic and imprecise time quantizer use strict; use warnings; use Getopt::Std qw{getopts}; use Time::HiRes qw{usleep gettimeofday tv_interval}; # be sure to flush right away! $| = 1; # arguments my %flags; getopts('s', \%flags); my $ms = ($ARGV[0]? $ARGV[0]: 1); my $dlen = length(pack("d", ())); # parser sub parser() { while() { my $v = pack("d", ($_ + 0)); syswrite(FD, $v, $dlen); } } # quantizer sub quantize() { my $res = $ms; my $cum = 0; my $num = 0; # prepare fds my $fds = ''; vec($fds, fileno(STDIN), 1) = 1; while($fds) { # select my $pre = [gettimeofday]; my $rfs = $fds; my $n = select($rfs, undef, undef, $res); $res -= tv_interval($pre, [gettimeofday]); # return values if($n > 0) { my $v; if(!sysread(STDIN, $v, $dlen)) { $fds = undef; } else { ++$num; $cum += unpack("d", $v); } } # average if($res <= 0) { my $v = ($flags{s}? $cum: ($num? $cum / $num: 0)); syswrite(STDOUT, pack("d", $v), $dlen); # we should rather compensate than drift $num = $cum = 0; $res += $ms; } } } # execution my $pid = open(FD, "|-"); die unless(defined($pid)); if($pid) { parser(); } else { quantize(); } trend-1.4/AUTHORS.rst0000644000000000000000000000010312647742406013055 0ustar rootrootCopyright(c) 2003-2016 by wave++ "Yuri D'Elia" trend-1.4/trend.10000644000000000000000000003215612647742471012413 0ustar rootroot.\" trend.1: trend manual .\" Copyright(c) 2006-2009 by wave++ "Yuri D'Elia" .\" Distributed under GNU LGPL WITHOUT ANY WARRANTY. .\" .Dd November 2, 2007 .Dt TREND 1 .\" .\" .Sh NAME .Nm trend .Nd a general-purpose, efficient trend graph .\" .\" .Sh SYNOPSIS .Nm .Op Fl dDSsvlmFgGhtAERIMNTLzfcpue .Op Fl display .Op Fl geometry .Op Fl iconic .Aq Ar fifo | \- .Aq Ar hist-spec | hist-sz x-sz .Op Ar low high .\" .\" .Sh DESCRIPTION .Nm is a general-purpose, efficient trend graph for "live" data. Data is read in ASCII form from a file or continuously from a FIFO and displayed in real-time into a multi-pass trend (much like a CRT oscilloscope). .Nm can be used as a rapid analysis tool for progressive or time-based data series together with trivial scripting. .Pp .Nm requires at least a valid .Ar fifo to read from and an history specification .Ar ( hist-spec ) or, for advanced usage, a combination of history size and horizontal size .Ar ( hist-sz No and Ar x-sz No respectively). Optionally, to disable auto-scaling, the vertical limits can be specified directly through the command line via .Ar low No and Ar high . The default input format is ASCII, in absolute counting mode. Many settings can be changed directly during execution. .\" .\" .Sh INPUT .\" .Ss FIFO To display real-time data you should use a FIFO. Both standard input and named pipes can be used. Standard input (used for simple pipelining purposes) can be opened by using .Ar \- instead of a named file. A named FIFO can be created using the .Xr mkfifo 1 command. FIFOs are automatically re-opened upon EOF. See the .Sx EXAMPLES section. .Pp Alternatively you can store your data in a plain file and simply display its last values non-interactively. .Pp When new data is written, the value is plotted and the cursor position is advanced. That is, the graph scrolling speed is determined by the speed of the data flow. When the number of received values is above the specified horizontal size, the graph will wrap or scroll, depending on your settings. .\" .Ss ASCII DATA The default data format is a space/tab/newline-separated series of parseable ASCII numbers; eg: .Bd -literal -offset indent 1 2 3 4 5.1 0642 0x12 \-12.4E5 .987 .Ed .Pp The parser is very lenient, and will silently ignore whatever looks like garbage. .\" .Ss COUNTING MODES By default all input values are considered absolute and displayed "as is" in a single graph. .Pp The .Fl c Ar [N]mode flag sets an alternate counting mode and the number of available graphs. Available modes are: .Pp .Bl -tag -offset indent -compact -width " a " .It Ar a absolute (default) .It Ar i incremental counter .It Ar d differential values .El .Pp In incremental and differential mode, each value is calculated using the previous value as a reference except for the first, which is taken as absolute. The number of graphs can be specified by prefixing a multiplier before the counting mode (eg: .Ar 2a draws two graphs in absolute mode). See .Sx MULTIPLE GRAPHS for more details on how this affects the input stream. .\" .Ss FORMAT TYPES Different input formats are supported, as specified by the .Fl f flag. Note however that only the ASCII parser (the default) silently ignores errors. NaNs and Infinity have special treatment. Internally, .Nm always works with double precision floating points: conversion toward these is performed with the default FPU conversion rules. The actual underlying binary format depends on the host architecture: .Pp .Bl -tag -offset indent -compact -width " a " .It Ar a ASCII parser (default) .It Ar f binary float .It Ar d binary double .It Ar s binary short .It Ar i binary int .It Ar l binary long .El .\" .Ss SPECIAL VALUES ASCII and binary floating point input have special treatment for NaNs and Infinity (entered in any representable form). Both are considered as "undefined values". Undefined values can be highlighted, but aren't otherwise rendered. If the .Fl e flag is set, Infinity enters an escape sequence instead (See .Sx ESCAPE SEQUENCES ) .\" .Ss MULTIPLE GRAPHS Multiple graphs can be displayed inside a single trend instance by specifying a prefix number N for the .Fl c flag. The input is interleaved, but otherwise unchanged: the reference value, if needed, is expected to be seen N times, one for each graph. Thus, for three graphs (A, B and C), the input order is: .Bd -literal -offset indent .Op A0 B0 C0 A1 B1 C1 A2 B2 C2 \&.. .. .. .Ed .Pp The display is updated only once all graph values are read. The color, label and origin for each graph can be specified through the usual command-line flags, separating each value with a comma; in the same order as the input. Default colors and labels are assigned if not completely specified. .Pp All graphs share and are affected by the same settings, except for the origin (zero) which can be changed independently. Filling, values and the examiners only work on the current graph. The current graph can be cycled dynamically with the .Ic TAB key and differentiated using the .Ic K key, which cycles between "normal", "dim others" and "hide others" views. The graph key, if enabled, also highlights the current graph. .\" .Ss ESCAPE SEQUENCES If escape sequences are enabled (through the .Fl e flag), entering Infinity (in any representable form) will start an escape sequence. Currently, this feature is not yet implemented: Infinity is simply discarded. This is reserved for future use as a way to control the .Nm interface and parameters remotely. .\" .\" .Sh OPTIONS .\" .Ss FLAGS .Bl -tag -compact -width " \-I colour[,colour...] " .It Fl d "dimmed" shading mode .It Fl D visible distribution graph .It Fl S enable anti-aliasing .It Fl s "scrolling" mode .It Fl v visible values .It Fl l visible visual/max sync latency .It Fl m visible marker .It Fl F enable filling .It Fl g visible grid .It Fl G Ar grid-spec specify grid resolution .It Fl z Ar zero[,zero...] specify y zero/s .It Fl h help and version info .It Fl t Ar str specify a window title .It Fl A Ar colour background colour .It Fl E Ar colour text (values) colour .It Fl R Ar colour grid colour .It Fl I Ar colour[,colour...] trend colour/s .It Fl M Ar colour marker colour .It Fl N Ar colour interactive examiner colour .It Fl T Ar colour edit mode colour .It Fl L Ar label[,label...] trend label/s .It Fl c Ar mode input number/counting mode (See .Sx COUNTING MODES ) .It Fl f Ar format input format (See .Sx FORMAT TYPES ) .It Fl p Ar rate polling rate (hz) .It Fl u show undefined values .It Fl e enable escape sequences (See .Sx ESCAPE SEQUENCES ) .It Fl display .No See Xr X 7 . .It Fl geometry .No See Xr X 7 . .It Fl iconic .No See Xr X 7 . .El .\" .Ss HIST-SPEC An history specification is another convenient form of defining the pair `hist-sz x-sz` for common cases. An history specification can be in either one of the following formats: .Pp .Bl -tag -compact -offset indent -width " NxM " .It Ar N Sets x-sz to N, and hist-sz to N+1. .It Ar N/M Sets hist-sz to N, and x-sz to N/M. .It Ar NxM Sets x-sz to N, and hist-sz to N*M. .El .Pp While this may seem hard at first, .Ic trend fifo '60x3' is an easier way of expressing "60 seconds for 3 minutes" and similar idioms. .\" .Ss COLOUR A colour is specified in hex RGB format, as follows: .Li #RRGGBB , RRGGBB No or Li 0xRRGGBB ; some examples: .Pp .Bl -tag -compact -offset indent -width " #000000 " .It Li #FF0000 red .It Li #00FF00 green .It Li #A020F0 purple .El .\" .Ss GRID-SPEC A grid specification is of the form: .Pp .Dl [[A][+C]][x[B][+C]] .Pp (eg: .Li 1.3 , 10+5 , 1x10+5 , +5x+5 ; +1x+1 gets the old behaviour) where: .Pp .Bl -tag -compact -offset indent -width " A " .It Va A y grid resolution .It Va B x grid resolution .It Va C draw a mayor line every C normal grid lines .El .\" .\" .Sh DISPLAY .\" .Ss INTERACTIVE KEYS .Bl -tag -compact -offset indent -width " space " .It Ic ESC quit/exit .It Ic TAB cycle current graph .It Ic a toggle auto-scaling .It Ic A re-scale the graph without activating auto-scaling .It Ic d toggle dimmed shading mode .It Ic D toggle distribution graph .It Ic S toggle anti-aliasing .It Ic s switch scrolling mode (wrap-around or scrolling) .It Ic v toggle values .It Ic l show visual and maximal sync latency .It Ic L set limits interactively .It Ic m activate a marker on the current cursor position .It Ic f toggle filling .It Ic g toggle grid .It Ic G change grid-spec interactively .It Ic z change zero interactively .It Ic Z set limits by center and amplitude .It Ic p change polling rate interactively .It Ic u toggle display of undefined values .It Ic k toggle the graph key .It Ic K cycle view mode (normal, dim others or hide others) .It Ic space pause visualisation (but still continue to consume input to preserve time coherency) .El .\" .Ss AUTOSCALING When autoscaling is enabled the graph will be scaled vertically to fit visible values. The grid resolution is used to add some vertical bounds to the graph. Disabling autoscaling interactively will retain current limits. When the grid is too dense to be displayed it's deactivated automatically. .\" .Ss LATENCY INDICATOR The latency indicator shows a 5s average of the visual and maximal sync latency (in seconds). The visual latency is the time-frame between real value updates and the final output you're seeing: it includes copy/redraw times, which varies depending on enabled layers, plus video sync. The maximal sync latency is the maximal time ever required for any received value to be synced with the display: since the display is updated atomically, values received while redrawing are implicitly delayed. See the .Sx UPDATE POLICY section for further details. .\" .Ss SHADING MODES The default is to shade uniformly old values to complete transparency. The "dimmed" shading mode draws the foreground values with full opacity and the others with half opacity. .\" .Ss SCROLLING MODES The default visualisation mode is "wrap-around": newer values will simply wrap around the screen when new data arrives. The other available one is "scrolling": new data is always placed at the right edge of the screen, and older values scrolled on the left. .\" .Ss VALUE INDICATORS Three value indicators are drawn on the screen: upper limit, lower limit and current value (respectively on the upper right, lower right and lower left of the screen). .\" .Ss INTERACTIVE EXAMINERS You can query interactively the graph for any value in the history by clicking with the first mouse button. This will enable a permanent examiner in the selected position and display up to the three nearest values in the upper-left corner of the screen. Intersections are projected horizontally, while a small circle will show the position of the nearest sampled value. The mean value refers to the three intersections. .Pp By holding down the CTRL key while clicking/dragging only "foreground" values will be considered. .Pp When clicking inside the distribution graph, the current count for the selected value is displayed instead. .Pp The examiners can be removed by clicking anywhere with the third mouse button. .\" .Ss DISTRIBUTION GRAPH .Ic D No or Fl D enable a distribution graph on the left side of the window. This is especially useful when analyzing the continuity of a function or signal. Intensity is proportional to the visible maximum. .\" .Ss FILLING .Ic f No or Fl F enable filling. In standard mode, or when hist-sz is smaller than x-sz, the area between the curve and zero will be filled. Otherwise, in dimmed mode, the area between the "foreground" and "background" values is filled instead. .\" .\" .Sh UPDATE POLICY .Bl -item .It The fifo is read and managed asynchronously from the graphics. Delays at the display end will not interfere with the data feed. .It The fifo is unbuffered and the feeder thread is synchronously locked on it waiting for new data. .It The value is put in the history buffer when a separator character is received after the value, or, for binary input, when the needed amount of bytes is read (in this case each value is read with a single read call). .It The polling rate (as defined by .Ic p No or Fl p and defaulting to 1000) defines how often the history buffer should be checked for updates and kept in sync with the visual. Values greater than 1000 result in continuous scanning (note that this only affects the maximal sync latency, and not the display rate, which is handled automatically). .It Syncing occurs atomically, reflecting the actual state at the instant of the update. Scheduler latencies apply. .El .\" .\" .Sh ENVIRONMENT .Ev DISPLAY See Xr X 7 . .\" .\" .Sh EXAMPLES Running .Nm with a named FIFO: .Pp .Dl mkfifo fifo .Dl command > fifo & .Dl trend fifo ... .Pp Display the number of current active processes over time: .Pp .Dl (while true; do ps \-A | wc \-l; sleep 1; done) | \e .Dl trend \- 60x24 .Pp Display two graphs: .Pp .Dl trend \-c2a \-L"graph 1, graph 2" fifo ... .\" .\" .Sh DIAGNOSTICS .Ex -std .\" .\" .Sh ERRORS .Bl -diag .It trend: producer thread exiting The data stream finished for some reason (the specified file was invalid at the time of the request). For regular or invalid files this warning is normal. .El .\" .\" .Sh SEE ALSO .Xr mkfifo 1 , .Xr stdin 4 , .Xr fd 4 , .Pa /usr/share/doc/trend/examples/ .\" .\" .Sh AUTHORS .Nm is distributed under LGPL (see COPYING) .Em WITHOUT ANY WARRANTY . Copyright(c) 2003-2009 by .An "Yuri D'Elia" Aq wavexx@thregr.org . trend-1.4/THANKS.rst0000644000000000000000000000020411454047245012714 0ustar rootrootAndras Horvath http://cern.ch/ahorvath/ * S/RPMs maintenance Liam MacKenzie * Testing and suggestions trend-1.4/TODO.rst0000644000000000000000000000062511454047245012500 0ustar rootrootPlanned features * More optimisations can be done for: different shading modes, different input types. * Faster oscilloscope controls like: graph offsetting, zooming and panning. * Remote control via stdin. * Internal refactoring. * Infinity support is lacking (lines, fill and integration could be correctly implemented by using signbit() instead of ignoring the value completely). trend-1.4/COPYING.txt0000644000000000000000000006350411454047245013057 0ustar rootroot GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! trend-1.4/README.rst0000644000000000000000000001513312647742300012667 0ustar rootroot=============================================== Trend: a general-purpose, efficient trend graph =============================================== trend is a general-purpose, efficient trend graph for "live" data. Data is read in ASCII form from a file or continuously from a FIFO and displayed in real-time into a multi-pass trend (much like a CRT oscilloscope). trend can be used as a rapid analysis tool for progressive or time-based data series together with trivial scripting. .. contents:: Features and requirements ========================= Features: - OpenGL graphics - Automatic or fixed graph scaling - Two graph scrolling, shading and filling modes - Configurable colours/grid - Flexible input - Interactivity Requirements: - OpenGL - GLUT (http://www.opengl.org/resources/libraries/glut.html) or (preferably) FreeGLUT (http://freeglut.sourceforge.net/) - A recent C++ compiler - POSIX system (currently tested on Solaris, FreeBSD, OS X, Linux and IRIX). Building ======== Cd into the distribution's "src" directory and execute "make". Compiler optimisations are left to the user. Set your standard compiler flags (CPPFLAGS/CXXFLAGS/LDFLAGS) before building. Copy the resulting "src/trend" executable and trend's manual "trend.1" where appropriate. trend should work on any POSIX/OpenGL capable system. Usage examples ============== Some simple example scripts are included in the package. Within the "examples" directory you can find: ``./mem ``: Print-out active memory (incl. swap) of a linux kernel using /proc/meminfo using Perl each tenth of second or the specified number of seconds. ``./imem ``: The same using pmval from Peformance Co-Pilot. ``./net [if]``: Show network usage (in and out) in bytes using /proc/net/dev using Perl (the default network interface if you don't specify any is eth0). ``./tstimes``: A more complicated example I use to display server production times without particular requirements (the log is parsed and displayed in realtime). ``./timeq [-s] ``: Time-quantize ASCII input: show an average (or total with -s) for received values (from stdin) in the specified time-lapse. A common example of usage would be in conjunction with the preceding "tstimes", or see the following example with apache. Note that timeq outputs binary values to avoid double-parses (see/use -fd on the command line). The ASCII parser is not as flexible as trend's and requires each value to be in a separated line. Do not use this sample implementation for any serious work. In the following example we will display the latest two minutes of network activity (with the first one being in front of the other) sampled each tenth of second:: ./examples/net 0.1 | trend -c2a -Lin,out - 1200 600 To display the number of current active processes over time you can do:: (while true; do ps -A | wc -l; sleep 1; done) | trend - ... Bytes roughly transferred each minute on an apache server?:: tail -f access.log | \ sed -une 's/.* \([0-9][0-9]*\) [0-9]*$/\1/p' | \ ./examples/timeq -s 60 | trend -fd -d - 60x24 An example of using snmpdelta from the NET-SNMP utilities to monitor a remote IF-MIB network interface:: snmpdelta -v1 -CT -c public router ifInOctets.1 | trend - ... A collection of contributed data-gathering scripts is kept at http://www.thregr.org/~wavexx/software/trend/contrib/ (if you want to make a contribution just mail me). Alternatively, many (if not all) of the contributed MRTG scripts are a valuable resource to system administrators in particular. Accurate timing =============== trend was designed with accuracy and speed in mind (I use it literally as a virtual oscilloscope). For this reasons trend offloads to the caller both the timing and sampling responsibility, allowing trend to be used for any purpose with maximum precision. For the non-experts, the scripting convention of sleeping a fixed amount of time after sampling the value will lead to cumulative timing errors. ASCII input by itself adds a variable delay, so use binary formats when performance and latency are a concern. General/support mailing list ============================ If you feel to discuss improvements and suggestions, and/or test beta releases before announcement you can subscribe to `trend-users` by either sending an empty email to , using GMane_ (group "gmane.comp.graphics.trend.general") or by contacting the author at . The archives are accessible via web through http://news.gmane.org/gmane.comp.graphics.trend.general or via news directly. .. _GMane: http://www.gmane.org/ Troubleshooting =============== trend crashes on start with SIGBUS/SIGSEGV: This problem experienced on some machines is caused by the new joystick support present in FreeGLUT 2.2.0. Either use standard GLUT, or upgrade to a later/cvs version of FreeGLUT (nightly snapshots are fine), where joystick initialisation has been made conditional. Screen-shots ============ Due to popular demand, here's how the screen-shots as found in http://www.thregr.org/~wavexx/software/trend/ were generated: trend-and-ion: Several instances of trend running under the `ION `_ window manager. Data source: /proc/ and mrtg-utils. trend-distrib: trend with the distribution graph active, showing a sine, tangent, random-incremental and random function. trend-intr: ``trend -d fifo 1200 600``, with the interactive examiners active. Input is from a custom board. trend-oversample: ``trend -S -I 0x00FF00 fifo 10000x3`` on a ~700 pixels wide window (implicit 1x14 oversampling), showing buffer and visual latency in respect to the source (taken before the actual release). trend-qtac: Multiple instances of trend running as a server room monitoring system. Courtesy of Liam MacKenzie and qtac.edu.au Further customisation and development ===================================== Almost all internal aspects and defaults of trend can be changed by modifying "defaults.hh" and recompiling. If you feel that a default should be changed or an internal constant be exposed contact me to make the change customizable instead. trend's GIT repository is publicly accessible at:: git://src.thregr.org/trend or at https://github.com/wavexx/trend Authors and Copyright ===================== trend is distributed under LGPL (see COPYING) WITHOUT ANY WARRANTY. Copyright(c) 2003-2016 by wave++ "Yuri D'Elia" . Suggestions/comments are welcome. A new version of trend is coming out shortly, so don't hesitate. Latest trend versions can be downloaded from http://www.thregr.org/~wavexx/software/trend/ trend-1.4/NEWS.rst0000644000000000000000000001065112742656624012517 0ustar rootroottrend 1.4 17/07/2016 -------------------- * Fixed another build failure with GCC 6.1. trend 1.3 20/01/2016 -------------------- * Fixed build failure with GCC >= 6. * Fixed spelling errors in the manpage. trend 1.2 17/11/2009 -------------------- * Fix linking error with "binutils-gold" trend 1.1 14/08/2009 -------------------- * Auto-scaling now considers only the current graph when multiple graphs are present and "hide others" is in effect. * 'Legend' is now properly called 'Key'. The 'nN' key bindings were also remapped to 'kK' for consistency. * Infinity is now handled like NaNs. * DEPRECATES: 'nN' key bindings are still available, but should no longer be used, use 'kK' instead. trend 1.0 11/08/2009 -------------------- * Fix man page warnings. * Use a traditional version numbering scheme. Rev #58 03/10/2006 to Rev #68 02/11/2007 ---------------------------------------- * Polling rate limits can now be configured dynamically. * Latency sampling now also shows maximal sync times. * NaNs can now be entered in the stream and highlighted. * Memory usage reduction (reduced in half). * 'Z' allows to specify view limits by center and amplitude. * Support for multiple graphs in a single instance. * Using '-' as a file name now causes stdin to be read. Rev #54 28/04/2006 to Rev #58 03/10/2006 ---------------------------------------- * Graph filling can be enabled with 'f'. * 'd' now affects filling mode as well. * Messages are now removed also when paused. * Created a man page (trend.1). Rev #49 05/12/2005 to Rev #54 28/04/2006 ---------------------------------------- * Changing zero now aligns the graph instead of the grid. * Fixed hung on negative 'grid-spec'. Rev #44 23/07/2005 to Rev #49 05/12/2005 ---------------------------------------- * Console is no longer used for input, an embedded line editor is now used (ie when setting limits/grid-spec interactively, stdin will eventually be used for remote controlling). * Console is no longer used for output (except for fatal errors), messages are now displayed on screen. * Zero can be set interactively with 'z'. * Dragging inside the distribution graph now shows the distribution count for the selected value. Rev #40 15/04/2005 to Rev #44 23/07/2005 ---------------------------------------- * Solaris build fixes. * Ported to OS X. Rev #35 14/12/2004 to Rev #40 15/04/2005 ---------------------------------------- * Correctly align X grid lines in scrolling mode. * hist-spec now uses "x" instead of "*". * Support for direct binary input. * New example (see timeq) and cleanup. * DEPRECATES: N*M hist-specs should no longer be used, use NxM instead. -i and -r flags should no longer be used, use -ci -cd. Rev #27 02/11/2004 to Rev #35 14/12/2004 ---------------------------------------- * An "history specification" can be used on the command line as a simplified alternative to the hist-sz/x-div pair. * Visual latency sampling/visualisation. * Differential input. * Grid enhancements/offsetting. Rev #23 29/10/2004 to Rev #27 02/11/2004 ---------------------------------------- * Incorrectly initialised buffers could cause interactive indicators to malfunction for first values. * Visualisation can be paused while still consuming data. * 'A' re-scales the graph without activating auto-scaling. Rev #20 21/10/2004 to Rev #23 29/10/2004 ---------------------------------------- * Optimisations and huge internal latency reductions. * Fixed precision truncation in auto-scaling. * Fixed scrolling mode for "history" non multiple of "divisions". * Created a support/testing mailing list. See README for details. Rev #15 27/09/2004 to Rev #20 21/10/2004 ---------------------------------------- * Implemented distribution graph. * Fixed trend for plain files. * Fixed parsing bug (unterminated buffer). * Fixed precision truncation in drawing code. Rev #11 21/09/2004 to Rev #15 27/09/2004 ---------------------------------------- * Fixed standard X11/GLUT options (-display, -geometry, etc) * Implemented interactive indicators. Rev #4 09/09/2004 to Rev #11 21/09/2004 --------------------------------------- * Several optimisations. Code cleanup. * Colours are configurable. * All options have a command line flag now. * current/min/max values can be shown on the graph. * New shading mode. * Input can be an incremental counter. * Grid positioning was fixed. * The grid now disables itself when it's too dense to be drawn. * Auto-scaling can be toggled dynamically. trend-1.4/src/0000755000000000000000000000000012742657152011772 5ustar rootroottrend-1.4/src/color.cc0000644000000000000000000000125312256034167013413 0ustar rootroot/* * color: color parsing/lookup functions - implementation * Copyright(c) 2004 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ /* * Headers */ // interface #include "color.hh" // system headers #include using std::strtoul; /* * Implementation */ GLfloat* parseColor(GLfloat* buf, const char* color) { // parse the value unsigned long v = strtoul((color[0] == '#'? color + 1: color), NULL, 16); // separate the components buf[0] = static_cast((v >> 16) & 0xFF) / 255.; buf[1] = static_cast((v >> 8) & 0xFF) / 255.; buf[2] = static_cast((v) & 0xFF) / 255.; return buf; } trend-1.4/src/color.hh0000644000000000000000000000054412256034167013427 0ustar rootroot/* * color: color parsing/lookup functions * Copyright(c) 2004-2005 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ #ifndef color_hh #define color_hh // GL headers #include "gl.hh" // parse a color in hexadecimal format ([[#]0x]RRGGBB) GLfloat* parseColor(GLfloat* buf, const char* color); #endif trend-1.4/src/trend.cc0000644000000000000000000012220512742656772013426 0ustar rootroot/* * trend: display live data on a trend graph * Copyright(c) 2003-2016 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ /* * Headers */ // force C99 macros in libstdc++ (for compatibility with other standards) #define _GLIBCXX_USE_C99_MATH 1 // defaults #include "version.h" #include "defaults.hh" #include "color.hh" #include "timer.hh" #include "rr.hh" using Trend::Value; // system headers #include #include #include using std::vector; #include using std::deque; #include using std::cout; using std::cerr; #include using std::string; #include using std::pair; #include using std::numeric_limits; // c system headers #include using std::strtod; using std::strtoul; #include using std::memcpy; using std::strlen; using std::strpbrk; using std::strchr; using std::strcmp; #include #include #include #include #include #include #include // OpenGL/GLU #include "gl.hh" #ifndef NAN #define NAN (numeric_limits::quiet_NaN()) #endif #ifndef INF #define INF (numeric_limits::infinity()) #endif typedef void (*edit_callback_t)(const string& str); /* * Data structures */ struct Intr { // nearest value double near; size_t pos; // intersection double value; double dist; }; struct Graph { rr* rrData; Value* rrBuf; Value* rrEnd; size_t rrPos; double zero; GLfloat lineCol[3]; string label; }; bool operator<(const Intr& l, const Intr& r) { return (l.dist < r.dist); } struct Grid { double res; unsigned long mayor; }; struct GrSpec { Grid x; Grid y; }; /* * Graph/Program state * TODO: refactor! refactor! refactor! */ namespace { // Basic data const char* fileName; pthread_mutex_t mutex; volatile bool damaged = false; Trend::input_t input = Trend::input; Trend::format_t format = Trend::format; bool allowEsc = false; // Main graph data vector graphs; Graph* graph; double loLimit; double hiLimit; bool autoLimit; // Graph defaults vector lineCol; vector labels; vector zeros; // Visual/Fixed settings size_t history; size_t divisions; size_t offset; const char* title = NULL; GLfloat backCol[3]; GLfloat textCol[3]; GLfloat gridCol[3]; GLfloat markCol[3]; GLfloat intrCol[3]; GLfloat editCol[3]; // Visual/Changeable settings int width; int height; int lc; bool dimmed = Trend::dimmed; bool smooth = Trend::smooth; bool scroll = Trend::scroll; bool values = Trend::values; bool marker = Trend::marker; bool filled = Trend::filled; bool showUndef = Trend::showUndef; Trend::view_t view = Trend::view; bool grid = Trend::grid; GrSpec grSpec; bool paused = false; deque > messages; int pollMs = Trend::pollMs; // Key bool graphKey; size_t maxLabel = 0; size_t maxValue = 0; // Indicator status bool intr = false; bool intrFg; double intrX; double intrY; // Distribution graph bool distrib = Trend::distrib; vector distribData; // Latency bool latency = Trend::latency; ATimer atVLat(Trend::latAvg); ATimer atBLat(Trend::latAvg); double bLat = 0.; double vLat = 0.; // Edit form bool edit; edit_callback_t editCallback; string editTitle; string editStr; } /* * I/O and data manipulation */ // fill the round robin consistently with a single value void rrFill(const Graph& g, double v) { for(size_t i = 0; i != history; ++i) g.rrData->push_back(v); } // shift values void rrShift(const Graph& g, double v) { for(Value* it = g.rrBuf; it != g.rrEnd; ++it) *it -= v; } // skip whitespace void skipSpc(FILE* fd) { int c; do { c = getc_unlocked(fd); } while(isspace(c) && c != EOF); ungetc(c, fd); } // skip a space-separated string void skipStr(FILE* fd) { int c; do { c = getc_unlocked(fd); } while(!isspace(c) && c != EOF); ungetc(c, fd); } // read a space-separated string char* readStr(FILE* fd, char* buf, size_t len) { char* p(buf); int c; while(len--) { c = getc_unlocked(fd); if(c == EOF || isspace(c)) { ungetc(c, fd); return p; } *p++ = c; } // overflow return NULL; } // read a number from an ascii stream bool readANum(FILE* fd, double& v) { for(;;) { // read skipSpc(fd); char buf[Trend::maxNumLen]; char* end = readStr(fd, buf, sizeof(buf) - 1); if(feof(fd)) return false; if(!end) { // long string, skip it. skipStr(fd); continue; } *end = 0; // convert the number v = strtod(buf, &end); if(end != buf) break; } return true; } // read a number from a binary stream template bool readNum(FILE* fd, double& v) { T buf; if(fread(&buf, sizeof(buf), 1, fd) != 1) return false; v = static_cast(buf); return true; } // read up to the first number in the stream using the current format bool readFNum(FILE* fd, double& v) { switch(format) { case Trend::f_ascii: return readANum(fd, v); case Trend::f_float: return readNum(fd, v); case Trend::f_double: return readNum(fd, v); case Trend::f_short: return readNum(fd, v); case Trend::f_int: return readNum(fd, v); case Trend::f_long: return readNum(fd, v); } return false; } // read/handle incoming escape sequences bool readEsc(FILE* fd) { // TODO: incomplete return true; } // read the next valid element from the stream bool readNext(FILE* fd, double& v) { if(!allowEsc) return readFNum(fd, v); while(readFNum(fd, v)) { if(!isinf(v)) return true; if(!readEsc(fd)) break; } return false; } // producer thread void* producer(void* prg) { // iostreams under gcc 3.x are completely unusable for advanced tasks such as // customizable buffering/locking/etc. They also removed the (really // standard) ->fd() access for "encapsulation"... FILE* in; // some buffers size_t ng = graphs.size(); double* old = new double[ng]; for(;;) { // open the file and disable buffering in = (*fileName? fopen(fileName, "r"): stdin); if(!in) break; setvbuf(in, NULL, _IONBF, 0); // check for useless file types struct stat stBuf; fstat(fileno(in), &stBuf); if(S_ISDIR(stBuf.st_mode)) break; // first value for incremental data if(input != Trend::absolute) for(size_t i = 0; i != ng; ++i) if(!readNext(in, old[i])) goto end; // read all data for(;;) { for(size_t i = 0; i != ng; ++i) { double num; if(!readNext(in, num)) goto end; // determine the actual value switch(input) { case Trend::incremental: { double tmp = num; num -= old[i]; old[i] = tmp; } break; case Trend::differential: old[i] += num; num = old[i]; break; default:; } // append the value graphs[i].rrData->push_back(num); } // notify pthread_mutex_lock(&mutex); if(!damaged) { atBLat.start(); damaged = true; } pthread_mutex_unlock(&mutex); } end: // close the stream and terminate the loop for regular files fclose(in); if(S_ISREG(stBuf.st_mode) || S_ISBLK(stBuf.st_mode)) break; } // should never get so far delete []old; cerr << reinterpret_cast(prg) << ": producer thread exiting\n"; return NULL; } /* * OpenGL functions */ // project model coordinates void project(double xi, double yi, int& xo, int& yo) { int width(distrib? ::width - Trend::distribWidth: ::width); int off(distrib? Trend::distribWidth: 0); xo = (off + static_cast(xi * width / divisions)); yo = static_cast((yi - loLimit) * height / (hiLimit - loLimit)); } // unproject video to model coordinates void unproject(int xi, int yi, double& xo, double& yo) { int width = (distrib? ::width - Trend::distribWidth: ::width); int xr = (distrib? xi - Trend::distribWidth: xi); xo = (static_cast(divisions) * xr / width); yo = hiLimit - (static_cast(hiLimit - loLimit) * yi / height); } // OpenGL state initializer void init() { // Smoothing if(smooth) { glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); } else glDisable(GL_LINE_SMOOTH); // Blending should be enabled by default glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Clear color glClearColor(backCol[0], backCol[1], backCol[2], 0.0); } // Resize handler void reshape(const int w, const int h) { width = w; height = h; glViewport(0, 0, w, h); } // write a normal string void drawString(const int x, const int y, const string& str) { glRasterPos2i(0, 0); glBitmap(0, 0, 0, 0, x, y, NULL); for(string::const_iterator p = str.begin(); p != str.end(); ++p) glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *p); } // write strings in the lower-left corner void drawLEString(const string& str) { drawString(Trend::strSpc, Trend::strSpc + Trend::fontHeight * lc++, str); } // push a message void pushMessage(const string& str) { messages.push_back(pair(time(NULL), str)); while(messages.size() > static_cast(Trend::maxPersist)) messages.pop_front(); } // write an on-screen string using video coordinates void drawOSString(const int x, const int y, const string& str) { using Trend::strSpc; using Trend::fontHeight; using Trend::fontWidth; int len(str.size() * fontWidth); int rx(x + strSpc); int ry(y + strSpc); // check x if((rx + strSpc + len) > width) rx = width - len - strSpc; if(rx < 0) rx = strSpc; // check y if((ry + strSpc + fontHeight) > height) ry = height - fontHeight - strSpc; if(ry < 0) ry = strSpc; drawString(rx, ry, str); } void drawGridX(double gridres) { // horizontal lines double it; glBegin(GL_LINES); if(scroll) for(it = divisions; it > 0; it -= gridres) { glVertex2d(it, loLimit); glVertex2d(it, hiLimit); } else for(it = gridres; it <= divisions; it += gridres) { glVertex2d(it, loLimit); glVertex2d(it, hiLimit); } glEnd(); } void drawGridY(double gridres) { // vertical lines double it = loLimit - fmod(loLimit, gridres); if(it <= loLimit) it += gridres; glBegin(GL_LINES); for(; it < hiLimit; it += gridres) { glVertex2d(0, it); glVertex2d(divisions, it); } glEnd(); } void drawGrid() { using Trend::maxGridDens; double r, d; // x r = (divisions / grSpec.x.res); d = (width / maxGridDens); if(r < (d * grSpec.x.mayor)) { // minor lines if(grSpec.x.mayor != 1 && r < d) { glColor4f(gridCol[0], gridCol[1], gridCol[2], 0.5); drawGridX(grSpec.x.res); } // mayor lines if(grSpec.x.mayor) { glColor3fv(gridCol); drawGridX(grSpec.x.res * grSpec.x.mayor); } } // y r = ((hiLimit - loLimit) / grSpec.y.res); d = (height / maxGridDens); if(r < (d * grSpec.y.mayor)) { // minor lines if(grSpec.y.mayor != 1 && r < d) { glColor4f(gridCol[0], gridCol[1], gridCol[2], 0.5); drawGridY(grSpec.y.res); } // mayor lines if(grSpec.y.mayor) { glColor3fv(gridCol); drawGridY(grSpec.y.res * grSpec.y.mayor); } } } void drawMarker(const double x) { glColor3fv(markCol); glBegin(GL_LINES); glVertex2d(x, loLimit); glVertex2d(x, hiLimit); glEnd(); } void drawCircle(const int x, const int y) { using Trend::intrRad; // ok, it's not really a circle. glBegin(GL_LINE_LOOP); glVertex2i(x - intrRad, y); glVertex2i(x, y + intrRad); glVertex2i(x + intrRad, y); glVertex2i(x, y - intrRad); glEnd(); } // get count/drawing position based on current settings size_t getCount(const Graph& g, const Value* v) { return g.rrPos - (g.rrEnd - v); } size_t getPosition(const Graph& g, size_t pos, const Value* v) { return ((scroll? pos: getCount(g, v)) % divisions); } size_t drawLine(const Graph& g, double alphaMul) { const Value* it = g.rrBuf; const Value* nit = it + 1; const size_t mark(history + offset - divisions - 1); bool st = false; size_t pos = 0; for(size_t i = offset; it != g.rrEnd; ++i, ++it, ++nit) { if(!st && isfinite(*it) && (nit == g.rrEnd || isfinite(*nit))) { st = true; glBegin(GL_LINE_STRIP); } // shade the color double alpha(dimmed? (i > mark? 1.: .5): (static_cast(i - offset) / history)); glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], alpha * alphaMul); pos = getPosition(g, i, it); if(st) { if(pos) glVertex2d(pos, *it); else { // Cursor at the end glVertex2d(divisions, *it); glEnd(); glBegin(GL_LINE_STRIP); glVertex2d(0, *it); } } else if(isfinite(*it)) { glBegin(GL_LINES); if(pos) { glVertex2d(pos - 0.5, *it); glVertex2d(pos + 0.5, *it); } else { glVertex2d(0, *it); glVertex2d(0.5, *it); glVertex2d(divisions, *it); glVertex2d(divisions - 0.5, *it); } glEnd(); } if(st && (nit == g.rrEnd || !isfinite(*nit))) { glEnd(); st = false; } } return pos; } void drawFillZero(const Graph& g) { const size_t m = std::min(history, divisions + 1); const size_t mark(history + offset - m); const Value* it = g.rrEnd - m; const Value* nit = it + 1; bool st = false; Value last = NAN; glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], Trend::fillTrendAlpha); for(size_t i = mark; it != g.rrEnd; ++i, ++it, ++nit) { if(!st && isfinite(*it) && (nit == g.rrEnd || isfinite(*nit))) { last = *it; st = true; glBegin(GL_QUAD_STRIP); } if(st) { size_t pos = getPosition(g, i, it); if((last < 0) != (*it < 0)) { // extra truncation needed double zt = (pos? pos: divisions) - *it / (*it - last); glVertex2d(zt, 0); glVertex2d(zt, 0); } last = *it; if(pos) { glVertex2d(pos, *it); glVertex2d(pos, 0); } else { // cursor at the end glVertex2d(divisions, *it); glVertex2d(divisions, 0); glEnd(); glBegin(GL_QUAD_STRIP); glVertex2d(0, *it); glVertex2d(0, 0); } if(nit == g.rrEnd || !isfinite(*nit)) { glEnd(); st = false; } } } } void drawFillDelta(const Graph& g) { const size_t m = std::min(history - divisions, divisions + 1); const size_t mark(history + offset - m); const Value* it = g.rrEnd - m; const Value* nit = it + 1; bool st = false; Value l1 = NAN; Value l2 = NAN; glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], Trend::fillTrendAlpha); glBegin(GL_QUAD_STRIP); for(size_t i = mark; it != g.rrEnd; ++i, ++it, ++nit) { Value v1 = *it; Value v2 = *(it - divisions); if(!st && (isfinite(v1) && (nit == g.rrEnd || isfinite(*nit))) && (isfinite(v2) && isfinite(*(nit - divisions)))) { l1 = v1; l2 = v2; st = true; glBegin(GL_QUAD_STRIP); } if(st) { size_t pos = getPosition(g, i, it); if((v1 < v2) != (l1 < l2)) { // extra truncation needed double r = (l1 - l2) / (l1 - v1 - l2 + v2); double zx = (pos? pos: divisions) - 1 + r; double zy = l1 + (v1 - l1) * r; glVertex2d(zx, zy); glVertex2d(zx, zy); } if(pos) { glVertex2d(pos, v1); glVertex2d(pos, v2); } else { // cursor at the end glVertex2d(divisions, v1); glVertex2d(divisions, v2); glEnd(); glBegin(GL_QUAD_STRIP); glVertex2d(0, v1); glVertex2d(0, v2); } l1 = v1; l2 = v2; if(nit == g.rrEnd || !isfinite(*nit) || !isfinite(*(nit - divisions))) { glEnd(); st = false; } } } } void drawFill(const Graph& g) { if(!dimmed || history < divisions + 2) drawFillZero(g); else drawFillDelta(g); } void drawFillUndef(const Graph& g) { const size_t m = std::min(history, divisions + 1); const size_t mark(history + offset - m); const Value* it = g.rrEnd - m; const Value* nit = it + 1; bool st = false; size_t pos; glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], Trend::fillUndefAlpha); for(size_t i = mark; it != g.rrEnd; ++i, ++it, ++nit) { if(!st && ((nit == g.rrEnd && !isfinite(*it)) || !isfinite(*nit))) { st = true; glBegin(GL_QUAD_STRIP); } if(st) { pos = getPosition(g, i, it); if(pos) { glVertex2d(pos, loLimit); glVertex2d(pos, hiLimit); } else { glVertex2d(divisions, loLimit); glVertex2d(divisions, hiLimit); glEnd(); glBegin(GL_QUAD_STRIP); glVertex2d(0, loLimit); glVertex2d(0, hiLimit); } if(nit == g.rrEnd || (isfinite(*it) && isfinite(*nit))) { glEnd(); st = false; } } } } void drawDistrib() { // reallocate only if necessary. we must avoid to reallocate in order to // not fragment memory (resize() on gcc 3 isn't very friendly) if(distribData.size() != static_cast(height)) distribData.resize(height); // calculate distribution const Value* it = graph->rrBuf; const Value* end = graph->rrEnd - 1; distribData.assign(distribData.size(), 0.); double max = 0; for(; it != end; ++it) { const Value* a = it; const Value* b = (it + 1); if(!isfinite(*a) || !isfinite(*b)) continue; // projection double mul = (static_cast(height) / (hiLimit - loLimit)); int begin = static_cast(mul * (*a - loLimit)); int end = static_cast(mul * (*b - loLimit)); if(begin > end) std::swap(begin, end); // fixation if(end < 0 || begin > height) continue; if(begin < 0) begin = 0; if(end > height) end = height; // integration for(int y = begin; y != end; ++y) { if(++distribData[y] > max) max = distribData[y]; } } if(max != 0.) max = 1. / max; // draw the results (optimize for continue zones) glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, 0, height); using Trend::distribWidth; double oldColor = distribData[0] * max; glColor3d(oldColor, oldColor, oldColor); glBegin(GL_QUADS); glVertex2i(0, 0); glVertex2i(distribWidth, 0); for(int y = 1; y != (height - 1); ++y) { double color = distribData[y] * max; if(color != oldColor) { glVertex2i(distribWidth, y); glVertex2i(0, y); oldColor = color; glColor3d(color, color, color); glVertex2i(0, y); glVertex2i(distribWidth, y); } } glVertex2i(distribWidth, height); glVertex2i(0, height); glEnd(); glPopMatrix(); } void drawTIntr() { // handle side cases const double intrX = (::intrX < 0 || ::intrX > divisions? 0: ::intrX); // initial color and current position glColor3fv(intrCol); glBegin(GL_LINES); glVertex2d(intrX, loLimit); glVertex2d(intrX, hiLimit); glEnd(); // scan for all intersections size_t trX = (static_cast(floor(intrX))); if(trX == divisions) --trX; double mul = (intrX - trX); vector intrs; // starting position size_t i = trX; const Value* it = graph->rrBuf + (trX - (scroll? offset: getCount(*graph, graph->rrBuf)) % divisions); if(it < graph->rrBuf) it += divisions; if(intrFg) it += ((graph->rrEnd - it) / divisions) * divisions; const Value* end = graph->rrEnd - 1; for(; it < end; i += divisions, it += divisions) { // fetch the next value const Value* nit = (it + 1); if(!isfinite(*it) && !isfinite(*nit)) continue; Intr buf; double far; if(mul < 0.5) { buf.near = *it; buf.pos = getPosition(*graph, i, it); far = *nit; } else { buf.near = *nit; buf.pos = getPosition(*graph, i + 1, nit); far = *it; } if(isfinite(buf.near)) { buf.value = (!isfinite(far)? buf.near: *it + mul * (*nit - *it)); buf.dist = fabs(buf.value - intrY); intrs.push_back(buf); } } // no intersections found if(!intrs.size()) return; // consider only the nearest n values std::sort(intrs.begin(), intrs.end()); if(intrs.size() > static_cast(Trend::intrNum)) intrs.resize(Trend::intrNum); // draw intersections and estimate mean value double mean = 0; glBegin(GL_LINES); for(vector::const_iterator it = intrs.begin(); it != intrs.end(); ++it) { mean += it->value; glVertex2d(0, it->value); glVertex2d(divisions, it->value); } glEnd(); mean /= intrs.size(); // switch to video coordinates glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, 0, height); // nearest point int nearX, nearY; project(intrs[0].pos, intrs[0].near, nearX, nearY); drawCircle(nearX, nearY); if(!intrs[0].pos) drawCircle(width, nearY); // plot values using Trend::strSpc; char buf[256]; int curY = height; snprintf(buf, sizeof(buf), "nearest: %g, mean: %g", intrs[0].near, mean); drawString(strSpc, curY -= Trend::fontHeight + strSpc, buf); i = 1; for(vector::const_iterator it = intrs.begin(); it != intrs.end(); ++i, ++it) { snprintf(buf, sizeof(buf), "%lu: %g", static_cast(i), it->value); drawString(strSpc, curY -= Trend::fontHeight + strSpc, buf); } // restore model space glPopMatrix(); } void drawDIntr() { // handle side cases int x, y; project(intrX, intrY, x, y); int nY = (y < 0? 0: (y >= height? height - 1: y)); // initial color and current position glColor3fv(intrCol); glBegin(GL_LINES); glVertex2d(0, y); glVertex2d(width, y); glEnd(); char buf[256]; snprintf(buf, sizeof(buf), "%g: %g", intrY, (y != nY? NAN: distribData[nY])); drawString(Trend::strSpc, height - Trend::strSpc - Trend::fontHeight, buf); } void drawValues() { const Value& last = graph->rrBuf[history - 1]; char buf[256]; glColor3fv(textCol); snprintf(buf, sizeof(buf), "%g", loLimit); drawOSString(width, 0, buf); snprintf(buf, sizeof(buf), "%g", hiLimit); drawOSString(width, height, buf); if(!graphs.size() || graphKey) snprintf(buf, sizeof(buf), "%g", last); else snprintf(buf, sizeof(buf), "%s: %g", graph->label.c_str(), last); drawLEString(buf); } void drawGraphKey() { using Trend::fontHeight; using Trend::fontWidth; using Trend::strSpc; // calculate dynamic widths vector lines; char buf[256]; if(values) { for(size_t i = 0; i != graphs.size(); ++i) { snprintf(buf, sizeof(buf), ": %g", graphs[i].rrBuf[history - 1]); string str(buf); lines.push_back(str); if(str.size() > maxValue) maxValue = str.size(); } } // positioning size_t maxLen = maxLabel + (values? 1 + maxValue: 1); int boxWidth = fontWidth * 2; int boxX1 = width - boxWidth; int textX1 = boxX1 - maxLen * fontWidth; int textX2 = textX1 + maxLabel * fontWidth; int y = height - fontHeight * 2 - strSpc; int graphKeyX1 = textX1 - strSpc; int graphKeyY1 = y - graphs.size() * fontHeight - strSpc; int graphKeyY2 = y + strSpc; glColor4f(0., 0., 0., Trend::fillTextAlpha); glBegin(GL_QUADS); glVertex2i(width, graphKeyY1); glVertex2i(graphKeyX1, graphKeyY1); glVertex2i(graphKeyX1, graphKeyY2); glVertex2i(width, graphKeyY2); glEnd(); for(size_t i = 0; i != graphs.size(); ++i, y -= fontHeight) { const Graph& g(graphs[i]); glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], (&g == graph? 1.: Trend::fillTrendAlpha)); glBegin(GL_QUADS); glVertex2i(width, y - fontHeight); glVertex2i(boxX1, y - fontHeight); glVertex2i(boxX1, y); glVertex2i(width, y); glEnd(); if(&g == graph) { glColor4f(g.lineCol[0], g.lineCol[1], g.lineCol[2], Trend::fillTrendAlpha); glBegin(GL_QUADS); glVertex2i(boxX1, y - fontHeight); glVertex2i(textX1, y - fontHeight); glVertex2i(textX1, y); glVertex2i(boxX1, y); glEnd(); } glColor3f(textCol[0], textCol[1], textCol[2]); drawString(textX1 + (maxLabel - graphs[i].label.size()) * fontWidth, y - fontHeight + strSpc, graphs[i].label); if(values) drawString(textX2, y - fontHeight + strSpc, lines[i]); } } void drawLatency() { char buf[256]; glColor3fv(textCol); snprintf(buf, sizeof(buf), "lat: %g/%g", vLat, bLat); drawLEString(buf); } void drawEdit() { using Trend::fontHeight; using Trend::fontWidth; const int height2 = height / 2; const int width2 = width / 2; const int blockH = fontHeight * 2; const int blockS = fontHeight / 2; glBegin(GL_QUADS); // background glColor4f(0., 0., 0., Trend::fillTextAlpha); glVertex2d(0, height2 + blockH); glVertex2d(width, height2 + blockH); glVertex2d(width, height2 - blockH); glVertex2d(0, height2 - blockH); // borders glColor3fv(editCol); glVertex2d(0, height2 + blockH + blockS); glVertex2d(width, height2 + blockH + blockS); glVertex2d(width, height2 + blockH); glVertex2d(0, height2 + blockH); glVertex2d(0, height2 - blockH - blockS); glVertex2d(width, height2 - blockH - blockS); glVertex2d(width, height2 - blockH); glVertex2d(0, height2 - blockH); glEnd(); // edit string string buf(editTitle + ": " + editStr); drawString(width2 - fontWidth * buf.size() / 2, height2 - blockS, buf); } void drawMessages() { // purge old messages time_t maxTime = time(NULL) - Trend::persist; while(messages.size() && messages.front().first <= maxTime) messages.pop_front(); if(!messages.size()) return; // draw background using Trend::fontHeight; using Trend::fontWidth; using Trend::strSpc; const int width2 = width / 2; int ty = height - fontHeight * messages.size() - strSpc * 4; glColor4f(0., 0., 0., Trend::fillTextAlpha); glBegin(GL_QUADS); glVertex2d(0, ty); glVertex2d(width, ty); glVertex2d(width, height); glVertex2d(0, height); glEnd(); // draw messages int y = height - strSpc - fontHeight; glColor3fv(editCol); for(deque >::const_iterator it = messages.begin(); it != messages.end(); ++it, y -= fontHeight) { int len = it->second.size() * fontWidth; drawString(width2 - len / 2, y, it->second); } } // redraw handler void display() { // reset some data lc = 0; // setup model coordinates double zero = (distrib? -(static_cast(Trend::distribWidth) * divisions / (width - Trend::distribWidth)): 0); glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); gluOrtho2D(zero, divisions, loLimit, hiLimit); // background grid and main data if(grid) drawGrid(); if(filled) drawFill(*graph); if(showUndef) drawFillUndef(*graph); // graphs if(view != Trend::v_hide) { double alphaMul = (view == Trend::v_dim? Trend::drawOthersAlpha: 1.); for(vector::iterator gi = graphs.begin(); gi != graphs.end(); ++gi) if(&*gi != graph) drawLine(*gi, alphaMul); } size_t pos = drawLine(*graph, 1.); // other data if(distrib) drawDistrib(); if(marker && !scroll) drawMarker(pos); if(intr && (!distrib || intrX >= 0)) drawTIntr(); // setup video coordinates glLoadIdentity(); gluOrtho2D(0, width, 0, height); // video stuff if(values) drawValues(); if(graphKey) drawGraphKey(); if(latency) drawLatency(); if(intr && distrib && intrX < 0) drawDIntr(); // editing if(edit) drawEdit(); if(messages.size()) drawMessages(); // flush buffers glutSwapBuffers(); atVLat.stop(); vLat = atVLat.avg(); } void setGraphLimits(const Graph& g, Value& lo, Value& hi) { for(const Value* it = g.rrBuf; it != g.rrEnd; ++it) { if(isfinite(*it)) { if(!isfinite(lo) || *it < lo) lo = *it; if(!isfinite(hi) || *it > hi) hi = *it; } } } void setLimits() { Value lo = *graph->rrBuf; Value hi = lo; if(view == Trend::v_hide) { // only operate on the curren graph setGraphLimits(*graph, lo, hi); } else { for(vector::iterator it = graphs.begin(); it != graphs.end(); ++it) setGraphLimits(*it, lo, hi); } // some vertical bounds hiLimit = hi + grSpec.y.res; loLimit = lo - grSpec.y.res; } void check() { // check if a redraw is really necessary bool recalc = false; pthread_mutex_lock(&mutex); if(damaged) { damaged = false; atBLat.stop(); bLat = atBLat.avg(); recalc = true; } pthread_mutex_unlock(&mutex); if(recalc) { atVLat.start(); // update buffers for(vector::iterator gi = graphs.begin(); gi != graphs.end(); ++gi) { gi->rrPos = gi->rrData->copy(gi->rrBuf); if(gi->zero) rrShift(*gi, gi->zero); } // recalculate limits seldom if(autoLimit) setLimits(); glutPostRedisplay(); } } void idle(int = 0) { // re-register the callback glutTimerFunc(pollMs, idle, 0); // consume messages when paused if(paused) { if(messages.size()) glutPostRedisplay(); return; } check(); } /* * Keyboard interaction */ // Parse a grid (res+mayor) void parseGrid(Grid& grid, char* spec) { char* p = strchr(spec, '+'); if(p) { *p++ = 0; if(*p) grid.mayor = strtoul(p, NULL, 0); } if(*spec) grid.res = fabs(strtod(spec, NULL)); } // Parse a grid-spec void parseGrSpec(GrSpec& grid, char* spec) { char* p = strchr(spec, 'x'); if(p) { *p++ = 0; if(*p) parseGrid(grid.x, p); } if(*spec) parseGrid(grid.y, spec); } void toggleStatus(const string& str, bool& var) { var = !var; pushMessage(str + ": " + (var? "enabled": "disabled")); } void editMode(bool mode); void editMode(const string& str, edit_callback_t call) { editTitle = str; editStr.clear(); editCallback = call; editMode(true); } edit_callback_t editCall() { edit_callback_t call = editCallback; editCallback = NULL; (*call)(editStr); return editCallback; } void editKeyboard(const unsigned char key, const int, const int) { switch(key) { case 13: case 27: if(key == 27 || !editStr.size() || !editCall()) editMode(false); break; case 8: case 127: if(!editStr.size()) return; editStr.resize(editStr.size() - 1); break; default: if(!isprint(key) && editStr.size() + 1 != static_cast(Trend::maxNumLen)) return; editStr += key; } glutPostRedisplay(); } void getLimits2(const string& str) { hiLimit = strtod(str.c_str(), NULL); } void getLimits1(const string& str) { if(autoLimit) toggleStatus("autolimit", autoLimit); loLimit = strtod(str.c_str(), NULL); editMode("+y", getLimits2); } void getLimits() { editMode("-y", getLimits1); } void getCenterAmp2(const string& str) { double amp2 = strtod(str.c_str(), NULL) / 2; double c = loLimit + (hiLimit - loLimit) / 2; loLimit = c - amp2; hiLimit = c + amp2; } void getCenterAmp1(const string& str) { if(autoLimit) toggleStatus("autolimit", autoLimit); double c = strtod(str.c_str(), NULL); double amp2 = (hiLimit - loLimit) / 2; loLimit = c - amp2; hiLimit = c + amp2; editMode("amplitude", getCenterAmp2); } void getCenterAmp() { editMode("center", getCenterAmp1); } void getGrid(const string& str) { if(!grid) toggleStatus("grid", grid); char* buf(strdup(str.c_str())); parseGrSpec(grSpec, buf); free(buf); } void getZero(const string& str) { double nZero = strtod(str.c_str(), NULL); if(nZero != graph->zero) { rrShift(*graph, nZero - graph->zero); graph->zero = nZero; if(autoLimit) setLimits(); } } void setPollRate(const double rate) { pollMs = static_cast(1000. / rate); } void getPollRate(const string& str) { double rate = strtod(str.c_str(), NULL); if(rate > 0) setPollRate(rate); } void changeGraph() { if(++graph == &*graphs.end()) graph = &graphs[0]; if(!graphKey && !values) pushMessage(string("current graph: ") + graph->label); if(autoLimit && view == Trend::v_hide) setLimits(); } void toggleView() { switch(view) { case Trend::v_normal: view = Trend::v_dim; pushMessage("view mode: dim others"); break; case Trend::v_dim: view = Trend::v_hide; if(autoLimit) setLimits(); pushMessage("view mode: hide others"); break; case Trend::v_hide: view = Trend::v_normal; if(autoLimit) setLimits(); pushMessage("view mode: normal"); break; } } void dispKeyboard(const unsigned char key, const int x, const int y) { switch(key) { case Trend::quitKey: exit(Trend::success); break; // redraw alteration case Trend::changeKey: changeGraph(); break; case Trend::dimmedKey: toggleStatus("dimmed", dimmed); break; case Trend::viewModeKey: case 'N': // TODO: 'N' is deprecated toggleView(); break; case Trend::distribKey: toggleStatus("distribution", distrib); break; case Trend::autolimKey: toggleStatus("autolimit", autoLimit); break; case Trend::resetlimKey: setLimits(); pushMessage("limits reset"); break; case Trend::setlimKey: getLimits(); break; case Trend::smoothKey: toggleStatus("smoothing", smooth); init(); break; case Trend::scrollKey: toggleStatus("scrolling", scroll); break; case Trend::valuesKey: toggleStatus("values", values); break; case Trend::markerKey: toggleStatus("marker", marker); break; case Trend::fillKey: toggleStatus("fill", filled); break; case Trend::showUndefKey: toggleStatus("show undefined", showUndef); break; case Trend::graphKeyKey: case 'n': // TODO: 'n' is deprecated toggleStatus("graph key", graphKey); break; case Trend::gridKey: toggleStatus("grid", grid); break; case Trend::setResKey: editMode("grid-spec", getGrid); break; case Trend::setZeroKey: editMode("zero", getZero); break; case Trend::setCAKey: getCenterAmp(); break; case Trend::latKey: toggleStatus("latency", latency); break; case Trend::pollRateKey: editMode("poll rate", getPollRate); break; case Trend::pauseKey: toggleStatus("paused", paused); default: return; } glutPostRedisplay(); } void dispMotion(int x, int y) { unproject(x, y, intrX, intrY); glutPostRedisplay(); } void dispMouse(int button, int state, int x, int y) { // cause a motion event internally intr = (button != GLUT_RIGHT_BUTTON); intrFg = (glutGetModifiers() & GLUT_ACTIVE_CTRL); dispMotion(x, y); } /* * CLI and options */ // Parse a hist/n, div*n, div spec bool parseHistSpec(size_t& hist, size_t& div, const char* spec) { // find the separator first. // TODO: * is deprecated const char* p = strpbrk(spec, "/*x"); if((p == spec) || (p && *(p + 1) == 0)) return true; if(!p) { div = strtoul(spec, NULL, 0); hist = div + 1; return false; } else if(*p == '/') { hist = strtoul(spec, NULL, 0); div = strtoul(p + 1, NULL, 0); if(!div) return true; div = hist / div; } else { div = strtoul(spec, NULL, 0); hist = div * strtoul(p + 1, NULL, 0); } return false; } size_t parseInput(Trend::input_t& input, const char* arg) { char* end; size_t n = strtoul(arg, &end, 10); if(end == arg) n = 1; switch(*end) { case 'a': input = Trend::absolute; break; case 'i': input = Trend::incremental; break; case 'd': input = Trend::differential; break; default: return 0; }; return n; } bool parseFormat(Trend::format_t& format, const char* arg) { switch(arg[0]) { case 'a': format = Trend::f_ascii; break; case 'f': format = Trend::f_float; break; case 'd': format = Trend::f_double; break; case 's': format = Trend::f_short; break; case 'i': format = Trend::f_int; break; case 'l': format = Trend::f_long; break; default: return true; }; return false; } bool parseNums(vector& nums, char* arg) { char* p; while((p = strsep(&arg, ","))) nums.push_back(strtod(p, NULL)); return false; } bool parseStrings(vector& strings, char* arg) { char* p; while((p = strsep(&arg, ","))) strings.push_back(p); return false; } // Initialize globals through command line int parseOptions(int argc, char* const argv[]) { // starting options memcpy(backCol, Trend::backCol, sizeof(backCol)); memcpy(textCol, Trend::textCol, sizeof(textCol)); memcpy(gridCol, Trend::gridCol, sizeof(gridCol)); memcpy(markCol, Trend::markCol, sizeof(markCol)); memcpy(intrCol, Trend::intrCol, sizeof(intrCol)); memcpy(editCol, Trend::editCol, sizeof(editCol)); grSpec.x.res = grSpec.y.res = Trend::gridres; grSpec.x.mayor = grSpec.y.mayor = Trend::mayor; int arg; while((arg = getopt(argc, argv, "dDSsvlmFgG:ht:A:E:R:I:M:N:T:L:irz:f:c:p:u:e")) != -1) switch(arg) { case 'd': dimmed = !dimmed; break; case 'D': distrib = !distrib; break; case 'S': smooth = !smooth; break; case 's': scroll = !scroll; break; case 'v': values = !values; break; case 'l': latency = !latency; break; case 'm': marker = !marker; break; case 'F': filled = !filled; break; case 'u': showUndef = !showUndef; break; case 'e': allowEsc = !allowEsc; break; case 'g': grid = !grid; break; case 'G': parseGrSpec(grSpec, optarg); break; case 'z': parseNums(zeros, optarg); break; case 't': title = optarg; break; case 'A': parseColor(backCol, optarg); break; case 'E': parseColor(textCol, optarg); break; case 'R': parseColor(gridCol, optarg); break; case 'I': parseStrings(lineCol, optarg); break; case 'M': parseColor(markCol, optarg); break; case 'N': parseColor(intrCol, optarg); break; case 'T': parseColor(editCol, optarg); break; case 'L': parseStrings(labels, optarg); break; case 'c': graphs.resize(parseInput(input, optarg)); if(!graphs.size()) { cerr << argv[0] << ": bad input mode\n"; return -1; } break; case 'i': // TODO: deprecated input = Trend::incremental; break; case 'r': // TODO: deprecated input = Trend::differential; break; case 'p': { double rate = strtod(optarg, NULL); if(!rate) { cerr << argv[0] << "bad polling rate"; return -1; } setPollRate(rate); } break; case 'f': if(parseFormat(format, optarg)) { cerr << argv[0] << ": bad format type\n"; return -1; } break; case 'h': cout << argv[0] << " usage: " << argv[0] << " [options] [-y +y]\n" << argv[0] << " version: " << TREND_VERSION << "\n"; return 1; default: return -1; } // main parameters argc -= optind; if(argc < 2 || argc > 5) { cerr << argv[0] << ": bad number of parameters\n"; return -1; } // fifo fileName = argv[optind++]; if(!strcmp(fileName, "-")) *const_cast(fileName) = 0; // history/divisions if(argc == 2 || argc == 4) { if(parseHistSpec(history, divisions, argv[optind++])) { cerr << argv[0] << ": bad hist-spec\n"; return -1; } } else { history = strtoul(argv[optind++], NULL, 0); divisions = strtoul(argv[optind++], NULL, 0); } // parameters may still be buggy if(!divisions) { cerr << argv[0] << ": x-sz can't be zero\n"; return -1; } if(history < 2) { cerr << argv[0] << ": history must be at least 2\n"; return -1; } offset = divisions - (history % divisions) + 1; graphKey = labels.size(); // optional y limits if(argc == 4 || argc == 5) { loLimit = strtod(argv[optind++], NULL); hiLimit = strtod(argv[optind++], NULL); autoLimit = false; } else autoLimit = true; return 0; } void editMode(bool edit) { if(edit) { glutKeyboardFunc(editKeyboard); glutMouseFunc(NULL); glutMotionFunc(NULL); } else { glutKeyboardFunc(dispKeyboard); glutMouseFunc(dispMouse); glutMotionFunc(dispMotion); } ::edit = edit; } void initGraphs() { char buf[Trend::maxNumLen]; const size_t maxLineCol = (sizeof(Trend::lineCol) / sizeof(*Trend::lineCol)); for(vector::iterator gi = graphs.begin(); gi != graphs.end(); ++gi) { gi->rrData = new rr(history); gi->rrBuf = new Value[history]; gi->rrEnd = gi->rrBuf + history; gi->rrPos = 0; rrFill(*gi, NAN); size_t n = gi - graphs.begin(); gi->zero = (zeros.size() > n? zeros[n]: 0.); if(labels.size() > n) gi->label = labels[n]; else { snprintf(buf, sizeof(buf), "%lu", static_cast(n + 1)); gi->label = buf; } if(gi->label.size() > maxLabel) maxLabel = gi->label.size(); if(lineCol.size() > n && lineCol[n].size()) parseColor(gi->lineCol, lineCol[n].c_str()); else memcpy(gi->lineCol, Trend::lineCol[n % maxLineCol], sizeof(GLfloat[3])); } } int main(int argc, char* argv[]) try { // parameters glutInit(&argc, argv); if(parseOptions(argc, argv)) return Trend::args; // initialize rr buffers if(!graphs.size()) graphs.resize(1); graph = &graphs[0]; initGraphs(); // start the producer thread pthread_t thrd; pthread_mutex_init(&mutex, NULL); pthread_create(&thrd, NULL, producer, argv[0]); // display, main mindow and callbacks glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow(title? title: argv[0]); glutReshapeFunc(reshape); glutDisplayFunc(display); editMode(false); // first redraw atVLat.start(); init(); idle(); // processing glutMainLoop(); return Trend::success; } catch(const std::exception& e) { std::cerr << argv[0] << ": " << e.what() << std::endl; throw; } trend-1.4/src/version.h0000644000000000000000000000005712742657152013632 0ustar rootrootstatic const char TREND_VERSION[]="trend-1.4"; trend-1.4/src/rr.hh0000644000000000000000000000345412256034167012737 0ustar rootroot/* * rr: thread-safe round robin container * Copyright(c) 2004-2007 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ #ifndef rr_hh #define rr_hh // system headers #include #include /* * Here's the general idea: we store the data in a classic round-robin buffer * but we support only push_back. Since we never read like a classic 'consumer' * we call the method copy(v) to flatten _all_ the values in a simple linear * buffer in at maximum two memcpy (for performance reasons the assignement * operator is not called). We then iterate in the linear buffer, which saves * us wrap-around checks. */ template class rr { public: typedef ::size_t size_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef const T& const_reference; private: pthread_mutex_t mutex; pointer data; const size_type size; volatile size_type pos; public: explicit rr(size_type size) : size(size), pos(0) { data = new value_type[size]; pthread_mutex_init(&mutex, NULL); } ~rr() throw() { pthread_mutex_destroy(&mutex); delete[] data; } void push_back(const_reference value) { pthread_mutex_lock(&mutex); memcpy(data + pos++ % size, &value, sizeof(value_type)); pthread_mutex_unlock(&mutex); } size_type copy(pointer buf) { // try harder to reduce latency pthread_mutex_lock(&mutex); const size_type p = pos; const size_type mp = p % size; const size_type res = (size - mp); memcpy(buf, data + mp, sizeof(value_type) * res); pthread_mutex_unlock(&mutex); memcpy(buf + res, data, sizeof(value_type) * mp); return p; } }; #endif trend-1.4/src/Makefile0000644000000000000000000000265212647771575013451 0ustar rootroot## Makefile for trend ## Copyright(c) 2003-2009 by wave++ "Yuri D'Elia" ## Distributed under GNU LGPL WITHOUT ANY WARRANTY. #if $(CXX) == "CC" # pmake (assume Mipspro) TREND_CXXFLAGS := TREND_CPPFLAGS := -I/usr/freeware/include -I/usr/local/include TREND_LDFLAGS := -FE:template_in_elf_section -quiet_prelink TREND_LDADD := -lpthread -L/usr/freeware/lib32 -L/usr/local/lib32 -lm -lglut -lGL -lGLU -lX11 -lXmu #else ifeq ($(shell uname), Darwin) # OS X (_nice_ framework system, I admit) TREND_CXXFLAGS := -pthread TREND_CPPFLAGS := TREND_LDFLAGS := TREND_LDADD := -framework GLUT -framework OpenGL else # classic posix TREND_CXXFLAGS := -pthread TREND_CPPFLAGS := -MD TREND_LDFLAGS := TREND_LDADD := -lglut -lGL -lGLU endif #endif CXXFLAGS += $(TREND_CXXFLAGS) CPPFLAGS += $(TREND_CPPFLAGS) LDFLAGS += $(TREND_LDFLAGS) LDADD += $(TREND_LDADD) # Config TREND_BUILT = version.h TREND_OBJECTS = trend.o color.o TARGETS = trend # Rules .SUFFIXES: .cc .o .PHONY: all dist clean distclean .cc.o: $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< # Targets all: $(TARGETS) dist: $(TREND_BUILT) trend: $(TREND_OBJECTS) $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $(TREND_OBJECTS) $(LDADD) # just update upon tagging version.h: echo -n `git describe` | cencode -q 'static const' -s TREND_VERSION > $@ distclean: clean rm -rf $(TREND_BUILT) clean: rm -rf *.[do] core ii_files $(TARGETS) # Dependencies trend.o: version.h sinclude *.d trend-1.4/src/defaults.hh0000644000000000000000000000542712647771575014144 0ustar rootroot/* * defaults: trend defaults and constants * Copyright(c) 2004-2007 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ #ifndef defaults_hh #define defaults_hh // GL headers #include "gl.hh" namespace Trend { // Keys const unsigned char quitKey = 27; const unsigned char autolimKey = 'a'; const unsigned char resetlimKey = 'A'; const unsigned char setlimKey = 'L'; const unsigned char dimmedKey = 'd'; const unsigned char distribKey = 'D'; const unsigned char smoothKey = 'S'; const unsigned char scrollKey = 's'; const unsigned char valuesKey = 'v'; const unsigned char markerKey = 'm'; const unsigned char gridKey = 'g'; const unsigned char setResKey = 'G'; const unsigned char setZeroKey = 'z'; const unsigned char setCAKey = 'Z'; const unsigned char pauseKey = ' '; const unsigned char latKey = 'l'; const unsigned char fillKey = 'f'; const unsigned char showUndefKey = 'u'; const unsigned char pollRateKey = 'p'; const unsigned char changeKey = '\t'; const unsigned char graphKeyKey = 'k'; const unsigned char viewModeKey = 'K'; // Some types typedef double Value; enum input_t {absolute, incremental, differential}; enum format_t {f_ascii, f_float, f_double, f_short, f_int, f_long}; enum view_t {v_normal, v_dim, v_hide}; // Defaults const input_t input = absolute; const format_t format = f_ascii; const bool dimmed = false; const bool distrib = false; const bool smooth = false; const bool scroll = false; const bool values = false; const bool marker = true; const bool latency = false; const bool filled = false; const bool showUndef = false; const view_t view = v_normal; const bool grid = false; const double gridres = 1.; const int mayor = 10; const int pollMs = 1; // Colors const GLfloat backCol[3] = {0.0, 0.0, 0.0}; const GLfloat textCol[3] = {1.0, 1.0, 1.0}; const GLfloat gridCol[3] = {0.5, 0.0, 0.5}; const GLfloat markCol[3] = {0.5, 0.5, 0.0}; const GLfloat intrCol[3] = {0.0, 1.0, 0.0}; const GLfloat editCol[3] = {1.0, 0.0, 0.0}; const GLfloat lineCol[][3] = { {1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}, {0.3, 0.0, 1.0}, {1.0, 0.0, 0.7}, {1.0, 0.4, 0.0}, {1.0, 0.8, 0.0} }; const GLfloat drawOthersAlpha = 0.3; const GLfloat fillTrendAlpha = 0.25; const GLfloat fillUndefAlpha = 0.125; const GLfloat fillTextAlpha = 0.9; // Exit const int success = 0; const int fail = 1; const int args = 2; // Constants const int maxNumLen = 128; const int fontHeight = 13; const int fontWidth = 8; const int strSpc = 2; const int intrRad = 4; const int intrNum = 3; const int distribWidth = 30; const int maxGridDens = 4; const int latAvg = 5; const int persist = 2; const int maxPersist = 5; } #endif trend-1.4/src/timer.hh0000644000000000000000000000175412256034167013435 0ustar rootroot/* * timer: timing utilities * Copyright(c) 2004-2005 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ #ifndef timer_hh #define timer_hh // c system headers #include // Averaging stop-watch timer (with variable-bound precision) class ATimer { double delta; double cum; double le; double ini; double last; unsigned long sc; double now() { timeval n; gettimeofday(&n, NULL); return (static_cast(n.tv_sec) + .000001 * static_cast(n.tv_usec)); } public: explicit ATimer(double delta) : delta(delta), cum(0), le(0), last(0), sc(0) { ini = now(); } void start() { le = now(); } void stop() { double n = now(); cum += n - le; le = n; ++sc; } double avg() { double n = now(); if((n - ini) >= delta) { last = cum / (sc? sc: 1); ini = n; cum = 0; sc = 0; } return last; } }; #endif trend-1.4/src/gl.hh0000644000000000000000000000056412256034167012715 0ustar rootroot/* * gl: gl headers inclusion wrapper * Copyright(c) 2005 by wave++ "Yuri D'Elia" * Distributed under GNU LGPL WITHOUT ANY WARRANTY. */ #ifndef gl_hh #define gl_hh // GL headers #ifdef __APPLE__ #include #include #include #else #include #include #include #endif #endif