Tripletail

 view release on metacpan or  search on metacpan

lib/Tripletail/MemorySentinel.pm  view on Meta::CPAN

# -----------------------------------------------------------------------------
# Tripletail::MemorySentinel - メモリ使用状況の監視
# -----------------------------------------------------------------------------
package Tripletail::MemorySentinel;
use strict;
use warnings;
use Tripletail;

sub _HOOK_PRIORITY() { 2_000_000 } # 順序は問わない
our $_INSTANCE;

1;

sub _getInstance {
	my $class = shift;

	if(!$_INSTANCE) {
		$_INSTANCE = $class->_new(@_);
	}

	$_INSTANCE;
}

sub __install {
	my $this = shift;

	$TL->setHook('postRequest', _HOOK_PRIORITY, sub { $this->__postRequest });
}

sub _new {
	my $class = shift;
	my $this = bless {} => $class;

	$this->{getmemfunc} = undef; # メモリ使用量を取得する為の関数。'NONE'なら存在しない。
	$this->{getmemfh} = undef;
	$this->{initial} = undef; # 最初のpostRequestの時点でのメモリ使用量
	$this->{permissible} = {}; # {key => size} 用途別のメモリ使用許容量

	$this->setPermissibleSize(_HEAP => 10 * 1024); # 10 MiB
	$this;
}

sub getMemorySize {
	my $this = shift;

	if(!defined($this->{getmemfunc})) {
		my $uname = eval {
			$^O eq 'MSWin32' and die 'MSWin32 is not supported';
			`uname -sr`;
		};
		if($@) {
			$TL->log(__PACKAGE__, "Failed to exec `uname -sr`. [$@]");
			$uname = $^O;
		} else {
			$uname =~ s/^\s*|\s*$//g;
            
            if ($TL->INI->get(TL => memorylog => 'leak') eq 'full') {
                $TL->log(__PACKAGE__, "Uname is [$uname]");
            }
		}

		if($uname =~ m/^Linux [2-4]\./) {
			$this->{getmemfunc} = \&__getMemLinux2;
		} else {
			$TL->log(__PACKAGE__, "We can't get memory usage on [$uname] currently...");
			$this->{getmemfunc} = 'NONE';
		}
	}

	if(ref($this->{getmemfunc})) {
		$this->{getmemfunc}($this);
	} else {
		0;
	}
}

sub setPermissibleSize {
	my $this = shift;
	my $key = shift;
	my $size = shift;

	$this->{permissible}{$key} = $size;
	$this;
}

sub getTotalPermissibleSize {
	my $this = shift;

	my $total = 0;
	foreach(values %{$this->{permissible}}) {
		$total += $_;
	}



( run in 1.284 second using v1.01-cache-2.11-cpan-8f98c5d2c55 )