Memória használat ellenőrzés linuxon

Ez egy élesben is működő megoldás, amit elszabaduló weboldalak és egyebek miatt kellett létrehozni, hogy kiderüljön pontosan mi okozza az adott szerveren a memória elfogyását és ezzel a szerver kifekvését. Eredetileg a coderprofile-ra dobtam fel ezt a kódot, így a kódhoz tartozó leírás is angolul következik:

Description

This is a bash script that i made when i was bored on a saturday night.

There were memory issues with one of our systems and we couldn’t debug it, because nobody really monitored the server, we just know that in 24hours the memory fills and the server dies. So i created this script to warn me when the memory usage goes up and list me the processes with the highest memory usage.

This wasn’t a solution for the problem. :-) Later i manually checked the server in every hour, listed the processes with ‘ps’, etc. Then i found the problem. We had a cronjob that opened a link with lynx in every 5 minutes, but lynx never exited, so in every 5 minutes the processes were groving with one more lynx and the first version of this script couldn’t detect it, because we were waiting for a huge memory usage of one process, but the cronjob made a many processes with low memory usage, so the server died again. :-)

Then i developed this script to the version as you can see now, this monitors the whole memory usage too, counts with the cached memory size and else. So now it can really warn you if the free memory is running out.

In the first section of the script you can find the Config, where you should adjust the values to your system, especially for the limit_vsz, limit_rss, i just set them based on what i saw in ‘top’.

Also if you disable the mail_cmd then email won’t be send, but you will get a nice output in the console, but you may check the warn email too. ;-)

PS.: i have some trouble with the mail send part, it will be better to set an email address and subject in the config and then use it in the end of the script for the mail send, but on our server it made a lot of errors i couldn’t make out, althought i copied solutions from tutorials.. so that’s why i made a mail_cmd config variable instead.

Technical

OS: Linux (tested on Debian 3)
Requirements: probably nothing more than a Linux server has already.
Installation: it should be runned as a cronjob, although it has a nice console output.
Setup: in the first (config) section, the variables should be changed to suit your needs, especially the mail_cmd that will be used to send the warning email (if needed).

Config variables and meanings:

  • mail_cmd – command to send email
  • limit_vsz – virtual memory usage size limit per process (in kilobyte)
  • limit_rss – normal memory usage size limit per process (in kilobyte)
  • limit_warning – percentage of the used memory limit -> warn email send
  • limit_critical – percentage of the used memory limit -> critical warn email send
  • limit_report_lines – number of top memory using processes to list in email
  • report_file – here will be the contents of the email generated
  • memget_file – a temporary file to store data returned be ‘free’

Cron line for running the script every 5 minute (ignoring console output):

*/5 * * * * bash /path/to/file/check_memory_usage.sh &> /dev/null

Source code

#!/bin/bash
#############################################################################
# Check memory usage script                                                 #
# This script will check for the highest virtual and physical memory usage. #
# If they exceed a given limit then a report will be sent to a given email. #
# Written by: Tommey <http://coderprofile.com/coder/Tommey>  @ 2009.02.27   #
#############################################################################
 
# Config - set mail sending command, limits (in kB) , report tmp file
mail_cmd="mail monitor@email-address.com -s MemUsageCheck"
limit_vsz=20000  # in kB
limit_rss=10000  # in kB
limit_warning=90  # in %
limit_critical=95 # in %
limit_report_lines=10
report_file="/tmp/check_mem_usage_report"
memget_file="/tmp/check_mem_usage_get"
 
# Init
echo "---------------------------"
echo "Check memory usage (script)"
echo "---------------------------"
send_email=0
 
