2012年5月29日 星期二

在 Apache 伺服器上使用 memcached ( LAMP 優化 )


CentOS 5.8 升級 Apache

因為 mod_memcached_cache 這個 Apache模組,僅支援 2.2.4 之後的版本方可使用,
CentOS 5.8 的預設內建的 Apache 版本為 2.2.3-xx.
故無法使用 memcached 的外掛模組.需透過下方網站所提供的方式,
透過YUM的方式將 Apache 升級至2.2.22的版本.方可啟用  memcached 功能.


http://www.jasonlitka.com/yum-repository/

rpm --import http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka
vi /etc/yum.repos.d/utterramblings.repo
[utterramblings]
name=Jason's Utter Ramblings Repo
baseurl=http://www.jasonlitka.com/media/EL$releasever/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka

RHEL 5 / CentOS 5 :
rpm --import http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
httpd upgrade to 2.2.22
#yum upgrade --enablerepo=utterramblings httpd*
#yum upgrade --enablerepo=utterramblings mod_*

Source

#wget http://apache.stu.edu.tw//httpd/httpd-2.2.22.tar.gz
#tar -zvxf  http://apache.stu.edu.tw//httpd/httpd-2.2.22.tar.gz

Install apr_memcache

#wget http://www.outoforder.cc/downloads/apr_memcache/apr_memcache-0.7.0.tar.bz2
#tar -jvxf apr_memcache-0.7.0.tar.bz2 
#cd  apr_memcache-0.7.0/
#./configure --prefix=/usr/local/ --exec-prefix=/usr/local/
#make
#make install

Install mod_memcached_cache

#wget http://modmemcachecache.googlecode.com/files/mod_memcached_cache-0.1.0.tar.bz2
#tar -jxvf mod_memcached_cache-0.1.0.tar.bz2
#cd mod_memcached_cache-0.1.0
#CFLAGS="-I/usr/local/src/httpd-2.2.22/modules/cache/" ./configure --with-apxs=/usr/sbin/apxs  --with-apr-memcache=/usr/local/
#make
#make install
....
   * Apache Modules Directory:    /usr/lib/httpd/modules
....

讓 php 支援 memcached & memcache

yum install    --enablerepo=remi memcache*
yum install    --enablerepo=remi libmemcached*
yum install    --enablerepo=remi php-pecl-memcached
yum install    --enablerepo=remi php-pecl-memcache

[root@apache]# rpm -qa | grep mem
php-pecl-memcached-2.0.1-1.el5.remi
libmemcached-1.0.4-1.el5.remi
libmemcached-devel-1.0.4-1.el5.remi
memcached-1.4.5-2.el5.remi
memcached-devel-1.4.5-2.el5.remi
php-pecl-memcache-3.0.6-2.el5.remi

mamcached 可使用系統預設的 1.4.5 版本
http://memcached.org/ 所提供的 v1.4.13 的版本
在這裡我是以membase取代memcached
url為 http://www.couchbase.com/membase
download url 為 http://www.couchbase.com/download

Install membase

[root@naginx ~]# rpm -ivh couchbase-server-community_x86_1.8.0.rpm
Preparing...                ########################################### [100%]
   1:couchbase-server       ########################################### [100%]
Starting couchbase-server[  OK  ]
You have successfully installed Couchbase Server.
Please browse to http://apache:8091/ to configure your server.
Please refer to http://couchbase.com/ for additional resources.
Please note that you have to update your firewall configuration to
allow connections to the following ports: 11211, 11210, 4369, 8091
and from 21100 to 21299.
By using this software you agree to the End User License Agreement.
See /opt/couchbase/LICENSE.txt.
[root@apache ~]# netstat -an | grep 11211
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN     
[root@apache ~]#

vi /etc/httpd/conf/httpd.conf
======================
LoadModule memcached_cache_module modules/mod_memcached_cache.so
<IfModule mod_memcached_cache.c>
        CacheEnable memcached /
        MemcachedCacheServer localhost:11211
        MemcachedMaxServers 10
        MemcachedMinConnections 10
        MemcachedSMaxConnections 10
        MemcachedMaxConnections 10
        MemcachedConnectionTTL 10
        MemcachedCacheMinFileSize 1
        MemcachedCacheMaxFileSize 2097152
        CacheDisable /admin/
        CacheDisable /server-status/
</IfModule>
============================
service httpd restart
============================

mod_memcached_cache 安裝參考的URL為 
http://www.mabishu.com/blog/2009/12/08/using-memcache-server-as-apache-content-cach/

