練功房推薦書單

  • Google!Android 3手機應用程式設計入門(第四版)
  • 賈伯斯傳(軟皮精裝版)
  • 猛虎出閘制霸版:最新OCP Java SE 6 Programmer專業認證(附原始程式碼及範例檔)
  • SCWCD 5 猛虎出閘:Java Web 應用程式專業認證
Messages posted by: andowson
Forum Index » Profile for andowson » Messages posted by andowson
Message
由於公司資安規定需要定期備份網路設備的網路設定檔,如果每個月都要進到console介面去操作一次,輸入一堆指令也是滿花時間的;
另外一個作法是登入命令列界面,然後手動去下copy running-config tftp://${tftp.host} 這個指令,雖然是比較快速了些,但總是感覺多一件事情在身上,到時要是別的事忙起來,還是怕會忘記。

由於懶惰是人的天性,所以總是會想如何把事情自動化,於是我就想用ant的telnet task來自動登入Cisco Switch並執行copy running-config指令,方法大致如下:
1.在備份用的主機上架設TFTP Server
2.下載及安裝JRE、Ant 1.7.1及telnet task所需之commons-net套件。
3.編輯一個build.xml及一個build.properties檔案
4.執行 ant cisco看是否可正常備份
5.寫一個shell script檔將該ant指令包裝起來
6.設定/etc/crontab自動執行該shell script檔

由於手邊只有Linux主機可以當備份主機使用,底下再簡單說明一下上述步驟
1.安裝TFTP Server可以參考這篇
http://www.andowson.com/posts/list/544.page,安裝完成後,手動建立一個/tftpboot的目錄,並把tftpboot的根目錄(Base Directory)設定777

2.將把下載來的ant zip檔解壓縮到/root/cisco底下,設定環境變數ANT_HOME指向安裝的目錄,並在PATH變數加上$ANT_HOME/bin。然後把commons-net的jar檔放到ANT_HOME的lib目錄下。

3.可以參考底下兩個範例,將這兩個檔案存到/root/cisco目錄下
build.xml範例如下:
 
<?xml version="1.0" encoding="Big5" ?>

<project name="backup" default="cisco" basedir=".">
	<description>Network Switch Config Backup</description>

	<!-- Enable access to build.properties variables -->
	<property file="build.properties" />
	<property name="backup.root.dir" value="/root/cisco" />
	<property name="cisco.backup.dir" value="${backup.root.dir}/${cisco.ip}" />
	<property name="tftp.root" value="/tftpboot" />

	<!-- Init -->
	<target name="init" description="Create backup directory">
		<tstamp>
			<format property="TODAY" pattern="yyyyMMdd" />
		</tstamp>
    <property name="cisco.cfg" value="cisco_${TODAY}.cfg" />
		<mkdir dir="${backup.root.dir}" />
		<mkdir dir="${backup.root.dir}/${cisco.ip}" />
		<touch file="${tftp.root}/${cisco.cfg}"/>
		<chmod file="${tftp.root}/${cisco.cfg}" perm="ugo+rwx"/>
	</target>

  <!-- Backup cisco Config -->
  <target name="cisco" depends="init" description="Backup cisco config">
		<property name="cisco.cfg" value="cisco_${TODAY}.cfg" />
    <telnet server="${cisco.ip}">
     <read timeout="5">Username: </read>
     <write>${cisco.username}</write>
     <read timeout="5">Password: </read>
     <write>${cisco.password}</write>
     <read timeout="5">></read>
     <write>enable</write>
     <read timeout="5">Password: </read>
     <write>${enable.password}</write>
     <read timeout="5">#</read>
     <write>copy running-config tftp://${tftp.host}</write>
     <read timeout="30">Address or name of remote host [${tftp.host}]?</read>
     <write>${tftp.host}</write>
     <read timeout="30">-confg]?</read>
     <write>${cisco.cfg}</write>
     <read timeout="30">bytes/sec)</read>
     <write>exit</write>
    </telnet>
    <move file="${tftp.root}/${cisco.cfg}" todir="${cisco.backup.dir}" />
  </target>

</project>


build.properties範例如下:請視您真正的情況修改對應的參數值,下列例子中我們的TFTP主機IP是172.16.38.1,Cisco Switch的IP是172.16.38.254。
 
tftp.host=172.16.38.1
cisco.ip=172.16.38.254
cisco.username=admin
cisco.password=admin
enable.password=admin


4.開啟一個shell命令列視窗,然後切換到build.xml及build.properties所存放的目錄/root/cisco下,接著執行
ant cisco

5.將上述動作編輯成一個backup_config.sh
backup_config.sh:
#!/bin/bash
ANT_HOME=/root/cisco/apache-ant-1.7.1
JAVA_HOME=/usr/java/latest
PATH=$PATH:$ANT_HOME/bin:$JAVA_HOME/bin
ant cisco


6.編輯 /etc/crontab,並設定backup_config.sh執行的頻率。
# 每個月備份網路設備的網路設定 (2011.11.18 by Andowson)
30 5 23 * * root /root/cisco/backup_config.sh > /var/log/backup_config.log 2>&1
我的意思是指如果您想要拜訪(visit)holidays.txt檔案中每一行的資料時,只要寫成下面的 for迴圈即可:
@echo off
for /f  %%i in (holidays.txt) do (
  echo %%i is a holiday 
)

%%i 就是迴圈每前進一圈時,由holidays.txt所讀出的下一筆資料
假設holidays.txt內容如下
2011/1/1
2011/2/2
2011/2/28
2011/4/4
2011/4/5
2011/6/6
2011/9/12
2011/10/10

將會依序印出:
2011/1/1 is a holiday
2011/2/2 is a holiday
2011/2/28 is a holiday
2011/4/4 is a holiday
2011/4/5 is a holiday
2011/6/6 is a holiday
2011/9/12 is a holiday
2011/10/10 is a holiday
starzine您好,
看起來你的for迴圈那段有點問題,如果你是一行一筆資料的話,請參考先前我的holiday.bat裡面的寫法。
echo lcd %BACKUPDIR% >> ftpscript.txt
echo prompt >> ftpscript.txt
for /f %%i in (pbank.txt) do ( 
    echo cd %%i >>ftpscript.txt
    echo mget *%year%%month%%day%.* >> ftpscript.txt 
    echo cd .. >> ftpscript.txt 
)

又你可以先把你的測試程式寫成一個小bat檔,測試看看能不能動,再貼回原來的主程式去。

感謝您的補充,我查了一下目前最新版的JForum 2.3.2使用的是方法二:
 if (this.request.getParameter("search_forum") != null && !"".equals(this.request.getParameter("search_forum"))) {
     args.setForumId(this.request.getIntParameter("search_forum"));
 }
在 CentOS 5 上安裝 WebLogic Server 10.0 MP1

設計理念:
1.需要啟動兩個WebLogic Server,一個是AdminServer,一個是ManagedServer。AdminServer負責管理Project Domain,ManagedServer負責執行被佈署上去的WebApp。
2.因為該主機上尚需執行其他AP Server(如Tomcat),我們讓ManagedServer跑在Port 8081上,並透過proxy機制整合至Apache以免佔用port 80。

實作步驟:
1.安裝JDK 5.0
smilie WebLogic Server 10.0 MP1必須搭配JDK 5.0版本使用,如果改用JDK 6.0,雖然可以執行,但將會在log檔中看到一堆錯誤訊息,且運作起來會有很多不順的現象。如果系統上已經安裝JDK 6.0者須先反安裝,待安裝完JDK 5.0後再裝回JDK 6.0。
smilie 下載Sun Java Development Kit 5.0 Update 22(JDK 5.0在2009/11/3被宣告EOSL,最後的公眾可下載版本是Update 22,如果有購買Java SE for Business者可下載較新版本)
x86_64:
cd /tmp
wget http://download.oracle.com/otn-pub/java/jdk/1.5.0_22/jdk-1_5_0_22-linux-amd64-rpm.bin -O jdk-1_5_0_22-linux-amd64-rpm.bin

