Wednesday, March 13, 2013

Tomcat Connectors


Connector elements are Tomcat's links to the outside world, allowing Catalina to receive requests, pass them to the correct web application, and send back the results through the Connector as dynamically generated content.

Each Connector element represents a port that Tomcat will listen to for requests.

A Connector performs following jobs

  1. Routing user requests to appropriate Services
  2. To link Tomcat with other supporting web technologies, such as Apache webserver.

The Connector element does only one job - listening for requests, passing them on to an Engine, and returning the results to its specified port.  

On its own, the Connector can't function - the only information this element contains is a port to listen on and talk to, and some attributes that tell it exactly how to listen and talk. 

Connector elements are nested within hierarchies of Services and Engines, to achieve the desired functionality.

This is how a Tomcat server configuration looks like in server.xml file

<Server>
    <Service name="Catalina">
           <Connector port="8080"/>
           <Connector port="8443"/>
        <Engine name="Catalina">
             <Host name="yourhostname">
                    <Context path="/webapp1"/>
                    <Context path="/webapp2"/
             </Host>
        </Engine>
    </Service>
</Server>

Using the above arrangement, both Connectors(one listening on port 8080 and other on port 8443) will pass all requests to the same Engine, which will in turn pass all these requests to both of its contained web applications - webapp1 and webapp2.  This means that each request(either to port 8080 or 8443) will potentially generate two responses, one from each application(webapp1 and webapp2).

<Server>
  <Service name="Catalina">
    <Connector port="8080"/>
       <Engine>
          <Host name="yourhostname">
               <Context path="/webapp1"/>
          </Host>
       </Engine>
  </Service>

  <Service name="Catalina8443">
      <Connector port="8443"/>
         <Engine>
            <Host name="yourhostname">
                <Context path="/webapp2"/>
            </Host>
         </Engine>
  </Service>
</Server>


There are two Connector elements here, listening for connections on ports 8080 and 8443.  It is important to note that an OS will only allow one connector on each port, so every connector you define will require its own unique port.


Tomcat has two types of Connectors

  1. HTTP
  2. AJP

HTTP Connectors

Tomcat comes with a preconfigured HTTP connector that can handle incoming HTTP requests from a browser, because of this Tomcat can act as a standalone Web server, it can handle both HTTP and HTTPS requests.

HTTP connectors are Java classes that implement the HTTP protocol. By default, the HTTP Connector listens on port 8080.

There are a number of HTTP Connectors available

1) JIO(java.io) - Java based HTTP/1.1(Coyote) Connector :
     This is Tomcat’s default connector implementation. It is a pure Java TCP sockets server implementation that uses the java.io core Java network classes. It is a fully blocking implementation of both HTTP and AJP. Being written in pure Java, it is binary portable to all operating systems that fully support Java.

<!-- The stock HTTP JIO connector. -->
<Connector port="8080" protocol="HTTP/1.1"
    maxThreads="150" connectionTimeout="20000"
    redirectPort="8443" />


2) NIO(java.nio) - 
     This connector, written in Java like JIO, uses the java.nio core Java network classes that offer nonblocking TCP socket features. The main goal of this Connector design is to offer Tomcat administrators a Connector implementation that performs better than the JIO Connector by using fewer threads by implementing parts of the Connector in a nonblocking fashion. The fact that the JIO Connector blocks on reads and writes means that if the administrator configures it to handle 400 concurrent connections, the JIO Connector must spawn 400 Java threads. The NIO Connector, on the other hand, needs only one thread to parse the requests on many connections, but then each request that gets routed to a servlet must run in its own thread(a limitation mandated by the Java Servlet Specification). Since part of the request handling is done in nonblocking Java code, the time it takes to handle that part of the request is time that a Java thread does not need to be in use, which means a smaller threadpool can be usedto handle the same number of concurrent requests. A smaller threadpool usually means lower CPU utilization.

<!-- HTTP NIO connector. -->
<Connector port="8080"
   maxThreads="150" connectionTimeout="20000"
   redirectPort="8443"
   protocol="org.apache.coyote.http11.Http11NioProtocol"/>

3) APR (Apache Portable Runtime) -
    APR works well in Windows and Linux environment, it is written using APR and compiled to native code for optimized platform specific performance. It is not a complete Connector, it actually makes use of the standard Java-based connector for most of its operations. 