將 membase & memcached 加入 Cacti 監控

新增 cacti 的 manager monitor port

[root@apache scripts]# pwd
/var/www/html/cacti/scripts
[root@apache scripts]# vi  ports.inc
80#HTTP
443#HTTP SSL
110#POP
995#POP SSL
25#SMTP
21#FTPD
53#DNS
389#LDAP
23#Telnet
22#SSH
3306#MYSQL
143#IMAP
993#IMAP SSL
514#RSH
8003#NAV GW
10000#Ipsec
8090#X-Ray
8080#Zope
5903#VNC
11211#memcached
8091#CouchbaseConsole

再進入 cacti \ console \ device \ TCP (Verbose Query) \ 再點選新增的監控服務即可

Cacti Manage Monitor


Couchbase Console

2012年5月28日 星期一

使用 membase 取代 memcached ( LNMP 優化 )


使用 membase 取代 memcached ( LNMP 優化 )


URL http://www.couchbase.com/membase
download http://www.couchbase.com/download

[root@nginx ~]# rpm -ivh couchbase-server-community_x86_1.8.0.rpm  --test
Preparing...                ########################################### [100%]
[root@nginx ~]# rpm -ivh couchbase-server-community_x86_1.8.0.rpm
Preparing...                ########################################### [100%]
   1:couchbase-server       ########################################### [100%]
Starting couchbase-server[  OK  ]
You have successfully installed Couchbase Server.
Please browse to http://nginx:8091/ to configure your server.
Please refer to http://couchbase.com/ for additional resources.
Please note that you have to update your firewall configuration to
allow connections to the following ports: 11211, 11210, 4369, 8091
and from 21100 to 21299.
By using this software you agree to the End User License Agreement.
See /opt/couchbase/LICENSE.txt.
[root@nginx ~]#





使用 google-perftools ( LNMP 優化 )

使用 google-perftools 優化 Nginx

在網路上看到有許多人在談論如何加速 LNMP 的使用環境.
方式為 google-perftools & ngx_cache_purge
再加上 memcache (php模組)及使用 memcached (php模組) 等

安裝 libunwind

http://download.savannah.gnu.org/releases/libunwind/
http://download.savannah.gnu.org/releases/libunwind/libunwind-1.0.1.tar.gz

#tar -zvxf libunwind-1.0.1.tar.gz
#cd libunwind-1.0.1
#CFLAGS=-fPIC ./configure --prefix=/usr
#make CFLAGS=-fPIC
#make CFLAGS=-fPIC install

安裝 google-perftools

http://code.google.com/p/gperftools/downloads/list
http://gperftools.googlecode.com/files/gperftools-2.0.tar.gz

#tar -zvxf gperftools-2.0.tar.gz
#cd gperftools-2.0
#./configure
#make
#make install

#echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
#/sbin/ldconfig


#mkdir /tmp/tcmalloc
#chmod 0777 /tmp/tcmalloc
vi /usr/local/nginx/conf/nginx.conf

#pid        logs/nginx.pid;
google_perftools_profiles /tmp/tcmalloc;

====================

ngx_cache_purge
http://labs.frickle.com/nginx_ngx_cache_purge/

http://www.pcre.org/
http://sourceforge.net/projects/pcre/files/pcre/8.30/

Nginx module Source
https://github.com/agentzh/srcache-nginx-module

https://github.com/agentzh/memc-nginx-module

pcre source
http://sourceforge.net/projects/pcre/files/pcre/
http://sourceforge.net/projects/pcre/files/pcre/8.30/pcre-8.30.tar.gz/download


安裝

Nginx

./configure --prefix=/usr/local/nginx3 --user=nginx --group=nginx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --with-http_perl_module --with-google_perftools_module --with-pcre=/usr/local/src/pcre-8.30 --add-module=/root/ngx_cache_purge-1.5 --http-proxy-temp-path=/usr/local/nginx3/proxy_temp  --add-module=/root/agentzh-memc-nginx-module-8befc56 --add-module=/root/agentzh-srcache-nginx-module-027dd06

安裝 memcache

http://pecl.php.net/package/memcache
http://pecl.php.net/get/memcache-2.2.6.tgz

#tar -zvxf memcache-2.2.6.tgz
#cd   memcache-2.2.6
#phpize
#./configure --enable-memcache

Installing shared extensions:     /usr/lib/php/modules/
==> memcache.so



安裝 memcached
yum install --enablerepo=remi  php-pecl-memcached
yum install  --enablerepo=remi   memcached
yum install  --enablerepo=remi  memcached-devel

