Chủ Nhật, 19 tháng 9, 2010

How To Set Up A Load-Balanced MySQL Cluster

This tutorial shows how to configure a MySQL 5 cluster with three nodes: two storage nodes and one management node. This cluster is load-balanced by a high-availability load balancer that in fact has two nodes that use the Ultra Monkey package which provides heartbeat (for checking if the other node is still alive) and ldirectord (to split up the requests to the nodes of the MySQL cluster).

In this document I use Debian Sarge for all nodes. Therefore the setup might differ a bit for other distributions. The MySQL version I use in this setup is 5.0.19. If you do not want to use MySQL 5, you can use MySQL 4.1 as well, although I haven't tested it.

This howto is meant as a practical guide; it does not cover the theoretical backgrounds. They are treated in a lot of other documents in the web.

This document comes without warranty of any kind! I want to say that this is not the only way of setting up such a system. There are many ways of achieving this goal but this is the way I take. I do not issue any guarantee that this will work for you!

1 My Servers

I use the following Debian servers that are all in the same network (192.168.0.x in this example):

* sql1.example.com: 192.168.0.101 MySQL cluster node 1
* sql2.example.com: 192.168.0.102 MySQL cluster node 2
* loadb1.example.com: 192.168.0.103 Load Balancer 1 / MySQL cluster management server
* loadb2.example.com: 192.168.0.104 Load Balancer 2

In addition to that we need a virtual IP address : 192.168.0.105. It will be assigned to the MySQL cluster by the load balancer so that applications have a single IP address to access the cluster.

Although we want to have two MySQL cluster nodes in our MySQL cluster, we still need a third node, the MySQL cluster management server, for mainly one reason: if one of the two MySQL cluster nodes fails, and the management server is not running, then the data on the two cluster nodes will become inconsistent ("split brain"). We also need it for configuring the MySQL cluster.
So normally we would need five machines for our setup:

2 MySQL cluster nodes + 1 cluster management server + 2 Load Balancers = 5

As the MySQL cluster management server does not use many resources, and the system would just sit there doing nothing, we can put our first load balancer on the same machine, which saves us one machine, so we end up with four machines.

2 Set Up The MySQL Cluster Management Server

First we have to download MySQL 5.0.19 (the max version!) and install the cluster management server (ndb_mgmd) and the cluster management client (ndb_mgm - it can be used to monitor what's going on in the cluster). The following steps are carried out on loadb1.example.com (192.168.0.103):

loadb1.example.com:

mkdir /usr/src/mysql-mgm
cd /usr/src/mysql-mgm
wget http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-max-5.0.19-linux-i686-\
glibc23.tar.gz/from/http://www.mirrorservice.org/sites/ftp.mysql.com/
tar xvfz mysql-max-5.0.19-linux-i686-glibc23.tar.gz
cd mysql-max-5.0.19-linux-i686-glibc23
mv bin/ndb_mgm /usr/bin
mv bin/ndb_mgmd /usr/bin
chmod 755 /usr/bin/ndb_mg*
cd /usr/src
rm -rf /usr/src/mysql-mgm

Next, we must create the cluster configuration file, /var/lib/mysql-cluster/config.ini:

loadb1.example.com:

mkdir /var/lib/mysql-cluster
cd /var/lib/mysql-cluster
vi config.ini

[NDBD DEFAULT]
NoOfReplicas=2

[MYSQLD DEFAULT]

[NDB_MGMD DEFAULT]

[TCP DEFAULT]

# Section for the cluster management node
[NDB_MGMD]
# IP address of the management node (this system)
HostName=192.168.0.103

# Section for the storage nodes
[NDBD]
# IP address of the first storage node
HostName=192.168.0.101
DataDir= /var/lib/mysql-cluster

[NDBD]
# IP address of the second storage node
HostName=192.168.0.102
DataDir=/var/lib/mysql-cluster

# one [MYSQLD] per storage node
[MYSQLD]
[MYSQLD]

Please replace the IP addresses in the file appropriately.

Then we start the cluster management server:

loadb1.example.com:

ndb_mgmd -f /var/lib/mysql-cluster/config.ini

It makes sense to automatically start the management server at system boot time, so we create a very simple init script and the appropriate startup links:

loadb1.example.com:

echo 'ndb_mgmd -f /var/lib/mysql-cluster/config.ini' > /etc/init.d/ndb_mgmd
chmod 755 /etc/init.d/ndb_mgmd
update-rc.d ndb_mgmd defaults
3 Set Up The MySQL Cluster Nodes (Storage Nodes)

Now we install mysql-max-5.0.19 on both sql1.example.com and sql2.example.com:

sql1.example.com / sql2.example.com:
groupadd mysql
useradd -g mysql mysql
cd /usr/local/
wget http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-max-5.0.19-linux-i686-\
glibc23.tar.gz/from/http://www.mirrorservice.org/sites/ftp.mysql.com/
tar xvfz mysql-max-5.0.19-linux-i686-glibc23.tar.gz
ln -s mysql-max-5.0.19-linux-i686-glibc23 mysql
cd mysql
scripts/mysql_install_db --user=mysql
chown -R root:mysql .
chown -R mysql data
cp support-files/mysql.server /etc/init.d/
chmod 755 /etc/init.d/mysql.server
update-rc.d mysql.server defaults
cd /usr/local/mysql/bin
mv * /usr/bin
cd ../
rm -fr /usr/local/mysql/bin
ln -s /usr/bin /usr/local/mysql/bin

Then we create the MySQL configuration file /etc/my.cnf on both nodes:

sql1.example.com / sql2.example.com:

vi /etc/my.cnf

[mysqld]
ndbcluster
# IP address of the cluster management node
ndb-connectstring=192.168.0.103

[mysql_cluster]
# IP address of the cluster management node
ndb-connectstring=192.168.0.103

Make sure you fill in the correct IP address of the MySQL cluster management server.

Next we create the data directories and start the MySQL server on both cluster nodes:

sql1.example.com / sql2.example.com:

mkdir /var/lib/mysql-cluster
cd /var/lib/mysql-cluster
ndbd --initial
/etc/init.d/mysql.server start

(Please note: we have to run ndbd --initial only when the start MySQL for the first time, and if /var/lib/mysql-cluster/config.ini on loadb1.example.com changes.)

Now is a good time to set a password for the MySQL root user:

sql1.example.com / sql2.example.com:

mysqladmin -u root password yourrootsqlpassword

We want to start the cluster nodes at boot time, so we create an ndbd init script and the appropriate system startup links:

sql1.example.com / sql2.example.com:

echo 'ndbd' > /etc/init.d/ndbd
chmod 755 /etc/init.d/ndbd
update-rc.d ndbd defaults
How To Set Up A Load-Balanced MySQL Cluster - Page 3
Submitted by falko (Contact Author) (Forums) on Mon, 2006-03-27 11:09. ::
4 Test The MySQL Cluster

Our MySQL cluster configuration is already finished, now it's time to test it. On the cluster management server (loadb1.example.com), run the cluster management client ndb_mgm to check if the cluster nodes are connected:

loadb1.example.com:

ndb_mgm

You should see this:

-- NDB Cluster -- Management Client --
ndb_mgm>

Now type show; at the command prompt:
show;

The output should be like this:

ndb_mgm> show;
Connected to Management Server at: localhost:1186
Cluster Configuration
---------------------
[ndbd(NDB)] 2 node(s)
id=2 @192.168.0.101 (Version: 5.0.19, Nodegroup: 0, Master)
id=3 @192.168.0.102 (Version: 5.0.19, Nodegroup: 0)

[ndb_mgmd(MGM)] 1 node(s)
id=1 @192.168.0.103 (Version: 5.0.19)

[mysqld(API)] 2 node(s)
id=4 @192.168.0.101 (Version: 5.0.19)
id=5 @192.168.0.102 (Version: 5.0.19)

ndb_mgm>

If you see that your nodes are connected, then everything's ok!

Type

quit;

to leave the ndb_mgm client console.

Now we create a test database with a test table and some data on sql1.example.com:

sql1.example.com:

mysql -u root -p
CREATE DATABASE mysqlclustertest;
USE mysqlclustertest;
CREATE TABLE testtable (i INT) ENGINE=NDBCLUSTER;
INSERT INTO testtable () VALUES (1);
SELECT * FROM testtable;
quit;

(Have a look at the CREATE statment: We must use ENGINE=NDBCLUSTER for all database tables that we want to get clustered! If you use another engine, then clustering will not work!)

The result of the SELECT statement should be:

mysql> SELECT * FROM testtable;
+------+
| i |
+------+
| 1 |
+------+
1 row in set (0.03 sec)

Now we create the same database on sql2.example.com (yes, we still have to create it, but afterwards testtable and its data should be replicated to sql2.example.com because testtable uses ENGINE=NDBCLUSTER):

sql2.example.com:

mysql -u root -p
CREATE DATABASE mysqlclustertest;
USE mysqlclustertest;
SELECT * FROM testtable;

The SELECT statement should deliver you the same result as before on sql1.example.com:

mysql> SELECT * FROM testtable;
+------+
| i |
+------+
| 1 |
+------+
1 row in set (0.04 sec)

So the data was replicated from sql1.example.com to sql2.example.com. Now we insert another row into testtable:

sql2.example.com:

INSERT INTO testtable () VALUES (2);
quit;

Now let's go back to sql1.example.com and check if we see the new row there:

sql1.example.com:

mysql -u root -p
USE mysqlclustertest;
SELECT * FROM testtable;
quit;

You should see something like this:

mysql> SELECT * FROM testtable;
+------+
| i |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.05 sec)