<!-- The HTTP APR connector. -->
<Connector port="8080"
      protocol="org.apache.coyote.http11.Http11AprProtocol"
      enableLookups="false" redirectPort="8443"
      connectionTimeout="20000"/>

AJP Connectors


For running Tomcat behind Apache(using Apache as a proxy server), AJP connectors are needed.

AJP Connectors work in the same way as HTTP Connectors, but they use the AJP protocol in place of HTTP.  Apache JServ Protocol, or AJP, is an optimized binary version of HTTP that is typically used to allow Tomcat to communicate with an Apache web server. 

The AJP protocol is a TCP packet-based binary protocol with the goal of relaying the essentials of HTTP requests to another server software instance significantly faster than could be done with HTTP itself. The premise is that HTTP is very plain-text oriented, and thus requires slower, more complex parsers on the server side of the connection, and that if we instead implement a binary protocol that relays the already-parsed text strings of the requests, the server can respond significantly faster, and the network communications overhead can be minimized.

mod_jk :
   This is an Apache httpd module that implements the client end of the AJP protocol (Tomcat’s AJP Connectors implement the server side of the protocol).

mod_proxy_ajp :
         This is mod_proxy’s AJP protocol connector support module. It connects with Tomcat via TCP to Tomcat’s AJP server port, sends requests through to Tomcat, waits for Tomcat’s responses, and then Apache httpd forwards the responses to the web client(s). The requests go through Apache httpd to Tomcat and back,and the protocol used between Apache httpd and Tomcat is the AJP protocol, just as it is with mod_jk. This connector became part of Apache httpd itself as of httpd version 2.2 and is already built into the httpd that comes with most operating systems (or it is prebuilt as a loadable httpd module). No extra compilation or installation is usually necessary to use it — just configuration of Apache httpd. Also, this module is a derivative of mod_jk, so mod_proxy_ajp’s code and features are very similar to those of mod_jk.

For Apache to serve as proxy for Tomcat via AJP, using mod_proxy module of Apache, in Apache configuration file, set the following

ProxyPass               /   ajp://127.0.0.1:8009/
ProxyPassReverse  /   ajp://127.0.0.1:8009/

mod_proxy_http
      This is mod_proxy’s HTTP protocol connector support module. Like mod_proxy_ajp, it connects with Tomcat via TCP, but this time it connects to Tomcat’s HTTP (web) server port. A simple way to think about how it works: the web client makes a request to Apache httpd’s web server, and then httpd makes that same request on Tomcat’s web server, Tomcat responds, and httpd forwards the response to the web client. All communication between Apache httpd and Tomcat is done via HTTP when using this module. This connector module is also part of Apache httpd, and it usually comes built into the httpd binaries found on most operating systems. It has been part of Apache httpd for a very long time, so it is available to you regardless of which version of Apache httpd we run.

For Apache to serve as proxy for Tomcat via HTTP, using mod_proxy module of Apache, in Apache configuration file, set the following

ProxyPass               /   http://127.0.0.1:8080/
ProxyPassReverse  /    http://127.0.0.1:8080/


Forward and Reverse Proxy using Apache


Forward Proxy 

A proxy server sitting in between client and origin server, acts as forward proxy, by sending HTTP requests on the client's behalf to the origin servers. The proxy protects the internal network by hiding the actual client's IP address and by using it's own instead. The client sends a request to the proxy naming the origin server as the target and the proxy then requests the content from the origin server and returns it to the client. The client must be specially configured to use the forward proxy to access other sites.

1) A good use of forward proxy is that it can be used for caching(mod_cache). The client's requests are served from cache provided by forward proxy server rather than requesting from the origin servers.

2) Another use of forward proxy is in filtering proxied content before passing them to the client or for restricting clients from accessing certain hosts/domains.

How to enable forward proxy in Apache?

The forward proxy is activated using the ProxyRequests directive.

Since any arbitrary client can use the forward proxy server, we need to secure the forward proxy server by allowing only authorized clients to use it.

From Apache 2.0, this can be done as follows. In httpd.conf file, add/uncomment the following lines

LoadModule proxy_module  modules/mod_proxy.so

<IfModule mod_proxy.c>
    ProxyRequests On

    <Proxy *>
    Order deny,allow
    Deny from all
    Allow from 192.168.1
    </Proxy>
</IfModule>

How to set up caching server using Apache?

