munin-cgi-graph "Result too large"

Проблемы с установкой, настройкой и работой системных и сетевых программ.

Модераторы: GRooVE, alexco

Правила форума
Убедительная просьба юзать теги [code] при оформлении листингов.
Сообщения не оформленные должным образом имеют все шансы быть незамеченными.
master_255
рядовой
Сообщения: 16
Зарегистрирован: 2010-04-07 11:02:40

munin-cgi-graph "Result too large"

Непрочитанное сообщение master_255 » 2010-04-21 16:40:51

Поставил месяц назад munin, замониторил все сервера, рисование графиков сделал через munin-cgi-graph чтобы рисовались по требованию а не каждую минуту.

Все работало, и вдруг сегодня перестало.
Выдает ошибку

Код: Выделить всё

Result too large at /var/www/data/munin/graph.cgi line 145.
строка 145

Код: Выделить всё

semop($semid,$opstring) || die "$!";
пробывал вывести в лог значения переменных используемых в semop
$semid=65535
$opstring=ничего не вывел, возможно в этом ошибка?

предыдущая строка

Код: Выделить всё

my $opstring = pack("s!s!s!",0, $max_cgi_graph_jobs,0);
$max_cgi_graph_jobs=6

все на этом я сдулся, в перле ничерта не понимаю.
весь скрипт graph.cgi на всякий случай

Код: Выделить всё

#!/usr/local/bin/perl  -Tw
# -*- perl -*-
#
# Copyright (C) 2004 Jimmy Olsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2 dated June,
# 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# $Id: munin-cgi-graph.in 3252 2009-12-23 08:00:05Z janl $
#
# Please see http://munin.projects.linpro.no/wiki/CgiHowto for how to
# use this, and how to convert it to fastcgi which will improve speed.
#

use RRDs;
use Munin::Master::Utils;
use Munin::Common::Defaults;
use strict;
use IO::Handle;
use Date::Manip;
use POSIX qw(strftime);
use IPC::SysV qw(IPC_CREAT);

my $GRAPHER = "$Munin::Common::Defaults::MUNIN_LIBDIR/munin-graph";
my $conffile = "$Munin::Common::Defaults::MUNIN_CONFDIR/munin.conf";

my %TIMES   = ( "day"   => ["--noweek", "--nomonth", "--noyear", "--nosumweek", "--nosumyear"], 
		"week"  => ["--noday", "--nomonth", "--noyear", "--nosumweek", "--nosumyear"], 
		"month" => ["--noday", "--noweek", "--noyear", "--nosumweek", "--nosumyear"], 
		"year"  => ["--noday", "--noweek", "--nomonth", "--nosumweek", "--nosumyear"],
		"week-sum"  => ["--noday", "--nomonth", "--noyear", "--noweek", "--nosumyear"], 
		"year-sum"  => ["--noday", "--noweek", "--nomonth", "--nosumweek", "--noyear"]
	    );

my %period  = ( "day"   => 300,
		"week"  => 1800,
		"month" => 7200,
		"year"  => 86400,
		"week-sum" => 1800,
		"year-sum" => 86400
	    );

my $log = new IO::Handle;
my $scale = "day";
my $host  = "";
my $serv  = "";
my $dom   = "";
my $lock  = "";
my $IPC_KEY = 89340;

my $config = &munin_readconfig ($conffile);

my $path = $ENV{PATH_INFO} || "";
$path =~ s/^\///;
($dom, $host, $serv) = split /\//, $path;
($serv, $scale) = split /-/, $serv, 2;
$scale =~ s/\.png$//;

&verify_parameters ($dom, $host, $serv, $scale);

my $filename = get_picture_filename ($config, $dom, $host, $serv, $scale);

my $time = time;

# Get semaphore handle - Before graphing as recommended by snide.
my $semid = undef;

sem_setup();

