apache 2.4 tuning and Keepalive

https://servercheck.in/blog/3-small-tweaks-make-apache-fly

Note: There is a good discussion on Reddit about situations when KeepAlive may be helpful and may, in fact, help Apache (or your server in general) perform better, like if you have an AJAX-heavy site, or if you are serving many requests to mobile or international users. Additionally, if you use a reverse proxy like squid, Varnish, or Nginx in front of Apache, KeepAlive doesn't have the same cost in terms of memory and process usage.
KeepAlive does one simple thing: destroy Apache's ability to handle many concurrent requests. Well, that and speed up existing connections by allowing them to download all assets before closing a TCP connection between a browser and your server (see note above).
This feature was designed to help ensure a browser could load the HTML, some images, stylesheets, etc. from your server all within one connection. Before people started using CDNs like CloudFlare or Amazon S3 for static content, and when most people had internet connections with hundreds of milliseconds of latency, this setting was much more valuable. (It still could be, in some circumstances, for mobile clients on 3G or LTE networks, or if you have an AJAX-heavy site.)
However, for many websites today, either setting the KeepAliveTimeout to a lower value like 1-5 seconds or switching KeepAlive off altogether will be a much better option.
Real-world example: When I launched Server Check.in with this thread on Hacker News, the post made the HN front page, meaning I was getting upwards of 10-20 requests per second for an hour or so. I noticed quickly that the server's load was under 1.00, and nothing seemed awry, but trying to access https://servercheck.in/ was taking 30 seconds or longer!
Turning off KeepAlive allowed the server to serve more users more quickly, since I didn't have a bunch of httpd threads sitting connected to browsers that had already received all the content they needed. If I want to turn it back on at some point, I'll make sure to set it lower than the default of 30 seconds!
Caveat: Now, in my case, I have the MaxClients directive set to 45, because with Drupal, I've made sure I don't spawn more threads than my server's limited memory can handle (I'll get to the why's for this below). If you are serving only static/cached content, and don't need to have a bunch of memory-hogging httpd threads for a PHP application like Drupal, you may be able to live with KeepAlive (make sure the timeout is low, still!), and a much larger MaxClients setting.

MaxClients

Queuing requests may save your server from swapping.
This setting helps Apache fly when your server is getting hit hard, say by a post from Reddit, Hacker News, or some fast and furious marketing campaign.
MaxClients is pretty self-descriptive: it's a setting that tells Apache the maximum number of clients it should serve simultaneously. It's important that you choose a sane value for this setting to prevent any number of bad things from happening:
  • Set it too low and you might cause people to wait for Apache to respond to their request while your server is almost sitting idle, with plenty of RAM and CPU to spare.
  • Set it too high and watch your server die in a slow, painful death as Apache runs out of RAM and starts swapping to disk. And watch page response times go from milliseconds to seconds or even minutes.