So both MySQL cluster nodes alwas have the same data!

Now let's see what happens if we stop node 1 (sql1.example.com): Run

sql1.example.com:

killall ndbd

and check with

ps aux | grep ndbd | grep -iv grep

that all ndbd processes have terminated. If you still see ndbd processes, run another

killall ndbd

until all ndbd processes are gone.

Now let's check the cluster status on our management server (loadb1.example.com):

loadb1.example.com:

ndb_mgm

On the ndb_mgm console, issue

show;

and you should see this:

ndb_mgm> show;
Connected to Management Server at: localhost:1186
Cluster Configuration
---------------------
[ndbd(NDB)] 2 node(s)
id=2 (not connected, accepting connect from 192.168.0.101)
id=3 @192.168.0.102 (Version: 5.0.19, Nodegroup: 0, Master)

[ndb_mgmd(MGM)] 1 node(s)
id=1 @192.168.0.103 (Version: 5.0.19)

[mysqld(API)] 2 node(s)
id=4 @192.168.0.101 (Version: 5.0.19)
id=5 @192.168.0.102 (Version: 5.0.19)

ndb_mgm>

You see, sql1.example.com is not connected anymore.

Type

quit;

to leave the ndb_mgm console.

Let's check sql2.example.com:

sql2.example.com:

mysql -u root -p
USE mysqlclustertest;
SELECT * FROM testtable;
quit;

The result of the SELECT query should still be

mysql> SELECT * FROM testtable;
+------+
| i |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.17 sec)

Ok, all tests went fine, so let's start our sql1.example.com node again:

sql1.example.com:

ndbd
5 How To Restart The Cluster

Now let's asume you want to restart the MySQL cluster, for example because you have changed /var/lib/mysql-cluster/config.ini on loadb1.example.com or for some other reason. To do this, you use the ndb_mgm cluster management client on loadb1.example.com:
loadb1.example.com:

ndb_mgm

On the ndb_mgm console, you type

shutdown;

You will then see something like this:

ndb_mgm> shutdown;
Node 3: Cluster shutdown initiated
Node 2: Node shutdown completed.
2 NDB Cluster node(s) have shutdown.
NDB Cluster management server shutdown.
ndb_mgm>

This means that the cluster nodes sql1.example.com and sql2.example.com and also the cluster management server have shut down.

Run

quit;

to leave the ndb_mgm console.

To start the cluster management server, do this on loadb1.example.com:

loadb1.example.com:

ndb_mgmd -f /var/lib/mysql-cluster/config.ini

and on sql1.example.com and sql2.example.com you run

sql1.example.com / sql2.example.com:

ndbd

or, if you have changed /var/lib/mysql-cluster/config.ini on loadb1.example.com:

ndbd --initial

Afterwards, you can check on loadb1.example.com if the cluster has restarted:

loadb1.example.com:

ndb_mgm

On the ndb_mgm console, type

show;

to see the current status of the cluster. It might take a few seconds after a restart until all nodes are reported as connected.

Type

quit;

to leave the ndb_mgm console.
6 Configure The Load Balancers

Our MySQL cluster is finished now, and you could start using it now. However, we don't have a single IP address that we can use to access the cluster, which means you must configure your applications in a way that a part of it uses the MySQL cluster node 1 (sql1.example.com), and the rest uses the other node (sql2.example.com). Of course, all your applications could just use one node, but what's the point then in having a cluster if you do not split up the load between the cluster nodes? Another problem is, what happens if one of the cluster nodes fails? Then the applications that use this cluster node cannot work anymore.

The solution is to have a load balancer in front of the MySQL cluster which (as its name suggests) balances the load between the MySQL cluster nodes. The load blanacer configures a virtual IP address that is shared between the cluster nodes, and all your applications use this virtual IP address to access the cluster. If one of the nodes fails, then your applications will still work, because the load balancer redirects the requests to the working node.

Now in this scenario the load balancer becomes the bottleneck. What happens if the load balancer fails? Therefore we will configure two load balancers (loadb1.example.com and loadb2.example.com) in an active/passive setup, which means we have one active load balancer, and the other one is a hot-standby and becomes active if the active one fails. Both load balancers use heartbeat to check if the other load balancer is still alive, and both load balancers also use ldirectord, the actual load balancer the splits up the load onto the cluster nodes. heartbeat and ldirectord are provided by the Ultra Monkey package that we will install.

It is important that loadb1.example.com and loadb2.example.com have support for IPVS (IP Virtual Server) in their kernels. IPVS implements transport-layer load balancing inside the Linux kernel.


6.1 Install Ultra Monkey

Ok, let's start: first we enable IPVS on loadb1.example.com and loadb2.example.com:

loadb1.example.com / loadb2.example.com:

modprobe ip_vs_dh
modprobe ip_vs_ftp
modprobe ip_vs
modprobe ip_vs_lblc
modprobe ip_vs_lblcr
modprobe ip_vs_lc
modprobe ip_vs_nq
modprobe ip_vs_rr
modprobe ip_vs_sed
modprobe ip_vs_sh
modprobe ip_vs_wlc
modprobe ip_vs_wrr

In order to load the IPVS kernel modules at boot time, we list the modules in /etc/modules:

loadb1.example.com / loadb2.example.com:

vi /etc/modules

ip_vs_dh
ip_vs_ftp
ip_vs
ip_vs_lblc
ip_vs_lblcr
ip_vs_lc
ip_vs_nq
ip_vs_rr
ip_vs_sed
ip_vs_sh
ip_vs_wlc
ip_vs_wrr

