November 23, 2011

MySQL Replication cluster

MySQL Replication cluster

This guide is designed to help do the initial setup on a MySQL cluster in which multiple MySQL servers all serve the same content through the use of the replication function. We have successfully deployed this solution for multiple clients and it is a very good option for those needing a more powerful mysql solution.

Be sure your mysql servers are running the same version before starting this guide, yes, is possible to have a few combinations of master-slave versions, for more information about this you can check:

http://dev.mysql.com/doc/refman/4.1/en/replication-compatibility.html


1 - Write down which is the setup you are going to do, which server is master and which server/s will be slave.

2 - Select your username/password for replications accounts. You can have one per server if you want, or one for all the mysql network.

3 - mysql> GRANT REPLICATION SLAVE ON *.*

TO 'USERNAME'@'IPFROMTHESLAVE' IDENTIFIED BY 'PASSWORD';

Username: mysql username
IPfromtheslave: ip from the mysql server that will be the one replicating the master db.
PASSWORD: the password for the replicator account.

Just a few side notes.

a) None of the passwords need to be root passwords.
b) Is not recomend to use only 1 user for replication in all the network.

4) In the master server you need to Flush all the tables, this will prevent clients from writing the db so it will keep without change while we copy over.

mysql> FLUSH TABLES WITH READ LOCK;

5) Make sure that the [mysqld] section of the my.cnf file on the master host includes a log-bin option. The section should also have a server-id=master_id option, where master_id must be a positive integer value from 1 to 232 – 1. For example:

[mysqld]

log-bin=mysql-bin

server-id=1

6) Login using another ssh client to the master server and lets create a snapshot.

mkdir /home/slave_db
rsync -vrplogDtH /var/lib/mysql /home/slave_db

You may not want to replicate the mysql database if the slave server has a different set of user accounts from those that exist on the master. In this case, you should exclude it from the archive. When the rsync is finish, just login inside mysql and type:

SHOW MASTER STATUS;

Save this info in a txt file inside the slave_db folder that we will use them laster. After you finish doing this, you can reenable the activity on the master: UNLOCK TABLES;

7) Stop the server that is to be used as a slave server and add the following to its my.cnf file:

[mysqld]

server-id=slave_id

The slave_id value, like the master_id value, must be a positive integer value from 1 to 232 – 1. In addition, it is very important that the ID of the slave be different from the ID of the master. For example:

[mysqld]

server-id=2

Remember that server-id must be unique in all the mysql network.

8) Copy the files over from the slave_db folder to the remote location. You can do this doing the following command:

rsync -e ssh -avz /home/slave_db/ root@REMOTESERVER:/var/lib/mysql

Check that all the permitions and correctly in the /var/lib/mysql folder.Remember files must be own by mysql:mysql



9) Start Mysql and enter to it, write the following changing the values that are needed:

mysql> CHANGE MASTER TO

-> MASTER_HOST='master_host_name',

-> MASTER_USER='replication_user_name',

-> MASTER_PASSWORD='replication_password',

-> MASTER_LOG_FILE='recorded_log_file_name',

-> MASTER_LOG_POS=recorded_log_position;



10) type: START SLAVE;

Mirror Your Web Site With rsync

This tutorial shows how you can mirror your web site from your main web server to a backup server that can take over if the main server fails. We use the tool rsync for this, and we make it run through a cron job that checks every x minutes if there is something to update on the mirror. Thus your backup server should usually be up to date if it has to take over.

rsync updates only files that have changed, so you do not need to transfer 5 GB of data whenever you run rsync. It only mirrors new/changed files, and it can also delete files from the mirror that have been deleted on the main server. In addition to that it can preserve permissions and ownerships of mirrored files and directories; to preserve the ownerships, we need to run rsync as root which is what we do here. If permissions and/or ownerships change on the main server, rsync will also change them on the backup server.