echo "Memory Usage Statistics (MB)" > $report_file
free -m -t > $memget_file
get_memory=`cat $memget_file | head -2 | tail -1 | awk '{print " Memory: "$2"\t"$3"\t"$4"\t"$7}'` 
get_swap=`cat $memget_file | head -4 | tail -1 |  awk '{print " Swap:   "$2"\t"$3"\t"$4}'`
get_total=`cat $memget_file | tail -1 | awk '{print " Total:  "$2"\t"$3"\t"$4}'`
get_max=`cat $memget_file | tail -1 | awk '{print $2}'`
get_total_used=`cat $memget_file | tail -1 | awk '{print $3}'`
get_cached=`cat $memget_file | head -2 | tail -1 | awk '{print $7}'`
get_real_used=`printf "%.0lf" $(echo "scale=4; $get_total_used-$get_cached" | bc)`
get_limit_warning=`printf "%.0lf" $(echo "scale=4; $get_max*$limit_warning/100" | bc)`
get_limit_critical=`printf "%.0lf" $(echo "scale=4; $get_max*$limit_critical/100" | bc)`
get_usage_percent=`printf "%0.2lf" $(echo "scale=4; $get_real_used/$get_max*100" | bc)`
get_physical=`cat $memget_file | head -2 | tail -1 | awk '{print $3" "$2" "$7}'` 
get_virtual=`cat $memget_file | head -4 | tail -1 |  awk '{print $3" "$2}'`
 
echo -n "Checking total memory usage..."
if [ $get_limit_warning -lt $get_real_used ] && [ $get_real_used -lt $get_limit_critical ] 
then
    echo "WARNING, usage is above $limit_warning% -> $get_usage_percent%"
    echo " " >> $report_file
    echo " WARNING - Total memory usage is above $limit_warning%!" >> $report_file
    echo " " >> $report_file
    let send_email+=1
elif [ $get_limit_critical -lt $get_real_used ] 
then
    echo "CRITICAL, usage is above $limit_critical% -> $get_usage_percent%"
    echo " " >> $report_file
    echo " CRITICAL - Total memory usage is above $limit_critical%!" >> $report_file
    echo " " >> $report_file
    let send_email+=1
else
    echo "OK, usage: $get_usage_percent% - $get_real_used MB / $get_max MB"
    printf " - Physical: %3d MB / %3d MB, cached: %d MB\n" $get_physical
    printf " - Virtual:  %3d MB / %3d MB\n" $get_virtual
fi
echo "        Total   Used    Free   Cached" >> $report_file
echo "$get_memory" >> $report_file
echo "$get_swap" >> $report_file
echo "$get_total" >> $report_file
echo " " >> $report_file
 
# Check virtual memory usage
max_vsz=`ps axo vsz --sort -vsz | head -2 | tail -1`
report_vsz=`ps axo pid,pcpu,vsz,rss,comm,cmd --sort -vsz | head -$(($limit_report_lines+1))`
 
echo -n "Checking virtual memory usage..."
if [ $max_vsz -gt $limit_vsz ] 
then
    echo "EXCEEDED with size: $(($max_vsz-$limit_vsz)) kB, limit: $limit_vsz kB"
    echo "Top $limit_report_lines processes by Virtual Memory Usage (limit: $limit_vsz kB)" >> $report_file
    echo "$report_vsz" >> $report_file
    echo " " >> $report_file
    let send_email+=1
else
    echo "OK - max: $max_vsz kB, limit: $limit_vsz kB"
fi
 
# Check physical memory usage
max_rss=`ps axo rss --sort -rss | head -2 | tail -1`
report_rss=`ps axo pid,pcpu,vsz,rss,comm,cmd --sort -rss | head -$(($limit_report_lines+1))`
 
echo -n "Checking physical memory usage..."
if [ $max_rss -gt $limit_rss ] 
then
    echo "EXCEEDED with size: $(($max_rss-$limit_rss)) kB, limit: $limit_rss kB"
    echo "Top $limit_report_lines processes by Physical Memory Usage (limit: $limit_rss kB)" >> $report_file
    echo "$report_rss" >> $report_file
    let send_email+=1
else
    echo "OK - max: $max_rss kB, limit: $limit_rss kB"
fi
 
# Check if report created and send
if [ $send_email -gt 0 ] 
then
    echo "$send_email check(s) FAILED!"
    echo -n "Sending notify email..."
    $mail_cmd < $report_file
    echo "DONE."
else
    echo "All checks PASSED!"
fi
 
rm -f $report_file

PHP vs C ciklus futási idő

