
Heyecan devam ediyor:-)
Bu bölümde:
- Bir önceki sürümde eksik kalan $_SERVER['REMOTE_ADDR'] ve $_SERVER['REMOTE_PORT'] halloldu.
- .ConfigHandler.php isimli dosyayı kullanarak Apache’de .htaccess ile çözülen işler saf PHP ile çözülür hale geldi. Bir rewrite örneğini yazının devamında bulabilirsiniz.
- Benchmark sevenler: Bu bölümde istemediğiniz kadar benchmark var;-) Ayrıca, benchmark işleri küçük bir Python kodu yardımıyla otomatik hale getirildi.
Bir önceki yazımda bir web sunucusunda bulunması gereken temel özelliklerin çoğuna sahip, PHP çalıştıran bir web sunucusunu, yine PHP kullanarak hayata geçirebilmiş ve adını da Azra Erhat’ın anısına “Azra” koymuştum. Yukarıda gördüğünüz logo için ise, bir bakışta anlayabileceğiniz gibi hiç uğraşmadım, çünkü uğraşsam da daha iyisini yapamayacağımı biliyorum! Hayırsever bir arkadaş düzgün bir logo yapabilirse seve seve kullanırım. Şimdiki logo basitçe Göktürk alfabesi kullanarak “Azra” stringinden ibaret.
Bu sürümde yeni ne var?
- Artık supergloballer ($_POST, $_GET, $_REQUEST, $_COOKIE, $_SERVER) tam olarak destekleniyor.
- .ConfigHandler.php diye bir dosya icat ettim. Azra bu dosya var mı diye bakıyor, varsa içeri alıyor ve ConfigHandler sınıfını çağırıyor. Aşağıdaki dosyada da görebileceğiniz gibi, örneğin “url rewrite” işi çocuk oyuncağı.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php
class ConfigHandler
{
public $url = NULL;
public function __construct ($input)
{
$this->azraRewrite($input);
}
public function azraRewrite ($input)
{
$candidate = getcwd() . $input;
if(!is_file($candidate) && !is_dir($candidate)) $this->url = '/router.php?' . $input;
else $this->url = $input;
}
} |
- Web sunucumuzun yeni sürümü ise şu şekilde:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
| <?php
/**
* Azra Web Server
*
* Web Server coded in pure PHP
*
* @package Azra Web Server
* @author Can Ince
* @copyright Copyright (c) 2010, Logikit / Can Ince.
* @version 0.0.2
* @license http://www.opensource.org/licenses/mit-license.php
* @link http://can.logikit.net
*/
set_time_limit(0);
interface server
{
public function setWebRoot ($path);
public function setPort ($port);
public function serve ();
}
final class webserver implements server
{
private $_port , $_webroot , $_queryString , $_webRootWithoutSlash, $_input , $_file , $_verbose , $_remoteAddr , $_remotePort;
public function __construct ()
{
$this->_verbose = 0;
}
public function setPort ($port)
{
$this->_port = $port;
}
public function verbose ()
{
$this->_verbose = 1;
}
public function setWebRoot ($path)
{
$this->_webroot = $path . '/';
$this->_webRootWithoutSlash = $path;
}
private function _mimeHandler ($input)
{
$fileinfo = pathinfo($input);
switch ($fileinfo['extension'])
{
case 'png':
$mime = "text/png";
break;
case 'jpg':
case 'jpeg':
$mime = "text/jpeg";
break;
case 'gif':
$mime = "text/gif";
break;
case 'css':
$mime = "text/css";
break;
case 'swf':
$mime = "application/x-shockwave-flash";
break;
default:
$mime = "text/html; charset=UTF-8";
}
return $mime;
}
private function _handleCode ($contents)
{
//eval() edilecek kodun başında <?php ya da <? varsa çakar. halledelim.
$contents = trim($contents);
if(substr($contents , 0 , 5) == '<?php')
{
$contents = substr($contents , 5);
}
elseif(substr($contents , 0 , 2) == '<?')
{
$contents = substr($contents , 2);
}
return $contents;
}
private function _parseGet ($str)
{
$_GET = array();
$array = explode('&' , $str);
foreach($array as $requestItem)
{
$itemArray = explode('=' , $requestItem);
if(!empty($itemArray[0])) $_GET[$itemArray[0]] = $itemArray[1];
}
unset($_GET['hyperTextServer_php']); //bunu $_GET'e enjekte ediyor. neden, bilmiyorum...
}
private function _parsePost ($str)
{
$_POST = array();
$array = explode('&' , $str);
foreach($array as $requestItem)
{
$itemArray = explode('=' , $requestItem);
if(!empty($itemArray[0])) $_POST[$itemArray[0]] = $itemArray[1];
}
}
private function _parseCookie ($str)
{
$_COOKIE = array();
$array = explode('; ' , $str);
foreach($array as $requestItem)
{
$itemArray = explode('=' , $requestItem);
if(!empty($itemArray[0])) $_COOKIE[$itemArray[0]] = $itemArray[1];
}
}
private function _parseRequest ($str)
{
$_SERVER = array();
$lines = explode("\n" , $str);
$rawData = explode(' ' , $lines[0]);
$_SERVER['REQUEST_METHOD'] = $rawData[0];
if($_SERVER['REQUEST_METHOD'] == 'POST') $this->_parsePost (end($lines));
$_SERVER['PHP_SELF'] = $this->_webRootWithoutSlash . $rawData[1];
$_SERVER['HTTP_HOST'] = substr($lines[1] , 6);
$_SERVER['HTTP_USER_AGENT'] = substr($lines[2] , 12);
$_SERVER['HTTP_ACCEPT'] = substr($lines[3] , 8);
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = substr($lines[4] , 17);
$_SERVER['HTTP_ACCEPT_ENCODING'] = substr($lines[5] , 17);
$_SERVER['HTTP_ACCEPT_CHARSET'] = substr($lines[6] , 16);
$_SERVER['HTTP_KEEP_ALIVE'] = substr($lines[7] , 12);
$_SERVER['HTTP_CONNECTION'] = substr($lines[8] , 12);
if(strstr($lines[9] , 'Referer'))
{
$_SERVER['HTTP_REFERER'] = substr($lines[9] , 9);
$_SERVER['HTTP_COOKIE'] = substr($lines[10] , 8);
}
else $_SERVER['HTTP_COOKIE'] = substr($lines[9] , 8);
if(!empty($_SERVER['HTTP_COOKIE'])) $this->_parseCookie ($_SERVER['HTTP_COOKIE']);
$_SERVER['SERVER_SIGNATURE'] = ' <address>Azra/0.0.1 Server at ' . $_SERVER['HTTP_HOST'] . ' Port ' . $this->_port . '</address>';
$_SERVER['SERVER_SOFTWARE'] = 'Azra/0.0.1';
$_SERVER['DOCUMENT_ROOT'] = $this->_webroot ;
$_SERVER['SCRIPT_FILENAME'] = $this->_webRootWithoutSlash . str_replace('./' , '/' , $this->_file );
$_SERVER['REQUEST_TIME'] = time();
$_SERVER['REMOTE_ADDR'] = $this->_remoteAddr ;
$_SERVER['REMOTE_PORT'] = $this->_remotePort ;
if(!empty($this->_queryString )) $_SERVER['QUERY_STRING'] = $this->_queryString ;
}
private function _handle404 ()
{
return "<title>UHU 404</title><h2>UHU 404</h2>Iın-ıın-ıın-ıın-cav-cav-cav-cav-oooooo - oooooo - zört - zört - zört -zört (araba alarmı efekti) Çok afedersin müdürüm ama yok öyle bir dosya.";
}
public function serve ()
{
$socket = @socket_create_listen($this->_port );
if (!$socket)
{
echo "Soket olamiyor!\n";
exit;
}
while (1) //daire-i ilanihaye!
{
$client = socket_accept($socket);
socket_getpeername($client , $remoteAddr , $remotePort);
$this->_remoteAddr = $remoteAddr;
$this->_remotePort = $remotePort;
$input = $this->_input = trim(socket_read ($client, 4096));
if($this->_verbose == 1) echo $input;
$input = explode(" " , $input);
$input = $input[1];
$dirName = dirname(__FILE__);
$directoryConfigCandidate = $dirName . '/.ConfigHandler.php';
if ($directoryConfigCandidate && is_readable($directoryConfigCandidate))
{
require_once ($directoryConfigCandidate);
if(class_exists('ConfigHandler'))
{
$configHandler = new ConfigHandler ($input);
//konvansiyonumuza göre rewrite işi $configHandler'ın url özelliğinde bulunmalı
if($configHandler->url != NULL) $input = $configHandler->url;
}
}
$mime = $this->_mimeHandler ($input);
if ($input == "" || $input == '/')
{
$input = "/index.html";
}
$input = ".$input";
$inputArray = explode('?' , $input);
$this->_file = $inputArray[0];
$input = $this->_webroot . $this->_file ;
if (file_exists($input) && is_readable($input))
{
if($this->_verbose == 1) echo "Dosya: $input\n";
$contents = file_get_contents($input);
if(strstr($input , '.php'))
{
$this->_queryString = $inputArray[1];
$this->_parseGet ($this->_queryString );
$this->_parseRequest ($this->_input );
$_REQUEST = array_merge($_GET , $_POST , $_COOKIE);
$contents = $this->_handleCode ($contents);
//PHP çalıştıktan sonra sonucu echo etmesini değil, $contents stringine atmasını istiyoruz.
ob_start();
eval($contents);
//gidip $contents'in üstüne yazmak doğru alışkanlık değil ama yeni değişken register etmek istemiyorum
$contents = ob_get_contents();
ob_end_clean();
}
$output = "HTTP/1.0 200 OK\r\nServer: HyperTextServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents";
}
else
{
$contents = $this->_handle404 ();
$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: HyperTextServer\r\nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n$contents";
}
socket_write($client, $output);
socket_close ($client);
}
socket_close ($socket);
}
}
$server = new webserver ();
$server->setWebRoot('/var/www/webserver');
//$server->verbose(); //ayrıntıları stdout'a echo et.
$server->setPort(8008);
$server->serve(); |
konsoldan
şeklinde çağırmak suretiyle çalıştırıyoruz.
- Benchmarklar:
Benchmark işleri için aşağıdaki test.php dosyasını kullandım. Göreceğiniz gibi bir for döngüsüne girip 10001′e kadar saymaktan ve çalışma süresini bir metin dosyasına yeni satır olarak yazmaktan başka bir iş yapmıyor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php
$start = microtime(1);
for($n = 0; $n <= 10000; $n++)
{
//bir şey yapma. yalnızca say...
}
$end = microtime(1);
$elapsed = $end - $start;
echo "<br/>vakit(ms): $elapsed";
$fileHandle = fopen('serverBenchmark.txt' , 'a');
fputs($fileHandle , $elapsed . "\n");
fclose($fileHandle); |
Testleri otomatik hale getirebilmek için de, en kolayıma Python geldiği için kısa ve basit bir kod yazdım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import urllib2
from threading import Thread
class testSuite:
def testConnection(self , url , thread = 0):
page = urllib2.urlopen(url)
data = page.read()
page.close()
print("Thread:%d" % thread)
def simpleConnection(self , url , tourNum):
for i in range(tourNum):
self.testConnection(url)
def threadedConnection(self , url , tourNum , threadNum):
for i in range(tourNum):
myThread = i % threadNum
t = Thread(target=self.testConnection , args=(url , myThread))
t.start()
myTestSuite = testSuite()
#myTestSuite.simpleConnection('http://localhost:8008/test.php' , 1000)
#myTestSuite.simpleConnection('http://localhost/webserver/test.php' , 1000)
myTestSuite.threadedConnection('http://localhost:8008/test.php' , 1000 , 10) |
Bu kodu ‘benchmark.py’ adıyla kaydedip konsoldan
1
| time python benchmark.py |
ile çağırıyoruz ve böylece ne kadar sürede çalıştığını ayrıntılarıyla okuyabiliyoruz. Benim apache için webroot’um /var/www. Azra için webroot’um ise /var/www/webserver. localhost:8008′den Azra’ya, localhost:80 (varsayılan port) adresinden Apache’ye ulaşabiliyoruz.
Bunların yanında, bir tür “pseudo-multi-processing” elde edebilmek için aşağıdaki PHP kodunu kullandım:
1 2 3 4 5 6 7 8 9 10
| <?php
set_time_limit(0);
include ("thread.php");
$t2 = new Thread ("azra.php");
while ($t2->isActive())
{
echo $t2->listen();
}
$t2->close(); |
Bu kodu da konsoldan
ile çağırıyoruz. Göreceğiniz gibi server.php, yeni bir PID ile bildiğimiz, sevdiğimiz azra.php’yi çağırıyor.
Kullandığımız üçüncü parti PHP sınıfı (thread.php) ise aşağıda
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| <?php
/**
* original version can be found at http://www.alternateinterior.com/2007/05/multi-threading-strategies-in-php.html
* This version is slightly modified to run with PHP 5 - Can Ince
*/
class Thread
{
var $pref ; // process reference
var $pipes; // stdio
var $buffer; // output buffer
public function __construct ($file)
{
$this->pref = 0;
$this->buffer = "";
$this->pipes = (array)NULL;
$descriptor = array (0 => array ("pipe", "r"), 1 => array ("pipe", "w"), 2 => array ("pipe", "w"));
$this->pref = proc_open ("php $file ", $descriptor, $this->pipes);
stream_set_blocking ($this->pipes[1], 0);
}
public function isActive ()
{
$this->buffer .= $this->listen();
$f = stream_get_meta_data ($this->pipes[1]);
return !$f["eof"];
}
public function close ()
{
$r = proc_close ($this->pref);
$this->pref = NULL;
return $r;
}
public function tell ($thought)
{
fwrite ($this->pipes[0], $thought);
}
public function listen ()
{
$buffer = $this->buffer;
$this->buffer = "";
while ($r = fgets ($this->pipes[1], 1024))
{
$buffer .= $r;
}
return $buffer;
}
public function getError ()
{
$buffer = "";
while ($r = fgets ($this->pipes[2], 1024))
{
$buffer .= $r;
}
return $buffer;
}
} |
Benim lokal sistemimde benchmarklar aşağıdaki gibi çıktı:
—-Azra——–
0.00114736318588 – 10 farklı thread – 100 tur
real 0m0.334s
user 0m0.056s
sys 0m0.020s
0.0180547189713 – 10 farklı thread – 1000 tur
real 0m2.982s
user 0m0.192s
sys 0m0.056s
0.00165226125717 – 100 farklı thread – 1000 tur
real 0m5.251s
user 0m0.196s
sys 0m0.056s
0.00191986322403 – 10 farklı thread – 10000 tur
real 0m38.442s
user 0m1.640s
sys 0m0.608s
0.00110848665237 – tek thread – 100 tur
real 0m0.354s
user 0m0.092s
sys 0m0.068s
0.0111782860756 – tek thread – 1000 tur
real 0m3.421s
user 0m0.744s
sys 0m0.424s
0.00116171479225 – tek thread – 1000 tur (pseudo-multiprocess destekli)
real 0m4.293s
user 0m0.792s
sys 0m0.384s
0.00114714858532 – tek thread – 10000 tur
real 0m37.138s
user 0m8.209s
sys 0m4.280s
—-Apache——-
0.00138350725174 – 10 farklı thread – 100 tur
real 0m0.360s
user 0m0.068s
sys 0m0.028s
0.0136778688431 – 10 farklı thread – 1000 tur
real 0m3.524s
user 0m0.176s
sys 0m0.060s
0.00142541861534 – 100 farklı thread – 1000 tur
real 0m4.030s
user 0m0.144s
sys 0m0.040s
0.00147548000813 – 10 farklı thread – 10000 tur
real 0m46.358s
user 0m1.476s
sys 0m0.496s
0.00153880357742 – tek thread – 100 tur
real 0m0.499s
user 0m0.140s
sys 0m0.068s
0.0135918140411 – tek thread – 1000 tur
real 0m3.824s
user 0m0.972s
sys 0m0.504s
0.0135918140411 – tek thread – 10000 tur
real 1m7.090s
user 0m9.149s
sys 0m4.984s
Benchmarklara hızlıca göz attığımızda fark edebileceğimiz gibi, Azra multi-threaded isteklerde yavaş kalıyor. Bu durumu yeni Ubuntu çıktıktan sonra, PHP’yi pcntl ile derleyerek aşabilmeyi umuyorum. Diğer benchmarkların hepsinde Azra, Apache’ye fark atıyor.
Yeni bölümde yeni maceralarla görüşmek üzere:)