or

http://libevent.org/
wget https://github.com/downloads/libevent/libevent/libevent-2.0.19-stable.tar.gz
tar -zvxf libevent-2.0.19-stable.tar.gz
cd libevent-2.0.19-stable
./configure
make
make test
meke install

ln -s /usr/local/lib/libevent-2.0.so.5 /usr/lib/libevent-2.0.so.5
memcached (Service ( DAEMON ) )

http://memcached.org/

wget http://memcached.googlecode.com/files/memcached-1.4.13.tar.gz
tar -zvxf memcached-1.4.13.tar.gz
cd memcached-1.4.13
./configure
make
make test
meke install

/usr/local/bin/memcached -d -m 128 -u nginx -l 127.0.0.1 -p 11211 -c 256 -P /tmp/memcached.pid
kill `cat /tmp/memcached.pid`


https://launchpad.net/libmemcached/+download
libmemcached-1.0.8.tar.gz 
./configure --prefix=/usr  --exec-prefix=usr
make
make install


http://pecl.php.net/package/memcached
http://pecl.php.net/get/memcached-2.0.1.tgz
#wget http://pecl.php.net/get/memcached-2.0.1.tgz
#tar -zvxf memcached-2.0.1.tgz
#cd   memcached-2.0.1
#phpize
#./configure --enable-memcached

Installing shared extensions:     /usr/lib/php/modules/

==> memcached.so



啟動

/usr/local/bin/memcached -d -m 128 -u nginx -l 127.0.0.1 -p 11211 -c 256 -P /tmp/memcached.pid

or
memcached -d -p 11211 -u nginx -m 64 -c 1024
memcached -d -p 11212 -u nginx -m 64 -c 1024
memcached -d -p 11213 -u nginx -m 1024
memcached -d -p 11214 -u nginx -m 1024

vi /etc/php.ini

cgi.fix_pathinfo=1

; zend_optimizer.optimization_level=15
; zend_extension=/usr/lib/php/modules/ZendOptimizer.so

zend_extension=/usr/lib/php/modules/ZendGuardLoader.so
zend_loader.enable=1
zend_loader.disable_licensing=0
zend_loader.obfuscation_level_support=3
zend_loader.license_path=

extension="eaccelerator.so"
extension="memcache.so"
eaccelerator.shm_size="16"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
[memcache]
memcache.hash_strategy = "consistent"
memcache.default_timeout_ms = 300
[root@nginx modules]#

重啟 php-fpm
#service php-rpm restart

========================
[root@nginx modules]# php -m
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dom
eAccelerator
ereg
exif
fileinfo
filter
ftp
gd
gettext
gmp
hash
iconv
igbinary
imap
json
ldap
libxml
mbstring
mcrypt
memcache
memcached

mhash
mysql
mysqli
odbc
openssl
pcntl
pcre
PDO
pdo_mysql
PDO_ODBC
pdo_sqlite
Phar
readline
Reflection
session
shmop
SimpleXML
snmp
soap
sockets
SPL
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend Guard Loader
zip
zlib
[Zend Modules]
Zend Guard Loader
eAccelerator
[root@nginx modules]#



[root@nginx conf]# cat nginx.conf
user  nginx nginx;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
google_perftools_profiles /tmp/tcmalloc;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    gzip  on;
    gzip_min_length 1k;
    gzip_buffers 16 64k;
    gzip_http_version 1.1;
    gzip_comp_level 6;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    include  /usr/local/nginx3/conf/proxy.conf;

    upstream memcached {
    server 127.0.0.1:11211;
    }

    server {
        listen       80;
        server_name  localhost;
        charset utf-8;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htmi index.php;
            # proxy_pass  http://192.168.100.10/;
            proxy_cache             tmpcache;
            proxy_cache_key         $uri$is_args$args;
          
          
            set $key $uri$args;
            srcache_fetch GET /memc $key;
            srcache_store PUT /memc $key;
       
            #set $memcached_key      $host$uri;
            #memcached_pass   memcached;
            #default_type   text/html;
            #error_page 404 = /error_page;
   
        }
        location /memc {
         internal;
         memc_connect_timeout 100ms;
         memc_send_timeout 100ms;
         memc_read_timeout 100ms;
         set $memc_key $query_string;
         set $memc_exptime 300;
         memc_pass memcached;
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1/;
        #}
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            fastcgi_param  SCRIPT_FILENAME   /html$fastcgi_script_name;
            include        fastcgi_params;
            set $key $uri$args;
            srcache_fetch GET /memc $key;        
            srcache_store PUT /memc $key;
        }
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
        location /server-status {
         stub_status on;
         access_log off;
         allow 127.0.0.1;
         allow 192.168.100.0/24;
         deny all;
        }
        location /nginx_status {
        stub_status on;
        # disable access_log if requared
        access_log   off;
        allow 127.0.0.1;
        allow 192.168.100.0/24;
        deny all;
        }

        location ~ /purge(/.*) {
        allow                   127.0.0.1;
        deny                    all;
        proxy_cache_purge       tmpcache   $1$is_args$args;
        }

    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443;
    #    server_name  localhost;
    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    #    ssl_session_timeout  5m;
    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}



