mysql loadbalancing with HAProxy 1.5

http://www.percona.com/doc/percona-xtradb-cluster/5.5/howtos/haproxy.html

apt-add-repository ppa:vbernat/haproxy-1.5
apt-get update
apt-get install haproxy

apt-get install xinetd
cd /etc/xinetd.d

root@server55:/etc/xinetd.d# vim   mysqlchk
# default: on
# description: mysqlchk
service mysqlchk
{
        disable = no
        flags = REUSE
        socket_type = stream
        port = 9200
        wait = no
        user = nobody
        server = /usr/bin/clustercheck
        log_on_failure += USERID
        only_from = 0.0.0.0/0
        per_source = UNLIMITED
}

########Creating script to check the cluster status for haproxy##########
#create a script in /usr/bin

#vim /usr/bin/clustercheck

#!/bin/bash
#
# Script to make a proxy (ie HAProxy) capable of monitoring Percona XtraDB Cluster nodes properly
#
# Author: Olaf van Zandwijk <olaf.vanzandwijk@nedap.com>
# Author: Raghavendra Prabhu <raghavendra.prabhu@percona.com>
#
# Documentation and download: https://github.com/olafz/percona-clustercheck
#
# Based on the original script from Unai Rodriguez
#

if [[ $1 == '-h' || $1 == '--help' ]];then
    echo "Usage: $0 <user> <pass> <available_when_donor=0|1> <log_file> <available_when_readonly=0|1> <defaults_extra_file>"
    exit
fi

# if the disabled file is present, return 503. This allows
# admins to manually remove a node from a cluster easily.
if [ -e "/var/tmp/clustercheck.disabled" ]; then
    # Shell return-code is 1
    echo -en "HTTP/1.1 503 Service Unavailable\r\n"
    echo -en "Content-Type: text/plain\r\n"
    echo -en "Connection: close\r\n"
    echo -en "Content-Length: 51\r\n"
    echo -en "\r\n"
    echo -en "Percona XtraDB Cluster Node is manually disabled.\r\n"
    sleep 0.1
    exit 1
fi

MYSQL_USERNAME="${1-clustercheck}"
MYSQL_PASSWORD="${2-clustercHeck223p@ssword}"
AVAILABLE_WHEN_DONOR=${3:-0}
ERR_FILE="${4:-/dev/null}"
AVAILABLE_WHEN_READONLY=${5:-1}
DEFAULTS_EXTRA_FILE=${6:-/etc/my.cnf}

#Timeout exists for instances where mysqld may be hung
TIMEOUT=10

EXTRA_ARGS=""
if [[ -n "$MYSQL_USERNAME" ]]; then
    EXTRA_ARGS="$EXTRA_ARGS --user=${MYSQL_USERNAME}"
fi
if [[ -n "$MYSQL_PASSWORD" ]]; then
    EXTRA_ARGS="$EXTRA_ARGS --password=${MYSQL_PASSWORD}"
fi
if [[ -r $DEFAULTS_EXTRA_FILE ]];then
    MYSQL_CMDLINE="mysql --defaults-extra-file=$DEFAULTS_EXTRA_FILE -nNE --connect-timeout=$TIMEOUT \
                    ${EXTRA_ARGS}"
else
    MYSQL_CMDLINE="mysql -nNE --connect-timeout=$TIMEOUT ${EXTRA_ARGS}"
fi
#
# Perform the query to check the wsrep_local_state
#
WSREP_STATUS=$($MYSQL_CMDLINE -e "SHOW STATUS LIKE 'wsrep_local_state';" \
    2>${ERR_FILE} | tail -1 2>>${ERR_FILE})

if [[ "${WSREP_STATUS}" == "4" ]] || [[ "${WSREP_STATUS}" == "2" && ${AVAILABLE_WHEN_DONOR} == 1 ]]
then
    # Check only when set to 0 to avoid latency in response.
    if [[ $AVAILABLE_WHEN_READONLY -eq 0 ]];then
        READ_ONLY=$($MYSQL_CMDLINE -e "SHOW GLOBAL VARIABLES LIKE 'read_only';" \
                    2>${ERR_FILE} | tail -1 2>>${ERR_FILE})

        if [[ "${READ_ONLY}" == "ON" ]];then
            # Percona XtraDB Cluster node local state is 'Synced', but it is in
            # read-only mode. The variable AVAILABLE_WHEN_READONLY is set to 0.
            # => return HTTP 503
            # Shell return-code is 1
echo -en "HTTP/1.1 503 Service Unavailable\r\n"
            echo -en "Content-Type: text/plain\r\n"
            echo -en "Connection: close\r\n"
            echo -en "Content-Length: 43\r\n"
            echo -en "\r\n"
            echo -en "Percona XtraDB Cluster Node is read-only.\r\n"
            sleep 0.1
            exit 1
        fi
    fi
    # Percona XtraDB Cluster node local state is 'Synced' => return HTTP 200
    # Shell return-code is 0
    echo -en "HTTP/1.1 200 OK\r\n"
    echo -en "Content-Type: text/plain\r\n"
    echo -en "Connection: close\r\n"
    echo -en "Content-Length: 40\r\n"
    echo -en "\r\n"
    echo -en "Percona XtraDB Cluster Node is synced.\r\n"
    sleep 0.1
    exit 0