Forward proxy should be enabled to set the server as caching one.

From Apache 2.0, the proxying and caching functionalities have been split between the modules mod_proxy and mod_cache

After activating forward proxy with "ProxyRequests On", the same can be configured as caching server by adding the following lines in Apache configuration file 

CacheRoot "/var/spool/httpd/cache/"
CacheSize 5
CacheGcInterval 4
CacheMaxExpire 24
CacheLastModifiedFactor 0.1
CacheDefaultExpire 1
NoCache anonexp.blogspot.com

CacheRoot - Specifies the name of the directory that contains the cache.
CacheSize - Specifies the disk space required for the cache in KB
CacheGcInterval - Specifies the interval(in hours) to wait before checking if the disk space used by cache is greater than set by the CacheSize. In case if exceeding, unused objects are cache are cleaned out.
CacheMaxExpire - Specifies the maximum number of hours for which cached objects will be retained.
CacheLastModifiedFactor - It defines a value that will be used to calculate whether an item in the cache should be expired if the object hasn't explicitly been marked with an expiration date.
CacheDefaultExpire - Specifies the number of hours after which an object will be expired if no specific data is supplied about the expiration date or period from the original server.
NoCache - Specifies a list of words, hosts seperated by spaces that will not be cached.

How to use forward proxy for filtering?

Using  ProxyBlock directive, clients can be restricted from accessing specifies sites or domains.

ProxyBlock  www.xyz.com   # Blocks a specific host
ProxyBlock  xyz.com       # Blocks a specific domain
ProxyBlock  xyz           # Block any host or domain with string xyz in them

Reverse Proxy

A reverse proxy proxies on behalf of a backend server and not on behalf of outside client's request. Reverse proxy acts as a gateway to servers behind it.

Apache is activated as a reverse proxy using the ProxyPass directive or the flag to the RewriteRule directive. It is not necessary to turn ProxyRequests on in order to configure a reverse proxy.

ProxyPass directive is used to convert a URL into another URL

ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass               /    http://xyz.com/foo
ProxyPassReverse  /     http://xyz.com/foo

Selecting the Right Database Engine for MySQL


Choosing the right storage engine for MySQL is based on the following criteria

  1. Transactions and Concurrency
  2. Backups
  3. Special Features


Transactions and Concurrency

1) If the application requires high transactions and high read/write concurrency, then InnoDB is the most suitable one. A good example of high transactions is Order processing applications, something like, Online Stock quotes.

2) If the applications requires high transactions but moderate read/write concurrency, then either BDB or InnoDB shall work fine.

3) If the application doesn't require transactions and  primarily issues SELECT or INSERT/UPDATE queries, MyISAM is a good choice. Many web applications fall in this category. Good examples are student database, jobs, acutions, realestate postings - there are more reads than writes to these applications.

Backups

Based on the frequency of backups, the storage engine selection can vary.

Special Features

Not all storage engines may provide a quick answer to a query like the following

select count(*) from itable;

MyISAM is the answer for this type of fast row counts. Innodb must count up all the rows actually, but the MyISAM  storage engine always knows the exact row count of a table without needing to do any work.

If the application requires referential integerity with foreign keys, then InnoDB is the best.

For full text-search capabilities, MyISAM is the only answer.


Monday, March 4, 2013

Why dedicated IP address is needed for SSL host?


SSL is part of application layer and is a seperate layer which sits inbetween TCP and HTTP in TCP/IP protocol stack(it encapsulates HTTP). If SSL needs to be used with HTTP, then  the communication should occur over a port other than the clear channel standard port, 80, so that it doesn't affect other clients who connect to the HTTP server on clear channel port(80). So port 80 is reserved for HTTP and port 443 is reserved for SSL over HTTP.

When a browser requests to access a secure site, first a SSL session should be setup with the server before HTTP session can begin. So when using HTTPS the SSL/TLS handshake happens before the server sees any HTTP headers. 

The hostname requested by browser is resolved into an IP address(IP address of the WebServer on which the host is running) by DNS. Before the HTTP session can begin, the path between server and client(browser) should be encrypted. So with the IP address of the hostname(server) provided by the nameserver, an SSL session need to be setup between server and client. The server receives an SSL request on IP address X and port Y (usually 443). Since the SSL request does not contain any Host: field, the server has no way to decide which SSL virtual host to use. Usually, it will just use the first one it finds, which matches the port and IP address specified. 

