From 79ff46b4870bbdb19424a9609653658aea859190 Mon Sep 17 00:00:00 2001 From: Hobbestigrou Date: Sat, 14 Apr 2012 16:53:26 +0200 Subject: [PATCH 1/3] [Core] Status: Rename the file to mahewin-wmfs-status. --- status.pl => mahewin-wmfs-status.pl | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename status.pl => mahewin-wmfs-status.pl (100%) diff --git a/status.pl b/mahewin-wmfs-status.pl similarity index 100% rename from status.pl rename to mahewin-wmfs-status.pl From 09f3911981cd9ba53c3e2521bab98cd06389c873 Mon Sep 17 00:00:00 2001 From: Hobbestigrou Date: Sat, 14 Apr 2012 16:55:44 +0200 Subject: [PATCH 2/3] [Core] Mahewin-wmfs-status: Generate a binary file with all dependecies. --- mahewin-wmfs-status | 6809 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 6809 insertions(+) create mode 100644 mahewin-wmfs-status diff --git a/mahewin-wmfs-status b/mahewin-wmfs-status new file mode 100644 index 0000000..8a3f649 --- /dev/null +++ b/mahewin-wmfs-status @@ -0,0 +1,6809 @@ +# This chunk of stuff was generated by App::FatPacker. To find the original +# file's code, look for the end of this BEGIN block or the string 'FATPACK' +BEGIN { +my %fatpacked; + +$fatpacked{"Config/IniFiles.pm"} = <<'CONFIG_INIFILES'; + package Config::IniFiles; + + use vars qw($VERSION); + + $VERSION = '2.70'; + + require 5.004; + use strict; + use Carp; + use Symbol 'gensym','qualify_to_ref'; # For the 'any data type' hack + + @Config::IniFiles::errors = ( ); + + # $Header: /home/shlomi/progs/perl/cpan/Config/IniFiles/config-inifiles-cvsbackup/config-inifiles/IniFiles.pm,v 2.41 2003-12-08 10:50:56 domq Exp $ + + =head1 NAME + + Config::IniFiles - A module for reading .ini-style configuration files. + + =head1 SYNOPSIS + + use Config::IniFiles; + my $cfg = Config::IniFiles->new( -file => "/path/configfile.ini" ); + print "The value is " . $cfg->val( 'Section', 'Parameter' ) . "." + if $cfg->val( 'Section', 'Parameter' ); + + =head1 DESCRIPTION + + Config::IniFiles provides a way to have readable configuration files outside + your Perl script. Configurations can be imported (inherited, stacked,...), + sections can be grouped, and settings can be accessed from a tied hash. + + =head1 FILE FORMAT + + INI files consist of a number of sections, each preceded with the + section name in square brackets, followed by parameter names and + their values. + + [a section] + Parameter=Value + + [section 2] + AnotherParameter=Some value + Setting=Something else + Parameter=Different scope than the one in the first section + + The first non-blank character of the line indicating a section must + be a left bracket and the last non-blank character of a line indicating + a section must be a right bracket. The characters making up the section + name can be any symbols at all. However section names must be unique. + + Parameters are specified in each section as Name=Value. Any spaces + around the equals sign will be ignored, and the value extends to the + end of the line (including any whitespace at the end of the line. + Parameter names are localized to the namespace of the section, but must + be unique within a section. + + Both the hash mark (#) and the semicolon (;) are comment characters. + by default (this can be changed by configuration). Lines that begin with + either of these characters will be ignored. Any amount of whitespace may + precede the comment character. + + Multi-line or multi-valued parameters may also be defined ala UNIX + "here document" syntax: + + Parameter=< method: + + $cfg = Config::IniFiles->new( -file => "/path/config_file.ini" ); + $cfg = new Config::IniFiles -file => "/path/config_file.ini"; + + Optional named parameters may be specified after the configuration + file name. See the I in the B section, below. + + Values from the config file are fetched with the val method: + + $value = $cfg->val('Section', 'Parameter'); + + If you want a multi-line/value field returned as an array, just + specify an array as the receiver: + + @values = $cfg->val('Section', 'Parameter'); + + =head1 METHODS + + =head2 new ( [-option=>value ...] ) + + Returns a new configuration object (or "undef" if the configuration + file has an error, in which case check the global C<@Config::IniFiles::errors> + array for reasons why). One Config::IniFiles object is required per configuration + file. The following named parameters are available: + + =over 10 + + + =item I<-file> filename + + Specifies a file to load the parameters from. This 'file' may actually be + any of the following things: + + 1) the pathname of a file + + $cfg = Config::IniFiles->new( -file => "/path/to/config_file.ini" ); + + 2) a simple filehandle + + $cfg = Config::IniFiles->new( -file => STDIN ); + + 3) a filehandle glob + + open( CONFIG, "/path/to/config_file.ini" ); + $cfg = Config::IniFiles->new( -file => *CONFIG ); + + 4) a reference to a glob + + open( CONFIG, "/path/to/config_file.ini" ); + $cfg = Config::IniFiles->new( -file => \*CONFIG ); + + 5) an IO::File object + + $io = IO::File->new( "/path/to/config_file.ini" ); + $cfg = Config::IniFiles->new( -file => $io ); + + or + + open my $fh, '<', "/path/to/config_file.ini" or die $!; + $cfg = Config::IniFiles->new( -file => $fh ); + + 6) A reference to a scalar (requires newer versions of IO::Scalar) + + $ini_file_contents = <new( -file => \$ini_file_contents ); + + + If this option is not specified, (i.e. you are creating a config file from scratch) + you must specify a target file using L in order to save the parameters. + + + =item I<-default> section + + Specifies a section to be used for default values. For example, in the + following configuration file, if you look up the "permissions" parameter + in the "joe" section, there is none. + + [all] + permissions=Nothing + + [jane] + name=Jane + permissions=Open files + + [joe] + name=Joseph + + If you create your Config::IniFiles object with a default section of "all" like this: + + $cfg = Config::IniFiles->new( -file => "file.ini", -default => "all" ); + + Then requsting a value for a "permissions" in the [joe] section will + check for a value from [all] before returning undef. + + $permissions = $cfg->val( "joe", "permissions"); // returns "Nothing" + + + =item I<-fallback> section + + Specifies a section to be used for parameters outside a section. Default is none. + Without -fallback specified (which is the default), reading a configuration file + which has a parameter outside a section will fail. With this set to, say, + "GENERAL", this configuration: + + wrong=wronger + + [joe] + name=Joseph + + will be assumed as: + + [GENERAL] + wrong=wronger + + [joe] + name=Joseph + + Note that Config::IniFiles will also omit the fallback section header when + outputing such configuration. + + =item I<-nocase> 0|1 + + Set -nocase => 1 to handle the config file in a case-insensitive + manner (case in values is preserved, however). By default, config + files are case-sensitive (i.e., a section named 'Test' is not the same + as a section named 'test'). Note that there is an added overhead for + turning off case sensitivity. + + + =item I<-import> object + + This allows you to import or inherit existing setting from another + Config::IniFiles object. When importing settings from another object, + sections with the same name will be merged and parameters that are + defined in both the imported object and the I<-file> will take the + value of given in the I<-file>. + + If a I<-default> section is also given on this call, and it does not + coincide with the default of the imported object, the new default + section will be used instead. If no I<-default> section is given, + then the default of the imported object will be used. + + + =item I<-allowcontinue> 0|1 + + Set -allowcontinue => 1 to enable continuation lines in the config file. + i.e. if a line ends with a backslash C<\>, then the following line is + appended to the parameter value, dropping the backslash and the newline + character(s). + + Default behavior is to keep a trailing backslash C<\> as a parameter + value. Note that continuation cannot be mixed with the "here" value + syntax. + + + =item I<-allowempty> 0|1 + + If set to 1, then empty files are allowed at L + time. If set to 0 (the default), an empty configuration file is considered + an error. + + + =item I<-negativedeltas> 0|1 + + If set to 1 (the default if importing this object from another one), + parses and honors lines of the following form in the configuration + file: + + ; [somesection] is deleted + + or + + [inthissection] + ; thisparameter is deleted + + If set to 0 (the default if not importing), these comments are treated + like ordinary ones. + + The L1)> form will output such + comments to indicate deleted sections or parameters. This way, + reloading a delta file using the same imported object produces the + same results in memory again. See L for more + details. + + =item I<-commentchar> 'char' + + The default comment character is C<#>. You may change this by specifying + this option to another character. This can be any character except + alphanumeric characters, square brackets or the "equal" sign. + + + =item I<-allowedcommentchars> 'chars' + + Allowed default comment characters are C<#> and C<;>. By specifying this + option you may change the range of characters that are used to denote a + comment line to include any set of characters + + Note: that the character specified by B<-commentchar> (see above) is + I part of the allowed comment characters. + + Note 2: The given string is evaluated as a regular expression character + class, so '\' must be escaped if you wish to use it. + + + =item I<-reloadwarn> 0|1 + + Set -reloadwarn => 1 to enable a warning message (output to STDERR) + whenever the config file is reloaded. The reload message is of the + form: + + PID reloading config file at YYYY.MM.DD HH:MM:SS + + Default behavior is to not warn (i.e. -reloadwarn => 0). + + This is generally only useful when using Config::IniFiles in a server + or daemon application. The application is still responsible for determining + when the object is to be reloaded. + + + =item I<-nomultiline> 0|1 + + Set -nomultiline => 1 to output multi-valued parameter as: + + param=value1 + param=value2 + + instead of the default: + + param=< 0|1 + + Set -handle_trailing_comment => 1 to enable support of parameter trailing + comments. + + For example, if we have a parameter line like this: + + param1=value1;comment1 + + by default, handle_trailing_comment will be set to B<0>, and we will get + I as the value of I. If we have + -handle_trailing_comment set to B<1>, then we will get I + as the value for I, and I as the trailing comment of + I. + + Set and get methods for trailing comments are provided as + L and L. + + =back + + =cut + + sub _nocase + { + my $self = shift; + + if (@_) + { + $self->{nocase} = (shift(@_) ? 1 : 0); + } + + return $self->{nocase}; + } + + sub new { + my $class = shift; + my %parms = @_; + + my $errs = 0; + my @groups = ( ); + + my $self = bless { + default => '', + fallback =>undef, + fallback_used => 0, + imported =>undef, + v =>{}, + cf => undef, + firstload => 1, + nomultiline => 0, + handle_trailing_comment => 0, + }, $class; + + if( ref($parms{-import}) && ($parms{-import}->isa('Config::IniFiles')) ) { + $self->{imported}=$parms{-import}; # ReadConfig will load the data + $self->{negativedeltas}=1; + } elsif( defined $parms{-import} ) { + carp "Invalid -import value \"$parms{-import}\" was ignored."; + } # end if + delete $parms{-import}; + + # Copy the original parameters so we + # can use them when we build new sections + %{$self->{startup_settings}} = %parms; + + # Parse options + my($k, $v); + local $_; + $self->_nocase(0); + + # Handle known parameters first in this order, + # because each() could return parameters in any order + if (defined ($v = delete $parms{'-file'})) { + # Should we be pedantic and check that the file exists? + # .. no, because now it could be a handle, IO:: object or something else + $self->{cf} = $v; + } + if (defined ($v = delete $parms{'-nocase'})) { + $self->_nocase($v); + } + if (defined ($v = delete $parms{'-default'})) { + $self->{default} = $self->_nocase ? lc($v) : $v; + } + if (defined ($v = delete $parms{'-fallback'})) { + $self->{fallback} = $self->_nocase ? lc($v) : $v; + } + if (defined ($v = delete $parms{'-reloadwarn'})) { + $self->{reloadwarn} = $v ? 1 : 0; + } + if (defined ($v = delete $parms{'-nomultiline'})) { + $self->{nomultiline} = $v ? 1 : 0; + } + if (defined ($v = delete $parms{'-allowcontinue'})) { + $self->{allowcontinue} = $v ? 1 : 0; + } + if (defined ($v = delete $parms{'-allowempty'})) { + $self->{allowempty} = $v ? 1 : 0; + } + if (defined ($v = delete $parms{'-negativedeltas'})) { + $self->{negativedeltas} = $v ? 1 : 0; + } + if (defined ($v = delete $parms{'-commentchar'})) { + if(!defined $v || length($v) != 1) { + carp "Comment character must be unique."; + $errs++; + } + elsif($v =~ /[\[\]=\w]/) { + # must not be square bracket, equal sign or alphanumeric + carp "Illegal comment character."; + $errs++; + } + else { + $self->{comment_char} = $v; + } + } + if (defined ($v = delete $parms{'-allowedcommentchars'})) { + # must not be square bracket, equal sign or alphanumeric + if(!defined $v || $v =~ /[\[\]=\w]/) { + carp "Illegal value for -allowedcommentchars."; + $errs++; + } + else { + $self->{allowed_comment_char} = $v; + } + } + + if (defined ($v = delete $parms{'-handle_trailing_comment'})) { + $self->{handle_trailing_comment} = $v ? 1 : 0; + } + + $self->{comment_char} = '#' unless exists $self->{comment_char}; + $self->{allowed_comment_char} = ';' unless exists $self->{allowed_comment_char}; + # make sure that comment character is always allowed + $self->{allowed_comment_char} .= $self->{comment_char}; + + $self->{_comments_at_end_of_file} = []; + + # Any other parameters are unkown + while (($k, $v) = each %parms) { + carp "Unknown named parameter $k=>$v"; + $errs++; + } + + return undef if $errs; + + if ($self->ReadConfig) { + return $self; + } else { + return undef; + } + } + + + =head2 val ($section, $parameter [, $default] ) + + Returns the value of the specified parameter (C<$parameter>) in section + C<$section>, returns undef (or C<$default> if specified) if no section or + no parameter for the given section exists. + + + If you want a multi-line/value field returned as an array, just + specify an array as the receiver: + + @values = $cfg->val('Section', 'Parameter'); + + A multi-line/value field that is returned in a scalar context will be + joined using $/ (input record separator, default is \n) if defined, + otherwise the values will be joined using \n. + + =cut + + sub _caseify { + my ($self, @refs) = @_; + + if (not $self->_nocase) + { + return; + } + + foreach my $ref (@refs) { + ${$ref} = lc(${$ref}) + } + + return; + } + + sub val { + my ($self, $sect, $parm, $def) = @_; + + # Always return undef on bad parameters + return if not defined $sect; + return if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + my $val = defined($self->{v}{$sect}{$parm}) ? + $self->{v}{$sect}{$parm} : + $self->{v}{$self->{default}}{$parm}; + + # If the value is undef, make it $def instead (which could just be undef) + $val = $def unless defined $val; + + # Return the value in the desired context + if (wantarray) { + if (ref($val) eq "ARRAY") { + return @$val; + } elsif (defined($val)) { + return $val; + } else { + return; + } + } elsif (ref($val) eq "ARRAY") { + if (defined ($/)) { + return join "$/", @$val; + } else { + return join "\n", @$val; + } + } else { + return $val; + } + } + + + + =head2 exists($section, $parameter) + + True if and only if there exists a section C<$section>, with + a parameter C<$parameter> inside, not counting default values. + + =cut + + sub exists { + my ($self, $sect, $parm) = @_; + + $self->_caseify(\$sect, \$parm); + + return (exists $self->{v}{$sect}{$parm}); + } + + + + =head2 push ($section, $parameter, $value, [ $value2, ...]) + + Pushes new values at the end of existing value(s) of parameter + C<$parameter> in section C<$section>. See below for methods to write + the new configuration back out to a file. + + You may not set a parameter that didn't exist in the original + configuration file. B will return I if this is + attempted. See B below to do this. Otherwise, it returns 1. + + =cut + + sub push { + my ($self, $sect, $parm, @vals) = @_; + + return undef if not defined $sect; + return undef if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + return undef if (! defined($self->{v}{$sect}{$parm})); + + return 1 if (! @vals); + + $self->_touch_parameter($sect, $parm); + + $self->{EOT}{$sect}{$parm} = 'EOT' if + (!defined $self->{EOT}{$sect}{$parm}); + + $self->{v}{$sect}{$parm} = [$self->{v}{$sect}{$parm}] unless + (ref($self->{v}{$sect}{$parm}) eq "ARRAY"); + + CORE::push @{$self->{v}{$sect}{$parm}}, @vals; + return 1; + } + + =head2 setval ($section, $parameter, $value, [ $value2, ... ]) + + Sets the value of parameter C<$parameter> in section C<$section> to + C<$value> (or to a set of values). See below for methods to write + the new configuration back out to a file. + + You may not set a parameter that didn't exist in the original + configuration file. B will return I if this is + attempted. See B below to do this. Otherwise, it returns 1. + + =cut + + sub setval { + my $self = shift; + my $sect = shift; + my $parm = shift; + my @val = @_; + + return undef if not defined $sect; + return undef if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + if (defined($self->{v}{$sect}{$parm})) { + $self->_touch_parameter($sect, $parm); + if (@val > 1) { + $self->{v}{$sect}{$parm} = \@val; + $self->{EOT}{$sect}{$parm} = 'EOT'; + } else { + $self->{v}{$sect}{$parm} = shift @val; + } + return 1; + } else { + return undef; + } + } + + =head2 newval($section, $parameter, $value [, $value2, ...]) + + Assignes a new value, C<$value> (or set of values) to the + parameter C<$parameter> in section C<$section> in the configuration + file. + + =cut + + sub newval { + my $self = shift; + my $sect = shift; + my $parm = shift; + my @val = @_; + + return undef if not defined $sect; + return undef if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + $self->AddSection($sect); + + CORE::push(@{$self->{parms}{$sect}}, $parm) + unless (grep {/^\Q$parm\E$/} @{$self->{parms}{$sect}} ); + + $self->_touch_parameter($sect, $parm); + if (@val > 1) { + $self->{v}{$sect}{$parm} = \@val; + $self->{EOT}{$sect}{$parm} = 'EOT' unless defined $self->{EOT}{$sect}{$parm}; + } else { + $self->{v}{$sect}{$parm} = shift @val; + } + return 1 + } + + =head2 delval($section, $parameter) + + Deletes the specified parameter from the configuration file + + =cut + + sub delval { + my $self = shift; + my $sect = shift; + my $parm = shift; + + return undef if not defined $sect; + return undef if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + @{$self->{parms}{$sect}} = grep !/^\Q$parm\E$/, @{$self->{parms}{$sect}}; + $self->_touch_parameter($sect, $parm); + delete $self->{v}{$sect}{$parm}; + return 1 + } + + =head2 ReadConfig + + Forces the configuration file to be re-read. Returns undef if the + file can not be opened, no filename was defined (with the C<-file> + option) when the object was constructed, or an error occurred while + reading. + + If an error occurs while parsing the INI file the @Config::IniFiles::errors + array will contain messages that might help you figure out where the + problem is in the file. + + =cut + + # Auxillary function to make deep (aliasing-free) copies of data + # structures. Ignores blessed objects in tree (could be taught not + # to, if needed) + sub _deepcopy { + my $ref=shift; + + if (! ref($ref)) { return $ref; } + + local $_; + + if (UNIVERSAL::isa($ref, "ARRAY")) { + return [map {_deepcopy($_)} @$ref]; + } + + if (UNIVERSAL::isa($ref, "HASH")) { + my $return={}; + foreach my $k (keys %$ref) { + $return->{$k}=_deepcopy($ref->{$k}); + } + return $return; + } + + carp "Unhandled data structure in $ref, cannot _deepcopy()"; + } + + # Internal method, gets the next line, taking proper care of line endings. + sub _nextline { + my ($self, $fh)=@_; + local $_; + if (!exists $self->{line_ends}) { + # no $self->{line_ends} is a hint set by caller that we are at + # the first line (kludge kludge). + { + local $/=\1; + my $nextchar; + do { + $nextchar=<$fh>; + return undef if (!defined $nextchar); + $_ .= $nextchar; + } until (m/((\015|\012|\025|\n)$)/s); + $self->{line_ends}=$1; + if ($nextchar eq "\x0d") { + # peek at the next char + $nextchar = <$fh>; + if ($nextchar eq "\x0a") { + $self->{line_ends} .= "\x0a"; + } else { + seek $fh, -1, 1; + } + } + } + + # If there's a UTF BOM (Byte-Order-Mark) in the first + # character of the first line then remove it before processing + # (http://www.unicode.org/unicode/faq/utf_bom.html#22) + s/^//; + + return $_; + } else { + local $/=$self->{line_ends}; + return scalar <$fh>; + } + } + + # Internal method, closes or resets the file handle. To be called + # whenever ReadConfig() returns. + sub _rollback { + my ($self, $fh)=@_; + # Only close if this is a filename, if it's + # an open handle, then just roll back to the start + if( !ref($self->{cf}) ) { + close($fh); + } else { + # Attempt to rollback to beginning, no problem if this fails (e.g. STDIN) + seek( $fh, 0, 0 ); + } # end if + } + + + sub ReadConfig { + my $self = shift; + + my($lineno, $sect); + my($group, $groupmem); + my($parm, $val); + my @cmts; + my $end_comment; + + @Config::IniFiles::errors = ( ); + + # Initialize (and clear out) storage hashes + $self->{sects} = []; + $self->{parms} = {}; + $self->{group} = {}; + $self->{v} = {}; + $self->{sCMT} = {}; + $self->{pCMT} = {}; + $self->{EOT} = {}; + $self->{mysects} = []; # A pair of hashes to remember which params are loaded + $self->{myparms} = {}; # or set using the API vs. imported - useful for + $self->{peCMT} = {}; # this will store trailing comments at the end of single-lined params + # import shadowing, see below, and WriteConfig(-delta=>1) + + if( defined $self->{imported} ) { + # Run up the import tree to the top, then reload coming + # back down, maintaining the imported file names and our + # file name. + # This is only needed on a re-load though + $self->{imported}->ReadConfig() unless ($self->{firstload}); + + foreach my $field (qw(sects parms group v sCMT pCMT EOT)) { + $self->{$field} = _deepcopy($self->{imported}->{$field}); + } + } # end if + + if ( (not exists $self->{cf}) + or (not defined $self->{cf}) + or ($self->{cf} eq '') + ) + { + return 1; + } + + my $nocase = $self->_nocase; + my $end_commenthandle = $self->{handle_trailing_comment}; + + # If this is a reload and we want warnings then send one to the STDERR log + unless( $self->{firstload} || !$self->{reloadwarn} ) { + my ($ss, $mm, $hh, $DD, $MM, $YY) = (localtime(time))[0..5]; + printf STDERR + "PID %d reloading config file %s at %d.%02d.%02d %02d:%02d:%02d\n", + $$, $self->{cf}, $YY+1900, $MM+1, $DD, $hh, $mm, $ss; + } + + # Turn off. Future loads are reloads + $self->{firstload} = 0; + + # Get a filehandle, allowing almost any type of 'file' parameter + my $fh = $self->_make_filehandle( $self->{cf} ); + if (!$fh) { + carp "Failed to open $self->{cf}: $!"; + return undef; + } + + # Get mod time of file so we can retain it (if not from STDIN) + # also check if it's a real file (could have been a filehandle made from a scalar). + if (ref($fh) ne "IO::Scalar" && -e $fh) + { + my @stats = stat $fh; + $self->{file_mode} = sprintf("%04o", $stats[2]) if defined $stats[2]; + } + + + # The first lines of the file must be blank, comments or start with [ + my $first = ''; + my $allCmt = $self->{allowed_comment_char}; + + local $_; + delete $self->{line_ends}; # Marks start of parsing for _nextline() + while ( defined($_ = $self->_nextline($fh)) ) { + s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s) + $lineno++; + if (/^\s*$/) { # ignore blank lines + next; + } + elsif (/^\s*[$allCmt]/) { # collect comments + if ($self->{negativedeltas} && + m/^$self->{comment_char} (.*) is deleted$/) { + my $todelete=$1; + if ($todelete =~ m/^\[(.*)\]$/) { + $self->DeleteSection($1); + } else { + $self->delval($sect, $todelete); + } + } else { + CORE::push(@cmts, $_); + } + next; + } + elsif (/^\s*\[\s*(\S|\S.*\S)\s*\]\s*$/) { # New Section + $sect = $1; + $self->_caseify(\$sect); + $self->AddSection($sect); + $self->SetSectionComment($sect, @cmts); + @cmts = (); + } + elsif (($parm, $val) = /^\s*([^=]*?[^=\s])\s*=\s*(.*)$/) { # new parameter + if ((!defined($sect)) and defined($self->{fallback})) + { + $sect = $self->{fallback}; + $self->{fallback_used}++; + } + if (!defined $sect) { + CORE::push(@Config::IniFiles::errors, sprintf('%d: %s', $lineno, + qq#parameter found outside a section#)); + $self->_rollback($fh); + return undef; + } + + $parm = lc($parm) if $nocase; + my @val = ( ); + my $eotmark; + if ($val =~ /^<<(.*)$/) { # "here" value + $eotmark = $1; + my $foundeot = 0; + my $startline = $lineno; + while ( defined($_=$self->_nextline($fh)) ) { + s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s) + $lineno++; + if ($_ eq $eotmark) { + $foundeot = 1; + last; + } else { + # Untaint + /(.*)/ms; + CORE::push(@val, $1); + } + } + if (! $foundeot) { + CORE::push(@Config::IniFiles::errors, sprintf('%d: %s', $startline, + qq#no end marker ("$eotmark") found#)); + $self->_rollback(); + return undef; + } + } else { # no here value + + # process continuation lines, if any + while($self->{allowcontinue} && $val =~ s/\\$//) { + $_ = $self->_nextline($fh); + s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s) + $lineno++; + $val .= $_; + } + + # we should split value and comments if there is any comment + if ($end_commenthandle && + $val =~ /(.*?)\s*[$allCmt]\s*([^$allCmt]*)$/) { + $val = $1; + $end_comment = $2; + } else { + $end_comment = ""; + } + + @val = $val; + } + # Now load value + if (exists $self->{v}{$sect}{$parm} && + exists $self->{myparms}{$sect} && + grep( /^\Q$parm\E$/, @{$self->{myparms}{$sect}}) ) { + $self->push($sect, $parm, @val); + } else { + # Loaded parameters shadow imported ones, instead of appending + # to them + $self->newval($sect, $parm, @val); + } + $self->SetParameterComment($sect, $parm, @cmts); + @cmts = ( ); + $self->SetParameterEOT($sect,$parm,$eotmark) if (defined $eotmark); + # if handle_trailing_comment is off, this line makes no sense, since all $end_comment="" + $self->SetParameterTrailingComment($sect, $parm, $end_comment); + + } else { + CORE::push(@Config::IniFiles::errors, sprintf("Line \%d in file " . $self->{cf} . " is mal-formed:\n\t\%s", $lineno, $_)); + } + } # End main parsing loop + + # Special case: return undef if file is empty. (suppress this line to + # restore the more intuitive behaviour of accepting empty files) + if (! keys %{$self->{v}} && ! $self->{allowempty}) { + CORE::push @Config::IniFiles::errors, "Empty file treated as error"; + $self->_rollback($fh); + return undef; + } + + if( defined (my $defaultsect=$self->{startup_settings}->{-default}) ) { + $self->AddSection($defaultsect); + } # end if + + $self->_SetEndComments(@cmts); + + $self->_rollback($fh); + @Config::IniFiles::errors ? undef : 1; + } + + + =head2 Sections + + Returns an array containing section names in the configuration file. + If the I option was turned on when the config object was + created, the section names will be returned in lowercase. + + =cut + + sub Sections { + my $self = shift; + return @{$self->{sects}} if ref $self->{sects} eq 'ARRAY'; + return (); + } + + =head2 SectionExists ( $sect_name ) + + Returns 1 if the specified section exists in the INI file, 0 otherwise (undefined if section_name is not defined). + + =cut + + sub SectionExists { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + + return undef() if not defined $sect; + return 1 if (grep {/^\Q$sect\E$/} @{$self->{sects}}); + return 0; + } + + =head2 AddSection ( $sect_name ) + + Ensures that the named section exists in the INI file. If the section already + exists, nothing is done. In this case, the "new" section will possibly contain + data already. + + If you really need to have a new section with no parameters in it, check that + the name that you're adding isn't in the list of sections already. + + =cut + + sub AddSection { + my ($self, $sect) = @_; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + + return if $self->SectionExists($sect); + CORE::push @{$self->{sects}}, $sect unless + grep /^\Q$sect\E$/, @{$self->{sects}}; + $self->_touch_section($sect); + + $self->SetGroupMember($sect); + + # Set up the parameter names and values lists + $self->{parms}{$sect} = [] unless ref $self->{parms}{$sect} eq 'ARRAY'; + if (!defined($self->{v}{$sect})) { + $self->{sCMT}{$sect} = []; + $self->{pCMT}{$sect} = {}; # Comments above parameters + $self->{parms}{$sect} = []; + $self->{v}{$sect} = {}; + } + } + + # Marks a section as modified by us (this includes deleted by us). + sub _touch_section { + my ($self, $sect)=@_; + + $self->{mysects} ||= []; + CORE::push @{$self->{mysects}}, $sect unless + grep /^\Q$sect\E$/, @{$self->{mysects}}; + } + + # Marks a parameter as modified by us (this includes deleted by us). + sub _touch_parameter { + my ($self, $sect, $parm)=@_; + + $self->_touch_section($sect); + return if (!exists $self->{v}{$sect}); + $self->{myparms}{$sect} ||= []; + CORE::push @{$self->{myparms}{$sect}}, $parm unless + grep /^\Q$parm\E$/, @{$self->{myparms}{$sect}}; + } + + + =head2 DeleteSection ( $sect_name ) + + Completely removes the entire section from the configuration. + + =cut + + sub DeleteSection { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + + # This is done the fast way, change if data structure changes!! + delete $self->{v}{$sect}; + delete $self->{sCMT}{$sect}; + delete $self->{pCMT}{$sect}; + delete $self->{EOT}{$sect}; + delete $self->{parms}{$sect}; + delete $self->{myparms}{$sect}; + + @{$self->{sects}} = grep !/^\Q$sect\E$/, @{$self->{sects}}; + $self->_touch_section($sect); + + if( $sect =~ /^(\S+)\s+\S+/ ) { + my $group = $1; + if( defined($self->{group}{$group}) ) { + @{$self->{group}{$group}} = grep !/^\Q$sect\E$/, @{$self->{group}{$group}}; + } # end if + } # end if + + return 1; + } # end DeleteSection + + =head2 Parameters ($sect_name) + + Returns an array containing the parameters contained in the specified + section. + + =cut + + sub Parameters { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + + return @{$self->{parms}{$sect}} if ref $self->{parms}{$sect} eq 'ARRAY'; + return (); + } + + =head2 Groups + + Returns an array containing the names of available groups. + + Groups are specified in the config file as new sections of the form + + [GroupName MemberName] + + This is useful for building up lists. Note that parameters within a + "member" section are referenced normally (i.e., the section name is + still "Groupname Membername", including the space) - the concept of + Groups is to aid people building more complex configuration files. + + =cut + + sub Groups { + my $self = shift; + return keys %{$self->{group}} if ref $self->{group} eq 'HASH'; + return (); + } + + =head2 SetGroupMember ( $sect ) + + Makes sure that the specified section is a member of the appropriate group. + + Only intended for use in newval. + + =cut + + sub SetGroupMember { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + return(1) unless $sect =~ /^(\S+)\s+\S+/; + + my $group = $1; + if (not exists($self->{group}{$group})) { + $self->{group}{$group} = []; + } + if (not grep {/^\Q$sect\E$/} @{$self->{group}{$group}}) { + CORE::push @{$self->{group}{$group}}, $sect; + } + } + + =head2 RemoveGroupMember ( $sect ) + + Makes sure that the specified section is no longer a member of the + appropriate group. Only intended for use in DeleteSection. + + =cut + + sub RemoveGroupMember { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + return(1) unless $sect =~ /^(\S+)\s+\S+/; + + my $group = $1; + return unless exists $self->{group}{$group}; + @{$self->{group}{$group}} = grep {!/^\Q$sect\E$/} @{$self->{group}{$group}}; + } + + =head2 GroupMembers ($group) + + Returns an array containing the members of specified $group. Each element + of the array is a section name. For example, given the sections + + [Group Element 1] + ... + + [Group Element 2] + ... + + GroupMembers would return ("Group Element 1", "Group Element 2"). + + =cut + + sub GroupMembers { + my $self = shift; + my $group = shift; + + return undef if not defined $group; + + $self->_caseify(\$group); + + return @{$self->{group}{$group}} if ref $self->{group}{$group} eq 'ARRAY'; + return (); + } + + =head2 SetWriteMode ($mode) + + Sets the mode (permissions) to use when writing the INI file. + + $mode must be a string representation of the octal mode. + + =cut + + sub SetWriteMode + { + my $self = shift; + my $mode = shift; + return undef if not defined ($mode); + return undef if not ($mode =~ m/[0-7]{3,3}/); + $self->{file_mode} = $mode; + return $mode; + } + + =head2 GetWriteMode ($mode) + + Gets the current mode (permissions) to use when writing the INI file. + + $mode is a string representation of the octal mode. + + =cut + + sub GetWriteMode + { + my $self = shift; + return undef if not exists $self->{file_mode}; + return $self->{file_mode}; + } + + =head2 WriteConfig ($filename [, %options]) + + Writes out a new copy of the configuration file. A temporary file + (ending in '-new') is written out and then renamed to the specified + filename. Also see B below. + + If C<-delta> is set to a true value in %options, and this object was + imported from another (see L), only the differences between this + object and the imported one will be recorded. Negative deltas will be + encoded into comments, so that a subsequent invocation of I + with the same imported object produces the same results (see the + I<-negativedeltas> option in L). + + C<%options> is not required. + + Returns true on success, C on failure. + + =cut + + sub WriteConfig { + my ($self, $file, %parms) = @_; + + return undef unless defined $file; + + + # If we are using a filename, then do mode checks and write to a + # temporary file to avoid a race condition + if( !ref($file) ) { + if (-e $file) { + if (not (-w $file)) + { + #carp "File $file is not writable. Refusing to write config"; + return undef; + } + my $mode = (stat $file)[2]; + $self->{file_mode} = sprintf "%04o", ($mode & 0777); + #carp "Using mode $self->{file_mode} for file $file"; + } elsif (defined($self->{file_mode}) and not (oct($self->{file_mode}) & 0222)) { + #carp "Store mode $self->{file_mode} prohibits writing config"; + } + + my $new_file = $file . "-new"; + open(my $fh, '>', $new_file) || do { + carp "Unable to write temp config file $new_file: $!"; + return undef; + }; + $self->OutputConfigToFileHandle($fh, $parms{-delta}); + close($fh); + if (!rename( $new_file, $file )) { + carp "Unable to rename temp config file ($new_file) to $file: $!"; + return undef; + } + if (exists $self->{file_mode}) { + chmod oct($self->{file_mode}), $file; + } + + } # Otherwise, reset to the start of the file and write, unless we are using STDIN + else { + # Get a filehandle, allowing almost any type of 'file' parameter + ## NB: If this were a filename, this would fail because _make_file + ## opens a read-only handle, but we have already checked that case + ## so re-using the logic is ok [JW/WADG] + my $fh = $self->_make_filehandle( $file ); + if (!$fh) { + carp "Could not find a filehandle for the input stream ($file): $!"; + return undef; + } + + + # Only roll back if it's not STDIN (if it is, Carp) + if( $fh == \*STDIN ) { + carp "Cannot write configuration file to STDIN."; + } else { + seek( $fh, 0, 0 ); + $self->OutputConfigToFileHandle($fh, $parms{-delta}); + seek( $fh, 0, 0 ); + } # end if + + } # end if (filehandle/name) + + return 1; + + } + + =head2 RewriteConfig + + Same as WriteConfig, but specifies that the original configuration + file should be rewritten. + + =cut + + sub RewriteConfig { + my $self = shift; + + return undef if ( + (not exists $self->{cf}) or + (not defined $self->{cf}) or + ($self->{cf} eq '') + ); + + # Return whatever WriteConfig returns :) + $self->WriteConfig($self->{cf}); + } + + =head2 GetFileName + + Returns the filename associated with this INI file. + + If no filename has been specified, returns undef. + + =cut + + sub GetFileName + { + my $self = shift; + my $filename; + if (exists $self->{cf}) { + $filename = $self->{cf}; + } else { + undef $filename; + } + return $filename; + } + + =head2 SetFileName ($filename) + + If you created the Config::IniFiles object without initialising from + a file, or if you just want to change the name of the file to use for + ReadConfig/RewriteConfig from now on, use this method. + + Returns $filename if that was a valid name, undef otherwise. + + =cut + + sub SetFileName { + my $self = shift; + my $newfile = shift; + + return undef if not defined $newfile; + + if ($newfile ne "") { + $self->{cf} = $newfile; + return $self->{cf}; + } + return undef; + } + + =head2 $ini->OutputConfigToFileHandle($fh, $delta) + + Writes OutputConfig to the $fh filehandle. $delta should be set to 1 + 1 if writing only delta. This is a newer and safer version of + C and one is encouraged to use it instead. + + =head2 $ini->OutputConfig($delta) + + Writes OutputConfig to STDOUT. Use select() to redirect STDOUT to + the output target before calling this function. Optional argument + should be set to 1 if writing only delta. Also see OutputConfigToFileHandle + + =cut + + sub _OutputParam { + my ($self, $sect, $parm, $val, $ors, $end_comment, $output_cb) = @_; + + if (! @$val) { + # An empty variable - see: + # https://rt.cpan.org/Public/Bug/Display.html?id=68554 + $output_cb->("$parm="); + $output_cb->("$ors"); + } + elsif ((@$val == 1) or $self->{nomultiline}) { + my $cnt = 0; + foreach (@{$val}) { + $cnt++; + $output_cb->("$parm=$_"); + # output trailing comment at the last parameter + if ($end_comment && $cnt == @$val) { + $output_cb->(" $self->{comment_char} $end_comment") + } + $output_cb->("$ors"); + } + } + else + { + my $eotmark = $self->{EOT}{$sect}{$parm} || 'EOT'; + + # Make sure the $eotmark does not occur inside the string. + my @letters = ('A' .. 'Z'); + my $joined_val = join(q{ }, @$val); + while (index($joined_val, $eotmark) >= 0) + { + $eotmark .= $letters[rand(@letters)]; + } + + $output_cb->("$parm= <<$eotmark$ors"); + my $cnt = 0; + foreach (@{$val}) { + $cnt++; + $output_cb->("$_"); + # output trailing comment at the last parameter + if ($end_comment && $cnt == @$val) { + $output_cb->(" $self->{comment_char} $end_comment") + } + $output_cb->("$ors"); + } + $output_cb->("$eotmark$ors"); + } + + return; + } + + sub OutputConfig { + my ($self, $delta) = @_; + + return $self->OutputConfigToFileHandle(select(), $delta); + } + + sub OutputConfigToFileHandle { + # We need no strict 'refs' to be able to print to $fh if it points + # to a glob filehandle. + no strict 'refs'; + my ($self, $fh, $delta) = @_; + + my($sect, $parm, @cmts); + my $ors = $self->{line_ends} || $\ || "\n"; # $\ is normally unset, but use input by default + my $notfirst = 0; + local $_; + SECT: + foreach $sect (@{$self->{$delta ? "mysects" : "sects"}}) { + if (!defined $self->{v}{$sect}) { + if ($delta) { + print {$fh} "$self->{comment_char} [$sect] is deleted$ors"; + } else { + warn "Weird unknown section $sect" if $^W; + } + next SECT; + } + next unless defined $self->{v}{$sect}; + print {$fh} $ors if $notfirst; + $notfirst = 1; + if ((ref($self->{sCMT}{$sect}) eq 'ARRAY') && + (@cmts = @{$self->{sCMT}{$sect}})) { + foreach (@cmts) { + print {$fh} "$_$ors"; + } + } + + if (! + ($self->{fallback_used} and $sect eq $self->{fallback}) + ) + { + print {$fh} "[$sect]$ors"; + } + next unless ref $self->{v}{$sect} eq 'HASH'; + + PARM: + foreach $parm (@{$self->{$delta ? "myparms" : "parms"}{$sect}}) { + if (!defined $self->{v}{$sect}{$parm}) { + if ($delta) { + print {$fh} "$self->{comment_char} $parm is deleted$ors"; + } else { + warn "Weird unknown parameter $parm" if $^W; + } + next PARM; + } + if ((ref($self->{pCMT}{$sect}{$parm}) eq 'ARRAY') && + (@cmts = @{$self->{pCMT}{$sect}{$parm}})) { + foreach (@cmts) { + print {$fh} "$_$ors"; + } + } + + my $val = $self->{v}{$sect}{$parm}; + my $end_comment = $self->{peCMT}{$sect}{$parm}; + + next if ! defined ($val); # No parameter exists !! + + $self->_OutputParam( + $sect, + $parm, + ((ref($val) eq 'ARRAY') + ? $val + : [split /[$ors]/, $val, -1] + ), + $ors, + defined $end_comment ? $end_comment : "", + sub { print {$fh} @_; }, + ); + } + } + foreach my $comment ($self->_GetEndComments()) { + print {$fh} "$comment$ors"; + } + return 1; + } + + =head2 SetSectionComment($section, @comment) + + Sets the comment for section $section to the lines contained in @comment. + + Each comment line will be prepended with the comment character (default + is C<#>) if it doesn't already have a comment character (ie: if the + line does not start with whitespace followed by an allowed comment + character, default is C<#> and C<;>). + + To clear a section comment, use DeleteSectionComment ($section) + + =cut + + sub SetSectionComment + { + my $self = shift; + my $sect = shift; + my @comment = @_; + + return undef if not defined $sect; + return undef unless @comment; + + $self->_caseify(\$sect); + + $self->_touch_section($sect); + $self->{sCMT}{$sect} = []; + # At this point it's possible to have a comment for a section that + # doesn't exist. This comment will not get written to the INI file. + + CORE::push @{$self->{sCMT}{$sect}}, $self->_markup_comments(@comment); + return scalar @comment; + } + + + + # this helper makes sure that each line is preceded with the correct comment + # character + sub _markup_comments + { + my $self = shift; + my @comment = @_; + + my $allCmt = $self->{allowed_comment_char}; + my $cmtChr = $self->{comment_char}; + foreach (@comment) { + m/^\s*[$allCmt]/ or ($_ = "$cmtChr $_"); + } + @comment; + } + + + + =head2 GetSectionComment ($section) + + Returns a list of lines, being the comment attached to section $section. In + scalar context, returns a string containing the lines of the comment separated + by newlines. + + The lines are presented as-is, with whatever comment character was originally + used on that line. + + =cut + + sub GetSectionComment + { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + + if (exists $self->{sCMT}{$sect}) { + my @ret = @{$self->{sCMT}{$sect}}; + if (wantarray()) { + return @ret; + } + else { + if (defined ($/)) { + return join "$/", @ret; + } else { + return join "\n", @ret; + } + } + } else { + return undef; + } + } + + =head2 DeleteSectionComment ($section) + + Removes the comment for the specified section. + + =cut + + sub DeleteSectionComment + { + my $self = shift; + my $sect = shift; + + return undef if not defined $sect; + + $self->_caseify(\$sect); + $self->_touch_section($sect); + + delete $self->{sCMT}{$sect}; + } + + =head2 SetParameterComment ($section, $parameter, @comment) + + Sets the comment attached to a particular parameter. + + Any line of @comment that does not have a comment character will be + prepended with one. See L above + + =cut + + sub SetParameterComment + { + my $self = shift; + my $sect = shift; + my $parm = shift; + my @comment = @_; + + defined($sect) || return undef; + defined($parm) || return undef; + @comment || return undef; + + $self->_caseify(\$sect, \$parm); + + $self->_touch_parameter($sect, $parm); + if (not exists $self->{pCMT}{$sect}) { + $self->{pCMT}{$sect} = {}; + } + + $self->{pCMT}{$sect}{$parm} = []; + # Note that at this point, it's possible to have a comment for a parameter, + # without that parameter actually existing in the INI file. + CORE::push @{$self->{pCMT}{$sect}{$parm}}, $self->_markup_comments(@comment); + return scalar @comment; + } + + sub _SetEndComments + { + my $self = shift; + my @comments = @_; + + $self->{_comments_at_end_of_file} = \@comments; + + return 1; + } + + sub _GetEndComments { + my $self = shift; + + return @{$self->{_comments_at_end_of_file}}; + } + + =head2 GetParameterComment ($section, $parameter) + + Gets the comment attached to a parameter. In list context returns all + comments - in scalar context returns them joined by newlines. + + =cut + + sub GetParameterComment + { + my $self = shift; + my $sect = shift; + my $parm = shift; + + defined($sect) || return undef; + defined($parm) || return undef; + + $self->_caseify(\$sect, \$parm); + + exists($self->{pCMT}{$sect}) || return undef; + exists($self->{pCMT}{$sect}{$parm}) || return undef; + + my @comment = @{$self->{pCMT}{$sect}{$parm}}; + return wantarray() ? @comment : join((defined $/ ? $/ : "\n"), @comment); + } + + =head2 DeleteParameterComment ($section, $parmeter) + + Deletes the comment attached to a parameter. + + =cut + + sub DeleteParameterComment + { + my $self = shift; + my $sect = shift; + my $parm = shift; + + defined($sect) || return undef; + defined($parm) || return undef; + + $self->_caseify(\$sect, \$parm); + + # If the parameter doesn't exist, our goal has already been achieved + exists($self->{pCMT}{$sect}) || return 1; + exists($self->{pCMT}{$sect}{$parm}) || return 1; + + $self->_touch_parameter($sect, $parm); + delete $self->{pCMT}{$sect}{$parm}; + return 1; + } + + =head2 GetParameterEOT ($section, $parameter) + + Accessor method for the EOT text (in fact, style) of the specified parameter. If any text is used as an EOT mark, this will be returned. If the parameter was not recorded using HERE style multiple lines, GetParameterEOT returns undef. + + =cut + + sub GetParameterEOT + { + my $self = shift; + my $sect = shift; + my $parm = shift; + + defined($sect) || return undef; + defined($parm) || return undef; + + $self->_caseify(\$sect, \$parm); + + if (not exists $self->{EOT}{$sect}) { + $self->{EOT}{$sect} = {}; + } + + if (not exists $self->{EOT}{$sect}{$parm}) { + return undef; + } + return $self->{EOT}{$sect}{$parm}; + } + + =head2 $cfg->SetParameterEOT ($section, $parameter, $EOT) + + Accessor method for the EOT text for the specified parameter. Sets the HERE style marker text to the value $EOT. Once the EOT text is set, that parameter will be saved in HERE style. + + To un-set the EOT text, use DeleteParameterEOT ($section, $parameter). + + =cut + + sub SetParameterEOT + { + my $self = shift; + my $sect = shift; + my $parm = shift; + my $EOT = shift; + + defined($sect) || return undef; + defined($parm) || return undef; + defined($EOT) || return undef; + + $self->_caseify(\$sect, \$parm); + + $self->_touch_parameter($sect, $parm); + if (not exists $self->{EOT}{$sect}) { + $self->{EOT}{$sect} = {}; + } + + $self->{EOT}{$sect}{$parm} = $EOT; + } + + =head2 DeleteParameterEOT ($section, $parmeter) + + Removes the EOT marker for the given section and parameter. + When writing a configuration file, if no EOT marker is defined + then "EOT" is used. + + =cut + + sub DeleteParameterEOT + { + my $self = shift; + my $sect = shift; + my $parm = shift; + + defined($sect) || return undef; + defined($parm) || return undef; + + $self->_caseify(\$sect, \$parm); + + $self->_touch_parameter($sect, $parm); + delete $self->{EOT}{$sect}{$parm}; + } + + =head2 SetParameterTrailingComment ($section, $parameter, $cmt) + + Set the end trailing comment for the given section and parameter. + If there is a old comment for the parameter, it will be + overwritten by the new one. + + If there is a new parameter trailing comment to be added, the + value should be added first. + + =cut + + sub SetParameterTrailingComment + { + my $self = shift; + my $sect = shift; + my $parm = shift; + my $cmt = shift; + + return undef if not defined $sect; + return undef if not defined $parm; + return undef if not defined $cmt; + + $self->_caseify(\$sect, \$parm); + + # confirm the parameter exist + return undef if not exists $self->{v}{$sect}{$parm}; + + $self->_touch_parameter($sect, $parm); + $self->{peCMT}{$sect}{$parm} = $cmt; + 1; + } + + =head2 GetParameterTrailingComment ($section, $parameter) + + An accessor method to read the trailing comment after the parameter. + The trailing comment will be returned if there is one. A null string + will be returned if the parameter exists but no comment for it. + otherwise, L will be returned. + + =cut + + sub GetParameterTrailingComment + { + my $self = shift; + my $sect = shift; + my $parm = shift; + + return undef if not defined $sect; + return undef if not defined $parm; + + $self->_caseify(\$sect, \$parm); + + # confirm the parameter exist + return undef if not exists $self->{v}{$sect}{$parm}; + return $self->{peCMT}{$sect}{$parm}; + } + + =head2 Delete + + Deletes the entire configuration file in memory. + + =cut + + sub Delete { + my $self = shift; + + foreach my $section ($self->Sections()) { + $self->DeleteSection($section); + } + + return 1; + } # end Delete + + + + =head1 USAGE -- Tied Hash + + =head2 tie %ini, 'Config::IniFiles', (-file=>$filename, [-option=>value ...] ) + + Using C, you can tie a hash to a B object. This creates a new + object which you can access through your hash, so you use this instead of the + B method. This actually creates a hash of hashes to access the values in + the INI file. The options you provide through C are the same as given for + the B method, above. + + Here's an example: + + use Config::IniFiles; + + my %ini + tie %ini, 'Config::IniFiles', ( -file => "/path/configfile.ini" ); + + print "We have $ini{Section}{Parameter}." if $ini{Section}{Parameter}; + + Accessing and using the hash works just like accessing a regular hash and + many of the object methods are made available through the hash interface. + + For those methods that do not coincide with the hash paradigm, you can use + the Perl C function to get at the underlying object tied to the hash + and call methods on that object. For example, to write the hash out to a new + ini file, you would do something like this: + + tied( %ini )->WriteConfig( "/newpath/newconfig.ini" ) || + die "Could not write settings to new file."; + + =head2 $val = $ini{$section}{$parameter} + + Returns the value of $parameter in $section. + + Multiline values accessed through a hash will be returned + as a list in list context and a concatenated value in scalar + context. + + =head2 $ini{$section}{$parameter} = $value; + + Sets the value of C<$parameter> in C<$section> to C<$value>. + + To set a multiline or multiv-alue parameter just assign an + array reference to the hash entry, like this: + + $ini{$section}{$parameter} = [$value1, $value2, ...]; + + If the parameter did not exist in the original file, it will + be created. However, Perl does not seem to extend autovivification + to tied hashes. That means that if you try to say + + $ini{new_section}{new_paramters} = $val; + + and the section 'new_section' does not exist, then Perl won't + properly create it. In order to work around this you will need + to create a hash reference in that section and then assign the + parameter value. Something like this should do nicely: + + $ini{new_section} = {}; + $ini{new_section}{new_paramters} = $val; + + =head2 %hash = %{$ini{$section}} + + Using the tie interface, you can copy whole sections of the + ini file into another hash. Note that this makes a copy of + the entire section. The new hash in no longer tied to the + ini file, In particular, this means -default and -nocase + settings will not apply to C<%hash>. + + + =head2 $ini{$section} = {}; %{$ini{$section}} = %parameters; + + Through the hash interface, you have the ability to replace + the entire section with a new set of parameters. This call + will fail, however, if the argument passed in NOT a hash + reference. You must use both lines, as shown above so that + Perl recognizes the section as a hash reference context + before COPYing over the values from your C<%parameters> hash. + + =head2 delete $ini{$section}{$parameter} + + When tied to a hash, you can use the Perl C function + to completely remove a parameter from a section. + + =head2 delete $ini{$section} + + The tied interface also allows you to delete an entire + section from the ini file using the Perl C function. + + =head2 %ini = (); + + If you really want to delete B the items in the ini file, this + will do it. Of course, the changes won't be written to the actual + file unless you call B on the object tied to the hash. + + =head2 Parameter names + + =over 4 + + =item my @keys = keys %{$ini{$section}} + + =item while (($k, $v) = each %{$ini{$section}}) {...} + + =item if( exists %{$ini{$section}}, $parameter ) {...} + + =back + + When tied to a hash, you use the Perl C and C + functions to iteratively list the parameters (C) or + parameters and their values (C) in a given section. + + You can also use the Perl C function to see if a + parameter is defined in a given section. + + Note that none of these will return parameter names that + are part of the default section (if set), although accessing + an unknown parameter in the specified section will return a + value from the default section if there is one. + + + =head2 Section names + + =over 4 + + =item foreach( keys %ini ) {...} + + =item while (($k, $v) = each %ini) {...} + + =item if( exists %ini, $section ) {...} + + =back + + When tied to a hash, you use the Perl C and C + functions to iteratively list the sections in the ini file. + + You can also use the Perl C function to see if a + section is defined in the file. + + =cut + + ############################################################ + # + # TIEHASH Methods + # + # Description: + # These methods allow you to tie a hash to the + # Config::IniFiles object. Note that, when tied, the + # user wants to look at thinks like $ini{sec}{parm}, but the + # TIEHASH only provides one level of hash interace, so the + # root object gets asked for a $ini{sec}, which this + # implements. To further tie the {parm} hash, the internal + # class Config::IniFiles::_section, is provided, below. + # + ############################################################ + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub TIEHASH { + my $class = shift; + my %parms = @_; + + # Get a new object + my $self = $class->new( %parms ); + + return $self; + } # end TIEHASH + + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub FETCH { + my $self = shift; + my( $key ) = @_; + + $self->_caseify(\$key); + return if (! $self->{v}{$key}); + + my %retval; + tie %retval, 'Config::IniFiles::_section', $self, $key; + return \%retval; + + } # end FETCH + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000Jun14 Fixed bug where wrong ref was saved JW + # 2000Oct09 Fixed possible but in %parms with defaults JW + # 2001Apr04 Fixed -nocase problem in storing JW + # ---------------------------------------------------------- + sub STORE { + my $self = shift; + my( $key, $ref ) = @_; + + return undef unless ref($ref) eq 'HASH'; + + $self->_caseify(\$key); + + $self->AddSection($key); + $self->{v}{$key} = {%$ref}; + $self->{parms}{$key} = [keys %$ref]; + $self->{myparms}{$key} = [keys %$ref]; + 1; + } # end STORE + + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # 2000Dec17 Now removes comments, groups and EOTs too JW + # 2001Arp04 Fixed -nocase problem JW + # ---------------------------------------------------------- + sub DELETE { + my $self = shift; + my( $key ) = @_; + + my $retval=$self->FETCH($key); + $self->DeleteSection($key); + return $retval; + } # end DELETE + + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub CLEAR { + my $self = shift; + + return $self->Delete(); + } # end CLEAR + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub FIRSTKEY { + my $self = shift; + + $self->{tied_enumerator}=0; + return $self->NEXTKEY(); + } # end FIRSTKEY + + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub NEXTKEY { + my $self = shift; + my( $last ) = @_; + + my $i=$self->{tied_enumerator}++; + my $key=$self->{sects}[$i]; + return if (! defined $key); + return wantarray ? ($key, $self->FETCH($key)) : $key; + } # end NEXTKEY + + + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # 2001Apr04 Fixed -nocase bug and false true bug JW + # ---------------------------------------------------------- + sub EXISTS { + my $self = shift; + my( $key ) = @_; + return $self->SectionExists($key); + } # end EXISTS + + + # ---------------------------------------------------------- + # DESTROY is used by TIEHASH and the Perl garbage collector, + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000May09 Created method JW + # ---------------------------------------------------------- + sub DESTROY { + # my $self = shift; + } # end if + + + # ---------------------------------------------------------- + # Sub: _make_filehandle + # + # Args: $thing + # $thing An input source + # + # Description: Takes an input source of a filehandle, + # filehandle glob, reference to a filehandle glob, IO::File + # object or scalar filename and returns a file handle to + # read from it with. + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 06Dec2001 Added to support input from any source JW + # ---------------------------------------------------------- + sub _make_filehandle { + my $self = shift; + + # + # This code is 'borrowed' from Lincoln D. Stein's GD.pm module + # with modification for this module. Thanks Lincoln! + # + + no strict 'refs'; + my $thing = shift; + + if (ref($thing) eq "SCALAR") { + if (eval { require IO::Scalar; $IO::Scalar::VERSION >= 2.109; }) { + return IO::Scalar->new($thing); + } else { + warn "SCALAR reference as file descriptor requires IO::stringy ". + "v2.109 or later" if ($^W); + return; + } + } + + return $thing if defined(fileno $thing); + # return $thing if defined($thing) && ref($thing) && defined(fileno $thing); + + # otherwise try qualifying it into caller's package + my $fh = qualify_to_ref($thing,caller(1)); + return $fh if defined(fileno $fh); + # return $fh if defined($thing) && ref($thing) && defined(fileno $fh); + + # otherwise treat it as a file to open + $fh = gensym; + open($fh,$thing) || return; + + return $fh; + } # end _make_filehandle + + ############################################################ + # + # INTERNAL PACKAGE: Config::IniFiles::_section + # + # Description: + # This package is used to provide a single-level TIEHASH + # interface to the sections in the IniFile. When tied, the + # user wants to look at thinks like $ini{sec}{parm}, but the + # TIEHASH only provides one level of hash interace, so the + # root object gets asked for a $ini{sec} and must return a + # has reference that accurately covers the '{parm}' part. + # + # This package is only used when tied and is inter-woven + # between the sections and their parameters when the TIEHASH + # method is called by Perl. It's a very simple implementation + # of a tied hash object that simply maps onto the object API. + # + ############################################################ + # Date Modification Author + # ---------------------------------------------------------- + # 2000.May.09 Created to excapsulate TIEHASH interface JW + ############################################################ + package Config::IniFiles::_section; + + use strict; + use Carp; + use vars qw( $VERSION ); + + $Config::IniFiles::_section::VERSION = 2.16; + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::TIEHASH + # + # Args: $class, $config, $section + # $class The class that this is being tied to. + # $config The parent Config::IniFiles object + # $section The section this tied object refers to + # + # Description: Builds the object that implements accesses to + # the tied hash. + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # ---------------------------------------------------------- + sub TIEHASH { + my $proto = shift; + my $class = ref($proto) || $proto; + my ($config, $section)=@_; + + # Make a new object + return bless {config=>$config, section=>$section}, $class; + } # end TIEHASH + + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::FETCH + # + # Args: $key + # $key The name of the key whose value to get + # + # Description: Returns the value associated with $key. If + # the value is a list, returns a list reference. + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2000Jun15 Fixed bugs in -default handler JW + # 2000Dec07 Fixed another bug in -deault handler JW + # 2002Jul04 Returning scalar values (Bug:447532) AS + # ---------------------------------------------------------- + sub FETCH { + my ($self, $key)=@_; + my @retval=$self->{config}->val($self->{section}, $key); + return (@retval <= 1) ? $retval[0] : \@retval; + } # end FETCH + + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::STORE + # + # Args: $key, @val + # $key The key under which to store the value + # @val The value to store, either an array or a scalar + # + # Description: Sets the value for the specified $key + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2001Apr04 Fixed -nocase bug JW + # ---------------------------------------------------------- + sub STORE { + my ($self, $key, @val)=@_; + return $self->{config}->newval($self->{section}, $key, @val); + } # end STORE + + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::DELETE + # + # Args: $key + # $key The key to remove from the hash + # + # Description: Removes the specified key from the hash and + # returns its former value. + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2001Apr04 Fixed -nocase bug JW + # ---------------------------------------------------------- + sub DELETE { + my ($self, $key)=@_; + my $retval=$self->{config}->val($self->{section}, $key); + $self->{config}->delval($self->{section}, $key); + return $retval; + } # end DELETE + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::CLEAR + # + # Args: (None) + # + # Description: Empties the entire hash + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # ---------------------------------------------------------- + sub CLEAR { + my ($self) = @_; + return $self->{config}->DeleteSection($self->{section}); + } # end CLEAR + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::EXISTS + # + # Args: $key + # $key The key to look for + # + # Description: Returns whether the key exists + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # 2001Apr04 Fixed -nocase bug JW + # ---------------------------------------------------------- + sub EXISTS { + my ($self, $key)=@_; + return $self->{config}->exists($self->{section},$key); + } # end EXISTS + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::FIRSTKEY + # + # Args: (None) + # + # Description: Returns the first key in the hash + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # ---------------------------------------------------------- + sub FIRSTKEY { + my $self = shift; + + $self->{tied_enumerator}=0; + return $self->NEXTKEY(); + } # end FIRSTKEY + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::NEXTKEY + # + # Args: $last + # $last The last key accessed by the interator + # + # Description: Returns the next key in line + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # ---------------------------------------------------------- + sub NEXTKEY { + my $self = shift; + my( $last ) = @_; + + my $i=$self->{tied_enumerator}++; + my @keys = $self->{config}->Parameters($self->{section}); + my $key=$keys[$i]; + return if (! defined $key); + return wantarray ? ($key, $self->FETCH($key)) : $key; + } # end NEXTKEY + + + # ---------------------------------------------------------- + # Sub: Config::IniFiles::_section::DESTROY + # + # Args: (None) + # + # Description: Called on cleanup + # ---------------------------------------------------------- + # Date Modification Author + # ---------------------------------------------------------- + # ---------------------------------------------------------- + sub DESTROY { + # my $self = shift + } # end DESTROY + + 1; + + =head1 IMPORT / DELTA FEATURES + + The I<-import> option to L allows one to stack one + I object on top of another (which might be itself + stacked in turn and so on recursively, but this is beyond the + point). The effect, as briefly explained in L, is that the + fields appearing in the composite object will be a superposition of + those coming from the ``original'' one and the lines coming from the + file, the latter taking precedence. For example, let's say that + C<$master> and C were created like this: + + my $master = Config::IniFiles->new(-file => "master.ini"); + my $overlay = Config::IniFiles->new(-file => "overlay.ini", + -import => $master); + + If the contents of C and C are respectively + + ; master.ini + [section1] + arg0=unchanged from master.ini + arg1=val1 + + [section2] + arg2=val2 + + and + + ; overlay.ini + [section1] + arg1=overriden + + Then C<< $overlay->val("section1", "arg1") >> is "overriden", while + C<< $overlay->val("section1", "arg0") >> is "unchanged from + master.ini". + + This feature may be used to ship a ``global defaults'' configuration + file for a Perl application, that can be overridden piecewise by a + much shorter, per-site configuration file. Assuming UNIX-style path + names, this would be done like this: + + my $defaultconfig = Config::IniFiles->new + (-file => "/usr/share/myapp/myapp.ini.default"); + my $config = Config::IniFiles->new + (-file => "/etc/myapp.ini", -import => $defaultconfig); + # Now use $config and forget about $defaultconfig in the rest of + # the program + + Starting with version 2.39, I also provides features + to keep the importing / per-site configuration file small, by only + saving those options that were modified by the running program. That + is, if one calls + + $overlay->setval("section1", "arg1", "anotherval"); + $overlay->newval("section3", "arg3", "val3"); + $overlay->WriteConfig(-delta=>1); + + C would now contain + + ; overlay.ini + [section1] + arg1=anotherval + + [section3] + arg3=val3 + + This is called a I (see L). The untouched + [section2] and arg0 do not appear, and the config file is therefore + shorter; while of course, reloading the configuration into C<$master> + and C<$overlay>, either through C<< $overlay->ReadConfig() >> or through + the same code as above (e.g. when application restarts), would yield + exactly the same result had the overlay object been saved in whole to + the file system. + + The only problem with this delta technique is one cannot delete the + default values in the overlay configuration file, only change + them. This is solved by a file format extension, enabled by the + I<-negativedeltas> option to L: if, say, one would delete + parameters like this, + + $overlay->DeleteSection("section2"); + $overlay->delval("section1", "arg0"); + $overlay->WriteConfig(-delta=>1); + + The I file would now read: + + ; overlay.ini + [section1] + ; arg0 is deleted + arg1=anotherval + + ; [section2] is deleted + + [section3] + arg3=val3 + + Assuming C<$overlay> was later re-read with C<< -negativedeltas => 1 >>, + the parser would interpret the deletion comments to yield the correct + result, that is, [section2] and arg0 would cease to exist in the + C<$overlay> object. + + =cut + + + =head1 DIAGNOSTICS + + =head2 @Config::IniFiles::errors + + Contains a list of errors encountered while parsing the configuration + file. If the I method returns B, check the value of this + to find out what's wrong. This value is reset each time a config file + is read. + + =head1 BUGS + + =over 3 + + =item * + + The output from [Re]WriteConfig/OutputConfig might not be as pretty as + it can be. Comments are tied to whatever was immediately below them. + And case is not preserved for Section and Parameter names if the -nocase + option was used. + + =item * + + No locking is done by [Re]WriteConfig. When writing servers, take + care that only the parent ever calls this, and consider making your + own backup. + + =back + + =head1 Data Structure + + Note that this is only a reference for the package maintainers - one of the + upcoming revisions to this package will include a total clean up of the + data structure. + + $iniconf->{cf} = "config_file_name" + ->{startup_settings} = \%orginal_object_parameters + ->{firstload} = 0 OR 1 + ->{imported} = $object WHERE $object->isa("Config::IniFiles") + ->{nocase} = 0 + ->{reloadwarn} = 0 + ->{sects} = \@sections + ->{mysects} = \@sections + ->{sCMT}{$sect} = \@comment_lines + ->{group}{$group} = \@group_members + ->{parms}{$sect} = \@section_parms + ->{myparms}{$sect} = \@section_parms + ->{EOT}{$sect}{$parm} = "end of text string" + ->{pCMT}{$sect}{$parm} = \@comment_lines + ->{v}{$sect}{$parm} = $value OR \@values + + =head1 AUTHOR and ACKNOWLEDGEMENTS + + The original code was written by Scott Hutton. + Then handled for a time by Rich Bowen (thanks!), + It is now managed by Jeremy Wadsack, + with many contributions from various other people. + + In particular, special thanks go to (in roughly chronological order): + + Bernie Cosell, Alan Young, Alex Satrapa, Mike Blazer, Wilbert van de Pieterman, + Steve Campbell, Robert Konigsberg, Scott Dellinger, R. Bernstein, + Daniel Winkelmann, Pires Claudio, Adrian Phillips, + Marek Rouchal, Luc St Louis, Adam Fischler, Kay Röpke, Matt Wilson, + Raviraj Murdeshwar and Slaven Rezic, Florian Pfaff + + Geez, that's a lot of people. And apologies to the folks who were missed. + + If you want someone to bug about this, that would be: + + Jeremy Wadsack + + If you want more information, or want to participate, go to: + + http://sourceforge.net/projects/config-inifiles/ + + Please send bug reports to config-inifiles-bugs@lists.sourceforge.net + + Development discussion occurs on the mailing list + config-inifiles-dev@lists.sourceforge.net, which you can subscribe + to by going to the project web site (link above). + + This program is free software; you can redistribute it and/or + modify it under the same terms as Perl itself. + + =cut + + 1; + + # Please keep the following within the last four lines of the file + #[JW for editor]:mode=perl:tabSize=8:indentSize=2:noTabs=true:indentOnEnter=true: + +CONFIG_INIFILES + +$fatpacked{"Sys/Statistics/Linux.pm"} = <<'SYS_STATISTICS_LINUX'; + =head1 NAME + + Sys::Statistics::Linux - Front-end module to collect system statistics + + =head1 SYNOPSIS + + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new( + sysinfo => 1, + cpustats => 1, + procstats => 1, + memstats => 1, + pgswstats => 1, + netstats => 1, + sockstats => 1, + diskstats => 1, + diskusage => 1, + loadavg => 1, + filestats => 1, + processes => 1, + ); + + sleep 1; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux is a front-end module and gather different linux system information + like processor workload, memory usage, network and disk statistics and a lot more. Refer the + documentation of the distribution modules to get more information about all possible statistics. + + =head1 MOTIVATION + + My motivation is very simple... every linux administrator knows the well-known tool sar of sysstat. + It helps me a lot of time to search for system bottlenecks and to solve problems, but it's hard to + parse the output if you want to store the statistics into a database. So I thought to develope + Sys::Statistics::Linux. It's not a replacement but it should make it simpler to you to write your + own system monitor. + + If Sys::Statistics::Linux doesn't provide statistics that are strongly needed then let me know it. + + =head1 TECHNICAL NOTE + + This distribution collects statistics by the virtual F filesystem (procfs) and is + developed on the default vanilla kernel. It is tested on x86 hardware with the distributions + RHEL, Fedora, Debian, Ubuntu, Asianux, Slackware, Mandriva and openSuSE (SLES on zSeries as + well but a long time ago) on kernel versions 2.4 and/or 2.6. It's possible that it doesn't + run on all linux distributions if some procfs features are deactivated or too much modified. + As example the linux kernel 2.4 can compiled with the option C what turn + on or off block statistics for devices. + + Don't give up if some of the modules doesn't run on your hardware! Tell me what's wrong + and I will try to solve it! You just have to make the first move and to send me a mail. :-) + + =head1 VIRTUAL MACHINES + + Note that if you try to install or run C under virtual machines + on guest systems that some statistics are not available, such as C, C + and C. The reason is that not all /proc data are passed to the guests. + + If the installation fails then try to force the installation with + + cpan> force install Sys::Statistics::Linux + + and notice which tests fails, because this statistics maybe not available on the virtual machine - sorry. + + =head1 DELTAS + + The statistics for C, C, C, C, C and C + are deltas, for this reason it's necessary to initialize the statistics before the data can be + prepared by C. These statistics can be initialized with the methods C, C and + C. For any option that is set to 1, the statistics will be initialized by the call of + C or C. The call of init() re-initialize all statistics that are set to 1 or 2. + By the call of C the initial statistics will be updated automatically. Please refer the + section L to get more information about the usage of C, C, C + and C. + + Another exigence is to sleep for a while - at least for one second - before the call of C + if you want to get useful statistics. The statistics for C, C, C, + C, C and C are no deltas. If you need only one of these information + you don't need to sleep before the call of C. + + The method C prepares all requested statistics and returns the statistics as a + L object. The inital statistics will be updated. + + =head1 MANUAL PROC(5) + + The Linux Programmer's Manual + + http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html + + If you have questions or don't understand the sense of some statistics then take a look + into this awesome documentation. + + =head1 OPTIONS + + All options are identical with the package names of the distribution in lowercase. To activate + the gathering of statistics you have to set the options by the call of C or C. + In addition you can deactivate statistics with C. + + The options must be set with one of the following values: + + 0 - deactivate statistics + 1 - activate and init statistics + 2 - activate statistics but don't init + + In addition it's possible to pass a hash reference with options. + + my $lxs = Sys::Statistics::Linux->new( + processes => { + init => 1, + pids => [ 1, 2, 3 ] + }, + netstats => { + init => 1, + initfile => $file, + }, + ); + + Option C is useful if you want to store initial statistics on the filesystem. + + my $lxs = Sys::Statistics::Linux->new( + cpustats => { + init => 1, + initfile => '/tmp/cpustats.yml', + }, + diskstats => { + init => 1, + initfile => '/tmp/diskstats.yml', + }, + netstats => { + init => 1, + initfile => '/tmp/netstats.yml', + }, + pgswstats => { + init => 1, + initfile => '/tmp/pgswstats.yml', + }, + procstats => { + init => 1, + initfile => '/tmp/procstats.yml', + }, + ); + + Example: + + #!/usr/bin/perl + use strict; + use warnings; + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new( + pgswstats => { + init => 1, + initfile => '/tmp/pgswstats.yml' + } + ); + + $lxs->get(); # without to sleep + + The initial statistics are stored to the temporary file: + + #> cat /tmp/pgswstats.yml + --- + pgfault: 397040955 + pgmajfault: 4611 + pgpgin: 21531693 + pgpgout: 49511043 + pswpin: 8 + pswpout: 272 + time: 1236783534.9328 + + Every time you call the script the initial statistics are loaded/stored from/to the file. + This could be helpful if you doesn't run it as daemon and if you want to calculate the + average load of your system since the last call. Do you understand? I hope so :) + + To get more information about the statistics refer the different modules of the distribution. + + sysinfo - Collect system information with Sys::Statistics::Linux::SysInfo. + cpustats - Collect cpu statistics with Sys::Statistics::Linux::CpuStats. + procstats - Collect process statistics with Sys::Statistics::Linux::ProcStats. + memstats - Collect memory statistics with Sys::Statistics::Linux::MemStats. + pgswstats - Collect paging and swapping statistics with Sys::Statistics::Linux::PgSwStats. + netstats - Collect net statistics with Sys::Statistics::Linux::NetStats. + sockstats - Collect socket statistics with Sys::Statistics::Linux::SockStats. + diskstats - Collect disk statistics with Sys::Statistics::Linux::DiskStats. + diskusage - Collect the disk usage with Sys::Statistics::Linux::DiskUsage. + loadavg - Collect the load average with Sys::Statistics::Linux::LoadAVG. + filestats - Collect inode statistics with Sys::Statistics::Linux::FileStats. + processes - Collect process statistics with Sys::Statistics::Linux::Processes. + + =head1 METHODS + + =head2 new() + + Call C to create a new Sys::Statistics::Linux object. You can call C with options. + This options would be passed to the method C. + + Without options + + my $lxs = Sys::Statistics::Linux->new(); + + Or with options + + my $lxs = Sys::Statistics::Linux->new( cpustats => 1 ); + + Would do nothing + + my $lxs = Sys::Statistics::Linux->new( cpustats => 0 ); + + It's possible to call C with a hash reference of options. + + my %options = ( + cpustats => 1, + memstats => 1 + ); + + my $lxs = Sys::Statistics::Linux->new(\%options); + + =head2 set() + + Call C to activate or deactivate options. + + The following example would call C and initialize C + and delete the object of C. + + $lxs->set( + processes => 0, # deactivate this statistic + pgswstats => 1, # activate the statistic and calls new() and init() if necessary + netstats => 2, # activate the statistic and call new() if necessary but not init() + ); + + It's possible to call C with a hash reference of options. + + my %options = ( + cpustats => 2, + memstats => 2 + ); + + $lxs->set(\%options); + + =head2 get() + + Call C to get the collected statistics. C returns a L + object. + + my $lxs = Sys::Statistics::Linux->new(\%options); + sleep(1); + my $stat = $lxs->get(); + + Or you can pass the time to sleep with the call of C. + + my $stat = $lxs->get($time_to_sleep); + + Now the statistcs are available with + + $stat->cpustats + + # or + + $stat->{cpustats} + + Take a look to the documentation of L for more information. + + =head2 init() + + The call of C initiate all activated statistics that are necessary for deltas. That could + be helpful if your script runs in a endless loop with a high sleep interval. Don't forget that if + you call C that the statistics are deltas since the last time they were initiated. + + The following example would calculate average statistics for 30 minutes: + + # initiate cpustats + my $lxs = Sys::Statistics::Linux->new( cpustats => 1 ); + + while ( 1 ) { + sleep(1800); + my $stat = $lxs->get; + } + + If you just want a current snapshot of the system each 30 minutes and not the average + then the following example would be better for you: + + # do not initiate cpustats + my $lxs = Sys::Statistics::Linux->new( cpustats => 2 ); + + while ( 1 ) { + $lxs->init; # init the statistics + my $stat = $lxs->get(1); # get the statistics + sleep(1800); # sleep until the next run + } + + If you want to write a simple command line utility that prints the current workload + to the screen then you can use something like this: + + my @order = qw(user system iowait idle nice irq softirq total); + printf "%-20s%8s%8s%8s%8s%8s%8s%8s%8s\n", 'time', @order; + + my $lxs = Sys::Statistics::Linux->new( cpustats => 1 ); + + while ( 1 ){ + my $cpu = $lxs->get(1)->cpustats; + my $time = $lxs->gettime; + printf "%-20s%8s%8s%8s%8s%8s%8s%8s%8s\n", + $time, @{$cpu->{cpu}}{@order}; + } + + =head2 settime() + + Call C to define a POSIX formatted time stamp, generated with localtime(). + + $lxs->settime('%Y/%m/%d %H:%M:%S'); + + To get more information about the formats take a look at C of POSIX.pm + or the manpage C. + + =head2 gettime() + + C returns a POSIX formatted time stamp, @foo in list and $bar in scalar context. + If the time format isn't set then the default format "%Y-%m-%d %H:%M:%S" will be set + automatically. You can also set a time format with C. + + my $date_time = $lxs->gettime; + + Or + + my ($date, $time) = $lxs->gettime(); + + Or + + my ($date, $time) = $lxs->gettime('%Y/%m/%d %H:%M:%S'); + + =head1 EXAMPLES + + A very simple perl script could looks like this: + + use strict; + use warnings; + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new( cpustats => 1 ); + sleep(1); + my $stat = $lxs->get; + my $cpu = $stat->cpustats->{cpu}; + + print "Statistics for CpuStats (all)\n"; + print " user $cpu->{user}\n"; + print " nice $cpu->{nice}\n"; + print " system $cpu->{system}\n"; + print " idle $cpu->{idle}\n"; + print " ioWait $cpu->{iowait}\n"; + print " total $cpu->{total}\n"; + + Set and get a time stamp: + + use strict; + use warnings; + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new(); + $lxs->settime('%Y/%m/%d %H:%M:%S'); + print $lxs->gettime, "\n"; + + If you want to know how the data structure looks like you can use C to check it: + + use strict; + use warnings; + use Sys::Statistics::Linux; + use Data::Dumper; + + my $lxs = Sys::Statistics::Linux->new( cpustats => 1 ); + sleep(1); + my $stat = $lxs->get; + + print Dumper($stat); + + How to get the top 5 processes with the highest cpu workload: + + use strict; + use warnings; + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new( processes => 1 ); + sleep(1); + my $stat = $lxs->get; + my @top5 = $stat->pstop( ttime => 5 ); + + =head1 BACKWARD COMPATIBILITY + + The old options and keys - CpuStats, NetStats, etc - are still available but deprecated! + It's not possible to access the statistics via L and it's + not possible to call C and C if you use the old options. + + You should use the new options and access the statistics over the accessors + + $stats->cpustats + + or directly with + + $stats->{cpustats} + + =head1 PREREQUISITES + + Carp + POSIX + Test::More + Time::HiRes + UNIVERSAL + + =head1 EXPORTS + + No exports. + + =head1 TODOS + + * Are there any wishs from your side? Send me a mail! + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (C) 2006-2008 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux; + our $VERSION = '0.66'; + + use strict; + use warnings; + use Carp qw(croak); + use POSIX qw(strftime); + use UNIVERSAL; + use Sys::Statistics::Linux::Compilation; + + sub new { + my $class = shift; + my $self = bless { obj => { } }, $class; + + my @options = qw( + SysInfo CpuStats ProcStats + MemStats PgSwStats NetStats + SockStats DiskStats DiskUsage + LoadAVG FileStats Processes + ); + + foreach my $opt (@options) { + # backward compatibility + $self->{opts}->{$opt} = 0; + $self->{maps}->{$opt} = $opt; + # new style + my $lcopt = lc($opt); + $self->{opts}->{$lcopt} = 0; + $self->{maps}->{$lcopt} = $opt; + } + + $self->set(@_) if @_; + return $self; + } + + sub set { + my $self = shift; + my $class = ref $self; + my $args = ref($_[0]) eq 'HASH' ? shift : {@_}; + my $opts = $self->{opts}; + my $obj = $self->{obj}; + my $maps = $self->{maps}; + my $pids = (); + + foreach my $opt (keys %$args) { + if (!exists $opts->{$opt}) { + croak "$class: invalid option '$opt'"; + } + + if (ref($args->{$opt})) { + $opts->{$opt} = delete $args->{$opt}->{init} || 1; + } elsif ($args->{$opt} !~ qr/^[012]\z/) { + croak "$class: invalid value for '$opt'"; + } else { + $opts->{$opt} = $args->{$opt}; + } + + if ($opts->{$opt}) { + my $package = $class.'::'.$maps->{$opt}; + + # require module - require know which modules are loaded + # and doesn't load a module twice. + my $require = $package; + $require =~ s/::/\//g; + $require .= '.pm'; + require $require; + + if (!$obj->{$opt}) { + if (ref($args->{$opt})) { + $obj->{$opt} = $package->new(%{$args->{$opt}}); + } else { + $obj->{$opt} = $package->new(); + } + } + + # get initial statistics if the function init() exists + # and the option is set to 1 + if ($opts->{$opt} == 1 && UNIVERSAL::can($package, 'init')) { + $obj->{$opt}->init(); + } + + } elsif (exists $obj->{$opt}) { + delete $obj->{$opt}; + } + } + } + + sub init { + my $self = shift; + my $class = ref $self; + my $maps = $self->{maps}; + + foreach my $opt (keys %{$self->{opts}}) { + if ($self->{opts}->{$opt} > 0 && UNIVERSAL::can(ref($self->{obj}->{$opt}), 'init')) { + $self->{obj}->{$opt}->init(); + } + } + } + + sub get { + my ($self, $time) = @_; + sleep $time if $time; + my %stat = (); + + foreach my $opt (keys %{$self->{opts}}) { + if ($self->{opts}->{$opt}) { + $stat{$opt} = $self->{obj}->{$opt}->get(); + if ($opt eq 'netstats') { + $stat{netinfo} = $self->{obj}->{$opt}->get_raw(); + } + } + } + + return Sys::Statistics::Linux::Compilation->new(\%stat); + } + + sub settime { + my $self = shift; + my $format = @_ ? shift : '%Y-%m-%d %H:%M:%S'; + $self->{timeformat} = $format; + } + + sub gettime { + my $self = shift; + $self->settime(@_) unless $self->{timeformat}; + my $tm = strftime($self->{timeformat}, localtime); + return wantarray ? split /\s+/, $tm : $tm; + } + + 1; +SYS_STATISTICS_LINUX + +$fatpacked{"Sys/Statistics/Linux/Compilation.pm"} = <<'SYS_STATISTICS_LINUX_COMPILATION'; + =head1 NAME + + Sys::Statistics::Linux::Compilation - Statistics compilation. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux; + + my $lxs = Sys::Statistics::Linux->new( loadavg => 1 ); + my $stat = $lxs->get; + + foreach my $key ($stat->loadavg) { + print $key, " ", $stat->loadavg($key), "\n"; + } + + # or + + use Sys::Statistics::Linux::LoadAVG; + use Sys::Statistics::Linux::Compilation; + + my $lxs = Sys::Statistics::Linux::LoadAVG->new(); + my $load = $lxs->get; + my $stat = Sys::Statistics::Linux::Compilation->new({ loadavg => $load }); + + foreach my $key ($stat->loadavg) { + print $key, " ", $stat->loadavg($key), "\n"; + } + + # or + + foreach my $key ($stat->loadavg) { + print $key, " ", $stat->loadavg->{$key}, "\n"; + } + + =head1 DESCRIPTION + + This module provides different methods to access and filter the statistics compilation. + + =head1 METHODS + + =head2 new() + + Create a new C object. This creator is only useful if you + don't call C of C. You can create a new object with: + + my $lxs = Sys::Statistics::Linux::LoadAVG->new(); + my $load = $lxs->get; + my $stat = Sys::Statistics::Linux::Compilation->new({ loadavg => $load }); + + =head2 Statistic methods + + =over 4 + + =item sysinfo() + + =item cpustats() + + =item procstats() + + =item memstats() + + =item pgswstats() + + =item netstats() + + =item netinfo() + + C provides raw data - no deltas. + + =item sockstats() + + =item diskstats() + + =item diskusage() + + =item loadavg() + + =item filestats() + + =item processes() + + =back + + All methods returns the statistics as a hash reference in scalar context. In list all methods + returns the first level keys of the statistics. Example: + + my $net = $stat->netstats; # netstats as a hash reference + my @dev = $stat->netstats; # the devices eth0, eth1, ... + my $eth0 = $stat->netstats('eth0'); # eth0 statistics as a hash reference + my @keys = $stat->netstats('eth0'); # the statistic keys + my @vals = $stat->netstats('eth0', @keys); # the values for the passed device and @keys + my $val = $stat->netstats('eth0', $key); # the value for the passed device and key + + Sorted ... + + my @dev = sort $stat->netstats; + my @keys = sort $stat->netstats('eth0'); + + =head2 pstop() + + This method is looking for top processes and returns a sorted list of PIDs as an array or + array reference depending on the context. It expected two values: a key name and the number + of top processes to return. + + As example you want to get the top 5 processes with the highest cpu usage: + + my @top5 = $stat->pstop( ttime => 5 ); + # or as a reference + my $top5 = $stat->pstop( ttime => 5 ); + + If you want to get all processes: + + my @top_all = $stat->pstop( ttime => $FALSE ); + # or just + my @top_all = $stat->pstop( 'ttime' ); + + =head2 search(), psfind() + + Both methods provides a simple scan engine to find special statistics. Both methods except a filter + as a hash reference. It's possible to pass the statistics as second argument if the data is not stored + in the object. + + The method C scans for statistics and rebuilds the hash tree until that keys that matched + your filter and returns the hits as a hash reference. + + my $hits = $stat->search({ + processes => { + cmd => qr/\[su\]/, + owner => qr/root/ + }, + cpustats => { + idle => 'lt:10', + iowait => 'gt:10' + }, + diskusage => { + '/dev/sda1' => { + usageper => 'gt:80' + } + } + }); + + This would return the following matches: + + * processes with the command "[su]" + * processes with the owner "root" + * all cpu where "idle" is less than 50 + * all cpu where "iowait" is grather than 10 + * only disk '/dev/sda1' if "usageper" is grather than 80 + + The method C scans for processes only and returns a array reference with all process + IDs that matched the filter. Example: + + my $pids = $stat->psfind({ cmd => qr/init/, owner => 'eq:apache' }); + + This would return the following process ids: + + * processes that matched the command "init" + * processes with the owner "apache" + + There are different match operators available: + + gt - grather than + lt - less than + eq - is equal + ne - is not equal + + Notation examples: + + gt:50 + lt:50 + eq:50 + ne:50 + + Both argumnents have to be set as a hash reference. + + Note: the operators < > = ! are not available any more. It's possible that in further releases + could be different changes for C and C. So please take a look to the + documentation if you use it. + + =head1 EXPORTS + + No exports. + + =head1 TODOS + + * Are there any wishs from your side? Send me a mail! + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + Thanks to Moritz Lenz for his suggestion for the name of this module. + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::Compilation; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.10'; + + # Creating the statistics accessors + BEGIN { + foreach my $stat (qw/sysinfo procstats memstats sockstats loadavg filestats/) { + no strict 'refs'; + *{$stat} = sub { + use strict 'refs'; + my ($self, @keys) = @_; + return () unless $self->{$stat}; + if (@keys) { + return @{$self->{$stat}}{@keys}; + } + return wantarray ? keys %{$self->{$stat}} : $self->{$stat}; + }; + } + foreach my $stat (qw/cpustats pgswstats netstats netinfo diskstats diskusage processes/) { + no strict 'refs'; + *{$stat} = sub { + use strict 'refs'; + my ($self, $sub, @keys) = @_; + return () unless $self->{$stat}; + if ($sub) { + my $ref = $self->{$stat}; + return () unless exists $ref->{$sub}; + if (@keys) { + return @{$ref->{$sub}}{@keys}; + } else { + return wantarray ? keys %{$ref->{$sub}} : $ref->{$sub}; + } + } + return wantarray ? keys %{$self->{$stat}} : $self->{$stat}; + }; + } + } + + sub new { + my ($class, $stats) = @_; + unless (ref($stats) eq 'HASH') { + croak 'Usage: $class->new( \%statistics )'; + } + return bless $stats, $class; + } + + sub search { + my $self = shift; + my $filter = ref($_[0]) eq 'HASH' ? shift : {@_}; + my $class = ref($self); + my %hits = (); + + foreach my $opt (keys %{$filter}) { + + unless (ref($filter->{$opt}) eq 'HASH') { + croak "$class: not a hash ref opt '$opt'"; + } + + # next if the object isn't loaded + next unless exists $self->{$opt}; + my $fref = $filter->{$opt}; + my $proc = $self->{$opt}; + my $subref; + + # we search for matches for each key that is defined + # in %filter and rebuild the tree until that key that + # matched the searched string + + foreach my $x (keys %{$fref}) { + if (ref($fref->{$x}) eq 'HASH') { + # if the key $proc->{eth0} doesn't exists + # then we continue with the next defined filter + next unless exists $proc->{$x}; + $subref = $proc->{$x}; + + while ( my ($name, $value) = each %{$fref->{$x}} ) { + if (exists $subref->{$name} && $self->_compare($subref->{$name}, $value)) { + $hits{$opt}{$x}{$name} = $subref->{$name}; + } + } + } else { + foreach my $key (keys %{$proc}) { + if (ref($proc->{$key}) eq 'HASH') { + $subref = $proc->{$key}; + if (ref $subref->{$x} eq 'HASH') { + foreach my $y (keys %{$subref->{$x}}) { + if ($self->_compare($subref->{$x}->{$y}, $fref->{$x})) { + $hits{$opt}{$key}{$x}{$y} = $subref->{$x}->{$y}; + } + } + } elsif (defined $subref->{$x} && $self->_compare($subref->{$x}, $fref->{$x})) { + $hits{$opt}{$key}{$x} = $subref->{$x}; + } + } else { # must be a scalar now + if (defined $proc->{$x} && $self->_compare($proc->{$x}, $fref->{$x})) { + $hits{$opt}{$x} = $proc->{$x} + } + last; + } + } + } + } + } + + return wantarray ? %hits : \%hits; + } + + sub psfind { + my $self = shift; + my $filter = ref($_[0]) eq 'HASH' ? shift : {@_}; + my $proc = $self->{processes} or return undef; + my @hits = (); + + PID: foreach my $pid (keys %{$proc}) { + my $proc = $proc->{$pid}; + while ( my ($key, $value) = each %{$filter} ) { + if (exists $proc->{$key}) { + if (ref $proc->{$key} eq 'HASH') { + foreach my $v (values %{$proc->{$key}}) { + if ($self->_compare($v, $value)) { + push @hits, $pid; + next PID; + } + } + } elsif ($self->_compare($proc->{$key}, $value)) { + push @hits, $pid; + next PID; + } + } + } + } + + return wantarray ? @hits : \@hits; + } + + sub pstop { + my ($self, $key, $count) = @_; + unless ($key) { + croak 'Usage: pstop( $key => $count )'; + } + my $proc = $self->{processes}; + my @top = ( + map { $_->[0] } + reverse sort { $a->[1] <=> $b->[1] } + map { [ $_, $proc->{$_}->{$key} ] } keys %{$proc} + ); + if ($count) { + @top = @top[0..--$count]; + } + return wantarray ? @top : \@top; + } + + # + # private stuff + # + + sub _compare { + my ($self, $x, $y) = @_; + + if (ref($y) eq 'Regexp') { + return $x =~ $y; + } elsif ($y =~ s/^eq://) { + return $x eq $y; + } elsif ($y =~ s/^ne://) { + return $x ne $y; + } elsif ($y =~ s/^gt://) { + return $x > $y; + } elsif ($y =~ s/^lt://) { + return $x < $y; + } else { + croak ref($self).": bad search() / psfind() operator '$y'"; + } + + return undef; + } + + 1; +SYS_STATISTICS_LINUX_COMPILATION + +$fatpacked{"Sys/Statistics/Linux/CpuStats.pm"} = <<'SYS_STATISTICS_LINUX_CPUSTATS'; + =head1 NAME + + Sys::Statistics::Linux::CpuStats - Collect linux cpu statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::CpuStats; + + my $lxs = Sys::Statistics::Linux::CpuStats->new; + $lxs->init; + sleep 1; + my $stats = $lxs->get; + + Or + + my $lxs = Sys::Statistics::Linux::CpuStats->new(initfile => $file); + $lxs->init; + my $stats = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::CpuStats gathers cpu statistics from the virtual + F filesystem (procfs). + + For more information read the documentation of the front-end module + L. + + =head1 CPU STATISTICS + + Generated by F for each cpu (cpu0, cpu1 ...). F without + a number is the summary. + + user - Percentage of CPU utilization at the user level. + nice - Percentage of CPU utilization at the user level with nice priority. + system - Percentage of CPU utilization at the system level. + idle - Percentage of time the CPU is in idle state. + total - Total percentage of CPU utilization. + + Statistics with kernels >= 2.6. + + iowait - Percentage of time the CPU is in idle state because an I/O operation + is waiting to complete. + irq - Percentage of time the CPU is servicing interrupts. + softirq - Percentage of time the CPU is servicing softirqs. + steal - Percentage of stolen CPU time, which is the time spent in other + operating systems when running in a virtualized environment (>=2.6.11). + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::CpuStats->new; + + Maybe you want to store/load the initial statistics to/from a file: + + my $lxs = Sys::Statistics::Linux::CpuStats->new(initfile => '/tmp/cpustats.yml'); + + If you set C it's not necessary to call sleep before C. + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::CpuStats->new( + files => { + # This is the default + path => '/proc' + stat => 'stat', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stats = $lxs->get; + + =head2 raw() + + Get raw values. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::CpuStats; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.20'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + stat => 'stat', + } + ); + + if (defined $opts->{initfile}) { + require YAML::Syck; + $self{initfile} = $opts->{initfile}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub raw { + my $self = shift; + my $stat = $self->_load; + return $stat; + } + + sub init { + my $self = shift; + + if ($self->{initfile} && -r $self->{initfile}) { + $self->{init} = YAML::Syck::LoadFile($self->{initfile}); + } else { + $self->{init} = $self->_load; + } + } + + sub get { + my $self = shift; + my $class = ref $self; + + if (!exists $self->{init}) { + croak "$class: there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + + if ($self->{initfile}) { + YAML::Syck::DumpFile($self->{initfile}, $self->{init}); + } + + return $self->{stats}; + } + + # + # private stuff + # + + sub _load { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my (%stats, $iowait, $irq, $softirq, $steal); + + my $filename = $file->{path} ? "$file->{path}/$file->{stat}" : $file->{stat}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /^(cpu.*?)\s+(.*)$/) { + my $cpu = \%{$stats{$1}}; + (@{$cpu}{qw(user nice system idle)}, + $iowait, $irq, $softirq, $steal) = split /\s+/, $2; + # iowait, irq and softirq are only set + # by kernel versions higher than 2.4. + # steal is available since 2.6.11. + $cpu->{iowait} = $iowait if defined $iowait; + $cpu->{irq} = $irq if defined $irq; + $cpu->{softirq} = $softirq if defined $softirq; + $cpu->{steal} = $steal if defined $steal; + } + } + + close($fh); + return \%stats; + } + + sub _deltas { + my $self = shift; + my $class = ref $self; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + + foreach my $cpu (keys %{$lstat}) { + my $icpu = $istat->{$cpu}; + my $dcpu = $lstat->{$cpu}; + my $uptime; + + while (my ($k, $v) = each %{$dcpu}) { + if (!defined $icpu->{$k}) { + croak "$class: not defined key found '$k'"; + } + + if ($v !~ /^\d+\z/ || $dcpu->{$k} !~ /^\d+\z/) { + croak "$class: invalid value for key '$k'"; + } + + $dcpu->{$k} -= $icpu->{$k}; + $icpu->{$k} = $v; + $uptime += $dcpu->{$k}; + } + + foreach my $k (keys %{$dcpu}) { + if ($dcpu->{$k} > 0) { + $dcpu->{$k} = sprintf('%.2f', 100 * $dcpu->{$k} / $uptime); + } elsif ($dcpu->{$k} < 0) { + $dcpu->{$k} = sprintf('%.2f', 0); + } else { + $dcpu->{$k} = sprintf('%.2f', $dcpu->{$k}); + } + } + + $dcpu->{total} = sprintf('%.2f', 100 - $dcpu->{idle}); + } + } + + 1; +SYS_STATISTICS_LINUX_CPUSTATS + +$fatpacked{"Sys/Statistics/Linux/DiskStats.pm"} = <<'SYS_STATISTICS_LINUX_DISKSTATS'; + =head1 NAME + + Sys::Statistics::Linux::DiskStats - Collect linux disk statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::DiskStats; + + my $lxs = Sys::Statistics::Linux::DiskStats->new; + $lxs->init; + sleep 1; + my $stat = $lxs->get; + + Or + + my $lxs = Sys::Statistics::Linux::DiskStats->new(initfile => $file); + $lxs->init; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::DiskStats gathers disk statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 DISK STATISTICS + + Generated by F or F. + + major - The mayor number of the disk + minor - The minor number of the disk + rdreq - Number of read requests that were made to physical disk per second. + rdbyt - Number of bytes that were read from physical disk per second. + wrtreq - Number of write requests that were made to physical disk per second. + wrtbyt - Number of bytes that were written to physical disk per second. + ttreq - Total number of requests were made from/to physical disk per second. + ttbyt - Total number of bytes transmitted from/to physical disk per second. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::DiskStats->new; + + Maybe you want to store/load the initial statistics to/from a file: + + my $lxs = Sys::Statistics::Linux::DiskStats->new(initfile => '/tmp/diskstats.yml'); + + If you set C it's not necessary to call sleep before C. + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::DiskStats->new( + files => { + # This is the default + path => '/proc', + diskstats => 'diskstats', + partitions => 'partitions', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head2 raw() + + Get raw values. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::DiskStats; + + use strict; + use warnings; + use Carp qw(croak); + use Time::HiRes; + + our $VERSION = '0.24'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + diskstats => 'diskstats', + partitions => 'partitions', + }, + # -------------------------------------------------------------- + # The sectors are equivalent with blocks and have a size of 512 + # bytes since 2.4 kernels. This value is needed to calculate the + # amount of disk i/o's in bytes. + # -------------------------------------------------------------- + blocksize => 512, + ); + + if (defined $opts->{initfile}) { + require YAML::Syck; + $self{initfile} = $opts->{initfile}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + if ($opts->{blocksize}) { + $self{blocksize} = $opts->{blocksize}; + } + + return bless \%self, $class; + } + + sub init { + my $self = shift; + + if ($self->{initfile} && -r $self->{initfile}) { + $self->{init} = YAML::Syck::LoadFile($self->{initfile}); + $self->{time} = delete $self->{init}->{time}; + } else { + $self->{time} = Time::HiRes::gettimeofday(); + $self->{init} = $self->_load; + } + } + + sub get { + my $self = shift; + my $class = ref $self; + + if (!exists $self->{init}) { + croak "$class: there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + + if ($self->{initfile}) { + $self->{init}->{time} = $self->{time}; + YAML::Syck::DumpFile($self->{initfile}, $self->{init}); + } + + return $self->{stats}; + } + + sub raw { + my $self = shift; + my $raw = $self->_load; + + return $raw; + } + + # + # private stuff + # + + sub _load { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $bksz = $self->{blocksize}; + my (%stats, $fh); + + # ----------------------------------------------------------------------------- + # one of the both must be opened for the disk statistics! + # if diskstats (2.6) doesn't exists then let's try to read + # the partitions (2.4) + # + # /usr/src/linux/Documentation/iostat.txt shortcut + # + # ... the statistics fields are those after the device name. + # + # Field 1 -- # of reads issued + # This is the total number of reads completed successfully. + # Field 2 -- # of reads merged, field 6 -- # of writes merged + # Reads and writes which are adjacent to each other may be merged for + # efficiency. Thus two 4K reads may become one 8K read before it is + # ultimately handed to the disk, and so it will be counted (and queued) + # as only one I/O. This field lets you know how often this was done. + # Field 3 -- # of sectors read + # This is the total number of sectors read successfully. + # Field 4 -- # of milliseconds spent reading + # This is the total number of milliseconds spent by all reads (as + # measured from __make_request() to end_that_request_last()). + # Field 5 -- # of writes completed + # This is the total number of writes completed successfully. + # Field 7 -- # of sectors written + # This is the total number of sectors written successfully. + # Field 8 -- # of milliseconds spent writing + # This is the total number of milliseconds spent by all writes (as + # measured from __make_request() to end_that_request_last()). + # Field 9 -- # of I/Os currently in progress + # The only field that should go to zero. Incremented as requests are + # given to appropriate request_queue_t and decremented as they finish. + # Field 10 -- # of milliseconds spent doing I/Os + # This field is increases so long as field 9 is nonzero. + # Field 11 -- weighted # of milliseconds spent doing I/Os + # This field is incremented at each I/O start, I/O completion, I/O + # merge, or read of these stats by the number of I/Os in progress + # (field 9) times the number of milliseconds spent doing I/O since the + # last update of this field. This can provide an easy measure of both + # I/O completion time and the backlog that may be accumulating. + # ----------------------------------------------------------------------------- + + my $file_diskstats = $file->{path} ? "$file->{path}/$file->{diskstats}" : $file->{diskstats}; + my $file_partitions = $file->{path} ? "$file->{path}/$file->{partitions}" : $file->{partitions}; + + if (open $fh, '<', $file_diskstats) { + while (my $line = <$fh>) { + # -- -- -- F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 + # $1 $2 $3 $4 -- $5 -- $6 -- $7 -- -- -- -- + if ($line =~ /^\s+(\d+)\s+(\d+)\s+(.+?)\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+$/) { + for my $x ($stats{$3}) { # $3 -> the device name + $x->{major} = $1; + $x->{minor} = $2; + $x->{rdreq} = $4; # Field 1 + $x->{rdbyt} = $5 * $bksz; # Field 3 + $x->{wrtreq} = $6; # Field 5 + $x->{wrtbyt} = $7 * $bksz; # Field 7 + $x->{ttreq} += $x->{rdreq} + $x->{wrtreq}; + $x->{ttbyt} += $x->{rdbyt} + $x->{wrtbyt}; + } + } + + # ----------------------------------------------------------------------------- + # Field 1 -- # of reads issued + # This is the total number of reads issued to this partition. + # Field 2 -- # of sectors read + # This is the total number of sectors requested to be read from this + # partition. + # Field 3 -- # of writes issued + # This is the total number of writes issued to this partition. + # Field 4 -- # of sectors written + # This is the total number of sectors requested to be written to + # this partition. + # ----------------------------------------------------------------------------- + # -- -- -- F1 F2 F3 F4 + # $1 $2 $3 $4 $5 $6 $7 + elsif ($line =~ /^\s+(\d+)\s+(\d+)\s+(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$/) { + for my $x ($stats{$3}) { # $3 -> the device name + $x->{major} = $1; + $x->{minor} = $2; + $x->{rdreq} = $4; # Field 1 + $x->{rdbyt} = $5 * $bksz; # Field 2 + $x->{wrtreq} = $6; # Field 3 + $x->{wrtbyt} = $7 * $bksz; # Field 4 + $x->{ttreq} += $x->{rdreq} + $x->{wrtreq}; + $x->{ttbyt} += $x->{rdbyt} + $x->{wrtbyt}; + } + } + } + close($fh); + } elsif (open $fh, '<', $file_partitions) { + while (my $line = <$fh>) { + # -- -- -- -- F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 + # $1 $2 -- $3 $4 -- $5 -- $6 -- $7 -- -- -- -- + next unless $line =~ /^\s+(\d+)\s+(\d+)\s+\d+\s+(.+?)\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+$/; + for my $x ($stats{$3}) { # $3 -> the device name + $x->{major} = $1; + $x->{minor} = $2; + $x->{rdreq} = $4; # Field 1 + $x->{rdbyt} = $5 * $bksz; # Field 3 + $x->{wrtreq} = $6; # Field 5 + $x->{wrtbyt} = $7 * $bksz; # Field 7 + $x->{ttreq} += $x->{rdreq} + $x->{wrtreq}; + $x->{ttbyt} += $x->{rdbyt} + $x->{wrtbyt}; + } + } + close($fh); + } else { + croak "$class: unable to open $file_diskstats or $file_partitions ($!)"; + } + + if (!-e $file_diskstats || !scalar %stats) { + croak "$class: no diskstats found! your system seems not to be compiled with CONFIG_BLK_STATS=y"; + } + + return \%stats; + } + + sub _deltas { + my $self = shift; + my $class = ref $self; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + my $time = Time::HiRes::gettimeofday(); + my $delta = sprintf('%.2f', $time - $self->{time}); + $self->{time} = $time; + + foreach my $dev (keys %{$lstat}) { + if (!exists $istat->{$dev}) { + delete $lstat->{$dev}; + next; + } + + my $idev = $istat->{$dev}; + my $ldev = $lstat->{$dev}; + + while (my ($k, $v) = each %{$ldev}) { + next if $k =~ /^major\z|^minor\z/; + + if (!defined $idev->{$k}) { + croak "$class: not defined key found '$k'"; + } + + if ($v !~ /^\d+\z/ || $ldev->{$k} !~ /^\d+\z/) { + croak "$class: invalid value for key '$k'"; + } + + if ($ldev->{$k} == $idev->{$k} || $idev->{$k} > $ldev->{$k}) { + $ldev->{$k} = sprintf('%.2f', 0); + } elsif ($delta > 0) { + $ldev->{$k} = sprintf('%.2f', ($ldev->{$k} - $idev->{$k}) / $delta); + } else { + $ldev->{$k} = sprintf('%.2f', $ldev->{$k} - $idev->{$k}); + } + + $idev->{$k} = $v; + } + } + } + + 1; +SYS_STATISTICS_LINUX_DISKSTATS + +$fatpacked{"Sys/Statistics/Linux/DiskUsage.pm"} = <<'SYS_STATISTICS_LINUX_DISKUSAGE'; + =head1 NAME + + Sys::Statistics::Linux::DiskUsage - Collect linux disk usage. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::DiskUsage; + + my $lxs = new Sys::Statistics::Linux::DiskUsage; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::DiskUsage gathers the disk usage with the command C. + + For more information read the documentation of the front-end module L. + + =head1 DISK USAGE INFORMATIONS + + Generated by F. + + total - The total size of the disk. + usage - The used disk space in kilobytes. + free - The free disk space in kilobytes. + usageper - The used disk space in percent. + mountpoint - The moint point of the disk. + + =head2 GLOBAL VARS + + If you want to change the path or arguments for C you can use the following + variables... + + $Sys::Statistics::Linux::DiskUsage::DF_PATH = '/bin'; + $Sys::Statistics::Linux::DiskUsage::DF_CMD = 'df -akP'; + + Example: + + use Sys::Statistics::Linux; + use Sys::Statistics::Linux::DiskUsage; + $Sys::Statistics::Linux::DiskUsage::DF_CMD = 'df -akP'; + + my $sys = Sys::Statistics::Linux->new(diskusage => 1); + my $disk = $sys->get; + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::DiskUsage->new; + + It's possible to set the path to df. + + Sys::Statistics::Linux::DiskUsage->new( + cmd => { + # This is the default + path => '/bin', + df => 'df -kP 2>/dev/null', + } + ); + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::DiskUsage; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.14'; + our $DF_PATH = undef; + our $DF_CMD = undef; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + cmd => { + path => '/bin', + df => 'df -kP 2>/dev/null', + } + ); + + foreach my $p (keys %{ $opts->{cmd} }) { + $self{cmd}{$p} = $opts->{cmd}->{$p}; + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref $self; + my $cmd = $self->{cmd}; + my $df_cmd = $DF_CMD || $cmd->{df}; + my (%disk_usage); + + local $ENV{PATH} = $DF_PATH || $cmd->{path}; + open my $fh, "$df_cmd|" or croak "$class: unable to execute '$df_cmd' ($!)"; + + # filter the header + {my $null = <$fh>;} + + while (my $line = <$fh>) { + next unless $line =~ /^(.+?)\s+(.+)$/; + + @{$disk_usage{$1}}{qw( + total + usage + free + usageper + mountpoint + )} = (split /\s+/, $2)[0..4]; + + $disk_usage{$1}{usageper} =~ s/%//; + } + + close($fh); + return \%disk_usage; + } + + 1; +SYS_STATISTICS_LINUX_DISKUSAGE + +$fatpacked{"Sys/Statistics/Linux/FileStats.pm"} = <<'SYS_STATISTICS_LINUX_FILESTATS'; + =head1 NAME + + Sys::Statistics::Linux::FileStats - Collect linux file statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::FileStats; + + my $lxs = Sys::Statistics::Linux::FileStats->new; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::FileStats gathers file statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 FILE STATISTICS + + Generated by F, F and F. + + fhalloc - Number of allocated file handles. + fhfree - Number of free file handles. + fhmax - Number of maximum file handles. + inalloc - Number of allocated inodes. + infree - Number of free inodes. + inmax - Number of maximum inodes. + dentries - Dirty directory cache entries. + unused - Free diretory cache size. + agelimit - Time in seconds the dirty cache entries can be reclaimed. + wantpages - Pages that are requested by the system when memory is short. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::FileStats->new; + + It's possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::FileStats->new( + files => { + # This is the default + path => '/proc', + file_nr => 'sys/fs/file-nr', + inode_nr => 'sys/fs/inode-nr', + dentries => 'sys/fs/dentry-state', + } + ); + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::FileStats; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.09'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + file_nr => 'sys/fs/file-nr', + inode_nr => 'sys/fs/inode-nr', + dentries => 'sys/fs/dentry-state', + } + ); + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $stats = { }; + + $self->{stats} = $stats; + $self->_get_file_nr; + $self->_get_inode_nr; + $self->_get_dentries; + + return $stats; + } + + sub _get_file_nr { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $stats = $self->{stats}; + + my $filename = $file->{path} ? "$file->{path}/$file->{file_nr}" : $file->{file_nr}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + @$stats{qw(fhalloc fhfree fhmax)} = (split /\s+/, <$fh>)[0..2]; + close($fh); + } + + sub _get_inode_nr { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $stats = $self->{stats}; + + my $filename = $file->{path} ? "$file->{path}/$file->{inode_nr}" : $file->{inode_nr}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + @$stats{qw(inalloc infree)} = (split /\s+/, <$fh>)[0..1]; + $stats->{inmax} = $stats->{inalloc} + $stats->{infree}; + close($fh); + } + + sub _get_dentries { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $stats = $self->{stats}; + + my $filename = $file->{path} ? "$file->{path}/$file->{dentries}" : $file->{dentries}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + @$stats{qw(dentries unused agelimit wantpages)} = (split /\s+/, <$fh>)[0..3]; + close($fh); + } + + 1; +SYS_STATISTICS_LINUX_FILESTATS + +$fatpacked{"Sys/Statistics/Linux/LoadAVG.pm"} = <<'SYS_STATISTICS_LINUX_LOADAVG'; + =head1 NAME + + Sys::Statistics::Linux::LoadAVG - Collect linux load average statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::LoadAVG; + + my $lxs = Sys::Statistics::Linux::LoadAVG->new; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::LoadAVG gathers the load average from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 LOAD AVERAGE STATISTICS + + Generated by F. + + avg_1 - The average processor workload of the last minute. + avg_5 - The average processor workload of the last five minutes. + avg_15 - The average processor workload of the last fifteen minutes. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::LoadAVG->new; + + It's possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::LoadAVG->new( + files => { + # This is the default + path => '/proc', + loadavg => 'loadavg', + } + ); + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::LoadAVG; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.08'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + loadavg => 'loadavg', + } + ); + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my %lavg = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{loadavg}" : $file->{loadavg}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + ( $lavg{avg_1} + , $lavg{avg_5} + , $lavg{avg_15} + ) = (split /\s+/, <$fh>)[0..2]; + + close($fh); + return \%lavg; + } + + 1; +SYS_STATISTICS_LINUX_LOADAVG + +$fatpacked{"Sys/Statistics/Linux/MemStats.pm"} = <<'SYS_STATISTICS_LINUX_MEMSTATS'; + =head1 NAME + + Sys::Statistics::Linux::MemStats - Collect linux memory information. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::MemStats; + + my $lxs = Sys::Statistics::Linux::MemStats->new; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::MemStats gathers memory statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 MEMORY INFORMATIONS + + Generated by F. + + memused - Total size of used memory in kilobytes. + memfree - Total size of free memory in kilobytes. + memusedper - Total size of used memory in percent. + memtotal - Total size of memory in kilobytes. + buffers - Total size of buffers used from memory in kilobytes. + cached - Total size of cached memory in kilobytes. + realfree - Total size of memory is real free (memfree + buffers + cached). + realfreeper - Total size of memory is real free in percent of total memory. + swapused - Total size of swap space is used is kilobytes. + swapfree - Total size of swap space is free in kilobytes. + swapusedper - Total size of swap space is used in percent. + swaptotal - Total size of swap space in kilobytes. + swapcached - Memory that once was swapped out, is swapped back in but still also is in the swapfile. + active - Memory that has been used more recently and usually not reclaimed unless absolutely necessary. + inactive - Memory which has been less recently used and is more eligible to be reclaimed for other purposes. + On earlier kernels (2.4) Inact_dirty + Inact_laundry + Inact_clean. + + The following statistics are only available by kernels from 2.6. + + slab - Total size of memory in kilobytes that used by kernel for data structure allocations. + dirty - Total size of memory pages in kilobytes that waits to be written back to disk. + mapped - Total size of memory in kilbytes that is mapped by devices or libraries with mmap. + writeback - Total size of memory that was written back to disk. + committed_as - The amount of memory presently allocated on the system. + + The following statistic is only available by kernels from 2.6.9. + + commitlimit - Total amount of memory currently available to be allocated on the system. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::MemStats->new; + + It's possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::MemStats->new( + files => { + # This is the default + path => '/proc', + meminfo => 'meminfo', + } + ); + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::MemStats; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.16'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + meminfo => 'meminfo', + } + ); + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my %meminfo = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{meminfo}" : $file->{meminfo}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + # MemTotal: 1035648 kB + # MemFree: 15220 kB + # Buffers: 4280 kB + # Cached: 47664 kB + # SwapCached: 473988 kB + # Active: 661992 kB + # Inactive: 314312 kB + # HighTotal: 130884 kB + # HighFree: 264 kB + # LowTotal: 904764 kB + # LowFree: 14956 kB + # SwapTotal: 1951856 kB + # SwapFree: 1164864 kB + # Dirty: 520 kB + # Writeback: 0 kB + # AnonPages: 908892 kB + # Mapped: 34308 kB + # Slab: 19284 kB + # SReclaimable: 7532 kB + # SUnreclaim: 11752 kB + # PageTables: 3056 kB + # NFS_Unstable: 0 kB + # Bounce: 0 kB + # CommitLimit: 2469680 kB + # Committed_AS: 1699568 kB + # VmallocTotal: 114680 kB + # VmallocUsed: 12284 kB + # VmallocChunk: 100992 kB + + # kernel <= 2.4 + # Inact_dirty: 138632 kB + # Inact_laundry: 35520 kB + # Inact_clean: 7544 kB + + while (my $line = <$fh>) { + if ($line =~ /^((?:Mem|Swap)(?:Total|Free)|Buffers|Cached|SwapCached|Active|Inactive| + Dirty|Writeback|Mapped|Slab|Commit(?:Limit|ted_AS)):\s*(\d+)/x) { + my ($n, $v) = ($1, $2); + $n =~ tr/A-Z/a-z/; + $meminfo{$n} = $v; + } elsif ($line =~ /^Inact_(?:dirty|laundry|clean):\s*(\d+)/) { + $meminfo{inactive} += $1; + } + } + + close($fh); + + $meminfo{memused} = sprintf('%u', $meminfo{memtotal} - $meminfo{memfree}); + $meminfo{memusedper} = sprintf('%.2f', 100 * $meminfo{memused} / $meminfo{memtotal}); + $meminfo{swapused} = sprintf('%u', $meminfo{swaptotal} - $meminfo{swapfree}); + $meminfo{realfree} = sprintf('%u', $meminfo{memfree} + $meminfo{buffers} + $meminfo{cached}); + $meminfo{realfreeper} = sprintf('%.2f', 100 * $meminfo{realfree} / $meminfo{memtotal}); + + # maybe there is no swap space on the machine + if (!$meminfo{swaptotal}) { + $meminfo{swapusedper} = '0.00'; + } else { + $meminfo{swapusedper} = sprintf('%.2f', 100 * $meminfo{swapused} / $meminfo{swaptotal}); + } + + return \%meminfo; + } + + 1; +SYS_STATISTICS_LINUX_MEMSTATS + +$fatpacked{"Sys/Statistics/Linux/NetStats.pm"} = <<'SYS_STATISTICS_LINUX_NETSTATS'; + =head1 NAME + + Sys::Statistics::Linux::NetStats - Collect linux net statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::NetStats; + + my $lxs = Sys::Statistics::Linux::NetStats->new; + $lxs->init; + sleep 1; + my $stat = $lxs->get; + + Or + + my $lxs = Sys::Statistics::Linux::NetStats->new(initfile => $file); + $lxs->init; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::NetStats gathers net statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 NET STATISTICS + + Generated by F. + + rxbyt - Number of bytes received per second. + rxpcks - Number of packets received per second. + rxerrs - Number of errors that happend while received packets per second. + rxdrop - Number of packets that were dropped per second. + rxfifo - Number of FIFO overruns that happend on received packets per second. + rxframe - Number of carrier errors that happend on received packets per second. + rxcompr - Number of compressed packets received per second. + rxmulti - Number of multicast packets received per second. + txbyt - Number of bytes transmitted per second. + txpcks - Number of packets transmitted per second. + txerrs - Number of errors that happend while transmitting packets per second. + txdrop - Number of packets that were dropped per second. + txfifo - Number of FIFO overruns that happend on transmitted packets per second. + txcolls - Number of collisions that were detected per second. + txcarr - Number of carrier errors that happend on transmitted packets per second. + txcompr - Number of compressed packets transmitted per second. + ttpcks - Number of total packets (received + transmitted) per second. + ttbyt - Number of total bytes (received + transmitted) per second. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::NetStats->new; + + Maybe you want to store/load the initial statistics to/from a file: + + my $lxs = Sys::Statistics::Linux::NetStats->new(initfile => '/tmp/netstats.yml'); + + If you set C it's not necessary to call sleep before C. + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::NetStats->new( + files => { + # This is the default + path => '/proc', + netdev => 'net/dev', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head2 raw() + + The same as get_raw() but it's not necessary to call init() first. + + =head2 get_raw() + + Call C to get the raw data - no deltas. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::NetStats; + + use strict; + use warnings; + use Carp qw(croak); + use Time::HiRes; + + our $VERSION = '0.21'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + netdev => 'net/dev', + } + ); + + if (defined $opts->{initfile}) { + require YAML::Syck; + $self{initfile} = $opts->{initfile}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub init { + my $self = shift; + + if ($self->{initfile} && -r $self->{initfile}) { + $self->{init} = YAML::Syck::LoadFile($self->{initfile}); + $self->{time} = delete $self->{init}->{time}; + } else { + $self->{time} = Time::HiRes::gettimeofday(); + $self->{init} = $self->_load; + } + } + + sub get { + my $self = shift; + my $class = ref $self; + + if (!exists $self->{init}) { + croak "$class: there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + + if ($self->{initfile}) { + $self->{init}->{time} = $self->{time}; + YAML::Syck::DumpFile($self->{initfile}, $self->{init}); + } + + return $self->{stats}; + } + + sub raw { + my $self = shift; + my $stat = $self->_load; + + return $stat; + } + + sub get_raw { + my $self = shift; + my %raw = %{$self->{init}}; + delete $raw{time}; + return \%raw; + } + + # + # private stuff + # + + sub _load { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my %stats = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{netdev}" : $file->{netdev}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + next unless $line =~ /^\s*(.+?):\s*(.*)/; + @{$stats{$1}}{qw( + rxbyt rxpcks rxerrs rxdrop rxfifo rxframe rxcompr rxmulti + txbyt txpcks txerrs txdrop txfifo txcolls txcarr txcompr + )} = split /\s+/, $2; + $stats{$1}{ttbyt} = $stats{$1}{rxbyt} + $stats{$1}{txbyt}; + $stats{$1}{ttpcks} = $stats{$1}{rxpcks} + $stats{$1}{txpcks}; + } + + close($fh); + return \%stats; + } + + sub _deltas { + my $self = shift; + my $class = ref $self; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + my $time = Time::HiRes::gettimeofday(); + my $delta = sprintf('%.2f', $time - $self->{time}); + $self->{time} = $time; + + foreach my $dev (keys %{$lstat}) { + if (!exists $istat->{$dev}) { + delete $lstat->{$dev}; + next; + } + + my $idev = $istat->{$dev}; + my $ldev = $lstat->{$dev}; + + while (my ($k, $v) = each %{$ldev}) { + if (!defined $idev->{$k}) { + croak "$class: not defined key found '$k'"; + } + + if ($v !~ /^\d+\z/ || $ldev->{$k} !~ /^\d+\z/) { + croak "$class: invalid value for key '$k'"; + } + + if ($ldev->{$k} == $idev->{$k} || $idev->{$k} > $ldev->{$k}) { + $ldev->{$k} = sprintf('%.2f', 0); + } elsif ($delta > 0) { + $ldev->{$k} = sprintf('%.2f', ($ldev->{$k} - $idev->{$k}) / $delta); + } else { + $ldev->{$k} = sprintf('%.2f', $ldev->{$k} - $idev->{$k}); + } + + $idev->{$k} = $v; + } + } + } + + 1; +SYS_STATISTICS_LINUX_NETSTATS + +$fatpacked{"Sys/Statistics/Linux/PgSwStats.pm"} = <<'SYS_STATISTICS_LINUX_PGSWSTATS'; + =head1 NAME + + Sys::Statistics::Linux::PgSwStats - Collect linux paging and swapping statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::PgSwStats; + + my $lxs = Sys::Statistics::Linux::PgSwStats->new; + $lxs->init; + sleep 1; + my $stat = $lxs->get; + + Or + + my $lxs = Sys::Statistics::Linux::PgSwStats->new(initfile => $file); + $lxs->init; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::PgSwStats gathers paging and swapping statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 PAGING AND SWAPPING STATISTICS + + Generated by F or F. + + pgpgin - Number of pages the system has paged in from disk per second. + pgpgout - Number of pages the system has paged out to disk per second. + pswpin - Number of pages the system has swapped in from disk per second. + pswpout - Number of pages the system has swapped out to disk per second. + + The following statistics are only available by kernels from 2.6. + + pgfault - Number of page faults the system has made per second (minor + major). + pgmajfault - Number of major faults per second the system required loading a memory page from disk. + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::PgSwStats->new; + + Maybe you want to store/load the initial statistics to/from a file: + + my $lxs = Sys::Statistics::Linux::PgSwStats->new(initfile => '/tmp/pgswstats.yml'); + + If you set C it's not necessary to call sleep before C. + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::PgSwStats->new( + files => { + # This is the default + path => '/proc', + stat => 'stat', + vmstat => 'vmstat', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head2 raw() + + Get raw values. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::PgSwStats; + + use strict; + use warnings; + use Carp qw(croak); + use Time::HiRes; + + our $VERSION = '0.18'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + stat => 'stat', + vmstat => 'vmstat', + } + ); + + if (defined $opts->{initfile}) { + require YAML::Syck; + $self{initfile} = $opts->{initfile}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub init { + my $self = shift; + + if ($self->{initfile} && -r $self->{initfile}) { + $self->{init} = YAML::Syck::LoadFile($self->{initfile}); + $self->{time} = delete $self->{init}->{time}; + } else { + $self->{time} = Time::HiRes::gettimeofday(); + $self->{init} = $self->_load; + } + } + + sub get { + my $self = shift; + my $class = ref $self; + + if (!exists $self->{init}) { + croak "$class: there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + + if ($self->{initfile}) { + $self->{init}->{time} = $self->{time}; + YAML::Syck::DumpFile($self->{initfile}, $self->{init}); + } + + return $self->{stats}; + } + + sub raw { + my $self = shift; + my $stat = $self->_load; + + return $stat; + } + + # + # private stuff + # + + sub _load { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my %stats = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{stat}" : $file->{stat}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /^page\s+(\d+)\s+(\d+)$/) { + @stats{qw(pgpgin pgpgout)} = ($1, $2); + } elsif ($line =~ /^swap\s+(\d+)\s+(\d+)$/) { + @stats{qw(pswpin pswpout)} = ($1, $2); + } + } + + close($fh); + + # if paging and swapping are not found in /proc/stat + # then let's try a look into /proc/vmstat (since 2.6) + + if (!defined $stats{pswpout}) { + my $filename = $file->{path} ? "$file->{path}/$file->{vmstat}" : $file->{vmstat}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + while (my $line = <$fh>) { + next unless $line =~ /^(pgpgin|pgpgout|pswpin|pswpout|pgfault|pgmajfault)\s+(\d+)/; + $stats{$1} = $2; + } + close($fh); + } + + return \%stats; + } + + sub _deltas { + my $self = shift; + my $class = ref $self; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + my $time = Time::HiRes::gettimeofday(); + my $delta = sprintf('%.2f', $time - $self->{time}); + $self->{time} = $time; + + while (my ($k, $v) = each %{$lstat}) { + if (!defined $istat->{$k} || !defined $lstat->{$k}) { + croak "$class: not defined key found '$k'"; + } + + if ($v !~ /^\d+\z/ || $istat->{$k} !~ /^\d+\z/) { + croak "$class: invalid value for key '$k'"; + } + + if ($lstat->{$k} == $istat->{$k} || $istat->{$k} > $lstat->{$k}) { + $lstat->{$k} = sprintf('%.2f', 0); + } elsif ($delta > 0) { + $lstat->{$k} = sprintf('%.2f', ($lstat->{$k} - $istat->{$k}) / $delta); + } else { + $lstat->{$k} = sprintf('%.2f', $lstat->{$k} - $istat->{$k}); + } + + $istat->{$k} = $v; + } + } + + 1; +SYS_STATISTICS_LINUX_PGSWSTATS + +$fatpacked{"Sys/Statistics/Linux/ProcStats.pm"} = <<'SYS_STATISTICS_LINUX_PROCSTATS'; + =head1 NAME + + Sys::Statistics::Linux::ProcStats - Collect linux process statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::ProcStats; + + my $lxs = Sys::Statistics::Linux::ProcStats->new; + $lxs->init; + sleep 1; + my $stat = $lxs->get; + + Or + + my $lxs = Sys::Statistics::Linux::ProcStats->new(initfile => $file); + $lxs->init; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::ProcStats gathers process statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 IMPORTANT + + I renamed key C to C! + + =head1 LOAD AVERAGE STATISTICS + + Generated by F and F. + + new - Number of new processes that were produced per second. + runqueue - The number of currently executing kernel scheduling entities (processes, threads). + count - The number of kernel scheduling entities that currently exist on the system (processes, threads). + blocked - Number of processes blocked waiting for I/O to complete (Linux 2.5.45 onwards). + running - Number of processes in runnable state (Linux 2.5.45 onwards). + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::ProcStats->new; + + Maybe you want to store/load the initial statistics to/from a file: + + my $lxs = Sys::Statistics::Linux::ProcStats->new(initfile => '/tmp/procstats.yml'); + + If you set C it's not necessary to call sleep before C. + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::ProcStats->new( + files => { + # This is the default + path => '/proc', + loadavg => 'loadavg', + stat => 'stat', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head2 raw() + + Get raw values. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::ProcStats; + + use strict; + use warnings; + use Carp qw(croak); + use Time::HiRes; + + our $VERSION = '0.20'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + loadavg => 'loadavg', + stat => 'stat', + } + ); + + if (defined $opts->{initfile}) { + require YAML::Syck; + $self{initfile} = $opts->{initfile}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub init { + my $self = shift; + + if ($self->{initfile} && -r $self->{initfile}) { + $self->{init} = YAML::Syck::LoadFile($self->{initfile}); + $self->{time} = delete $self->{init}->{time}; + } else { + $self->{time} = Time::HiRes::gettimeofday(); + $self->{init} = $self->_load; + } + } + + sub get { + my $self = shift; + my $class = ref $self; + + if (!exists $self->{init}) { + croak "$class: there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + + if ($self->{initfile}) { + $self->{init}->{time} = $self->{time}; + YAML::Syck::DumpFile($self->{initfile}, $self->{init}); + } + + return $self->{stats}; + } + + sub raw { + my $self = shift; + my $stat = $self->_load; + + return $stat; + } + + # + # private stuff + # + + sub _load { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $lavg = $self->_procs; + + my $filename = $file->{path} ? "$file->{path}/$file->{loadavg}" : $file->{loadavg}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + ($lavg->{runqueue}, $lavg->{count}) = (split m@/@, (split /\s+/, <$fh>)[3]); + close($fh); + + return $lavg; + } + + sub _procs { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my %stat = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{stat}" : $file->{stat}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /^processes\s+(\d+)/) { + $stat{new} = $1; + } elsif ($line =~ /^procs_(blocked|running)\s+(\d+)/) { + $stat{$1} = $2; + } + } + + close($fh); + return \%stat; + } + + sub _deltas { + my $self = shift; + my $class = ref $self; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + my $time = Time::HiRes::gettimeofday(); + my $delta = sprintf('%.2f', $time - $self->{time}); + $self->{time} = $time; + + if (!defined $istat->{new} || !defined $lstat->{new}) { + croak "$class: not defined key found 'new'"; + } + if ($istat->{new} !~ /^\d+\z/ || $lstat->{new} !~ /^\d+\z/) { + croak "$class: invalid value for key 'new'"; + } + + my $new_init = $lstat->{new}; + + if ($lstat->{new} == $istat->{new} || $istat->{new} > $lstat->{new}) { + $lstat->{new} = sprintf('%.2f', 0); + } elsif ($delta > 0) { + $lstat->{new} = sprintf('%.2f', ($new_init - $istat->{new}) / $delta ); + } else { + $lstat->{new} = sprintf('%.2f', $new_init - $istat->{new}); + } + + $istat->{new} = $new_init; + } + + 1; +SYS_STATISTICS_LINUX_PROCSTATS + +$fatpacked{"Sys/Statistics/Linux/Processes.pm"} = <<'SYS_STATISTICS_LINUX_PROCESSES'; + =head1 NAME + + Sys::Statistics::Linux::Processes - Collect linux process statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::Processes; + + my $lxs = Sys::Statistics::Linux::Processes->new; + # or Sys::Statistics::Linux::Processes->new(pids => \@pids) + + $lxs->init; + sleep 1; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::Processes gathers process information from the virtual + F filesystem (procfs). + + For more information read the documentation of the front-end module + L. + + =head1 PROCESS STATISTICS + + Generated by FpidE/stat>, FpidE/status>, + FpidE/cmdline> and F. + + Note that if F isn't readable, the key owner is set to F. + + ppid - The parent process ID of the process. + nlwp - The number of light weight processes that runs by this process. + owner - The owner name of the process. + pgrp - The group ID of the process. + state - The status of the process. + session - The session ID of the process. + ttynr - The tty the process use. + minflt - The number of minor faults the process made. + cminflt - The number of minor faults the child process made. + mayflt - The number of mayor faults the process made. + cmayflt - The number of mayor faults the child process made. + stime - The number of jiffies the process have beed scheduled in kernel mode. + utime - The number of jiffies the process have beed scheduled in user mode. + ttime - The number of jiffies the process have beed scheduled (user + kernel). + cstime - The number of jiffies the process waited for childrens have been scheduled in kernel mode. + cutime - The number of jiffies the process waited for childrens have been scheduled in user mode. + prior - The priority of the process (+15). + nice - The nice level of the process. + sttime - The time in jiffies the process started after system boot. + actime - The time in D:H:M:S (days, hours, minutes, seconds) the process is active. + vsize - The size of virtual memory of the process. + nswap - The size of swap space of the process. + cnswap - The size of swap space of the childrens of the process. + cpu - The CPU number the process was last executed on. + wchan - The "channel" in which the process is waiting. + fd - This is a subhash containing each file which the process has open, named by its file descriptor. + 0 is standard input, 1 standard output, 2 standard error, etc. Because only the owner or root + can read /proc//fd this hash could be empty. + cmd - Command of the process. + cmdline - Command line of the process. + + Generated by FpidE/statm>. All statistics provides information + about memory in pages: + + size - The total program size of the process. + resident - Number of resident set size, this includes the text, data and stack space. + share - Total size of shared pages of the process. + trs - Total text size of the process. + drs - Total data/stack size of the process. + lrs - Total library size of the process. + dtp - Total size of dirty pages of the process (unused since kernel 2.6). + + It's possible to convert pages to bytes or kilobytes. Example - if the pagesize of your + system is 4kb: + + $Sys::Statistics::Linux::Processes::PAGES_TO_BYTES = 0; # pages (default) + $Sys::Statistics::Linux::Processes::PAGES_TO_BYTES = 4; # convert to kilobytes + $Sys::Statistics::Linux::Processes::PAGES_TO_BYTES = 4096; # convert to bytes + + # or with + Sys::Statistics::Linux::Processes->new(pages_to_bytes => 4096); + + Generated by FpidE/io>. + + rchar - Bytes read from storage (might have been from pagecache). + wchar - Bytes written. + syscr - Number of read syscalls. + syscw - Numner of write syscalls. + read_bytes - Bytes really fetched from storage layer. + write_bytes - Bytes sent to the storage layer. + cancelled_write_bytes - Refer to docs. + + See Documentation/filesystems/proc.txt for more (from kernel 2.6.20) + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::Processes->new; + + It's possible to handoff an array reference with a PID list. + + my $lxs = Sys::Statistics::Linux::Processes->new(pids => [ 1, 2, 3 ]); + + It's also possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::Processes->new( + files => { + # This is the default + path => '/proc', + uptime => 'uptime', + stat => 'stat', + statm => 'statm', + status => 'status', + cmdline => 'cmdline', + wchan => 'wchan', + fd => 'fd', + io => 'io', + } + ); + + =head2 init() + + Call C to initialize the statistics. + + $lxs->init; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + Note: + + Processes that were created between the call of init() and get() are returned as well, + but the keys minflt, cminflt, mayflt, cmayflt, utime, stime, cutime, and cstime are set + to the value 0.00 because there are no inititial values to calculate the deltas. + + =head2 raw() + + Get raw values. + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify + it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::Processes; + + use strict; + use warnings; + use Time::HiRes; + use constant NUMBER => qr/^-{0,1}\d+(?:\.\d+){0,1}\z/; + + our $VERSION = "0.38"; + our $PAGES_TO_BYTES = 0; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + uptime => 'uptime', + stat => 'stat', + statm => 'statm', + status => 'status', + cmdline => 'cmdline', + wchan => 'wchan', + fd => 'fd', + io => 'io', + }, + ); + + if (defined $opts->{pids}) { + if (ref($opts->{pids}) ne 'ARRAY') { + die "the PIDs must be passed as a array reference to new()"; + } + + foreach my $pid (@{$opts->{pids}}) { + if ($pid !~ /^\d+\z/) { + die "PID '$pid' is not a number"; + } + } + + $self{pids} = $opts->{pids}; + } + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + if ($opts->{pages_to_bytes}) { + $self{pages_to_bytes} = $opts->{pages_to_bytes}; + } + + return bless \%self, $class; + } + + sub init { + my $self = shift; + $self->{init} = $self->_init; + } + + sub get { + my $self = shift; + + if (!exists $self->{init}) { + die "there are no initial statistics defined"; + } + + $self->{stats} = $self->_load; + $self->_deltas; + return $self->{stats}; + } + + sub raw { + my $self = shift; + my $stat = $self->_load; + + return $stat; + } + + # + # private stuff + # + + sub _init { + my $self = shift; + my $file = $self->{files}; + my $pids = $self->_get_pids; + my $stats = { }; + + $stats->{time} = Time::HiRes::gettimeofday(); + + foreach my $pid (@$pids) { + my $stat = $self->_get_stat($pid); + + if (defined $stat) { + foreach my $key (qw/minflt cminflt mayflt cmayflt utime stime cutime cstime sttime/) { + $stats->{$pid}->{$key} = $stat->{$key}; + } + $stats->{$pid}->{io} = $self->_get_io($pid); + } + } + + return $stats; + } + + sub _load { + my $self = shift; + my $file = $self->{files}; + my $uptime = $self->_uptime; + my $pids = $self->_get_pids; + my $stats = { }; + + $stats->{time} = Time::HiRes::gettimeofday(); + + PID: foreach my $pid (@$pids) { + foreach my $key (qw/statm stat io owner cmdline wchan fd/) { + my $method = "_get_$key"; + my $data = $self->$method($pid); + + if (!defined $data) { + delete $stats->{$pid}; + next PID; + } + + if ($key eq "statm" || $key eq "stat") { + for my $x (keys %$data) { + $stats->{$pid}->{$x} = $data->{$x}; + } + } else { + $stats->{$pid}->{$key} = $data; + } + } + } + + return $stats; + } + + sub _deltas { + my $self = shift; + my $istat = $self->{init}; + my $lstat = $self->{stats}; + my $uptime = $self->_uptime; + + if (!defined $istat->{time} || !defined $lstat->{time}) { + die "not defined key found 'time'"; + } + + if ($istat->{time} !~ NUMBER || $lstat->{time} !~ NUMBER) { + die "invalid value for key 'time'"; + } + + my $time = $lstat->{time} - $istat->{time}; + $istat->{time} = $lstat->{time}; + delete $lstat->{time}; + + for my $pid (keys %{$lstat}) { + my $ipid = $istat->{$pid}; + my $lpid = $lstat->{$pid}; + + # yeah, what happends if the start time is different... it seems that a new + # process with the same process-id were created... for this reason I have to + # check if the start time is equal! + if ($ipid && $ipid->{sttime} == $lpid->{sttime}) { + for my $k (qw(minflt cminflt mayflt cmayflt utime stime cutime cstime)) { + if (!defined $ipid->{$k}) { + die "not defined key found '$k'"; + } + if ($ipid->{$k} !~ NUMBER || $lpid->{$k} !~ NUMBER) { + die "invalid value for key '$k'"; + } + + $lpid->{$k} -= $ipid->{$k}; + $ipid->{$k} += $lpid->{$k}; + + if ($lpid->{$k} > 0 && $time > 0) { + $lpid->{$k} = sprintf('%.2f', $lpid->{$k} / $time); + } else { + $lpid->{$k} = sprintf('%.2f', $lpid->{$k}); + } + } + + $lpid->{ttime} = sprintf('%.2f', $lpid->{stime} + $lpid->{utime}); + + for my $k (qw(rchar wchar syscr syscw read_bytes write_bytes cancelled_write_bytes)) { + if(defined $ipid->{io}->{$k} && defined $lpid->{io}->{$k}){ + if($ipid->{io}->{$k} !~ NUMBER || $lpid->{io}->{$k} !~ NUMBER){ + die "invalid value for io key '$k'"; + } + $lpid->{io}->{$k} -= $ipid->{io}->{$k}; + $ipid->{io}->{$k} += $lpid->{io}->{$k}; + if ($lpid->{io}->{$k} > 0 && $time > 0) { + $lpid->{io}->{$k} = sprintf('%.2f', $lpid->{io}->{$k} / $time); + } else { + $lpid->{io}->{$k} = sprintf('%.2f', $lpid->{io}->{$k}); + } + } + } + } else { + # calculate the statistics since process creation + for my $k (qw(minflt cminflt mayflt cmayflt utime stime cutime cstime)) { + my $p_uptime = $uptime - $lpid->{sttime} / 100; + $istat->{$pid}->{$k} = $lpid->{$k}; + + if ($p_uptime > 0) { + $lpid->{$k} = sprintf('%.2f', $lpid->{$k} / $p_uptime); + } else { + $lpid->{$k} = sprintf('%.2f', $lpid->{$k}); + } + } + + for my $k (qw(rchar wchar syscr syscw read_bytes write_bytes cancelled_write_bytes)) { + my $p_uptime = $uptime - $lpid->{sttime} / 100; + $lpid->{io}->{$k} ||= 0; + $istat->{$pid}->{io}->{$k} = $lpid->{io}->{$k}; + + if ($p_uptime > 0) { + $lpid->{io}->{$k} = sprintf('%.2f', $lpid->{io}->{$k} / $p_uptime); + } else { + $lpid->{io}->{$k} = sprintf('%.2f', $lpid->{io}->{$k}); + } + } + + $lpid->{ttime} = sprintf('%.2f', $lpid->{stime} + $lpid->{utime}); + $istat->{$pid}->{sttime} = $lpid->{sttime}; + } + } + } + + sub _get_statm { + my ($self, $pid) = @_; + my $file = $self->{files}; + my %stat = (); + + open my $fh, '<', "$file->{path}/$pid/$file->{statm}" + or return undef; + + my @line = split /\s+/, <$fh>; + + if (@line < 7) { + return undef; + } + + my $ptb = $self->{pages_to_bytes} || $PAGES_TO_BYTES; + + if ($ptb) { + @stat{qw(size resident share trs lrs drs dtp)} = map { $_ * $ptb } @line; + } else { + @stat{qw(size resident share trs lrs drs dtp)} = @line; + } + + close($fh); + return \%stat; + } + + sub _get_stat { + my ($self, $pid) = @_; + my $file = $self->{files}; + my %stat = (); + + open my $fh, '<', "$file->{path}/$pid/$file->{stat}" + or return undef; + + my @line = split /\s+/, <$fh>; + + if (@line < 38) { + return undef; + } + + @stat{qw( + cmd state ppid pgrp session ttynr minflt + cminflt mayflt cmayflt utime stime cutime cstime + prior nice nlwp sttime vsize nswap cnswap + cpu + )} = @line[1..6,9..19,21..22,35..36,38]; + + my $uptime = $self->_uptime; + my ($d, $h, $m, $s) = $self->_calsec(sprintf('%li', $uptime - $stat{sttime} / 100)); + $stat{actime} = "$d:".sprintf('%02d:%02d:%02d', $h, $m, $s); + + close($fh); + return \%stat; + } + + sub _get_owner { + my ($self, $pid) = @_; + my $file = $self->{files}; + my $owner = "N/a"; + + open my $fh, '<', "$file->{path}/$pid/$file->{status}" + or return undef; + + while (my $line = <$fh>) { + if ($line =~ /^Uid:(?:\s+|\t+)(\d+)/) { + $owner = getpwuid($1) || "N/a"; + last; + } + } + + close($fh); + return $owner; + } + + sub _get_cmdline { + my ($self, $pid) = @_; + my $file = $self->{files}; + + open my $fh, '<', "$file->{path}/$pid/$file->{cmdline}" + or return undef; + + my $cmdline = <$fh>; + close $fh; + + if (!defined $cmdline) { + $cmdline = "N/a"; + } + + $cmdline =~ s/\0/ /g; + $cmdline =~ s/^\s+//; + $cmdline =~ s/\s+$//; + chomp $cmdline; + return $cmdline; + } + + sub _get_wchan { + my ($self, $pid) = @_; + my $file = $self->{files}; + + open my $fh, '<', "$file->{path}/$pid/$file->{wchan}" + or return undef; + + my $wchan = <$fh>; + close $fh; + + if (!defined $wchan) { + $wchan = defined; + } + + chomp $wchan; + return $wchan; + } + + sub _get_io { + my ($self, $pid) = @_; + my $file = $self->{files}; + my %stat = (); + + if (open my $fh, '<', "$file->{path}/$pid/$file->{io}") { + while (my $line = <$fh>) { + if ($line =~ /^([a-z_]+):\s+(\d+)/) { + $stat{$1} = $2; + } + } + + close($fh); + } + + return \%stat; + } + + sub _get_fd { + my ($self, $pid) = @_; + my $file = $self->{files}; + my %stat = (); + + if (opendir my $dh, "$file->{path}/$pid/$file->{fd}") { + foreach my $link (grep !/^\.+\z/, readdir($dh)) { + if (my $target = readlink("$file->{path}/$pid/$file->{fd}/$link")) { + $stat{$pid}{fd}{$link} = $target; + } + } + } + + return \%stat; + } + + sub _get_pids { + my $self = shift; + my $file = $self->{files}; + + if ($self->{pids}) { + return $self->{pids}; + } + + opendir my $dh, $file->{path} + or die "unable to open directory $file->{path} ($!)"; + my @pids = grep /^\d+\z/, readdir $dh; + closedir $dh; + return \@pids; + } + + sub _uptime { + my $self = shift; + my $file = $self->{files}; + + my $filename = $file->{path} ? "$file->{path}/$file->{uptime}" : $file->{uptime}; + open my $fh, '<', $filename or die "unable to open $filename ($!)"; + my ($up, $idle) = split /\s+/, <$fh>; + close($fh); + return $up; + } + + sub _calsec { + my $self = shift; + my ($s, $m, $h, $d) = (shift, 0, 0, 0); + $s >= 86400 and $d = sprintf('%i', $s / 86400) and $s = $s % 86400; + $s >= 3600 and $h = sprintf('%i', $s / 3600) and $s = $s % 3600; + $s >= 60 and $m = sprintf('%i', $s / 60) and $s = $s % 60; + return ($d, $h, $m, $s); + } + + 1; +SYS_STATISTICS_LINUX_PROCESSES + +$fatpacked{"Sys/Statistics/Linux/SockStats.pm"} = <<'SYS_STATISTICS_LINUX_SOCKSTATS'; + =head1 NAME + + Sys::Statistics::Linux::SockStats - Collect linux socket statistics. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::SockStats; + + my $lxs = Sys::Statistics::Linux::SockStats->new; + my $stat = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::SockStats gathers socket statistics from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 SOCKET STATISTICS + + Generated by F. + + used - Total number of used sockets. + tcp - Number of tcp sockets in use. + udp - Number of udp sockets in use. + raw - Number of raw sockets in use. + ipfrag - Number of ip fragments in use (only available by kernels > 2.2). + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::SockStats->new; + + It's possible to set the path to the proc filesystem. + + Sys::Statistics::Linux::SockStats->new( + files => { + # This is the default + path => '/proc', + sockstat => 'net/sockstat', + } + ); + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $stat = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::SockStats; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.09'; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => '/proc', + sockstat => 'net/sockstat', + } + ); + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my %socks = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{sockstat}" : $file->{sockstat}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /sockets: used (\d+)/) { + $socks{used} = $1; + } elsif ($line =~ /TCP: inuse (\d+)/) { + $socks{tcp} = $1; + } elsif ($line =~ /UDP: inuse (\d+)/) { + $socks{udp} = $1; + } elsif ($line =~ /RAW: inuse (\d+)/) { + $socks{raw} = $1; + } elsif ($line =~ /FRAG: inuse (\d+)/) { + $socks{ipfrag} = $1; + } + } + + close($fh); + return \%socks; + } + + 1; +SYS_STATISTICS_LINUX_SOCKSTATS + +$fatpacked{"Sys/Statistics/Linux/SysInfo.pm"} = <<'SYS_STATISTICS_LINUX_SYSINFO'; + =head1 NAME + + Sys::Statistics::Linux::SysInfo - Collect linux system information. + + =head1 SYNOPSIS + + use Sys::Statistics::Linux::SysInfo; + + my $lxs = Sys::Statistics::Linux::SysInfo->new; + my $info = $lxs->get; + + =head1 DESCRIPTION + + Sys::Statistics::Linux::SysInfo gathers system information from the virtual F filesystem (procfs). + + For more information read the documentation of the front-end module L. + + =head1 SYSTEM INFOMATIONS + + Generated by F + and F, F, F, F. + + hostname - The host name. + domain - The host domain name. + kernel - The kernel name. + release - The kernel release. + version - The kernel version. + memtotal - The total size of memory. + swaptotal - The total size of swap space. + uptime - The uptime of the system. + idletime - The idle time of the system. + pcpucount - The total number of physical CPUs. + tcpucount - The total number of CPUs (cores, hyper threading). + interfaces - The interfaces of the system. + arch - The machine hardware name (uname -m). + + # countcpus is the same like tcpucount + countcpus - The total (maybe logical) number of CPUs. + + C and C are really easy to understand. Both values + are collected from C. C is the number of physical + CPUs, counted by C. C is just the total number + counted by C. + + If you want to get C and C as raw value you can set + + $Sys::Statistics::Linux::SysInfo::RAWTIME = 1; + # or with + Sys::Statistics::Linux::SysInfo->new(rawtime => 1) + + =head1 METHODS + + =head2 new() + + Call C to create a new object. + + my $lxs = Sys::Statistics::Linux::SysInfo->new; + + =head2 get() + + Call C to get the statistics. C returns the statistics as a hash reference. + + my $info = $lxs->get; + + =head1 EXPORTS + + No exports. + + =head1 SEE ALSO + + B + + =head1 REPORTING BUGS + + Please report all bugs to . + + =head1 AUTHOR + + Jonny Schulz . + + =head1 COPYRIGHT + + Copyright (c) 2006, 2007 by Jonny Schulz. All rights reserved. + + This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. + + =cut + + package Sys::Statistics::Linux::SysInfo; + + use strict; + use warnings; + use Carp qw(croak); + + our $VERSION = '0.13'; + our $RAWTIME = 0; + + sub new { + my $class = shift; + my $opts = ref($_[0]) ? shift : {@_}; + + my %self = ( + files => { + path => "/proc", + meminfo => "meminfo", + sysinfo => "sysinfo", + cpuinfo => "cpuinfo", + uptime => "uptime", + hostname => "sys/kernel/hostname", + domain => "sys/kernel/domainname", + kernel => "sys/kernel/ostype", + release => "sys/kernel/osrelease", + version => "sys/kernel/version", + netdev => "net/dev", + arch => [ "/bin/uname", "-m" ], + } + ); + + foreach my $file (keys %{ $opts->{files} }) { + $self{files}{$file} = $opts->{files}->{$file}; + } + + foreach my $param (qw(rawtime cpuinfo)) { + if ($opts->{$param}) { + $self{$param} = $opts->{$param}; + } + } + + return bless \%self, $class; + } + + sub get { + my $self = shift; + my $class = ref $self; + my $file = $self->{files}; + my $stats = { }; + + $self->{stats} = $stats; + + $self->_get_common; + $self->_get_meminfo; + $self->_get_uptime; + $self->_get_interfaces; + $self->_get_cpuinfo; + + foreach my $key (keys %$stats) { + chomp $stats->{$key}; + $stats->{$key} =~ s/\t+/ /g; + $stats->{$key} =~ s/\s+/ /g; + } + + return $stats; + } + + sub _get_common { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my $stats = $self->{stats}; + + for my $x (qw(hostname domain kernel release version)) { + my $filename = $file->{path} ? "$file->{path}/$file->{$x}" : $file->{$x}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + $stats->{$x} = <$fh>; + close($fh); + } + + if (-x $file->{arch}->[0] ) { + my $cmd = join(" ", @{$file->{arch}}); + $stats->{arch} = `$cmd`; + } + } + + sub _get_meminfo { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my $stats = $self->{stats}; + + my $filename = $file->{path} ? "$file->{path}/$file->{meminfo}" : $file->{meminfo}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /^MemTotal:\s+(\d+ \w+)/) { + $stats->{memtotal} = $1; + } elsif ($line =~ /^SwapTotal:\s+(\d+ \w+)/) { + $stats->{swaptotal} = $1; + } + } + + close($fh); + } + + sub _get_cpuinfo { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my $stats = $self->{stats}; + my (%cpu, $phyid); + + $stats->{countcpus} = 0; + + my $filename = $file->{path} ? "$file->{path}/$file->{cpuinfo}" : $file->{cpuinfo}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + + while (my $line = <$fh>) { + if ($line =~ /^physical\s+id\s*:\s*(\d+)/) { + $phyid = $1; + $cpu{$phyid}{count}++; + } elsif ($line =~ /^core\s+id\s*:\s*(\d+)/) { + $cpu{$phyid}{cores}{$1}++; + } elsif ($line =~ /^processor\s*:\s*\d+/) { # x86 + $stats->{countcpus}++; + } elsif ($line =~ /^# processors\s*:\s*(\d+)/) { # s390 + $stats->{countcpus} = $1; + last; + } + } + + close($fh); + + $stats->{countcpus} ||= 1; # if it was not possible to match + $stats->{tcpucount} = $stats->{countcpus}; + $stats->{pcpucount} = scalar keys %cpu || $stats->{countcpus}; + } + + sub _get_interfaces { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my $stats = $self->{stats}; + my @iface = (); + + my $filename = $file->{path} ? "$file->{path}/$file->{netdev}" : $file->{netdev}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + { my $head = <$fh>; } + + while (my $line = <$fh>) { + if ($line =~ /^\s*(\w+):/) { + push @iface, $1; + } + } + + close $fh; + + $stats->{interfaces} = join(", ", @iface); + $stats->{interfaces} ||= ""; + } + + sub _get_uptime { + my $self = shift; + my $class = ref($self); + my $file = $self->{files}; + my $stats = $self->{stats}; + + my $filename = $file->{path} ? "$file->{path}/$file->{uptime}" : $file->{uptime}; + open my $fh, '<', $filename or croak "$class: unable to open $filename ($!)"; + ($stats->{uptime}, $stats->{idletime}) = split /\s+/, <$fh>; + close $fh; + + if (!$RAWTIME && !$self->{rawtime}) { + foreach my $x (qw/uptime idletime/) { + my ($d, $h, $m, $s) = $self->_calsec(sprintf('%li', $stats->{$x})); + $stats->{$x} = "${d}d ${h}h ${m}m ${s}s"; + } + } + } + + sub _calsec { + my $self = shift; + my ($s, $m, $h, $d) = (shift, 0, 0, 0); + $s >= 86400 and $d = sprintf('%i',$s / 86400) and $s = $s % 86400; + $s >= 3600 and $h = sprintf('%i',$s / 3600) and $s = $s % 3600; + $s >= 60 and $m = sprintf('%i',$s / 60) and $s = $s % 60; + return ($d, $h, $m, $s); + } + + 1; +SYS_STATISTICS_LINUX_SYSINFO + +s/^ //mg for values %fatpacked; + +unshift @INC, sub { + if (my $fat = $fatpacked{$_[1]}) { + open my $fh, '<', \$fat + or die "FatPacker error loading $_[1] (could be a perl installation issue?)"; + return $fh; + } + return +}; + +} # END OF FATPACK CODE +#!/usr/bin/env perl + +use strict; +use warnings; +use Sys::Statistics::Linux; +use Sys::Statistics::Linux::DiskUsage; +use Config::IniFiles; + +sub _my_home { + if ( exists $ENV{HOME} && defined $ENV{HOME} ) { + return $ENV{HOME}; + } + + if ( $ENV{LOGDIR} ) { + return $ENV{LOGDIR}; + } + + return undef; +} + +sub _my_infos { + my @infos; + open (PASSWD, "< /etc/passwd"); + while () { + @infos = split /:/; + last if $infos[0] eq $ENV{LOGNAME}; + } + close(PASSWD); + + return @infos; +} + +sub free { + my $lxs = Sys::Statistics::Linux->new( + memstats => 1, + ); + + my $stat = $lxs->get; + my $memfree = $stat->memstats->{memfree}; + my $memused = $stat->memstats->{memused}; + my $memtotal = $stat->memstats->{memtotal}; + + my $home = _my_home(); + my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" + ); + + my $format = $cfg->val('memory', 'format') || 'string'; + my $color = $cfg->val('memory', 'color') + ? "\\" . $cfg->val('memory', 'color') . "\\" + : '\\' . $cfg->val('misc', 'color') . '\\'; + + my $free = $color . 'Mem: ' . int($memfree / 1024) . '/' . int($memused / 1024); + + if ( $format eq 'percent' ) { + my $free_usage = sprintf("%0.2f", int($memused / 1024) / int($memtotal / 1024 ) * 100); + $free = $color . 'Mem: ' . $free_usage . '%'; + } + + return $free; +} + +sub disk_space { + my $disk_usage = Sys::Statistics::Linux::DiskUsage->new( + cmd => { + # This is the default + df => 'df -hP 2>/dev/null', + } + ); + + my $stat = $disk_usage->get; + my $home = _my_home(); + my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" + ); + + my $format = $cfg->val('disk', 'format') || 'string'; + my $disk_path = $cfg->val('disk', 'disk_path') || '/dev/sda1'; + my $color = $cfg->val('disk', 'color') + ? "\\" . $cfg->val('disk', 'color') . "\\" + : '\\' . $cfg->val('misc', 'color') . '\\'; + my $disk = $color . 'Disk: ' . $stat->{$disk_path}->{usage} . '/' . $stat->{$disk_path}->{free}; + + if ( $format eq 'percent' ) { + my @usage = split(/G/, $stat->{$disk_path}->{usage}); + my @total = split(/G/, $stat->{$disk_path}->{total}); + $usage[0] =~ s/,/./; + $total[0] =~ s/,/./; + + my $disk_usage = sprintf("%0.2f", $usage[0] / $total[0] * 100); + $disk = $color . 'Disk: ' . $disk_usage . '%'; + } + + return $disk; +} + +sub time_date { + my $lxs = Sys::Statistics::Linux->new(); + my $home = _my_home(); + my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" + ); + my $format = $cfg->val('date', 'format') || '%Y/%m/%d %H:%M:%S'; + my $color = $cfg->val('date', 'color') + ? "\\" . $cfg->val('date', 'color') . "\\" + : '\\' . $cfg->val('misc', 'color') . '\\'; + + $lxs->settime($format); + my $date_time = $color . 'Date: ' . $lxs->gettime; + + return $date_time; +} + +sub name { + my @infos = _my_infos(); + my $home = _my_home(); + my @name = split(/,/, $infos[4]); + my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" + ); + my $color = $cfg->val('name', 'color') + ? "\\" . $cfg->val('name', 'color') . "\\" + : '\\' . $cfg->val('misc', 'color') . '\\'; + + return $color . $name[0]; +} + +sub status { + my $home = _my_home(); + my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" + ); + + my @call; + + my @sections = $cfg->Sections(); + my $dispatch = { + memory => free(), + disk => disk_space(), + date => time_date(), + name => name() + }; + + foreach my $section (@sections) { + next if $section eq 'misc'; + + $call[$cfg->val($section, 'position')] = $dispatch->{$section} + if $cfg->val($section, 'display'); + } + + `wmfs -c status "default @call"`; +} + +my $home = _my_home(); +my $cfg = Config::IniFiles->new( + -file => "$home/.config/wmfs/mahewin-wmfs-statusrc" +); + +my $timing = $cfg->val('misc', 'timing') || 1; + +while ( 1 ) { + sleep( $timing ); + status(); +} From 7c72ba5a28ae4ff618b12a6c485a7f9141396cfc Mon Sep 17 00:00:00 2001 From: Hobbestigrou Date: Sat, 14 Apr 2012 17:04:47 +0200 Subject: [PATCH 3/3] [Documentation] Changes: Update changelog. --- Changes | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Changes b/Changes index 6d9af9e..5a928df 100644 --- a/Changes +++ b/Changes @@ -1,5 +1,9 @@ Revision history for mahewin-status-bar +0.5 14/04/2012 + * [Core] Mahewin-wmfs-status: Generate a binary file with all dependecies. (Hobbestigrou) + * [Core] Status: Rename the file to mahewin-wmfs-status. (Hobbestigrou) + 0.4 14/04/2012 * [Core] Status: Adapt the call to wmfs 2. (Hobbestigrou)