else
    # Percona XtraDB Cluster node local state is not 'Synced' => return HTTP 503
    # Shell return-code is 1
    echo -en "HTTP/1.1 503 Service Unavailable\r\n"
    echo -en "Content-Type: text/plain\r\n"
    echo -en "Connection: close\r\n"
    echo -en "Content-Length: 44\r\n"
    echo -en "\r\n"
    echo -en "Percona XtraDB Cluster Node is not synced.\r\n"
    sleep 0.1
    exit 1
fi
                         
##############

#chmod 755  /usr/bin/clustercheck
Note:- the user and password should be matched with /usr/bin/clustercheck  script user/pass values.
On galera 10 and mariadb 10 , you can create that user on one node only ,rest will be replicated automatically.
###  create user for haproxy in each cluster nodes
@db01 #GRANT PROCESS ON *.* TO 'clustercheckuser'@'localhost' IDENTIFIED BY 'clustercHeck223p@ssword' ;

# Modify /etc/services to add 9200 port for mysqlcheck
#check for 9200 port  disable it and add like below to end of file

mysqlchk 9200/tcp #galera clustercheck

On EACH MariaDB Cluster node, start xinetd.
service xinetd start
Now we create the pools by editing the HAProxy configuration file. It would be a good idea to backup the existing (default) haproxy.cfg file before making edits.

@HAPROXY SERVER

global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon



defaults
  mode    tcp
  log     global
  option  dontlognull
  option  redispatch
  retries                   3
  timeout queue             45s
  timeout connect           5s
  timeout client            1m
  timeout server            1m
  timeout check             10s
  maxconn                   1020

listen haproxy-monitoring *:8090
  mode    http
  stats   enable
  stats   show-legends
  stats   refresh           5s
  stats   uri               /
  stats   realm             Haproxy\ Statistics
  stats   auth              monitor:AdMiN123
  stats   admin             if TRUE

listen mysql-cluster 0.0.0.0:3306
    mode tcp
    balance roundrobin
    option httpchk

    server mysql-1 192.168.163.55:3306 check port 9200 inter 12000 rise 3 fall 3
    server mysql-2 192.168.163.56:3306 check port 9200 inter 12000 rise 3 fall 3

    server mysql-3 192.168.163.57:3306 check port 9200 inter 12000 rise 3 fall 3


####
to check with script
root@server55:/usr/bin# clustercheck 
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: close
Content-Length: 40

Percona XtraDB Cluster Node is synced.

MariaDB [(none)]> show status like '%wsrep_cluster_size%';  
MariaDB [(none)]> show status like '%wsrep%';

| wsrep_provider_name          | Galera                                                    
| wsrep_provider_vendor        | Codership Oy <info@codership.com>                          
| wsrep_provider_version       | 25.3.5-wheezy(rXXXX)                                    

| wsrep_ready                  | ON    <= this means good    

From a web browser, visit http://192.168.56.224:9000/haproxy_stats and login with user haproxy and password 

mysql -e 'show status like "wsrep%"' | grep -E "comment|ready|connected|cluster_size"
output on 3 node cluster
wsrep_local_state_comment       Synced
wsrep_cluster_size      3
wsrep_connected ON

wsrep_ready     ON
https://dba.stackexchange.com/questions/132769/how-to-verify-galera-is-synced

Reference:-

https://mariadb.com/blog/setup-mariadb-enterprise-cluster-part-3-setup-ha-proxy-load-balancer-read-and-write-pools








MariaDB Galera Cluster on Debian/Ubuntu

This is a HOWTO about installing MariaDB Galera Cluster on Debian/Ubuntu.
It is because a lot of people had problems installing MariaDB Galera Cluster.
In the end elenst from #maria on freenode forced me to write a Howto :)
You will find out, installing MariaDB Galera Cluster is in fact quite easy and some kind of boring in the end.
This Howto is written (tested) on Debian 7.1 (Wheezy) and Ubuntu 12.04 (Precise).

What we need

In our setup we assume 3 nodes (node01, node02, node03) with one interface.
We assume following IP addresses: 172.16.8.5, 172.16.8.6 and 172.16.8.4. We need three packages installed on all nodes:
  • rsync
  • galera
  • mariadb-galera-server
As Galera does not ship with the distribution repositories, go for the repo configurator and follow the instructions to include the repository fitting your system.
Keep in mind to Choose "5.5" in Step 3 (Choose a Version). Doing this you can jump directly to Install Packages

Including Repository

Alternatively you can just take following steps.

Debian Wheezy

 # apt-get install python-software-properties
 # apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xcbcb082a1bb943db
 # add-apt-repository 'deb http://mirror3.layerjet.com/mariadb/repo/5.5/debian wheezy main'
 # apt-get update

Ubuntu Precise

 # apt-get install python-software-properties
 # apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xcbcb082a1bb943db
 # add-apt-repository 'deb http://mirror3.layerjet.com/mariadb/repo/5.5/ubuntu precise main'
 # apt-get update
Yes, they are nearly the same :)

Install Packages

(Just another shortcut for the impatient)
 # DEBIAN_FRONTEND=noninteractive apt-get install -y  rsync galera mariadb-galera-server
