Commit 022595de authored by Dave Johnson's avatar Dave Johnson Committed by GitHub
Browse files

Merge pull request #130 from cuongnv23/tomcat_failover_memcached

Initial commit for playbook tomcat-mecached-failover
parents b5e0415c c455cf4e
Copyright (c) 2015 Cuong Nguyen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Tomcat failover with Memcached + Memcached Session Manager + Nginx (load blancer)
- Tested on Ansible 1.9.3 for Debian
- Expects hosts: Centos 6.x
This playbook deploys a failover solution for clustered Tomcat using Nginx as load balancer and Memcached + MSM as session manager.
- Nginx: balances the requests by round robin.
- Memcached: stores `sessionid` of tomcat.
- MSM: manages tomcat session.
For more detail about session management, see https://github.com/magro/memcached-session-manager
This playbook also deploys a demo web app (https://github.com/magro/msm-sample-webapp) to test the session management.
## Initial setup of inventory file
```
[lb_servers]
lbserver
[backend_servers]
tomcat_server_1
tomcat_server_2
[memcached_servers]
cached_server1
cached_server2
```
Edit inventory file `hosts` to suit your requirements and run playbook:
```
$ ansible-playbook -i host site.yml
```
When finished, open web browser and access to http://nginx_ip/ to start testing.
## Ideas and improvements
- Setup SSL for load balancer.
- HA load balancer.
- Hardening iptables rules.
Pull requests are welcome.
## License
This work is licensed under MIT license.
# Java variables
# Nginx variables
nginx_http_port: 80
# nginx_https_port: 443
# Tomcat variables
tomcat_http_port: 8080
tomcat_https_port: 8443
# Memcached variables
memcached_port: 11211
[lb_servers]
lbserver
[backend_servers]
tomcat_server_1
tomcat_server_2
[memcached_servers]
cached_server1
cached_server2
---
- name: restart iptables
service: name=iptables state=restarted
---
- name: Install libselinux-python
yum: name=libselinux-python state=present
- name: Install GPG key for EPEL
get_url: url=https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-6 dest=/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
- name: Install EPEL repository
yum: name=https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm state=present
- name: Setup Iptables rules
template: src=iptables.j2 dest=/etc/sysconfig/iptables
notify: restart iptables
# {{ ansible_managed }}
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
{% if (inventory_hostname in groups['lb_servers']) %}
-A INPUT -p tcp --dport {{ nginx_http_port }} -j ACCEPT
{% endif %}
{% if inventory_hostname in groups['backend_servers'] %}
-A INPUT -p tcp --dport {{ tomcat_http_port }} -j ACCEPT
-A INPUT -p tcp --dport {{ tomcat_https_port }} -j ACCEPT
{% endif %}
{% if inventory_hostname in groups['memcached_servers'] %}
-A INPUT -p tcp --dport {{ memcached_port }} -j ACCEPT
{% endif %}
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
COMMIT
---
- name: restart nginx
service: name=nginx state=restarted
---
- name: Install nginx
yum: name=nginx state=present
- name: Deliver main configuration file
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
- name: Copy configuration file to nginx/sites-avaiable
template: src=default.conf.j2 dest=/etc/nginx/conf.d/default.conf
notify: restart nginx
- name: Make sure nginx start with boot
service: name=nginx state=started enabled=yes
upstream tomcat {
{% for host in groups['backend_servers'] %}
server {{ host }}:{{ tomcat_http_port }};
{% endfor %}
}
server {
listen 80 default_server;
server_name {{ inventory_hostname }};
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://tomcat;
}
}
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
#error_log /var/log/nginx/error.log info;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# Load config files from the /etc/nginx/conf.d directory
# The default server is in conf.d/default.conf
include /etc/nginx/conf.d/*.conf;
}
---
- name: restart memcached
service: name=memcached state=restarted
---
- name: Install memcached
yum: name=memcached state=present
- name: Deliver configuration file
template: src=memcached.conf.j2 dest=/etc/sysconfig/memcached backup=yes
notify: restart memcached
- name: Deliver init script
template: src=init.sh.j2 dest=/etc/init.d/memcached mode=0755
notify: restart memcached
- name: Start memcached service
service: name=memcached state=started enabled=yes
#! /bin/sh
#
# chkconfig: - 55 45
# description: The memcached daemon is a network memory cache service.
# processname: memcached
# config: /etc/sysconfig/memcached
# pidfile: /var/run/memcached/memcached.pid
# Standard LSB functions
#. /lib/lsb/init-functions
# Source function library.
. /etc/init.d/functions
PORT=11211
USER=memcached
MAXCONN=1024
CACHESIZE=64
OPTIONS=""
if [ -f /etc/sysconfig/memcached ];then
. /etc/sysconfig/memcached
fi
# Check that networking is up.
. /etc/sysconfig/network
if [ "$NETWORKING" = "no" ]
then
exit 0
fi
RETVAL=0
prog="memcached"
pidfile=${PIDFILE-/var/run/memcached/memcached.pid}
lockfile=${LOCKFILE-/var/lock/subsys/memcached}
start () {
echo -n $"Starting $prog: "
# Ensure that /var/run/memcached has proper permissions
if [ "`stat -c %U /var/run/memcached`" != "$USER" ]; then
chown $USER /var/run/memcached
fi
# daemon --pidfile ${pidfile} memcached -d -p $PORT -u $USER -m $CACHESIZE -c $MAXCONN -P ${pidfile} $OPTIONS
daemon --pidfile ${pidfile} memcached -d -p $PORT -u $USER -m $CACHESIZE -c $MAXCONN -P ${pidfile} $OPTIONS -vv > $LOGFILE 2>&1
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch ${lockfile}
}
stop () {
echo -n $"Stopping $prog: "
killproc -p ${pidfile} /usr/bin/memcached
RETVAL=$?
echo
if [ $RETVAL -eq 0 ] ; then
rm -f ${lockfile} ${pidfile}
fi
}
restart () {
stop
start
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status -p ${pidfile} memcached
RETVAL=$?
;;
restart|reload|force-reload)
restart
;;
condrestart|try-restart)
[ -f ${lockfile} ] && restart || :
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|try-restart}"
RETVAL=2
;;
esac
exit $RETVAL
# Running on Port 11211
PORT="{{ memcached_port }}"
# Start as memcached daemon
USER="memcached"
# Set max simultaneous connections to 1024
MAXCONN="1024"
# Set log file
LOGFILE="/var/log/memcached.log"
# Set Memory size to half of all memory
CACHESIZE="{{ ansible_memtotal_mb / 2 }}"
#Set server IP address
OPTIONS="-l {{ ansible_default_ipv4['address'] }}"
---
- name: restart tomcat
service: name=tomcat state=restarted
---
- name: Install OpenJDK
yum: name=java-1.7.0-openjdk state=present
- name: Install Tomcat
yum: name=tomcat state=present
- name: Deliver configuration files for tomcat
template: src={{ item.src }} dest={{ item.dest }} backup=yes
with_items:
- { src: 'default.j2', dest: '/etc/tomcat/default' }
- { src: 'server.xml.j2', dest: '/etc/tomcat/server.xml' }
- { src: 'context.xml.j2', dest: '/etc/tomcat/context.xml' }
notify: restart tomcat
- name: Deliver libraries support memcached
get_url: url="{{ item }}" dest=/usr/share/tomcat/lib/
with_items:
- http://repo1.maven.org/maven2/de/javakaffee/msm/memcached-session-manager/1.8.0/memcached-session-manager-1.8.0.jar
- http://repo1.maven.org/maven2/de/javakaffee/msm/memcached-session-manager-tc7/1.8.0/memcached-session-manager-tc7-1.8.0.jar
- https://spymemcached.googlecode.com/files/spymemcached-2.10.2.jar
- name: Deploy sample app
copy: src=msm-sample-webapp-1.0-SNAPSHOT.war dest=/var/lib/tomcat/webapps/ROOT.war owner=tomcat group=tomcat
- name: Start tomcat service
service: name=tomcat state=started enabled=yes
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
memcachedNodes="{% for host in groups['memcached_servers'] %}n{{ loop.index }}:{{ host }}:{{ memcached_port }}{% if not loop.last %},{% endif %}{% endfor %}"
sticky="false"
sessionBackupAsync="false"
lockingMode="none"
requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
/>
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
# Service-specific configuration file for tomcat. This will be sourced by
# the SysV init script after the global configuration file
# /etc/tomcat/tomcat.conf, thus allowing values to be overridden in
# a per-service manner.
#
# NEVER change the init script itself. To change values for all services make
# your changes in /etc/tomcat/tomcat.conf
#
# To change values for a specific service make your edits here.
# To create a new service create a link from /etc/init.d/<your new service> to
# /etc/init.d/tomcat (do not copy the init script) and make a copy of the
# /etc/sysconfig/tomcat file to /etc/sysconfig/<your new service> and change
# the property values so the two services won't conflict. Register the new
# service in the system as usual (see chkconfig and similars).
#
# Where your java installation lives
#JAVA_HOME="/usr/lib/jvm/java"
# Where your tomcat installation lives
#CATALINA_BASE="/usr/share/tomcat"
#CATALINA_HOME="/usr/share/tomcat"
#JASPER_HOME="/usr/share/tomcat"
#CATALINA_TMPDIR="/var/cache/tomcat/temp"
# You can pass some parameters to java here if you wish to
#JAVA_OPTS="-Xminf0.1 -Xmaxf0.3"
# Use JAVA_OPTS to set java.library.path for libtcnative.so
#JAVA_OPTS="-Djava.library.path=/usr/lib"
# What user should run tomcat
#TOMCAT_USER="tomcat"
# You can change your tomcat locale here
#LANG="en_US"
# Run tomcat under the Java Security Manager
#SECURITY_MANAGER="false"
# Time to wait in seconds, before killing process
#SHUTDOWN_WAIT="30"
# Whether to annoy the user with "attempting to shut down" messages or not
#SHUTDOWN_VERBOSE="false"
# Set the TOMCAT_PID location
#CATALINA_PID="/var/run/tomcat.pid"
# Connector port is 8080 for this tomcat instance
#CONNECTOR_PORT="8080"
# If you wish to further customize your tomcat environment,
# put your own definitions here
# (i.e. LD_LIBRARY_PATH for some jdbc drivers)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment