Version : 2023.01.

Dernière mise-à-jour : 2023/10/11 09:11

SER506 - Journalisation, Supervision et Clustering

Contenu du Module

  • SER506 - Journalisation, Supervision et Clustering
    • Contenu du Module
    • Configuration des journaux
      • java.util.logging
    • Supervision
      • JMeter
      • Interface JMX
      • JConsole
    • Clustering avec Tomcat
      • Préparation
      • Le Cluster de Répartition de Charge avec Apache et mod_jk
      • Le Cluster de Répartition de Charge avec Apache et mod_proxy_ajp
      • Le Cluster en mode Maître/Esclave
      • Maintenir l'Etat des Clients
        • Préparation
        • Sessions Persistantes sur Système de Fichiers

Configuration des journaux

java.util.logging

Par défaut, Tomcat utilise le framework java.util.logging pour produire ses journaux.

Ce système de journalisation utilise le fichier $CATALINA_HOME/conf/logging.properties :

[root@centos8 ~]# cat $CATALINA_HOME/conf/logging.properties
# 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.

handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

2localhost.org.apache.juli.AsyncFileHandler.level = FINE
2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.org.apache.juli.AsyncFileHandler.maxDays = 90
2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8

3manager.org.apache.juli.AsyncFileHandler.level = FINE
3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.AsyncFileHandler.prefix = manager.
3manager.org.apache.juli.AsyncFileHandler.maxDays = 90
3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

4host-manager.org.apache.juli.AsyncFileHandler.level = FINE
4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager.
4host-manager.org.apache.juli.AsyncFileHandler.maxDays = 90
4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.encoding = UTF-8


############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.AsyncFileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.AsyncFileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.org.apache.juli.AsyncFileHandler

# For example, set the org.apache.catalina.util.LifecycleBase logger to log
# each component that extends LifecycleBase changing state:
#org.apache.catalina.util.LifecycleBase.level = FINE

# To see debug messages in TldLocationsCache, uncomment the following line:
#org.apache.jasper.compiler.TldLocationsCache.level = FINE

# To see debug messages for HTTP/2 handling, uncomment the following line:
#org.apache.coyote.http2.level = FINE

# To see debug messages for WebSocket handling, uncomment the following line:
#org.apache.tomcat.websocket.level = FINE

Dans ce fichier on constate la directive handlers :

...
handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler
...

Il existe deux types de handlers :

  • org.apache.juli.AsyncFileHandler qui écrit dans un fichier texte,
  • java.util.logging.ConsoleHandler qui écrit sur la sortie standard.

Dans la déclaration des handlers, il faut spécifier un nom. Dans la déclaration ci-dessus, les noms sont :

  • 1catalina,
  • 2localhost,
  • 3manager,
  • 4host-manager.

La directive suivante permet de référencer le gestionnaire principal pour le serveur lui-même :

...
.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler
...

Chaque handler doit ensuite être configuré :

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

2localhost.org.apache.juli.AsyncFileHandler.level = FINE
2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.org.apache.juli.AsyncFileHandler.maxDays = 90
2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8

3manager.org.apache.juli.AsyncFileHandler.level = FINE
3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.AsyncFileHandler.prefix = manager.
3manager.org.apache.juli.AsyncFileHandler.maxDays = 90
3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

4host-manager.org.apache.juli.AsyncFileHandler.level = FINE
4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager.
4host-manager.org.apache.juli.AsyncFileHandler.maxDays = 90
4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.encoding = UTF-8

Les attributs communs à la classe org.apache.juli.AsyncFileHandler et java.util.logging.ConsoleHandler sont les suivants :

Attribut Description
level Spécifie le niveau de journalisation. Les niveaux sont SEVERE, CONFIG, INFO, WARN, FINE, FINEST ou ALL
formatter Spécifie la classe utilisée pour formater le journal soit par défaut java.util.logging.SimpleFormatter soit java.util.logging.XMLFormatter pour générer une sortie au format XML

Les attributs spécifiques à la classe org.apache.juli.AsyncFileHandler sont les suivants :

Attribut Description
prefix Spécifie le nom du fichier
suffix Spécifie l'extension du fichier
directory Spécifie le répertoire de stockage des journaux

La rotation des journaux est journalier à 00h00. Le nom du journal aura don la forme suivante : nom.AAAA.MM.JJ.

La section suivante du fichier fournit un niveau de contrôle supplémentaire :

...
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.AsyncFileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.AsyncFileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.org.apache.juli.AsyncFileHandler
...

Par exemple :

  • [Catalina].[localhost] fait référence au hôte localhost,
  • [Catalina].[localhost].[/manager] fait référence à l'application manager.

Il est à noter que les configurations spécifiques aux applications peuvent être incluses soit dans le fichier $CATALINA_HOME/conf/logger.properties soit dans un fichier logger.properties qui se trouve dans le répertoire WEB-INF/classes de l'application concernée.

Important : Pour mettre en place le debugging, utilisez le niveau FINEST ou ALL. Pour plus d'information concernant la journalisation, consultez le manuel de Tomcat 10.

Supervision

JMeter

Ouvrez un terminal dans l'interface graphique de votre VM.

La gestion de la montée en charge de Tomcat peut être faite avec le produit libre JMeter. Pour l'obtenir, il convient de le télécharger :

[root@centos8 ~]# wget https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-5.6.2.zip
--2023-10-06 05:46:27--  https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-5.6.2.zip
Resolving archive.apache.org (archive.apache.org)... 65.108.204.189, 2a01:4f9:1a:a084::2
Connecting to archive.apache.org (archive.apache.org)|65.108.204.189|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 94326599 (90M) [application/zip]
Saving to: ‘apache-jmeter-5.6.2.zip’

apache-jmeter-5.6.2.zip     100%[========================================>]  89.96M  21.6MB/s    in 4.7s    

2023-10-06 05:46:33 (19.0 MB/s) - ‘apache-jmeter-5.6.2.zip’ saved [94326599/94326599]

Décompressez l'archive dans $CATALINA_HOME/JMeter :

[root@centos8 ~]# mkdir $CATALINA_HOME/JMeter

[root@centos8 ~]# mv apache-jmeter-5.6.2.zip $CATALINA_HOME/JMeter

[root@centos8 ~]# cd $CATALINA_HOME/JMeter

[root@centos8 JMeter]# unzip apache-jmeter-5.6.2.zip  

L'arborescence obtenu est :

[root@centos8 JMeter]# ls
apache-jmeter-5.6.2  apache-jmeter-5.6.2.zip

[root@centos8 JMeter]# cd apache-jmeter-5.6.2/

[root@centos8 apache-jmeter-5.6.2]# ls
bin  docs  extras  lib  LICENSE  licenses  NOTICE  printable_docs  README.md

Définissez maintenant la variable $JMETER_HOME :

[root@centos8 apache-jmeter-5.6.2]# JMETER_HOME=/usr/tomcat10/JMeter/apache-jmeter-5.6.2

[root@centos8 apache-jmeter-5.6.2]# export JMETER_HOME

[root@centos8 apache-jmeter-5.6.2]# echo $JMETER_HOME
/usr/tomcat10/JMeter/apache-jmeter-5.6.2

Connectez-vous à votre VM CentOS 8 en mode graphique en utilisant Guacamole :

Si, et uniquement si, votre VM CentOS 8 n'est pas en mode graphique ( erreur de connexion sous Guacamole ), modifiez la target par défaut à graphical target :

[root@centos8 apache-jmeter-5.6.2]# systemctl set-default graphical.target

Re-démarrez votre VM CentoS 8 :

[root@centos8 apache-jmeter-5.6.2]# reboot

Si votre connexion réussie mais la VM semble être bloquée, retournez dans votre connexion SSH et saisissez la commande suivante :

[root@centos8 apache-jmeter-5.6.2]# systemctl restart vncserver@\:1.service

Lancez ensuite JMeter dans un terminal graphique de votre VM :

[root@centos8 apache-jmeter-5.6.2]# /usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/jmeter

Testez cet outil en utilisant les différents fichiers mis-à-disposition lors de l'installation de JMeter :

[root@centos8 apache-jmeter-5.6.2]# updatedb
[root@centos8 apache-jmeter-5.6.2]# locate .jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/examples/CSVSample.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/examples/PerformanceTestPlanMemoryThread.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/BeanShellSampler.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/GroovyJSR223Sampler.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/ThinkTime.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-adv-web-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-ftp-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-ldap-ext-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-ldap-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-web-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/build-webservice-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/functional-testing-01-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/jdbc.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/mongodb.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/recording-with-think-time.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/recording.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/bin/templates/simple-http-request-test-plan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/extras/Test.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/AssertionTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/AuthManagerTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/ForEachTest2.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/HeaderManagerTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/InterleaveTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/InterleaveTestPlan2.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/JDBC-Pre-Post-Processor.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/JMSPointToPoint.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/LoopTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/OnceOnlyTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/ProxyServerTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/RegEx-User-Parameters.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/SimpleGraphQLTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/SimpleTestPlan.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/URLRewritingExample.jmx
/usr/tomcat10/JMeter/apache-jmeter-5.6.2/printable_docs/demos/forEachTestPlan.jmx

Important : Pour plus d'information concernant l'utilisation de cet outil, consultez la page https://jmeter.apache.org/usermanual/get-started.html.

Interface JMX

L'interface JMX est un outil complémentaire à JMeter car il est capable de montrer :

  • le comportement interne du serveur,
  • le nombre de connexions JDBC disponibles à un instant t,
  • le nombre de threads occupés dans un connecteur.

JMX ou Java Management eXtensions est un API Java qui extrait des informations des MBeans. Les MBeans sont créés dans le fichier $CATALINA_HOME/conf/server.xml en utilisant des éléments <Listener> :

...
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!-- APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
...

Revenez à l'authentification en utilisant le fichier tomcat-users.xml en éditant le fichier $CATALINA_HOME/conf/server.xml :

[root@centos8 apache-jmeter-5.6.2]# vi $CATALINA_HOME/conf/server.xml
[root@centos8 apache-jmeter-5.6.2]# cat $CATALINA_HOME/conf/server.xml
...
      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase">
        <CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler" algorithm="SHA-256"/>
      </Realm>

      <!--<Realm  className="org.apache.catalina.realm.DataSourceRealm"
         dataSourceName="jdbc/AuthTomcat"
              userTable="users" userNameCol="nom_user" userCredCol="mdp_user"
          userRoleTable="roles" roleNameCol="nom_role" /> -->

      <!-- <Realm  className="org.apache.catalina.realm.JNDIRealm"
          connectionURL="ldap://localhost:389"
         connectionName="cn=Manager,o=ittraining.loc"
     connectionPassword="fenestros"
               roleBase="ou=roles,o=ittraining.loc"
               roleName="cn"
             roleSearch="(uniqueMember={0})"
           userPassword="userPassword"
            userPattern="cn={0},ou=utilisateurs,o=ittraining.loc" /  -->>

      </Realm>
...

Éditez ensuite le fichier $CATALINA_HOME/conf/tomcat-users.xml :

[root@centos8 apache-jmeter-5.6.2]# vi $CATALINA_HOME/conf/tomcat-users.xml
[root@centos8 apache-jmeter-5.6.2]# cat $CATALINA_HOME/conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager-script"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-jmx"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="admin" password="f13c89ed8da3d2674c1937503b73fb15cd061751ddbefdb12c337cf0a67c0b0c$1$ad18b00f8856db9fa0396a5448fa022ed2b7c367faf113e209bb68e16cbffbce" roles="manager-script,manager-gui,manager-jmx"/>
</tomcat-users>

Redémarrez le serveur Tomcat :

[root@centos8 apache-jmeter-5.6.2]# systemctl restart tomcat
[root@centos8 apache-jmeter-5.6.2]# systemctl status tomcat
● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 06:25:23 EDT; 7s ago
  Process: 4235 ExecStart=/usr/tomcat10/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 4245 (java)
    Tasks: 62 (limit: 100949)
   Memory: 351.7M
   CGroup: /system.slice/tomcat.service
           └─4245 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10//conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLo>

Oct 06 06:25:23 centos8.ittraining.loc systemd[1]: Starting Apache Tomcat Web Application Container...
Oct 06 06:25:23 centos8.ittraining.loc startup.sh[4235]: Existing PID file found during start.
Oct 06 06:25:23 centos8.ittraining.loc startup.sh[4235]: Removing/clearing stale PID file.
Oct 06 06:25:23 centos8.ittraining.loc startup.sh[4235]: Tomcat started.
Oct 06 06:25:23 centos8.ittraining.loc systemd[1]: Started Apache Tomcat Web Application Container.

Testez que l'authentification fonctionne correctement :

[root@centos8 apache-jmeter-5.6.2]# lynx --dump -auth admin:fenestros "http://www.ittraining.loc:8080/manager/text/serverinfo"
OK - Server info
Tomcat Version: [Apache Tomcat/10.0.27]
OS Name: [Linux]
OS Version: [4.18.0-305.7.1.el8_4.x86_64]
OS Architecture: [amd64]
JVM Version: [1.8.0_312-b07]
JVM Vendor: [Red Hat, Inc.]

L'application manager propose un client JMX sous la forme d'un proxy JMX, jmxproxy.

Saisissez donc la commande suivante :

[root@centos8 apache-jmeter-5.6.2]# lynx --dump -auth admin:fenestros "http://www.ittraining.loc:8080/manager/jmxproxy/?qry=*:*" | more
OK - Number of results: 185