Now we edit /etc/apt/sources.list and add the Ultra Monkey repositories (don't remove the other repositories), and then we install Ultra Monkey:

loadb1.example.com / loadb2.example.com:

vi /etc/apt/sources.list

deb http://www.ultramonkey.org/download/3/ sarge main
deb-src http://www.ultramonkey.org/download/3 sarge main

apt-get update
apt-get install ultramonkey libdbi-perl libdbd-mysql-perl libmysqlclient14-dev

Now Ultra Monkey is being installed. If you see this warning:

¦ libsensors3 not functional ¦
¦ ¦
¦ It appears that your kernel is not compiled with sensors support. As a ¦
¦ result, libsensors3 will not be functional on your system. ¦
¦ ¦
¦ If you want to enable it, have a look at "I2C Hardware Sensors Chip ¦
¦ support" in your kernel configuration. ¦

you can ignore it.

Answer the following questions:

Do you want to automatically load IPVS rules on boot?
<-- No

Select a daemon method.
<-- none

The libdbd-mysql-perl package we've just installed does not work with MySQL 5 (we use MySQL 5 on our MySQL cluster...), so we install the newest DBD::mysql Perl package:

loadb1.example.com / loadb2.example.com:

cd /tmp
wget http://search.cpan.org/CPAN/authors/id/C/CA/CAPTTOFU/DBD-mysql-3.0002.tar.gz
tar xvfz DBD-mysql-3.0002.tar.gz
cd DBD-mysql-3.0002
perl Makefile.PL
make
make install

We must enable packet forwarding:

loadb1.example.com / loadb2.example.com:

vi /etc/sysctl.conf

# Enables packet forwarding
net.ipv4.ip_forward = 1

sysctl -p
6.2 Configure heartbeat

Next we configure heartbeat by creating three files (all three files must be identical on loadb1.example.com and loadb2.example.com):

loadb1.example.com / loadb2.example.com:

vi /etc/ha.d/ha.cf

logfacility local0
bcast eth0
mcast eth0 225.0.0.1 694 1 0
auto_failback off
node loadb1
node loadb2
respawn hacluster /usr/lib/heartbeat/ipfail
apiauth ipfail gid=haclient uid=hacluster
Please note: you must list the node names (in this case loadb1 and loadb2) as shown by
uname -n

Other than that, you don't have to change anything in the file.

vi /etc/ha.d/haresources

loadb1 \
ldirectord::ldirectord.cf \
LVSSyncDaemonSwap::master \
IPaddr2::192.168.0.105/24/eth0/192.168.0.255

You must list one of the load balancer node names (here: loadb1) and list the virtual IP address (192.168.0.105) together with the correct netmask (24) and broadcast address (192.168.0.255). If you are unsure about the correct settings, http://www.subnetmask.info/ might help you.

vi /etc/ha.d/authkeys

auth 3
3 md5 somerandomstring

somerandomstring is a password which the two heartbeat daemons on loadb1 and loadb2 use to authenticate against each other. Use your own string here. You have the choice between three authentication mechanisms. I use md5 as it is the most secure one.

/etc/ha.d/authkeys should be readable by root only, therefore we do this:

loadb1.example.com / loadb2.example.com:

chmod 600 /etc/ha.d/authkeys


6.3 Configure ldirectord

Now we create the configuration file for ldirectord, the load balancer:

loadb1.example.com / loadb2.example.com:

vi /etc/ha.d/ldirectord.cf

# Global Directives
checktimeout=10
checkinterval=2
autoreload=no
logfile="local0"
quiescent=yes

virtual = 192.168.0.105:3306
service = mysql
real = 192.168.0.101:3306 gate
real = 192.168.0.102:3306 gate
checktype = negotiate
login = "ldirector"
passwd = "ldirectorpassword"
database = "ldirectordb"
request = "SELECT * FROM connectioncheck"
scheduler = wrr

Please fill in the correct virtual IP address (192.168.0.105) and the correct IP addresses of your MySQL cluster nodes (192.168.0.101 and 192.168.0.102). 3306 is the port that MySQL runs on by default. We also specify a MySQL user (ldirector) and password (ldirectorpassword), a database (ldirectordb) and an SQL query. ldirectord uses this information to make test requests to the MySQL cluster nodes to check if they are still available. We are going to create the ldirector database with the ldirector user in the next step.

Now we create the necessary system startup links for heartbeat and remove those of ldirectord (bacause ldirectord will be started by heartbeat):

loadb1.example.com / loadb2.example.com:

update-rc.d -f heartbeat remove
update-rc.d heartbeat start 75 2 3 4 5 . stop 05 0 1 6 .
update-rc.d -f ldirectord remove
How To Set Up A Load-Balanced MySQL Cluster - Page 7
Submitted by falko (Contact Author) (Forums) on Mon, 2006-03-27 11:18. ::
6.4 Create A Database Called ldirector

Next we create the ldirector database on our MySQL cluster nodes sql1.example.com and sql2.example.com. This database will be used by our load balancers to check the availability of the MySQL cluster nodes.

sql1.example.com:
mysql -u root -p
GRANT ALL ON ldirectordb.* TO 'ldirector'@'%' IDENTIFIED BY 'ldirectorpassword';
FLUSH PRIVILEGES;
CREATE DATABASE ldirectordb;
USE ldirectordb;
CREATE TABLE connectioncheck (i INT) ENGINE=NDBCLUSTER;
INSERT INTO connectioncheck () VALUES (1);
quit;

sql2.example.com:

mysql -u root -p
GRANT ALL ON ldirectordb.* TO 'ldirector'@'%' IDENTIFIED BY 'ldirectorpassword';
FLUSH PRIVILEGES;
CREATE DATABASE ldirectordb;
quit;


6.5 Prepare The MySQL Cluster Nodes For Load Balancing

Finally we must configure our MySQL cluster nodes sql1.example.com and sql2.example.com to accept requests on the virtual IP address 192.168.0.105.

sql1.example.com / sql2.example.com:

apt-get install iproute

Add the following to /etc/sysctl.conf:

sql1.example.com / sql2.example.com:

vi /etc/sysctl.conf

# Enable configuration of arp_ignore option
net.ipv4.conf.all.arp_ignore = 1

# When an arp request is received on eth0, only respond if that address is
# configured on eth0. In particular, do not respond if the address is
# configured on lo
net.ipv4.conf.eth0.arp_ignore = 1

# Ditto for eth1, add for all ARPing interfaces
#net.ipv4.conf.eth1.arp_ignore = 1


# Enable configuration of arp_announce option
net.ipv4.conf.all.arp_announce = 2

# When making an ARP request sent through eth0 Always use an address that
# is configured on eth0 as the source address of the ARP request. If this
# is not set, and packets are being sent out eth0 for an address that is on
# lo, and an arp request is required, then the address on lo will be used.
# As the source IP address of arp requests is entered into the ARP cache on
# the destination, it has the effect of announcing this address. This is
# not desirable in this case as adresses on lo on the real-servers should
# be announced only by the linux-director.
net.ipv4.conf.eth0.arp_announce = 2

# Ditto for eth1, add for all ARPing interfaces
#net.ipv4.conf.eth1.arp_announce = 2

sysctl -p

Add this section for the virtual IP address to /etc/network/interfaces:

sql1.example.com / sql2.example.com:

vi /etc/network/interfaces

auto lo:0
iface lo:0 inet static
address 192.168.0.105
netmask 255.255.255.255
pre-up sysctl -p > /dev/null

ifup lo:0
7 Start The Load Balancer And Do Some Testing

Now we can start our two load balancers for the first time:

loadb1.example.com / loadb2.example.com:

/etc/init.d/ldirectord stop
/etc/init.d/heartbeat start

If you don't see errors, you should now reboot both load balancers:

loadb1.example.com / loadb2.example.com:

shutdown -r now

After the reboot we can check if both load balancers work as expected :

loadb1.example.com / loadb2.example.com:

ip addr sh eth0

The active load balancer should list the virtual IP address (192.168.0.105):

2: eth0: mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:16:3e:45:fc:f8 brd ff:ff:ff:ff:ff:ff
inet 192.168.0.103/24 brd 192.168.0.255 scope global eth0
inet 192.168.0.105/24 brd 192.168.0.255 scope global secondary eth0

The hot-standby should show this:

2: eth0: mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:16:3e:16:c1:4e brd ff:ff:ff:ff:ff:ff
inet 192.168.0.104/24 brd 192.168.0.255 scope global eth0

loadb1.example.com / loadb2.example.com:

ldirectord ldirectord.cf status

Output on the active load balancer:

ldirectord for /etc/ha.d/ldirectord.cf is running with pid: 1603

Output on the hot-standby:

ldirectord is stopped for /etc/ha.d/ldirectord.cf

loadb1.example.com / loadb2.example.com:

ipvsadm -L -n

Output on the active load balancer:

IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 192.168.0.105:3306 wrr
-> 192.168.0.101:3306 Route 1 0 0
-> 192.168.0.102:3306 Route 1 0 0

Output on the hot-standby:

IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn

loadb1.example.com / loadb2.example.com:

/etc/ha.d/resource.d/LVSSyncDaemonSwap master status

Output on the active load balancer:

master running
(ipvs_syncmaster pid: 1766)

Output on the hot-standby:

master stopped
(ipvs_syncbackup pid: 1440)

If your tests went fine, you can now try to access the MySQL database from a totally different server in the same network (192.168.0.x) using the virtual IP address 192.168.0.105:

mysql -h 192.168.0.105 -u ldirector -p

(Please note: your MySQL client must at least be of version 4.1; older versions do not work with MySQL 5.)

You can now switch off one of the MySQL cluster nodes for test purposes; you should then still be able to connect to the MySQL database.


8 Annotations

There are some important things to keep in mind when running a MySQL cluster:

- All data is stored in RAM! Therefore you need lots of RAM on your cluster nodes. The formula how much RAM you need on ech node goes like this:

(SizeofDatabase × NumberOfReplicas × 1.1 ) / NumberOfDataNodes

So if you have a database that is 1 GB of size, you would need 1.1 GB RAM on each node!

- The cluster management node listens on port 1186, and anyone can connect. So that's definitely not secure, and therefore you should run your cluster in an isolated private network!

It's a good idea to have a look at the MySQL Cluster FAQ: http://dev.mysql.com/doc/refman/5.0/en/mysql-cluster-faq.html and also at the MySQL Cluster documentation: http://dev.mysql.com/doc/refman/5.0/en/ndbcluster.html


Links

MySQL: http://www.mysql.com/

MySQL Cluster documentation: http://dev.mysql.com/doc/refman/5.0/en/ndbcluster.html

MySQL Cluster FAQ: http://dev.mysql.com/doc/refman/5.0/en/mysql-cluster-faq.html

Ultra Monkey: http://www.ultramonkey.org/

The High-Availability Linux Project: http://www.linux-ha.org/

Sử dụng Fdisk trong Linux

# fdisk -l

Disk /dev/hda: 80.0 GB, 80060424192 bytes
255 heads, 63 sectors/track, 9733 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda1 1 262 2104483+ 82 Linux swap / Solaris
/dev/hda2 * 263 2873 20972857+ 83 Linux
/dev/hda3 2874 9733 55102950 83 Linux

Disk /dev/sda: 40.0 GB, 40007761920 bytes
64 heads, 32 sectors/track, 38154 cylinders
Units = cylinders of 2048 * 512 = 1048576 bytes

Lấy ví dụ trên máy đang có một harddisk 80GB được gán vào /dev/hda và chia thành 3 partition hda1, hda2, hda3. Harddisk thứ 2 40GB được gán vào /dev/sda, và harddisk này chưa được định dạng.

Cần chú ý rằng với một số Hệ điều hành Linux, sẽ quy định khe IDE0 tương ứng với /dev/hda, khe IDE1 tương ứng với /dev/hdb,... Các ổ cứng SCSI, hay USB sẽ được gán vào /dev/sda, /dev/sdb,...
Với /dev/sda mới chưa được định dạng nói trên, trước hết ta dùng lệnh fdisk như sau:

# fdisk /dev/sda

The number of cylinders for this disk is set to 38154.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): m
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
l list known partition types
m print this menu
n add a new partition
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition's system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)