There's a really simple way you can know exactly how high to set MaxClients:
(Total RAM - RAM used for Linux, MySQL, etc.) / Average httpd process size.
To get the average httpd process size, log into your server and run the following on the command line: ps aux | grep 'httpd' | awk '{print $6/1024 " MB";}'. This will output a list of process sizes. If you want to calculate the average on-the-fly, try the command ps aux | grep 'httpd' | awk '{print $6/1024;}' | awk '{avg += ($1 - avg) / NR;} END {print avg " MB";}'. It's best to run this a few different times throughout a normal day to see if there's any major fluctuation in process size.
Let's say your average process is 50 MB (fairly common if you're using PHP and a CMS like Wordpress or Drupal!). You have a VPS with 2 GB of RAM, and you have about .5 GB allocated to MySQL (you can find the full amount with the command ps aux | grep 'mysql' | awk '{print $6/1024 " MB";}'). Let's leave a little overhead for Linux and other bits on the server, say .4 GB:
(2000 MB - 900 MB) / 50 MB = 22
You should set the MaxClients directive to 22, maybe even a little lower to allow for more overhead when your server is getting hammered. Apache's default is usually > 200—this means if your server gets hit by a more than 22 people in a short period of time, it will slow to a crawl, since Apache will gobble up all the RAM!
Setting the MaxClients value lower will allow Apache to simply queue up further requests until it gets a free thread (remember, also, that if you have KeepAlive on, threads will be locked up for [KeepAliveTimeout] seconds!). This might seem like a bad thing... but it's a lot better doing this and serving queued requests quickly (since Apache is working from RAM and not swap space), than trying to serve a hundred requests at once and having massive slowdowns for everyone!
Real-world example: One site I work with had a page pick up tons of traffic over the course of a few hours, and the web server (a small 2 GB VPS running LAMP) was getting hammered by up to 100 separate requests per second. We had the MaxClients setting a bit too high, and the server immediately started swapping. It was hard even connecting to the server via SSH, and when I checked top, the server was using about 4 GB of swap (yikes!), and the CPU was spiking around 45 (normally around .2-.3). Once we set MaxClients to a sane amount and restarted Apache, the server was able to get most pages served in 2-3 seconds (instead of 2-3 minutes—ifever). Once traffic died down, we were serving pages in less than 1 second again.

AllowOverride