In this tutorial we will tunnel rsync through SSH which is more secure; it also means you do not have to open another port in your firewall for rsync - it is enough if port 22 (SSH) is open. The problem is that SSH requires a password for logging in which is not good if you want to run rsync as a cron job. The need for a password requires human interaction which is not what we want.

But fortunately there is a solution: the use of public keys. We create a pair of keys (on our backup server mirror.example.com), one of which is saved in a file on the remote system (server1.example.com). Afterwards we will not be prompted for a password anymore when we run rsync. This also includes cron jobs which is exactly what we want.

As you might have guessed already from what I have written so far, the concept is that we initiate the mirroring of server1.example.com directly from mirror.example.com; server1.example.com does not have to do anything to get mirrored.

I will use the following setup here:

* Main server: server1.example.com (server1) - IP address: 192.168.0.100
* Mirror/backup server: mirror.example.com (mirror) - IP address: 192.168.0.175
* The web site that is to be mirrored is in /var/www on server1.example.com.

rsync is for mirroring files and directories only; if you want to mirror your MySQL database, please take a look at these tutorials:

* How To Set Up Database Replication In MySQL
* How To Set Up A Load-Balanced MySQL Cluster

I want to say first 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 Install rsync

First we have to install rsync on both server1.example.com and mirror.example.com. For Debian systems, this looks like this:

server1/mirror:

(We do this as root!)

apt-get install rsync

On other Linux distributions you would use yum (Fedora/CentOS) or yast (SuSE) to install rsync.

2 Create An Unprivileged User On server1.example.com

Now we create an unprivileged user called someuser on server1.example.com that will be used by rsync on mirror.example.com to mirror the directory /var/www (of course, someuser must have read permissions on /var/www on server1.example.com).

server1:

(We do this as root!)

useradd -d /home/someuser -m -s /bin/bash someuser

This will create the user someuser with the home directory /home/someuser and the login shell /bin/bash (it is important that someuser has a valid login shell - something like /bin/false does not work!). Now give someuser a password:

passwd someuser

3 Test rsync

Next we test rsync on mirror.example.com. As root we do this:

mirror:

rsync -avz -e ssh someuser@server1.example.com:/var/www/ /var/www/

You should see something like this. Answer with yes:

The authenticity of host 'server1.example.com (192.168.0.100)' can't be established.
RSA key fingerprint is 32:e5:79:8e:5f:5a:25:a9:f1:0d:ef:be:5b:a6:a6:23.
Are you sure you want to continue connecting (yes/no)?

<-- yes Then enter someuser's password, and you should see that server1.example.com's /var/www directory is mirrored to /var/www on mirror.example.com. You can check that like this on both servers: server1/mirror: ls -la /var/www You should see that all files and directories have been mirrored to mirror.example.com, and the files and directories should have the same permissions/ownerships as on server1.example.com. 4 Create The Keys On mirror.example.com Now we create the private/public key pair on mirror.example.com: mirror: (We do this as root!) mkdir /root/rsync ssh-keygen -t dsa -b 2048 -f /root/rsync/mirror-rsync-key You will see something like this: Generating public/private dsa key pair. Enter passphrase (empty for no passphrase): [press enter here] Enter same passphrase again: [press enter here] Your identification has been saved in /root/cron/mirror-rsync-key. Your public key has been saved in /root/cron/mirror-rsync-key.pub. The key fingerprint is: 68:95:35:44:91:f1:45:a4:af:3f:69:2a:ea:c5:4e:d7 root@mirror It is important that you do not enter a passphrase otherwise the mirroring will not work without human interaction so simply hit enter! Next, we copy our public key to server1.example.com: mirror: (Still, we do this as root.) scp /root/rsync/mirror-rsync-key.pub someuser@server1.example.com:/home/someuser/ The public key mirror-rsync-key.pub should now be available in /home/someuser on server1.example.com. 5 Configure server1.example.com Now log in through SSH on server1.example.com as someuser (not root!) and do this: server1: (Please do this as someuser!) mkdir ~/.ssh chmod 700 ~/.ssh mv ~/mirror-rsync-key.pub ~/.ssh/ cd ~/.ssh touch authorized_keys chmod 600 authorized_keys cat mirror-rsync-key.pub >> authorized_keys