Name: Catalina:type=Service
modelerType: org.apache.catalina.mbeans.ServiceMBean
stateName: STARTED
connectorNames: Array[javax.management.ObjectName] of length 3
        Catalina:type=Connector,port=8080
        Catalina:type=Connector,port=8443
        Catalina:type=Connector,port=8009,address="127.0.0.1"
name: Catalina
managedResource: StandardService[Catalina]

Name: Catalina:j2eeType=Servlet,WebModule=//localhost/examples,name=stock,J2EEAp
plication=none,J2EEServer=none
modelerType: org.apache.catalina.mbeans.ContainerMBean
maxTime: 0
requestCount: 0
servletClass: async.AsyncStockServlet
countAllocated: 0
available: 0
backgroundProcessorDelay: -1
processingTime: 0
loadOnStartup: -1
loadTime: 0
stateName: STARTED
minTime: 9223372036854775807
classLoadTime: 0
asyncSupported: true
objectName: Catalina:j2eeType=Servlet,WebModule=//localhost/examples,name=stock,
J2EEApplication=none,J2EEServer=none
maxInstances: 20
errorCount: 0

Name: Catalina:type=Valve,host=localhost,context=/,name=NonLoginAuthenticator
modelerType: org.apache.tomcat.util.modeler.BaseModelMBean
cache: true
changeSessionIdOnAuthentication: true
disableProxyCaching: true
stateName: STARTED
className: org.apache.catalina.authenticator.NonLoginAuthenticator
securePagesWithPragma: false

Name: Catalina:j2eeType=Filter,WebModule=//localhost/examples,name=Compression F
ilter,J2EEApplication=none,J2EEServer=none
modelerType: org.apache.tomcat.util.modeler.BaseModelMBean
filterClass: compressionFilters.CompressionFilter
filterName: Compression Filter
filterInitParameterMap: {debug=0, compressionThreshold=128, compressionBuffer=81
92, compressionMimeTypes=text/html,text/plain,text/xml}

Name: Catalina:j2eeType=Servlet,WebModule=//localhost/examples,name=RequestHeade
rExample,J2EEApplication=none,J2EEServer=none
modelerType: org.apache.catalina.mbeans.ContainerMBean
maxTime: 0
requestCount: 0
servletClass: RequestHeaderExample
countAllocated: 0
available: 0
--More--

Saisissez maintenant la commande suivante :

[root@centos8 apache-jmeter-5.6.2]# lynx --dump -auth admin:fenestros "http://www.ittraining.loc:8080/manager/jmxproxy/?qry=Catalina:type=Connector,*" | more
OK - Number of results: 3

Name: Catalina:type=Connector,port=8443
modelerType: org.apache.catalina.mbeans.ConnectorMBean
maxPostSize: 2097152
proxyName: 10.0.2.45
scheme: http
redirectPortWithOffset: 443
acceptCount: 100
secure: false
threadPriority: 5
maxSwallowSize: 2097152
maxSavePostSize: 4096
proxyPort: 443
portWithOffset: 8443
maxParameterCount: 10000
useIPVHosts: false
stateName: STARTED
redirectPort: 443
allowTrace: false
protocolHandlerClassName: org.apache.coyote.http11.Http11NioProtocol
maxThreads: 200
connectionTimeout: 60000
tcpNoDelay: true
useBodyEncodingForURI: false
connectionLinger: -1
processorCache: 200
keepAliveTimeout: 60000
maxKeepAliveRequests: 100
localPort: 8443
enableLookups: false
URIEncoding: UTF-8
minSpareThreads: 10
executorName: Internal
maxHeaderCount: 100
port: 8443
portOffset: 0
xpoweredBy: false

Name: Catalina:type=Connector,port=8009,address="127.0.0.1"
modelerType: org.apache.catalina.mbeans.ConnectorMBean
maxPostSize: 2097152
scheme: http
redirectPortWithOffset: 8443
acceptCount: 100
secure: false
threadPriority: 5
ajpFlush: true
maxSavePostSize: 4096
proxyPort: 0
portWithOffset: 8009
protocol: AJP/1.3
maxParameterCount: 10000
useIPVHosts: false
stateName: STARTED
redirectPort: 8443
allowTrace: false
protocolHandlerClassName: org.apache.coyote.ajp.AjpNioProtocol
--More--

Saisissez maintenant la commande suivante :

[root@centos8 apache-jmeter-5.6.2]# lynx --dump -auth admin:fenestros "http://www.ittraining.loc:8080/manager/jmxproxy/?qry=Catalina:type=ThreadPool,*"
OK - Number of results: 3

Name: Catalina:type=ThreadPool,name="http-nio-8443"
modelerType: org.apache.catalina.mbeans.ClassNameMBean
currentThreadsBusy: 0
paused: false
selectorTimeout: 1000
connectionCount: 1
acceptCount: 100
threadPriority: 5
executorTerminationTimeoutMillis: 5000
running: true
portWithOffset: 8443
currentThreadCount: 10
sSLEnabled: false
sniParseLimit: 65536
maxThreads: 200
connectionTimeout: 60000
tcpNoDelay: true
maxConnections: 8192
connectionLinger: -1
keepAliveCount: 0
keepAliveTimeout: 60000
maxKeepAliveRequests: 100
localPort: 8443
useSendfile: true
daemon: true
minSpareThreads: 10
useInheritedChannel: false
alpnSupported: false
acceptorThreadPriority: 5
bindOnInit: true
pollerThreadPriority: 5
port: 8443
portOffset: 0
domain: Catalina
name: http-nio-8443
defaultSSLHostConfigName: _default_

Name: Catalina:type=ThreadPool,name="ajp-nio-127.0.0.1-8009"
modelerType: org.apache.catalina.mbeans.ClassNameMBean
currentThreadsBusy: 0
paused: false
selectorTimeout: 1000
connectionCount: 1
acceptCount: 100
threadPriority: 5
executorTerminationTimeoutMillis: 5000
running: true
portWithOffset: 8009
currentThreadCount: 10
sSLEnabled: false
sniParseLimit: 65536
maxThreads: 200
connectionTimeout: -1
tcpNoDelay: true
maxConnections: 8192
connectionLinger: -1
keepAliveCount: 0
keepAliveTimeout: -1
maxKeepAliveRequests: 100
localPort: 8009
useSendfile: false
daemon: true
minSpareThreads: 10
useInheritedChannel: false
alpnSupported: false
acceptorThreadPriority: 5
bindOnInit: true
pollerThreadPriority: 5
port: 8009
portOffset: 0
domain: Catalina
name: ajp-nio-127.0.0.1-8009
defaultSSLHostConfigName: _default_