my $no_cache = defined($ENV{HTTP_CACHE_CONTROL}) && $ENV{HTTP_CACHE_CONTROL} =~ /no-cache/i;

if ($no_cache or (! &graph_usable($filename,$time) )) {
    exit 0 unless draw_graph_or_complain($host, $serv, $TIMES{$scale});
    goto draw;
}

# At this time the file exists.  But may be old.  Or not.

my @stats         = stat ($filename);
my $last_modified = strftime ("%a, %d %b %Y %H:%M:%S %Z", localtime ($stats[9]));
# "Expires" has to use last modified time as base:
my $expires       = strftime ("%a, %d %b %Y %H:%M:%S GMT", 
			      gmtime($stats[9]+($period{$scale}-($stats[9]%$period{$scale}))));

# Check for If-Modified-Since and send 304 if not changed:
if (defined $ENV{HTTP_IF_MODIFIED_SINCE} and 
    !&modified ($ENV{HTTP_IF_MODIFIED_SINCE}, $stats[9]-1)) {
    print "Status: 304\n";
    print "Content-Type: image/png\n";
    print "Expires: ", $expires, "\n";
    print "Last-Modified: $last_modified\n";
    print "\n";
    exit 0;
}

draw:

    @stats = stat ($filename) unless @stats;

$last_modified = strftime ("%a, %d %b %Y %H:%M:%S %Z", localtime ($stats[9]))
    unless defined($last_modified); 

$expires       = strftime ("%a, %d %b %Y %H:%M:%S GMT", 
			     gmtime($stats[9]+($period{$scale}-($stats[9]%$period{$scale}))))
    unless defined($expires);

print "Content-Type: image/png\n";
print "Expires: ", strftime ("%a, %d %b %Y %H:%M:%S GMT", gmtime(time+($period{$scale}-($time%$period{$scale})))), "\n";
print "Last-Modified: $last_modified\n";
print "\n";

&graph ($filename);

# # # # # # # # # # END OF MAIN

sub sem_setup {
    # Try to police the number of concurrent rrdgraph instances. 

    # Fox kindly submitted a patch to convert to SysV IPC semaphores.
    # Lovely! (ticket #499).

    if(!defined($semid)) {
	semget($IPC_KEY, 0, 0 );

	# Or create it if needed
	$semid = semget($IPC_KEY, 1 , oct(666) | IPC_CREAT );

	die "Creating semaphore: $!" unless defined($semid);

	my $max_cgi_graph_jobs = &munin_get ($config, "max_cgi_graph_jobs" , 6, $dom);

	# And initialize to max_cgi_graph_jobs
	my $opstring = pack("s!s!s!",0, $max_cgi_graph_jobs,0);

	semop($semid,$opstring) || die "$!";
    }
}


sub sem_get {
    # Call this before doing heavy work.
    # Decrement, or lock/hang/yield if already 0
    my $opstring = pack("s!s!s!",0, -1, 0);
    semop($semid,$opstring);
}


sub sem_release {
    # Call this after doing heavy work.
    # Increment (and release waiting processes).
    my $opstring = pack("s!s!s!",0, 1, 0);
    semop($semid,$opstring);
}


sub graph {
    # This just serves the file, no file is made.
    my $filename = shift;

    open (my $GRAPH, '<', $filename) 
        or die "Warning: Could not open picture file \"$filename\" for reading: $!\n";
    print while (<$GRAPH>);
    close ($GRAPH);
}


sub get_picture_filename {
    my $config  = shift;
    my $domain  = shift;
    my $name    = shift;
    my $service = shift;
    my $scale   = shift;

    return "$config->{'htmldir'}/$domain/$name/$service-$scale.png";
}


sub logger_open {
    my $dirname = shift;

    if (!$log->opened)
    {
	unless (open ($log, '>>', "$dirname/munin-cgi-graph.log"))
	{
	    print STDERR "Warning: Could not open log file \"$dirname/munin-cgi-graph.log\" for writing: $!";
	}
    }
}