x86:
cd /tmp
wget http://download.oracle.com/otn-pub/java/jdk/1.5.0_22/jdk-1_5_0_22-linux-i586-rpm.bin -O jdk-1_5_0_22-linux-i586-rpm.bin

smilie 安裝JDK 5.0 Update 22
sh jdk-1_5_0_22-linux-amd64-rpm.bin

smilie 安裝路徑:/usr/java/jdk1.5.0_22

2.安裝WebLogic Server
smilie 上傳光碟檔案B46881-01.zip至/tmp目錄下
smilie 解壓縮
cd /tmp
unzip B46881-01.zip

smilie 開始安裝
java -jar server1001_generic.jar


BEA_HOME=/var/bea
選擇自訂安裝,取消安裝Server Examples [1.2]及Workshop for WebLogic Platform [2]

3.建立WebLogic Domain
cd /var/bea/wlserver_10.0/common/bin
./config.sh

設定weblogic的密碼
設定啟動模式: Development Mode
選擇JDK的路徑:/usr/java/jdk1.5.0_22


4.上傳啟動用的shell script至/var/bea/user_projects/domains/base_domain/
smilie 先將原本產生的startWebLogic.sh更名
cd /var/bea/user_projects/domains/base_domain/
mv startWebLogic.sh startWebLogic.sh.orig
chmod a-x startWebLogic.sh.orig

smilie 上傳下列檔案
startAdminServer.sh
startManagedServer.sh
startOnBoot.sh
startWebLogic.sh
stopAdminServer.sh
stopManagedServer.sh
smilie 編輯下列檔案,取代AdminServer的IP
startManagedServer.sh
stopManagedServer.sh
smilie 將檔案設定為可執行
cd /var/bea/user_projects/domains/base_domain/
chmod a+x *.sh



5.建立boot.properties符號連結
cd /var/bea/user_projects/domains/base_domain/
ln -s servers/AdminServer/security/boot.properties boot.properties


6.建立Log目錄
mkdir -p /var/log/bea


7.啟動AdminServer
cd /var/bea/user_projects/domains/base_domain/
./startAdminServer.sh


8.開放防火牆iptables
加上下列port
7001:tcp

9.登入weblogic console
smilie 開啟瀏覽器,輸入下列網址
http://my_server_ip:7001/console/
帳號跟密碼就是步驟3.建立WebLogic Domain時所輸入的資訊
smilie 建立一個新的Server:
Name: ManagedServer
Listen Port: 8081

10.啟動ManagedServer
cd /var/bea/user_projects/domains/base_domain/
./startManagedServer.sh


11.檢查ManagedServer的狀態是否為RUNNING

12.關閉ManagedServer:
cd /var/bea/user_projects/domains/base_domain/
./stopManagedServer.sh


13.關閉AdminServer:
cd /var/bea/user_projects/domains/base_domain/
./stopAdminServer.sh


到此完成WebLogic Server 10.0 MP1的安裝

接下來再透過WebLogic Server的Apache HTTP Server Plug-In整合至Apache HTTP Server 2.2
x86_64:
cp -p /var/bea/wlserver_10.0/server/plugin/linux/x86_64/mod_wl_22.so /etc/httpd/modules/.

x86:
cp -p /var/bea/wlserver_10.0/server/plugin/linux/i686/mod_wl_22.so /etc/httpd/modules/.

vi /etc/httpd/conf.d/mod_wl.conf
LoadModule weblogic_module     modules/mod_wl_22.so
<IfModule mod_weblogic.c>
  WebLogicHost localhost
  WebLogicPort 8081
  MatchExpression *.jsp
</IfModule>

<Location /myapp>
  SetHandler weblogic-handler
</Location>


smilie 測試一下設定有沒有問題:
httpd -t

如果出現Syntax OK就表示沒問題了

smilie 重新啟動WebLogic Server和Apache Server
cd /var/bea/user_projects/domains/base_domain/
./startOnBoot.sh
/etc/init.d/httpd restart

就可以透過下面的網址來存取myapp了
http://my_server_ip/myapp

參考資料:
http://download.oracle.com/docs/cd/E13222_01/wls/docs100/plugins/apache.html
如果執行一個命令後,發覺系統卡住不動很久,可以先透過Ctrl-C去中斷命令看看,如果不行,再試試看下面的方法:
先執行Ctrl-Z將該命令丟到背景去執行,如果成功的話,將會回到shell的命令提示畫面,這時再輸入下列兩行
echo 1 > /proc/sys/kernel/sysrq
echo b > /proc/sysrq-trigger

將會強迫系統立即重新開機。