Command (m for help):

Khi dùng lệnh fdisk /dev/sda, sẽ xuất hiện chế độ gõ lệnh của fdisk, ấn 'm' để đưa ra các hướng dẫn về lệnh của fdisk. Trong ví dụ này, chọn 'n' để thêm một partition mới.

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-38154, default 1): 1
Last cylinder or +size or +sizeM or +sizeK (1-38154, default 38154): 20480

Command (m for help):

Sau khi chọn 'n', xuất hiện các lựa chọn: lựa chọn 'p' để tạo primary partition – phân vùng có thể boot được, lựa chọn 'e' để tạo một phân vùng extended. Bước này chọn 'p'. Sau khi chọn 'p', chương trình sẽ hỏi Partition number (1-4), gõ số 1. Chương trình sẽ cho phép bạn thay đổi First cylinder và Last cylinder. Chọn First cylinder = 1 và Last cylinder =20480. Fdisk sẽ quay trở lại chế độ gõ lệnh chính của nó.
Tại chế đô gõ lệnh chính, dùng 'w' để ghi lại các thông tin nói trên.

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

Sau khi chọn 'w', các thông tin sẽ được fdisk ghi lại trên harddisk và fdisk tự động thoát, quay trở lại chế độ gõ lệnh của Linux. Tại đây, gõ lệnh fdisk -l để kiểm tra các thay đổi.

# fdisk -l

Disk /dev/hda: 80.0 GB, 80060424192 bytes
255 heads, 63 sectors/track, 9733 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda1 1 262 2104483+ 82 Linux swap / Solaris
/dev/hda2 * 263 2873 20972857+ 83 Linux
/dev/hda3 2874 9733 55102950 83 Linux

Disk /dev/sda: 40.0 GB, 40007761920 bytes
64 heads, 32 sectors/track, 38154 cylinders
Units = cylinders of 2048 * 512 = 1048576 bytes

Device Boot Start End Blocks Id System
/dev/sda1 1 20480 20971504 83 Linux

Sau khi gõ lệnh fdisk -l, có thể nhận thấy một partition /dev/sda1 mới được tạo.

Để format partition này, sử dụng lệnh mkfs

# mkfs.ext3 /dev/sda1
mke2fs 1.38 (30-Jun-2005)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
2621440 inodes, 5242876 blocks
262143 blocks (5.00%) reserved for the super user
First data block=0
160 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 25 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
#

Tuỳ vào dự định của bạn tạo dạng hệ thống file cho /dev/sda1 là ext2, ext3 hay một định dạng khác mà tao sẽ dùng tham số thích hợp. Trong ví dụ trên, ta format /dev/sda1 với ext3.

Sau khi format, để sử dụng được /dev/sda1, cần phải mount nó vào một mount point, giả sử mount vào mount point /media/data

# mount /dev/sda1 /media/data

Để Linux tự động mount /dev/sda1 vào mount point nói trên, cần phải thêm vào file /etc/fstab dòng sau: /dev/sda1 /media/data ext3 defaults 0 0.

# vi /etc/fstab
/dev/hda2 / reiserfs acl,golden 1 1
/dev/hda3 /home reiserfs acl,golden 1 2
/dev/hda1 swap swap defaults 0 0
proc /proc proc defaults 0 0
sysfs /sys sysfs noauto 0 0
debugfs /sys/kernel/debug debugfs noauto 0 0
usbfs /proc/bus/usb usbfs noauto 0 0
devpts /dev/pts devpts mode=0620,gid=5 0 0
192.168.1.100:/home/goldenbook /home/goldenbook nfs defaults 0 0
/dev/sda1 /media/data ext3 defaults 0 0

Để kiểm tra partition nào được mount vào mount point nào dùng lênh df.

# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/hda2 20972152 8155616 12816536 39% /
udev 517332 164 517168 1% /dev
/dev/hda3 55101224 33054028 22047196 60% /home
/dev/sda1 20642412 131232 19462608 1% /media/data

Quota trong Redhat