sub logger {
  my ($comment) = @_;
  my $now = strftime ("%b %d %H:%M:%S", localtime);

  if ($log->opened)
  {
          print $log "$now - $comment\n";
  }
  else
  {
          if (defined $config->{logdir})
          {
                  if (open ($log, '>>', "$config->{logdir}/munin-cgi-graph.log"))
                  {
                          print $log "$now - $comment\n";
                      }
                  else
                  {
                          print STDERR "Warning: Could not open log file \"$config->{logdir}/munin-cgi-graph.log\" for wr
iting: $!";
                          print STDERR "$now - $comment\n";
                  }
          }
          else
          {
                  print STDERR "$now - $comment\n";
          }
    }
}


sub verify_parameters
{
	my $dom   = shift;
	my $host  = shift;
	my $serv  = shift;
	my $scale = shift;

	if (!$dom)
	{
		print STDERR "Warning: Request for graph without specifying domain. Bailing out.\n";
		exit 1;
	}
	if (!$host)
	{
		print STDERR "Warning: Request for graph without specifying host. Bailing out.\n";
		exit 1;
	}
	if (!$serv)
	{
		print STDERR "Warning: Request for graph without specifying service. Bailing out.\n";
		exit 1;
	}

	if (!$scale)
	{
		print STDERR "Warning: Request for graph without specifying scale. Bailing out.\n";
		exit 1;
	}
	else
	{
		if (!defined $TIMES{$scale})
		{
			print STDERR "Warning: Weird scale setting \"$scale\". Bailing out.\n";
			exit 1;
		}
	}
}


sub graph_usable {
    # Check how old the graph is and return 1 if it's new enough and 0 otherwise.
    my ($filename, $time) = @_;

    if (-f $filename) {
	my @stats = stat (_);
	# $stats[9] holds the "last update" time and this needs to be in the last update period:
	if ($stats[9] > ($time - $time%$period{$scale})) {
#print STDERR ("Graph unexpired for $scale. ($stats[9] , $time, ". ($time%$period{$scale}). ", ". ($time - $time%$period{$scale}). ").\n");
	    return 1;
	} else {
#print STDERR ("Graph expired for $scale. ($stats[9] , $time, ". ($time%$period{$scale}). ", ". ($time - $time%$period{$scale}). ").\n");
	    return 0;
	}
    }
    return 0;
}