Name: Catalina:type=ThreadPool,name="http-nio-8080"
modelerType: org.apache.catalina.mbeans.ClassNameMBean
currentThreadsBusy: 2
paused: false
selectorTimeout: 1000
connectionCount: 3
acceptCount: 100
threadPriority: 5
executorTerminationTimeoutMillis: 5000
running: true
portWithOffset: 8080
currentThreadCount: 10
sSLEnabled: false
sniParseLimit: 65536
maxThreads: 200
connectionTimeout: 20000
tcpNoDelay: true
maxConnections: 8192
connectionLinger: -1
keepAliveCount: 1
keepAliveTimeout: 20000
maxKeepAliveRequests: 100
localPort: 8080
useSendfile: true
daemon: true
minSpareThreads: 10
useInheritedChannel: false
alpnSupported: false
acceptorThreadPriority: 5
bindOnInit: true
pollerThreadPriority: 5
port: 8080
portOffset: 0
domain: Catalina
name: http-nio-8080
defaultSSLHostConfigName: _default_

Notez la valeur de maxThreads dans la section name=“http-nio-8080” :

...
maxThreads: 200
...

Pour modifier la valeur de maxThreads, il faut créer le fichier $CATALINA_HOME/bin/setenv.sh :

[root@centos8 apache-jmeter-5.6.2]# cd $CATALINA_HOME/bin

[root@centos8 bin]# vi setenv.sh

[root@centos8 bin]# cat setenv.sh
export JAVA_OPTS="-Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"

[root@centos8 bin]# chmod ugo+x setenv.sh

[root@centos8 bin]# ls -l setenv.sh
-rwxr-xr-x 1 root root 146 Oct  6 06:31 setenv.sh

Redémarrez le serveur Tomcat pour une prise en compte du fichier setenv.sh :

[root@centos8 bin]# systemctl restart tomcat
[root@centos8 bin]# systemctl status tomcat
● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 06:32:04 EDT; 8s ago
  Process: 4441 ExecStop=/bin/kill -15 $MAINPID (code=exited, status=0/SUCCESS)
  Process: 4450 ExecStart=/usr/tomcat10/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 4462 (java)
    Tasks: 62 (limit: 100949)
   Memory: 371.2M
   CGroup: /system.slice/tomcat.service
           └─4462 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10//conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLo>

Oct 06 06:32:04 centos8.ittraining.loc systemd[1]: Starting Apache Tomcat Web Application Container...
Oct 06 06:32:04 centos8.ittraining.loc startup.sh[4450]: Existing PID file found during start.
Oct 06 06:32:04 centos8.ittraining.loc startup.sh[4450]: Removing/clearing stale PID file.
Oct 06 06:32:04 centos8.ittraining.loc startup.sh[4450]: Tomcat started.
Oct 06 06:32:04 centos8.ittraining.loc systemd[1]: Started Apache Tomcat Web Application Container.

Maintenant saisissez l'URL suivant dans un navigateur en mode graphique pour modifier la valeur de MaxThreads :

http://www.ittraining.loc:8080/manager/jmxproxy/?set=Catalina:type=ThreadPool,name="http-nio-8080"&att=maxThreads&val=300

Important : Notez que le navigateur vous demande de renseigner un utilisateur et un mot de passe : admin/fenestros.

Vous obtiendrez un résultat similaire à celui-ci :

OK - Attribute set

Saisissez la commande suivante pour vérifier la prise en compte de la modification :

[root@centos8 bin]# lynx --dump -auth admin:fenestros "http://www.ittraining.loc:8080/manager/jmxproxy/?qry=Catalina:type=ThreadPool,*"
OK - Number of results: 3

...
Name: Catalina:type=ThreadPool,name="http-nio-8080"
modelerType: org.apache.catalina.mbeans.ClassNameMBean
currentThreadsBusy: 2
paused: false
selectorTimeout: 1000
connectionCount: 3
acceptCount: 100
threadPriority: 5
executorTerminationTimeoutMillis: 5000
running: true
portWithOffset: 8080
currentThreadCount: 10
sSLEnabled: false
sniParseLimit: 65536
maxThreads: 300
connectionTimeout: 20000
tcpNoDelay: true
maxConnections: 8192
connectionLinger: -1
keepAliveCount: 1
keepAliveTimeout: 20000
maxKeepAliveRequests: 100
localPort: 8080
useSendfile: true
daemon: true
minSpareThreads: 10
useInheritedChannel: false
alpnSupported: false
acceptorThreadPriority: 5
bindOnInit: true
pollerThreadPriority: 5
port: 8080
portOffset: 0
domain: Catalina
name: http-nio-8080
defaultSSLHostConfigName: _default_

Important : Pour plus d'information concernant jmx, consultez le manual de Tomcat.

JConsole

Pour utiliser JConsole, commencez par créer le fichier des utilisateurs et des mots de passe :

[root@centos8 bin]# cd ../conf

[root@centos8 conf]# vi jmxremote.access

[root@centos8 conf]# cat jmxremote.access
administrator   readwrite
operator        readonly

[root@centos8 conf]# vi jmxremote.password

[root@centos8 conf]# cat jmxremote.password
administrator   fenestros
operator        tomcat

[root@centos7 conf]# chmod 600 jmxremote.password

Modifiez le propriétaire et le groupe des fichiers jmxremote.access et jmxremote.password :

[root@centos8 logs]# chown tomcat:tomcat /usr/tomcat10/conf/jmxremote.access 

[root@centos8 logs]# chown tomcat:tomcat /usr/tomcat10/conf/jmxremote.password

Dans un premier temps vous allez mettre en place une connexion anonyme à JConsole. Éditez donc votre fichier $CATALINA_HOME/bin/setenv.sh :

[root@centos8 conf]# cd ../bin

[root@centos8 bin]# vi setenv.sh

[root@centos8 bin]# cat setenv.sh
export JAVA_OPTS="-Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=9004"

Redémarrez maintenant le serveur Tomcat :

[root@centos8 bin]# systemctl restart tomcat
[root@centos8 bin]# systemctl status tomcat
● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 06:45:21 EDT; 7s ago
  Process: 5296 ExecStop=/bin/kill -15 $MAINPID (code=exited, status=0/SUCCESS)
  Process: 5303 ExecStart=/usr/tomcat10/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 5315 (java)
    Tasks: 65 (limit: 100949)
   Memory: 366.4M
   CGroup: /system.slice/tomcat.service
           └─5315 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10//conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLo>

Oct 06 06:45:21 centos8.ittraining.loc systemd[1]: Starting Apache Tomcat Web Application Container...
Oct 06 06:45:21 centos8.ittraining.loc startup.sh[5303]: Existing PID file found during start.
Oct 06 06:45:21 centos8.ittraining.loc startup.sh[5303]: Removing/clearing stale PID file.
Oct 06 06:45:21 centos8.ittraining.loc startup.sh[5303]: Tomcat started.
Oct 06 06:45:21 centos8.ittraining.loc systemd[1]: Started Apache Tomcat Web Application Container.