[root@nginx conf]# cat proxy.conf
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 50m;
client_body_buffer_size 256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
proxy_max_temp_file_size 128m;
proxy_temp_path /usr/local/nginx3/proxy_temp/temp;
proxy_cache_path /usr/local/nginx3/proxy_temp/proxy levels=1:2 keys_zone=tmpcache:10m inactive=1d max_size=1g; 
proxy_cache tmpcache;
proxy_cache_valid  200 304 12h;
proxy_cache_valid  301 302 1m;
proxy_cache_valid  any 1m;
proxy_cache_key $host$uri$is_args$args;
[root@nginx conf]#


[root@CentOS6 init.d]# cat memcached
#! /bin/sh
#
# chkconfig: - 55 45
# description:  The memcached daemon is a network memory cache service.
# processname: memcached
# config: /etc/sysconfig/memcached
# pidfile: /var/run/memcached/memcached.pid
# Standard LSB functions
#. /lib/lsb/init-functions
# Source function library.
. /etc/init.d/functions
PORT=11211
USER=root
MAXCONN=1024
CACHESIZE=2048
OPTIONS="-l 127.0.0.1"
if [ -f /etc/sysconfig/memcached ];then
        . /etc/sysconfig/memcached
fi
# Check that networking is up.
. /etc/sysconfig/network
if [ "$NETWORKING" = "no" ]
then
        exit 0
fi
RETVAL=0
prog="memcached"
pidfile=${PIDFILE-/var/run/memcached/memcached.pid}
lockfile=${LOCKFILE-/var/lock/subsys/memcached}
start () {
        echo -n $"Starting $prog: "
        # Ensure that /var/run/memcached has proper permissions
        if [ "`stat -c %U /var/run/memcached`" != "$USER" ]; then
                chown $USER /var/run/memcached
        fi
        daemon --pidfile ${pidfile} /usr/local/memcached/bin/memcached -d -p $PORT -u $USER  -m $CACHESIZE -c $MAXCONN -P ${pidfile} $OPTIONS
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch ${lockfile}
}
stop () {
        echo -n $"Stopping $prog: "
        killproc -p ${pidfile} /usr/local/memcached/bin/memcached
        RETVAL=$?
        echo
        if [ $RETVAL -eq 0 ] ; then
                rm -f ${lockfile} ${pidfile}
        fi
}
restart () {
        stop
        start
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status -p ${pidfile} /usr/local/memcached/bin/memcached
        RETVAL=$?
        ;;
  restart|reload|force-reload)
        restart
        ;;
  condrestart|try-restart)
        [ -f ${lockfile} ] && restart || :
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|try-restart}"
        RETVAL=2
        ;;
esac
exit $RETVAL

===============
mkdir /var/run/memcached
touch /var/run/memcached/memcached.pid

vi vi /etc/sysconfig/memcached

PORT="11211"
USER="root"
# max connection 2048
MAXCONN="2048"
# set ram size to 2048 - 2GiB
CACHESIZE="4096"
# listen to loopback ip 127.0.0.1, for network connection use real ip e.g., 10.0.0.4
OPTIONS="-l 127.0.0.1"





2012年5月26日 星期六

Cacti templates ApacheStats & Nginx

http://forums.cacti.net/about26458.html

另一個 scripts and templates for nginx


ApacheStats 0.8.2

http://forums.cacti.net/about25227.html


實用的 Cacti Monitoring Template


http://www.percona.com/downloads/percona-monitoring-plugins/

上述 URL 可以下載到許多實用的 Cacti Template , 安裝與使用的方式詳見

http://www.percona.com/doc/percona-monitoring-plugins/cacti/installing-templates.html
或 Percona_Monitoring_Plugins_100_Operations_Manual.pdf

以 WEB Server 來說它提供了
(1) cacti_host_template_percona_nginx_server_ht_0.8.6i-sver1.0.0.xml
(2) cacti_host_template_percona_apache_server_ht_0.8.6i-sver1.0.0.xml
這2個template