Sokat foglalkoztat az optimalizálás dolga, s most azon gondolkodtam, hogy mikor éri meg egy php kódot átvinni natív környezetbe? Például mi van, ha 1 milliárd adaton kell végig vergődnünk? Persze jó esetben, ha adatokon kell dolgozni az egy adatbázis dolga, melyet erre találtak ki, így ilyen szempontból az alábbi kód csak érdeklődés főként. :)

A script végén egy próba futás eredményei olvashatóak.. lehet megpróbálni megmagyarázni a dolgot, én nem találtam rá elfogadható magyarázatot – vártam, hogy a C lesz gyorsabb, de hogy ennyivel?! Miért?

#!/usr/bin/php
<?php
	// TESTING SPEED of PHP and C for cycle
	$TESTCOUNT = 10;
	$Mcycles = 1000000000; // 1 billion
	$SUMphp = 0;
	$SUMc = 0;
 
	for($k=0;$k<$TESTCOUNT;$k++) 
	{
		echo "--- TEST No.".($k+1)."--------------------\n";
 
		$start = microtime(true); // START PHP TEST
 
		for($i=0;$i<$Mcycles;$i++);
 
		$end=(microtime(true)-$start); // END PHP TEST
 
		$SUMphp+=$end;
		echo " PHP run time for ".($Mcycles/1000000)."M cycles: ".$end."\n";
 
		$start = microtime(true); // START C TEST
 
		shell_exec("./cprog $Mcycles");
		/* CODE FOR cprog.c:
		  #include <stdio.h>
		  int main(int argc, char *argv[]) {
			  int i=0, mcycles=0;
			  mcycles = atoi(argv[1]);
			  for(i=0;i<mcycles;i++);
			  return 0;
		  }
		*/
 
		$end=(microtime(true)-$start); // END C TEST
 
		$SUMc+=$end;
		echo " C run time for ".($Mcycles/1000000)."M cycles: ".$end."\n";
	}
 
	echo "+++ Run time average for $TESTCOUNT test +++\n";
	echo "+ PHP: ".($SUMphp/$TESTCOUNT)."\n";
	echo "+ C: ".($SUMc/$TESTCOUNT)."\n";
	echo "+ C is ".(($SUMphp/$TESTCOUNT)/($SUMc/$TESTCOUNT))." times faster than PHP!\n";
	echo "+++ End of Test +++\n\n";
	// END of tests
 
	/* RESULT:
	--- TEST No.1--------------------
	PHP run time for 1000M cycles: 154.275972128
	C run time for 1000M cycles: 2.31521296501
	--- TEST No.2--------------------
	PHP run time for 1000M cycles: 153.671184063
	C run time for 1000M cycles: 2.37220811844
	--- TEST No.3--------------------
	PHP run time for 1000M cycles: 155.169855118
	C run time for 1000M cycles: 2.36763596535
	--- TEST No.4--------------------
	PHP run time for 1000M cycles: 154.442512989
	C run time for 1000M cycles: 2.51379799843
	--- TEST No.5--------------------
	PHP run time for 1000M cycles: 154.667973042
	C run time for 1000M cycles: 2.4199180603
	--- TEST No.6--------------------
	PHP run time for 1000M cycles: 155.01296711
	C run time for 1000M cycles: 2.32301092148
	--- TEST No.7--------------------
	PHP run time for 1000M cycles: 155.053942204
	C run time for 1000M cycles: 2.34866404533
	--- TEST No.8--------------------
	PHP run time for 1000M cycles: 155.172408104
	C run time for 1000M cycles: 2.3524749279
	--- TEST No.9--------------------
	PHP run time for 1000M cycles: 154.056202888
	C run time for 1000M cycles: 2.39964699745
	--- TEST No.10--------------------
	PHP run time for 1000M cycles: 154.065726042
	C run time for 1000M cycles: 2.35821318626
	+++ Run time average for 10 test +++
	+ PHP: 154.558874369
	+ C: 2.3770783186
	+ C is 65.0205225295 times faster than PHP!
	+++ End of Test +++
	*/
?>

Tiszta víz vagy kóla?