After you installed the packages you have a running MariaDB/MySQL on each node. But none of them is configured to run in/as a Galera Cluster.

Configuring Galera

So we got to do some configuration next. There is a MySQL/MariaDB configuration part and one part to configure Galera (starting with wsrep_). As we do the most basic and simple installation in this Howto, it is sufficient you just change the IP's (Remember: 172.16.8.5, 172.16.8.6, 172.16.8.4) with your IP's.
This will be needed to define the wsrep_cluster_address Variable. The list of nodes a starting mysql contacts to get into the cluster.
The following configuration file has to be distributed on all nodes. We use a separate configuration file/etc/mysql/conf.d/galera.cnf with following settings:
[mysqld]
#mysql settings
binlog_format=ROW
default-storage-engine=innodb
innodb_autoinc_lock_mode=2
query_cache_size=0
query_cache_type=0
bind-address=0.0.0.0
#galera settings
wsrep_provider=/usr/lib/galera/libgalera_smm.so
wsrep_cluster_name="my_wsrep_cluster"
wsrep_cluster_address="gcomm://172.16.8.5,172.16.8.6,172.16.8.4"
wsrep_sst_method=rsync
FYI: The shared library for wsrep_provider is provided by the installed galera package.
We could also change the cluster name by changing the value of wserp_cluster_name to fit our style.
This setting also works as a shared secret to control the access to the cluster.
With wsrep_cluster_address you see the IP addresses of our setup. The wsrep_sst_method tells what method to use to synchronise the nodes. While there are also mysqldump and xtrabackup available.
I prefer rsync because it is easy to configure (i.e. it does not need any credentials set on the nodes).
There will be a time you are going to consider using the xtrabackup method. Don't forget to install xtrabackup then.

Starting the Galera Cluster

Let us stop mysql on all nodes.
node01# service mysql stop
node02# service mysql stop
node03# service mysql stop
As we got the configuration file (galera.cnf) already distributed to all nodes, we start the first mysqld. This node initialises/starts the cluster (creates a GTID).
node01# service mysql start --wsrep-new-cluster
So just have a look if everything really worked well be checking the cluster size.
node01# mysql -u root -e 'SELECT VARIABLE_VALUE as "cluster size" FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME="wsrep_cluster_size"'
+--------------+
| cluster size |
+--------------+
| 1            |
+--------------+
Ok great thats what we would expect. Ok now as the Cluster already exists, let the next nodes just start and join the cluster.
node2# service mysql start
[ ok ] Starting MariaDB database server: mysqld . . . . . . . . . ..
[info] Checking for corrupt, not cleanly closed and upgrade needing tables..
node01:/home/debian# ERROR 1045 (28000): Access denied for user 'debian-sys-maint'@'localhost' (using password: YES)
We ignore the error for now. This node is still starting fine.
Let's do a quick check. As we run a cluster it is not important if we check on node01 or node02.
node01# mysql -u root -e 'SELECT VARIABLE_VALUE as "cluster size" FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME="wsrep_cluster_size"'
+--------------+
| cluster size |
+--------------+
| 2            |
+--------------+
Very nice. Now lets start the third node:
node3# # service mysql start
[ ok ] Starting MariaDB database server: mysqld . . . . . . . . . ..
[info] Checking for corrupt, not cleanly closed and upgrade needing tables..
node03:/home/debian# ERROR 1045 (28000): Access denied for user 'debian-sys-maint'@'localhost' (using password: YES)


node03# mysql -u root -e 'SELECT VARIABLE_VALUE as "cluster size" FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME="wsrep_cluster_size"'
+--------------+
| cluster size |
+--------------+
| 3            |
+--------------+
Ok we are finished. We got a running MariaDB Galera Cluster \o/

Having fun with Debian/Ubuntu init scripts

But we've got to fix some things because Debian/Ubuntu oddities.
As we saw already the error while starting the node.
What happened? Debian/Ubuntu uses a special user ('debian-sys-maint'@'localhost') in there init script.
Where the credentials for that user are stored in /etc/mysql/debian.cnf.
This user is used to make some checks starting MySQL. Checks I don't think belong into a service script anyway.
We could simply ignore it, but the user user is also used to shutdown the mysqld.
This is also not required, as a SIGTERM is sufficient to shutdown the mysqld :/
As we copied the data from node01 to all other nodes, the credentials in /etc/mysql/debian.cnf are not fitting on node02 and node03.
Thats why we will not be able to shutdown mysql on any of these nodes.
node02# service mysql stop
[FAIL] Stopping MariaDB database server: mysqld failed!
So we've got to fix it, by copying /etc/mysql/debian.cnf from the first node (node01) to all other nodes. So data and configuration file have the same data again.
After that we are able to shutdown the daemon again:
node02# service mysql stop
[ ok ] Stopping MariaDB database server: mysqld.
Great.
So if we would have a proper init script the Howto would have been even shorter ;)
Follow the Bug :)
Ok enjoy your MariaDB Galera Cluster and have fun!
Erkan Yanar
Thx to teuto.net for providing me an OpenStack tenant, so I can run the tests for that Howto.

Keine TrackBacks

TrackBack-URL: http://linsenraum.de/mt/mt-tb.cgi/293

highly available LAMP project