其它的還有:
 cacti_host_template_percona_gnu_linux_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_jmx_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_memcached_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_mongodb_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_mysql_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_openvz_server_ht_0.8.6i-sver1.0.0.xml
 cacti_host_template_percona_redis_server_ht_0.8.6i-sver1.0.0.xml

所使用的scripts為:
(1)ss_get_mysql_stats.php
(2)ss_get_by_ssh.php

以 ss_get_by_ssh.php 必需使用 SSH key 的方式

vi ss_get_by_ssh.php

....
$ssh_user   = 'cactiuser';                          # SSH username
$ssh_port   = 22;                               # SSH port
$ssh_iden   = '-i /home/cactiuser/.ssh/id_rsa';  # SSH identity$ssh_tout   = 10;                               # SSH connect timeout
$nc_cmd     = 'nc -C -q1';                      # How to invoke netcat
$cache_dir  = '/tmp';  # If set, this uses caching to avoid multiple calls.
$poll_time  = 300; # Adjust to match your polling interval.
$timezone   = null;    # If not set, uses the system default.  Example: "UTC"
$use_ss     = FALSE; # Whether to use the script server or not
$use_ssh    = TRUE;  # Whether to connect via SSH or not (default yes).
$debug      = FALSE; # Define whether you want debugging behavior.
......

使用 SSH 自動 login 必需 vi /etc/ssh/sshd_config

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys

PasswordAuthentication yes
PermitEmptyPasswords yes

再 產生 ssh key

#ssh-keygen -t rsa -b 1024
#cat id_rsa.pub  > authorized_keys
#chmod 644 authorized_keys <非 root user>

[root@nginx ssh]# useradd xrcd2
[root@nginx ssh]# passwd xrcd2
Changing password for user xrcd2.
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[root@nginx ssh]# su - xrcd2
[xrcd2@nginx ~]$ ssh-keygen -t rsa -b 1024
Generating public/private rsa key pair.
Enter file in which to save the key (/home/xrcd2/.ssh/id_rsa):
Created directory '/home/xrcd2/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/xrcd2/.ssh/id_rsa.
Your public key has been saved in /home/xrcd2/.ssh/id_rsa.pub.
The key fingerprint is:
94:8b:ea:42:58:e0:09:e5:ed:37:07:6c:8b:86:55:f5 xrcd2@nginx
[xrcd2@nginx ~]$ cd .ssh
[xrcd2@nginx .ssh]$ pwd
/home/xrcd2/.ssh
[xrcd2@nginx .ssh]$ cat id_rsa.pub  > authorized_keys
[xrcd2@nginx .ssh]$ chmod 644 authorized_keys
[xrcd2@nginx .ssh]$ ssh 127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is 54:0d:5b:cf:90:db:f5:98:c9:3a:52:3d:24:b1:ae:15.
Are you sure you want to continue connecting (yes/no)? yes
[xrcd2@nginx ~]$ ssh 127.0.0.1
Last login: Sat May 26 21:58:24 2012 from nginx
[xrcd2@nginx ~]$ w
 21:59:37 up  7:12,  3 users,  load average: 0.06, 0.12, 0.10
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1     -                14:39    7:18m  0.05s  0.05s -bash
root     pts/0    192.168.100.200  21:47    0.00s  0.16s  0.03s ssh 127.0.0.1
xrcd2    pts/3    nginx            21:58    0.00s  0.04s  0.01s w
[xrcd2@nginx ~]$

vi /etc/httpd/conf/httpd.conf

#
# ExtendedStatus controls whether Apache will generate "full" status
# information (ExtendedStatus On) or just basic information (ExtendedStatus
# Off) when the "server-status" handler is called. The default is Off.
#
ExtendedStatus On

#
# Allow server status reports generated by mod_status,
# with the URL of http://servername/server-status
# Change the ".example.com" to match your domain to enable.
#
<Location /server-status>
    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from 127.0.0.1 192.168.100.1/24

</Location>


vi /usr/local/nginx/conf/nginx.conf


        location /server-status {
         stub_status on;
         access_log off;
         allow 127.0.0.1;
         allow 192.168.100.0/24;
         deny all;
        }

        location /nginx_status {
        stub_status on;
        access_log   off;
        allow 127.0.0.1;
        allow 192.168.100.0/24;
        deny all;
        }






2012年5月6日 星期日

LAMP or LNMP ( Cacti 運行環境 )

LNMP (Linux、Nginx、MySQL、PHP)