Lancez la commande jconsole dans un terminal de l'interface graphique de votre VM. Cochez Remote Process et utilisez l'adresse localhost:9004 sans stipuler un utilisateur et un mot de passe :

Cliquez ensuite sur Insecure connection. Vous obtiendrez :

A Faire : Fermez la fenêtre jconsole.

Pour mettre en place une autorisation en utilisant les fichiers jmxremote.access et jmxremote.password, il convient d'éditer de nouveau le fichier $CATALINA_HOME/bin/setenv.sh :

[root@centos7 bin]# vi setenv.sh
[root@centos7 bin]# cat setenv.sh 
export JAVA_OPTS="-Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=9004 -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.password.file=$CATALINA_HOME/conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=$CATALINA_HOME/conf/jmxremote.access" 

Redémarrez le serveur Tomcat :

[root@centos8 bin]# systemctl restart tomcat
[root@centos8 bin]# systemctl status tomcat
● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 07:47:44 EDT; 4s ago
  Process: 7104 ExecStop=/bin/kill -15 $MAINPID (code=exited, status=0/SUCCESS)
  Process: 7111 ExecStart=/usr/tomcat10/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 7122 (java)
    Tasks: 65 (limit: 100949)
   Memory: 339.5M
   CGroup: /system.slice/tomcat.service
           └─7122 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10//conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLo>

Oct 06 07:47:44 centos8.ittraining.loc systemd[1]: Starting Apache Tomcat Web Application Container...
Oct 06 07:47:44 centos8.ittraining.loc startup.sh[7111]: Existing PID file found during start.
Oct 06 07:47:44 centos8.ittraining.loc startup.sh[7111]: Removing/clearing stale PID file.
Oct 06 07:47:44 centos8.ittraining.loc startup.sh[7111]: Tomcat started.
Oct 06 07:47:44 centos8.ittraining.loc systemd[1]: Started Apache Tomcat Web Application Container.

Lancez la commande jconsole dans un terminal de l'interface graphique de votre VM. Cochez Remote Process et utilisez l'adresse localhost:9004 en stipulant un utilisateur et un mot de passe dans les fichiers jmxremote.access et jmxremote.password respectivement.

Clustering avec Tomcat

Préparation

Arrêtez et désactivez le service Tomcat :

[root@centos8 bin]# systemctl stop tomcat

[root@centos8 bin]# systemctl disable tomcat

Créez maintenant deux répertoires en dessous de $CATALINA_HOME :

[root@centos8 bin]# mkdir $CATALINA_HOME/tomcat1 $CATALINA_HOME/tomcat2

Arrêtez le serveur Tomcat et copiez les répertoires $CATALINA_HOME/conf, $CATALINA_HOME/logs, $CATALINA_HOME/temp, $CATALINA_HOME/webapps, $CATALINA_HOME/work dans les répertoires $CATALINA_HOME/tomcat1 et $CATALINA_HOME/tomcat2 :

[root@centos8 bin]# cd $CATALINA_HOME
[root@centos8 tomcat10]# cp -rp conf/ tomcat1/
[root@centos8 tomcat10]# cp -rp logs/ tomcat1
[root@centos8 tomcat10]# cp -rp temp/ tomcat1
[root@centos8 tomcat10]# cp -rp webapps/ tomcat1
[root@centos8 tomcat10]# cp -rp work/ tomcat1
[root@centos8 tomcat10]# cp -rp conf/ tomcat2/
[root@centos8 tomcat10]# cp -rp logs/ tomcat2/
[root@centos8 tomcat10]# cp -rp temp/ tomcat2/
[root@centos8 tomcat10]# cp -rp webapps/ tomcat2/
[root@centos8 tomcat10]# cp -rp work/ tomcat2/

Supprimez les répertoires $CATALINA_HOME/conf, $CATALINA_HOME/logs, $CATALINA_HOME/temp, $CATALINA_HOME/webapps, $CATALINA_HOME/work :

[root@centos8 tomcat10]# rm -rf conf/ logs/ temp/ webapps/ work/

Supprimez maintenant le fichier $CATALINA_HOME/bin/setenv.sh :

[root@centos8 tomcat10]# rm -rf bin/setenv.sh 

Créez maintenant les scripts de démarrage et d'arrêt de chaque instance de Tomcat :

[root@centos8 tomcat10]# cd bin