參考資料:
http://www.linuxjournal.com/content/rebooting-magic-way
最近想利用yum update來升級CentOS 5.6至CentOS 5.7時遇到這樣的錯誤訊息:

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: centos.mirror.cdnetworks.com
* extras: centos.mirror.cdnetworks.com
* updates: centos.mirror.cdnetworks.com
Setting up Update Process
Resolving Dependencies
--> Running transaction check
---> Package NetworkManager.i386 1:0.7.0-13.el5 set to be updated
---> Package NetworkManager-glib.i386 1:0.7.0-13.el5 set to be updated
---> Package SysVinit.i386 0:2.86-17.el5 set to be updated
---> Package authconfig.i386 0:5.3.21-7.el5 set to be updated
---> Package autofs.i386 1:5.0.1-0.rc2.156.el5_7.3 set to be updated
---> Package bash.i386 0:3.2-32.el5 set to be updated
---> Package centos-release.i386 10:5-7.el5.centos set to be updated
---> Package centos-release-notes.i386 0:5.7-0 set to be updated
---> Package coreutils.i386 0:5.97-34.el5 set to be updated
---> Package cpuspeed.i386 1:1.2.1-10.el5 set to be updated
---> Package cryptsetup-luks.i386 0:1.0.3-8.el5 set to be updated
---> Package curl.i386 0:7.15.5-9.el5_7.4 set to be updated
---> Package dbus.i386 0:1.1.2-16.el5_7 set to be updated
---> Package dbus-libs.i386 0:1.1.2-16.el5_7 set to be updated
---> Package device-mapper.i386 0:1.02.63-4.el5 set to be updated
---> Package device-mapper-event.i386 0:1.02.63-4.el5 set to be updated
---> Package device-mapper-multipath.i386 0:0.4.7-46.el5_7.1 set to be updated
---> Package dhclient.i386 12:3.0.5-29.el5_7.1 set to be updated
---> Package dmidecode.i386 1:2.11-1.el5 set to be updated
---> Package dmraid.i386 0:1.0.0.rc13-65.el5 set to be updated
---> Package dmraid-events.i386 0:1.0.0.rc13-65.el5 set to be updated
---> Package e2fsprogs.i386 0:1.39-33.el5 set to be updated
---> Package e2fsprogs-libs.i386 0:1.39-33.el5 set to be updated
---> Package ecryptfs-utils.i386 0:75-5.el5_7.2 set to be updated
---> Package finger.i386 0:0.17-33 set to be updated
---> Package glibc.i686 0:2.5-65 set to be updated
---> Package glibc-common.i386 0:2.5-65 set to be updated
---> Package glibc-headers.i386 0:2.5-65 set to be updated
---> Package gnome-vfs2.i386 0:2.16.2-8.el5 set to be updated
---> Package gzip.i386 0:1.3.5-13.el5.centos set to be updated
---> Package httpd.i386 0:2.2.3-53.el5.centos.3 set to be updated
---> Package hwdata.noarch 0:0.213.24-1.el5 set to be updated
---> Package initscripts.i386 0:8.45.38-2.el5.centos set to be updated
---> Package iscsi-initiator-utils.i386 0:6.2.0.872-10.el5 set to be updated
---> Package kernel-PAE.i686 0:2.6.18-274.7.1.el5 set to be installed
---> Package kernel-headers.i386 0:2.6.18-274.7.1.el5 set to be updated
---> Package kpartx.i386 0:0.4.7-46.el5_7.1 set to be updated
---> Package krb5-libs.i386 0:1.6.1-62.el5 set to be updated
---> Package krb5-workstation.i386 0:1.6.1-62.el5 set to be updated
---> Package ksh.i386 0:20100202-1.el5_6.6 set to be updated
---> Package libX11.i386 0:1.0.3-11.el5_7.1 set to be updated
---> Package libXfont.i386 0:1.2.2-1.0.4.el5_7 set to be updated
---> Package libgcc.i386 0:4.1.2-51.el5 set to be updated
---> Package libpng.i386 2:1.2.10-7.1.el5_7.5 set to be updated
---> Package libstdc++.i386 0:4.1.2-51.el5 set to be updated
---> Package libsysfs.i386 0:2.1.0-1.el5 set to be updated
---> Package libvolume_id.i386 0:095-14.27.el5 set to be updated
---> Package libxml2.i386 0:2.6.26-2.1.12 set to be updated
---> Package libxml2-python.i386 0:2.6.26-2.1.12 set to be updated
---> Package logrotate.i386 0:3.7.4-12 set to be updated
---> Package lvm2.i386 0:2.02.84-6.el5_7.1 set to be updated
---> Package m2crypto.i386 0:0.16-8.el5 set to be updated
---> Package man.i386 0:1.6d-2.el5 set to be updated
---> Package mkinitrd.i386 0:5.1.19.6-71.el5 set to be updated
---> Package mod_ssl.i386 1:2.2.3-53.el5.centos.3 set to be updated
---> Package nash.i386 0:5.1.19.6-71.el5 set to be updated
---> Package nfs-utils.i386 1:1.0.9-54.el5 set to be updated
---> Package nscd.i386 0:2.5-65 set to be updated
---> Package nspr.i386 0:4.8.8-1.el5_7 set to be updated
---> Package nss.i386 0:3.12.10-4.el5.centos set to be updated
---> Package nss-tools.i386 0:3.12.10-4.el5.centos set to be updated
---> Package nss_ldap.i386 0:253-42.el5 set to be updated
---> Package ntp.i386 0:4.2.2p1-15.el5.centos set to be updated
---> Package openldap.i386 0:2.3.43-12.el5_7.9 set to be updated
---> Package openssh.i386 0:4.3p2-72.el5_7.5 set to be updated
---> Package openssh-clients.i386 0:4.3p2-72.el5_7.5 set to be updated
---> Package openssh-server.i386 0:4.3p2-72.el5_7.5 set to be updated
---> Package openssl.i686 0:0.9.8e-20.el5 set to be updated
---> Package pam_krb5.i386 0:2.2.14-21.el5 set to be updated
---> Package pango.i386 0:1.14.9-8.el5.centos.3 set to be updated
---> Package parted.i386 0:1.8.1-28.el5 set to be updated
---> Package popt.i386 0:1.10.2.3-22.el5_7.2 set to be updated
---> Package postgresql-libs.i386 0:8.1.23-1.el5_7.2 set to be updated
---> Package procps.i386 0:3.2.7-17.el5 set to be updated
---> Package python.i386 0:2.4.3-44.el5_7.1 set to be updated
---> Package python-libs.i386 0:2.4.3-44.el5_7.1 set to be updated
---> Package rpm.i386 0:4.4.2.3-22.el5_7.2 set to be updated
---> Package rpm-libs.i386 0:4.4.2.3-22.el5_7.2 set to be updated
---> Package rpm-python.i386 0:4.4.2.3-22.el5_7.2 set to be updated
---> Package rsync.i386 0:3.0.6-4.el5_7.1 set to be updated
---> Package selinux-policy.noarch 0:2.4.6-316.el5 set to be updated
---> Package selinux-policy-targeted.noarch 0:2.4.6-316.el5 set to be updated
---> Package sendmail.i386 0:8.13.8-8.1.el5_7 set to be updated
---> Package sos.noarch 0:1.7-9.54.el5 set to be updated
---> Package sysfsutils.i386 0:2.1.0-1.el5 set to be updated
---> Package sysstat.i386 0:7.0.2-11.el5 set to be updated
---> Package system-config-network-tui.noarch 0:1.3.99.19-2.el5 set to be updated
---> Package talk.i386 0:0.17-31.el5 set to be updated
---> Package traceroute.i386 3:2.0.1-6.el5 set to be updated
---> Package tzdata.i386 0:2011h-2.el5 set to be updated
---> Package udev.i386 0:095-14.27.el5 set to be updated
---> Package xinetd.i386 2:2.3.14-13.el5 set to be updated
---> Package yum.noarch 0:3.2.22-37.el5.centos set to be updated
---> Package yum-fastestmirror.noarch 0:1.1.16-16.el5.centos set to be updated
---> Package zlib.i386 0:1.2.3-4.el5 set to be updated
http://centos.mirror.cdnetworks.com/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://centos.tt.co.kr/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://centos.ustc.edu.cn/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://centos.vr-zone.com/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://data.nicehosting.co.kr/os/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.cs.pu.edu.tw/Linux/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.cse.yzu.edu.tw/pub/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.daum.net/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.isu.edu.tw/pub/Linux/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.stu.edu.tw/Linux/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.tc.edu.tw/Linux/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://ftp.twaren.net/Linux/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirror.khlug.org/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirror.neu.edu.cn/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirror.yongbok.net/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirror01.idc.hinet.net/CentOS/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirrors.163.com/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirrors.btte.net/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirrors.sin1.sg.voxel.net/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
http://mirrors.ta139.com/centos/5.7/updates/i386/repodata/filelists.sqlite.bz2: [Errno -1] Metadata file does not match checksum
Trying other mirror.
Error: failure: repodata/filelists.sqlite.bz2 from updates: [Errno 256] No more mirrors to try.
You could try using --skip-broken to work around the problem
You could try running: package-cleanup --problems
package-cleanup --dupes
rpm -Va --nofiles --nodigest
The program package-cleanup is found in the yum-utils package.


經過一番搜尋後,最後利用下面的方法解決了:
yum clean all
yum clean metadata
yum makecache --disableplugin=fastestmirror
yum update


參考資料:
http://www.linuxquestions.org/questions/fedora-35/prob-with-yum-%5Berrno-1%5D-metadata-file-does-not-match-checksum-trying-other-mirro-462093/
在 CentOS 上安裝 Jenkins
http://pkg.jenkins-ci.org/redhat/
https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+RedHat+distributions
安裝 Jenkins

sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
sudo rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key
yum install jenkins

在公司內部環境需透過proxy才能連線的話,
應先切換身分為root並設定http_proxy這個環境變數,例如:
sudo -i
export http_proxy=http://10.160.3.88:8080/
rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key

啟動 Jenkins

service jenkins start

整合 Jenkins 至 Apache

https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
修改/etc/sysconfig/jenkins

JENKINS_ARGS="--prefix=/jenkins"

vi /etc/httpd/conf.d/proxy_ajp.conf

ProxyPass         /jenkins  http://localhost:8080/jenkins
ProxyPassReverse  /jenkins  http://localhost:8080/jenkins
ProxyRequests     Off

重新啟動 Jenkins

service jenkins restart

存取 Jenkins
http://myserver.domain.name/jenkins
試著改用psftp這個程式來執行SFTP的工作看看
將原先使用ftp的指令改為psftp指令,下載後將psftp.exe放在remote_backup_web.bat相同目錄即可。
remote_backup_web.bat:
@echo off
rem ---------------------------------------------------------------------------
rem Backup web application to remote host
rem
rem $Id: remote_backup_web.bat 2011-10-20 07:10:58 andowson $
rem ---------------------------------------------------------------------------