Bước1: Chỉnh sửa tập tin /etc/fstab
Tập tin /etc/fstab là nơi chứa phân vùng mount khi unix khơi động.
Ví dụ tập tin /etc/fstab:
/dev/VolGroup00/LogVol00 / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
devpts /dev/pts devpts gid=5,mode=620 0 0
/dev/hda5 /home ext3 defaults 1 2
tmpfs /dev/shm tmpfs defaults 0 0
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
/dev/VolGroup00/LogVol01 swap swap defaults 0 0
Vào tập tin này ta chỉ định phận vùng mà ta muốn thực hiện quota. Ta có thể chỉ định quota cho user hay group.
Trong ví dụ trên ta thấy dòng:
dev/hda5 /home ext3 defaults 1 2
Bây giờ ta sẽ chỉ định phân vùng này thực hiện quota cho user, bằng cách thêm tham số usrquota vào :
/dev/hda5 /home ext3 defaults,usrquota 1 2
Nếu muốn thực hiện quota cho group thì thêm tham số grpquota vào:
/dev/hda5 /home ext3 defaults,grpquota 1 2
Ta cũng có thể thực hiện quota cho cả user và group trên phân vùng ta muốn chỉ định:
/dev/hda5 /home ext3 defaults usrquota,grpquota 1 2
Bước 2: Tạo tập tin lưu cấu hình
Sau khi ta thực hiện việc chỉnh sữa tập tin /etc/fdtab để chỉ định phân vùng thực hiện quota cho user và group, thì ta phải tạo ra tập tin để lưu trữ thông tin cấu hình cho user, group trong thư mục home. Tập tin cho user có tên là aquota.user còn group thì aquota.gruop, cách tạo tập tin:
#touch aquota.user
#touch aquota.group
Bước 3: Kích hoạt chức năng Quota
Sau khi tạo tập tin lưu thông tin thì ta phải reboot lại máy. Sau khi reboot để chức năng quota được gắn kết với hệ thống tập tin, thì hệ thống bây có khả năng làm việc. Tuy nhiên, hệ thống tập tin này chưa thật sự sẵn sàng, nên ta phải thực hiện quotacheck.
Lệnh quotacheck là nhằm để kiểm tra hệ thống tập tin được cấu hình quota và xây dựng lại bảng sử dụng đĩa hiện hành. Với câu lệnh như sau:
#quotacheck
Option: –avug
( #quotacheck –avug )
-a: kiểm tra tất cả những hệ thống tập tin cấu hình quota
-v: hiển thị thông tin trạng thái khi kiểm tra
-u: kiểm tra quota cho từng user
-g: kiểm tra quota cho nhóm
Bước 4: Giới hạn không gian đĩa cho user, group
Người quản trị hệ thống sẽ thiết lập quota cho user hay group trong tập tin có tên aquota.user hay aquota.group, bằng cách lệnh sau:
#edquota
Option:
-g: chỉnh sửa cho group
-u: chỉnh sửa cho user ( là option mặc định )
-t: chỉnh sửa thời gian của giới hạn mềm
Ví dụ:
#edquota –u User_Quota
Thì mặc định màn hình sẽ hiện ra trong trình soạn thảo vi :
Disk quotas for user User_Quota (uid 506):
Filesystem blocks soft hard inodes soft hard
/dev/hda5 796 0 0 71 0 0
Ta thấy có:
Blocks: dung lượng tính theo block user đang sử dụng
Inodes: số file user đang sử dụng
Soft: dung lượng giới hạn mềm theo (blocks/inodes). Chú ý nếu soft bằng 0 có nghĩa là giới hạn này không sử dụng.
Hard: dung lượng giới hạn cứng (blocks/inodes)
Ví dụ ta chỉ lại dung lượn giới hạn như sau:
Disk quotas for user User_Quota (uid 506):
Filesystem blocks soft hard inodes soft hard
/dev/hda5 796 1500 2000 71 0 0
Sau khi thiết lập quota, ta nên khởi động quota lên bằng lệnh
#quotaon /dev/hda5
Sau các bước trên ta đã hoàn tất được giới hạn dung lượng đĩa bằng tiện ích quota. Ta có thể xem lại user hay group mà ta cấu hình bằng lệnh:
#quota
Option:
- g: group
- u: user
- q: chỉ hiển thị những hệ thống tâp tin có thiết lập quota/
Ví dú:
#quota User_Quota
Disk quotas for user User_Quota (uid 506):
Filesystem blocks quota limit grace files quota limit grace
/dev/hda5 884 1500 2000 76 0 0
Trong câu lệnh edquota có tham số -t như đã nói như trên, là thời gian giới hạn mềm hay còn gọi là hạn nghạch (grace periods). Mặc định là 7 ngày, ta có thể chỉnh lại bằng lệnh :
#edquota –t
Grace period before enforcing soft limits for users:
Time units may be: days, hours, minutes, or seconds
Filesystem Block grace period Inode grace period
dev/hda5 7days 7days
Ta chỉnh lại hạn nghạch bằng cách sửa số 7 bằng con số thích hợp.

Install bộ gõ tiếng việt

#yum install gcc gucharmap-devel
#wget http://xvnkb.sourceforge.net/xvnkb-0.2.9a.tar.gz
#cd xvnkb-2.0.9
#./configure
#make && make install

tạo session load module xvnkb sau mỗi lần restart: ( X-window )
System > Preferences > More preferences > Session
tab Startup program: + Add
thêm vào dòng:
xvnkb --method=vni --charset=utf8
Nếu bạn nào thích chọn icon trên mành hình thì chọn, khởi dộng không phải dùng lệnh

Thứ Ba, 17 tháng 8, 2010

Hướng dẫn chạy OpenVZ

Một trong nhiều công cụ ảo hoá dành cho Linux để bạn lựa chọn là OpenVZ, phần mềm miễn phí thuộc Virtuozzo do SWsoft cung cấp. OpenVZ và Virtuozzo là các giải pháp ảo hoá mức hệ điều hành, cho phép phân vùng server thành các máy chủ riêng ảo (VPS). Dạo qua một vòng tài liệu hướng dẫn trên chính OpenVZ, bạn sẽ thấy để hiểu được đầy đủ sâu sắc về công cụ này thông qua các tài liệu của nhà sản xuất không hề “dễ xơi”, thậm chí còn “đáng sợ”. Chúng ta thử tìm cách thức dễ dàng hơn để khởi đầu với OpenVZ: trên hệ thống Debian Etch.

Một năm trước đây, người dùng thường sử dụng Virtuozzo 3.0 cho Linux. Nhưng không phải túi người nào cũng rủng rỉnh để “tậu” được bản quyền Virtuozzo. OpenVZ mở ra giải pháp khác.

Khi nào nên sử dụng OpenVZ thay vì VMware Server hay Xen? Điều đó tuỳ thuộc vào từng trường hợp cụ thể. Với các hoạt động không cần chạy đa hệ điều này nhưng có nhiều khách, tạo hầu hết phần cứng hoặc cung cấp sự phân tách giữa các dịch vụ (như phân tách Web server giữa file server và print server chẳng hạn) với khả năng tràn tối thiểu, OpenVZ là lựa chọn tốt. Nhưng khi muốn chạy hệ điều hành non-Linux (như FreeBSD hay Windows Server) trên máy trạm Linux, nên sử dụng VMware hơn là OpenVZ (hoặc nếu mang tính thương mại và bản quyền nhiều hơn, nên dùng Virtuozzo), vì OpenVZ không cung cấp khả năng chạy đa hệ điều hành.

OpenVZ hỗ trợ nhiều nền tảng vi xử lý hơn là các bản luân phiên. VMware Server và Xen có thể dùng được cho dòng x86, AMD 64; còn OpenVZ được chấp nhận ở dòng x86, AMD64, Itanium (IA64), PowerPC, và UltraSPARC. Chú ý là hiện nay chưa có các kernel (nhân hệ điều hành) PowerPC xây dựng trước cho Debian, nhưng OpenVZ được hỗ trợ trên PowerPC.

Cài đặt OpenVZ

Có thể chạy OpenVZ trên bất kỳ hệ thống host nào, ví dụ ở đây là Debian. Bạn hoàn toàn có thể dùng Ubuntu, Fedora Core, Gentoo hoặc bất kỳ phân phối nào khác với một mẫu hệ điều hành (OS template). Mẫu hệ điều hành là tập hợp các gói dùng để tạo VPS, môi trường ảo AKA trong ngôn ngữ nước ngoài của OpenVZ.

Các nhân Debian cho khách OpenVZ được lấy từ vùng lưu trữ OpenVZ, nhưng chỉ cho Etch. Sử dụng kernel gần đây nhất cùng các gói “linux-header” lấy từ kho lưu trữ OpenVZ, cài đặt chúng bằng lệnh -i linux-image-2.6.18-openvz-686_02_i386.deb và dpkg -i linux-headers-2.6.18-openvz-686_02_i386.deb. Nhớ thay tên gói trong ví dụ bằng tên file bạn download về. Khi cài đặt các gói, dpkg đưa ra hai liên kết biểu tượng trỏ tới thư mục thiếu. Nhưng, cho đến nay chưa có vấn đề xuất hiện khi dùng OpenVZ. Vì vậy, các bạn không cần phải lo lắng.

Sau khi cài kernel và các header, bạn cần thêm một vài tham số (tìm trên OpenVZ wiki) vào thư mục /etc/sysctl.conf để chuẩn bị cho hệ thống chạy OpenVZ. Ví dụ, bạn cần nói với hệ thống cho phép gửi địa chỉ IP để các VPS (máy chủ riêng ảo) cũng sử dụng được mạng chia sẻ. Chỉ cần thêm các dòng này vào sysct.conf nếu chưa có, hoặc kiểm tra để chắc chắn xem chúng đã khớp nhau chưa:

net.ipv4.ip_forward = 1
net.ipv4.conf.default.proxy_arp = 0
net.ipv4.conf.all.rp_filter = 1
kernel.sysrq = 1
net.ipv4.conf.default.send_redirects = 1
net.ipv4.conf.all.send_redirects = 0

Sau khi cài đặt kernel và thực hiện các thay đổi này, bạn cần khởi động lại máy. Nhân kernel OpenVZ sẽ được thiết lập làm kernel mặc định trong menu GRUB đã sẵn sàng.

Tiếp theo, cần sử dụng các tiện ích OpenVZ, dùng lệnh sau apt-get install vzctl. Lệnh này sẽ cài đặt các gói vzctl và vzquota, gồm nhiều tiện ích (như vzctl) cần để quản lý OpenVZ.

OpenVZ sẽ được thiết lập khởi động trong quá trình boot sau khi cài đặt các tiện ích này. Nếu muốn sử dụng ngay bây giờ, bạn cần khởi động OpenVZ “thủ công” (hoặc khởi động lại). Khởi động OpenVZ bằng câu lệnh init script:

/etc/init.d/vz start

Thiết lập hệ thống khách

Bây giờ là thời gian thu thập một vài template và cài đặt hệ điều hành khách (Guest Operating System). Bạn có thể tìm thấy một số được tạo trước đó trên website download của OpenVZ, như các phiên bản của Fedora Core, Debian Sarge và Debian Etch, CentOS, Gentoo, Mandriva, và openSUSE. Chú ý là các khuôn mẫu này được dùng cho từng loại vi xử lý cụ thể. Vì thế hãy cẩn thận, đừng download nhầm phiên bản mẫu AMD64 hay UltraSPARC nếu bạn sẽ chạy nó trên hệ thống dòng x86.

Bạn cũng nên biết đến thư mục contrib chứa mẫu hệ điều hành do cộng đồng OpenVZ lập ra. Đây không phải là các mẫu “chính thức”, nhưng nếu muốn chạy Ubuntu, Slackware, AltLinux hay phân phối nào khác không thấy trong các mẫu OpenVZ, bạn nên xem trong thư mục này.

Nếu muốn chạy phân phối không có mẫu, có thể xem trong phần hướng dẫn OpenVZ wiki về các mẫu hệ điều hành. OpenVZ không phải là phần mềm cải tiến hơn VMware hay một số kỹ thuật ảo hoá khác. Cài đặt một phân phối Linux trên VMware Server hay VMware Workstation thường đơn giản như chạy qua thủ tục cài đặt của phân phối. Trong OpenVZ thì phức tạp hơn. Bạn cần phải tìm hiểu thêm nhiều về OpenVZ mới có thể chạy được hai thể hiện của khách.

Các mẫu OS download về cần lưu trữ trong thư mục /var/lib/vz/template/cache. Chúng được để ở dạng tarred và gzipped khi bạn download về. Nếu muốn giữ nguyên dạng, đừng giải nén chúng.

Để cài đặt hệ thống, sử dụng tiện ích vzctl. Có một tin xấu và một tin tốt ở đây. Tin xấu là tiện ích vzctl không dễ dùng như các công cụ đồ hoạ giao diện người dùng (GUI) trong Virtuozzo. Tin tốt là vzctl không quá khó sử dụng. Nó có thể đọc theo kịch bản (script) và không phân biệt chữ hoa chữ thường. Nếu bạn quản lý nhiều hệ thống OpenVZ, bạn cần viết cú pháp vào bất kỳ lúc nào. Nếu không tạo hay “dọn dẹp” các hệ thống khách OpenVZ, lượng thời gian tiêu tốn để vzctl quản lý trang và phác hoạ tuỳ chọn là rất lớn. Chúng ta hãy cùng xem một số lệnh phổ biến nhất.

Cú pháp tạo hệ thống khách là vzctl create vpsid --ostemplate ostemplatename. Trong đó vpsid là số gán cho hệ thống mới. OpenVZ đảo ngược các ID thấp dưới 100 để sử dụng nội bộ. Vì thế tôi thường gán ID từ 1001 trở lên. Trong trường hợp nếu bạn download mẫu hệ điều hành Debian Sarge cho dòng x86, chạy lệnh sau:

vzctl create 1001 --ostemplate debian-3.1-i386-minimal

Khi host khách được cài đặt, bạn có thể tìm thấy file hệ thống trong thư mục /var/lib/vz/root/vpsid và phạm vi riêng ở /var/lib/vz/private/vpsid (trừ khi thay đổi các thiết lập dùng --root mặc định hoặc tuỳ chọn --private). Thư mục riêng bao gồm các file riêng cho môi trường ảo (VE).

Nếu bạn tạo khách với mã số vz là 1001, file hệ thống gốc nằm ở /var/lib/vz/root/1001. File này sẽ trở nên hữu ích khi bạn muốn truy cập trực tiếp file (như khi admin thực hiện cấu hình ngăn khách khởi động theo cách thông thường chẳng hạn) hoặc trong các mục đích sao lưu.

Bây giờ chúng ta sẽ cài đặt mạng dù không mấy dễ dàng:

vzctl set --ipadd ipaddr --nameserver nameserverIP --hostname hostname --save

Tham số --ipadd gán cho địa chỉ IP giao diện venet đầu tiên trong hệ điều hành khách. Tham số --hostname gán tên host cho VPS (máy chủ riêng ảo), và tham số --nameserver cung cấp tên server. Giao diện venet không cung cấp cho các hệ thống khách OpenVZ mặc định địa chỉ vật lý MAC. Có nghĩa là, bạn không thể lấy địa chỉ giao diện qua DHCP.

Tuy nhiên, đến nay, một số cư dân cộng đồng OpenVZ đã bổ sung thêm kiểu giao diện mới gọi là veth, có thể cung cấp địa chỉ MAC. Thiết bị veth cũng cho phép người dùng cài đặt server DHCP bên trong hệ điều hành khách. Người dùng có thể cài đặt các thiết lập mạng riêng, nhưng không dùng được thiết bị venet. Nếu muốn cung cấp giao diện veth thay vì venet, bạn có thể xem thêm phần hướng dẫn trên OpenVZ wiki.

Quản lý OpenVZ

Khi VPS được cài đặt, khởi động hệ điều hành khách bằng cách chạy vzctl start vpsid, trong đó vpsid là ID bạn gán cho khách khi tạo ra nó.

Bạn nên xem một số thông báo về khởi động VPS, kết thúc với các từ "VPS start in progress..." (VPS đang trong quá trình khởi động). Khi đó, VPS đang chạy với lệnh vzlist. Sau khi chạy vzlist, bạn sẽ thấy như sau:

VPSID NPROC STATUS IP_ADDR HOSTNAME
1002 4 running 10.0.1.34 vroomfondle

Sử dụng tuỳ chọn -a để hiển thị tất cả server riêng ảo (VPS), cho dù chúng đang chạy hay không. Nếu muốn xem tài nguyên nào đang được khai thác, và xem dung lượng bộ nhớ đang được sử dụng là bao nhiêu, chạy lệnh vzcalc -v vpsid. Bạn sẽ thấy như sau:

Resource Current Promised Max
Low Mem 0.13 1.20 1.20
Total RAM 0.55 n/a n/a
Mem + Swap 0.36 1.83 n/a
Alloc. Mem 0.67 1.83 13.82
Num. Proc 0.06 n/a 0.40
--------------------------------------------
Memory 0.67 1.83 13.82

Thông số trên cho bạn biết dung lượng bộ nhớ đang được VPS dùng là bao nhiêu, bao nhiêu được cấp phát cho VPS và mức tăng lên có thể là bao nhiêu.

Các tham số VPS sử dụng tuỳ chọn -o. (Xem trên trang vzcalc man để biết thêm chi tiết).

Mặc định, các VPS không được khởi động cùng lúc với máy tính. Nhưng trong hầu hết mọi trường hợp, người ta thường muốn VPS được load sau khi hệ thống khởi động lại. Thay đổi thiết lập này, dùng vzctl như sau:

vzctl set vpsid --onboot yes --save

Tiện ích vzctl cũng được dùng để thiết lập tham số hệ thống, như tổng dung lượng, tài nguyên CPU, truy cập mô hình bảng IP (iptable), v.v…. Chúng ta cùng xem một ví dụ.

Một trong những điểm khó chịu trong OpenVZ là không dễ dàng chút nào khi nói “cung cấp cho RAM VPS 256MB”. Thay vào đó, bạn phải điều chỉnh cặp tham số và đọc qua một số tài liệu kỹ thuật thì mới tìm ra được cách xử lý OpenVZ với bộ nhớ.

Để đơn giản hơn một chút, tăng dung lượng RAM từ 256MB lên 1GB. Sau đó cách thiết lập các tham số vmguarpage (bộ nhớ cấp phát cho VPS) và privvmpage (dung lượng lớn bộ nhớ nhất được cấp phát) như sau:

vzctl set vpsid --vmguarpages 65536 --save
vzctl set vpsid --privvmpages 262144 --save

Một cách khác trực quan hơn là tính toán tổng dung lượng RAM bằng “các trang” trên diễn đàn SWsoft forum. Cần nhân thêm dung lượng RAM 256 bằng cách:

vzctl set vpsid --vmguarpages $((256 * 256)) --save
vzctl set vpsid --privvmpages $((256 * 1024)) --save

Đọc trang man và wiki OpenVZ, cùng một số tài liệu khác để biết thêm thông tin chi tiết.

Khi thiết lập tham số cho từng VPS, các thiết thiết lập cấu hình được lưu trữ ở: /etc/vz/conf/vpsid.conf. Nếu muốn thực hiện một thay đổi nào đó trên file, bạn có thể sử dụng tiện ích vzcfgvalidate để đảm bảo file cấu hình luôn được chính xác.

Thông thường, với các host, bạn cần sử dụng hệ thống admin đã thay đổi mật khẩu thư mục gốc. Với các hệ thống vật lý, bạn cần khởi động lại hệ thống và nhập mô hình người dùng đơn (single-user) để truy cập thư mục gốc cho các nhiệm vụ quản trị điều khiển. Với OpenVZ, tất cả điều bạn cần làm là vào một nút phần cứng và dùng vzctl để đăng nhập:

vzctl enter vpid

Câu lệnh này cho phép bạn đăng nhập vào VPS với vai trò root. Sau khi thực hiện xong hoạt động quản trị bạn cần, gõ lệnh exit để thoát. Nếu muốn thiết lập lại mật khẩu cho người dùng, sử dụng tuỳ chọn --userpasswd:

vzctl set vpsid --userpasswd user:passwd

Nếu người dùng (user) không tồn tại, nó sẽ được tạo.

Nếu muốn chạy lệnh trong VPS mà không cần đăng nhập VPS thực sự, sử dụng tham số exec cho vzctl để chạy lệnh ở thư mục gốc (root). Ví dụ, nếu muốn chạy lệnh nâng cấp nhanh trong Debian VPS:

vzctl exec vpsid apt-get upgrade

Lệnh này sẽ chạy apt-get upgrade trong bản thân VPS.

Để tắt VPS, chạy lệnh ngừng vzctl stop vpsid. Lệnh này sẽ thực thi tắt hoàn toàn bên trong VPS. Chạy vzctl restart vpsid để khởi động lại VPS. Các VPS có thể được tắt hoặc khởi động lại một cách bình thường bên trong VPS.

Đã đủ rồi, xin tạm biệt

Đến bây giờ, hệ thống khách đã chạy ổn định, và cũng nên đóng gói nó lại. Nếu muốn loại bỏ VPS, sử dụng lệnh destroy với vzctl:

vzctl destroy veid

Một điểm cần đặc biệt chú ý ở đây là: tiện ích vzctl không yêu cầu xác nhận lại trước khi phá huỷ VPS. Ngay sau khi ấn Enter, VPS sẽ bị loại bỏ, kể cả các thư mục dữ liệu riêng. Nếu không sao lưu, bạn sẽ gặp trở ngại khi muốn truy vấn dữ liệu.

Còn nhiều điều để nói, nhưng như thế cũng là đã đủ để bắt đầu với OpenVZ. Không phải mất quá nhiều thời gian tra tìm, đọc hiểu từ các wiki hay tài liệu của nhà sản xuất, nhưng sau khi chạy thành công VPS với những bước khởi đầu, bạn nên tham khảo thêm một số tài liệu khác để hiểu sâu hơn về OpenVZ.
(Theo QTM )

Hướng Dẫn Cài Đặt Firewall-Proxy

Chúng ta xây dựng mô hình Firewall kết hợp Proxy để quản lý mọi hành động trong hệ thống, tránh được những rủi ro không mong muốn.
Mô hình tham khảo như sau:



Để thực hiện, chúng ta cần cài đặt các chương trình sau:
• ShoreWall: làm firewall, quản lý traffic, chặn ứng dụng dựa vào port,…
• Squid: làm proxy, cache web, quản lý hành vi user,…
• Sarg: monitor proxy.

Do tài nguyên hạn hẹp, nên ta thực hiện nó trên cùng 1 máy, RAM chừng 2GB là được.
Bài viết này dùng Cent OS 5.4 (áp dụng luôn cho các distro của cent, như RedHat).
Các gói hỗ trợ cho cài đặt:
#yum install -y gcc gcc-c++ ;compiler

Cài đặt gói rpmforge-release từ http://dag.wieers.com/rpm/packages/rpmforge-release/
#wget http://dag.wieers.com/rpm/packages/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
#rpm –ivh /rpmforge-release-0.3.6-1.el5.rf.i386.rpm
Gói này để nó tự động đi tìm những thứ cần thiết cho ta khi cần.


I. ShoreWall:
1. Giới thiệu:
Shorewall là chương trình quản lý iptables, giúp ta điều khiển được hành vi traffic ở mức L3.
2. Cài đặt:
Download các gói cần thiết, ổn định tại thời điểm đó tại http://www.shorewall.net/pub/shorewall/
#mkdir /source
#cd source
#wget http://www.shorewall.net/pub/shorewall/4.2/shorewall-4.2.2/shorewall-shell-4.2.2.tar.bz2
#wget http://www.shorewall.net/pub/shorewall/4.2/shorewall-4.2.2/shorewall-perl-4.2.2.2.tar.bz2
#wget http://www.shorewall.net/pub/shorewall/4.2/shorewall-4.2.2/shorewall-common-4.2.2.1.tar.bz2
#tar -jxvf shorewall-shell-4.2.2.tar.bz2
#tar -jxvf shorewall-perl-4.2.2.2.tar.bz2
#tar -jxvf shorewall-common-4.2.2.1.tar.bz2

Vào các directory vừa giải nén, cài đặt:
#./install.sh
Vào nơi chứa các file cấu hình cho shorewall
#cd /etc/shorewall

Tạo các zones trong /etc/shorewall/zones
#ZONE TYPE OPTIONS IN OUT
# OPTIONS OPTIONS
fw firewall
loc ipv4
net ipv4
dmz ipv4

Khai báo các interfaces tương ứng với các zonez trong file /etc/shorewall/interfaces
#ZONE INTERFACE BROADCAST OPTIONS
net eth0
loc eth1
dmz eth2

Khai báo trong các policy trong /etc/shorewall/policy
#SOURCE DEST POLICY LOG LIMIT: CONNLIMIT:
# LEVEL BURST MASK
loc net REJECT info
loc dmz REJECT info
loc fw REJECT info
net all ACCEPT info
dmz all ACCEPT info
$FW all ACCEPT

Dùng SNAT để các máy trong LAN, DMZ đi internet bằng IP public, trong file /etc/shorewall/masq
#INTERFACE SOURCE ADDRESS PROTO PORT(S) IPSEC MARK
eth0 eth1
eth0 eth2

Dùng DNAT để các máy ngoài internet truy cập vào máy ta đã publish, trong file /etc/shorewall/rules
#ACTION SOURCE DEST PROTO DEST SOURCE ORIGINAL RATE USER/ MARK CONNLIMIT TIME

ACCEPT loc fw icmp echo-request
ACCEPT loc dmz icmp echo-request
ACCEPT loc net tcp 80,443
ACCEPT loc net udp 53
DNAT net dmz:172.27.1.104 tcp 80 - ; giả sử ta đang publish web server 172.27.1.104

REDIRECT loc 3128 tcp www - !172.27.1.105 ;172.27.1.105 là máy Proxy server, dòng này để user truy cập internet đều bị tự động đá qua cho proxy xử lý.


Chỉnh lại STARTUP_ENABLED=Yes trong file /etc/shorewall/shorewall.conf
# vi /etc/shorewall/shorewall.conf
STARTUP_ENABLED=Yes


Start dịch vụ shorewall:
#shorewall start
#shorewall restart
#shorewall clear //Xóa các rule trong cache

Vậy là xong phần shorewall.

II. Squid:
1. Giới thiệu:
Hiện có rất nhiều chương trình làm proxy, nhưng ta chọn squid bởi những tính năng ưu việt của nó (tính tới thời điểm hiện tại):
• Quản lý cache theo kiểu chia nhỏ, giúp truy cập nhanh hơn (trong khi ISA thì gom 1 cục, và 15GB thì die)
• Hỗ trợ ICP , tự động cập nhật thông tin của những URL đã có sẵn trong cache, đảm bảo nội dung mới liên tục ( một số chương trình proxy không hỗ trợ cái này phải set thời gian update, chứ không chỉ đọc được thông tin cũ).
• Khắc phục được tình trạng chỉ hỗ trợ HTTP, HTTPs, FTP như các proxy khác.
• ….
Có thể làm được mọi thứ theo ý mình trên squid.

2. Cài đặt:
#yum -y install squid
Cấu hình các thông số cơ bản:(ta chỉ cần thay đổi một số tùy chọn là squid có thể hoạt động được, mặc định squid cấm tất cả các browser truy cập)
Ta nên copy file squid.conf.default thành file squid.conf.
#cp /etc/squid/squid.conf.default /etc/squid.conf
#vi /etc/squid/squid.conf
#squid lang nghe cac proxy client tren port 3128, có thể đổi lại port tùy thích
#thong so transparent de no co the lam viec voi firewall redirect
http_port 3128 transparent //line 919

#port su dung ICP
icp_port 3130 //line 1449

#cahe_mem = RAM/3, o day la RAM he thong = 256
cache_mem 60 MB //line 1576
cache_swap_low 90 //line 1838
cache_swap_high 95

#cache_dir: cấu hình thư mục lưu dữ liệu được cache
#default: cache_dir ufs /var/spool/squid 100 16 256
#squid se luu cache tai /var/spool/squid voi kich thuoc cache=5000MB
#level-1 subdirectory =16 la so thu muc con tao trong squid
#level-2 subdirectory=256
cache_dir ufs /var/spool/squid 5000 16 256 //line 1782

#cache_access_log: lưu trữ activity request của client yêu cầu đến proxy server để truy cập web
cache_access_log /var/log/squid/access.log //line 1961

#cache_log: lưu trữ thông tin chung về cache
cache_log /var/log/squid/cache.log //line 1962

#cache_store_log: lưu trữ các thông tin về đối tượng được cache trên proxy, thời gian lưu trữ...
cache_store_log /var/log/squid/store.log //line 1971

#cache_effective_user, cache_effective_group: người dùng và nhóm có thể thay đổi squid
cache_effective_user squid
cache_effective_group squid

cache_replacement_policy heap LFUDA // thuật toán cache đĩa
memory_replacement_policy heap GDSF //thuật toán cache RAM
maximum_object_size_in_memory 32 KB // file lớn nhất có thể RAM cache
maximum_object_size 1000 MB // file lớn nhất có thể cache

#Access Control List và Access Control Operators: dùng để ngăn chặn việc truy xuất dựa vào tên #miền, địa chỉ IP. Mặc định, squid từ chối tất cả, vì vậy phải cấu hình lại

acl mynetwork src "/etc/squid/allowip.txt" //line 591
http_access allow mynetwork
http_access deny all

visible_hostname squid

Khởi động squid:
#/etc/init.d/squid start
Nếu có báo lỗi do không có quyền ghi trong /var/spool/squid, ta phải gán cho user/group squid có quyền 770.
#chmod 770 /var/spool/squid

Cho nó auto start:
#chkconfig squid on

3. Tùy biến nâng cao trong squid:
a. Cấm truy cập website dựa trên domain đã định:
Thêm vào trong file cấu hình một số phần như sau:
#vi /etc/squid/squid.conf
//deny website in ban_list
acl denywebsite dstdom_regex "/etc/squid/ban_list"
http_access deny denywebsite

Tạo file ban_list
#vi /etc/squid/ban_list
yahoo.com
vnexpress.net
nhacso.net

b. Hạn chế nội dung các file download:
#vi /etc/squid/squid.conf
acl home_network src 192.168.1.0/24
acl denyfiletypes url_regex -i .mp3$ .mpg$ .mpeg$ .mp2$ .avi$ .wmv$ .wma$ .exe$
http_access deny denyfiletypes
http_access allow home_network

Nếu muốn chỉ cho 1 net nào đó được download thì thêm vào !net_muon_cho
acl it-server src "/etc/squid/it-server.txt"
http_access deny denyfiletypes !it-server
sau đó soạn file it-server.txt gồm net mình muốn cho download các file trên

c. Cấu hình squid proxy để điều khiển băng thông:
Thêm vào file cấu hình một số phần như sau:
#Add control bandwidth
acl ip src "/etc/squid/ip.txt"
acl all src 0.0.0.0/0.0.0.0
#Add control bandwidth
delay_pools 1
delay_class 1 2
delay_access 1 allow ip
delay_access 1 deny all
delay_parameters 1 -1/-1 15000/15000

Với delay_parameters 1 -1/-1 15000/15000 ta sẽ giới hạn băng thông cho các client không thể vượt quá 15000 tương đương 15Kbps.
Sau đó tạo file /etc/squid/ip.txt như sau:
#vi /etc/squid/ip.txt
192.168.1.33/24
192.168.1.34/24

d. Cấu hình nội dung hiện ra khi client bị cấm truy cập site nào đó:
Chỉnh sửa file /usr/share/squid/errors/English/ERR_ACCESS_DENIED
#vi /usr/share/squid/errors/English/ERR_ACCESS_DENIED
giờ thì tùy biến nội dung hiện ra khi user truy cập một trang web nào mà ta đã cấm.

e. Hạn chế dung lượng download:
Giả sử ta hạn chế không cho download trên 10MB, ngoại trừ IT
Nếu muốn chỉ cho 1 net nào đó được download thì thêm vào !net_muon_cho
#vi /etc/squid/squid.conf
acl network src "/etc/squid/network.txt"
acl it-server src "/etc/squid/it-server.txt"
reply_body_max_size 10000000 allow network !it-server

Xem thông tin squid:
#squidclient mgr:info //xem tình trạng cache
#uptime //xem tải
#top //xem tổng hợp tình trạng hệ thống

III. Cấu hình Sarg để monitor squid log:
Dĩ nhiên ta cần phải monitor squid log để biết được user truy cập site nào nhiều, download cái gì, …
1. Cài đặt:
#yum -y install gd gd-devel
#yum -y install sarg

Nên để ý 2 thông số sau trong file cấu hình của sarg
#vi /etc/sarg/sarg.conf
access_log /var/log/squid/access.log ( file log của squid )
output_dir /var/www/sarg/ONE-SHOT ( thư mục chứa report )

Cho phép IP nào được xem report của sarg:
#vi /etc/httpd/conf.d/sarg.conf
Allow from 192.168.0.1,127.0.0.1 //allow IP to see report

Các file script để lấy thông tin theo ngày, theo tuần, theo tháng:
#vi /etc/cron.daily/sarg
#!/bin/bash

# Get yesterday's date
YESTERDAY=$(date --date "1 days ago" +%d/%m/%Y)

exec /usr/bin/sarg \
-o /var/www/sarg/daily \
-d $YESTERDAY &>/dev/null
exit 0

#vi /etc/cron.weekly/sarg
#!/bin/bash

# Get one week ago date
WEEKAGO=$(date --date "7 days ago" +%d/%m/%Y)

exec /usr/bin/sarg \
$LOG_FILES \
-o /var/www/sarg/weekly \
-d $WEEKAGO-$YESTERDAY &>/dev/null
exit 0

#vi /etc/cron.monthly/sarg
#!/bin/bash

# Get 1 month ago date
MONTHAGO=$(date --date "1 month ago" +%d/%m/%Y)

exec /usr/bin/sarg \
$LOG_FILES \
-o /var/www/sarg/monthly \
-d $MONTHAGO-$YESTERDAY &>/dev/null
exit 0

Tạo chỉ số index:
#sarg -ix
Chạy lần đầu:
#/usr/bin/sarg
#/etc/cron.daily/sarg
#/etc/cron.weekly/sarg
#/etc/cron.monthly/sarg

2. Cấu hình Crontab:
Trong file /etc/crontab thêm vào những dòng sau
#vi /etc/crontab
1 0 * * * root /etc/cron.daily/sarg
1 1 * * 0 root /etc/cron.weekly/sarg
1 2 1 * * root /etc/cron.monthly/sarg

Note : /etc/init.d/httpd start
Kiểm tra: http://IP_server_proxy/sarg

3. Setup Real Time cho Squid:
SqStat là một đoạn script cho phép xem các kết nối của user đang active qua squid. Nó dùng cachemgr protocol để lấy thông tin từ squid proxy server.
Ta download SqStat từ http://samm.kiev.ua/sqstat/ gói sqstat-1.20.tar.gz.
Yêu cầu hệ thống phải cài squid và php 4.1 trở lên.

Cài đặt SqStat: giải nén gói download về vào trong thư mục /var/www/html/ , đổi tên thư mục sqstat-1.20 thành realtime, vào thư mục realtime đổi tên file config.inc.php.defaults lại thành config.inc.php , sửa lại file config.inc.php với thông số như sau :

/* Squid proxy server ip address or host name */
$squidhost[0]="localhost"; //line 13
/* Squid proxy server port */
$squidport[0]=3128; //đây là port lắng nghe của squid, nếu squid thay đổi phải đổi ở đây

Đổi tên tập tin sqstat.php thành index.php.
Restart httpd.

Vào trình duyệt gõ http://IP_squid/realtime.

Trên trình duyệt chính sẽ có nhưng thông số như sau:

Auto refresh : chỉnh thông số sẽ refresh lại sau thời gian cụ thể nào đó ( đơn vị tính là s ) , mặc định là 0 s
Update : lấy thông số kết nối tại thời điểm hiện tại
Stop : dừng lại


Tham khảo tại:
http://www.shorewall.net/shorewall_setup_guide.htm#Concepts
http://www.squid-cache.org/Doc/config/

Thứ Hai, 31 tháng 8, 2009

MƯA QUA MẮT AI

“Ai lang thang trên đường phố đêm mưa, vẫn biết rằng lòng mãi cô đơn. Từng hạt mưa mơn man trên bờ mi ai kia, để hòa tan trong tim giọt nước mắt lạnh lùng...", những ca từ trong bài hát ấy khiến tôi nhớ về những ngày mưa rơi trên phố Sài thành. Mưa Sài thành không giống như mưa trên những đồi thông Đà Lạt, bãng lãng dịu dàng và đẹp nên thơ. Mưa Sài thành gai góc, lạnh lùng và vội vã, những giọt mưa tí tách rơi thoáng qua rồi lại tắt. Phải chăng ngay cả mưa cũng bị ảnh hưởng bởi lối sống tất bật ồn ã của chốn đô thành?

Có những chiều dạo phố, mưa rơi… Nói ra nhiều người cho là tôi mơ mộng quá, và tôi đang sống một lối sống lãng mạn xa xỉ không nên có giữa cái thế giới dường chư đã lãng quên những giá trị đơn thuần. Nhưng thật ra việc thú nhận chút miên man, lãng mạn và mộng mơ của bản thân thì có gì là xấu!

Những lúc đi dạo dưới trời mưa với cái ô màu xanh nhạt che trên đầu chắc thích lắm nhỉ! Đôi lúc lại mong muốn che ô dạo quanh Sài Gòn như thế nhưng rồi lại thôi! Sợ điều gì? Phải chăng là những ánh nhìn kì quặc? Mà cũng phải, liệu có mấy khi Sài Gòn xuất hiện những cơn mưa phùn, mưa nhè nhẹ tưới mát con đường mà không hề làm ướt bước người qua.

Mưa chiều buồn bã, nhưng cũng miên man làm ấm lòng những đôi uyên ương dạo bước. Nhìn họ và mỉm cười, bạn sẽ thấy hạnh phúc thật sự đang tồn tại. Họ ấm áp choàng tay và nép mình sau những chiếc ô trong suốt xinh xinh…Một tình yêu bắt đầu.

Nhưng mưa cũng vô tình lắm, nó khiến những đôi chân lạc bước trở nên bơ vơ và trơ trọi , khiến những kẻ lãng du quên bẵng lối về. Đứa bé không nhà nằm co ro ngoài hiên vắng, không người đi qua, mặt em lấm tấm những giọt mưa, nhưng rồi tôi tự hỏi, là mưa hay nước mắt?

Và có những con đường mưa rơi mang theo kỉ niệm và nỗi nhớ về một thời đã xa. Một ông lão, mái tóc đã bạc màu với chiếc áo mưa mỏng manh dường như không che chắn được một thân thể gầy gò và ốm yếu, vẫn ngồi đấy, lặng lẽ, mong mưa… Vì sao? Phải chăng có những khoảnh khắc mà cả một đời người ta không thể nào quên, có những khoảnh khắc dù cho thời gian có bào mòn bao nhiêu kí ức, có làm tàn phai bao sắc thanh xuân vẫn không thể nào lay động cảm giác về mối tình đầu năm cũ – một tình yêu bắt đầu dưới những cơn mưa…