AllowOverride is basically Apache's way of allowing developers to be lazy. Instead of using a global configuration file and includes, Apache lets you stick an '.htaccess' file in any directory, anywhere, and every time anyone requests any page through Apache, Apache will recursively scan every directory from the site's root to apply rules in .htaccess files.
This is very convenient—especially in situations like shared hosting, where the hosting provider can't be bothered to include hundreds of extra configuration directives in the main httpd.conf file, or (for security purposes) allow everyone on the server to have their own configuration files included via httpd.conf!
However, if you are running only one or two websites on a server, or you generally have full control of the server, you can turn off this convenient feature and simply add the rules into httpd.conf or an include (to add an include, just use something like Include /home/user/public_html/.htaccess inside the VirtualHosts directive for your server, along with the rule AllowOverride None.
Real-world example: The impact of this change on server performance varies greatly, and depends mostly on how many directory-levels deep you have files that are served on a given page request. For most people, though, there may be a file in something like /home/user/public_html/sites/sitename/files/images/cached/large/thumbnail/image.jpg. In this case, Apache has to recurse through 10 levels of directories, parsing all found .htaccess files, just to serve this one image file. For one Drupal site, though, which is a VPS with a virtualized disk on a SAN, I've measured 7-10% faster individual page loads.
Caveat: Many CMSes like Wordpress and Drupal rely on .htaccess rules for certain functionality, like 'Clean URLs', www-to-non-www redirects, file upload protections, and static content caching. Make sure you include any relevant .htaccess files in your VirtualHosts directive if you set AllowOverrides to None. See more: How to make Apache faster for Drupal.
Also, the real-world speedup you'll get when using a server that has a dedicated, real hard drive or SSD will be much smaller than a server that has a slow drive or uses NAS/SAN storage.

Conclusion

These are just three of 'low-hanging fruit' performance-related settings buried in your Apache httpd.conf file; many others will have a big impact on your site's performance as well. With proper tuning, and an eye towards memory usage, you can make Apache as scalable, fast and lightweight as almost any web server.


The problem

By default apache2 is configured to support 150 concurrent connections. This forces all parallel requests beyond that limit to wait. Especially if, for example, active sync clients maintain a permanent connection for push events to arrive.
To calculate the number of concurrent sessions each of your apache nodes must be able to provide, consider the total number of concurrent sessions in your OX cluster and divide it by the number of apache nodes involved in serving those sessions. Then add some room for statistical fluctuations.

The solution

This is an example configuration to provide 8000 concurrent connections. Please ensure that your apache is using the mpm_worker module. This allows us to serve lots of concurrent connections by using less RAM than with mpm_prefork as we are going to start much less processes.
<IfModule mpm_worker_module>
    ServerLimit             250
    StartServers             10
    MinSpareThreads          75
    MaxSpareThreads         250 
    ThreadLimit              64
    ThreadsPerChild          32
    MaxClients             8000
    MaxRequestsPerChild   10000
</IfModule>

Short explanation of the parameters:

ServerLimitDeclares the maximum number of running apache processes. If you change this value you have to restart the daemon.
StartServersThe number of processes to start initially when starting the apache daemon.
MinSpareThreads/MaxSpareThreadsThis regulates how many threads may stay idle without being killed. Apache regulates this on its own very well with default values.
ThreadsPerChildHow many threads can be created per process. Can be changed during a reload.
ThreadLimitThreadsPerChild can be configured as high as this value during runtime. If you change this value you have to restart the daemon.
MaxClientsThis declares how many concurrent connections we provide. Devided by ThreadsPerChild you get the suitable ServerLimit value. May be less than ServerLimit * ThreadsPerChild to reserve some resources that can be engaged during runtime with increasing MaxClients and reloading the configuration.
MaxRequestsPerChildDefines the number of Connections that a process can handle during its lifetime (keep-alives are counted once). After that it will be killed. This can be used to prevent possible apache memory leaks. If set to 0 the lifetime is infinite.

Haproxy 1.5 HTTPS termination and Load balancing

Create certificate files in /etc/haproxy

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/haproxy/apache.pem -out /etc/haproxy/apache.crt

 openssl req  $@  -new  -x509  -days  365  -nodes  -out  apache.pem -keyout  apache.pem

#here $@  =  '@' Expands to the positional parameters, starting from one.  When the expansion occurs within double quotes, each parameter expands to  a  separate  word.   That  is, "$@" is equivalent to "$1" "$2" ...

#chmod 600 /etc/apache2/apache.pem

cat   apache.pem   apache.key  >   apache.final.pem


#This is self signed

configuration file /etc/haproxy/haproxy.cfg

root@haserva:~# cat /etc/haproxy/haproxy.cfg
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
maxconn 256

# Default SSL material locations
ca-base /etc/ssl/certs
crt-base /etc/ssl/private

# Default ciphers to use on SSL-enabled listening sockets.
# For more information, see ciphers(1SSL).
ssl-default-bind-ciphers kEECDH+aRSA+AES:kRSA+AES:+AES256:RC4-SHA:!kEDH:!LOW:!EXP:!MD5:!aNULL:!eNULL
        ssl-default-bind-options no-sslv3

defaults
log global
mode http
option httplog
option dontlognull
option  forwardfor #enables the insertion of the X-Forwarded-For header to requests sent to servers.
        option redispatch
option http-server-close #reduces latency between HAProxy and your users by closing connections but maintaining keep-alives,Enable or disable HTTP connection closing on the server side,enables HTTP connection-close mode on the server side while keeping the ability to support HTTP keep-alive and pipelining on the client side.  This provides the lowest latency on the client side (slow network) and the fastest session reuse on the server side to save server resources
option tcp-smart-accept
option tcp-smart-connect
#option dontlog-normal
timeout connect 5000#amount of time HAProxy should spend trying to connect to a host so if a host died, HAProxy would try to connect to the same host for 30 seconds option specifies the maximum time to wait for a connection attempt to a VPS to succeed.
        timeout client  50000
        timeout server  50000
timeout http-keep-alive 10s
timeout check 5s
retries 3
compression algo gzip
compression type text/html text/html;charset=utf-8 text/plain text/css text/javascript application/x-javascript application/javascript application/ecmascript application/rss+xml application/atomsvc+xml application/atom+xml application/atom+xml;type=entry application/atom+xml;type=feed application/cmisquery+xml application/cmisallowableactions+xml application/cmisatom+xml application/cmistree+xml application/cmisacl+xml application/msword application/vnd.ms-excel application/vnd.ms-powerpoint
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
#frontend defn
frontend www-http
bind *:80
reqadd X-Forwarded-Proto:\ http
default_backend apache
frontend www-https
bind *:443 ssl crt /etc/haproxy/apache.final.pem
reqadd X-Forwarded-Proto:\ https
default_backend apache

#backend definitions
backend apache
redirect scheme https if !{ ssl_fc }
mode http
###statistics page
stats enable
stats auth demo:p@ssw0rd
        stats hide-version
stats uri /monitor
stats refresh 2s
###statistics page end

# balance source
# cookie SRV_ID prefix
# server web1 192.168.163.40:80 check cookie web1
# server web2 192.168.163.41:80 check cookie web2
balance roundrobin
server web1 192.168.163.40:80 check
server web2 192.168.163.41:80 check

central php session directory
..............................................
 vim /etc/php5/apache2/php.ini

session.save_path = "/gmount/phpsession/"       #here gmount/phpsession is new directory to store session by default phpsession is /var/lib/php5


Now copy ownership and file permission

chmod --reference=/var/lib/php5/ /gmount/phpsession/
chown root:root /gmount/phpsession



MariaDB Galera Cluster Monitoring

http://galeracluster.com/documentation-webpages/monitoringthecluster.html#monitoring-cluster

To check cluster integrity, for each node complete the following steps:
  1. Check that the node is part of the cluster:
Each node in the cluster should provide the same value. If you find a node that carries a different cluster state UUID, that node is not connected to the cluster.
At Node 1

MariaDB [(none)]> show status like 'wsrep_cluster_state_uuid';
MariaDB [(none)]> show status like 'wsrep_cluster_state_uuid';
+--------------------------+--------------------------------------+
| Variable_name            | Value                                |
+--------------------------+--------------------------------------+
| wsrep_cluster_state_uuid | e48cd2c2-ab6e-11e4-a8af-268a757dde7a |
+--------------------------+--------------------------------------+

1 row in set (0.00 sec)

Node 2 and Node 3 should return same UUID


  1. Check that the node belongs to the same component:
    show status like 'wsrep_cluster_conf_id';
    +-----------------------+-------+
    | Variable_name         | Value |
    +-----------------------+-------+
    | wsrep_cluster_conf_id | 4     |
    +-----------------------+-------+
    1 row in set (0.00 sec)
    
    Each node in the cluster should provide the same value. If you find a node that carries a different value, this indicates the cluster is partitioned. Once network connectivity is restored, the value will align itself with the others.
On the first node check cluster size:-


 > show status like 'wsrep_cluster_size';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 3     |
+--------------------+-------+

If the value equals the expected number of nodes in the cluster, all nodes are connected to the cluster.
Note

You only need to check the cluster size on one node.
Check primary cluster status
show status like 'wsrep_cluster_status';
+----------------------+---------+
| Variable_name        | Value   |
+----------------------+---------+
| wsrep_cluster_status | Primary |

The node should return a value of Primary. Other values indicate that the node is part of a nonoperational component. This can occur in cases of multiple membership changes and a loss of quorum or in the case of a split-brain condition.

  1. Check the node status:
    SHOW VARIABLES LIKE 'wsrep_ready';
    
    If the value is TRUE, the node can accept SQL load.
  2. If the wsrep_ready value is FALSE, check that the node is connected:
    SHOW VARIABLES LIKE 'wsrep_connected';
    
    If the value is OFF, the node has not connected to any of the cluster components. This may relate to misconfiguration. For instance, if the node uses invalid values forwsrep_cluster_address or wsrep_cluster_name.
    Check the error log for proper diagnostics.
  3. If the node is connected, but still cannot accept SQL load, check that the node is part of the Primary Component:
    SHOW VARIABLES LIKE 'wsrep_local_state_comment';
    
    If the the state comment is Joining, Waiting for SST, or Joined, the node is syncing with the cluster.

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