By doing this, we have appended the contents of mirror-rsync-key.pub to the file /home/someuser/.ssh/authorized_keys. /home/someuser/.ssh/authorized_keys should look similar to this:

server1:

(Still as someuser!)

vi /home/someuser/.ssh/authorized_keys

ssh-dss AAAAB3NzaC1kc3MAAA[...]lSUom root@
mirror

Now we want to allow connections only from mirror.example.com, and the connecting user should be allowed to use only rsync, so we add

command="/home/someuser/rsync/checkrsync",from="mirror.example.com",no-port-forwarding,no-X11-forwarding,no-pty

right at the beginning of /home/someuser/.ssh/authorized_keys:

server1:

(Still as someuser!)

vi /home/someuser/.ssh/authorized_keys

command="/home/someuser/rsync/checkrsync",from="mirror.example.com",no-port-forwarding,no-X11-forwarding,no-pty ssh-dss AAAAB3NzaC1kc3MAAA[...]lSUom root@
mirror

It is important that you use a FQDN like mirror.example.com instead of an IP address after from=, otherwise the automated mirroring will not work!

Now we create the script /home/someuser/rsync/checkrsync that rejects all commands except rsync.

server1:

(We still do this as someuser!)

mkdir ~/rsync
vi ~/rsync/checkrsync

#!/bin/sh