Hence, it is NOT possible to have name-based SSL virtual hosts i.e. Name-based hosting does not support SSL virtual hosts.

Sunday, March 3, 2013

How to run Tomcat on different port


By default, Tomcat listens on port 8080.

Tomcat configuration file is $CATALINA_HOME/conf/server.xml

To use a different port number, edit the port attribute value of Connector port in $CATALINA_HOME/conf/server.xml:

<!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />


How to find the $CATALINA_HOME directory?

# ps -ef | grep java
tomcat      1437       1  0 07:04 ?        00:00:07 /usr/java/jdk1.7.0_09/bin/java -Djava.util.logging.config.file=/opt/apache-tomcat-7.0.32/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/opt/apache-tomcat-7.0.32/endorsed -classpath /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar -Dcatalina.base=/opt/apache-tomcat-7.0.32 -Dcatalina.home=/opt/apache-tomcat-7.0.32 -Djava.io.tmpdir=/opt/apache-tomcat-7.0.32/temp org.apache.catalina.startup.Bootstrap start

catalina.home=/opt/apache-tomcat-7.0.32 gives the $CATALINA_HOME

$CATALINA_HOME/conf/server.xml = /opt/apache-tomcat-7.0.32/conf/server.xml

Change the port number for Tomcat

Change the port number to 9080 by editing "Connector port" value in $CATALINA_HOME/conf/server.xml, as follows

<Connector port="9080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />


# service tomcat stop
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr/java/jdk1.7.0_09
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

# service tomcat start
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr/java/jdk1.7.0_09
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

Verify if the port number has changed after restarting tomcat

# pgrep java
2667

# netstat -anp | grep java
tcp        0      0 :::8009                     :::*                        LISTEN      2667/java
tcp        0      0 :::9080                     :::*                        LISTEN      2667/java
unix  2      [ ]         STREAM     CONNECTED     22042  2667/java

Note : 8009 is the port number used by mod_jk module to connect Apache to Tomcat

# telnet localhost 9080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

# nc -v -z localhost 9080
Connection to localhost 9080 port [tcp/glrpc] succeeded! 

Tomcat Installation in CentOS


Tomcat is a Java servlet container and web server from the Apache Software Foundation. Tomcat is written in Java, which prompts the need to have  Java runtime installed before we can build or test it.

There are two ways to install tomcat on CentOS
  • Using the package manager yum
  • Downloading the latest Apache multiplatform binary release
Installing Tomcat Using yum

1) Prepare the repository
yum install yum-priorities

2) Install Java
yum -y install java

3) Search for tomcat packages to be installed
yum search tomcat6
N/S Matched: tomcat6 
tomcat6.noarch : Apache Servlet/JSP Engine, RI for Servlet 2.5/JSP 2.1 API
tomcat6-admin-webapps.noarch : The host-manager and manager web applications for
                             : Apache Tomcat
tomcat6-docs-webapp.noarch : The docs web application for Apache Tomcat
tomcat6-el-2.1-api.noarch : Expression Language v1.0 API
tomcat6-javadoc.noarch : Javadoc generated documentation for Apache Tomcat
tomcat6-jsp-2.1-api.noarch : Apache Tomcat JSP API implementation classes
tomcat6-lib.noarch : Libraries needed to run the Tomcat Web container
tomcat6-log4j.noarch : Log4J support for Apache Tomcat
tomcat6-servlet-2.5-api.noarch : Apache Tomcat Servlet API implementation classes
tomcat6-webapps.noarch : The ROOT and examples web applications for Apache Tomcat

4) Install tomcat - We shall just install  the following packages - tomcat6, tomcat6-webapps, tomcat6-admin-webapps

yum -y install tomcat6 tomcat6-webapps tomcat6-admin-webapps

5) Start tomcat6

service tomcat6 status
tomcat6 is stopped                                         [  OK  ]

# service tomcat6 start
Starting tomcat6:                                          [  OK  ]

# service tomcat6 status
tomcat6 (pid 7891) is running...                           [  OK  ]

Verify if tomcat is listening on port 8080
# netstat -nlp | grep 8080
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      7891/java


File Structure of tomcat6 when installed using yum


The Red Hat file structure is different than the default file structure Tomcat 6 has when installing from source. Here is the file structure that is used when installing using yum method:

