Centos 5.5(Dell R610)安装Nginx 0.8、MySQL、php 5.3.4、Nagios监控

远程链接工具Puttp,下载地址http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe

第一步,修改SSH配置

vi /etc/ssh/sshd_config

将PermitRootLogin yes修改为PermitRootLogin no禁止root用户远程登录,提高系统安全性。
重新启动sshd

/sbin/service sshd restart
或者
/etc/init.d/sshd restart

第二步:安装基础软件
这些软件是系统所需要的基础软件,执行前请确保已经联网。

sudo -s
LANG=C
yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers

顺手更新下系统

yum update

喝杯水,看着屏幕,一路yes。需要配置成国内的dns,使用163的centos源,安装速度比较快。

第三步:安装附加软件,下载地址请自己Google。
内部同事请修改host,

vi /etc/hosts

添加 192.168.1.3 svn.xxx.cn。
然后

cd /app
svn co svn://svn.xxx.cn/xxx/server/trunk software
cd software

1、安装iconv库,干嘛用的请google

tar zxvf libiconv-1.13.tar.gz
cd libiconv-1.13/
./configure --prefix=/usr/local
make
make install
cd ../

2、安装mcrypt库

tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make
make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

3、安装mhash

tar zxvf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9/
./configure
make
make install
cd ../

4、建立软链接

ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config

5、安装mcrypt

tar zxvf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make
make install
cd ../

6、安装ImageMagick

tar zxf ImageMagick.tar.gz
cd ImageMagick-6.5.1-2/
./configure
make
make install
cd ../

7、安装libevent

tar xf libevent-1.4.14b-stable.tar.gz
cd libevent-1.4.14b-stable
./configure --prefix=/usr
make
make install
cd ..

8、安装memcached

tar xf memcached-1.4.5.tar.gz
cd memcached-1.4.5
./configure --with-libevent=/usr
make
make install
cd ..

以11211端口启动Memcached

/usr/local/bin/memcached -d -p 11211 -u nobody -m 2048 -c 10240 -P /var/run/memcached/memcached.pid

第四步:安装MySQL
1、添加MYSQL用户

/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql

2、安装MySQL

tar xf mysql-5.1.50.tar.gz
cd mysql-5.1.50/
./configure --prefix=/app/mysql/ --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile --with-plugins=partition,innobase,myisammrg
make && make install

3、更改文件权限

chmod +w /app/mysql
chown -R mysql:root /app/mysql

4、创建配置文件和启动服务

cp support-files/my-huge.cnf /etc/my.cnf
cp support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld

5、初始化数据库

/app/mysql/bin/mysql_install_db --user=mysql

6、启动数据库

cd ../
/sbin/service mysqld start

第五步:安装PHP 5.3.4
1、安装php主程序

tar xf php-5.3.4.tar.gz
cd php-5.3.4
./configure --prefix=/app/php --with-config-file-path=/app/php/etc --with-mysql=/app/mysql --with-pdo-mysql=/app/mysql/ --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap --enable-ftp
make ZEND_EXTRA_LIBS='-liconv'
make install
cp php.ini-production /app/php/etc/php.ini
cd ../

2、安装memcache扩展

tar zxvf memcache-2.2.6.tgz
cd memcache-2.2.6/
/app/php/bin/phpize
./configure --with-php-config=/app/php/bin/php-config
make
make install
cd ../

3、安装imagick扩展

tar zxvf imagick-3.0.1.tgz
cd imagick-3.0.1/
/app/php/bin/phpize
./configure --with-php-config=/app/php/bin/php-config
make
make install
cd ../

4、安装xcache扩展

tar xf xcache-1.3.1.tar.gz
cd xcache-1.3.1
/app/php/bin/phpize
./configure --enable-xcache --with-php-config=/app/php/bin/php-config
make
make install
cd ../

5、修改php.ini文件 /app/etc/php.ini

extension_dir = "/app/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension = "memcache.so"
extension = "imagick.so"
short_open_tag = On
memory_limit = 512M
expose_php = Off

6、启动PHP FPM

ulimit -SHn 65535
/app/php/sbin/php-fpm

可以用 ps aux|grep php来验证下是否已经启动php-fpm

