Nginx-ru mailing list archive (nginx-ru@sysoev.ru)
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Скрипт конвертации апач евского конфига в nginx фор мат
- To: nginx-ru@xxxxxxxxx
- Subject: Скрипт конвертации апач евского конфига в nginx фор мат
- From: vk@xxxxxxxxxx
- Date: Fri, 7 Mar 2008 16:30:49 +0300 (MSK)
- Importance: Normal
Хочу поделиться с вами тем, что нашел на форумах http://www.directadmin.com
Скрипт используется как скрипт запуска нджинкса и пхп, ну и перепарсивает
конфиг при каждом запуске-перезапуске. #!/usr/local/bin/php -n
<?php
// Configuration Section
$nginx_init = "/etc/init.d/nginx";
$apache_config = "/etc/httpd/conf/httpd.conf";
$da_vhosts = "/etc/httpd/conf/extra/directadmin-vhosts.conf";
$tmp_folder = "/tmp/";
$debug_level = 0; // 0 => FATAL, 1 => WARN, 2 => INFO
$killall_bin = "/usr/bin/killall";
$spawn_bin = "/usr/local/bin/spawn-fcgi";
// Nginx Configuration
$nginx_config = "/usr/local/nginx/conf/nginx.conf";
$nginx_bin = "/usr/local/nginx/sbin/nginx";
$mod_status = true;
// PHP Configuration
$php_childs = 3;
$php_bin = "/opt/php/bin/php-cgi";
$php_startport = 11000;
$users = array();
$action = $argv[1];
$terminate = $argv[2];
if(!isset($argv[1]) || $action == "" || $action == "help") {
echo "Usage: nginx
{start|stop|restart|reload|status|graceful|help|rewrite-ini}\n";
die();
}
if($action == "rewrite-init") {
$fp = fopen($nginx_init, "w+");
$contents = '#!/bin/sh
#
# Name: NginX, tsj5j
#
# Function: Start up NginX which parses Apache Config.
# Usage: Run this script without any parameters to find out.
#
# chkconfig: - 85 15
# description: NginX starter, Apache config parser
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
case "$1" in
stop)
killproc '.basename($nginx_bin).';
killproc '.basename($php_bin).' -9;
;;
restart)
killproc '.basename($nginx_bin).';
killproc '.basename($php_bin).' -9;
;;
reload)
killproc '.basename($nginx_bin).' -HUP;
killproc '.basename($php_bin).' -9;
;;
graceful)
killproc '.basename($nginx_bin).' -HUP;
killproc '.basename($php_bin).' -9;
;;
esac
# Calls external PHP script
'.__FILE__.' $1 false;
exit 0;';
fwrite($fp, $contents);
fclose($fp);
echo "Rewrite completed.\n";
die();
}
if($action == "status") {
checkRunning(true);
die();
}
function checkRunning($verbose = false) {
global $php_bin, $nginx_bin;
exec("ps axfuw | grep ".basename($nginx_bin), $process_list);
if(count($process_list) > 2) $nginx = true; else $nginx = false;
unset($process_list);
exec("ps axfuw | grep ".$php_bin, $process_list);
if(count($process_list) > 2) $php = true; else $php = false;
if($verbose == true) {
if($nginx == true)
info_notice("Nginx is running...");
else
warn_notice("Nginx is not running...");
if($php == true)
info_notice("PHP (FastCGI) is running...");
else
warn_notice("PHP (FastCGI) is not running...");
}
return array($nginx, $php);
}
function substring_between($haystack,$start,$end) {
if (strpos($haystack,$start) === false || strpos($haystack,$end) === false) {
return false;
} else {
$start_position = strpos($haystack,$start)+strlen($start);
$newpage = substr($haystack,$start_position,strlen($haystack)-1);
$end_position = strpos($newpage,$end);
$end_position = $end_position + $start_position;
return
substr($haystack,$start_position,$end_position-$start_position);
}
}
function str_replace_once($needle, $replace, $haystack) {
// Looks for the first occurence of $needle in $haystack
// and replaces it with $replace.
$pos = strpos($haystack, $needle);
if ($pos === false) {
// Nothing found
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
function parseConfig($apache_config, $type="server") {
if(!isset($apache_config)) $apache_config = "/etc/httpd/conf/httpd.conf";
// Main Code
$apache_main = file_get_contents($apache_config);
$apache_main = explode("\n", $apache_main);
// Lets remove all comments for easier parsing
foreach ($apache_main as $key => $value) {
if(strlen(str_replace('#', '', $value)) == strlen($value))
$apache_main_parse .= $value."\n";
}
$apache_main = $apache_main_parse;
unset($apache_main_parse);
// Lets remove extra new lines for easier reading
$apache_main = str_replace("\n\n", "\n", $apache_main);
// Time to do basic parsing and initialization
$apache_main = explode("\n", $apache_main);
$codeblock = false;
$codeblock_no = 0;
foreach ($apache_main as $key => $value) {
if($codeblock == false) {
if(strlen(str_replace('<', '', $value)) != strlen($value))
if(strlen(str_replace('>', '', $value)) != strlen($value))
if(strlen(str_replace('</', '', $value)) == strlen($value))
{
$codeblock = substring_between($value, "<", ">");
$codeblock = explode(" ", $codeblock);
$codeblock = $codeblock[0];
$apache_main_codeblock[$codeblock_no][] = $value;
continue;
}
}
if($codeblock != false) {
if(strlen(str_replace('</'.$codeblock.'>', '', $value)) !=
strlen($value)) {
$codeblock = false;
}
$apache_main_codeblock[$codeblock_no][] = $value;
if($codeblock == false) $codeblock_no++;
continue;
}
if(strlen(str_replace('</', '', $value)) != strlen($value)) {
continue;
}
$apache_main_normal[] = $value;
}
unset($apache_main);
// Now, interpret normal (non-codeblock options)
$skip = 1;
foreach ($apache_main_normal as $key => $value) {
$value = str_replace('"', "", $value);
$value = explode(" ", $value);
// Remove blank elements
foreach ($value as $key2 => $value2) {
if($value2 != "") $value_new[] = $value2;
}
$value = $value_new;
unset($value_new);
if(is_null($value)) continue;
switch ($value[0]) {
case "ServerRoot" : $apache_vars["root_folder"] = $value[1]; break;
case "Listen" : $apache_vars["listen"] = $value[1]; break;
case "LoadModule" :
$apache_vars["modules"][] = array($value[1], $value[2]);
break;
case "User" : $apache_vars["user"] = $value[1]; break;
case "Group" : $apache_vars["group"] = $value[1]; break;
case "ServerAdmin" : $apache_vars["serveradmin"] = $value[1]; break;
case "DocumentRoot" : $apache_vars["docroot"] = $value[1]; break;
case "ErrorLog" : $apache_vars["log"] = array("error", $value[1]);
break;
case "LogLevel" : $apache_vars["errorlog_level"] = $value[1]; break;
case "CustomLog" :
$apache_vars["log"] = array("access", $value[1], $value[2]);
break;
case "DefaultType" : $apache_vars["defaulttype"] = $value[1]; break;
case "Include" : $apache_vars["includes"][] = $value[1]; break;
default : warn_notice($value[0]." cannot be recognised."); break;
}
}
if($type == "vhost") {
foreach($apache_main_codeblock as $key => $value) {
$vhost = "";
unset($ip, $port, $domain, $docroot, $log, $php);
foreach($value as $key2 => $value2) {
$vhost .= $value2."\n";
}
if(strpos($vhost, "VirtualHost") == false) continue;
// IP and Port
$ip = substring_between($vhost, "<VirtualHost ", ">");
$ip = explode(":", $ip);
$port = $ip[1];
$ip = $ip[0];
// Server Name
$domain[] = substring_between($vhost, "ServerName ", "\n");
// Server Aliases
$num_alias = substr_count($vhost, "ServerAlias ");
for($i=0; $i<$num_alias; $i++) {
$alias = substring_between($vhost, "ServerAlias ",
"\n");
$alias = explode(" ", $alias);
$domain[] = $alias[1];
$vhost = str_replace_once("ServerAlias ", "", $vhost);
}
$docroot = substring_between($vhost, "DocumentRoot ", "\n");
// Logging
$num_accesslog = substr_count($vhost, "CustomLog ");
for($i=0; $i<$num_accesslog; $i++) {
$accesslog = substring_between($vhost, "CustomLog ",
"\n");
$accesslog = explode(" ", $accesslog);
$log[] = array("access", $accesslog[0], $accesslog[1]);
$vhost = str_replace_once("CustomLog ", "", $vhost);
}
$log[] = array("error", substring_between($vhost, "ErrorLog ",
"\n"));
// PHP Admin Flag
$num_php = substr_count($vhost, "php_admin_flag ");
for($i=0; $i<$num_php; $i++) {
$php_value = substring_between($vhost, "php_admin_flag
", "\n");
$php_value = explode(" ", $php_value);
$php_value_name = $php_value[0];
unset($php_value[0]);
$php_value = implode(" ", $php_value);
$php[] = array($php_value_name, $php_value);
$vhost = str_replace_once("php_admin_flag ", "",
$vhost);
}
// PHP Admin Value
$num_php = substr_count($vhost, "php_admin_value ");
for($i=0; $i<$num_php; $i++) {
$php_value = substring_between($vhost, "php_admin_value
", "\n");
$php_value = explode(" ", $php_value);
$php_value_name = $php_value[0];
unset($php_value[0]);
$php_value = implode(" ", $php_value);
$php[] = array($php_value_name, $php_value);
$vhost = str_replace_once("php_admin_value ", "",
$vhost);
}
$user = str_replace("/home/", "", $docroot);
$user = explode("/", $user);
$user = $user[0];
$vhost_vars[] = array($ip, $port, $domain, $docroot, $log,
$php, $user);
global $users;
$users[$user] = "";
}
return $vhost_vars;
}
return $apache_vars;
}
function output_nginx($apache_vars, $vhost_vars) {
global $users, $php, $mod_status;
if(isset($apache_vars['user']) && isset($apache_vars['group']))
$nginx[] = "user ".$apache_vars['user']." ".$apache_vars['group'].";";
$nginx[] = "events {";
$nginx[] = "worker_connections 1024;";
$nginx[] = "multi_accept on;";
$nginx[] = "use epoll;";
$nginx[] = "}";
$nginx[] = "http {";
$nginx[] = "include conf/mime.types;";
$nginx[] = "default_type application/octet-stream;";
$nginx[] = "tcp_nopush on;";
$nginx[] = "tcp_nodelay on;";
$nginx[] = "server_names_hash_bucket_size 128;";
$nginx[] = "log_format bytes '".'$bytes_sent'."';";
foreach($vhost_vars as $key => $value) {
$nginx[] = "server {";
$nginx[] = "listen ".$value[1].";";
$domains = implode($value[2], " ");
$nginx[] = "server_name ".$domains.";";
foreach($value[4] as $key2 => $value2) {
if($value2[0] == "access") {
$nginx[] = "access_log ".$value2[1]."
".$value2[2].";";
} elseif($value2[0] == "error") {
$nginx[] = "error_log ".$value2[1]." warn;";
}
}
if($mod_status == true) {
$nginx[] = "location /nginx_status {";
$nginx[] = "stub_status on;";
$nginx[] = "access_log off;";
$nginx[] = "allow all;";
$nginx[] = "}";
}
$nginx[] = "location / {";
$nginx[] = "root ".$value[3].";";
$nginx[] = "index index.html index.htm index.php;";
$nginx[] = "}";
$nginx[] = 'location ~ \\.php$ {';
$nginx[] = "include conf/fastcgi.conf;";
$nginx[] = "fastcgi_pass 127.0.0.1:".$users[$value[6]].";";
$nginx[] = "fastcgi_index index.php;";
$nginx[] = "fastcgi_param SCRIPT_FILENAME
".$value[3].'$fastcgi_script_name;';
$nginx[] = "}";
$nginx[] = "}";
$php[$value[6]] = $value[5];
}
$nginx[] = "}";
return $nginx;
}
function formatOutput($nginx) {
$tabs = "";
foreach($nginx as $key => $value) {
if(strlen(str_replace('{', '', $value)) != strlen($value)) {
$output .= $tabs.$value."\n";
$tabs .= "\t";
continue;
}
if(strlen(str_replace('}', '', $value)) != strlen($value)) {
$tabs = substr($tabs, 0, strlen($tabs)-1);
$output .= $tabs.$value."\n";
continue;
}
$output .= $tabs.$value."\n";
}
return $output;
}
function testConfig($config) {
global $nginx_bin, $nginx_config, $tmp_folder;
$fp = fopen($tmp_folder.basename($nginx_config), "w+");
fwrite($fp, $config);
fclose($fp);
exec($nginx_bin." -t -c ".$tmp_folder.basename($nginx_config)." &>
".$tmp_folder.basename($nginx_config).".out");
$output = file_get_contents($tmp_folder.basename($nginx_config).".out");
@unlink($tmp_folder.basename($nginx_config).".out");
@unlink($tmp_folder.basename($nginx_config));
if(strlen(str_replace('syntax is ok', '', $output)) != strlen($output))
{
return true;
} else {
return $output;
}
}
if($action != "stop") {
$apache_vars = parseConfig($apache_config);
$directadmin_hosts = parseConfig($da_vhosts);
foreach($directadmin_hosts['includes'] as $key => $value) {
$vhost_temp = parseConfig($value, "vhost");
for($i=0; $i<count($vhost_temp); $i++) {
$vhost_vars[] = $vhost_temp[$i];
}
}
foreach($users as $key => $value) {
$users[$key] = $php_startport;
$php_startport++;
}
$nginx = output_nginx($apache_vars, $vhost_vars);
$nginx = formatOutput($nginx);
$test_results = testConfig($config);
if($test_results != true) {
fatal_notice("Generated configuration has an error. Please
report this problem.");
fatal_notice("Error details is as following :");
echo $test_results;
die();
}
$fp = fopen($nginx_config, "w+");
fwrite($fp, $nginx);
fclose($fp);
}
if($terminate != "false") {
if($action == "reload" || $action == "graceful")
exec($killall_bun." -HUP ".basename($nginx_bin));
if($action == "stop" || $action == "restart")
exec($killall_bin." -9 ".basename($nginx_bin));
if($action == "stop" || $action == "restart" || $action == "reload" ||
$action == "graceful")
exec($killall_bin." -9 ".basename($php_bin));
}
sleep(1); // 1 second to stop.
if($action == "start" || $action == "restart")
exec($nginx_bin." -c ".$nginx_config);
if($action == "start" || $action == "restart" || $action == "reload" || $action
== "graceful") {
foreach($users as $key => $value) {
foreach($php[$key] as $key2 => $value2) {
$param .= " -d ".$value2[0]."=".$value2[1];
$param = str_replace("'", '"', $param);
}
$process = popen($spawn_bin." -f '".$php_bin.$param."' -p
".$value." -C ".$php_childs." -u ".$key." -g ".$key."\n", "r");
pclose($process);
unset($param);
}
}
function info_notice($message) {
global $debug_level;
if($debug_level >= 2)
echo date('h:i:s j-m-y').": [INFO] ".$message."\n";
}
function warn_notice($message) {
global $debug_level;
if($debug_level >= 1)
echo date('h:i:s j-m-y').": [WARN] ".$message."\n";
}
function fatal_notice($message) {
global $debug_level;
if($debug_level >= 0)
echo date('h:i:s j-m-y').": [FATAL] ".$message."\n";
}
?>
|