The below command shall provide an idea of file structure for tomcat
# rpm -ql tomcat6

Some major files are as follows
/etc/tomcat6 (this is where the main tomcat config files reside)
/usr/share/doc/usr/share/tomcat6
/usr/share/tomcat6/bin
/usr/share/tomcat6/conf
/usr/share/tomcat6/lib
/usr/share/tomcat6/logs
/usr/share/tomcat6/temp
/usr/share/tomcat6/webapps
/usr/share/tomcat6/work
/var/cache/tomcat6
/var/cache/tomcat6/temp
/var/cache/tomcat6/work
/var/lib/tomcat6 (this is where you will add and/or change most of your files)
/var/lib/tomcat6/webapps
/var/log/tomcat6

Installing Tomcat7 using Apache mutliplatform binary release


Just followed the steps in http://www.davidghedini.com/pg/entry/install_tomcat_7_on_centos


From http://tomcat.apache.org/, get to know the latest version of Tomcat available. The latest version is Tomcat 7. Tomcat 7 implements the JavaServer Pages 2.2 and Servlet 3.0 specifications

First we need to download and install

1) JDK
2) JRE

for CentOS.

JRE (Java Runtime Environment) is needed to run Java applications and applets on our system.

To develop Java applications and applets, you need the JDK (Java Development Kit), which includes the JRE.

Installing JDK 7(1.7)

The latest JDK available is JDK 7.  Tomcat 7 requires a minimum of JDK 6

At the time of installation, the JDK available for download was "JDK 7 Update 9"

The JDK is specific to 32-bit and 64-bit versions. My CentOS is a 64-bit version. Hence I  download jdk-7u9-linux-x64.tar.gz

Start by creating a new directory /usr/java

# mkdir /usr/java
# cd /usr/java

Extract the package jdk-7u9-linux-x64.tar.gz in this directory.

# tar xzvf jdk-7u9-linux-x64.gz

This will create the directory /usr/java/jdk1.7.0_09. This will be our JAVA_HOME.

We can now set JAVA_HOME and put Java into the path of our users.

To set it for your current session, you can issue the following from the CLI:
# JAVA_HOME=/usr/java/jdk1.7.0_09
# export JAVA_HOME
# PATH=$JAVA_HOME/bin:$PATH
# export PATH

To set the JAVA_HOME permanently, however, we need to add below to the ~/.bash_profile of the user (in this case, root).  We can also add it /etc/profile and then source it to give to all users.

In case, Using JDK6 instead of JDK7 -
If you decided to use JDK 6 rather than JDK 7 as we did above, simply save the JDK 6 bin file to /opt (or another location), then navigate to /usr/java and issue: 'sh /opt/jdk-6u33-linux-x64.bin'. This will create a JAVA Home of /usr/java/jdk1.6.0.33. JDK6 bin file can be downloaded from http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html#jdk-6u33-oth-JPR

Now check the Java version, as follows
# java -version
java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)

If your Java version is at least 1.5.0, you can install Tomcat 5.5 or Tomcat 6.0. If you do not have a Java runtime of at least version 1.5.0, you cannot install Tomcat 6.0 or higher without first updating Java.


Download and Unpack Tomcat Binary release

We will now install Tomcat 7 under /opt

The latest Tomcat is Tomcat 7.x. Download the latest tomcat package from http://tomcat.apache.org/download-70.cgi

The latest binary distribution is Tomcat 7.0.32
# cd /opt
# wget http://apache.techartifact.com/mirror/tomcat/tomcat-7/v7.0.32/bin/apache-tomcat-7.0.32.tar.gz

This will create a directory /opt/apache-tomcat-7.0.32

The root of apache tomcat installation is referred as $CATALINA_HOME
So thus, CATALINA_HOME is /opt/apache-tomcat-7.0.32

Optionally, Tomcat may be configured for multiple instances by defining $CATALINA_BASE for each instance. If multiple instances are not configured, $CATALINA_BASE is the same as $CATALINA_HOME

Under /opt, create a symbolic link named "tomcat" to directory "/opt/apache-tomcat-7.0.32"
# ln -s apache-tomcat-7.0.32 tomcat

For security purpose, it is always better to run tomcat as non-root user

Now let us create a user and group named "tomcat"
# groupadd tomcat

Create user "tomcat" with home directory as /opt/tomcat/temp, and set user tomcat’s login shell to something that doesn’t actually work, such as /sbin/nologin