##note: make sure to remove older versions
add-apt-repository ppa:vbernat/haproxy-1.5
apt-get update
apt-get install -y haproxy keepalived
apt-get install lvm2 xfsprogs

##setup lvm disk for storing webdata(html,php,image etc)

add => at end of /etc/sysctl.conf

net.ipv4.ip_nonlocal_bind=1  ##enable for floating ip address not binded to interfae

#run
sysctl -p

 Add firewall rules to allow VRRP communication using the multicast IP address 224.0.0.18 
 and the VRRP protocol (112) on each network interface that Keepalived will control, for example:  
 # iptables -I INPUT -i eth0 -d 224.0.0.0/8 -p vrrp -j ACCEPT  
 # iptables -I OUTPUT -o eth0 -d 224.0.0.0/8 -p vrrp -j ACCEPT  
 # service iptables save  


Keepalived is a piece of software which can be used to achieve high availability by assigning two or more nodes a virtual IP and monitoring those nodes, failing over when one goes down. Keepalived can do more, like load balancing and monitoring,
Keepalived performs failover on layer 4, or the Transport layer, upon which TCP conducts connection-based data transmissions. When a real server fails to reply to simple timeout TCP connection, keepalived detects that the server has failed and removes it from the server pool.

############### keepalive of  LB1


root@vm1:~# cat /etc/keepalived/keepalived.conf
# Settings for notifications
global_defs {
    notification_email {
        your@emailaddress.com     # Email address for notifications
    }
    notification_email_from loadb01@domain.ext  # The from address for the notifications
    smtp_server 127.0.0.1     # You can specifiy your own smtp server here
    smtp_connect_timeout 15
}

# Define the script used to check if haproxy is still working
vrrp_script chk_haproxy {
    script "killall -0 haproxy"
    interval 2
    weight 2
}

# Configuation for the virtual interface
vrrp_instance VI_1 {
    interface eth0
    state MASTER        # set this to BACKUP on the other machine
    priority 100        # set this to number > 100 on the other machine
    virtual_router_id 51

    smtp_alert          # Activate email notifications

    authentication {
        auth_type PASS
        auth_pass myPassw0rd      # Set this to some secret phrase
    }

    # The virtual ip address shared between the two loadbalancers
    virtual_ipaddress {
        192.168.163.200
    }
   
    # Use the script above to check if we should fail over
    track_script {
        chk_haproxy
    }
}

####keepalive of LB2

root@vm2:/etc/keepalived# cat keepalived.conf
# Settings for notifications
global_defs {
    notification_email {
        your@emailaddress.com     # Email address for notifications
    }
    notification_email_from loadb01@domain.ext  # The from address for the notifications
    smtp_server 127.0.0.1     # You can specifiy your own smtp server here
    smtp_connect_timeout 15
}

# Define the script used to check if haproxy is still working
vrrp_script chk_haproxy {
    script "killall -0 haproxy"
    interval 2
    weight 2
}

# Configuation for the virtual interface
vrrp_instance VI_1 {
    interface eth0
    state BACKUP        # set this to BACKUP on the other machine
    priority 101        # set this to 100 on the other machine
    virtual_router_id 51

    smtp_alert          # Activate email notifications

    authentication {
        auth_type PASS
        auth_pass myPassw0rd      # Set this to some secret phrase
    }

    # The virtual ip address shared between the two loadbalancers
    virtual_ipaddress {
        192.168.163.200
    }
   
    # Use the script above to check if we should fail over
    track_script {
        chk_haproxy
    }
}
############################

@Server 1  = vm3.demo.com

#gluster peer probe vm4.demo.com

#gluster volume create volume1 replica 2 transport tcp vm3.demo.com:/glusterdata vm4.demo.com:/glusterdata force

#gluster volume start volume1
#gluster volume info


#### @server 1  Edit   /etc/fstab  and mount
#### lvm mount params
/dev/vg1-01/lv1-01     /storagepool     xfs     defaults     0     0     ###for gluster data

####gluster volume mount  for shared web data
vm3.demo.com:/volume1      /storagepool    glusterfs defaults,_netdev   0   0


#mount -a               ##mount the FS and see the gluster fs changes




kill killall kill processes kill signals

root@vm1:/home/user1# pgrep haproxy
926
root@vm1:/home/user1# killall -0 haproxy
root@vm1:/home/user1# echo $?
0
root@vm1:/home/user1# killall -0 jpt_process
haproxyd: no process found
root@vm1:/home/user1# echo $?
1

Many UNIX dæmons store their process IDs in a file in /var/run when they are started. Using kill -0 to test the pid is a lot easier than parsing ps output



 $ echo $$     # show our process id
 12833
 $ /bin/bash   # create new process
 $ echo $$     # show new process id
 12902
 $ kill -0 12902
 $ echo $?     # exists, exit code is 0
 0
 $ exit        # return to previous shell
 $ kill -0 12902
 bash: kill: (12902) - No such process
 $ echo $?     # doesn't exist, exit code is 1
 1


###############