case "$SSH_ORIGINAL_COMMAND" in
*\&*)
echo "Rejected"
;;
*\(*)
echo "Rejected"
;;
*\{*)
echo "Rejected"
;;
*\;*)
echo "Rejected"
;;
*\<*)
echo "Rejected"
;;
*\`*)
echo "Rejected"
;;
rsync\ --server*)
$SSH_ORIGINAL_COMMAND
;;
*)
echo "Rejected"
;;
esac

chmod 700 ~/rsync/checkrsync


6 Test rsync On mirror.example.com

Now we must test on mirror.example.com if we can mirror server1.example.com without being prompted for someuser's password. We do this:

mirror:

(We do this as root!)

rsync -avz --delete --exclude=**/stats --exclude=**/error --exclude=**/files/pictures -e "ssh -i /root/rsync/mirror-rsync-key" someuser@server1.example.com:/var/www/ /var/www/

(The --delete option means that files that have been deleted on server1.example.com should also be deleted on mirror.example.com. The --exclude option means that these files/directories should not be mirrored; e.g. --exclude=**/error means "do not mirror /var/www/error". You can use multiple --exclude options. I have listed these options as examples; you can adjust the command to your needs. Have a look at
man rsync

for more information.)

You should now see that the mirroring takes place:

receiving file list ... done

sent 71 bytes received 643 bytes 476.00 bytes/sec
total size is 64657 speedup is 90.56

without being prompted for a password! This is what we wanted.


7 Create A Cron Job

We want to automate the mirroring, that is why we create a cron job for it on mirror.example.com. Run crontab -e as root:

mirror:

(We do this as root!)

crontab -e

and create a cron job like this:

*/5 * * * * /usr/bin/rsync -azq --delete --exclude=**/stats --exclude=**/error --exclude=**/files/pictures -e "ssh -i /root/rsync/mirror-rsync-key" someuser@server1.example.com:/var/www/ /var/www/

This would run rsync every 5 minutes; adjust it to your needs (see

man 5 crontab

). I use the full path to rsync here (/usr/bin/rsync) just to go sure that cron knows where to find rsync. Your rsync location might differ. Run

mirror:

(We do this as root!)

which rsync

to find out where yours is.


8 Links

* rsync: http://samba.anu.edu.au/rsync

Logout root automatically when inactive

Logout root automatically when inactive

Generraly, administrators will stay login as “root” or forget to logout after finishing their work and leave their terminals unattended.

The answer to solve this problem is to make the bash shell automatically logout after not being used for a period of time. For that, you must set the special variable named “TMOUT” to the time in seconds of no input before logout.

Edit your profile file (vi /etc/profile) and add the following line somewhere after the line that read “HISTSIZE=” on this file:

Code:

TMOUT=7200


The value we enter for the variable “TMOUT=” is in seconds and represents 2 hours (60 * 60 = 3600 * 2 = 7200 seconds). It is important to note that if you decide to put the above line in your /etc/profile file, then the automatic logout after two hours of inactivity will apply for all users on the system. So, instead, if your prefer to control which users will be automatically logged out and which ones are not, you can set this variable in their individual .bashrc file.

After this parameter has been set on your system, you must logout and login again (as root) for the change to take effect.

Linux Shell Script to reboot DSL or ADSL router.

Linux Shell Script to reboot DSL or ADSL router

If you need to reboot the router then you need to use web interface or telnet interface. Both methods take time, especially if you are playing with ACL, NAT or router firewall or you just wanna reboot the router from your Linux desktop. I have created simple script using expect tool to reboot router. Make sure you have expect command installed. Use rpm or apt-get command to install expect tool.
Shell script

Create a script as follows (tested on Beetel ADSL 220x router):

#!/usr/bin/expect -f

set timeout 20

# router user name
set name "admin"

# router password
set pass "PASSWORD"

# router IP address
set routerip "192.168.1.254"

# Read command as arg to this script
set routercmd [lindex $argv 0]

# start telnet
spawn telnet $routerip

# send username & password
expect "Login:"
send -- "$name\r"
expect "Password:"
send -- "$pass\r"

# get out of ISP's Stupid menu program, go to shell
expect " -> "
send -- "sh\r"

# execute command
expect "# "
send -- "$routercmd\r"
# exit
send -- "^D"

Save script and setup executable permission on it:
$ chmod +x router.exp

How do I run this script?


You need to pass command to script to execute on a router. For example to display router uptime, interface information and to reboot router you need to type command as follows:
$ ./router.exp uptime
$ ./router.exp ifconfig
$ ./router.exp reboot

Since my ISP router offers menu as soon as login above script may not work on generic router such as Cisco or linksys router. Therefore, you may need to modify above script to work with your router. If you are a new to expect then use autoexpect command to generate script. It watches you interacting with another program and creates an Expect script that reproduces your interactions For straightline scripts, autoexpect saves substantial time over writing scripts by hand. Even if you are an Expect expert, you will find it convenient to use autoexpect to automate the more mindless parts of interactions. It is much easier to cut/paste hunks of autoexpect scripts together than to write them from scratch. Moreover, if you are a beginner, you may be able to get away with learning nothing more about Expect than how to call autoexpect. Just type autoexecpt:
$ autoexpectautoexpect started, file is script.exp

Next type telnet command (telnet to the router):
$ telnet 192.168.1.254
Output:

Login: USER
Password: Password

Now type commands on the router:
$ ifconfig
$ exit
You are done, type exit to stop autoexepct command:
$ exit
Output:

autoexpect done, file is script.exp

Just type ./script.exp to run ifconfig command:
$ ./script.exp

You can now modify script.exp to reboot or to run other commands. It is a real lifesaver.

How to Prevent DDoS Attack

How to Prevent DDoS Attack

All web servers been connected to the Internet subjected to DoS (Denial of Service) or DDoS (Distrubuted Denial of Service) attacks in some kind or another, where hackers or attackers launch large amount connections consistently and persistently to the server, and in advanced stage, distributed from multiple IP addresses or sources, in the hope to bring down the server or use up all network bandwidth and system resources to deny web pages serving or website not responding to legitimate visitors.

You can detect the ddos using the following command

netstat -anp|grep tcp|awk '{print $5}'| cut -d : -f1|sort|uniq -c|sort -n

It will shows the number of connections from all IPs to the server.

There are plenty of ways to prevent, stop, fight and kill off DDoS attack, such as using firewall. A low cost, and probably free method is by using software based firewall or filtering service. (D)DoS-Deflate is a free open source Unix/Linux script by MediaLayer that automatically mitigate (D)DoS attacks. It claims to be the best, free, open source solution to protect servers against some of the most excruciating DDoS attacks.

(D)DoS-Deflate script basically monitors and tracks the IP addresses are sending and establishing large amount of TCP network connections such as mass emailing, DoS pings, HTTP requests) by using netstat command, which is the symptom of a denial of service attack. When it detects number of connections from a single node that exceeds certain preset limit, the script will automatically uses APF or IPTABLES to ban and block the IPs. Depending on the configuration, the banned IP addresses would be unbanned using APF or IPTABLES (only works on APF v 0.96 or better).

Installation and setup of (D)DOS-Deflate on the server is extremely easy. Simply login as root by open SSH secure shell access to the server, and run the the following commands one by one:

wget http://www.inetbase.com/scripts/ddos/install.sh
chmod 0700 install.sh
./install.sh

To uninstall the (D)DOS-Deflate, run the following commands one by one instead:

wget http://www.inetbase.com/scripts/ddos/uninstall.ddos
chmod 0700 uninstall.ddos
./uninstall.ddos

The configuration file for (D)DOS-Deflate is ddos.conf, and by default it will have the following values:

Code:
FREQ=1
NO_OF_CONNECTIONS=50
APF_BAN=1
KILL=1
EMAIL_TO=”root”
BAN_PERIOD=600


Users can change any of these settings to suit the different need or usage pattern of different servers. It’s also possible to whitelist and permanently unblock (never ban) IP addresses by listing them in /usr/local/ddos/ignore.ip.list file. If you plan to execute and run the script interactively, users can set KILL=0 so that any bad IPs detected are not banned.

How to increase the memory limit of php

How to increase the memory limit of php

If you have seen an error like “Fatal Error: PHP Allowed Memory Size Exhausted” in apache logs or in your browser, this means that PHP has exhausted the maximum memory limit. This post will show 3 different ways on how you can increase the php memory limit and also explain when you should use them.

First, let’s see where is this limit coming from. Normally you will see from the error message what is the actual limit, as this will look like:

"PHP Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y) in whatever.php"

The default value might differ depending on what php version and linux distribution you are running, but normally this will be set to either 8M or 16M. For example on my debian etch, running on php 5.2 this is set by default at 16M.

In order to identify the current value on your system, look inside your php.ini and search for memory_limit:
memory_limit = 16M ; Maximum amount of memory a script may consume (16MB)

There are three ways to change this value, the obvious way - changing the global value from php.ini, but also an individual method to change it just for a script, or folder.

1. Changing memory_limit globally from php.ini

This is the simplest and most obvious method. You just edit your php.ini and change the memory_limit to whatever you need. For ex:

memory_limit = 32M

You will require access to make changes to php.ini on the system. This change is global and will be used by all php scripts running on the system. Once you change this value, you will need to restart the web server in order for it to become active.

Keep in mind that this limit has its logic and don’t increase it artificially, as poorly written php scripts might overkill your system without proper limits.
Note: if you know what you are doing and want to remove the memory limit, you would set this value to -1.

2. Changing memory_limit using .htaccess for a single folder/vhost


Changing the global memory_limit might not be a good idea, and you might be better changing this only inside one folder (normally one application or virtual host) that needs this value changed for its functionality. To do this you have to add to the respective location .htaccess something like:

php_value memory_limit 64M

This change will be local only, and can be useful for webmasters that don’t have control on the system php.ini. This change would not require a reload and will become active immediately.

3. Changing memory_limit inside a single php script.

For even more control you can set this directive inside a single php script. To do so you would use in your code:

ini_set('memory_limit', '64M');

The advantage of this method is that you have more control and set this value just where you know it is really needed. Also it can be done without having access to the system php.ini, and will become active immediately.

Note: in order to be able to use these PHP resource limits, your PHP version must have been compiled with the –enable-memory-limit configure option. Normally most packed versions will have this, but just in case if this doesn't work for you as expected, check on how php was compiled first.

Deny users and groups in Openssh

OpenSSH has two directives for allowing and denying ssh user access.

DenyUsers user1 user2 user3

Use to block user login. You can use wild cards as well as user1@somedomain.com (user1 is not allowed to login from somedomain.com host) pattern.

DenyGroups group1 group2
A list of group names, if user is part of primary of supplementary group login access is denied. You can use wildcards.

Please note that you cannot use a numeric group or username ID. If these directives are not used, default is to allow everyone.

AllowUsers user1 user2
This directive is opposite of DenyUsers directive.

AllowGroups group1 group2
This directive is opposite of DenyGroups directive.

You should always block access to root user/group:
Open /etc/ssh/sshd_config file:

# vi /etc/ssh/sshd_config

Append following names (directives):

DenyUsers root finadmin
DenyGroups root finadmin

Make sure at least one user is allowed to use 'su -' command.

Save the file and restart the sshd.

This is a secure setup and you are restricting the users allowed to access the system via SSH with four above directives.

Automatic Login using expect tool and ssh

Automatic Login using expect tool and ssh

In order to save time it is possible to save the login information to a file and then use the expect tool to login to a server.

Before you proceed with this,make sure that expect tool is installed.

else install expect tool

#yum install expect

Now save the login information to a file. Take a look at the below example.

vi server1

#!/usr/bin/expect -f
spawn ssh root@192.168.0.254
expect "password:"
send "password\r"
expect "#"
interact

save the file and exit. Make sure you replace the password in send "password\r" with the real password leaving \r alone. Else you will have to press enter to login to the server

Now use the command to login to the server 192.168.0.254

expect server1

Thats it you have logged in. No password nothing.

SSO of Alfresco with CAS

Notes for

Installation and configuration of Alfresco
Installation of CAS
Integration of Alfresco Explorer and Share with CAS
SSO


You can mail me on pcgeopc@gmail.com

November 22, 2011

Drush

drush” is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt. In general
• drush is a command line shell and scripting interface for Drupal.
• drush is not a module
• It is valid to use the latest '7.x' (or master) no matter what your version of Drupal is. Drush is independent of Drupal version

Installation:

1. Untar the tarball into a folder outside of your web site (/path/to/drush)
2. Make the 'drush' command executable:
$ chmod u+x /path/to/drush/drush
3. (Optional, but recommended:) To ease the use of drush,
- create a link to drush in a directory that is in your PATH, e.g.:
$ ln -s /path/to/drush/drush /usr/local/bin/drush
NOTE ON PHP.INI FILES
Usually, php is configured to use separate php.ini files for the web server and the command line. To see which php.ini file drush is using, run:
$ drush status
Compare the php.ini that drush is using with the php.ini that the webserver is using. Make sure that drush's php.ini is given as much memory to work with asthe web server is; otherwise, Drupal might run out of memory when drush bootstraps it.
Drush requires a fairly unrestricted php environment to run in. In particular, you should insure that safe_mode, open_basedir, disable_functions and disable_classes are empty.
If drush is using the same php.ini file as the web server, you can create a php.ini file exclusively for drush by copying your web server's php.ini file to the folder $HOME/.drush or the folder /etc/drush. Then you may edit this file and change the settings described above without affecting the php enviornment of your web server.

4. Start using drush by running "drush" from your Drupal root directory.

Drush Commands:
You can find the drush commands from the url: http://drush.ws/