# useradd -s /sbin/nologin -d /opt/tomcat/temp -g tomcat -c 'Tomcat User'  tomcat

# id tomcat
uid=502(tomcat) gid=502(tomcat) groups=502(tomcat)

Change ownership of the tomcat files to the user tomcat we created above:
# chown -Rf tomcat.tomcat /opt/apache-tomcat-7.0.32


Configure Tomcat to Run as a Service

We will now see how to run Tomcat as a service and create a simple Start/Stop/Restart script, as well as to start Tomcat at boot.

Change to the /etc/init.d directory and create a script called 'tomcat' as shown below.

cd /etc/init.d
vi tomcat

#!/bin/bash  
# description: Tomcat Start Stop Restart  
# processname: tomcat  

# Set JAVA home directory   
JAVA_HOME=/usr/java/jdk1.7.0_09
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

# Set Tomcat home directory
CATALINA_HOME=/opt/apache-tomcat-7.0.32
  
case $1 in  
start)  
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/startup.sh  
;;   
stop)     
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/shutdown.sh  
;;   
restart)  
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/shutdown.sh  
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/startup.sh  
;;   
esac      
exit 0  

In the above script, we are simply calling the startup.sh and shutdown.sh scripts located in the Tomcat bin directory (/opt/apache-tomcat-7.0.32/bin)

Since the user "tomcat" was created with no login option(/sbin/nologin), we specify the shell "/bin/sh" to start and stop the script as user "tomcat"

# chmod +x tomcat

# service tomcat start
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

We should review the catalina.out log located at /opt/apache-tomcat-7.0.32/logs/catalina.out and check for any errors
# less /opt/apache-tomcat-7.0.32/logs/catalina.out

Check if tomcat is running as follows. Check for running java processes and  tomcat as follows
# pgrep java
12513

# netstat -nlp | grep :8080
tcp        0      0 :::8080                     :::*                        LISTEN      12513/java

#stop tomcat service

# service tomcat stop
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

# pgrep java
#


Configure tomcat service to start automatically on boot

To make /etc/init.d/tomcat script to run on boot

# chkconfig --add tomcat
service tomcat does not support chkconfig

To overcome this error "service tomcat does not support chkconfig", add the line "# chkconfig: 235 20 80" in beginning of file /etc/init.d/tomcat.
 * 235 stand for runlevels and
 * 20 & 80 stand for stop and start priorities

Now /etc/init.d/tomcat will look as follows

#!/bin/bash
# description: Tomcat Start Stop Restart
# processname: tomcat
# chkconfig: 235 20 80

# Set JAVA home directory
JAVA_HOME=/usr/java/jdk1.7.0_09
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

# Set Tomcat home directory
CATALINA_HOME=/opt/apache-tomcat-7.0.32

case $1 in
start)
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/startup.sh
;;
stop)
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/shutdown.sh
;;
restart)
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/shutdown.sh
/bin/su -s /bin/sh tomcat $CATALINA_HOME/bin/startup.sh
;;
esac
exit 0

Now run
# chkconfig --add tomcat

No error shall be reported now

# chkconfig --level 235 tomcat on
# chkconfig --list tomcat
tomcat          0:off   1:off   2:on    3:on    4:off   5:on    6:off

Thus tomcat installation is completed.


More about Starting Up and Stopping Tomcat

We used the following scripts to start and stop tomcat

  • $CATALINA_HOME/bin/startup.sh
  • $CATALINA_HOME/bin/shutdown.sh

where, CATALINA_HOME = /opt/apache-tomcat-7.0.32.

Both startup.sh and shutdown.sh actually use catalina.sh

Tomcat invocation scripts are available under the path /opt/apache-tomcat-7.0.32/bin/
* catalina.sh - The main Tomcat script. This runs the java command to invoke the Tomcat startup and shutdown classes.
* cpappend.sh - This is used internally, and then only on Windows systems, to append items to Tomcat classpath environment variables.
* digest.sh - This makes a "crypto" digest of Tomcat passwords. Use it to generate encrypted passwords.
* setclasspath.sh - This is also only used internally and sets the Tomcat classpath and several other environment variables.
* shutdown.sh - This runs "catalina stop" and shuts down Tomcat.
* startup.sh - This runs "catalina start" and starts up Tomcat.
* tool-wrapper.sh - This is a generic Tomcat command-line tool wrapper script that can be used to set environment variables and then call the main method of any fully qualified class that is in the classpath that is set. This is used internally by the digest script.
* version.sh - This runs the catalina version, which outputs Tomcat’s version information.