Most Linux or UNIX users know that there is a kill(1) command to stop processes, but what are the options, what do they mean?
These options are called signals, which can be expressed in either numbers or words. Some known once are "-1" or "-HUP". Also well known is "-9" (aka "-KILL")
  • -1 or -HUP - This argument makes kill send the "Hang Up" signal to processes. This probably originates from the modem/dial-in era. Processes have to be programmed to actually listen to this process and do something with it. Most daemons are programmed to re-read their configuration when they receive such a signal. Anyway; this is very likely the safest kill signal there is, it should not obstruct anything.
  • -2 or -SIGINT - This is the same as starting some program and pressing CTRL+C during execution. Most programs will stop, you could lose data.
  • -9 or -KILL - The kernel will let go of the process without informing the process of it. An unclean kill like this could result in data loss. This is the "hardest", "roughest" and most unsafe kill signal available, and should only be used to stop something that seems unstoppable.
  • -15 or -TERM - Tell the process to stop whatever it's doing, and end itself. When you don't specify any signal, this signal is used. It should be fairly safe to perform, but better start with a "-1" or "-HUP".
To figure out how a program should respond to kill signals, check the man(1) page of the process you are trying to kill. For example the process init(8) has a man-page that explains: SIGHUP Has the same effect as telinit q. ... Q or q tell init to re-examine the /etc/inittab file.
By the way, there are many signals: :) [robertdb@node1 ~]$ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1

secure vsftpd ssl tls

configure vsftpd to use TLS/SSL

root@vm1:~# cat /etc/vsftpd.conf | grep -v "^#"
rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem
ssl_enable=YES  #
allow_anon_ssl=NO #
force_local_data_ssl=YES #
force_local_logins_ssl=YES #
ssl_tlsv1=YES #
ssl_sslv2=NO #
ssl_sslv3=NO #
listen=YES#
anonymous_enable=NO  #
local_enable=YES #
write_enable=YES  #
local_umask=022
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
ftpd_banner=Warning !!! All activities are logged.
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
allow_writeable_chroot=YES
pasv_enable=Yes
pasv_min_port=40000
pasv_max_port=40100
require_ssl_reuse=NO
ssl_ciphers=HIGH

##GEnerate ssl certificate
sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout /etc/ssl/private/vsftpd.pem -out /etc/ssl/private/vsftpd.pem


# service vsftpd restart
vsftpd stop/waiting
vsftpd start/running, process 3096

###### FTP client connection

open filezilla
File - > site manager ->
host:  ip or hostname
protocol: FTP
Encryption: Require explicit FTP over TLS
Logontype: Normal
User:  terminator1
Password: ***********

OK <finish>

Now connect


MySQL multi-master replication

http://scale-out-blog.blogspot.com/2012/04/if-you-must-deploy-multi-master.html

Multi-master replication means that applications update the same tables on different masters, and the changes replicate automatically between those masters.  Remote sites mean that the masters are separated by a wide area network (WAN), which implies high average network latency of 100ms or more.  WAN network latency is also characterized by a long tail, ranging from seconds due to congestion to hours or even days if a ship runs over the wrong undersea cable.


1. Use the Right Replication Technology and Configure It Properly

The best overall tool for MySQL multi-master replication between sites is Tungsten.  The main reason for this assertion is that Tungsten uses a flexible, asynchronous, point-to-point, master/slave replication model that handles a wide variety of topologies such as star replication or all-to-all.  Even so, you have to configure Tungsten properly.  The following topology is currently my favorite:

  • All-to-all topology.  Each master replicates directly to every other master.  This handles prolonged network outages or replication failures well, because one or more masters can drop out without breaking  replication between the remaining masters or requiring reconfiguration.  When the broken master(s) return, replication just resumes on all sides.  All-to-all does not work well if you have a large number of masters.  
  • Updates are not logged on slaves.  This keeps master binlogs simple, which is helpful for debugging, and eliminates the possibility of loops.  It also requires some extra configuration if the masters have their own slaves, as would be the case in a Tungsten Enterprise cluster. 
There are many ways to set up multi-master replication replication, and the right choice varies according to the number of masters, whether you have local clustering, or other considerations.  Giuseppe Maxia has described many topologies, for example here, and the Tungsten Cookbook has even more details.

One approach you should approach with special caution is MySQL circular replication.  In topologies of three or more nodes, circular replication results in broken systems if one of the masters fails.  Also, you should be wary of any kind of synchronous multi-master replication across sites that are separated by more than 50 kilometers (i.e. 1-2ms latency).  Synchronous replication makes a siren-like promise of consistency but the price you pay is slow performance under normal conditions and broken replication when WAN links go down.

2. Use Row-Based Replication to Avoid Data Drift

Replication depends on deterministic updates--a transaction that changes 10 rows on the original master should change exactly the same rows when it executes against a replica.  Unfortunately many SQL statements that are deterministic in master/slave replication are non-deterministic in multi-master topologies.  Consider the following example, which gives a 10% raise to employees in department #35.

   UPDATE emp SET salary = salary * 1.1 WHERE dep_id = 35;

If all masters add employees, then the number of employees who actually get the raise will vary depending on whether such additions have replicated to all masters.  Your servers will very likely become inconsistent with statement replication.  The fix is to enable row-based replication using binlog-format=row in my.cnf.  Row replication transfers the exact row updates from each master to the others and eliminates ambiguity.

3. Prevent Key Collisions on INSERTs