LAMP (Linux、Apache、MySQL、PHP)

在 WEB Server 的市佔率上,除了 Apache 外.另一個常見的是  Nginx (http://nginx.org/)
同樣是可以建立 PHP + MySql 的網站環境,在使用上也是一個不錯的選項之一.

以建構 Cacti 的網管監控來說.這兩者之間並無太大的差異存在.
但 Nginx 則必需透過 php-fpm 來取代 php5-cgi 或 spawn-fcgi 來取代 php5-cgi
方可支援 PHP!

對傳統 Apache的使用者來說,這是最大的不同之處.也就是說PHP的設定或功能支援上,
有所異動時,
除了要 restart web service 外( service httpd/nginx restart) 也要 restart php-cgi
如 service php-fpm restart or service spawn-fcgi restart.


nginx.conf

        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            # fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }


#!/bin/bash
/usr/local/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 6 -u nginx -g nginx -f /usr/bin/php-cgi -P /var/run/fastcgi-php.pid


spawn-fcgi
wget http://www.lighttpd.net/download/spawn-fcgi-1.6.3.tar.gz

php-fpm
http://php-fpm.org/

如使用php-fpm (FastCGI Process Manager)
其限制條件為 php 5.2.13以後的版本方可使用.
所以 php 可能會需要 upgrade 的問題

mysql 在 upgrade 無法啟用問題之解法為 先移除後安裝

yum remove mysql mysql-*

wget ftp://fr2.rpmfind.net/linux/epel/5/i386/epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm epel-release-5*.rpm
yum --enablerepo=remi update php php-* php_mysql
yum --enablerepo=remi list mysql mysql-server
yum --enablerepo=remi install mysql mysql-server

/etc/init.d/mysqld restart (service mysqld restart)

mysql_upgrade


參考上述方式可將 php Upgrade 至可支援 php-fpm 的版本.

LNMP 的使用環境一樣可以使用下列這些常見的PHP加速套件.

eAccelerator
ZendGuardLoader (限 php 5.3 以上)
ZendOptimizer (限 php 5.2 以下)

eAccelerator 的安裝方式如下.
# phpize
# ./configure
# make
# make install

#mkdir /tmp/eaccelerator
#chmod 0777 /tmp/eaccelerator

vi /etc/php.ini

cgi.fix_pathinfo=1

; zend_optimizer.optimization_level=15
; zend_extension=/usr/lib/php/modules/ZendOptimizer.so

zend_extension=/usr/lib/php/modules/ZendGuardLoader.so
zend_loader.enable=1
zend_loader.disable_licensing=0
zend_loader.obfuscation_level_support=3
zend_loader.license_path=

extension="eaccelerator.so"
eaccelerator.shm_size="16"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"

安裝完成後.

[root@nginx /]# php -v
PHP 5.3.12 (cli) (built: May  3 2012 20:26:56)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
    with eAccelerator v0.9.6.1, Copyright (c) 2004-2010 eAccelerator, by eAccelerator
    with Zend Guard Loader v3.3, Copyright (c) 1998-2010, by Zend Technologies
[root@nginx /]#

cacti

2012年5月3日 星期四

Cacti + XSMS_API (SOAP) (自行客製化 Cacti + SMS )

我最近在幫我朋友在 [某知名企業] 建置網管系統,並結合手機簡訊發報功能
使用軟體為 cacti + zabbix ( open source )



































































功能差不多是這樣,只是上面這些圖是以 syslog 為出發點的架構
網管角度與方式是最大的差異吧.













































































~ 網管系統不就是這樣.大同小異...

而這家 [某知名企業] 是用 Cacti + snmp + ping + Zabbix agent 加以監控的.
架構上是差不多的,功能上也是相似的.就是網管例行功能與需求.
Cacti & Zabbix
採主動出擊的網管方式! Syslog 則是被動通知.
運作邏輯簡要說明如下:

Device ---------------------->syslog---->
網管系統----->異常通知

Device <---SNMP/Zabbix-Agent/ICMP<-------
網管系統----->異常通知

 
外面買這樣 Solution 至少以萬起跳吧!
我大約花了一個多星期才完成這個專案.
作業方式就是就在家做好了所有PluginsAPIScripts.
再透過Teamview去完成相關的設定工作與相關測試與調校作業.
其中手機簡訊API的界接是將 XSMS_API 改寫入msn2web 程式(Pank msn2web程式 Source http://pank.org/msn/web2msn.tgz)
成為 web API 介面,改寫 msn2web 上半段 php 程式 (該企業的需求僅需手機簡訊)
類似這樣的畫面.





















亞太電信企業簡訊XSMS服務平台程式開發指引手冊(Release Version 1.9)

XSMS_API_V1.9.pdf


5.1. 即時簡訊發送API

5.1.1. SOAP 介面說明
此功能提供給企業用戶透過SOAP API 傳送即時簡訊發送之需求。


5.1.1.1. 介面協議
SOAP
HTTP Method: Post
5.1.1.2.
介面URL
未加密:
http://xsms.aptg.com.tw/XSMSAP/api/APIRTRequest
加密:
https://xsms.aptg.com.tw/XSMSAP/api/APIRTRequest

6.3. PHP
範例 + 介面協議說明


$url= "xsms.aptg.com.tw";
$fp = fsockopen($url,80,$errno,$errstr,30);
if (!$fp){
echo 'Could not open connection.';
}
else{
$xmlpacket ='<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:Header/>
<soap-env:Body>
<Request>
//
企業代表號
<MDN>xxxxxxxxxx</MDN>
//
使用者帳號(企業管理者之帳號即為企業代表號)
<UID>xxxxx</UID>
//
使用者密碼
<UPASS>xxxxxxx</UPASS>
//
簡訊主旨
<Subject>API test</Subject>
//Retry
是否啟用
<Retry>Y</Retry>
//
長簡訊是否啟用
<AutoSplit>N</AutoSplit>
//
簡訊發送截止時間
//Default
為發送時間+24 小時格式為YYYYMMDDhhmm 時分截止時間最晚為發送時間+24 小時,若使用者設定超過24 小時,將以24 小時為限,不再回覆任何訊息
//<StopDateTime>N</StopDateTime>
//
簡訊本文
<Message>SMS API Test OK</Message>
<MDNList>
//
接收端手機號碼
<MSISDN>xxxxxxxxxx</MSISDN>
</MDNList>
</Request>
</soap-env:Body>
</soap-env:Envelope>';
$contentlength = strlen($xmlpacket);
$out = "POST /XSMSAP/api/APIRTRequest HTTP/1.1\r\n";
$out .= "Host: 210.200.64.111\r\n";
$out .= "Connection: close\r\n";
$out .= "Content-type: text/xml;charset=utf-8\r\n";
$out .= "Content-length: $contentlength\r\n\r\n";
$out .= "$xmlpacket";
fwrite($fp, $out);
while (!feof($fp)) {
$theOutput .= fgets($fp, 128);
}
fclose($fp);
echo $theOutput;
}
?>
下方程式請依個自需求.自行改寫之...僅供參考使用...新的web2sms取代web2msn


===================================


<?php


function counter() {
$file="counter.txt";
if (!file_exists($file)) {
$fp=fopen($file, "w");
fputs($fp, 0, 2);
fclose($fp);
}
$conts=file("$file");
$counter=$conts[0]+1;
$fp=fopen($file, "w");
fputs($fp, $counter,
;
echo $counter;
}



function SMS_API(){


/*
填入API 指令的網址 */
$fp = fsockopen("xsms.aptg.com.tw", 80, $errno, $errstr, 30);
if (!$fp)
{
echo 'Could not open connection.';
}
else
{
$xmlpacket ='<soap-env:Envelope xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
<soap-env:Header/>
<soap-env:Body>
<Request>
<MDN>0982684444</MDN>
<UID>dennischung</UID>
<UPASS>aptgxsms</UPASS>
<Subject>
亞太電信簡訊發送平台</Subject>
<Retry>Y</Retry>
<AutoSplit>N</AutoSplit>
<StopDateTime>201006021230</StopDateTime>
<Message>
這是一封來自亞太電信....</Message> 重點在這裡=====> 想辦法將web2msnmsg所接收的訊息寫在這個地方,並成為SOAP的標準格式內容等(重點)
<MDNList>
<MSISDN>0982111111</MSISDN>
重點在這裡=====> 想辦法將web2msnmsn所接收的訊息寫在這個地方,並成為SOAP的標準格式內容等(重點)
<MSISDN>0982111222</MSISDN>
<MSISDN>0982111333</MSISDN>
</MDNList>
</Request>
</soap-env:Body>
</soap-env:Envelope>';
$contentlength = strlen($xmlpacket);
$out = "POST /XSMSAP/api/APIRTRequest HTTP/1.1\r\n";
$out .= "Host: 210.200.64.111\r\n";
$out .= "Connection: close\r\n";
$out .= "Content-type: text/xml;charset=utf-8\r\n";
$out .= "Content-length: $contentlength\r\n\r\n";
$out .= "$xmlpacket";
fwrite($fp, $out);
while (!feof($fp))
{
$theOutput .= fgets($fp, 128);
}
fclose($fp);
echo $theOutput; // $theOutput is the response returned from the remote script
}
?>


if ($msn) {
$c = $msn;
$g = $msg;
$msn=trim($msn);
$id=strlen($msg);
if (strstr($msn, '0') ) {
if ($charset=='big5') $msg=iconv('big5','utf-8',$msg);
SMS_API(); ---->
這裡指的是將網頁中的 MSN-ID & MS-MSG 餵入 function SMS_API() [亞太的XSMS SOAP API 變成 SMS-ID & SMS-MSG] 並執行手機簡訊傳送! 條件是一定是要輸入 ID & MSG 才會進行手機簡訊傳送動作!

==================
這裡的邏輯是這樣子的
MSN-ID --------> SMS-ID
MSN-MSG------> SMS-MSG
變成新的 sms.index.php
==================
原來舊的 msn.index.php
msn --------> MSN-ID
msg------> MSN-MSG
======================
整個流程就是
msn--->msn-id------->sms-id
msg--->msg-msg---->sms-msg
======================

if ($cli) exit;
echo ( "<P>SOAP API Message:" . $theOutput . ".</P>" );
// echo "<script>alert('Sending SMS');</script>";
} else {
echo "<script>alert('SMS
手機門號輸入不正確!');</script>";
}
}



?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WEB2MSN</title>
</head>
<body onload="form1.msn.focus()">
<h3>WEB2MSN</h3>
需要加入我的 MSN bot 才能送訊息給您, 請新增 MSN 連絡人:
<font color=blue><a href=msnim:add?contact=msn@pank.org><b>msn@pank.org</b></a></font><br>
測試完後再把他刪除即可, 非常感謝!<br>

<form name=form1 method=post>
<table border=0>
<tr>
<td>
傳送給 MSN</td>
<td><input name=msn size=70 title='
傳給多個連絡人請用 , 隔開'></td>
</tr>
<tr>
<td>
訊息</td>
<td>
<textarea rows=5 name=msg cols=50 title='
請輸入訊息'>
</textarea><br>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type=submit value="
傳送"></td>
</tr>
</table>
</form>
<br>
配合時間排程(crontab), 可以做到行事曆提醒功能<br>
CLI
傳訊方法<br>
wget -qO- "http://pank.org/msn/?cli=1&msn=MSN
帳號&msg=訊息"<br>
若您的系統是用 big5 編碼, 請加 charset 參數, 例如:<br>
wget -qO- "http://pank.org/msn/?cli=1&charset=big5&msn=MSN
帳號&msg=訊息"<br>
<br>
感謝 twu2 所分享的文章:
<a href=http://blog.teatime.com.tw/1/post/200>
使用 PHP 發送 MSN 訊息</a> |
<a href=http://blog.teatime.com.tw/1/post/218>msn.class.php v1.3a, a simple msnbot</a>
<hr>
<table border=0 width=100%>
<tr>
<td><a href=http://pank.org>pank.org</a></td>
<td align=right><font color=405060><? counter(); ?> Visitors</font></td>
</tr>
</table>
<p>&nbsp;</p>
</body>
</html>


===================================


Cacti
程式內容的修改請參考
Cacti plugin thold (Threshold Alert Module) + MSN
http://www.vlab.com.tw/vlabforums/viewtopic.php?t=15262

Threshold Alert Module
的程式內容會因版本不同.
所以程式有會有所不同.請特別注意!!

vi /var/www/html/cacti/plugins/thold/thold_functions.php

search [if (trim($alert_emails) != '') {]
thold_mail(....的下方新增 wget 的方式. alert_emails subjcet message 導入 sms2web MSN-Message (重點)

alert
if (trim($alert_emails) != '') {

wget ......
請參改如下的Wget CLI

warning
if (trim($warning_emails) != '') {

wget ......

==========================

Wget CLI
傳訊方法 :
wget -qO- "http://pank.org/msn/?cli=1&msn=MSN
帳號&msg=訊息"
若您的系統是用 big5 編碼, 請加 charset 參數, 例如:
wget -qO- "http://pank.org/msn/?cli=1&charset=big5&msn=MSN
帳號&msg=訊息"
===========================

================
XRCD2
==============
License Certified:
Juniper JNCIA-ER JNCIA-EX JNCIS-ES JNCIS-ER JNCIS-M