catalina.sh is the main Tomcat script which is called by both startup.sh as well as shutdown.sh scripts.

The main script, catalina, is invoked with one of several arguments. The most common arguments are
 * start,
 * run, or
 * stop.

When invoked with "start" (as it is when called from startup), it starts up Tomcat with the standard output and standard error streams directed into the file CATALINA_HOME/logs/catalina.out.

The "run" argument causes Tomcat to leave the standard output and error streams where they currently are (such as to the console window) useful for running from a terminal when you want to see the startup output.

Let us see their illustration

# ./catalina.sh start
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr/java/jdk1.7.0_09
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

# pgrep java
13616

# ./catalina.sh stop
Using CATALINA_BASE:   /opt/apache-tomcat-7.0.32
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.32
Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.32/temp
Using JRE_HOME:        /usr/java/jdk1.7.0_09
Using CLASSPATH:       /opt/apache-tomcat-7.0.32/bin/bootstrap.jar:/opt/apache-tomcat-7.0.32/bin/tomcat-juli.jar

# pgrep java
#

The config file read during start is /opt/apache-tomcat-7.0.32/conf/server.xml.

Thus the config file, server.xml, is available under the path $CATALINA_BASE/conf or $CATALINA_HOME/conf


Tomcat Environment Variables

CATALINA_BASE This sets the base directory for writable or customized portions of a Tomcat installation tree, such as logging files, work directories, Tomcat’s conf directory, and the webapps directory. It is an alias for CATALINA_HOME.

CATALINA_HOME This sets the base directory for static (read-only) portions of Tomcat, such as Tomcat’s lib directories and command-line scripts.

CATALINA_OPTS This passes through Tomcat-specific command-line options to the java command.

CATALINA_TMPDIR This sets the directory for Tomcat temporary files. CATALINA_HOME/temp

JAVA_HOME This sets the location of the Java runtime or JDK that Tomcat will use.

JRE_HOME This is an alias to JAVA_HOME.

JAVA_OPTS This is where you may set any Java command-line options.

JPDA_TRANSPORT This variable may set the transport protocol used for JPDA debugging.

JPDA_ADDRESS This sets the address for the JPDA used with the catalina jpda start command. For example, the port number and JPDA transport implementation can be set with JPDA_ADDRESS=8000 and JPDA_TRANSPORT=dt_socket.

JSSE_HOME This sets the location of the Java Secure Sockets Extension used with HTTPS.

CATALINA_PID This variable may optionally hold the path to the process ID file that Tomcat should use when starting up and shutting down.




Saturday, March 2, 2013

Aliasing, Redirecting and Rewriting in Apache

Difference between Aliasing, Redirecting and Rewriting in Apache

Aliasing refers to mapping a URL to a particular directory

Redirecting refers mapping a URL to another URL

Rewriting refers to using mod_rewrite module to alter an URL

Aliasing

Alias directive helps with aliasing as follows

1) To map URLs to a directory outside of the DocumentRoot directory tree

Eg:

To view the directory contents of user xyz through an URL, add the following entries in httpd.conf file


Alias /xyz /home/xyz

<Directory "/home/xyz">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Access the directory contents of user xyz as follows now
                 http://localhost/xyz

2) Helps in accessing the same content using different names

Eg: 

For the example shown above, suppose I want to access the contents of user "xyz" with name "abc" in httpd.conf file as follows

Alias /abc  /home/xyz

Now both the URLs show the same content

  http://localhost/xyz
  http://localhost/abc


Redirecting

Redirect maps a URL to another URL. The second argument to Redirect directive is a full URL.

Eg:

I want all requests coming to URL, http://localhost/xyz to be redirected to http://anonexp.blogspot.com

        http://localhost/xyz    ---->  http://anonexp.blogspot.com

In httpd.conf file, make the following entry

       Redirect   "/xyz"        "http://anonexp.blogspot.com"

From access_log file, we can confirm the redirection from 302 status

192.168.1.4 - - [03/Mar/2013:07:53:16 +0530] "GET /xyz/ HTTP/1.1" 302 290 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0"