For applications that use auto-increment keys, MySQL offers a useful trick to ensure that such keys do not  collide between masters using the auto-increment-increment and auto-increment-offset parameters in my.cnf.  The following example ensures that auto-increment keys start at 1 and increment by 4 to give values like 1, 5, 9, etc. on this server.

server-id=1
auto-increment-offset = 1

auto-increment-increment = 4
This works so long as your applications use auto-increment keys faithfully.  However, any table that either does not have a primary key or where the key is not an auto-increment field is suspect.  You need to hunt them down and ensure the application generates a proper key that does not collide across masters, for example using UUIDs or by putting the server ID into the key.   Here is a query on the MySQL information schema to help locate tables that do not have an auto-increment primary key. 
SELECT t.table_schema, t.table_name 
  FROM information_schema.tables t 
    WHERE NOT EXISTS 
      (SELECT * FROM information_schema.columns c
       WHERE t.table_schema = c.table_schema  
         AND t.table_name = c.table_name
         AND c.column_key = 'PRI'
         AND c.extra = 'auto_increment')

4. Beware of Semantic Conflicts in Applications

Neither Tungsten nor MySQL native replication can resolve conflicts, though we are starting to design this capability for Tungsten.  You need to avoid them in your applications.  Here are a few tips as you go about this.
First, avoid obvious conflicts.  These include inserting data with the same keys on different masters (described above), updating rows in two places at once, or deleting rows that are updated elsewhere.  Any of these can cause errors that will break replication or cause your masters to become out of sync.  The good news is that many of these problems are not hard to detect and eliminate using properly formatted transactions.  The bad news is that these are the easy conflicts.  There are others that are much harder to address.  
For example, accounting systems need to generate unbroken sequences of numbers for invoices.  A common approach is to use a table that holds the next invoice number and increment it in the same transaction that creates a new invoice.  Another accounting example is reports that need to read the value of accounts consistently, for example at monthly close.  Neither example works off-the-shelf in a multi-master system with asynchronous replication, as they both require some form of synchronization to ensure global consistency across masters.  These and other such cases may force substantial application changes.  Some applications simply do not work with multi-master topologies for this reason. 

5. Remove Triggers or Make Them Harmless
Triggers are a bane of replication.  They conflict with row replication if they run by accident on the slave.  They can also create strange conflicts due to weird behavior/bugs (like this) or other problems like needing definer accounts present.  MySQL native replication turns triggers off on slaves when using row replication, which is a very nice feature that prevents a lot of problems.  
Tungsten on the other hand cannot suppress slave-side triggers.  You must instead alter each trigger to add an IF statement that prevents the trigger from running on the slave.  The technique is described in the Tungsten Cookbook.  It is actually quite flexible and has some advantages for cleaning up data because you can also suppress trigger execution on the master.  
You should regard all triggers with suspicion when moving to multi-master.  If you cannot eliminate triggers, at least find them, look at them carefully to ensure they do not generate conflicts, and test them very thoroughly before deployment.  Here's a query to help you hunt them down: 
SELECT trigger_schema, trigger_name 
  FROM information_schema.triggers;
6. Have a Plan for Sorting Out Mixed Up Data

Master/slave replication has its discontents, but at least sorting out messed up replicas is simple: re-provision from another slave or the master.  No so with multi-master topologies--you can easily get into a situation where all masters have transactions you need to preserve and the only way to sort things out is to track down differences and update masters directly.   Here are some thoughts on how to do this.
  1. Ensure you have tools to detect inconsistencies.  Tungsten has built-in consistency checking with the 'trepctl check' command.  You can also use the Percona Toolkit pt-table-checksum to find differences.  Be forewarned that neither of these works especially well on large tables and may give false results if more than one master is active when you run them.  
  2. Consider relaxing foreign key constraints.  I love foreign keys because they keep data in sync.  However, they can also create problems for fixing messed up data, because the constraints may break replication or make it difficult to go table-by-table when synchronizing across masters.  There is an argument for being a little more relaxed in multi-master settings. 
  3. Switch masters off if possible.  Fixing problems is a lot easier if you can quiesce applications on all but one master.  
  4. Know how to fix data.  Being handy with SQL is very helpful for fixing up problems.  I find SELECT INTO OUTFILE and LOAD DATA INFILE quite handy for moving changes between masters.  Don't forget SET SESSION LOG_FILE_BIN=0 to keep changes from being logged and breaking replication elsewhere.  There are also various synchronization tools like pt-table-sync, but I do not know enough about them to make recommendations.  
At this point it's probably worth mentioning commercial support.  Unless you are a replication guru, it is very comforting to have somebody to call when you are dealing with messed up masters.  Even better, expert advice early on can help you avoid problems in the first place.