A vízről:
Az emberek 55-65 %-a krónikusan vízhiányos. Az emberek 37%-ánál a szomjúságérzet annyira gyenge, hogy gyakran összetévesztik az éhségérzettel, ezért akkor is esznek, amikor csak egy pohár vizet kellene inniuk – sokan ezért híznak el.
A Washingtoni Egyetem felmérése szerint egy pohár víz maradandóan csökkentette a diétázók 100 %-ának éhségérzetét.
A nappali fáradtság elsőszámú okozója a vízhiány. Folyamatban lévő tanulmányok kimutatják, hogy a hát- és izületi fájdalmakban szenvedők 80 %-ánál naponta 8-10 pohár víz csökkenti a fájdalmakat. Már 2 % folyadékvesztés megzavarhatja a rövidtávú emlékezetet, nehézségeket okozhat az alapműveletek elvégzésénél, összpontosítási zavarokat egy képernyő vagy egy kinyomtatott oldal felfogásánál.
Naponta 5 pohár víz elfogyasztása 45 %-kal csökkenti a vastagbélrák veszélyét, a mellrákét 79 %-kal és 50 %-kal kevesebb a rizikó a hólyagrákra.
Tényleg annyi vizet iszol, mint amennyi szükséges lenne?
Általában 8-10 pohár víz minden nap elengedhetetlen!!

A Coláról:
Vizsgáljuk meg a Coca-Cola-t:
Az USA több államában a rendőrség baleseti helyszínelői 2 gallon (kb. 7 liter) Cola-t visznek magukkal, hogy a baleseteknél az úttestre folyt vért azzal távolítsák el. Ha egy steak-et egy tálba tesznek és Cola-val leöntik, két nap alatt feloldódik. A WC-kagyló tisztítása: önts bele egy dobozos Cola-t a kagylóba és hagyd ezt az igazi(?) csodaszert(?) egy óráig hatni, utána öblítsd le. A kagyló maradéktalanul tiszta lesz. Az autóakkumulátor pólusairól könnyedén eltávolíthatod a korróziót,ha egy doboz Cola-t ráöntesz. Figyeld, ahogy pezseg. Egy berozsdásodott csavart könnyen meglazíthatsz, ha egy pár percig egy Cola-ba áztatott rongyot teszel rá. Ha kenőanyagokat akarsz eltávolítani egy szövetből, önts bele a mosógépbe a mosószer mellé egy doboz Cola-t, és futtasd le a programot. Eltávolítja a szélvédő szennyeződéseit is.

Hasznos információ:
A Cola aktív hatóanyaga a foszforsav, melynek pH értéke 2,8. Egy vasszöget négy nap alatt old fel. A foszforsav kioldja a csontokban lévő kalciumot és hozzájárul a csontritkulás kialakulásához. A Coca-Cola szirupot koncentrált formában szállító tartálykocsikat különösen korrodáló, veszélyes anyagokat jelző táblával kell ellátni.
A Cola-t már 20 éve használják a teherautók motorterének tisztítására!

Szóval, mit szeretnél inkább, egy pohár tiszta vizet, vagy egy Cola-t?

Cinema 4D

Egy kis új régiséggel tudok szolgálni. Feltámasztottam a Cinema4D-s oldalam, amire az általam C4D-ben készült képeket tettem ki, egy két kisebb videó is készült, ezeket ugyan nem tettem fel az oldalra :) Ha valaki foglalkozik ezzel a programmal és csinált már szép képeket, akkor a hozzászólásokban hagyjon egy megjegyzést róla :)

Főleg a matrix extrude nevű művelettel szórakoztam, amivel egészen érdekes formákat lehet kihozni, majd egy hyperNURBS objektumba tettem őket, hogy szép ívesek legyenek, aztán az alapmintákból kerestem valami jót hozzá, főként az elektron tetszik :) Illetve foglalkoztam üvegekkel és tükrökkel is, ezzel a két ‘mintával’ egészen bámulatos képeket lehet összehozni. Ezek után az anyagok után még a metálfényű kreációk néznek ki mesésen :) persze azok is tükrözve, ha lehet üvegfal mögött, vagy üvegtestbe zárva :]

Sajnos még időm nem engedte, hogy komolyabban belemártsam magam a különböző testek kialakításába, de a jövőben tervezem ennek is a megismerését, akinek van valami jó segédanyaga, például, hogy hogy csináljunk embert egy hengerből vagy hasonlók azokat szívesen venném és szerintem más látogatók is :)