[[root@centos8 bin]# vi startTomcat1

[root@centos8 bin]# cat startTomcat1 
#!/bin/bash
export CATALINA_BASE=/usr/tomcat10/tomcat1
. $CATALINA_HOME/bin/startup.sh

[root@centos8 bin]# vi startTomcat2

[root@centos8 bin]# cat startTomcat2
export CATALINA_BASE=/usr/tomcat10/tomcat2
. $CATALINA_HOME/bin/startup.sh

[root@centos8 bin]# vi stopTomcat1

[root@centos8 bin]# cat stopTomcat1
#!/bin/bash
export CATALINA_BASE=/usr/tomcat10/tomcat1
. $CATALINA_HOME/bin/shutdown.sh

[root@centos8 bin]# vi stopTomcat2

[root@centos8 bin]# cat stopTomcat2
#!/bin/bash
export CATALINA_BASE=/usr/tomcat10/tomcat2
. $CATALINA_HOME/bin/shutdown.sh

Rendez les scripts exécutables :

[root@centos8 bin]# chmod a+x startTomcat1
[root@centos8 bin]# chmod a+x startTomcat2
[root@centos8 bin]# chmod a+x stopTomcat1
[root@centos8 bin]# chmod a+x stopTomcat2
[root@centos8 bin]# ls -l | grep startT
-rwxr-xr-x 1 root root       88 Oct  6 10:12 startTomcat1
-rwxr-xr-x 1 root root       76 Oct  6 10:13 startTomcat2
[root@centos8 bin]# ls -l | grep stopT
-rwxr-xr-x 1 root root       89 Oct  6 10:14 stopTomcat1
-rwxr-xr-x 1 root root       88 Oct  6 10:14 stopTomcat2

Modifiez les ports dans le fichier server.xml de chaque installation de Tomcat en utilisant VI :

[root@centos8 bin]# vi /usr/tomcat10/tomcat1/conf/server.xml 
[root@centos8 bin]# vi /usr/tomcat10/tomcat2/conf/server.xml 

Les commandes VI suivantes peuvent vous aider.

Pour le fichier /usr/tomcat8/tomcat1/conf/server.xml :

:g/8080/s//8180/g
:g/8009/s//8109/g
:g/8005/s//8105/g
:g/8443/s//8143/g

Pour le fichier /usr/tomcat8/tomcat2/conf/server.xml :

:g/8080/s//8280/g
:g/8009/s//8209/g
:g/8005/s//8205/g
:g/8443/s//8243/g

Démarrez les deux instances de Tomcat :

[root@centos8 bin]# ./startTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[root@centos8 bin]# ps aux | grep tomcat
root        9991 85.0  2.0 9705084 337904 pts/0  Sl   10:22   0:11 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10/tomcat1/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat10/tomcat1 -Dcatalina.home=/usr/tomcat10 -Djava.io.tmpdir=/usr/tomcat10/tomcat1/temp org.apache.catalina.startup.Bootstrap start
root       10055  0.0  0.0  12136  1136 pts/0    S+   10:22   0:00 grep --color=auto tomcat

[root@centos8 bin]# ./startTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[root@centos8 bin]# ps aux | grep tomcat
root        9991 25.9  1.9 9705084 321360 pts/0  Sl   10:22   0:11 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10/tomcat1/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat10/tomcat1 -Dcatalina.home=/usr/tomcat10 -Djava.io.tmpdir=/usr/tomcat10/tomcat1/temp org.apache.catalina.startup.Bootstrap start
root       10065 78.4  2.1 9705084 345744 pts/0  Sl   10:22   0:11 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat10/tomcat2/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat10/tomcat2 -Dcatalina.home=/usr/tomcat10 -Djava.io.tmpdir=/usr/tomcat10/tomcat2/temp org.apache.catalina.startup.Bootstrap start
root       10129  0.0  0.0  12136  1068 pts/0    S+   10:23   0:00 grep --color=auto tomcat

Vérifiez maintenant que les deux instances peuvent être arrêtés :

[root@centos8 bin]# ./stopTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   

[root@centos8 bin]# ./stopTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:

[root@centos8 bin]# ps aux | grep tomcat
root       10229  0.0  0.0  12136  1152 pts/0    S+   10:24   0:00 grep --color=auto tomcat

Le Cluster de Répartition de Charge avec Apache et mod_jk

Modifiez le fichier /etc/httpd/conf/workers.properties :

[root@centos8 bin]# vi /etc/httpd/conf/workers.properties
[root@centos8 bin]# cat /etc/httpd/conf/workers.properties
worker.list=balancer

worker.tomcat1.type=ajp13
worker.tomcat1.host=127.0.0.1
worker.tomcat1.port=8109
worker.tomcat1.lbfactor=1

worker.tomcat2.type=ajp13
worker.tomcat2.host=127.0.0.1
worker.tomcat2.port=8209
worker.tomcat2.lbfactor=1

worker.balancer.type=lb
worker.balancer.balance_workers=tomcat1,tomcat2
worker.balancer.sticky_session=1

Modifiez la section concernant Tomcat dans le fichier /etc/httpd/conf/httpd.conf et commentez la ligne IncludeOptional conf.d/*.conf :

[root@centos7 bin]# vi /etc/httpd/conf/httpd.conf 
[root@centos7 bin]# tail /etc/httpd/conf/httpd.conf 
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
# IncludeOptional conf.d/*.conf

LoadModule	jk_module 	modules/mod_jk.so
JkWorkersFile	conf/workers.properties
JkLogFile	logs/mod_jk.log
JkLogLevel	info
JkMount		/docs/*	balancer
JkMount		/docs	balancer

Modifiez la section <Engine> du fichier $CATALINA_HOME/tomcat1/conf/server.xml :

[root@centos8 bin]# vi $CATALINA_HOME/tomcat1/conf/server.xml
...
    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
    <!-- <Engine name="Catalina" defaultHost="localhost"> -->

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
...

Modifiez ensuite la section <Engine> du fichier $CATALINA_HOME/tomcat2/conf/server.xml :

[root@centos8 bin]# vi $CATALINA_HOME/tomcat2/conf/server.xml
...
    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">
    <!-- <Engine name="Catalina" defaultHost="localhost"> -->

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
...

Pour pouvoir tester la configuration, remplacer les fichiers index.html de chaque application docs afin de pouvoir identifier quelle instance répond à des requêtes :

[root@centos8 bin]# mv $CATALINA_HOME/tomcat1/webapps/docs/index.html $CATALINA_HOME/tomcat1/webapps/docs/index.old

[root@centos8 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/index.html

[root@centos8 bin]# cat $CATALINA_HOME/tomcat1/webapps/docs/index.html
<html>
<title>Tomcat1</title>
<body>
<center>This is Tomcat1</center>
</body>
</html>

[root@centos8 bin]# mv $CATALINA_HOME/tomcat2/webapps/docs/index.html $CATALINA_HOME/tomcat2/webapps/docs/index.old

[root@centos8 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/index.html

[root@centos8 bin]# cat $CATALINA_HOME/tomcat2/webapps/docs/index.html
<html>
<title>Tomcat2</title>
<body>
<center>This is Tomcat2</center>
</body>
</html>

Redémarrez le service httpd.service :

[root@centos8 bin]# systemctl restart httpd
[root@centos8 bin]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 10:32:26 EDT; 6s ago
     Docs: man:httpd.service(8)
 Main PID: 10382 (httpd)
   Status: "Started, listening on: port 80"
    Tasks: 213 (limit: 100949)
   Memory: 43.7M
   CGroup: /system.slice/httpd.service
           ├─10382 /usr/sbin/httpd -DFOREGROUND
           ├─10386 /usr/sbin/httpd -DFOREGROUND
           ├─10387 /usr/sbin/httpd -DFOREGROUND
           ├─10388 /usr/sbin/httpd -DFOREGROUND
           └─10389 /usr/sbin/httpd -DFOREGROUND

Oct 06 10:32:26 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Oct 06 10:32:26 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Oct 06 10:32:26 centos8.ittraining.loc httpd[10382]: Server configured, listening on: port 80

Démarrez les deux instances de Tomcat :

[root@centos8 bin]# ./startTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[root@centos8 bin]# ./startTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

Utilisez Lynx pour vous connecter à l'application docs :

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

Attention : Notez que l'affinité de session est activée par défaut par le module AJP.

Arrêtez maintenant l'instance tomcat2 :

[root@centos7 bin]# ./stopTomcat2
Using CATALINA_BASE:   /usr/tomcat8/tomcat2
Using CATALINA_HOME:   /usr/tomcat8
Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64
Using CLASSPATH:       /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar

Connectez-vous de nouveau à l'application docs :

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

Important - Notez que c'est maintenant l'instance tomcat1 qui répond.

Le Cluster de Répartition de Charge avec Apache et mod_proxy_ajp

Vérifiez que les lignes LoadModule proxy_ajp_module modules/mod_proxy_ajp.so, LoadModule proxy_balancer_module modules/mod_proxy_balancer.so et LoadModule proxy_module modules/mod_proxy.so soient présentes dans le fichier /etc/httpd/conf.modules.d/00-proxy.conf :

[root@centos8 bin]# cat /etc/httpd/conf.modules.d/00-proxy.conf
# This file configures all the proxy modules:
LoadModule proxy_module modules/mod_proxy.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so

Modifiez le fichier /etc/httpd/conf/httpd.conf :

[root@centos8 bin]# vi /etc/httpd/conf/httpd.conf 

[root@centos8 bin]# cat /etc/httpd/conf/httpd.conf 
...
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
# IncludeOptional conf.d/*.conf

# LoadModule    jk_module       modules/mod_jk.so
# JkWorkersFile conf/workers.properties
# JkLogFile     logs/mod_jk.log
# JkLogLevel    info
# JkMount               /docs/* balancer
# JkMount               /docs   balancer

ProxyTimeout 300

<Proxy balancer://tomcat10-docs>
        BalancerMember ajp://localhost:8109/docs route=tomcat1
        BalancerMember ajp://localhost:8209/docs route=tomcat2
</Proxy>

ProxyPass               /docs   balancer://tomcat10-docs
ProxyPassReverse        /docs   balancer://tomcat10-docs

Redémarrez le serveur httpd :

[root@centos8 bin]# systemctl restart httpd
[root@centos8 bin]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 11:03:07 EDT; 9s ago
     Docs: man:httpd.service(8)
 Main PID: 13216 (httpd)
   Status: "Running, listening on: port 80"
    Tasks: 213 (limit: 100949)
   Memory: 46.8M
   CGroup: /system.slice/httpd.service
           ├─13216 /usr/sbin/httpd -DFOREGROUND
           ├─13219 /usr/sbin/httpd -DFOREGROUND
           ├─13220 /usr/sbin/httpd -DFOREGROUND
           ├─13221 /usr/sbin/httpd -DFOREGROUND
           └─13222 /usr/sbin/httpd -DFOREGROUND

Oct 06 11:03:07 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Oct 06 11:03:07 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Oct 06 11:03:08 centos8.ittraining.loc httpd[13216]: Server configured, listening on: port 80

Démarrez l'instance tomcat2 de Tomcat :

[root@centos7 bin]# ./startTomcat2
Using CATALINA_BASE:   /usr/tomcat8/tomcat2
Using CATALINA_HOME:   /usr/tomcat8
Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64
Using CLASSPATH:       /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar
Tomcat started

Utilisez Lynx pour vous connecter à l'application docs :

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

Attention : Notez que l'affinité de session n'est pas activée par défaut par le module proxy.

Afin de mettre en place l'affinité de session, il convient d'utiliser un cookie appelé ROUTEID.

Modifiez le fichier /etc/httdp/conf/httpd.conf ainsi :

[root@centos8 bin]# vi /etc/httpd/conf/httpd.conf
[root@centos8 bin]# cat /etc/httpd/conf/httpd.conf
...
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
# IncludeOptional conf.d/*.conf

# LoadModule    jk_module       modules/mod_jk.so
# JkWorkersFile conf/workers.properties
# JkLogFile     logs/mod_jk.log
# JkLogLevel    info
# JkMount               /docs/* balancer
# JkMount               /docs   balancer

ProxyTimeout 300
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<Proxy balancer://tomcat10-docs>
        BalancerMember ajp://localhost:8109/docs route=tomcat1
        BalancerMember ajp://localhost:8209/docs route=tomcat2
        ProxySet stickysession=ROUTEID
</Proxy>

ProxyPass               /docs   balancer://tomcat10-docs
ProxyPassReverse        /docs   balancer://tomcat10-docs

Re-démarrez le serveur httpd :

[root@centos8 bin]# systemctl restart httpd
[root@centos8 bin]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 11:13:16 EDT; 16s ago
     Docs: man:httpd.service(8)
 Main PID: 14093 (httpd)
   Status: "Running, listening on: port 80"
    Tasks: 213 (limit: 100949)
   Memory: 42.9M
   CGroup: /system.slice/httpd.service
           ├─14093 /usr/sbin/httpd -DFOREGROUND
           ├─14094 /usr/sbin/httpd -DFOREGROUND
           ├─14095 /usr/sbin/httpd -DFOREGROUND
           ├─14096 /usr/sbin/httpd -DFOREGROUND
           └─14097 /usr/sbin/httpd -DFOREGROUND

Oct 06 11:13:16 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Oct 06 11:13:16 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Oct 06 11:13:16 centos8.ittraining.loc httpd[14093]: Server configured, listening on: port 80

Testez ensuite l'affinité de session en utilisant un navigateur graphique.

Rechargez la page :

Attention : Notez que l'affinité de session est activée par le module proxy.

Pour plus d'information concernant l'utilisation de mod_proxy, consultez cette page

Le Cluster en mode Maître/Esclave

La configuration en mode Maître/Esclave utilise le module mod_jk. Editez donc votre fichier /etc/httpd/conf/httpd.conf :

[root@centos8 bin]# vi /etc/httpd/conf/httpd.conf 
[root@centos8 bin]# cat /etc/httpd/conf/httpd.conf 
...
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
# IncludeOptional conf.d/*.conf

LoadModule      jk_module       modules/mod_jk.so
JkWorkersFile   conf/workers.properties
JkLogFile       logs/mod_jk.log
JkLogLevel      info
JkMount         /docs/* balancer
JkMount         /docs   balancer
# Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
# <Proxy balancer://tomcat10-docs>
#       BalancerMember ajp://localhost:8109/docs route=tomcat1
#       BalancerMember ajp://localhost:8209/docs route=tomcat2
#       ProxySet stickysession=ROUTEID
# </Proxy>

# ProxyPass             /docs   balancer://tomcat10-docs
# ProxyPassReverse      /docs   balancer://tomcat10-docs

Éditez ensuite le fichier /etc/httpd/conf/workers.properties :

[root@centos8 bin]# vi /etc/httpd/conf/workers.properties
[root@centos8 bin]# cat /etc/httpd/conf/workers.properties
worker.list=tomcat1,tomcat2,balancer

worker.tomcat1.type=ajp13
worker.tomcat1.host=127.0.0.1
worker.tomcat1.port=8109
# Indique que tomcat2 doit prendre le relais en cas de défaillance de tomcat1
worker.tomcat1.redirect=tomcat2

worker.tomcat2.type=ajp13
worker.tomcat2.host=127.0.0.1
worker.tomcat2.port=8209
# Indique que l'instance tomcat2 est un escalve
worker.tomcat2.activation=disabled

worker.balancer.type=lb
worker.balancer.balance_workers=tomcat1,tomcat2

Redémarrez le serveur httpd :

[root@centos8 bin]# systemctl restart httpd
[root@centos8 bin]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2023-10-06 11:22:55 EDT; 8s ago
     Docs: man:httpd.service(8)
 Main PID: 14509 (httpd)
   Status: "Started, listening on: port 80"
    Tasks: 213 (limit: 100949)
   Memory: 48.5M
   CGroup: /system.slice/httpd.service
           ├─14509 /usr/sbin/httpd -DFOREGROUND
           ├─14511 /usr/sbin/httpd -DFOREGROUND
           ├─14512 /usr/sbin/httpd -DFOREGROUND
           ├─14513 /usr/sbin/httpd -DFOREGROUND
           └─14514 /usr/sbin/httpd -DFOREGROUND

Oct 06 11:22:55 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server...
Oct 06 11:22:55 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server.
Oct 06 11:22:55 centos8.ittraining.loc httpd[14509]: Server configured, listening on: port 80

Utilisez Lynx pour vous connecter à l'application docs :

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat1

Arrêtez l'instance tomcat1 :

[root@centos8 bin]# ./stopTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS: 

Utilisez de nouveau Lynx pour vous connecter à l'application docs :

[root@centos8 bin]# lynx --dump http://www.ittraining.loc/docs
                               This is Tomcat2

Attention : Notez que le basculement est automatique en cas de défaillance de l'instance tomcat1.

Maintenir l'Etat des Clients

Préparation

Editez le fichier web.xml de l'application /docs de chaque instance de Tomcat en incluant la directive <distributable/> :

[root@centos8 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/WEB-INF/web.xml

[root@centos8 bin]# cat $CATALINA_HOME/tomcat1/webapps/docs/WEB-INF/web.xml
<?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.
-->
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
  version="5.0"
  metadata-complete="true">

  <display-name>Tomcat Documentation</display-name>
  <description>
     Tomcat Documentation.
  </description>
 <distributable/>
</web-app>

[root@centos8 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/WEB-INF/web.xml
[root@centos8 bin]# cat $CATALINA_HOME/tomcat2/webapps/docs/WEB-INF/web.xml
<?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.
-->
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
  version="5.0"
  metadata-complete="true">

  <display-name>Tomcat Documentation</display-name>
  <description>
     Tomcat Documentation.
  </description>
 <distributable/>
</web-app>

Créez les fichiers $CATALINA_HOME/tomcat1/webapps/docs/session.jsp et $CATALINA_HOME/tomcat2/webapps/docs/session.jsp :

[root@centos8 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/session.jsp

[root@centos8 bin]# cat $CATALINA_HOME/tomcat1/webapps/docs/session.jsp
<%@page language="java" %>
<html>
<body>
<h3>
Session : <%= session.getId() %>
</h3>
</body>
</html>

[root@centos8 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/session.jsp

[root@centos8 bin]# cat $CATALINA_HOME/tomcat2/webapps/docs/session.jsp
<%@page language="java" %>
<html>
<body>
<h3>
Session : <%= session.getId() %>
</h3>
</body>
</html>

Dé-commentez la ligne suivante dans les fichiers server.xml :

[root@centos8 bin]# vi $CATALINA_HOME/tomcat1/conf/server.xml
...
        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
...
[root@centos8 bin]# vi $CATALINA_HOME/tomcat2/conf/server.xml
...
        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
...

Sessions Persistantes sur Système de Fichiers

Editez maintenant les fichier $CATALINA_HOME/tomcat1/conf/context.xml et $CATALINA_HOME/tomcat2/conf/context.xml en ajoutant la section suivante :

	<Manager className="org.apache.catalina.session.PersistentManager" >
		<Store className="org.apache.catalina.session.FileStore"
		directory="/tmp/sessions/" />
	</Manager>

Vous obtiendrez un résultat similaire à celui-ci pour les deux instances de Tomcat :

[root@centos8 bin]# cat $CATALINA_HOME/tomcat1/conf/context.xml
<?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. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to enable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="SESSIONS.ser" />
    -->
        <Manager className="org.apache.catalina.session.PersistentManager" >
                <Store className="org.apache.catalina.session.FileStore"
                directory="/tmp/sessions/" />
        </Manager>

</Context>

Créez le répertoire /tmp/sessions pour contenir les fichiers de sessions :

[root@centos8 bin]# mkdir /tmp/sessions

Re-démarrez les instances de Tomcat :

[root@centos8 bin]# ./stopTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Oct 06, 2023 11:37:50 AM org.apache.catalina.startup.Catalina stopServer
SEVERE: Could not contact [localhost:8105] (base port [8105] and offset [0]). Tomcat may not be running.
Oct 06, 2023 11:37:50 AM org.apache.catalina.startup.Catalina stopServer
SEVERE: Error stopping Catalina
java.net.ConnectException: Connection refused (Connection refused)
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:607)
        at java.net.Socket.connect(Socket.java:556)
        at java.net.Socket.<init>(Socket.java:452)
        at java.net.Socket.<init>(Socket.java:229)
        at org.apache.catalina.startup.Catalina.stopServer(Catalina.java:692)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.stopServer(Bootstrap.java:391)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:481)

[root@centos8 bin]# ./stopTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   

[root@centos8 bin]# ./startTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[root@centos8 bin]# ./startTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

Attention : Notez l'exception lors de l'arrêt de tomcat1 ci-dessus. Cette exception a lieu parce que tomcat1 avait été précédement arrêté. Dans votre cas l'exception pourrait se produire en arrêtant tomcat2 si celui-ci avait déjà été arrêté.

En utilisant votre navigateur graphique, saisissez l'URL suivante :

http://www.ittraining.loc/docs/session.jsp

Vous obtiendrez une résultat similaire à l'exemple suivant :

Session : D45C86D1E78A93F3EBEC2B3F9F178F0E.tomcat1

ou

Session : D45C86D1E78A93F3EBEC2B3F9F178F0E.tomcat2

Selon l'instance de Tomcat qui a répondu, arrêtez cette instance :

[root@centos8 bin]# ./stopTomcat1
Using CATALINA_BASE:   /usr/tomcat10/tomcat1
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat1/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS: 

ou

[root@centos8 bin]# ./stopTomcat2
Using CATALINA_BASE:   /usr/tomcat10/tomcat2
Using CATALINA_HOME:   /usr/tomcat10
Using CATALINA_TMPDIR: /usr/tomcat10/tomcat2/temp
Using JRE_HOME:        /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.312.b07-2.el8_5.x86_64
Using CLASSPATH:       /usr/tomcat10/bin/bootstrap.jar:/usr/tomcat10/bin/tomcat-juli.jar
Using CATALINA_OPTS: 

Contrôlez le contenu du répertoire /tmp/sessions :

[root@centos8 bin]# ls -l /tmp/sessions
total 4
-rw-r----- 1 root root 265 Oct  6 11:45 D45C86D1E78A93F3EBEC2B3F9F178F0E.tomcat1.session

Revenez à votre navigateur Web graphique et rafraîchissez la page. Vous obtiendrez un résultat démontrant que la session est resté la même malgré le fait que c'est l'autre instance de Tomcat qui vous a répondu.

Session : D45C86D1E78A93F3EBEC2B3F9F178F0E.tomcat1

ou

Session : D45C86D1E78A93F3EBEC2B3F9F178F0E.tomcat2


Copyright © 2023 Hugh Norris.

Menu