(Disclaimer:  My company sells support for Tungsten so I'm not unbiased.  That said, commercial outfits really earn their keep on problems like this.)

7. Test Everything

Cutting corners on testing for multi-master can really hurt.  This article has described a lot of things to look for, so put together a test plan and check for them.  Here are a few tips on procedure:
  1. Set up a realistic pre-prod test with production data snapshots.  
  2. Have a way to reset your test environment quickly from a single master, so you can get back to a consistent state to restart testing. 
  3. Run tests on all masters, not just one.  You never know if things are properly configured everywhere until you try. 
  4. Check data consistency after tests.  Quiesce your applications and run a consistency check to compare tables across masters. 
It is tempting to take shortcuts or slack off, so you'll need to find ways to improve your motivation.  If it helps, picture yourself explaining to the people you work for why your DBMS servers have conflicting data with broken replication, and the problem is getting worse because you cannot take applications offline to fix things.  It is a lot easier to ask for more time to test.  An even better approach is to hire great QA people and give them time to do the job right.

Summary

Before moving to a multi-master replication topology you should ask yourself whether the trouble is justified.  You can get many of the benefits of multi-master with system-of-record architectures with a lot less heartburn.  That said, an increasing number of applications do require full multi-master across multiple sites.  If you operate one of them, I hope this article is helpful in getting you deployed or improving what you already have.

Tungsten does a pretty good job of multi-master replication already, but I am optimistic we can make it much better.  There is a wealth of obvious features around conflict resolution, data repair, and up-front detection of problems that will make life better for Tungsten users and reduce our support load.  Plus I believe we can make it easier for developers to write applications that run on multi-master DBMS topologies.  You will see more about how we do this in future articles on this blog.




increase inodes in linux ext4 file system

inode

= data structure containing information about files.
= the inode number is an integer unique to the volume
= inodes point to blocks that make up a file and also contain the metadata of the file.

Warning: once the number is increased you can never reduce it
as new files are created, the file system consumes the additional disk space required to hold the inodes for the
additional files, there is no way for the storage system to release that disk space.

If you are keeping huge number of small files in your disks, this may one day cause running out of available inodes because of which even though you might have sufficient disk space, file system cannot create new files. Lets see how it works in my 1GB disk partition.

The parameter “-i” allows us to play with the number of inodes we can have in a partition. It is called “bytes-per-inode”. The bigger it is less number of inodes you will have. I have set a relatively big size “163840″ bytes per inode and the result is I have 6768 inodes. What this means indeed is I can’t create more than 6768 file.

In order to increase the number of inodes, format the partition again and specify the size.

#mkfs.ext3 -i 163840 /dev/sdb1

In order to check,use the command:
#df -i


The -i options specifies the size of the inode, not how many there are.
The -N option sets the number inodes

snapshots share inodes with live system files so snapshots shoud be deleted if present to free inodes

pcregrep

pcregrep 'April'  /var/log/messages

pcregrep 'April\s+(29|30|22)'  /var/log/messages

April + one or more spaces +29 or 30 or 22

pcregrep 'April\s+(29|30|22)'  /var/log/messages

setup KVM on centos 6 / 7


KVM requires a linux kernel module to support full virtualization. The linux module consists of three files:
1) kvm.ko,
2) kvm_intel.ko (for Intel processors),
3) kvm_amd.ko (for AMD processors).
the 2.6.20 kernel version (and higher) includes these kernel modules as part of the mainline kernel.

To disable SELinux on CentOS:
$ sudo -e /etc/selinux/config

SELINUX=permissive


modprobe is command used to add / remove module from linux kernel (check)
modprobe -l | grep kvm

kernel/arch/x86/kvm/kvm.ko
kernel/arch/x86/kvm/kvm-intel.ko
kernel/arch/x86/kvm/kvm-amd.ko

if kvm modules are properly loaded you will see following two sets of modules
lsmod | grep kvm

kvm_intel              54285  0
kvm                   333172  1 kvm_intel

OR

kvm_amd     35678
kvm         333172  kvm_amd

Load modules and its dependent modules if not loaded with modprobe command:
modprobe  kvm

yum groupinstall "Virtualization Tools" "Virtualization Platform"
yum install python-virtinst

OR

yum install kvm qemu-kvm python-virtinst libvirt libvirt-python virt-manager libguestfs-tools

yum install policycoreutils-python   //for selinux commands like semanage

yum install virt-viewer  //for viewing vms during install

//at client side install vnc with #yum install vnc -y

#chkconfig libvirtd on
The libvirtd program is the server side daemon component of the libvirt virtualization management system.
#service libvirtd start

check service status with:
service libvirtd status
or
virsh -c qemu:///system list

Sample setup

                     +-------------+
                     | CentOS/RHEL |             |-----|
     -->ISP router---+ Box Host w/ +--- eth0 -->-+ br0 +  Private IP
                     | KVM         |             |     |
                     +-------------+--- eth1 -->-+ br1 | Public IP
                                                 |-----|
                                                    |
                                                vm1-+---vm2----vm3---vm4
*** NOTE: each VMs will have two interface i.e. Private and Public *****

Where,
    eth0 - KVM servers' LAN interface.
    eth1 - KVM servers' WAN/Internet interface.
    br0 - KVM servers' bridge interface to give VM direct access to all the resources on the LAN.
    br1 - KVM servers' bridge interface to give VM direct access to all the resources on the WAN/Internet. Users can ssh into VMs or you can host HTTPD/SMTPD using this interface.
    obsd-vm1 (vm1) - OpenBSD VM name.
    rhel-vm1 (vm2) - RHEL VM name.

Install and configure a network bridge

All VMs will only have network access to host and other VMs on same physical server via private network. You need to crate a network bridge so that the VMs can access your LAN and possible the Internet/WAN from outside. Type the following yum command to install bridge-utils package:
# yum install bridge-utils