sub draw_graph {
    my $host  = shift;
    my $serv  = shift;
    my $scale = shift;

    $serv =~ s{[^\w_/"'\[\]\(\)\+=-]}{_}g; $serv =~ /^(.+)$/; $serv = $1; #"
    # . needs to be legal in host names
    $host =~ s{[^\w_/"'\[\]\(\)\.+=-]}{_}g; $host =~ /^(.+)$/; $host = $1; #"

    my @params = ($GRAPHER);
    push @params, @$scale;
    push @params, "--skip-locking", "--skip-stats", "--nolazy", "--list-images";
    push @params, "--host", $host, "--service", $serv;
    push @params, "STDERR>&STDOUT";

    my $file = "/dev/null";
    my $IN;
    sem_get();

    # Note: This open is an implicit fork
    if (! open ($IN, "-|")) { 
	%ENV=();
	exec @params;
    }
    $file = join (' ', <$IN>);
    chomp($file);

    close ($IN);
    sem_release();

    return $file;
}


sub draw_graph_or_complain {
    my $ret = draw_graph(@_);

	return $ret;
}


sub modified {
    # See if file has been modified since "the last time".

    # Format of since_string If-Modified-Since: Wed, 23 Jun 2004 16:11:06 GMT

    my $since_string = shift;
    my $created      = shift;
    my $ifmodsec = &UnixDate (&ParseDateString ($since_string), "%s");

    return 1 if ($ifmodsec < $created);
    return 0;
}

# vim: syntax=perl ts=8


Хостинговая компания Host-Food.ru
Хостинг HostFood.ru
 

Услуги хостинговой компании Host-Food.ru

Хостинг HostFood.ru

Тарифы на хостинг в России, от 12 рублей: https://www.host-food.ru/tariffs/hosting/
Тарифы на виртуальные сервера (VPS/VDS/KVM) в РФ, от 189 руб.: https://www.host-food.ru/tariffs/virtualny-server-vps/
Выделенные сервера, Россия, Москва, от 2000 рублей (HP Proliant G5, Intel Xeon E5430 (2.66GHz, Quad-Core, 12Mb), 8Gb RAM, 2x300Gb SAS HDD, P400i, 512Mb, BBU):
https://www.host-food.ru/tariffs/vydelennyi-server-ds/
Недорогие домены в популярных зонах: https://www.host-food.ru/domains/

Гость
проходил мимо

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение Гость » 2010-04-21 17:17:51

надо сказать заветные слова
ОООО Великий и могучий ProFTP, ты все знаешь, ты все умеешь, ты могуч, прийди к нам
и будет вам счастье

Аватара пользователя
ProFTP
подполковник
Сообщения: 3388
Зарегистрирован: 2008-04-13 1:50:04
Откуда: %&й
Контактная информация:

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение ProFTP » 2010-04-21 18:18:04

:drinks: :-D

тут поблема низкоуровневая, в семафорах в SysV, и я не знаю что это за прогармма, какие графики она строит и как она их строит - надо смотреть...
Pеrl FAQ
perl -e 'print join"",map $$_[rand@$_],([0..9,'a'..'z','A'..'Z'])x30'
ИзображениеИзображение

Гость
проходил мимо

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение Гость » 2010-04-21 18:37:35

ну и что что семафоры?
типа программа не на перле что ли?
отморозился он...

Аватара пользователя
ProFTP
подполковник
Сообщения: 3388
Зарегистрирован: 2008-04-13 1:50:04
Откуда: %&й
Контактная информация:

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение ProFTP » 2010-04-21 19:08:23

ну я имею ввиду что "с ходу" это не слелать...

вот документация ttp://search.cpan.org/~jesse/perl-5.12.0/pod/perlipc.pod#___top и в гугле еще есть...
Pеrl FAQ
perl -e 'print join"",map $$_[rand@$_],([0..9,'a'..'z','A'..'Z'])x30'
ИзображениеИзображение

Гость
проходил мимо

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение Гость » 2010-04-21 19:11:21

ОООО Великий и могучий ProFTP, ты все знаешь, ты все умеешь, ты могуч, прийди к нам
забираю свои слова обратно
не великий и не могучий :sorry:

Аватара пользователя
ProFTP
подполковник
Сообщения: 3388
Зарегистрирован: 2008-04-13 1:50:04
Откуда: %&й
Контактная информация:

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение ProFTP » 2010-04-21 19:12:35

великий и могучий - этот тот делает вместо кого-то его работу? :smile:
Pеrl FAQ
perl -e 'print join"",map $$_[rand@$_],([0..9,'a'..'z','A'..'Z'])x30'
ИзображениеИзображение

Гость
проходил мимо

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение Гость » 2010-04-21 19:17:42

ты смотри какие все стали важные
а ну бери скрипт в зубы и что бы к вечеру уже был фикс!

master_255
рядовой
Сообщения: 16
Зарегистрирован: 2010-04-07 11:02:40

Re: munin-cgi-graph "Result too large"

Непрочитанное сообщение master_255 » 2010-04-21 20:20:53

В общем попробовал я закомментировать эту строчку и посмотреть на что дальше будет ругаться, может уберу все семафоры из скрипта пусть в один поток графики строит.

А он после комментирования взял и заработал, никаких ошибок. Даже не знаю, может рано радуюсь, но пока работает.