rem Find out Windows version
for /f "tokens=1-2 delims=[" %%i in ('ver') do echo %%j > ver1.txt
for /f "tokens=1-2 delims= " %%i in (ver1.txt) do echo %%j > ver2.txt
for /f "tokens=1 delims=]" %%i in (ver2.txt) do set vers=%%i
del ver1.txt
del ver2.txt
if %vers% GEQ 6 goto ver6

rem Find out web server's IP address
ipconfig | findstr "Address" > ip1.txt
for /f "tokens=1-2 delims=:" %%i in (ip1.txt) do echo %%j > ip2.txt
for /f "tokens=1-2 delims= " %%i in (ip2.txt) do (set ip=%%i)
del ip1.txt
del ip2.txt
goto common

:ver6
rem Find out web server's IP address
ipconfig | findstr "IPv4 位址" > ip1.txt
for /f "tokens=1-2 delims=:" %%i in (ip1.txt) do echo %%j > ip2.txt
for /f "tokens=1-2 delims= " %%i in (ip2.txt) do (set ip=%%i)
del ip1.txt
del ip2.txt

:common
rem Get today's year, month, day
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set year=%%a& set month=%%b& set day=%%c)

rem Modify the following line for your environment
set TARGETNAME=demoweb
set TARGET=C:\Inetpub\wwwroot\%TARGETNAME%
set BACKUPDIR=D:\backup
set BACKUPFILE=%BACKUPDIR%\%year%\%TARGETNAME%_%ip%_%year%%month%%day%.zip
set LOGFILE=%TARGETNAME%_backup.log
set ZIPPASSWORD=secret

echo. | date | findstr "現在日期" >> %LOGFILE%
echo. | time | findstr "現在時間" >> %LOGFILE%

rem Compress the target directory with encryption password before ftp
"C:\Program Files\7-Zip\7z.exe" a -p%ZIPPASSWORD% %BACKUPFILE% %TARGET%\* >> %LOGFILE%

if not exist %BACKUPDIR%\%year% mkdir %BACKUPDIR%\%year%

if not exist %BACKUPFILE% goto nofile
goto ftpsession

:nofile
echo [FAILURE] File not found: %BACKUPFILE% >> %LOGFILE%
echo.>> %LOGFILE%
goto end

:ftpsession
for /f "tokens=1-3 delims= " %%i in (ftp.cfg) do (set FTPSERVER=%%i&set USERNAME=%%j&set PASSWORD=%%k)
echo mkdir %year%%month%%day% > ftpscript.txt
echo cd %year%%month%%day% >> ftpscript.txt
echo put %BACKUPFILE% >> ftpscript.txt
echo bye >> ftpscript.txt

echo ---=== ftp session begin ===--->> %LOGFILE%
echo ftp %BACKUPFILE% to %FTPSERVER% >> %LOGFILE%

psftp %FTPSERVER% -l %USERNAME% -pw %PASSWORD% -be -b ftpscript.txt >> %LOGFILE%

echo ---=== ftp session end   ===--->> %LOGFILE%
echo. |time | findstr "現在時間">> %LOGFILE%
echo.>> %LOGFILE%

del ftpscript.txt

set TARGET=
set TARGETNAME=
set BACKUPDIR=
set BACKUPFILE=
set LOGFILE=
set ZIPPASSWORD=
set FTPSERVER=
set USERNAME=
set PASSWORD=

:end


ftp.cfg可以使用原來的格式,也是放在跟remote_backup_web.bat相同目錄下:
remote_sftp_server   username   password


最後先開啟一個CMD命令視窗,然後利用cd切換工作目錄到存放remote_backup_web.bat的目錄下
手動執行一次remote_backup_web.bat,測試是否可以正常運作。因為第一次連線至SFTP Server需要驗證主機端的憑證,會詢問是否要儲存遠端主機的key,選擇yes。

有關psftp的使用說明請參考下列網址:
http://libai.math.ncu.edu.tw/bcc16/6/putty/psftp.html

註:本batch script中含有部份中文字串,存檔時請注意選擇編碼為ANSI/Windows
本站今天正式升級至JForum 2.3.2版。如果有發現任何問題請回報給我。
中華電信100年研發人員徵才公告

中華電信為強化研發能力,將招募研發人員 69 名,各職缺擔任工作、學歷資格條件及遴選相關事項,請參閱遴選簡章,一律採取網路報名方式辦理。