Setup a default gateway

Edit /etc/sysconfig/network as follows
# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=kvm-42.cyberciti.biz
## I am routing internet traffic via br1 ##
GATEWAYDEV=br1

Configure bridging

Update /etc/sysconfig/network-scripts/ifcfg-eth0 (private) as follows:
# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
ONBOOT=yes
HWADDR=00:30:48:C6:0A:D8
BRIDGE=br0

Update /etc/sysconfig/network-scripts/ifcfg-eth1 (public) as follows:
# cat /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth1
ONBOOT=yes
HWADDR=00:30:48:C6:0A:D9
BRIDGE=br1

Create/edit the /etc/sysconfig/network-scripts/ifcfg-br0 file to setup private/lan ip address for br0:
# cat /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
ONBOOT=yes
## setup LAN/VLAN ips as per your needs ##
IPADDR=10.10.29.66
NETMASK=255.255.255.192
DELAY=0


Create/edit the /etc/sysconfig/network-scripts/ifcfg-br1 file to setup public/wan/internet ip address for br1:
# cat /etc/sysconfig/network-scripts/ifcfg-br1
DEVICE=br1
TYPE=Bridge
BOOTPROTO=static
ONBOOT=yes
## setup INTERNET ips as per your needs ##
IPADDR=74.ww.xx.yy
NETMASK=255.255.255.248
GATEWAY=74.ww.xx.yy
DELAY=0


I need to route all lan traffic (subnet 10.0.0.0/8) via 10.10.29.65 gateway. Create/edit file /etc/sysconfig/network-scripts/route-br0 as follows:
# cat /etc/sysconfig/network-scripts/route-br0
10.0.0.0/8 via 10.10.29.65

#check the selinux context for newly created network config files(check the other files)
ls -lz /etc/sysconfig/network-scripts/route-br0

-rw-r--r--. root root system_u:object_r:net_conf_t:s0  route-br0

Warning: Restarting network service over the ssh session may result into total loss of the connectivity to the server. So make sure br0 and br1 configuration including routing set correctly.

cd /var/lib/libvirt/    #checkout selinux context
[root@v1 libvirt]# ls -lZ
drwx--x--x. root root system_u:object_r:virt_content_t:s0 boot
drwxr-xr-x. root root system_u:object_r:virt_var_lib_t:s0 dnsmasq
drwx--x--x. root root system_u:object_r:virt_var_lib_t:s0 filesystems
drwxr-xr-x. root root system_u:object_r:virt_image_t:s0 images
drwx------. root root system_u:object_r:virt_var_lib_t:s0 lxc
drwx------. root root system_u:object_r:virt_var_lib_t:s0 network
drwxr-x---. qemu qemu system_u:object_r:qemu_var_run_t:s0 qemu

[root@v1 libvirt]# ls -lZ boot/     #we have our centos 6.4 iso inside boot
-rw-r--r--. qemu qemu system_u:object_r:virt_content_t:s0 CentOS-6.4-x86_64-minimal.iso

Use below for restoring default SELinux contexts
# restorecon -Rv /etc/sysconfig/
If you are going to reboot the SELinux enabled server, make sure you type the following command:
# touch /.autorelabel
# reboot
####Now restart Network and verify br0/br1 settings
service network restart
brctl  show
ip address
ping youtube.com

###########CREATING VMS

cd /var/lib/libvirt/boot/
put your iso file there with proper selinux
do #chcon --reference  source   isofile

virt-install -n vm201 --description "demoserver centos6.4 64bit"  --ram=512 --vcpus=1 --cpu host  --cdrom /var/lib/libvirt/boot/CentOS-6.4-x86_64-minimal.iso  --network bridge:br0,model=virtio --network bridge:br1,model=virtio --graphics vnc  --disk path=/var/lib/libvirt/images/vm201.img,bus=virtio,size=10 --hvm

go to your REAL HOST MACHINE if you are using putty:-
In boot option edit boot machine and add below it:---->>>>

console=ttyS0,115200

install .................
guest centos 6.5 machine gets rebooted
now, you are on main Host machine now(No putty)

virsh console vm201

####Now set  ip address
[root@localhost network-scripts]# cat ifcfg-eth0
DEVICE=eth0
HWADDR=52:54:00:D2:CB:F0
TYPE=Ethernet
UUID=309c7798-762f-424a-a84f-d74036039a7e
ONBOOT=YES
NM_CONTROLLED=yes
BOOTPROTO=static
IPADDR=10.10.10.100
NETMASK=255.255.255.0
GATEWAY=10.10.10.2

[root@localhost network-scripts]# cat ifcfg-eth1
DEVICE=eth1
HWADDR=52:54:00:8E:CE:8C
TYPE=Ethernet
UUID=986d56c6-1aee-4fbe-bbf9-e12b55be520e
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=static
IPADDR=192.168.213.201
NETMASK=255.255.255.0
GATEWAY=192.168.213.2

#service network restart

You can access your GUEST vm with VNC

on your NON-kvm  linux laptop
do ssh portforwarding
ssh -L 5900:127.0.0.1:5900  root@KVM-Server-IP-Here
OR
ssh -L 5900:127.0.0.1:5900 -N -f -l root


hit tab and enter

console=ttyS0,115200