第六步:安装Nginx
1、安装PCRE

tar zxvf pcre-8.01.tar.gz
cd pcre-8.01/
./configure
make && make install
cd ../

2、安装openssl

tar zxvf ./openssl-0.9.8l.tar.gz
cd ./openssl-0.9.8l
./config enable-tlsext
make
make install
cd ..

3、安装Nginx

tar zxvf nginx-0.8.50.tar.gz
cd nginx-0.8.50/
./configure --user=nobody --group=nobody --prefix=/app/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module --with-openssl=../openssl-0.9.8l/ --with-openssl-opt="enable-tlsext"
make && make install
cd ../

4、启动Nginx

ulimit -SHn 65535
/app/nginx/sbin/nginx

5、创建日志切割脚本

vi /app/nginx/sbin/cut_nginx_log.sh

添加内容如下

#!/bin/bash
# This script run at 00:00
 
# The Nginx logs path
logs_path="/app/nginx/logs/"
 
mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /app/nginx/logs/nginx.pid`

用Crontab使其每日凌晨自动运行

crontab -e

添加内容

00 00 * * * /bin/bash  /app/nginx/sbin/cut_nginx_log.sh

第七步:优化系统
1、修改/etc/sysctl.conf文件,添加下列内容到文件末尾

# Add
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog =  32768
net.core.somaxconn = 32768
 
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
 
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
 
net.ipv4.tcp_tw_recycle = 1
#net.ipv4.tcp_tw_len = 1
net.ipv4.tcp_tw_reuse = 1
 
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
 
#net.ipv4.tcp_fin_timeout = 30
#net.ipv4.tcp_keepalive_time = 120
net.ipv4.ip_local_port_range = 1024  65535

使之立即生效

/sbin/sysctl -p

第八步:安装ntp进行时间同步

yum install ntp
/usr/sbin/ntpdate 0.pool.ntp.org

下面进行ntp内网服务器的配置,注意非服务器不用执行下面的步骤
1、修改ntp配置文件
vi /etc/ntp.conf

# Hosts on local network are less restricted.
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap #去掉前面的注释,允许内网其他机器访问服务器。

2、vi /etc/ntp/step-tickers

#添加国际标准时间服务器
0.pool.ntp.org
1.pool.ntp.org
2.pool.ntp.org

3、启动NTPD时间服务器

/sbin/service ntpd start
/sbin/chkconfig ntpd on

第九步,安装Nagios监控
被监控机(即被监测服务器,非监测服务器,一般web服务器都是被监测的对象。)
1、添加用户

/usr/sbin/groupadd nagios
/usr/sbin/useradd -g nagios -d /app/nagios -s /sbin/nologin nagios

2、安装plugin

tar zxf nagios-plugins-1.4.15.tar.gz
cd nagios-plugins-1.4.15
./configure --with-nagios-user=nagios --with-nagios-group=nagios --prefix=/app/nagios --with-ping-command="/bin/ping" --with-mysql=/app/mysql --enable-perl-modules
make
make install
cd ..

3、安装Nrpe

tar zxvf nrpe-2.12.tar.gz
cd nrpe-2.12
./configure --prefix=/app/nagios
make all
make install-plugin
make install-daemon
make install-daemon-config
chown -R nagios:nagios /app/nagios

4、配置Nagios,即允许哪个服务器访问

vi /app/nagios/etc/nrpe.cfg
allowed_hosts=127.0.0.1,192.168.11.110

修改/etc/hosts.allow增加监控机ip

echo 'nrpe:192.168.1.110' >> /etc/hosts.allow

5、启动 NRPE 守护进程:

/app/nagios/bin/nrpe -c /app/nagios/etc/nrpe.cfg -d

可以将此命令加入 /etc/rc.local ,以便开机自动启动。

echo "/app/nagios/bin/nrpe -c /app/nagios/etc/nrpe.cfg -d" >> /etc/rc.local

检查 NRPE 是否正常:
在被监控机上

/app/nagios/libexec/check_nrpe -H 127.0.0.1

查看相应的端口:netstat -an |grep 5666
防火墙开启5666 允许局域网IP或固定IP连接
在监控主机上

/app/nagios/libexec/check_nrpe -H $目标主机地址

都应该可以输出 NRPE 的版本: NRPE v2.12
检查可监控的服务
在被监控端的 nrpe.cfg 文件中,可以看到这样的配置:
command[check_load]=/usr/local/nagios/libexec/check_load -w 15,10,5 -c 30,25,20
这是用来检查 CPU 负载的。
如果需要自定参数则使用下面命令
command[check_load]=/usr/local/nagios/libexec/check_load -w $ARG1$ -c $ARG2$
并开启dont_blame_nrpe =1
开启参数将会带来一定的安全风险

附:
创建用户

/usr/sbin/useradd somebody
passwd somebody

修改DNS

vi /etc/resolv.conf

去除所有内容
添加

nameserver 202.96.209.5

关闭防火墙命令

/sbin/service iptables stop
或者
/etc/init.d/iptables stop

重启网络

/sbin/service network restart

重新安装Dell R610网卡驱动,系统自带的驱动和网卡硬件不兼容,在高负载下网卡会停止运行

tar xf Bcom_LAN_14.1.5_Linux_Source_A00.tar.gz
cd Bcom_LAN_14.1.5_Linux_Source_A00/NetXtremeII/
rpm -ivh netxtreme2-5.0a.10-1.src.rpm
cd /usr/src/redhat/
rpmbuild -bb SPECS/netxtreme2.spec
rpm -ivh RPMS/x86_64/netxtreme2-5.0a.10-1.x86_64.rpm 
cd /app/software/Bcom_LAN_14.1.5_Linux_Source_A00
echo "/sbin/rmmod bnx2;/sbin/modprobe bnx2;" > lan_dr_up.sh
chmod +x lan_dr_up.sh
./lan_dr_up.sh &

安装并启动Rsync
为磁盘同步做准备

/usr/bin/rsync --daemon
echo "/usr/bin/rsync --daemon" >> /etc/rc.local

Magento备忘-通过某一个字段来Load对象

Magento提供了灵活的方式去获取一个对象,比如说Load、比如说Collection,等。。。 我们今天说的是Load函数。

很多人将表的主键值传到Mage_Core_Model_Abstract的load函数中去获取对象,而要通过表里面的某一个字段值来获取呢?

看下Load函数:

    /**
     * Load object data
     *
     * @param   integer $id
     * @return  G_Core_Model_Abstract
     */
    public function load($id, $field=null)
    {
        $this->_beforeLoad($id, $field);
        $this->_getResource()->load($this, $id, $field);
        $this->_afterLoad();
        $this->setOrigData();
        $this->_hasDataChanges = false;
        return $this;
    }

其实Load函数本身就支持传入某个字段,即通过某个字段去获取对象。

便于理解,我举个实际例子,通过Coupon Code来获取Coupon对象:

$coupon = Mage::getModel('salesrule/coupon')->load('discount50%off','code');

Magento随笔-关于SalesRule模块的问题

Magento的购物车促销规则和商品促销规则,看起来确实强大。乍一看强大得让人惊叹,不过只是浮云。为什么?因为你会发现,他无法做很多实际的促销活动。

我就拿我所在的服装行业为例:

第一,只能购物车中单个商品进行促销配置,无法进行组合促销。

我们通常会有“买两条牛仔裤,T恤衫50%折扣”。试问如何用Magento实现? 注意两条牛仔裤是不同款式的。因为几乎不会有顾客同时买同样一条牛仔库(同尺码、同颜色,即同SKU)。估计这个规则卖卖鸡蛋白菜还差不多。

第二,Best Deal不支持,只能用排序和是否停止匹配下一个规则来设置Rule。

什么意思呢?就是最佳折扣方式,比如有一个A “Buy N of X for Z$off” 和 B “Buy N of X get Y at 50% off”两个促销规则同时存在购物车里,那么A、B的应用顺序不一样,最终金额是不一样的,而不是通过SORT简单的配置A在B前面就可以的。虽然不容易做,但是这是一个促销模块应该考虑到的问题。

第三,如果是可配置商品,那么规则只能匹配可配置商品,不能具体匹配到最终购买的简单商品。

直接看代码吧,代码在SalesRule_Model_Quote_Discount里面。看这里 “Child item discount we calculate for parent”

/**
 * Child item discount we calculate for parent
 */
if ($item->getParentItemId()) {
    continue;
}

无法匹配子商品。都是问题。。。不过这个问题可以通过简单修改SalesRule_Model_Rule_Condition_Product来实现。

    /**
     * Validate Product Rule Condition (Upgrade by Joshua for apply child product)
     *
     * @param Varien_Object $object
     * @return bool
     */
    public function validate(Varien_Object $object)
    {
        $product = G::getModel('catalog/product')
            ->load($object->getProductId())
            ->setQuoteItemQty($object->getQty())
            ->setQuoteItemPrice($object->getPrice())
            ->setQuoteItemRowTotal($object->getRowTotal());
		$result = parent::validate($product);
		if($result){
			return $result;
		}elseif(count($object->getChildren()>0)){
			foreach ($object->getChildren() as $child){
		        $product = G::getModel('catalog/product')
		            ->load($child->getProductId())
		            ->setQuoteItemQty($object->getQty())
		            ->setQuoteItemPrice($object->getPrice())
		            ->setQuoteItemRowTotal($object->getRowTotal());
				$result = parent::validate($product);
				if($result)return $result;
			}
		}else{
			return $result;
		}
    }

有朋友也在使用Magento开展他们业务,并津津乐道,也许真是行业差异吧。

Magento备忘-EAV商品表直接取某一字段值

比通过模型LOAD商品模型后再用getData取值快

G::getResourceModel('catalog/product')->getAttributeRawValue($entityId, $attribute, $store)

getAttributeRawValue函数参考

    /**
     * Retrieve attribute's raw value from DB.
     *
     * @param int $entityId
     * @param int|string|array $attribute atrribute's ids or codes
     * @param int|G_Core_Model_Store $store
     * @return bool|string|array
     */
    public function getAttributeRawValue($entityId, $attribute, $store)

在CENTOS 5.5下安装JIRA

一、首先是准备相关软件:

1、从官方网站下载JIRA最新版,注意请选择Linux版本。

atlassian-jira-enterprise-4.2.1-b588-standalone.tar.gz

2、然后去SUN网站下载JDK

jdk-6u23-linux-x64.bin

二、开始安装JIRE

1.java安装和设置JAVA_HOME

把jdk-6u20-linux-i586.bin下载到/home/joshua,然后执行sh自解压脚本

sh jdk-6u23-linux-x64.bin

当前目录会有一个jdk1.6.0_23,将该目录移动到/app/,并改为名java。

设置环境变量JAVA_HOME

这一步有很多方法,修改各种配置文件中的一个。我采取的方法是

vi /etc/profile

在文件后面两行加上

export JAVA_HOME=/app/java
export CLASSPATH=$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib
export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH:$HOME/bin
export JIRA_HOME=/app/jira/

后面一行是接下来配置JIRA_HOME时候加上去的(可选,因为JIRA本身有配置文件配置这个路径)。

接下来使配置文件生效

source /etc/profile

这个时候echo $JAVA_HOME 就会圆满了。

[root@sys ~]# echo $JAVA_HOME
/app/java

不放心的话也可以验证一下其他路径。可以输入

java -version

看看是否得到如下结果:
[root@sys app]# java -version
java version “1.6.0_23″
Java(TM) SE Runtime Environment (build 1.6.0_23-b05)
Java HotSpot(TM) 64-Bit Server VM (build 19.0-b09, mixed mode)

2.JIRA安装

由于mysql已经安装好了,我只需要准备连接jar包。

a.安装JIRA
cd ~/
tar -zxvf atlassian-jira-enterprise-4.2.1-b588-standalone.tar.gz
mv atlassian-jira-enterprise-4.2.1-b588-standalone /app/jira

下载mysql连接jar包,还是到~/下执行

wget http://mysql.ntu.edu.tw/Downloads/Connector-J/mysql-connector-java-5.1.12.tar.gz

然后解压并吧jar包复制一份到jira的lib目录下。

[root@sys ~]# tar xf mysql-connector-java-5.1.12.tar.gz
[root@sys ~]# cd mysql-connector-java-5.1.12
[root@sys mysql-connector-java-5.1.12]# cp mysql-connector-java-5.1.12-bin.jar /app/java/lib/

接下来就是修改JIRA的配置文件了。

配置JIRA_HOME,可以通过之前的办法设置,也可以修改jira-application.properties文件

vi /app/jira/atlassian-jira/WEB-INF/classes/jira-application.properties

将jira.home =修改为
jira.home = /app/jira

vi /app/jira/atlassian-jira/WEB-INF/classes/entityengine.xml

找到 部分将field-type-name 修改为mysql。

修改为:

并且删除schema-name="PUBLIC",because it only works for a field-type-name of "hsql"。

然后修改server.xml文件

[root@sys ~]# vi /app/jira/conf/server.xml

找到数据库连接源部分,修改为

driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost:3306/jira?autoRconnect=true&useUnicode=true&characterEncoding=UTF8"
username="jira"
password="password"
maxActive="20"
/>
注意在此之前你应该在你的mysql上建立jira数据库,字符集是UTF-8。开始的时候我的url部分只是写成:

$ sudo /usr/sbin/useradd –create-home –home-dir /usr/local/jira –shell /bin/bash jira

Ensure that only the following directories can be written to by Tomcat:

•logs
•temp
•work
•database (this directory will be created the first time you run JIRA)
•your JIRA Home directory

chown -R jira:jira /app/jira

关闭和启动JIRA的方法是:

/bin目录下执行:

./shutdown.sh
./startup.sh

这个时候就可以通过浏览器访问JIRA 了,IP地址(或者域名)加上端口号8080。

插入到数据库的中文,读出来的中文,乱码。解决方案是:

将数据库连接源配置文件中的:

url=”jdbc:mysql://localhost:3306/jira”

修改为

url=”jdbc:mysql://localhost:3306/jira?autoRconnect=true&useUnicode=true&characterEncoding=UTF8″

使用SVNSYNC来同步SVN仓库

明天公司停电, SVN仓库用不成了.所以趁没停电前把仓库移动到公网.
PS我现在在家里.

第一步,在公网服务器中创建一个新的仓库:

svnadmin create rep

第二步,创建空的文件,该文件是允许修订版本属性的修改用的

vi rep/hooks/pre-revprop-change
:wq
echo "#!/bin/sh" > rep/hooks/pre-revprop-change
chmod 755 rep/hooks/pre-revprop-change

第三步,初始化公网的新仓库

svnsync initialize file:///app/rep svn://svn.xxx.com/aaa

第四部,开始同步版本库

svnsync sync file:///app/rep

你可以看到有输出内容:
Committed revision 1.
Copied properties for revision 1.
……..
好了,先去吃饭去,回来看结果.库比较大,让服务器自己搬砖头去吧…

吃过饭后看
发现同步好慢哦。。。

最终还是停电了,没同步完。。。。

不过使用SVNSYNC来做SVN仓库的备份也不错。

来电后再次使用SVNSYNC,报错:

[root@sys app]# svnsync sync file:///app/rep
Failed to get lock on destination repos, currently held by 'sys.xxx.cn:b4
Failed to get lock on destination repos, currently held by 'sys.xxx.cn:b4
svnsync: Couldn't get lock on destination repos after 10 attempts

在网上查了下,是属性被锁住了,使用如下命令解锁。

svn propdel svn:synclock --revprop  -r0  file:///app/rep

再次同步就好了

svnsync sync file:///app/rep

Magento深入理解-Grid报错clause is ambiguous问题

我记得之前没少讲过Grid,今天在写Grid遇到这样一个错误,将解决办法分享下。

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'increment_id' in where clause is ambiguous

这个错误怎么来的呢,关键是clause is ambiguous。

使用Grid必须要设置一个Collection,往往这个Grid需要联表查询,就是写join语句。请看下面例子:

    protected function _getCollectionClass()
    {
        return 'sales/order_shipment_grid_collection';
    }
 
    protected function _prepareCollection()
    {
        $collection = G::getResourceModel($this->_getCollectionClass());
        $collection->getSelect()
        			->joinLeft(array('o'=>'sales_flat_order'),'main_table.order_id = o.entity_id','grand_total')
        			->joinLeft(array('st'=>'sales_flat_shipment_track'),'main_table.order_id = st.order_id',array('carrier_code','number','shipped_time'));
 
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

这段例子是我改写后台配送模块时用到的。原来只是一个简单的表,因为需要跟COD结算、还要监督发货部门的效率。所以需要将订单金额、发货时间等等联表查询出来,问题出在shipment表有个increment_id字段,而关联的order表同样也有这个increment_id字段。

按下面的这样来配置Grid:

        $this->addColumn('increment_id', array(
            'header'    => G::helper('sales')->__('Shipment #'),
            'index'     => 'increment_id',
            'type'      => 'text',
        ));

本来我们这里的increment id是物流号,而订单里的increment id是订单号,打开页面,Grid可以正常显示,但是当尝试搜索物流号的时候就会报错了,就是上面的错误。
于是开始找哇,几乎看遍了后台所有的grid,就不信找不到,终于出现了这样一段代码:

        $this->addColumn('created_at', array(
            'header'    =>G::helper('reports')->__('Created At'),
            'width'     =>'170px',
            'type'      =>'datetime',
            'index'     =>'created_at',
            'filter_index'=>'main_table.created_at',
            'sortable'  =>false
        ));
 
        $this->addColumn('updated_at', array(
            'header'    =>G::helper('reports')->__('Updated At'),
            'width'     =>'170px',
            'type'      =>'datetime',
            'index'     =>'updated_at',
            'filter_index'=>'main_table.updated_at',
            'sortable'  =>false
        ));

请看G_Adminhtml_Block_Report_Shopcart_Abandoned_Grid这个文件。
原来Column可以设置filter_index,之前自己还尝试’index’=>’main_table.increament_id’等等,原来这样就可了,于是上面我改的代码变成了这样:

        $this->addColumn('increment_id', array(
            'header'    => G::helper('sales')->__('Shipment #'),
            'index'     => 'increment_id',
            'filter_index' =>'main_table.increment_id',
            'type'      => 'text',
        ));

爽~~过滤正常了~~ :)

Magento深入理解-原来将数据导出Excel&Csv是如此容易

在领教Magento后台Grid强大之后,今天又发现一个更简便的方法,可以将Grid快速导出到CSV或者Excel.

大家可看这个是后台Mage_Adminhtml_Sales_ShipmentController的一段代码,说到家还是Grid的强大,$grid可以直接调用getCsvFile或getCsvFile。

    /**
     * Export shipment grid to CSV format
     */
    public function exportCsvAction()
    {
        $fileName   = 'shipments.csv';
        $grid       = $this->getLayout()->createBlock('adminhtml/sales_shipment_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
    }
 
    /**
     *  Export shipment grid to Excel XML format
     */
    public function exportExcelAction()
    {
        $fileName   = 'shipments.xml';
        $grid       = $this->getLayout()->createBlock('adminhtml/sales_shipment_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
    }

Gap.cn上线实录

历时4个月;
从“ProjectG-Where dream come true.”到“Night is coming in the past, the day soon come.”,

从毛坯到明亮的办公室,

从迎龙转战到3131,

从设计变成产品,

多少个不眠的日夜,多少张尘埃满面的脸庞。

多少滴泪水、又多少行眼泪、多少次争论、如今一切都变得值得。

“Dream has come true!”!

阅读全文

Performance is Key! – Notes on Magento’s Performance

原文:http://www.magentocommerce.com/blog/comments/performance-is-key-notes-on-magentos-performance/

Magento’s performance is key.

在过去的几个月中,我们投入大量资源,诊断和优化Magento的性能。现在Magento 1.0的主要功能已经完成,我们很高兴能分享我们的工作和已实现Magento优化方式、和测试的结果。

当软件有了广泛的特点、功能和灵活性的表现,在性能方面肯定需要优化,Magento也没有例外。下面是一些性能优化的方法,在Magento的最新版本出现几个。

  • Top menu join queries rewritten, top menu block is cached now on per store view level for every active category
  • Added catalog indexes for layered navigation and search
  • Added dynamic merge and whitespace remove during JavaScript load
  • Footer block is cached
  • Implemented <remove name=”"> directive in layout xml to avoid instantiating of unwanted block objects, skipped left/right column blocks generation for pages with 1-column template</remove>
  • Most of sales order attributes became static and were moved to one raw table
  • Quote, quote address and quote items entities are stored separately
  • Greatly improved popular tags block generation time
  • Quote optimization for using in top links block and in the sidebar
  • Implemented caching API for using in Mage_Core_Model_Abstract descendant models
  • Removed unnecessary queries from catalog pages and homepage (e.g. reduced total number of database queries from 700 to 60 for homepage, and from 500 to 100 on product listing page on a database of 1000 products and 300 categories).

From our performance and load tests we have found that the latest Magento release outperforms version 0.8.17240 by almost double. Below we show a graph of one of the load tests we ran using Apache Benchmark (ab) comparing the two Magento versions. We experienced similar results throughout our tests and comparisons of the two versions.

image

DYI (Do it Yourself) Performance Enhancements

While we continue to improve Magento’s core performance, there are additional improvements that Magento users can implement to yield performance gains in a single-server environment:

  • Install a PHP opcode cache such as APC or XCache. These can deliver significant improvements to PHP’s responsiveness by caching PHP code in an intermediate bytecode format, which saves the interpreter from recompiling the PHP code for each and every request.
  • Make sure your Apache configuration has KeepAlives enabled. KeepAlives are a trick where multiple HTTP requests can be funneled through a single TCP connection. Since the setup of each TCP connection incurs additional time, this can significantly reduce the time it takes to download all the files (HTML, JavaScript, images) for a website.
  • Use a memory-based filesystem for Magento’s var directory. Magento makes extensive use of file-based storage for caching and session storage. The slowest component in a server is the hard drive, so if you use a memory-based filesystem such as tmpfs, you can save all those extra disk IO cycles by storing these temporary files in memory instead of storing them on your slow hard drive.
  • Modify the configuration for your MySQL server to take better advantage of your server’s RAM. Most Linux distributions provide a conservative MySQL package out of the box to ensure it will run on a wide array of hardware configurations. If you have ample RAM (eg, 1gb or more), then you may want to try tweaking the configuration. An example my.cnf is below, though you will want to consult the MySQL documentation for a complete list of configuration directives and recommended settings.

Example my.cnf:

image

Time to Cluster?

As any successful online retailer knows, a growing business means growing pains. If your store is a huge success, then you’ll undoubtedly require more horsepower to keep your customers happy. This means leaving the world of single-server websites and moving to a clustered environment with two or more servers.

There are varying ways to accomplish this, but a typical first step is to add more web servers and place them all behind a load balancer, which will distribute the load fairly among all web servers. This method is popular because (a) web servers are cheaper than database servers; and (b) there’s really no limit to the amount of web servers you can add.

Note: One current limitation in Magento is that there is no official method to propagate catalog images to each web node. If you’re not comfortable setting up some sort of facility to do this, then you may want to hire a professional or try a different method of scaling.

A second method involves a performance tactic called “database replication.” When using replication, you will have two or more database servers in your cluster. One will be the “master” and the rest will be called “slaves.” The master is the only database server that accepts any sort of write-based queries. These write queries are then replicated by each of the slaves in real-time (or very close to it). The advantage of this setup is that Magento can issue read queries to any of the slave servers, saving all the write queries for the master database. A database is traditionally a difficult component to scale horizontally, so replication is a happy compromise.

The initial setup and configuration for MySQL replication is out of the scope of this document, but we can refer you to the experts. Here is a tutorial that explains all the details.

Once you have MySQL replication functioning, configuring Magento to use multiple database servers is a relatively simple task. The only file you will have to edit is app/etc/local.xml. An example is shown below. As you can see, there are two database connections configured, one called default_setup and one called default_read. The default_setup connection will be used for all write-based queries, and the default_read connection will be used for all read-based queries.

Example app/etc/local.xml:

image

This article has only covered a few of the well-known tactics for improving site performance. However, every website’s scenario is slightly different, so it’s often worth hiring a professional to appraise the needs of your site and provide you with possible upgrade options. But if you’re comfortable with Linux and confident when working with configuration files, try out a few of our suggestions above. You may be pleasantly surprised.