一、報名日期:100 年10 月14 日至100 年10 月27 日24:00
二、第一試(資歷論文審查)日期:100 月10 月28 日至100 年11 月1 日由本公司電信研究所資歷審查小組上網遴選
三、第二試通知日期:100 年11 月2 日15:00 (http://www.chttl.com.tw 網站公告外,詳細口試時程另行e-mail 通知)
四、第二試(口試)日期:100 年11 月5 日至100 年11 月6 日(若有異動,以通知變更日期為準)
五、放榜日期:100 年11 月9 日(若有異動,以通知變更日期為準)

詳細資料請看
http://www.cht.com.tw/CompanyCat.php?CatID=275&NewsID=4479&Page=HotNewsDetail
網路報名網址:
http://202.39.164.13/pr/Login.php
在Oracle中有個desc tablename的指令,可以在SQL命令模式顯示出表格的結構,而在PostgreSQL中也有對應的功能,就是\d tablename,或是用\d+ tablename來獲得更多資訊。


參考資料:
http://stackoverflow.com/questions/109325/postgresql-describe-table
http://www.faqs.org/docs/ppbook/c4890.htm
網址:
https://sites.google.com/site/tiger2000/home
An Auto Installer for Integrating Apache 2.2 and Tomcat 7.0 for Clustering/Session Replication, Load Balancing with mod_jk 1.2 on CentOS 6.0
Author: Andowson Chang
Date: 2011.09.29

Design:
1. One Apache and Two Tomcat workers on the same machine.
2. Use mod_jk for load balancer
3. Use mod_ssl for SSL
4. Enable cluster configuration on both Tomcat workers to do session replication
image

Steps:
1.Install CentOS 6.0 (disbale SELinux and Firewall)
2.Install JRE
3.Install Apache and mod_ssl
4.Generate SSL key and certificate
5.Edit httpd.conf
6.Edit ssl.conf
7.Install Tomcat, mod_jk
8.Edit server.xml
9.Edit mod_jk.conf
10.Edit workers.properties
11.Edit uriworkermap.properties
12.Start Apache and Tomcat

Testing:
1.Browsing http://<your_server_ip>/clustertest.jsp, add some keys and values.
2.Shutdown worker1
3.Browsing http://<your_server_ip>/clustertest.jsp, check if the keys and values are still there.
4.Run restart.sh
5.Browsing http://<your_server_ip>/clustertest.jsp, check if the keys and values are still there.
6.Browsing https://<your_server_ip>/clustertest.jsp, check if the keys and values are still there.

Implementation:
1.Choose Minimal when install CentOS 6.0
2.Create a directory /root/setup and download the auto installer script for step 2-11, save it as httpd2_tomcat7_setup.sh in /root/setup
mkdir -p /root/setup
wget http://www.andowson.com/download/httpd2_tomcat7_setup.sh

then run it
chmod 755 /root/setup/httpd2_tomcat7_setup.sh
cd /root/setup
./httpd2_tomcat7_setup.sh


httpd2_tomca7_setup.sh:
#!/bin/bash
# Name: Apache 2.2.x && Tomcat 7.0.x auto installer for CentOS 6.x
# Author: Andowson Chang (andowson [at] gmail [dot] com)
# Version: 5.15
# Last Modified: 2011-09-29
# Source: http://www.andowson.com
#
# Assumption: 
#   * FQDN hostname is correctly set on /etc/sysconfig/network and /etc/hosts
#     ex. 
#     /etc/sysconfig/network:
#        HOSTNAME=www.andowson.com
#     /etc/hosts:
#        192.168.1.1 www.andowson.com  www
#     (reboot after modified)
#   * run this script as root user
# Post-Install:
#   * disable SELINUX: 
#     /etc/selinux/config
#        SELINUX=disabled
#     (reboot after modified)
#   * allow HTTP(80:tcp), HTTPS(443:tcp), 45564:udp in iptables
#
# This program will
# 1.install JRE 7
# 2.install httpd and mod_ssl
# 3.modify /etc/http/conf/httpd.conf
# 4.generate SSL key and a self-signed certificate
# 5.modify /etc/http/conf.d/ssl.conf
# 6.check for the lastest stable version of Tomcat 7.0.x
# 7.download apache-tomcat-7.0.x.tar.gz
# 8.unpack it into /var/apache-tomcat-7.0.x
# 9.make a symbolic link /var/tomcat7 to the above directory for easy upgrade
#   to a later version
# 10.check memory size to determine some JVM parameters
# 11.check for the latest stable verion of Tomcat Connector 1.2.x
# 12.download tomcat-connectors-1.2.x-src.tar.gz
# 13.unpack it
# 14.configure, make and make install
# 15.create user tomcat with home directory /var/tomcat7
# 16.make two instances of tomcat for load balancing, here I put them under 
#    /var/robust/worker[1,2] for easy to backup all of them.
# 17.setup default host directory(for testing)
# 18.generate server.xml
# 19.generate tomcat-users.xml
# 20.modify web.xml for production use
# 21.generate mod_jk.conf
# 22.generate workers.properties
# 23.generate uriworkermap.properties
# 24.generate tomcat startup script
# 25.modify web.xml for cluster test
# 26.generate clustertest.jsp for cluster test
# 27.generate cleanup.sh for easy to uninstall everything

#
# intranet workaround
# If your server doesn't have direct access to the Internet, ie. in the company 
# intranet behind a firewall, you can modify your server's proxy setting by edit
# /etc/wgetrc:
#http_proxy = http://proxy.yourcompany.com:8080/
#use_proxy = on

# If you still can't use proxy then you have to download all the files manually. 
# After download, copy them into ${SETUP_DIR}. And then change the following 
# default version number to the correct number you have downloaded.
#
TOMCAT_VERSION=7.0.21
TOMCAT_CONNECTOR_VERSION=1.2.32

#
# auto detect ip and hostname
#
ip=`/sbin/ifconfig|grep "inet addr"|awk '{print $2}'|cut -d":" -f2|head -1`
hostname=`/bin/hostname -f`

#
# adjustable parameters, you can modify any of them to fit your own need
#
DOMAIN=`/bin/hostname -d`
COUNTRY=TW
STATE=Taiwan
LOCATION=Taipei
COMPANY="Andowson Ltd."
ORGANIZATION=
HOSTNAME=${hostname}
hostname=${ip}
MIRROR_HOST=apache.ntu.edu.tw
CATALINA_HOME=/var/tomcat7
WORKER_ROOT=/var/robust
WEBAPP_ROOT=/var/webapps
SETUP_DIR=/root/setup/web

#
# create the setup directory
#
mkdir -p ${SETUP_DIR}
cd ${SETUP_DIR}
echo '/etc/init.d/tomcat stop' > ${SETUP_DIR}/cleanup.sh
echo '/etc/init.d/httpd stop' >> ${SETUP_DIR}/cleanup.sh

#
# install JRE
#
OS_MODEL=`uname -m`
JRE_FILE=""
if [ ${OS_MODEL} == "i686" ]; then
    JRE_FILE="jdk-7-linux-i586.rpm"
elif [ ${OS_MODEL} == "x86_64" ]; then
    JRE_FILE="jdk-7-linux-x64.rpm"
fi
echo "Install ${JRE_FILE}"
if [ -n ${JRE_FILE} ] && [ ! -r ${JRE_FILE} ]; then
   wget http://download.oracle.com/otn-pub/java/jdk/7/${JRE_FILE} -O ${JRE_FILE}
fi
if [ -r ${JRE_FILE} ]; then
   rpm -Uvh ${JRE_FILE}
fi

#
# install httpd and mod_ssl
#
yum -y install httpd mod_ssl
cp -p /etc/httpd/conf/httpd.conf /tmp/httpd.conf
cp -p /etc/httpd/conf.d/ssl.conf /tmp/ssl.conf

#
# modify httpd.conf
#
sed -i -e "s/ServerTokens OS/ServerTokens ProductOnly/g" \
-e "s/KeepAlive Off/KeepAlive On/g" \
-e "s/Group apache/Group tomcat/g" \
-e "s/root@localhost/webmaster@${DOMAIN}/g" \
-e "276a\ServerName ${HOSTNAME}:80" \
-e "292a\VirtualDocumentRoot /var/webapps/%0" \
-e "s/DirectoryIndex index.html index.html.var/DirectoryIndex sorry.html index.html index.htm default.html default.htm index.html.var index.jsp/g" \
-e '500a\LogFormat "%V %h %l %u %t \\"%r\\" %>s %b" vcommon' \
-e '500a\LogFormat "%V %h %l %u %t \\"%r\\" %>s %b \\"%{Referer}i\\" \\"%{User-Agent}i\\"" vcombined' \
-e '504c\LogFormat "%h %l %u %t \\"%r\\" %>s %b \\"%{Referer}i\\" \\"%{User-Agent}i\\" %I %O" combinedio' \
-e "526c\CustomLog logs/access_log combinedio\nCustomLog logs/vhost.log vcombined" \
-e "s/ServerSignature On/ServerSignature Off/g" \
-e "743c\LanguagePriority zh-TW en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN" \
-e "972a\<Location />" \
-e "972a\    # Insert filter" \
-e "972a\    SetOutputFilter DEFLATE\n" \
-e "972a\    # Netscape 4.x has some problems..." \
-e "972a\    BrowserMatch ^Mozilla/4 gzip-only-text/html\n" \
-e "972a\    # Netscape 4.06-4.08 have some more problems" \
-e '972a\    BrowserMatch ^Mozilla/4\\.0[678] no-gzip\n' \
-e "972a\    # MSIE masquerades as Netscape, but it is fine" \
-e '972a\    # BrowserMatch \\bMSIE \!no-gzip \!gzip-only-text/html\n' \
-e "972a\    # NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48" \
-e "972a\    # the above regex won't work. You can use the following" \
-e "972a\    # workaround to get the desired effect:" \
-e '972a\    BrowserMatch \\bMSI[E] \!no-gzip \!gzip-only-text/html\n' \
-e "972a\    # Don't compress images" \
-e '972a\    SetEnvIfNoCase Request_URI \\.(?:gif|jpe?g|png)$ no-gzip dont-vary\n' \
-e "972a\    # Make sure proxies don't deliver the wrong content" \
-e "972a\    Header append Vary User-Agent env=\!dont-vary" \
-e "972a\</Location>\n"  \
-e "972a\RewriteEngine on" \
-e "972a\RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)" \
-e "972a\RewriteRule .* - [F]\n" /etc/httpd/conf/httpd.conf
echo 'cp -p /tmp/httpd.conf /etc/httpd/conf/httpd.conf' >> ${SETUP_DIR}/cleanup.sh

#
# generate SSL key and cert
#
openssl genrsa -out /etc/pki/tls/private/${HOSTNAME}.key 2048
openssl req -new -key /etc/pki/tls/private/${HOSTNAME}.key -out /etc/pki/tls/certs/${HOSTNAME}.csr -subj "/C=${COUNTRY}/ST=${STATE}/L=${LOCATION}/O=${COMPANY}/OU=${ORGANIZATION}/CN=${HOSTNAME}"
openssl x509 -req -days 3650 -in /etc/pki/tls/certs/${HOSTNAME}.csr -signkey /etc/pki/tls/private/${HOSTNAME}.key -out /etc/pki/tls/certs/${HOSTNAME}.crt
echo 'rm -rf /etc/pki/tls/private/'${HOSTNAME}'.key' >> ${SETUP_DIR}/cleanup.sh
echo 'rm -rf /etc/pki/tls/certs/'${HOSTNAME}'.csr' >> ${SETUP_DIR}/cleanup.sh
echo 'rm -rf /etc/pki/tls/certs/'${HOSTNAME}'.crt' >> ${SETUP_DIR}/cleanup.sh

#
# modify ssl.conf
#
sed -i -e "79a\JkMountFile conf/uriworkermap.properties\n" \
-e "s/localhost.crt/${HOSTNAME}.crt/g" \
-e "s/localhost.key/${HOSTNAME}.key/g" /etc/httpd/conf.d/ssl.conf
echo 'cp -p /tmp/ssl.conf /etc/httpd/conf.d/ssl.conf' >> ${SETUP_DIR}/cleanup.sh

/sbin/chkconfig --level 235 httpd on
echo '/sbin/chkconfig httpd off' >> ${SETUP_DIR}/cleanup.sh

#
# check the latest stable version of Tomcat 7.0.x
#
wget http://tomcat.apache.org/whichversion.html -q -t 1 -T 5 -O /tmp/tomcat.html
if [ -s /tmp/tomcat.html ]; then
   TOMCAT_VERSION=`grep "7\.0\." /tmp/tomcat.html|grep -v "7\.0\.x"|cut -d">" -f2|cut -d"<" -f1`
fi
rm -rf /tmp/tomcat.html

echo "Install Tomcat ${TOMCAT_VERSION}"
if [ ! -r apache-tomcat-${TOMCAT_VERSION}.tar.gz ]; then
   wget http://${MIRROR_HOST}/tomcat/tomcat-7/v${TOMCAT_VERSION}/bin/apache-tomcat-${TOMCAT_VERSION}.tar.gz
fi
tar zxvf apache-tomcat-${TOMCAT_VERSION}.tar.gz -C /var
ln -s /var/apache-tomcat-${TOMCAT_VERSION} ${CATALINA_HOME}

echo 'rm -rf /var/apache-tomcat-'${TOMCAT_VERSION} >> ${SETUP_DIR}/cleanup.sh
echo 'rm -rf '${CATALINA_HOME} >> ${SETUP_DIR}/cleanup.sh

#
# check memory size to determine some JVM parameters
#
mem=`cat /proc/meminfo|grep "MemTotal:"|awk '{print $2}'`
let KB=1024
let memsize=$mem/$KB
let heapsize=$memsize/2
let newsize=$heapsize/4
echo 'JAVA_HOME="/usr/java/latest"
JAVA_OPTS="-server -XX:NewSize='${newsize}'m -XX:MaxNewSize='${newsize}'m -XX:SurvivorRatio=8 -XX:MaxPermSize=128m -Xss256k -Xms'${heapsize}'m -Xmx'${heapsize}'m -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true"' > ${CATALINA_HOME}/bin/setenv.sh
chmod 755 ${CATALINA_HOME}/bin/setenv.sh

#
# check the latest stable version of Tomcat Connector 1.2.x
#
# pre-requirment
yum -y install httpd-devel apr-devel libtool automake make gcc gcc-c++

wget http://tomcat.apache.org/download-connectors.cgi -q -t 1 -T 5 -O /tmp/connector.html
if [ -s /tmp/connector.html ]; then
   TOMCAT_CONNECTOR_VERSION=`grep "1\.2\." /tmp/connector.html|cut -d">" -f2|cut -d"<" -f1 |awk '{print $2}'|grep "1.2"|uniq`
fi
rm -rf /tmp/connector.html
echo "Install Tomcat Connector JK ${TOMCAT_CONNECTOR_VERSION}"
if [ ! -r tomcat-connectors-${TOMCAT_CONNECTOR_VERSION}-src.tar.gz ]; then
   wget http://${MIRROR_HOST}/tomcat/tomcat-connectors/jk/tomcat-connectors-${TOMCAT_CONNECTOR_VERSION}-src.tar.gz
fi
tar zxvf tomcat-connectors-${TOMCAT_CONNECTOR_VERSION}-src.tar.gz
cd tomcat-connectors-${TOMCAT_CONNECTOR_VERSION}-src/native
./buildconf.sh
./configure --with-apxs=/usr/sbin/apxs
make
make install
cd ${SETUP_DIR}
echo 'rm -rf /etc/httpd/modules/mod_jk.so' >> ${SETUP_DIR}/cleanup.sh

#
# add user tomcat
#
/usr/sbin/groupadd -g 80 tomcat
/usr/sbin/useradd tomcat -u 80 -g tomcat -d ${CATALINA_HOME} -M
echo '/usr/sbin/userdel -r tomcat' >> ${SETUP_DIR}/cleanup.sh

#
# setup workers' directory
#
mkdir -p ${WORKER_ROOT}/worker1/logs
mkdir -p ${WORKER_ROOT}/worker1/temp
mkdir -p ${WORKER_ROOT}/worker1/work
cp -rf ${CATALINA_HOME}/conf ${WORKER_ROOT}/worker1/conf
mkdir -p ${WEBAPP_ROOT}
ln -s ${WEBAPP_ROOT} ${WORKER_ROOT}/worker1/webapps
cp -rf ${WORKER_ROOT}/worker1 ${WORKER_ROOT}/worker2
echo 'rm -rf '${WORKER_ROOT} >> ${SETUP_DIR}/cleanup.sh
echo 'rm -rf '${WEBAPP_ROOT} >> ${SETUP_DIR}/cleanup.sh

#
# setup default host directory
#
mkdir -p ${WEBAPP_ROOT}/${hostname}
cp -rf ${CATALINA_HOME}/webapps/ROOT/* ${WEBAPP_ROOT}/${hostname}/.
mkdir -p ${WORKER_ROOT}/worker1/conf/Catalina/${hostname}
mkdir -p ${WORKER_ROOT}/worker2/conf/Catalina/${hostname}
cp -rf ${CATALINA_HOME}/webapps/host-manager/manager.xml ${WORKER_ROOT}/worker1/conf/Catalina/${hostname}
cp -rf ${CATALINA_HOME}/webapps/host-manager/manager.xml ${WORKER_ROOT}/worker2/conf/Catalina/${hostname}

#
# generate server.xml
#
echo '<?xml version="1.0" encoding="utf-8"?>
<Server port="workerPort" shutdown="shutdownCode">

  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <GlobalNamingResources>
    <!-- Used by Manager webapp -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
       description="User database that can be updated and saved"
           factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
          pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">
    <!-- Define an AJP 1.3 Connector on port ajpPort -->
    <Connector port="ajpPort" address="127.0.0.1"
               enableLookups="false" maxThreads="1000" connectionTimeout="3000"
               protocol="AJP/1.3" />

    <Engine name="Catalina" defaultHost="mydomain" jvmRoute="workerNo">
    
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      
      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
' > /tmp/server.header.template

sed -e "s/workerPort/8105/g" -e "s/shutdownCode/`head -1024c /dev/urandom | md5sum | cut -d " " -f1`/g" -e "s/ajpPort/8109/g" -e "s/workerNo/worker1/g" -e "s/mydomain/${hostname}/g" /tmp/server.header.template > ${WORKER_ROOT}/worker1/conf/server.header
sed -e "s/workerPort/8205/g" -e "s/shutdownCode/`head -1024c /dev/urandom | md5sum | cut -d " " -f1`/g" -e "s/ajpPort/8209/g" -e "s/workerNo/worker2/g" -e "s/mydomain/${hostname}/g" /tmp/server.header.template > ${WORKER_ROOT}/worker2/conf/server.header
rm -rf /tmp/server.header.template

echo '      <Host name="'${hostname}'" appBase="webapps/'${hostname}'"
            unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve"
               directory="logs" prefix="'${hostname}'_access_log." suffix=".txt" 
               pattern="combined" resolveHosts="false"/>
        <Context path="" docBase="" reloadable="false" />
      </Host>' > ${WORKER_ROOT}/worker1/conf/server.host

cp -rf ${WORKER_ROOT}/worker1/conf/server.host ${WORKER_ROOT}/worker2/conf/server.host

echo '    </Engine>
  </Service>
</Server>' > ${WORKER_ROOT}/worker1/conf/server.footer

cp -rf ${WORKER_ROOT}/worker1/conf/server.footer ${WORKER_ROOT}/worker2/conf/server.footer

cd ${WORKER_ROOT}/worker1/conf
cat server.header server.host server.footer > server.xml
cd ${WORKER_ROOT}/worker2/conf
cat server.header server.host server.footer > server.xml

#
# generate tomcat-users.xml
#
MANAGER_PASSWORD=`head -1024c /dev/urandom | md5sum | cut -d " " -f1 | awk '{print substr($1,1,8)}'`
echo '<?xml version="1.0" encoding="utf-8"?>
<tomcat-users>
  <role rolename="manager-gui"/>
  <user username="manager" password="'${MANAGER_PASSWORD}'" roles="manager-gui"/>
</tomcat-users>' > ${WORKER_ROOT}/worker1/conf/tomcat-users.xml
echo
echo "Your Tomcat Manager's login is 'manager', password is '${MANAGER_PASSWORD}'"
echo
cp -rf ${WORKER_ROOT}/worker1/conf/tomcat-users.xml ${WORKER_ROOT}/worker2/conf/tomcat-users.xml

#
# modify web.xml for production use
#
sed -i -e "240a\        <init-param>\n            <param-name>genStringAsCharArray</param-name>\n            <param-value>true</param-value>\n        </init-param>" \
-e "240a\        <init-param>\n            <param-name>trimSpaces</param-name>\n            <param-value>true</param-value>\n        </init-param>" ${WORKER_ROOT}/worker1/conf/web.xml
cp -rf ${WORKER_ROOT}/worker1/conf/web.xml ${WORKER_ROOT}/worker2/conf/web.xml

chmod 600 ${WORKER_ROOT}/worker*/conf/server.*
chmod 600 ${WORKER_ROOT}/worker*/conf/tomcat-users.xml
chown -R tomcat:tomcat ${WORKER_ROOT}

#
# generate mod_jk.conf
#
echo 'LoadModule jk_module modules/mod_jk.so

JkWorkersFile /etc/httpd/conf/workers.properties
JkShmFile     logs/jk-runtime-status
JkLogFile     "|/usr/sbin/rotatelogs /var/log/httpd/mod_jk.log 86400"
JkLogLevel info
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"
JkRequestLogFormat     "%w %V %T"
LogFormat     "%h %l %u %t \"%r\" %>s %b %{JK_WORKER_NAME}n %{JK_LB_FIRST_NAME}n %{JK_LB_FIRST_BUSY}n %{JK_LB_LAST_NAME}n %{JK_LB_LAST_BUSY}n" mod_jk_log
CustomLog     logs/worker_access_log     mod_jk_log

# Load mount points
JkMountFile conf/uriworkermap.properties

# Deny direct access to WEB-INF
<LocationMatch ".*WEB-INF.*">
    deny from all
</LocationMatch>' > /etc/httpd/conf.d/mod_jk.conf
echo 'rm -rf /etc/httpd/conf.d/mod_jk.conf' >> ${SETUP_DIR}/cleanup.sh

#
# generate workers.properties
#
echo '# workers.properties - ajp13
#
# List workers
#
worker.list=loadbalancer, jkstatus

#
# Define worker1
#
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8109
worker.worker1.socket_timeout=1200
worker.worker1.connection_pool_size=1
worker.worker1.connection_pool_timeout=1300
worker.worker1.lbfactor=1
# Define prefered failover node for worker1
worker.worker1.redirect=worker2

#
# Define worker2
#
worker.worker2.type=ajp13
worker.worker2.host=localhost
worker.worker2.port=8209
worker.worker2.socket_timeout=1200
worker.worker2.connection_pool_size=1
worker.worker2.connection_pool_timeout=1300
worker.worker2.lbfactor=1
# Disable worker2 for all requests except failover
worker.worker2.activation=d

#
# Defining a load balancer
#
worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=worker1, worker2

#
# Define status worker
#
worker.jkstatus.type=status' > /etc/httpd/conf/workers.properties
echo 'rm -rf /etc/httpd/conf/workers.properties' >> ${SETUP_DIR}/cleanup.sh

#
# generate uriworkermap.properties
#
echo '/jkmanager/*=jkstatus
/*.jsp=loadbalancer
/*.page=loadbalancer
/servlet/*=loadbalancer
/manager/*=loadbalancer' > /etc/httpd/conf/uriworkermap.properties
echo 'rm -rf /etc/httpd/conf/uriworkermap.properties' >> ${SETUP_DIR}/cleanup.sh

#
# generate tomcat startup script
#
echo '#!/bin/sh
#
# tomcat       Startup script for Tomcat, the Apache Servlet Engine
#
# chkconfig: - 84 16
# description: Tomcat Servlet Engine
# processname: tomcat
# pidfile: /var/run/worker1.pid /var/run/worker2.pid

# Source function library.
. /etc/rc.d/init.d/functions

# User under which tomcat will run
TOMCAT_USER=tomcat

RETVAL=0

CATALINA_HOME='${CATALINA_HOME}'
WORKER_ROOT='${WORKER_ROOT}'
WORKER_LIST=( worker1 worker2 )
WORKER_PORT=( 8105 8205 )
WORKER_AJP_PORT=( 8109 8209 )

# start, debug, stop, and status functions
start() {
    i=$1
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Tomcat ${WORKER_LIST[i]} already started"
    else
        echo "Starting tomcat ${WORKER_LIST[i]}..."
        CATALINA_BASE="$WORKER_ROOT/${WORKER_LIST[i]}"
        su -l $TOMCAT_USER -c "export CATALINA_BASE=$CATALINA_BASE; $CATALINA_HOME/bin/startup.sh"
        echo -n "Processing ..."
        SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
        while [ $SHUTDOWN_PORT -eq 0 ]; do
            echo -n "..."
            sleep 10
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
        done
        echo " Done!"
        echo "Tomcat ${WORKER_LIST[i]} started in normal mode"
        RETVAL=$?
        [ $RETVAL = 0 ] && touch /var/lock/subsys/${WORKER_LIST[i]} /var/run/${WORKER_LIST[i]}.pid
    fi
}

debug() {
    i=$1
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Tomcat ${WORKER_LIST[i]} already started"
    else
        echo "Starting tomcat ${WORKER_LIST[i]} in debug mode..."
        CATALINA_BASE="$WORKER_ROOT/${WORKER_LIST[i]}"
        rm -rf $CATALINA_BASE/work/*

        chown -R $TOMCAT_USER:$TOMCAT_USER $CATALINA_HOME
        chown -R $TOMCAT_USER:$TOMCAT_USER $WORKER_ROOT
        su -l $TOMCAT_USER -c "export CATALINA_BASE=$CATALINA_BASE; $CATALINA_HOME/bin/catalina.sh jpda start"
        echo -n "Processing ..."
        SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
        while [ $SHUTDOWN_PORT -eq 0 ]; do
            echo -n "..."
            sleep 10
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_PORT[i]}|wc -l`
        done
        echo " Done!"
        echo "Tomcat ${WORKER_LIST[i]} started in debug mode"
        RETVAL=$?
        [ $RETVAL = 0 ] && touch /var/lock/subsys/${WORKER_LIST[i]} /var/run/${WORKER_LIST[i]}.pid
    fi
}

stop() {
    i=$1
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_AJP_PORT[i]}|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Tomcat ${WORKER_LIST[i]} already stopped"
    else
        echo "Stopping tomcat ${WORKER_LIST[i]} ..."
        CATALINA_BASE="$WORKER_ROOT/${WORKER_LIST[i]}"
        su -l $TOMCAT_USER -c "export CATALINA_BASE=$CATALINA_BASE; $CATALINA_HOME/bin/shutdown.sh"
        echo -n "Processing ..."
        SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_AJP_PORT[i]}|wc -l`
        while [ $SHUTDOWN_PORT -ne 0 ]; do
            echo -n "..."
            sleep 10
            PROCESS_COUNT=`ps -ef|grep ${WORKER_LIST[i]}|grep -v grep|wc -l`
            if [ $PROCESS_COUNT -ne 0 ]; then
                kill -9 `ps -ef|grep ${WORKER_LIST[i]}|grep -v grep|awk '\'{print \$2}\''`
            fi
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_AJP_PORT[i]}|wc -l`
        done
        echo " Done!"
        echo "Tomcat ${WORKER_LIST[i]} stopped"
        RETVAL=$?
        [ $RETVAL=0 ] && rm -f /var/lock/subsys/${WORKER_LIST[i]} /var/run/${WORKER_LIST[i]}.pid
    fi
}

status() {
  for (( i = 0 ; i < ${#WORKER_LIST[@]} ; i++ ))
  do
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep ${WORKER_AJP_PORT[i]}|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Tomcat ${WORKER_LIST[i]} stopped"
    else
        MODE="normal"
        JPDA_PORT=`netstat -vatn|grep LISTEN|grep 8000|wc -l`
        if [ $JPDA_PORT -ne 0 ]; then
            MODE="debug"
        fi
        echo "Tomcat ${WORKER_LIST[i]} running in $MODE mode"
    fi
  done
}

case "$1" in
  start)
        start 0
        start 1
        ;;
  debug)
        debug 0
        debug 1
        ;;
  stop)
        stop 0
        stop 1
        ;;
  restart)
        stop 0
        start 0
        stop 1
        start 1
        ;;
  redebug)
        stop 0
        debug 0
        stop 1
        debug 1
        ;;
  status)
  	status
	;;
  *)
	echo "Usage: $0 {start|debug|stop|restart|redebug|status}"
	exit 1
esac

exit $RETVAL' > /etc/rc.d/init.d/tomcat

chmod 755 /etc/rc.d/init.d/tomcat
/sbin/chkconfig --add tomcat
/sbin/chkconfig --level 235 tomcat on

echo '/sbin/chkconfig tomcat off' >> ${SETUP_DIR}/cleanup.sh
echo '/sbin/chkconfig --del tomcat' >> ${SETUP_DIR}/cleanup.sh
echo 'rm -rf /etc/rc.d/init.d/tomcat' >> ${SETUP_DIR}/cleanup.sh

chmod 755 ${SETUP_DIR}/cleanup.sh

echo 'Tomcat installation is completed!'
echo
echo 'You can type "/etc/init.d/tomcat start" to start using tomcat now.'
echo 'You can type "/etc/init.d/httpd start" to start using apache now.'
echo 'Open a browser, and go to http://'${hostname}' to see it.'

#
# modify web.xml for cluster test
#
sed -i -e "26a\  <distributable/>" ${WEBAPP_ROOT}/${hostname}/WEB-INF/web.xml

#
# generate clustertest.jsp for cluster test
#
echo '<%@ page contentType="text/html; charset=UTF-8" import="java.util.*"%>
<html>
<head>
<title>Cluster Session Replication Test</title>
</head>
<body>
<%
    out.println("Session ID=" + session.getId() + "<br>");
 
    String key = request.getParameter("key");
    if (key != null && key.length() > 0) {
        String value = request.getParameter("value");
        session.setAttribute(key, value);
    }
 
    out.println("<b>Session Listing</b><br>");
 
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = (String)session.getAttribute(name);
        out.println(name + " = " + value + "<br>");
    }
%>

  <form method="post">
    key:<input type="text" size="20" name="key"> <br>
    value:<input type="text" size="20" name="value"> <br>
    <input type="submit">
  </form>
</body>
</html>' > ${WEBAPP_ROOT}/${hostname}/clustertest.jsp


4.Then you can use the following two commands to do step12
service tomcat start
service httpd start
5. For testing, you can use the following command to shutdown or startup a single Tomcat worker:
su -l tomcat -c "export CATALINA_BASE=/var/robust/worker1; /var/tomcat7/bin/shutdown.sh"
su -l tomcat -c "export CATALINA_BASE=/var/robust/worker1; /var/tomcat7/bin/startup.sh"
su -l tomcat -c "export CATALINA_BASE=/var/robust/worker2; /var/tomcat7/bin/shutdown.sh"
su -l tomcat -c "export CATALINA_BASE=/var/robust/worker2; /var/tomcat7/bin/startup.sh"

Or you may use a shell script to restart Tomcat repeatedly to verify if the session replication really works.
restart.sh
 for (( i = 0 ; i < 10 ; i++ ))
  do
     service tomcat restart
  done


If you can see all of the session objects no matter how Tomcat is restarted, then Tomcat clustering(session replication) is done.

Note: If you have enabled firewall like iptables, please add http(80:tcp), https(443:tcp) and 45564:udp port to the allowed list.

6. Finally, browse https://<your_server_ip>/ to check SSL works. You have to add this site as your trust site because we use a self-signed SSL certificate.

Reference:
http://tomcat.apache.org/connectors-doc/reference/apache.html
http://tomcat.apache.org/connectors-doc/generic_howto/loadbalancers.html
http://tomcat.apache.org/tomcat-7.0-doc/cluster-howto.html
http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html
http://tomcat.apache.org/tomcat-7.0-doc/logging.html
http://www.easywayserver.com/tomcat-clustering.htm
http://www.easywayserver.com/implementation-tomcat-clustering.htm
I don't have any experience on this kind of application. Here are some hints, you can try them yourself.
1.You may reference the net.jforum.view.install.InstallAction.java's saveMessage() method:
	private void saveMessage(final Connection conn, final String subject, final String message, final int topicType, final int forumId, final int userId, final String sourceIp) 
	{
		try {
			ConfigLoader.createLoginAuthenticator();
			ConfigLoader.loadDaoImplementation();			
			SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_GENERIC));
			SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_DRIVER));		
			
			final JForumExecutionContext executionContext = JForumExecutionContext.get();
			executionContext.setConnection(conn);
			JForumExecutionContext.set(executionContext);
			
			final User user = new User(userId);
			
			// Create topic
			final Topic topic = new Topic();
			topic.setPostedBy(user);
			topic.setTitle(subject);
			topic.setTime(new Date());
			topic.setType(topicType);
			topic.setForumId(forumId);
			
			final TopicDAO topicDao = DataAccessDriver.getInstance().newTopicDAO();
			topicDao.addNew(topic);
			
			// Create post
			final Post post = new Post();
			post.setSubject(topic.getTitle());
			post.setTime(topic.getTime());
			post.setUserId(user.getId());
			post.setText(message);
			post.setForumId(topic.getForumId());
			post.setSmiliesEnabled(true);
			post.setHtmlEnabled(true);
			post.setBbCodeEnabled(true);
			post.setUserIp(sourceIp);
			post.setTopicId(topic.getId());
			
			final PostDAO postDao = DataAccessDriver.getInstance().newPostDAO();
			postDao.addNew(post);
			
			// Update topic
			topic.setFirstPostId(post.getId());
			topic.setLastPostId(post.getId());
			
			topicDao.update(topic);
			DataAccessDriver.getInstance().newUserDAO().incrementPosts(post.getUserId());
			
			// Update forum stats
			final ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();
			forumDao.incrementTotalTopics(forumId, 1);
			forumDao.setLastPost(forumId, post.getId());
		}
		finally {
			final JForumExecutionContext executionContext = JForumExecutionContext.get();
			executionContext.setConnection(null);
			JForumExecutionContext.set(executionContext);
		}
	}


2.You may reference the net.jforum.api.integration.mail.pop.POPPostAction.java's insertMessages() method.
 
Forum Index » Profile for andowson » Messages posted by andowson
Go to: