1234
394151535358
TableofContents
TableofContentsPivotaltcServerAdministrationOverviewoftcServerAdministrationConfiguringatcRuntimeInstanceManuallyBashCompletionCreatingandManagingtcServerTemplatesManagingPlannedandUnplannedOutagesEnablingClusteringforHighAvailabilityClusteringOverviewMonitoringtcRuntimeInstancesUsingHyperic
©CopyrightPivotalSoftwareInc,2013-2016 1 3.x
PivotaltcServerAdministrationPivotaltcServerAdministrationdescribeshowtoperformthemostcommonPivotaltcServeradministrationtasks.ReadthisdocumentationtolearnhowtoconfigureinstancesmanuallywiththetcServercommand-lineinterfaceandenableclusteringforhighavailability.
OverviewoftcServerAdministration
ConfiguringatcRuntimeInstanceManually
CreatingandManagingtcRuntimeTemplates
ManagingPlannedandUnplannedOutages
EnablingClusteringforHighAvailability
MonitoringtcRuntimeInstancesUsingHyperic
IntendedAudiencePivotaltcServerAdministrationisintendedforanyonewhoneedstoconfigureandadministertcServerbeyondwhatisdescribedinGettingStartedwithPivotaltcServer.
©CopyrightPivotalSoftwareInc,2013-2016 2 3.x
OverviewoftcServerAdministrationThisguidedescribeshowtoperformthemostcommonPivotaltcServeradministrationtasks:
ConfiguringatcRuntimeInstanceManually.ConfigureasingletcRuntimeinstancebymanuallyupdatingitsconfigurationfiles,suchas server.xml .
CreatingandManagingtcServerTemplates.Createcustomizedtemplatestobeusedalongsidethebuilt-intemplates.Usethesetemplatetocustomizeconfigurationsofyourinstances.
ManagingPlannedandUnplannedOutages.Learnhowtohandleplannedandunplannedoutages.
EnablingClusteringforHighAvailability.CreateaclusteroftcRuntimeinstancessoastoenablesessionreplication,cluster-widedeployment,andcontextreplication.Thissectionalsodescribeshowtoenableloadbalancing.
MonitoringtcRuntimeInstanceUsingVMwareHyperic.UsethePivotaltcServerHypericPlugintomonitoryourinstances.
InproceduresthatdescribehowtoconfigureindividualtcRuntimeinstances,itisassumedthatyoualreadyhavecreatedatleastoneinstanceandthatyounowwanttochangethedefaultconfigurationtotakeadvantageoftcServerfeaturesaswellasstandardApacheTomcatfeatures.IfyouhavenotcreatedatcRuntimeinstance,see“CreatingaNewtcRuntimeInstance”inGettingStartedwithPivotaltcServer.
©CopyrightPivotalSoftwareInc,2013-2016 3 3.x
ConfiguringatcRuntimeInstanceManuallyWhenyoufirstinstalltcRuntime,the server.xml filecontainstypicalserverconfigurationvaluesthatgetyouupandrunningimmediately.However,asyouusetcRuntimeandgointoproduction,youmightrequireadditionalconfiguration.Thischapterdescribestypicalandadditionalconfigurationusecases.
ConfigurationFilesandTemplatesThetcRuntimeconfigurationfilesarelocatedinthe CATALINA_BASE/conf directory,where CATALINA_BASE referstothedirectoryinwhichyouhaveinstalledatcRuntimeinstance.Themainconfigurationfilesare:
server.xml MainconfigurationfileforatcRuntimeinstance.Itconfiguresthebehavioroftheservlet/JSPcontainer.Bydefault,the server.xmlfileforatcRuntimeinstanceusesvariablesubstitutionforconfigurationpropertiessuchasHTTPandJMXportnumbersthatmustbeuniqueacrossmultipleserverinstancesonthesamecomputer.Thesevariablestaketheform ${var} .Forexample,thevariablefortheHTTPportonanNIOconnectorthatthetcRuntimeinstancelistenstois ${nio.http.port} .Thespecificvaluesforthesevariablesforaparticularserverinstancearestoredinthe catalina.properties file,inthesamedirectoryasthe server.xml file.
catalina.properties .Propertiesfilethatcontainstheserverinstance-specificvaluesforvariablesinthe server.xml file.
The conf directoryalsocontainsthefollowingtwofilesthatconfigurecommonpropertiesforallWebapplicationsdeployedtothetcRuntimeinstance:
web.xml DefinesdefaultvaluesforallWebapplications.
context.xml ThecontentsofthisfilewillbeloadedforeachWebapplication.
ThetcRuntimeinstallationalsoincludesasetofconfigurationtemplatesinthe INSTALL-DIR/pivotal-tc-server-edition/templates directory,where edition referstotheeditionofPivotaltcServerthatyouareusing,whether developer or standard .YoucanspecifythesetemplateswhenyoucreateanewtcRuntimeinstancetoautomaticallyenablecertainconfigurationfeatures,suchasSSLorclustering.Eachtemplateisadirectorythatcontainsnew,modified,orfragmentsoffilesthatthe tcruntime-instance scriptusestomodifythedefaulttcRuntimeinstancefiles.Manyofthetemplateschangethedefaultserver.xml file,soyoucanalsolookatthe server-fragment.xml filesinthevarioustemplatedirectoriesforexamplesofconfiguringanexistingtcRuntimeinstance.The server-fragment.xml filesarefragmentsofthe server.xml filethatthe tcruntime-instance scriptappliestothedefaulttcRuntimeconfigurationsoastoenableaparticularfeature.
FordetailsaboutthetemplatesprovidedbytcRuntime,see“CreatingatcRuntimeInstanceUsingaTemplate”inGettingStartedwithPivotaltcServer.
SimpletcRuntimeConfigurationThefollowingsample server.xml fileshowsabasicout-of-the-boxconfigurationforadefaulttcRuntimeinstanceincludedintcRuntime.ThisconfigurationfileusestypicalvaluesforastandardsetofXMLelements.Sample server.xml filesinlatersectionsofthisdocumentationbuildonthisfile.
This server.xml fileusesvariablesubstitutionforconfigurationproperties,suchasHTTPandJMXportnumbers,thatmustbeuniqueacrossmultipleserverinstancesononecomputer.Thesevariablestaketheform ${var} .Forexample,thevariablefortheHTTPportonaNIOconnectorthatthetcRuntimeinstancelistenstois ${nio.http.port} .Thespecificvaluesforthesevariablesforaparticularserverinstancearestoredinthe catalina.properties file,locatedinthesamedirectoryasthe server.xml file.Asnippetofthedefault catalina.properties fileisshownafterthesample server.xml file.
SeeDescriptionoftheBasicserver.xmlFileforinformationabouttheelementsandattributesinthissampleconfigurationfileincaseyouneedtochangethemtosuityourownenvironment.
©CopyrightPivotalSoftwareInc,2013-2016 4 3.x
<?xmlversion='1.0'encoding='utf-8'?><Serverport="${shutdown.port}"shutdown="SHUTDOWN">
<ListenerclassName="org.apache.catalina.core.JreMemoryLeakPreventionListener"/><ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/><ListenerclassName="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/><ListenerclassName="com.springsource.tcserver.serviceability.deploy.TcContainerDeployer"/>
<ListenerclassName="com.springsource.tcserver.serviceability.rmi.JmxSocketListener"port="${base.jmx.port}"address="127.0.0.1"useSSL="false"passwordFile="${catalina.base}/conf/jmxremote.password"accessFile="${catalina.base}/conf/jmxremote.access"authenticate="true"/>
<GlobalNamingResources><Resourcename="UserDatabase"auth="Container"type="org.apache.catalina.UserDatabase"description="Userdatabasethatcanbeupdatedandsaved"factory="org.apache.catalina.users.MemoryUserDatabaseFactory"pathname="conf/tomcat-users.xml"/></GlobalNamingResources>
<Servicename="Catalina">
<Executorname="tomcatThreadPool"namePrefix="tomcat-http--"maxThreads="300"minSpareThreads="50"/>
<Connectorexecutor="tomcatThreadPool"port="${nio.http.port}"protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="${nio.https.port}"acceptCount="100"maxKeepAliveRequests="15"/>
<Enginename="Catalina"defaultHost="localhost">
<RealmclassName="org.apache.catalina.realm.UserDatabaseRealm"resourceName="UserDatabase"/>
<Hostname="localhost"appBase="webapps"unpackWARs="true"autoDeploy="true"deployOnStartup="true"deployXML="true"xmlValidation="false"xmlNamespaceAware="false"></Host></Engine></Service></Server>
Thefollowingsnippetof catalina.properties showshowtosetvaluesforthevariablesusedinthepreceding server.xml file.
base.shutdown.port=-1base.jmx.port=6969nio.http.port=8080nio.https.port=8443
DescriptionoftheBasicserver.xmlFileNotethefollowingcomponentsoftheprecedingsample server.xml :
<Server> .Rootelementofthe server.xml file.ItsattributesrepresentthecharacteristicsoftheentiretcRuntimeservletcontainer.Theshutdown attributespecifiesthecommandstringthattheshutdownportnumberreceivesthroughaTCP/IPconnectioninordertoshutdownthetcRuntimeinstance.The port attributeistheTCP/IPportnumberthatlistensforashutdownmessageforthistcRuntimeinstance;notethatinthisserver.xml filethevariableis ${shutdown.port} .Bydefault,the catalina.properties filesubstitutesavalueof -1 ,whichdisablestheshutdownviaTCPconnection.ThustheonlywaytostopthetcRuntimeinstanceistoissuea kill commandontheprocessID(PID)ofthetcRuntimeinstance.Thisiswhatthe tcruntime-ctl.sh commanddoeswhenyouuseittostoparunningtcRuntimeinstance.
<Listener> .ListoflifecyclelistenersthatmonitorandmanagethetcRuntimeinstance.EachlistenerlistenstoaspecificcomponentofthetcRuntimeinstanceandhasbeenprogrammedtodosomethingatcertainlifecycleeventsofthecomponent,suchasbeforestartingup,afterstopping,andsoon.Thefirstfour <Listener> elementsconfigurestandardTomcatlifecyclelisteners.Youcaninserta com.springsource.tcserver.properties.SystemProperties listenerbeforethesestandardlistenerstosetpropertiesfromexternalpropertiesfiles.
©CopyrightPivotalSoftwareInc,2013-2016 5 3.x
SeeAddingaSystemPropertiesListener.Thelistenerimplementedbythe com.springsource.tcserver.serviceability.rmi.JmxSocketListener classisspecifictotcServer.ThislistenerenablesJMXmanagementoftcRuntime;inparticular,thisistheJMXconfigurationthattheHQuserinterfaceusestomonitortcRuntimeinstances.The port
attributespecifiestheportoftheJMXserverthatmonitoringproducts,suchasHypericHQ,connectto.Thevariable ${jmx.port} issetto 6969 inthedefault catalina.properties file.The address attributespecifiesthehostoftheJMXserver;bydefault,thisattributeissettothelocalhost( 127.0.0.1 ).Warning:Thevalueofthe address attributeof JmxSocketListener overridesthevalueofthe java.rmi.server.hostname Javasystemproperty.ThisdirectlyaffectshownamesareboundintheRMIregistries;bydefault,thenameswillbeboundtolocalhost( 127.0.0.1 ).ThismeansthatRMIclientsrunningonadifferenthostfromtheonehostingthetcRuntimeinstancewillbeunabletoaccesstheRMIobjectsbecause,fromtheirperspective,thehostnameisincorrect.ThisisbecausethehostshouldbethenameorIPaddressofthetcRuntimecomputerratherthan localhost .WhenthetcRuntimeinstancestarts,ifitfindsthatthevalueofthe address attributeisdifferentfromorincompatiblewiththe java.rmi.server.hostname Javasystemproperty,theinstancewilllogawarningbutwillstartupanywayandoverridethesystempropertyasdescribed.Ifthiscausesproblemsinyourparticularenvironment,thenyoushouldchangethevalueofthe address attributetospecifytheactualhostnameonwhichthetcRuntimeruns.Themonitoringapplication(suchasVMwareHyperic)thatconnectstothetcRuntimeinstanceviaJMXmustspecifyauserandpasswordtoactuallygainaccess.Youconfiguretheseinthefilespointedtobythe accessFile and passwordFile attributesoftheListener.Bydefault,theJMXuseris admin
withpasswordthatisgenerated.YoucanalsoconfigurethetcRuntimeinstancetouseLDAPtolookupitsJMXcredentials;seeConfiguringatcRuntimeInstancetoObtainItsJMXCredentialsfromLDAPfordetails.Bydefault,SSLisdisabled;ifyouenableitbyupdatingthe useSSL attribute,youmustthenconfigureHQwiththetrustStoreandtrustStorePassword.Tosetthesevalues,addthefollowingtothe agent.javaOpts entryineachHQAgent’s agent.properties file:
agent.javaOpts=-Xmx128m-Djava.net.preferIPv4Stack=true-Dsun.net.inetaddr.ttl=60\-Djavax.net.ssl.trustStore=${fullpathtotruststore}-Djavax.net.ssl.trustStorePassword=${password}
<GlobalNamingResources> .GroupstheglobalJNDIresourcesforthisserverinstancethatWebapplicationsdeployedtotheservercanuse.Intheprecedingexample,the <Resource> elementdefinesthedatabaseusedtoloadtheusersandrolesfromthe CATALINA_BASE/conf/tomcat-users.xml fileintoanin-memorydatastructure.Thisresourceislaterreferencedbythe <Engine> XMLelementsothatWebapplicationsdeployedtotcRuntimeinstancescanquerythedatabaseforthelistofusersandtherolestowhichtheusersaremapped,aswellasupdatethefile.
<Service> .Groupsoneormoreconnectors,oneormoreexecutors,andasingleengine.Connectorsdefineatransportmechanism,suchasHTTP,thatclientsusetosendandreceivemessagestoandfromtheassociatedservice.Aclientcanusemanytransports,whichiswhya <Service> elementcanhavemany <Connector> elements.Theexecutorsdefinethreadpoolsthatcanbesharedbetweencomponents,suchasconnectors.TheenginethendefineshowtheserequestsandresponsesthattheconnectorreceivesandsendsareinturnhandledbythetcRuntimeinstance;youcandefineonlyasingle <Engine> elementforanygiven <Service> element.Thesample server.xml fileaboveincludesasingle <Connector> fortheHTTPtransport,asingle <Executor> thatconfiguresthethreadpoolusedbytheconnector,andasingle <Engine> asrequired.
tomcatThreadPool .Asdefinedbythe <Executor> XMLelement,allowsamaximumof300activethreads.Theminimumnumberofthreadsthatarealwayskeptaliveis50.
<Connector> .ListensforHTTPrequestsatthe8080TCP/IPport(assetbythe ${bio.http.port} variablein catalina.properties ).Theconnectorusesthethreadpooldefinedbythe tomcatThreadPool executorandignoresallotherthreadattributes.Afteracceptingaconnectionfromaclient,theconnectorwaitsamaximumof20000millisecondsforarequestURI,afterwhichittimesout.IfthisconnectorreceivesarequestfromtheclientthatrequirestheSSLtransport,thetcRuntimeinstanceautomaticallyredirectstherequesttoport8443.IfthetcRuntimeinstancereceivesaconnectionrequestatamomentintimewhenallpossiblerequestprocessingthreadsareinuse,theserverputstherequestonaqueue;the acceptCount attributespecifiesthemaximumlengthofthisqueue(100)afterwhichtheserverrefusesallconnectionrequests.Finally,themaximumnumberofHTTPrequeststhatcanbepipelineduntiltheconnectionisclosedbytheserveris15,asspecifiedbythe maxKeepAliveRequests attribute.
Catalina .Logicalnameoftheengine.Thisnameappearsinallloganderrormessagessoyoucaneasilyidentifyproblems.ThevalueofthedefaultHost attributeisthenameofa <Host> childelementof <Engine> ;thishostprocessesrequestsdirectedtohostnamesonthisserver.The <Realm> childelementof <Engine> representsadatabaseofusers,passwords,andmappedrolesusedforauthenticationinthisservice.Intheprecedingsample,therealmsimplyreferencesthe UserDatabase resource,definedbythe <Resource> childelementof <GlobalNamingResources> .The <Host> childelementrepresentsavirtualhost,whichisanassociationofanetworknameforaserver(suchaswww.mycompany.com )withtheparticularserveronwhichCatalinaisrunning.tcRuntimeautomaticallydeploysWebapplicationsthatarecopiedtothe CATALINA_BASE/webapps
directorywhilethetcRuntimeinstanceisrunningandautomaticallydeploysthemwhentheserverstarts.ThetcRuntimeinstanceunpackstheWebapplicationsintoadirectoryhierarchyiftheyaredeployedasWARfiles.tcRuntimeparsesany context.xml filecontainedinthe META-INF directoryofdeployedapplications.The xmlValidation attributespecifiesthatthetcRuntimeinstancedoesnotvalidateXMLfileswhenparsingthem,orinotherwords,itacceptsinvalidXML.The xmlNamespaceAware attributespecifiesthattcRuntimedoesnottakenamespacesintoaccountwhenreadingXMLfiles.
Theprecedingsample server.xml filecontainstypicalelementsandattributevaluesforasimpleout-of-the-boxtcRuntimeconfiguration.However,youcanconfiguremanymoreelementsandattributesinthisfile.ForcompleteelementsdocumentationaboutthetcRuntime server.xml file,seeApacheTomcatConfigurationReference .
AddingaSystemPropertiesListenertcServerincludesausefulfeaturethatallowsyoutoconfiguretcServerandJavasystempropertiesthroughexternalpropertiesfiles.Propertiesthatyousetusingthismethodcanbeusetoasreplacementvaluesin server.xml .Theexternalpropertiesfilesarealsousefulforsettingapplicationproperties,insteadofmodifyingthe setenv.sh scripttosetthemonthe java commandlinewiththe -D flag.Thepropertiesareavailabletoapplicationsthrough
©CopyrightPivotalSoftwareInc,2013-2016 6 3.x
java.lang.System.getProperties() .
Thelistenershouldbethefirstchildofthe Server elementinthe server.xml file,sinceXMLisprocessedintheorderitappearsandpropertiesmustbesetbeforetheyarereferenced.
Thefollowingexamplespecifiesfourpropertiesfilestobeprocessedinsequence.
<ListenerclassName="com.springsource.tcserver.properties.SystemProperties"file.1="${catalina.base}/conf/base.properties"file.3="${catalina.base}/conf/qa.properties"file.2="${catalina.base}/conf/dev.properties"file.4="${catalina.base}/conf/prod.properties"immutable="false"trigger="now"/>
Therecanbeuptoonehundredfiles,andtheyareprocessedinsequencebythenumericextension,notintheordertheyappear.Intheexampleabove,the dev.properties fileisprocessedbeforethe qa.properties file,eventhoughtheyarenotlistedinthatorder.
The immutable attribute, false bydefault,determinesifpropertiescanbeoverridden.When false ,thepropertyvalueisseteachtimethekeyisencountered.If immutable is true ,onceavalueisassociatedwithakeyitcannotbechanged;lateroccurrencesofthepropertyareignored.Whetherimmutable issetto true or false ,adebugmessageisloggedwhenanexistingpropertyisencountered.
Ifyouspecifyapropertiesfilethatdoesnotexist,amessageislogged,butprocessingcontinues.Thisallowsyoutosetup system.xml fordifferentruntimeenvironmentsbysupplyingonlytheappropriatepropertiesfiles.Intheexampleabove,forexample,ifthe prod.properties fileismissing,thepropertiesinthe base.properties , dev.properties ,and qa.properties filesareprocessed,withanypropertiesoverriddenin qa.properties takingprecedence.
Thepresenceofthe trigger attributecausesthepropertiestobeappliedbeforeparsingtheremainderofthe server.xml file.Thevalueofthe triggerattributeisignored.
SettingUpaHigh-ConcurrencyJDBCDatasourceAdatasourcedefinesapoolofJDBCconnectionsforaspecificdatabaseusingaURL,username,andsoon.JDBCdatasourcesmakeiteasyforanapplicationtoaccessdatainadatabaseserver.
ComparingtheDBCPDatasourceandthetcRuntimeDatasourceInatcRuntimeinstance,youcancreatethefollowingtwotypesofJDBCdatasources:
Databaseconnectionpool(DBCP)datasource
TomcatJDBCdatasource
TheDBCPdatasourceisthestandarddatasourceprovidedbytcRuntime;itusestheorg.apache.commons.dbcp package.Althoughthisdatasourceisadequateforsimpleapplications,itissingle-threaded,whichmeansthatinordertobethread-safe,thetcRuntimeinstancemustlocktheentirepool,evenduringqueryvalidation.Thusitisnotsuitableforhighlyconcurrentenvironments.Additionally,itcanbeslow,whichinturncannegativelyaffecttheperformanceofWebapplications.
TheTomcatJDBCdatasourceincludesallthefunctionalityoftheDBCPdatasource,butaddsadditionalfeaturestosupporthighly-concurrentenvironmentsandmultiplecore/cpusystems.ThetcRuntimedatasourcetypicallyperformsmuchbetterthantheDBCPdatasource.Additionalfeaturesinclude:
Dynamicimplementationoftheinterfaces,whichmeansthatthedatasourcesupportsthe java.sql and javax.sql interfacesforyourruntimeenvironment(aslongasyourJDBCdriversupportsit),evenwhencompiledwithalowerversionoftheJDK.
ValidationintervalssothattcRuntimedoesn’thavetovalidateeverysingletimetheapplicationusestheconnection,whichimprovesperformance.
Run-Oncequery,whichisaconfigurablequerythattcRuntimerunsonlyoncewhentheconnectiontothedatabaseisestablished.Thisisveryusefultosetupsessionsettingsthatyouwanttoexistduringtheentiretimetheconnectionisestablished.
Abilitytoconfigurecustominterceptorstoenhancethefunctionalityofthedatasource.Youcanuseinterceptorstogatherquerystats,cachesessionstates,reconnecttheconnectionuponfailures,retryqueries,cachequeryresults,andsoon.TheinterceptorsaredynamicandnottiedtoaJDKversionofa java.sql / javax.sql interface.
Asynchronousconnectionretrieval-youcanqueueyourrequestforaconnectionandreceiveaFuture<Connection>back.
©CopyrightPivotalSoftwareInc,2013-2016 7 3.x
ConfiguringthetcRuntimeHigh-ConcurrencyJDBCDatasourceAswithanytcRuntimeresource,youconfigurethehigh-concurrencydatasource(thatis,thetcRuntimedatasource)usinga<Resource> childelementof<GlobalNamingResource> .MostattributesarecommontothestandardDBCPandthetcRuntimedatasources;however,thefollowingnewattributesapplyonlytothenewtcRuntimedatasource.
initSQL
jdbcInterceptors
validationInterval
jmxEnabled
fairQueue
useEquals
Usethe factory attributeofthe <Resource> elementtospecifythetypeofdatasource:
Setthe factory attributeto org.apache.tomcat.jdbc.pool.DataSourceFactory tousetheTomcatJDBChigh-concurrencydatasource.Thisisalsothedefaultvalueofthe factory attributefortcRuntime,soyouwillautomaticallyusethehigh-concurrencydatasourceifyoudonotspecifythisattributeatall.
Setthe factory attributeto org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory tousethestandardDBCPdatasource.
IBMJVMUSERSONLY:IfyouareusinganIBMJVM,seeuseEqualsforimportantinformation.
Thefollowingtableliststheattributesforconfiguringeitherthehigh-concurrencydatasourceorthestandardDBCPdatasource.Mostattributesarevalidforbothofthedatasources,butsomeareonlyvalidforonedatasource.Theseexceptionsarenotedinthetable.Thedefaultvaluesshownareforthehigh-concurrencydatasource,whichisthedefaultdatasourcefortcServer.DefaultvaluesfortheDBCPdatasourcemaybedifferent.SeetheApacheDBCPdocumentationfordetails.
Table1.ConnectionPoolConfigurationAttributes
username(required) TheusernametopasstotheJDBCdrivertoestablishaconnectionwiththedatabase.
password(required) ThepasswordtopasstotheJDBCdrivertoestablishaconnectionwiththedatabase.
url(required) TheconnectionURLtopasstotheJDBCdrivertoestablishaconnection.
driverClassName(required) ThefullyqualifiedJavaclassnameoftheJDBCdrivertouse.Thedrivermustbeaccessiblefromthesameclassloaderas tomcat-jdbc.jar
connectionProperties
ConnectionpropertiestosendtotheJDBCdriverwhenestablishinganewdatabaseconnection.Thesyntaxforthisstringis[propertyName=value;]*
The“user”and“password”propertiesarepassedexplicitly,sodonotincludethemhere.
defaultAutoCommit true
Thedefaultauto-commitstateofconnectionscreatedbythispool.Ifitisnotset,theJDBCdriver’sdefaultsettingisactive.
defaultReadOnly driverdefault
Thedefaultread-onlystateofconnectionscreatedbythispool.Ifnotset,the setReadOnly methodwillnotbecalled.(Somedriversdonotsupportreadonlymode,forexampleInformix.)
defaultTransactionIsolation driverdefault
ThedefaultTransactionIsolationstateofconnectionscreatedbythispool.Oneofthefollowing:
NONE
READ_COMMITTED
READ_UNCOMMITTED
REPEATABLE_READ
©CopyrightPivotalSoftwareInc,2013-2016 8 3.x
SERIALIZABLE
(seeJavadoc).Ifnotset,thedefaultistheJDBCdriver’sdefault.
defaultCatalog Thedefaultcatalogofconnectionscreatedbythispool.
initialSize 10Theinitialnumberofconnectionstocreatewhenthepoolisstarted.
maxActive 100
Themaximumnumberofactiveconnectionsthatcanbeallocatedfromthispoolatthesametime,ornegativefornolimit.
maxIdle maxActive (100)
Themaximumnumberofconnectionsthatshouldbekeptinthepoolatalltimes.Idleconnectionsarecheckedperiodically(ifenabled)andconnectionsthathavebeenidleforlongerthanminEvictableIdleTimeMillis arereleased.Seealso testWhileIdle .
minIdle 10
Theminimumnumberofestablishedconnectionsthatshouldbekeptinthepoolatalltimes.Theconnectionpoolcanshrinkbelowthisnumberifvalidationqueriesfail.Thedefaultvalueisderivedfrom initialSize .
maxWait 30000
Themaximummillisecondsapoolwithnoavailableconnectionswillwaitforaconnectiontobereturnedbeforethrowinganexception,or -1 towaitindefinitely.
validationQuery
TheSQLquerytousetovalidateconnectionsfromthispoolbeforereturningthemtothecaller.Ifspecified,thequerymustbeanSQLSELECTstatementthatreturnsatleastonerow.
testOnBorrow false
Indicateswhetherobjectsarevalidatedbeforeborrowedfromthepool.Iftheobjectfailstovalidate,itisdroppedfromthepool,andanattemptismadetoborrowanother.
A true valuehasnoeffectunlessthe validationQueryparameterissettoanon-nullstring.
testOnReturn false
Indicatesifobjectsarevalidatedbeforetheyarereturnedtothepool.
Atruevaluehasnoeffectunlessthe validationQueryparameterissettoanon-nullstring.
testWhileIdle false
Indicateswhetherobjectsarevalidatedbytheidleobjectevictor(ifany).Ifanobjectfailstovalidate,itisdroppedfromthepool.
A true valuehasnoeffectunlessthe validationQueryparameterissettoanon-nullstring.Thisparametermustbesettoactivatethepooltest/cleanerthread.
timeBetweenEvictionRunsMillis 5000
Thenumberofmillisecondstosleepbetweenrunsoftheidleobjectevictorthread.Thethreadchecksforidle,abandonedconnectionsandvalidatesidleconnections.Thevalueshouldnotbesetbelow1second(1000).
numTestsPerEvictionRunNotusedbytheTomcatJDBCpool.Thenumberofobjectstoexamineduringeachrunoftheidleobjectevictorthread,ifany.
Theminimumamountoftimeanobjectmaysitidle
©CopyrightPivotalSoftwareInc,2013-2016 9 3.x
minEvictableIdleTimeMillis 60000 inthepoolbeforeitiseligibleforevictionbytheidleobjectevictor,ifany.
connectionInitSqls null
ACollectionofSQLstatementsusedtoinitializephysicalconnectionswhentheyarefirstcreated.Thesestatementsareexecutedonlyonce,whentheconnectionfactorycreatestheconnection.
DBCPVersions1.3and1.4ofincorrectlyuse“initConnectionSqls ”asthenameofthispropertyforJNDIobjectfactoryconfiguration.Until1.3.1/1.4.1arereleased,“ initConnectionSqls ”mustbeusedasthenameforthispropertywhenusingBasicDataSourceFactorytocreateBasicDataSourceinstancesviaJNDI.
poolPreparedStatements false Thispropertyisnotused.
maxOpenPreparedStatements Thispropertyisnotused.
accessToUnderlyingConnectionAllowed
Notused.Accesscanbeachievedbycallingunwrap onthepooledconnection.Seejavax.sql.DataSource interface,orcallgetConnection throughreflection,orcasttheobjectas javax.sql.PooledConnection .
removeAbandoned false
Setto true toremoveabandonedconnectionsiftheyexceedthe removeAbandonedTimeout .Settingthisto true canrecoverdatabaseconnectionsfrompoorlywrittenapplicationsthatfailtocloseaconnection.Aconnectionisconsideredabandonedandeligibleforremovalifithasbeenidlelongerthanthe removeAbandonedTimeout .
removeAbandonedTimeout 60
Timeoutinsecondsbeforeanabandonedconnectioncanberemoved.Thevalueshouldbesettothelongestrunningqueryyourapplicationsmighthave.
logAbandoned false
Setto true tologstacktracesforapplicationcodethatabandonsaConnection.LogginganabandonedConnectionaddsoverheadforeveryConnectionopenbecauseastacktracehastobegenerated.
initSQL(highconcurrencyJDBCdatasourceonly)
InitialSQLstatementthatisrunonlywhenaconnectionisfirstcreated.Usethisfeaturetosetupsessionsettingsthatshouldexistduringtheentiretimetheconnectionisestablished.
jdbcInterceptors(highconcurrencyJDBCdatasourceonly)
null
Semicolon-separatedlistofclassnamesextendingorg.apache.tomcat.jdbc.pool.JdbcInterceptor
.tcRuntimeinsertsinterceptorsinthechainofoperationsonthe java.sql.Connection object.
Warning:Besureyoudonotincludeanywhitespace(suchasspacesortabs)inthevalueofthisattribute,ortheclasseswillnotbefound.
Predefinedinterceptors:
org.apache.tomcat.jdbc.pool.interceptor .ConnectionState -keepstrackofautocommit,readonly,catalogandtransactionisolationlevel.
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer
-keepstrackofopenedstatements,andclosesthemwhentheconnectionisreturnedtothepool.
©CopyrightPivotalSoftwareInc,2013-2016 10 3.x
validationInterval(highconcurrencyJDBCdatasourceonly)
30000 (30seconds)
NumberofmillisecondstcRuntimewaitsbeforerunningavalidationchecktoensurethattheJDBCconnectionisstillvalid.Aconnectionthathasbeenvalidatedwithinthisintervalisnotrevalidated.Runningvalidationcheckstoofrequentlycanslowperformance.
jmxEnabled(highconcurrencyJDBCdatasourceonly)
trueSpecifieswhethertheconnectionpoolisregisteredwiththeJMXserver.
fairQueue(highconcurrencyJDBCdatasourceonly)
true
Specifieswhethercallsto getConnection()shouldbetreatedfairlyinatrueFIFO(firstin,firstout)fashion.Thisensuresthatthreadsreceiveconnectionsintheordertheyarrive.Itusestheorg.apache.tomcat.jdbc.pool. FairBlockingQueue implementationtomanagethelistofidleconnections.Thisfeaturemustbeenabled(thatis,settheattributeto true )tousetheasynchronousconnectionretrievalfeature,whichistheabilitytoqueueyourconnectionrequest.
Note:When fairQueue=true andtheoperatingsystemisLinux,thereisaverylargeperformancedifferenceinhowlocksandlockwaitingisimplemented.TodisablethisLinux-specificbehaviorandstillusethefairqueue,addtheproperty org.apache.tomcat.jdbc.pool. FairBlockingQueue.ignoreOS=true toyoursystempropertiesbeforetheconnectionpoolclassesareloaded.
abandonWhenPercentageFull 0
Connectionsthathavebeenabandoned(timedout)arenotclosedandreportedupunlessthenumberofconnectionsinuseisabovethepercentagedefinedbythisparameter.Thevalueshouldbebetween0and100.Thedefaultvalueis0,whichimpliesthatconnectionsareeligibleforclosureassoonas removeAbandonedTimeout hasbeenreached.
maxAge 0
Timeinmillisecondstokeepthisconnection.Whenaconnectionisreturnedtothepool,thepoolcheckstoseeifthenow -time-when-connected > maxAge hasbeenreached,andifso,itclosestheconnectionratherthanreturningittothepool.Thedefaultvalueis0,whichimpliesthatconnectionsareleftopenandnoagecheckisdoneuponreturningtheconnectiontothepool.
useEquals(highconcurrencyJDBCdatasourceonly)
false
SpecifieswhethertheProxyConnectionclassshoulduseString.equals()insteadof“==”whencomparingmethodnames.Doesnotapplytoaddedinterceptorsasthoseareconfiguredindividually.
NOTEFORIBMJVMUSERS:IfyouarerunningtcRuntimeonaplatformthatusestheIBMJVM(suchasAIX),alwayssetthe useEquals attributeto true ifyouwantahigh-concurrencyconnectionpooltoworkcorrectly.IBMJVMsdonotuseStringliteralpoolsformethodnames,whichmeansyoualwayswanttouse String.equals() whencomparingmethodnamesinthiscase.
Timeoutvalueinseconds.SimilartoremoveAbandonedTimeout butinsteadoftreatingtheconnectionasabandonedandpotentially
©CopyrightPivotalSoftwareInc,2013-2016 11 3.x
suspectTimeout 0
closingtheconnection,thissimplylogsthewarningif logAbandoned issettotrue.Ifthisvalueisequalorlessthan0,nosuspectcheckingwillbeperformed.Suspectcheckingonlytakesplaceifthetimeoutvalueislargerthan0andtheconnectionwasnotabandonedorifabandoncheckisdisabled.IfaconnectionissuspectaWARNmessageisloggedandaJMXnotificationissentonce.
alternateUsernameAllowed false
Forperformancereasons,bydefaulttheJDBCpoolignorestheDataSource.getConnection(username, password)
callandreturnsapreviouslypooledconnectionestablishedusingthegloballyconfiguredpropertiesusername and password .Thepoolcan,however,beusedwithdifferentcredentialseachtimeaconnectionisused.Ifyourequestaconnectionwiththecredentialsuser1/password1andtheconnectionwaspreviouslyconnectedusinguser2/password2,theconnectionisclosed,andreopenedwiththerequestedcredentials.Thisway,thepoolsizeisstillmanagedonagloballevel,andnotonaperschemalevel.ToenablethefunctionalitydescribedinDataSource.getConnection(username,password)
,settheproperty alternateUsernameAllowed totrue .
Thefollowing server.xml snippetshowshowtoconfigurethehigh-concurrencyJDBCdatasourceforyourtcRuntimeinstance.YoucanaddthisdatasourcetoatcServerRuntimeinstancebyincludingthediagnosticstemplateinthe tcruntime-instancecreate commandline.Foranexplanationofthefollowingexample,seeDescriptionoftheHighConcurrencyJDBCDatasource.
<?xmlversion='1.0'encoding='utf-8'?><Serverport="-1"shutdown="SHUTDOWN">
...
<GlobalNamingResources>
<Resourcename="jdbc/TestDB"auth="Container"type="javax.sql.DataSource"username="root"password="password"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"
testWhileIdle="true"testOnBorrow="true"testOnReturn="false"validationQuery="SELECT1"validationInterval="30000"timeBetweenEvictionRunsMillis="5000"maxActive="100"minIdle="10"maxWait="10000"initialSize="10"removeAbandonedTimeout="60"removeAbandoned="true"logAbandoned="true"minEvictableIdleTimeMillis="30000"jmxEnabled="true"jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmx(threshold=10000)"/>
</GlobalNamingResources>...<Servicename="Catalina">...</Service></Server>
©CopyrightPivotalSoftwareInc,2013-2016 12 3.x
DescriptionoftheTomcatHighConcurrencyJDBCDatasourceIntheprecedingsample server.xml ,the <Resource> elementdoesnotincludea factory attribute,whichmeansthattheresourceisusingthedefaultvalue, org.apache.tomcat.jdbc.pool.DataSourceFactory ,thetcRuntimehigh-concurrencydatasource.The <Resource> elementattributesintheexamplefunctionasfollows:
name .JNDInameofthisJDBCresourceis jdbc/TestDB .
auth .Thecontainersignsontotheresourcemanageronbehalfoftheapplication.
type .ThisresourceisaJDBCdatasource.
username, password .Nameandpasswordofthedatabaseuserwhoconnectstothedatabase.
driverClassName .tcRuntimeshouldusethe com.mysql.jdbc.Driver JDBCdrivertoconnecttothedatabase,inthiscaseaMySQLdatabase.
url .URLthattheJDBCdriverusestoconnecttoaMySQLdatabase.TheformatofthisURLisspecifiedbyJDBC.
testXXX attributes.tcRuntimevalidatesobjectsbeforeitborrowsthemfromtheconnectionpoolandthoseobjectsarevalidatedbytheidleobjectevictor,butthattcRuntimedoesnotvalidateobjectswhenitreturnsthemtothepool.
validationQuery .tcRuntimerunstheverysimpleSQLquery SELECT 1 whenitvalidatesconnectionsfromthepoolbeforereturningaconnectiontoauseruponrequest.Becausethisqueryshouldalwaysreturnavalue,ifitreturnsanexceptionthentcRuntimeknowsthereisaproblemwiththeconnection.
validationInterval .tcRuntimewaitsatleast30secondsbeforerunningavalidationquery.
timeBetweenEvictionRunsMillis .tcRuntimesleeps5000millisecondsbetweenrunsoftheidleconnectionvalidation/cleanerthread.
maxActive .tcRuntimeallocatesamaximumof100activeconnectionsfromthispoolatthesametime
minIdle .tcRuntimekeepsaminimumof10establishedconnectionsinthepoolatalltimes.
maxWait .Wherenoconnectionsareavailable,tcRuntimewaitsamaximumof10,000millisecondsforaconnectiontobereturnedbeforethrowinganexception.
initialSize .tcRuntimecreates10connectionswhenitinitiallystartstheconnectionpool.
removeAbandonedTimeout .tcRuntimewaits60secondsbeforeitremovesanabandoned,butstillinuse,connection.
removeAbandoned .tcRuntimeremovesabandonedconnectionsaftertheyhavebeenidleforthe removeAbandonedTimeout amountoftime.
logAbandoned .tcRuntimeflagstologstacktracesforapplicationcodethatabandonedaConnection.
minEvictableIdleTimeMillis .MinimumamountoftimeanobjectmaysitidleinthepoolbeforeitiseligibleforevictiononthistcRuntimeis30,000milliseconds.
jmxEnabled .ThistcRuntimecanbemonitoredusingJMX.YoumustsetthisattributetotrueifyouwantHQtomonitortheresource.
jdbcInterceptors .Listofinterceptorclassesassociatedwiththisdatasource.
ForcompletedocumentationaboutthetcRuntime server.xml fileandallthepossibleXMLelementsyoucaninclude,seeApacheTomcatConfigurationReference .
ConfiguringSSLWhenyouconfigureSSL(securesocketlayer)fortcRuntime,useoneofthefollowingframeworks:
TheSSLframeworkprovidedbyJavaSESecurity(JSSE),whichisincludedintheJDKandavailabletoyoubydefault.
OpenSSL ,whichiswhattcRuntimeuseswhenyouusetheApachePortableRuntime(APR)library.APRlibrariesprovideapredictableandconsistentinterfacetounderlyingplatform-specificimplementations.UseofAPRprovidessuperiorscalability,performance,andbetterintegrationwithnativeservertechnologies.TheAPRlibrariesareusuallyinstalledbydefaultonUnixversionsoftcRuntime;youmustdownloadthelibrariesforotherplatforms.
tcServerincludestemplatesthatmakeitsimpletoconfigureatcRuntimeinstancewithSSLwhenyoucreatetheinstance.ChooseoneoftheSSLtemplates— apr-ssl , bio-ssl ,or nio-ssl —basedonthetypeofI/Oyouwanttouse.Youcanalsousethe jmx-ssl templatetoconfigureSSLfortheJMXconnector.See“CreatingaRuntimeInstancewithaTemplate”inGettingStartedwithPivotaltcServerforhelpusingthetemplates.
Thefollowingsnippetofasample server.xml fileisequivalenttousingthe bio-ssl templatetocreateaninstance.Itbuildsonthesimpleout-of-the-boxconfigurationfilebyaddingSSLcapabilitiestotcRuntimesothatuserscanmakeasecureconnectiontodeployedapplicationsoverHTTPS.AddSSLtotcRuntimebyaddinga <Connector> childXMLelementtothe <Service> element,alongsidetheexistingconnectorthatconfiguresthenon-SSL-enabledHTTPport.ThisnewconnectorisconfiguredforadifferentTCP/IPportthantheregularnon-SSLport;userswhospecifytheSSLportenableSSLhandshake,encryption,anddecryptionduringtheirconnection.
SeeDescriptionoftheSSLConnectorfordetailedinformationaboutthisnew <Connector> element.ThisXMLsnippetusestheSSLframeworkprovidedbyJSSE;foranexampleofaconnectorthatusesAPR,seeUsinganAPRConnectortoConfigureSSL.
©CopyrightPivotalSoftwareInc,2013-2016 13 3.x
<Connectorexecutor="tomcatThreadPool"port="8443"protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443"acceptCount="100"maxKeepAliveRequests="15"keystoreFile="${catalina.base}/conf/tcserver.keystore"keystorePass="changeme"keyAlias="tcserver"SSLEnabled="true"scheme="https"secure="true"/>
DescriptionoftheSSLConnectorTheprecedingsnippetof server.xml describesanewSSL-enabled <Connector> thatusestheJSSElibrariesincludedintheJDK.Theattributevaluesintheexamplefunctionasfollows:
executor , protocol , connectionTimeout , maxKeepAliveRequests , acceptCount .SameattributesasthoseofthebasicHTTPconnector.AlthoughthisconnectorisusedforHTTPSconnections,youstillsetprotocolto HTTP/1.1 ;otherattributesspecifyanSSL-enabledconnection.
port .TheTCP/IPportthatusersspecifyasthesecureconnectionportis8443.Setthevalueofthe redirectPort attributeofyournon-SSLconnectorstothisvaluetoensurethatuserswhorequireasecureconnectionareredirectedtothesecureport,eveniftheyinitiallystartatthenon-secureport.
SSLEnabled .SpecifiesthatSSLisenabledforthisconnector.
secure .Ifsetto true ,ensuresthatacallto request.isSecure() fromtheconnectingclientalwaysreturns true .Defaultis false .
scheme .Ifsetto https ,ensuresthatacallto request.getScheme() fromtheconnectingclientreturns https whenclientsusethisconnector.Thedefaultvalueofthisattributeis http .
keystoreFile .Nameofthefilethatcontainstheserver’sprivatekeyandpubliccertificateusedintheSSLhandshake,encryption,anddecryption.Youuseanaliasandpasswordtoaccessthisinformation.Intheexample,thisfileiscalled tcserver.keystore andislocatedinthesamedirectoryasthestandardtcRuntimeconfigurationfiles: CATALINA_BASE/conf .SeeCreatingaSimpleKeystoreFileforinformationaboutcreatingthekeystorefile.
keyAlias and keystorePass .Aliasandpasswordtoaccessthekeystorespecifiedbythe keystoreFile attribute.Intheexample,thealiasis tcserver andthepasswordis changeme .
ForcompletedocumentationaboutconfiguringSSLfortcRuntimeservers,seeSSLConfigurationHOW-TO .
ForgeneraldocumentationaboutthetcRuntime server.xml fileandallthepossibleXMLelementsyoucaninclude,seeApacheTomcatConfigurationReference .
UsinganAPRConnectortoConfigureSSLWhenyouuseanAPRconnectortospecifyasecuretcRuntimeport,tcRuntimeusestheOpenSSLframework,meaningthatyouwillbeusinganSSLenginenativetoyourplatformratherthantheoneincludedinJSSE.Usethe apr-ssl templatewith tcruntime-instance scripttocreateatcRuntimeinstanceconfiguredtouseOpenSSL.Thissectiondescribesconfigurationchangesthataremadeforyouwhenyouusethe apr-ssl template.
Beforeconfiguringtheconnector,addtheAPRlistenertoyour server.xml fileinthe <Listener> element:
<ListenerclassName="org.apache.catalina.core.AprLifecycleListener"SSLEngine="on"/>
TheprecedingelementinitializesthenativeSSLengine.The <Connector> elementenablestheuseofthisengineintheconnectorwiththe SSLEnabledattribute,asshowninthefollowingsample:
©CopyrightPivotalSoftwareInc,2013-2016 14 3.x
<Connectorexecutor="tomcatThreadPool"port="8443"protocol="org.apache.coyote.http11.Http11AprProtocol"connectionTimeout="20000"redirectPort="8443"acceptCount="100"maxKeepAliveRequests="15"SSLCertificateFile="${catalina.base}/conf/tcserver.crt"SSLCertificateKeyFile="${catalina.base}/conf/tcserver.key"SSLPassword="changeme"SSLEnabled="true"scheme="https"secure="true"/>
ThisconnectorconfigurationissimilartotheonethatusestheJSSESSLlibraries,asdescribedinDescriptionoftheSSLConnector,butwiththefollowingdifferences,mostlyhavingtodowiththeconfigurationofOpenSSL:
Thevalueofthe protocol attributeis org.apache.coyote.http11.Http11AprProtocol ,ratherthan HTTP/1.1 ,toindicatethattheconnectorisusingtheAPRlibraries.
The SSLCertificateFile attributespecifiesthenameofthefilethatcontainstheservercertificate.TheformatisPEM-encoded.Intheexample,thisfileiscalled tcserver.crt ,andislocatedintheconfdirectoryunderthe CATALINA_BASE directoryinwhichyourtcRuntimeinstanceisinstalled.
The SSLCertificateKeyFile attributespecifiesthenameofthefilethatcontainstheserverprivatekey.TheformatisPEM-encoded.Intheexample,thefileiscalled tcserver.key andislocatedinthesamedirectoryasthecertificatefile.
The SSLPassword attributespecifiesthepasswordfortheencryptedprivatekeyinthefilepointedtobytheSSLCertificateKeyFile attribute.
Theprecedingattributesareusedinsteadofthe keystoreFile , keystorePass ,and keyAlias attributesoftheJSSEsecureconnector.
SeeApachePortableRuntime(APR)basednativelibraryforTomcat foradditionalinformationaboutAPRandhowtoconfigureanAPRHTTPSconnector.
CreatingaSimpleKeystoreFileForBothSSLandOpenSSLConfiguringSSLorOpenSSLfortcRuntimerequiresakeystorethatcontainscertificatesandpublickeys.Thecertificateidentifiesthecompanyororganizationandverifiesthepublickey.ClientsthatconnecttotcRuntimeusethepublickeytoencryptanddecryptdatatransferredoverthewire.
If,whenyouoriginallycreatedyourtcRuntimeinstance,youusedthe -t optionofthe tcruntime-instance.sh|bat scripttospecifyoneoftheSSLtemplates(suchas bio-ssl or nio-ssl ),thenthescriptgeneratedakeystoreforyouandconfigureditspropertiesinthe server.xml file.Thecertificateinthekeystorecontainsdefaultinformation.Ifyouusedthe --interactive optionof tcruntime-instance.sh|bat ,thenyoualsocustomizedthecertificatewithinformationaboutyourorganization.The quickstart/createInstance.sh|bat scriptalsoperformsallthesetasksforyou.
Additionally,thekeystoresgeneratedbythe tcruntime-instance and quickstart/createInstance scriptsuseself-signedcertificatesthat,althoughtheydonotguaranteeauthenticity,canbeusedbyboththeclientsandservertoencryptanddecryptdata.
If,however,youwanttogenerateanewkeystore,usethe keytool JDKtool,asshownbelow.Itwillalsocreateakeystorethatcontainsself-signedcertificates.Ifyourequireanauthentic,verifiedcertificate,purchaseonefromawell-knownCertificateAuthoritysuchasVeriSign.Thenusethe keytool
tooltoimportthecertificateintoyourkeystore.
Forcompletedocumentationaboutcreatingkeystores,inparticularhowtoimportafullyauthenticcertificateintoanexistingkeystore,seeSSLConfigurationHOW-TO .
Tousethe keytool tooltocreateakeystorethatcontainsself-signedcertificates:
prompt>$JAVA_HOME/bin/keytool-genkey-aliasalias-keyalgRSA-keystorekeystore
Besurethatthevalueofthe -alias optionmatchesthevalueofthe keyAlias attributeofthesecureConnectoryouconfiguredinthe server.xml file,asdescribedintheprecedingsection.Similarly,thevalueofthe -keystore optionshouldmatchthevalueofthe keystoreFile attribute.Forexample:
prompt>$JAVA_HOME/bin/keytool-genkey-aliastcserver-keyalgRSA-keystore\/var/opt/pivotal-tc-server-standard/myinstance/conf/tcserver.keystore
Intheexample, CATALINA_BASE isassumedtobe /var/opt/pivotal-tc-server-standard/myinstance .
Amessageasksforakeystorepassword;thispasswordmustmatchthe keystorePass attributeofthe <Connector> elementthatconfiguresthesecureport,asdescribedintheprecedingsection.Afterpromptsforinformationaboutyourcompany,amessagerequeststhepasswordforthekeystorealias;setthis
©CopyrightPivotalSoftwareInc,2013-2016 15 3.x
tothesamevalueasthekeystorepassword.
UsingtheApachePortableRuntime(APR)TheApachePortableRuntime(APR)isasetoflibrariesandAPIsthatmapdirectlytoyourunderlyingoperatingsystem.tcRuntimecanuseAPRtoprovideadditionalscalabilityandperformancebecauseofhigh-qualityintegrationwithnativeservertechnologies.APRprovidesaccesstoadvancedIOfunctionality(suchassendfile,epollandOpenSSL),OSlevelfunctionality(randomnumbergeneration,systemstatus,etc.),andnativeprocesshandling(sharedmemory,NTpipesandUnixsockets).
TheAPRlibrariesareautomaticallyinstalledinmostUnixplatforms,althoughyouneedtocompiletheJavaNativeInterface(JNI)wrappers.Forotherplatforms,suchasWindows,youmustdownloadandinstallthelibraries.SeeApachePortableRuntime(APR)NativeLibraryforTomcat .
AddtheAPRlibrariestothe LD_LIBRARY_PATH (Unix)or PATH (Windows)environmentvariableusedbythetcRuntimeprocesssothattcRuntimecanaccessthelibrarieswhenitruns.
Thefollowingsample server.xml fileshowshowtoconfiguretcRuntimetouseAPR.Thefilebuildsonthesimpleout-of-the-boxconfigurationdescribedinSimpletcRuntimeConfiguration.
SeeComparingtheAPR-Enabledserver.xmlFilewithOut-of-the-Boxserver.xmlforinformationabouthowthetwofilesdiffer.
©CopyrightPivotalSoftwareInc,2013-2016 16 3.x
<?xmlversion='1.0'encoding='utf-8'?><Serverport="-1"shutdown="SHUTDOWN">
<ListenerclassName="org.apache.catalina.core.AprLifecycleListener"SSLEngine="on"/><ListenerclassName="org.apache.catalina.core.JasperListener"/><ListenerclassName="org.apache.catalina.mbeans.ServerLifecycleListener"/><ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<GlobalNamingResources><Resourcename="UserDatabase"auth="Container"type="org.apache.catalina.UserDatabase"description="Userdatabasethatcanbeupdatedandsaved"factory="org.apache.catalina.users.MemoryUserDatabaseFactory"pathname="conf/tomcat-users.xml"/></GlobalNamingResources>
<Servicename="Catalina">
<Executorname="tomcatThreadPool"namePrefix="tomcat-http--"maxThreads="300"minSpareThreads="50"/>
<Connectorexecutor="tomcatThreadPool"port="8080"protocol="org.apache.coyote.http11.Http11AprProtocol"connectionTimeout="20000"redirectPort="8443"acceptCount="100"maxKeepAliveRequests="15"/>
<Connectorexecutor="tomcatThreadPool"port="8443"protocol="org.apache.coyote.http11.Http11AprProtocol"connectionTimeout="20000"redirectPort="8443"acceptCount="100"maxKeepAliveRequests="15"SSLCertificateFile="${catalina.base}/conf/tcserver.crt"SSLCertificateKeyFile="${catalina.base}/conf/tcserver.key"SSLPassword="changeme"SSLEnabled="true"scheme="https"secure="true"/>
<Enginename="Catalina"defaultHost="localhost">
<RealmclassName="org.apache.catalina.realm.UserDatabaseRealm"resourceName="UserDatabase"/>
<Hostname="localhost"appBase="webapps"unpackWARs="true"autoDeploy="true"deployOnStartup="true"deployXML="true"xmlValidation="false"xmlNamespaceAware="false"></Host></Engine></Service></Server>
ComparingtheAPR-Enabledserver.xmlFilewithOut-of-the-Boxserver.xmlIntheprecedingsample server.xml ,mostoftheconfigurationisthesameasthenon-APRenabled server.xml fileexceptforthefollowing:
Thepreceding server.xml fileincludesanadditionalAPR-specificlistener,implementedbytheorg.apache.catalina.core.AprLifecycleListener class.The SSLEngine="on" attributeenablesthenativeSSLengine,ratherthantheJSEEengineprovidedbytheJDK.
The protocol="org.apache.coyote.http11.Http11AprProtocol" attributeofthe <Connector> elementsspecifythatthetwoHTTPconnectors(withandwithoutSSLenabled)bothusethenativeHTTPprotocolimplementation.
SeeConfiguringSSLfordetailsaboutconfiguringthenativeSSLconnector.
ForcompletedocumentationaboutthetcRuntime server.xml fileandallthepossibleXMLelementsyoucaninclude,seeApacheTomcatConfigurationReference .
©CopyrightPivotalSoftwareInc,2013-2016 17 3.x
ConfiguringFIPS-140ModeForatcRuntimeInstanceYoucanconfigureatcRuntimeinstancetorunwithaFIPS-140compliantJavaSecureSocketExtension(JSSE)provider,asdescribedinthissection.
Important:CompletingtheseproceduresdonotresultinatcRuntimeinstancethatisFIPS-140compliant,onlythattheinstanceisusingaFIPS-140compliantJSSEprovider.
FIPS-140referstotheFederalInformationProcessingStandardization140,whichisastandardthatspecifiessecurityrequirementsforcryptographicmodulesusedbytheU.S.Government.FIPS140-2accreditation(themostcurrentlevel)isrequiredforanycryptographyproductsoldbyaprivatesectorcompanytotheU.S.Government.
TheinstructionsdifferdependingonwhetheryouwanttoconfigureaBIOorNIOConnectororAPRConnectorforyourtcRuntimeinstance.
ConfiguringFIPS-140ModeforBIOandNIOConnectorsToconfigureFIPS-140modefortcRuntimeinstancesthatusetheBIOorNIOConnectors,youmustfirstinstallaJavaCryptographyExtension(JCE)APIprovider,suchasRSABSAFE®Crypto-J.ThissectionusestheRSAJCEprovideronlyasanexample;youcanuseanycompliantprovideryouwant.
Procedure1. InstalltheJCEAPIimplementation,suchasRSABSAFECrypto-J,onthesamecomputeronwhichyouhaveinstalledPivotaltcServer.Followthe
installationinstructionsoftheJCEprovider.Inthisprocedure,itisassumedyouinstalledRSABSAFECrypto-Jinthe $CRYPTOJ_HOME directory.
2. FromthecomputeronwhichyouinstalledPivotaltcServer,openaterminalwindowastheuserwhowillcreateandruntcRuntimeinstances(suchas tcserver ).
3. StaticallyregistertheCyrpto-JJCEproviderbycopyingthe $CRYPTOJ_HOME/cryptoj/lib/cryptojFIPS.jar JARfiletothe $JAVA_HOME/jre/lib/ext directory.Forexample:
prompt$cp$CRYPTOJ_HOME/cryptoj/lib/cryptojFIPS.jar$JAVA_HOME/jre/lib/ext
4. Editthe $JAVA_HOME/lib/security/java.security fileasfollows:ConfiguretheCrypto-JJCEprovidertobethedefaultproviderbyaddingthefollowingline:
security.provider.1=com.rsa.jsafe.provider.JsafeJCE
Ifothersecurityprovidersarealreadyconfiguredwiththisproperty,changetheiridentifyingnumberssothattheyareunique,asshowninthefollowingexample:
security.provider.1=com.rsa.jsafe.provider.JsafeJCEsecurity.provider.2=sun.security.provider.Sun
AddthefollowingpropertiesasrequiredspecificallybytheCrypto-JJCEprovider:
com.rsa.cryptoj.fips140initialmode=FIPS140_MODEcom.rsa.cryptoj.kat.strategy=on.load
5. IfyouareusingtheevaluationmodeoftheRSABSAFECrypto-Jmodule,installtheRSAevaluationlicenseasshown:
prompt$cp$CRYPTOJ_HOME/cryptoj/lib/rsamisc.jar$JAVA_HOME/jre/lib/ext
6. CreateanSSL-enabledtcRuntimeinstancethatuseseithertheBIOorNIOConnectorbyspecifyingeitherthe bio-ssl or nio-ssl templatewhenrunningthe tcrutnime-instance.sh script.Forexample,ifyouinstalledtcServerin /opt/pivotal/pivotal-tc-server-standard andyourinstancesarelocatedin/var/opt/pivotal/pivotal-tc-server-standard :
prompt$cd/opt/pivotal/pivotal-tc-server-standardprompt$./tcruntime-instance.shcreatessl-instance-tbio-ssl-i/var/opt/pivotal/pivotal-tc-server-standard
7. Starttheinstance:
prompt$./tcruntime-ctl.sh-n/var/opt/pivotal/pivotal-tc-server-standardssl-instancestart
©CopyrightPivotalSoftwareInc,2013-2016 18 3.x
8. Checkthe logs/catalina-date.log filetoensurethattheinstancestartedcorrectly;youshouldseemessagessimilartothefollowing:
26-Jan-201210:11:14.477INFO[main]org.apache.coyote.AbstractProtocol.initInitializingProtocolHandler["http-bio-8443"]26-Jan-201210:11:15.603INFO[main]org.apache.coyote.AbstractProtocol.startStartingProtocolHandler["http-bio-8443"]
ConfiguringFIPS-140ModeforanAPRConnectorYoucanusetheApacheTomcatnativelibrariesprovidedbyPivotalWebServertoconfigureFIPS-140modeforatcRuntimeinstancethatusestheAPRlifecyclelistener.
Intheprocedure,youwilldownloadandunzipthePivotalWebServerdistribution,butyoudonotactuallycreateorstartWebServerinstances.Rather,youunziptheWebServerdistributiononlytogainaccesstosomeofitsnativecomponents.ThismeansyouwillnotconsumeanyPivotalWebServerlicenses.
Important:Currently,onlyversion5.0.2+ofWebServerincludestherequirednativecomponents;version5.1.0doesnotincludethem.CheckthePivotalWebServerReleaseNotes toseeiflater5.1.Xmaintenancereleasesincludetherequirednativecomponents.Iftheydonot,youmustdownloadandunzipversion5.0.2+ofPivotalWebServer.
Prerequisites
DownloadandunzipPivotalWebServeronthesamecomputerwherePivotaltcServerisinstalled:
1. OpenaterminalwindowandcreatethedirectoryinwhichyouwillunzipthePivotalWebServerdistribution.Forexample:
prompt$mkdir/var/opt/pivotal
2. DownloadtheappropriatePivotalWebServerself-extractingZIPfromthePivotalDownload Websiteandplaceitinthedirectoryyoucreated.Besuretochoosethecorrectoperatingsystemandchiparchitecture.
3. Fromyourterminalwindow,changetothedirectoryinwhichyoudownloadedtheZIPfile:
prompt$cd/var/opt/pivotal
4. Ifnecessary,changethepermissionsofthedownloadedZIPfiletomakeitexecutable.Forexample,onUnix:
prompt$chmod755pivotal-web-server-version-x86_64-linux-glibc2.zip.sfx
5. Self-extractthefilesfromthedownloadedZIPbyusingthefilenameasacommand.Forexample:
prompt$./pivotal-web-server-version-x86_64-linux-glibc2.zip.sfx
Whenitcompletes,thePivotalWebServerfilesarelocatedinthe pivotal-web-server subdirectory.Forclarity,thisdirectory( /var/opt/pivotal/pivotal-web-server )isreferredtoas $VFWS_HOME intheremainderoftheprocedure.
Procedure1. FromthecomputeronwhichyouinstalledPivotaltcServer,openaterminalwindowastheuserwhowillcreateandruntcRuntimeinstances(such
as tcserver ).
2. CreateatcRuntimeinstancethatusesthe apr-ssl template.Forexample,ifyouinstalledtcServerin /opt/pivotal/pivotal-tc-server-standard andyourinstancesarelocatedin /var/opt/pivotal/pivotal-tc-server-standard :
prompt$cd/opt/pivotal/pivotal-tc-server-standardprompt$./tcruntime-instance.shcreateapr-ssl-instance-tapr-ssl-i/var/opt/pivotal/pivotal-tc-server-standard
3. Editthe bin/setenv.sh fileintheinstancedirectoryandaddthefollowingtwolines:
LD_LIBRARY_PATH="$VFWS_HOME/httpd-2.2/lib/"exportLD_LIBRARY_PATH
©CopyrightPivotalSoftwareInc,2013-2016 19 3.x
Intheprecedingsample, $VFWS_HOME referstothedirectoryinwhichyouinstalledPivotalWebServer,suchas /var/opt/pivotal/pivotal-web-server .ThetcRuntimeinstancedirectoryinourexampleis /var/opt/pivotal/pivotal-tc-server-standard/apr-ssl-instance .
4. Editthe conf/server.xml configurationfileinthetcRuntimeinstancedirectoryandaddthe FIPSMode="on" attributetothe AprLifecycleListener<Listener/> element,asshown:
<ListenerSSLEngine="on"FIPSMode="on"className="org.apache.catalina.core.AprLifecycleListener"/>
5. Starttheinstance:
prompt$./tcruntime-ctl.sh-n/var/opt/pivotal/pivotal-tc-server-standardapr-ssl-instancestart
6. Checkthe logs/catalina-date.log filetoensurethattheinstancestartedcorrectly;youshouldseemessagessimilartothefollowing:
15-Feb-201216:04:34.973INFO[main]org.apache.catalina.core.AprLifecycleListener.initLoadedAPRbasedApacheTomcatNativelibrary1.1.22.15-Feb-201216:04:34.973INFO[main]org.apache.catalina.core.AprLifecycleListener.initAPRcapabilities:IPv6[true],sendfile[true],acceptfilters[false],random[true].15-Feb-201216:04:35.002INFO[main]org.apache.catalina.core.AprLifecycleListener.initializeSSLInitializingFIPSmode...15-Feb-201216:04:35.223INFO[main]org.apache.catalina.core.AprLifecycleListener.initializeSSLSuccessfullyenteredFIPSmode15-Feb-201216:04:35.243INFO[main]org.apache.coyote.AbstractProtocol.initInitializingProtocolHandler["http-apr-8443"]
ConfiguringLoggingfortcRuntimeAswithstandardApacheTomcat,PivotaltcRuntimeusesCommonsLogging throughoutitsinternalcode.Thisallowsyoutochoosealoggingconfigurationthatsuitsyourneeds,suchas java.util.logging (configuredbydefault)or log4j .CommonsLoggingprovidestcRuntimewiththeabilitytologhierarchicallyacrossvariousloglevelswithoutneedingtorelyonaparticularloggingimplementation.
ThesectionsthatfollowsummarizethebasicinformationinthestandardApacheTomcatloggingdocumentation(seeLogginginTomcat ).ThesesectionsalsodescribetheadditionalloggingfeaturesoftcRuntimeascomparedtothedefaultlogginginApacheTomcat,suchasasynchronouslogging.
ConfiguringtheJULIImplementationofjava.util.logging
LoggingLevelsforjava.util.logging
ConfiguringAsynchronousLogging
Configuringlog4j
UpdatingLoggingParametersDynamically
ConfiguringtheJULIImplementationofjava.util.loggingPivotaltcRuntimeprovidesitsownimplementationof java.util.logging calledJULIthataddressesamajorlimitationoftheJDKimplementation:theinabilitytoconfigureper-Webapplicationlogging.TheJULIimplementationisthedefaultloggingframeworkintcRuntime.
Note:Itisassumedthatyouarealreadyfamiliarwiththebasic java.util.logging facilityprovidedbytheJDK.Ifyouarenot,see:
JavaLoggingOverview
Packagejava.util.logging
WiththeJULIimplementation,youcanconfigureloggingatavarietyoflevels:
GloballyfortheentireJVMusedbytcRuntimebyupdatingthestandard logging.properties fileoftheJDK,typicallylocatedintheJAVA_HOME/jre/lib directory.
Per-tcRuntimeinstancebyupdatingthe logging.properties filelocatedinthe CATALINA_BASE/conf directoryofthetcRuntimeinstance.
Per-Webapplicationbyaddinga logging.properties fileinthe WEB-INF/classes directoryoftheWebapplicationdeployedtothetcRuntimeinstance.
Ateachlevelyouusea logging.properties filetoconfigurelogging;thelevelthatthefileconfiguresisbasedonthelocationofthefile.Youcanalsoconfigureloggingprogrammatically,althoughthisdocumentdoesnotdiscussthismethod.The logging.properties filesforthetcRuntimeinstanceorWebapplication,however,supportextendedconstructsthatallowmorefreedomtodefinehandlersandassignthemtologgers.Thedifferencesaredescribedlaterinthissection.
ThedefaulttcRuntime logging.properties file,locatedin CATALINA_BASE/conf ofyourserverinstance,specifiestwotypesofhandlers: ConsoleHandler for
©CopyrightPivotalSoftwareInc,2013-2016 20 3.x
routingloggingtostdoutand FileHandler forwritinglongmessagestoafile.Youcansettheloglevelofeachhandlertostandard java.util.logging levels,suchasSEVEREorWARNING;seeLoggingLevelsforjava.util.loggingforthefulllist.
ThedefaultloglevelsettingintheJDK logging.properties fileissettoINFO.Youcanalsotargetspecificpackagesfromwhichtocollectloggingandspecifythelevelofloggingyouwant.Forexample,tosetdebuggingfromtheentiretcRuntimeinstance,addthefollowingtotheCATALINA_BASE/conf/logging.properties file:
org.apache.catalina.level=FINEST
Ifyousettheprecedingloglevel,alsosetthe ConsoleHandler leveltocollectthisthreshold,orinotherwords,beatalevelhigherthantheoveralltcRuntimelevel.
Whenyouconfigurethe logging.properties fileforthetcRuntimeinstanceorWebapplication,youuseasimilarconfigurationasthatoftheJDKlogging.properties file.Youcanalsospecifyadditionalextensionstoallowbetterflexibilityinassigningloggers.Usethefollowingguidelines:
AsinJava6.0,declarethelistofhandlersusing handlers .
AsinJava6.0,loggersdefinealistofhandlersusingthe loggerName.handlers property.
Youdefinethesetofhandlersfortherootloggerusingthe .handlers property;notethatthereisnologgername.
Bydefault,loggersdonotdelegatetotheirparentiftheyhaveassociatedhandlers.YoucanchangethisbehaviorforaparticularloggerusingtheloggerName.useParentHandlers property,whichacceptsabooleanvalue( true or false ).
AsinJava6.0,usethe handlerName.level propertytospecifythelevelofloggingyouwantforagivenhandler.SeeLoggingLevelsforjava.util.loggingforalltheavailableloglevels.
Youcanaddaprefixtohandlernamesbyspecifyingthe handlerName.prefix property.Inthiscase,tcRuntimecaninstantiatemultiplehandlersfromasingleclass.AprefixisaStringthatstartswithadigitandendswith’.’.Forexample, 22foobar. isavalidprefix.Thedefaultprefix,ifyoudonotspecifyoneforaparticularhandler,is juli. .
Similarly,youcanalsoaddasuffixtohandlernameswiththe handlerName.suffix property.Thedefaultsuffix,ifyoudonotspecifyoneforaparticularhandler,is .log .
Specifythedirectorytowhichafilehandlerwritesitslogfilesusingthe handlerName.directory property;thedefaultvalueis logs .Youcanusethe ${catalina.base} variabletopointtoa CATALINA_BASE directoryofyourtcRuntimeinstance.
AtcRuntimeinstancebuffersloggingusingadefaultbuffersizeof8192bytes.Ifyouwanttoreducethediskaccessfrequencyandwritelargerchunksofdatatoalogeachtime,increasethebuffersizeofahandlerbyusingthe handlerName.bufferSize property.
Systempropertyreplacementforpropertyvaluesexpressedusingtheformat ${systemPropertyName} .
Thefollowingexampleshowsa CATALINA_BASE/conf/logging.properties fileforatcRuntimeinstance.Itshowshowtousethe level , prefix , directory ,andbufferSize propertiesforavarietyof FileHandlers :
©CopyrightPivotalSoftwareInc,2013-2016 21 3.x
handlers=1catalina.org.apache.juli.FileHandler,\2localhost.org.apache.juli.FileHandler,\3manager.org.apache.juli.FileHandler,\4admin.org.apache.juli.FileHandler,\java.util.logging.ConsoleHandler
.handlers=1catalina.org.apache.juli.FileHandler,java.util.logging.ConsoleHandler
#############################################################Handlerspecificproperties.#DescribesspecificconfigurationinfoforHandlers.############################################################
1catalina.org.apache.juli.FileHandler.level=FINE1catalina.org.apache.juli.FileHandler.directory=${catalina.base}/logs1catalina.org.apache.juli.FileHandler.prefix=catalina.
2localhost.org.apache.juli.FileHandler.level=FINE2localhost.org.apache.juli.FileHandler.directory=${catalina.base}/logs2localhost.org.apache.juli.FileHandler.prefix=localhost.
3manager.org.apache.juli.FileHandler.level=FINE3manager.org.apache.juli.FileHandler.directory=${catalina.base}/logs3manager.org.apache.juli.FileHandler.prefix=manager.
4admin.org.apache.juli.FileHandler.level=FINE4admin.org.apache.juli.FileHandler.directory=${catalina.base}/logs4admin.org.apache.juli.FileHandler.prefix=admin.4admin.org.apache.juli.FileHandler.bufferSize=16384
java.util.logging.ConsoleHandler.level=FINEjava.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
#############################################################Facilityspecificproperties.#Providesextracontrolforeachlogger.############################################################
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level=INFOorg.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers=\2localhost.org.apache.juli.FileHandler
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level=INFOorg.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers=\3manager.org.apache.juli.FileHandler
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].level=INFOorg.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/admin].handlers=\4admin.org.apache.juli.FileHandler
Thefollowingexampleshowsa WEB-INF/classes/logging.properties fileforaspecificWebapplication.Thepropertiesfileconfiguresa ConsoleHandler toroutemessagestostdout.Italsoconfiguresa FileHandler thatprintslogmessagesattheFINEleveltothe CATALINA_BASE/logs/servlet-examples.log file:
handlers=org.apache.juli.FileHandler,java.util.logging.ConsoleHandler
#############################################################Handlerspecificproperties.#DescribesspecificconfigurationinfoforHandlers.############################################################
org.apache.juli.FileHandler.level=FINEorg.apache.juli.FileHandler.directory=${catalina.base}/logsorg.apache.juli.FileHandler.prefix=servlet-examples.
java.util.logging.ConsoleHandler.level=FINEjava.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
LoggingLevelsforjava.util.loggingThefollowingtableliststhestandardloglevelsthatyoucansetinthevarious logging.properties files,withthehighestlevellistedfirstdowntothelowestlevel(OFF).Enablingloggingatagivenlevelalsoenablesloggingatallhigherlevels.Ingeneral,thelowerlevelofloggingyouenable,themoredatathattcRuntimewritestothelogfiles,sobecarefulwhensettingthelogginglevelverylow.
Table2.StandardLogLevels
©CopyrightPivotalSoftwareInc,2013-2016 22 3.x
ALL Logsallmessages.
SEVERE
Logsmessagesindicatingaseriousfailure.
SEVEREmessagesdescribeeventsthatpreventnormalprogramexecution.Theyshouldbecompletelyintelligibletoendusersandtosystemadministrators.
WARNING
Logsmessageindicatingapotentialproblem.
WARNINGmessagesdescribeeventsthatinterestendusersorsystemmanagers,orthatindicatepotentialproblems.
INFO
Logsinformationalmessages.
Typically,INFOmessagesarewrittentotheconsoleoritsequivalent,whichmeansthattheINFOlevelshouldonlybeusedforreasonablysignificantmessagesthatwillmakesensetoendusersandsystemadministrators.
CONFIG
Logsstaticconfigurationmessages.
CONFIGmessagesprovideavarietyofstaticconfigurationinformation,toassistindebuggingproblemsthatmaybeassociatedwithparticularconfigurations;forexample,theCPUtype,thegraphicsdepth,theGUIlook-and-feel,andsoon.
FINE
Logsrelativelydetailedtracing.FINEmessagesmightincludethingslikeminor(recoverable)failures.IssuesindicatingpotentialperformanceproblemsarealsoworthloggingasFINE.IngeneraltheFINElevelshouldbeusedforinformationthatwillbebroadlyinterestingtodeveloperswhodonothaveaspecializedinterestinthespecificsubsystem.
Theexactmeaningofthethreelevelsvaryamongsubsystems,butingeneral,useFINESTforthemostvoluminousdetailedoutput,FINERforsomewhatlessdetailedoutput,andFINEforthelowestvolumeandmostimportantmessages.
FINERSeeFINEforFINE,FINER,andFINESTdescriptions.FINERindicatesafairlydetailedtracingmessage.Bydefaultloggingcallsforentering,returning,orthrowinganexceptionaretracedatthislevel.
FINESTSeeFINEforFINE,FINER,andFINESTdescriptions.FINESTindicatesahighlydetailedtracingmessage.
OFF Turnsofflogging.
ConfiguringAsynchronousLoggingBydefault,thetcRuntimethreadthathandlesincomingWebrequestsisthesamethreadthatwritestothelogfile,suchas catalina.out .Thusifaresourceissuecausesthethreadwritingtothelogfiletoblock,theincomingWebrequestisalsoblockeduntilthethreadisabletofinishwritingtothelogfile.Dependingonyourenvironment,thisproblemcanaffecttheperformanceofincomingWebrequests.
Asynchronousloggingaddressesthispotentialperformanceproblemwithaseparatethreadtowritetothelogfile.TheWebrequestthreaddoesnothavetowaitforthewritetothelogfiletocomplete,andincomingrequestfromusers(orWebservices)arenotaffectedbyinternalresourceissues.
Anotheradvantageofasynchronousloggingisthatyoucanconfigureamoreverboseloglevelwithoutaffectingtheperformanceoftheincomingrequests,becauseeventhoughalotofinformationisbeingwrittentothelogfile,itisbeingwrittenbyadifferentthreadfromtheonehandlingtheincomingrequests.
Note:AsynchronousloggingisavailableonlyifyourtcRuntimeinstanceusesversion1.6oftheJDK/JRE.Also,asynchronousloggingisavailableonlywiththe java.util.logging loggingconfiguration,andnotwith log4j .
ToconfigureasynchronousloggingforatcRuntimeinstance:
1. IfyouarecreatinganewtcRuntimeinstance,youcanusethe async-logger templatetoautomaticallyconfigureasynchronouslogging.Forexample:
©CopyrightPivotalSoftwareInc,2013-2016 23 3.x
prompt$./tcruntime-instance.shcreatemyserver--templateasync-logger
Thistemplateupdatesthe CATALINA_BASE/conf/logging.properties appropriately,suchaschangingthedefault FileHandler to AsyncFileHandler .Ifyouhavealreadycreatedtheinstance,youmustmanuallyeditthe CATALINA_BASE/conf/logging.properties file,where CATALINA_BASE referstotherootdirectoryofyourtcRuntimeinstance,suchas /var/opt/pivotal/pivotal-tc-server-standard/myserver .Changeeveryinstanceof FileHandler inthefiletoAsyncFileHandler .Thefollowingsnippetshowshowthefirstfewnon-commentedlinesofthefilewilllookafterthesubstitution:
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
#############################################################Handlerspecificproperties.#DescribesspecificconfigurationinfoforHandlers.############################################################
1catalina.org.apache.juli.AsyncFileHandler.level=FINE1catalina.org.apache.juli.AsyncFileHandler.directory=${catalina.base}/logs1catalina.org.apache.juli.AsyncFileHandler.prefix=catalina.
2localhost.org.apache.juli.AsyncFileHandler.level=FINE2localhost.org.apache.juli.AsyncFileHandler.directory=${catalina.base}/logs2localhost.org.apache.juli.AsyncFileHandler.prefix=localhost....
2. Optionallyconfigurehowasynchronousloggingbehavesbysettingoneormoreofthesystempropertieslistedinthepropertiestable.Eachpropertyhasadefaultvaluesoyouonlyneedtosetthemiftheirdefaultvaluesarenotadequate.Setthepropertiesinthe CATALINA_BASE/bin/setenv.sh (Unix)or CATALINA_BASE/bin/setenv.bat (Windows)filebyupdatingthe APPLICATION_OPTS
variable.Usethestandard -D optionforeachsystempropertyyouset.ThefollowingexampleshowshowtosettwoofthepropertiesonUnix:
APPLICATION_OPTS=-Dorg.apache.juli.AsyncOverflowDropType=1-Dorg.apache.juli.AsyncMaxRecordCount=10000
3. RestartyourtcRuntimeinstanceforthechangestotakeeffect.
AsynchronousLoggingSystemProperties
ThefollowingtableliststhesystempropertiesyoucansettoconfiguretheasynchronousloggingfeatureoftcRuntime.
Table3.AsynchronousLoggingSystemProperties
org.apache. juli.AsyncOverflowDropType
SpecifiestheactiontakenbytcRuntimewhenthememorylimitofrecordshasbeenreached.Youcansetthispropertytooneofthefollowingvalues:
1 :tcRuntimedrops,anddoesnotlog,therecordthatcausedtheoverflow.
2 :tcRuntimedropstherecordthatisnextinlinetobeloggedtomakeroomforthelatestrecordonthequeue.
3 :tcRuntimesuspendsthethreadwhilethequeueemptiesoutandflushestheentriestothewritebuffer.
4 :tcRuntimedropsthecurrentlogentry.
1
org.apache.juli.AsyncMaxRecordCount
Maxnumberoflogrecordsthattheasynchronousloggerkeepsinmemory.WhenthislimitisreachedandanewrecordisbeingloggedbytheJULIframework,thesystemtakesanactionbasedonthevalueoftheorg.apache.juli.AsyncOverflowDropType
property.
10000
©CopyrightPivotalSoftwareInc,2013-2016 24 3.x
Thisnumberrepresentstheglobalnumberofrecords,notonaperhandlerbasis.
org.apache.juli.AsyncLoggerPollInterval
Pollinterval(inmilliseconds)oftheasynchronousloggerthread.Ifthelogqueueisempty,theasynchronousloggingthreadissuesa poll(poll_interval) callinordertonotwakeuptooften.
1000
Configuringlog4jThefollowingstepsdescribehowtoconfigurebasic log4j ,ratherthan java.util.logging ,astheloggingimplementationforagiventcRuntimeinstance.Thetextafterthebasicproceduredescribeshowtofurthercustomizethelog4jconfiguration.
1. Underthe CATALINA_BASE directory,createthefollowingdirectoriesiftheydonotalreadyexist:CATALINA_BASE/lib
CATALINA_BASE/bin
2. Createafilecalled log4j.properties inthe CATALINA_BASE/lib directoryofyourtcRuntimeinstance.
3. Addthefollowingpropertiestothe log4j.properties file:
log4j.rootLogger=INFO,Rlog4j.appender.R=org.apache.log4j.RollingFileAppenderlog4j.appender.R.File=${catalina.base}/logs/tomcat.loglog4j.appender.R.MaxFileSize=10MBlog4j.appender.R.MaxBackupIndex=10log4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%p%t%c-%m%n
4. Downloadlog4j (version1.2orlater)andplacethe log4j.jar fileinthe CATALINA_BASE/lib directoryofyourtcRuntimeinstance.
5. Copythe CATALINA_BASE/bin/extras/tomcat-juli.jar fileprovidedwithtcServertothe CATALINA_BASE/bin directoryofyourtcRuntimeinstance.
6. Copythe CATALINA_HOME/bin/extras/tomcat-juli-adpaters.jar fileprovidedwithtcServertothe CATALINA_BASE/lib directoryofyourtcRuntimeinstance.
7. Deletethe CATALINA_BASE/conf/logging.properties filetoprevent java.util.properties fromgeneratingzero-lengthlogfiles.
SpecifyingIncludedPackagesWithlog4jLogging
Pivotalrecommendsthatyouconfigurethespecificpackagesthatyouwanttoincludeinthelogging.BecausetcRuntimedefinesloggersbyEngineandHostnames,usethesenamesinthe log4j.properties file.
Forexample,ifyouwantamoredetailedCatalinalocalhostlog,addthefollowinglinestotheendofthe log4j.properties youcreated:
log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=DEBUGlog4j.logger.org.apache.catalina.core=DEBUGlog4j.logger.org.apache.catalina.session=DEBUG
Warning:AlevelofDEBUGproducesmegabytesofloggingandwillconsequentlyslowthestartupoftcRuntime.Besurethatyouusethislevelsparingly,typicallyonlywhenyouneedtodebuginternaltcRuntimeoperations.
Forthefulllistoflogginglevelsyoucanspecifywhenconfiguringlog4j,seeLogLevels .
ConfiguringaWebApplicationwithlog4jLogging
YoucanconfigureyourWebapplicationstouselog4jfortheirownlogging,whichisinadditiontothetcRuntimeloggingconfigurationdescribedintheprecedingsections.
Thebasicstepsareasfollows:
1. Createa log4j.properties filethatissimilartotheonedescribedinConfiguringlog4j.
©CopyrightPivotalSoftwareInc,2013-2016 25 3.x
2. Updatethe log4j.properties filewithlogginginformationspecifictoyourapplication.Forexample,ifyouwanttospecifythatthe logger inpackagemy.package beatlevelDEBUG,addthefollowing:
log4j.logger.my.package=DEBUG
3. Putthe log4j-version.jar fileinthe WEB-INF/lib directoryofyourWebapplication,where version referstotheversionoftheJARfile,suchas log4j-1.2.15.jar .
Seethelog4jdocumentation fordetailedinformation.
UpdatingLoggingParametersDynamicallyYoucanuseJMXtomodifylogginglevelsandotherloggingparameterswhiletcRuntimeisexecuting.ThemodificationsyoumakeusingJMXarenotpersisted;whentheserverrestarts,anychangesyoumadearelost.Youcouldusethisfeaturetoenabledebuggingmessagestohelptroubleshootanapplicationproblemwhiletheproblemisoccurring.Thisisusefulforproblemsthattaketimetodevelopafterarebootorareotherwisedifficulttoreproduce.
TheJULIimplementationof java.util.logging allowsyoutocreateseparateloggersforeachWebapplicationbyadding logging.properties filestoyourWebapplications.Thisallowsyoutocontrolloggingataveryfinelevel.
UsingJMX,youcanlistloggers,changethelogginglevelforanysingleloggerbyname,andsetanewhandler(logfile)foralogger.Youcanspecifytheloggeryouwanttomanageusingaloggerstringdefinedinthe logging.properties file,prefixedwith“ jmx: ”,forexample jmx:com.springsource.tcserver .
FollowingiscodeforaJSPyoucanusetotryoutusingJMXtomanageloggersdynamically.Itreportswhetherdifferentlogginglevelsareenabledandalsodisplaystheclassloaderandloggernames.AddtheJSPtoawebapplication,deployit,andcallitbeforeandafterchangingthelogginglevelasdescribedinthefirstexamplebelow.
<\%@pageimport="org.apache.juli.logging.*"%><\%Loglog=LogFactory.getLog(this.getClass());Stringdmessage="log.jsplogmessage[DEBUG]"+System.currentTimeMillis();Stringimessage="log.jsplogmessage[INFO]"+System.currentTimeMillis();Stringwmessage="log.jsplogmessage[WARN]"+System.currentTimeMillis();Stringemessage="log.jsplogmessage[ERROR]"+System.currentTimeMillis();log.debug(dmessage);log.info(imessage);log.warn(wmessage);log.error(emessage);%>DebugEnabled:<\%=log.isDebugEnabled()%><br/>InfoEnabled:<\%=log.isInfoEnabled()%><br/>WarnEnabled:<\%=log.isWarnEnabled()%><br/>ErrorEnabled:<\%=log.isErrorEnabled()%><br/>
ClassLoader:<\%=this.getClass().getClassLoader().getParent().getClass().getName()%>#<\%=System.identityHashCode(this.getClass().getClassLoader().getParent())%><br/>LoggerName:<\%=this.getClass().getName()%>#<\%=this.getClass().getClassLoader().getParent().getClass().getName()%>#<\%=System.identityHashCode(this.getClass().getClassLoader().getParent())%><br/>
ThefollowingexamplesuseJConsole ,theJavaMonitoringandManagementConsoleincludedwiththeJDK,tomanageloggers.Thereisa jconsoleexecutableintheJDK bin directorythatyoucanexecutefromashellorCommandPrompt.JConsoleconnectstoatcRuntimeinstanceattheJMXport,6969bydefault.ToverifyyourJMXport,checkthe base.jmx.port propertyinthe CATALINA_HOME/conf/catalina.properties file.
SettingaNewLoggingLevelforaLogger
ThisexampleshowshowtouseJMXtochangethelogginglevelforaloggerwithoutrestartingthetcRuntimeinstance.AloggerstringfromtheCATALINA_HOME/conf/logging.properties fileidentifiesthelogger.
1. StartJConsoleandconnecttothetcRuntimeinstance.IntheNewConnectionwindowRemoteProcessfield,enterthehostnameorIPandJMXportforthetcServer,separatedbyacolon.Entertheusernameandpassword(thedefaultsareadmin/springsource)andclickConnect.
©CopyrightPivotalSoftwareInc,2013-2016 26 3.x
2. ClicktheMBeanstab.
3. Inthetreeattheleft,expandjava.util.logging>Logging>Operations,andclickthesetLoggerLeveloperation.
4. IntheOperationinvocationsection,entertheloggernameinthep0fieldandthenewlogginglevelinthep1field.ThenclicksetLoggerLevel.Theloggername,p0,canbeoneofthefollowing:
Loggerstringsdefinedin CATALINA_HOME/conf/logging.properties prefixedwith“ jmx: ”.Forexamplejmx:com.springsource.tcserver , jmx:org.apache.catalina ,or jmx:org.apache.tomcat .Afullyqualifiedloggername,asdescribedintheprecedingsection.
IfyouareusingtheJSPcodepresentedabovetotestthisfeature,copytheloggernamefromthepage’soutputinyourbrowserandpasteitintothep0field.Becarefulnottocopyanytrailingspacesintothefield.Thelogginglevel,p1,isoneofthelogginglevelsdescribedinLoggingLevelsforjava.util.logging:SEVERE,WARNING,INFO,CONFIG,FINE,FINER,FINEST,OFF,orALL.
AfteryouclickSetLoggerLevel,thenewloggingleveltakeseffect.IfyouareusingthesampleJSPcode,reloadingthepagelogsmessagesandupdatesthestatusofthelogginglevels.
Example-CreateaNewLogFileandRedirectDebugOutputToIt
Thefollowingexamplecreatesaloghandler(alogfile),associatesitwithalogger,andsetsthelogginglevelforthelogger.Theresultisanewlycreatedlogfilewithmessagesredirectedintoit.
1. StartJConsoleandconnecttothetcServerinstance.(Seepreviousexample.)
2. ClicktheMBeanstabandthen,inthetreeatleft,navigatetotcServer>Serviceability>LoggingManager>Operations.
©CopyrightPivotalSoftwareInc,2013-2016 27 3.x
3. ClickthecreateHandleroperation.Youusethisoperationtocreatealogfile.Completetheparametersasfollows:p0:empty.Thisparameterisignored.p1:Thenameofyourhandler,forexample MyJMXLog .p2:Thelocationofthelogfile,forexample ${catalina.base}/logs .p3:Theprefixofthelogfilename,forexample debug-example .p4:Thesuffixforthelogfilename,forexample .log .
Parametersp2,p3,andp4establishthelocationandnameofthenewlogfile.Thefilenameisconstructedfromtheprefix,adaytimestamp,andthesuffix,forexample debug-example.2011-11-11.log .Thep2parameterspecifiesthedirectorywherethefileiscreated,inthisexampleCATALINA_HOME/logs .
4. ClickcreateHandler.Nowyoucanverifythatthenewlogfilehasbeencreatedinthe CATALINA_HOME/logs directory.
5. ClickthesetHandleroperation.Youusethisoperationtoassociatethelogfileyoucreatedwithalogger.Completetheparametersasfollows:p0:empty.p1:Thenameofyourhandler,forexample MyJMXLog .p2:Thenameofthelogger,forexample jmx:org.apache .
6. Navigatetojava.util.logging>Logging>OperationsandclickthesetLoggerLeveloperation.Completetheparametersasfollows:
©CopyrightPivotalSoftwareInc,2013-2016 28 3.x
p0: jmx.org.apachep1: ALL
7. ClicksetLoggerLevel.Messagesarenowwrittentothenewlogfile.
RememberthatchangesyoumakewithJMXarelostwhentheserverisrebooted.ThechangesarenotwrittentothetcServerconfigurationfiles.
ObfuscatingPasswordsintcRuntimeConfigurationFilesPivotaltcRuntimestoresitsconfigurationfilesinthe CATALINA_BASE/conf directory.Thedirectoryincludesthefollowingfiles:
context.xml
jmxremote.password
server.xml
web.xml
Bydefault,passwordsinthesefilesareincleartext.Thisistypicallynotaproblemduringdevelopment;however,whenyoumovetoproduction,youwillprobablywanttoprotectthesepasswordsforsecurityreasonssothattheactualpasswordstringdoesnotshowupintheconfigurationfiles.
Passwordsappearintheseconfigurationfilesinavarietyofplaces.Forexample,asdescribedinConfiguringtheHighConcurrencyJDBCConnectionPool,youusethe <Resource> elementofthe server.xml filetoconfigureaJDBCconnectionpool,andtheelement’s password attributespecifiesthepasswordoftheuserwhoconnectstothedatabaseserver,asshowninthefollowingsamplesnippetofthe server.xml file(onlyrelevantpartsshown):
<?xmlversion='1.0'encoding='utf-8'?><Serverport="-1"shutdown="SHUTDOWN">...<GlobalNamingResources><Resourcename="jdbc/TestDB"auth="Container"type="javax.sql.DataSource"username="root"password="mypassword"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"...</GlobalNamingResources>...<Servicename="Catalina">...</Service></Server>
Anotherexampleisthe jmxremote.password filethatcontainsthepasswordfortheJMXusername/rolethatHQusestoconnecttotheJMXserverassociatedwiththetcRuntimeinstance.Bydefault,thepasswordisincleartext.Thefollowingexampleshowstheout-of-the-boxfileinwhichthe admin rolehasthepassword pivotal :
#The"admin"rolehaspassword"pivotal".adminpivotal
©CopyrightPivotalSoftwareInc,2013-2016 29 3.x
TheremainderofthissectiondescribeshowtoprotectthepasswordtextinanyofthetcRuntimeconfigurationfileslocatedintheCATALINA_BASE/confdirectory.
tcruntime-adminencodeCommandAsoftcServer3.2.0,thetcruntime-admin.sh|batscripthasan encode optionthatsimplifiesthebasicusageofourPropertyDecoderasdescribedbelow.
Usageofthecommandisasfollows:
./tcruntime-admin.shencode<value><passphrase>
Where
<value>isthevaluesuchaspropertyvaluetoencode
<passphrase>isthesecretpassphrasetousetoencodethevalue
Thecommandwilloutputanencodedvaluewhichcanbeusedinoneofthesupportedconfigurationfilesdescribedinthissection.
Example
$./tcruntime-admin.shencodefoobarmypassphrase2kiFLxKkcQp6PNJCryL+fublW4Q8929ZqY3bY2asJnk=
The“encode”commandalsosupportsdecodinganencodedvaluewithaknownpassphrase.
./tcruntime-admin.shencode--decode<encodedvalue><passphrase>
Where
<encodedvalue>istheencodedresultofapreviouslyencodedvalue
<passphrase>isthepassphraseusedtoencodethevalue
Example
$./tcruntime-admin.shencode--decode2kiFLxKkcQp6PNJCryL+fublW4Q8929ZqY3bY2asJnk=mypassphrasefoobar
PropertyDecoderUsageIntcServer3.0.x,and3.1.xyouarerequiredtoinvokeajavacommandspecifyingclasspathforneededjarsandpropertiesfortheencodertouse.
BasicEncryptionUsage
Thefollowingexamplewillencrypt <valueToEncrypt> usingthe <passphrase> .ThecommandusesallthedefaultsystempropertiesforthePropertyDecoderclass.Itassumesthatthecurrentworkingdirectoryistheinstancehomedirectory.
java-cp":lib/*"com.springsource.tcserver.security.PropertyDecoder-encode<passphrase><valueToEncrypt>
Thiscommandwillprovideanencryptedvalue.Thisvalueisusedasapropertyvaluein catalina.properties .
Note:ThelengthofthepassphraseiscontrolledbytheJSESecurityPolicy.JVMinstallationswithoutJSEUnlimitedStrengthPolicyfilesarelimitedinthelengthofthepassphrasewhichis7charactersmaximum.
AdvancedEncryptionUsage
Ifyourequirefinergraincontrolovertheencryptionmethodusedtoencodeavalueyoumaydefinethecom.springsource.tcserver.security.PropertyDecoder.iterations .
©CopyrightPivotalSoftwareInc,2013-2016 30 3.x
Thefollowingexampleassumesthatthecurrentworkingdirectoryistheinstancehomedirectory.
java-cp":lib/*"-Dcom.springsource.tcserver.security.PropertyDecoder.iterations=10000com.springsource.tcserver.security.PropertyDecoder-encode<passphrase><valueToEncrypt>
Base64Encoding
ItispossibletouseBase64toencodeavalue.Thismethodislesssecurethanencryptingwithapassphrase.
java-cp":lib/*"-Dcom.springsource.tcserver.security.PropertyDecoder.iterations=10000com.springsource.tcserver.security.PropertyDecoder-encodebase64<valueToEncrypt>
PropertiesThistableexplainsthepropertieswhichmaybedefinedduringtheencoding/decodingprocess:
Name Default Description
com.springsource.tcserver.security.PropertyDecoder.algorithm
PBEWITHSHA256AND128BITAES-CBC-BC
Setstheencryptionalgorithmtouse
com.springsource.tcserver.security.iterations 1000 Setsthenumberofiterationstouseforencryption
com.springsource.tcserver.security.PropertyDecoder.passphrase
n/aDefinesthepassphrasetousetodecryptthevalue.Whenthevalue“console”isspecifiedtheuserwillbepromptedforthepassword.Ifusing"console”theinstancemustbestartedintheforeground.
BeingPromptedforthePassphraseWhenyouStarttheInstance
Storingthepassphraseandencryptedpasswordsonthelocalfilesystemwhenusingpassphraseencryptionisreasonablysecure.However,someusersmaywanttobepromptedforthepassphrasesothatitdoesnotappearincleartextinanyfileatall.
Warning:ThisfeaturerequiresthatyoustartthetcRuntimeinstanceasaforegroundprocessusingtherunoptionoftcruntime-ctl.sh|batonbothUnixandWindows.OnUnix,youcanthenputtheprocessinthebackground.OnWindows,however,thismeansthatyoucannotcontroltheinstanceusingtheWindowsServicesconsole.Forthisreason,thisfeatureisnotpracticalforproductionuseonWindows.
ThefollowingassumesthatyouhavealreadygeneratedanencodedvalueasdescribedinBasicEncryptionUsageandthatyouaddedittoyourconfigurationfile.
TobepromptedforthepassphrasewhenyoustartthetcRuntimeinstance,updatethe catalina.properties fileandsetthecom.springsource.tcserver.security.PropertyDecoder.passphrase propertytothevalueconsole.
Forexample( catalina.properties ):
org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.springsource.tcserver.security.PropertyDecodercom.springsource.tcserver.security.PropertyDecoder.passphrase=consoledb.password=tcEnc://koBC0uF1N200plwJgBfeQg==
StoringPassphrasesandEncryptedPropertiesinSeparateFiles
Althoughstoringthepassphrase(whenusingpassphraseencryption)andencryptedpasswordsinthe catalina.properties isreasonablysecure,someusersmightprefertostorethesevaluesinseparatefiles.
Tostorethepassphraseinaseparatefile,replacethevalueofthe com.springsource.tcserver.security.PropertyDecoder.passphrase propertywiththenameofafile.Youcanusethe ${catalina.base} variabletospecifyadirectoryrelativetotheCATALINA_BASEofthetcRuntimeinstance.
Inthefollowingsamplesnippetof catalina.properties ,thepassphraseisstoredinafilecalled secure.file inthe CATALINA_BASE/confdirectory ofthetcRuntimeinstance:
©CopyrightPivotalSoftwareInc,2013-2016 31 3.x
org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.springsource.tcserver.security.PropertyDecodercom.springsource.tcserver.security.PropertyDecoder.passphrase=${catalina.base}/conf/secure.filedb.password=tcEnc://koBC0uF1N200plwJgBfeQg==
Createthe secure.file file:itshouldcontainasinglelinewiththepassphrase.Forexample:
mypassphrase
Similarly,tostoretheactualencryptedpasswordinaseparatefile,replacethepasswordvariable(db.passwordinourexample)inthe catalina.propertiesfilewithapropertycalled com.springsource.tcserver.security.PropertyDecoder.properties .Setthispropertytothenameofafilethatcontainsthepasswordvariable.
Inthefollowingsamplesnippetof catalina.properties ,theencryptedpasswordisstoredinafilecalled application.properties inthe CATALINA_BASE/confdirectoryofthetcRuntimeinstance:
org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.springsource.tcserver.security.PropertyDecodercom.springsource.tcserver.security.PropertyDecoder.passphrase=${catalina.base}/conf/secure.filecom.springsource.tcserver.security.PropertyDecoder.properties=${catalina.base}/conf/application.properties
Createthe application.properties fileandaddtheoriginalpasswordvariable.Followingwithourexample,thefilewouldincludethefollowing:
db.password=tcEnc://koBC0uF1N200plwJgBfeQg==
ExampleThisisarealworldwalkthroughofallthenecessarystepstoutilizeencryptedpasswordvalues.ThisexampleassumesthereisatcRuntimeinstancebythenameof"example”andthatwewanttoencryptthepassword"catspaw”andthatthe"java”commandisinthePATHvariable.Ourpassphraseis"lucky77”.
Thefirstthingtodoistochangethecurrentworkingdirectory(CWD)tothebasedirectoryofthetcServerInstallation.
$cd$TCSERVER_HOME
NextwewanttotellPropertyDecodertoencodeourpassword"catspaw”.
$java-cp":lib/*"com.springsource.tcserver.security.PropertyDecoder-encodelucky77catspawFeb4,20169:53:46AMcom.springsource.tcserver.security.TcDecoderinitCiphersINFO:InitializingcipherstAAcYgb0BBg89Ms2xOCFEUqPXQgw0kFTuGXHJMbAQ1k=
Thecommandoutputted"tAAcYgb0BBg89Ms2xOCFEUqPXQgw0kFTuGXHJMbAQ1k=”thisisourencryptedversionof"catspaw.”Thisvaluewillbedifferenteachtimethesamecommandisexecuted.Therefore,yourencryptedvaluewillbedifferent.Here’sthesamecommandexecutedasecondtime.
$java-cp":lib/*"com.springsource.tcserver.security.PropertyDecoder-encodelucky77catspawFeb4,20169:56:54AMcom.springsource.tcserver.security.TcDecoderinitCiphersINFO:Initializingciphersl9IILG3R5Z5xLiKVWvqlF0qlQ28iG1W6kZ6y6mi9upQ=
Thesecondinvocationreturned"l9IILG3R5Z5xLiKVWvqlF0qlQ28iG1W6kZ6y6mi9upQ=”bothofthesevaluesrepresentanencryptedformof"catspaw.”Theybothmaybedecodedusingthesamepassphrase.
Hereweseewhathappenswhenwedecodethedifferentencryptedvalues.
$java-cp":lib/*"com.springsource.tcserver.security.PropertyDecoder-decodelucky77tAAcYgb0BBg89Ms2xOCFEUqPXQgw0kFTuGXHJMbAQ1k=Feb4,201610:00:52AMcom.springsource.tcserver.security.TcDecoderinitCiphersINFO:Initializingcipherscatspaw
$java-cp":lib/*"com.springsource.tcserver.security.PropertyDecoder-decodelucky77l9IILG3R5Z5xLiKVWvqlF0qlQ28iG1W6kZ6y6mi9upQ=Feb4,201610:00:52AMcom.springsource.tcserver.security.TcDecoderinitCiphersINFO:Initializingcipherscatspaw
Bothvaluesdecryptedto"catspaw.”
©CopyrightPivotalSoftwareInc,2013-2016 32 3.x
Nextweneedtoplacetheencodedvalueinto <instance-home>/conf/catalina.properties .Thevalueneedstohavethespecialprefix"tcEnc://”addedtoit.Thisiswhatindicatesthatitisanencodedvalue.Wealsoneedtotell PropertyDecoder wheretofindthepassphraseandtomakesurethat PropertyDecoder isbeingusedtoreadtheproperties.
#TellTomcat’sdigesterwhichclasstousetoreadproperties.org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.springsource.tcserver.security.PropertyDecoder#TellPropertyDecoderwheretolookforthepassphrasecom.springsource.tcserver.security.PropertyDecoder.passphrase=${catalina.base}/conf/secure.file#EncryptedPassowrddb.password=tcEnc://l9IILG3R5Z5xLiKVWvqlF0qlQ28iG1W6kZ6y6mi9upQ=
Thefile <instance-home>/conf/secure.file shouldcontainonly"lucky77”andnootherdataincludingnewlinesandwhitespaces.
AtthispointthetcRuntimeinstancemaybestartedviathestandardmethodandshouldreadthepassphrasefrom <instance-home>/conf/secure.file anddecrypttheproperty"db.password”andconnectproperlytotheDB.Ifthereisafailureitshouldbeloggedinthe catalina.log fortheinstance.
GeneralSecurityBestPracticesTheprecedingsectionsprovidespecificinformationaboutobfuscatingandencryptingpasswordsintcRuntimeconfigurationfilesusingavarietyofmethods.ThissectionprovidesgeneralbestpracticesforsecuringyourtcRuntimeinstances.
Foradditionalsecurity,Pivotalrecommendsthat:
OnthecomputeronwhichyouhaveinstalledtcServer,createanoperatingsystemuserwhoseonlypurposeistorunthetcRuntimeprocess.Inotherwords,thisuserwouldbetheonlyuserwhostarts/stopsthetcRuntimeinstance,andthisuserwoulddonothingelsebutstart/stopthetcRuntimeprocess.
MakeitimpossibleforanyonetologontothecomputerdirectlyasthisdedicatedtcServeruser.
SetthepermissionsforalltcRuntimeconfigurationfilessothattheyarereadableonlybythisdedicatedtcServeruser.
Ifyousetuptheprecedingscenario,theonlyuserswhowillbeablereadthepasswordsinthetcRuntimeconfigurationfiles(whethertheyareincleartext,areobfuscated,orencrypted)areuserswith root privileges.
ToimplementthisscenarioonWindows,youcanusethe installrun-as-user optionof tcruntime-ctl.bat toinstallthetcRuntimeinstanceasaWindowsserviceandspecifythatitshouldrunasthededicatedtcServeruser.See"tcruntime-ctlCommandReference”inGettingStartedwithPivotaltcServerfordetails.
OnUnix,youcanusethe boot.rc.template scripttocustomizeyourUnixbootprocesssothatthetcRuntimeinstancestartsautomaticallywhenyourcomputerstarts.Usethe TOMCAT_USER variableinthescripttospecifythededicatedtcServeruserthatyouwantthetcRuntimeinstancetorunas.YouthenusethebootscriptthesamewayyouuseanyotherUnixbootscriptonyourcomputer.Forexample,youmightcopyittothe /etc/init.d directory,givingitauniquenamesuchas my-tc-runtime-instance .Thenyouwouldlinkthisscriptfrom /etc/rc*.d asappropriate,dependingonwhenyouwantthetcRuntimeinstancetostartduringtheUnixbootsequence.
Alternatively,ifyoudonotwantthetcRuntimeinstancetostartautomaticallywhentheUnixcomputerboots,youcanrunthe my-tc-runtime-instance fileinthe /etc/init.d directoryasthe root user,ratherthanstartthetcRuntimeprocessusingthe tcruntime-ctl.sh script.
Formoreinformationaboutthe boot.rc.template script,see“Unix:StartingtcRuntimeInstancesAutomaticallyatSystemBootTime”inGettingStartedwithPivotaltcServer.
ConfiguringanOracleDataSourceWithProxiedUsernamesWhenyouconfigureaglobalsharedJDBCdatasourceforaparticulartcRuntimeinstance,bydefaultalldeployedapplicationsthatusethedatasourceconnecttotheconfigureddatabaseusingthesameusernameandpassword.Thisuseriscalledaproxy,becausetheproxyuserperformsadatabasetaskonbehalfoftheuserusingtheapplicationdeployedtotcRuntime.Whenanapplicationuserconnectsanonymouslythroughaproxy,however,itisimpossibletocustomizesecurityforindividualusersorgetameaningfulaudittrailoftheusersthatactuallyusedthedatabase.
ForthisreasonitcanbeusefultoconfigurethetcRuntimeinstancesothat,whilemanyapplicationsshareaparticularglobaldatasource,eachapplicationconnectstothedatabaseusingadifferentusernameandpasswordviatheproxyuser,ratherthandirectlythroughtheproxyuserthatisconfiguredforthedatasourceitself.PivotaltcRuntimehasimplementedthisfeatureusingtheOracleproxyconnectionauthentication .
NOTE:ThisfeatureappliesonlytoOracledatasources.
ThefollowingproceduredescribeshowtoconfiguretcRuntime,andyourapplications,touseasharedglobalOracledatasourcewiththeproxyconnectionauthentication.
©CopyrightPivotalSoftwareInc,2013-2016 33 3.x
1. ConfigureastandardsharedglobalOracledatasourceforyourtcRuntimeinstancebyaddinga <Resource> childelementofthe<GlobalNamingResource> elementinthe server.xml file.TheactualconfigurationdependsonyourOracledatabaseenvironment,butthefollowingsnippetprovidesanexample(relevantsectionsshowninbold):
<?xmlversion='1.0'encoding='utf-8'?><Serverport="-1"shutdown="SHUTDOWN">
...
<GlobalNamingResources>
<Resourcename="jdbc/TestDB"auth="Container"type="oracle.jdbc.pool.OracleDataSource"description="OracleDatasource"factory="oracle.jdbc.pool.OracleDataSourceFactory"url="jdbc:oracle:thin:@//localhost:1521/orcl"user="default_user"password="password"connectionCachingEnabled="true"connectionCacheName="CXCACHE"connectionCacheProperties="{MaxStatementsLimit=5,MinLimit=1,MaxLimit=1,ValidateConnection=true}"/>
</GlobalNamingResources>...<Servicename="Catalina">...</Service></Server>
Inthepreceding server.xml snippet,bydefaultthe jdbc/TestDB datasourceconnectstothedatabaseastheuser default_user withpasswordpassword ;thisistheproxyuser.
2. Usethe jdbc/TestDB datasourceinyourservletandJSPsasusual.ThefollowingsnippetshowsanexampleofusingitinaJSPtogetaconnectiontothedatabase:
<\%@pageimport="java.sql.Connection,java.sql.ResultSet,java.sql.Statement,javax.naming.*,javax.sql.*"%>
ContextinitContext=newInitialContext();ContextenvContext=(Context)initContext.lookup("java:/comp/env");DataSourcedatasource=(DataSource)envContext.lookup("jdbc/TestDB");Connectioncon=datasource.getConnection();...
3. Foreachapplicationthatusesthedatasourceandforwhichyouwanttoconfigureaspecificproxied-user,updatetheapplication’s META-
INF/context.xml filebyaddinga <ResourceLink> elementthatlinkstheglobalOracledatasourcetothecom.springsource.tcserver.oracle.OracleProxyDataSourceFactory factory.Usethe username and password attributesof <ResourceLink> toconfigurethespecificuseryouwantthisparticularapplicationtoconnecttothedatabaseas,viatheproxyuser.Forexample(relevantsectionshowninbold):
<?xmlversion='1.0'encoding='utf-8'?><Context><WatchedResource>WEB-INF/web.xml</WatchedResource><ResourceLinkglobal="jdbc/TestDB"name="jdbc/TestDB"username="proxieduser"password="proxypassword"factory="com.springsource.tcserver.oracle.OracleProxyDataSourceFactory"/></Context>
Whentheapplicationdescribedbythis context.xml fileusesthe jdbc/TestDB datasource,itwillconnecttothedatabasefirstastheproxyuser( default_user )andthenopenaproxyconnectionasthe proxieduser user,withpassword proxypassword .Note:Forthisfeaturetoworkcorrectly,youmustupdatethe context.xml filesforeachrelevantapplication,nottheglobal context.xml filelocatedinthe CATALINA_BASE/conf directory.
4. Forthechangestotakeeffect,restartyourtcRuntimeinstance,whichinturnredeploysallrelevantapplications.
5. Ifyouhavenotalreadydoneso,createallrequiredOracledatabaseusersthatmatchtheusernamesyouconfiguredinthe context.xml andserver.xml files.Forexample:
createuserdefault_useridentifiedbypassword;createuserproxieduseridentifiedbyproxypassword;grantdbatodefault_user;grantdbatoproxieduser;ALTERUSERproxieduserGRANTCONNECTTHROUGHdefault_userAUTHENTICATEDUSINGpassword;
TheprecedingSQLstatementsshowhowthe proxieduser connectstotheOracledatabasethrough default_user .TheseSQLstatementsarejustexamples;forcompletedescriptionsofthesestatements,seeyourOracledatabasedocumentation.
©CopyrightPivotalSoftwareInc,2013-2016 34 3.x
ReportingStatusforaDeployedApplication,Host,orEngineBydefault,theerrororstatuspagethattcRuntimedisplayswhenitencountersaparticularHTTPstatusorerrorcode(suchas 404 whentcRuntimedoesnotfindarequestedresource)ishard-coded.However,youmightwantorneedtochangethedisplayederror,forsimplecustomizationreasonsorbecauseofyourorganization’ssecurityrequirementsthatdictatehowerrorpagesshouldworkandwhattheyshouldlooklike.ThissectiondescribeshowtocustomizewhattcRuntimedisplayswhenitencountersaparticularHTTPstatuscode.
TheHTTP1.1specification definestheHTTPstatuscodes.Thefollowinglistdescribessomecommoncodes:
403 Forbidden :Theserverunderstoodtherequest,butisrefusingtofulfillit.
404 Not Found :TheserverhasnotfoundanythingmatchingtheRequest-URI.
500 Internal Server Error :Theserverencounteredanunexpectedconditionwhichpreventeditfromfulfillingtherequest.
TocustomizethewaytcRuntimerespondswhenitencountersoneofthesecodes,youaddaValve elementtothe server.xml configurationfilewhoseclassName attributeis com.springsource.tcserver.security.StatusReportValve .The StatusReportValve hasanumberofotherattributesthatdescribeitsbehavior,asdescribedinAttributesoftheStatusReportValve.
Youcanspecifythe StatusReportValve asadirectchildelementofeitherthe Host or Engine elementinthe server.xml file,dependingontheassociatedCatalinacontainerforwhichyouwanttoconfiguretheValve.Ifyouspecifythatthe StatusReportValve isadirectchildelementof Engine ,thenyoumustexplicitlydisabletheValveatthe Host level,usingthe Host attribute errorReportValveClass="" .
YoudefinehowtcRuntimehandlesaparticularHTTPstatuscodebyaddinganattributetothe StatusReportValve whosenameis error.XXX ,where XXXisthenumericalstatuscode,suchas error.404 .Thensetthevalueofthisattributeinoneofthefollowingways:
error.XXX=file://valid/file/path/URI :SpecifiesthatwhentcRuntimeencounterstheXXXstatuscode,itshoulddisplaythespecifiedURI.IftheURIisnotvalid,thefiledoesn’texist,oritisnotreadable,tcRuntimeignoresthestatuscode.
error.XXX=/path/to/file .SpecifiesthatwhentcRuntimeencounterstheXXXstatuscode,itshoulddisplaythespecifiedfile.Ifthepathdoesnotpointtoafilenode,tcRuntimeinterpretsthepathasamessagestring.Ifthefilenodeisadirectoryornotreadable,tcRuntimeignoresthestatuscode.
error.XXX=message string :SpecifiesthatwhentcRuntimeencounterstheXXXstatuscode,itshoulddisplaythespecifiedmessageasthebodyofthestatusresponse.
error.XXX=http://<myserver>/404error.html :SpecifiesthatwhentcRuntimeencounterstheXXXstatuscode,itretrievesthespecifiedURLandreturnsittotheclient.IftheURIisnotvalid,thefiledoesn’texist,oritisnotreadable,thentcRuntimeignoresthestatuscode.
IftcRuntimeencountersastatuscodethatyouhavenotdefinedin StatusReportValve usingan error.XXX attribute,thentcRuntimedoesnotactuponthestatuscode.Additionally,ifyourapplicationhasalreadyrespondedtothestatuscode,thenthe StatusReportValve doesnotactuponthestatuscode.
OnceyouconfigureyourtcRuntimeinstancewiththe StatusReportValve andyoustarttheinstance,youcandynamicallychangetheattributesoftheValveusingJMX.
Thefollowing server.xml snippetshowsanexampleofconfiguringa StatusReportValve fortheCatalinaEngine;onlyrelevantpartsof server.xml areshown(inbold):
©CopyrightPivotalSoftwareInc,2013-2016 35 3.x
<?xmlversion='1.0'encoding='utf-8'?><Serverport="${shutdown.port}"shutdown="SHUTDOWN">
...<Servicename="Catalina">...
<Enginename="Catalina"defaultHost="localhost">
<ValveclassName="com.springsource.tcserver.security.StatusReportValve"fileEncoding="utf-8"contentType="text/html"characterEncoding="utf-8"zeroLengthContent="false"commitOnReport="true"cacheFiles="true"removeException="true"error.500="${catalina.base}/conf/500.html"error.404="${catalina.base}/conf/404.html"error.403="Iamsorry,youdonothaveaccess"/>
...<Hostname="localhost"appBase="webapps"unpackWARs="true"autoDeploy="true"deployOnStartup="true"deployXML="true"xmlValidation="false"xmlNamespaceAware="false"errorReportValveClass=""></Host></Engine></Service></Server>
Intheprecedingexample,the StatusReportValve canactuponthreeHTTPstatuscodes: 404 , 500 ,and 403 .WhentcRuntimeencountersthe 404statuscode,itdisplaysthecontentsofthefile CATALINA_BASE/conf/404.html .Similarlyforstatuscode 500 ,althoughinthiscaseitdisplaysthefileCATALINA_BASE/conf/500.html .IftcRuntimeencountersthestatuscode 500 ,itdisplaystheliteralmessage Iamsorry,youdonothaveaccess .
Notethat,becausethe StatusReportValve isconfiguredatthe Engine level,thechild Host elementexplicitlydisablestheValveusingtheattributeerrorReportValveClass="" .
Thefollowingtabledescribesalltheattributesofthe StatusReportValve .
Table4.AttributesoftheStatusReportValve
Attribute Description
classNameSpecifythe com.springsource.tcserver. security.StatusReportValve class,oraclassthatextendstheStatusReportValve class.
fileEncodingSpecifiestheencodingofthedisplayedstaticfiles.Ifyoudonotspecifythisattribute,tcRuntimeusesthedefaultplatformencoding.
contentTypeSpecifiesthe Content-Type headerfortheHTTPresponse.Defaultvalueis text/html .SeeMIMEMediaTypes forthefulllist.
characterEncodingSpecifiesthe charset parameterofthe Content-Type headerfortheHTTPresponse.Defaultvalueis utf-8 .SeeCharacterSets forthefullset.
zeroLengthContentIfyouhavesetthisattributeto true andtheresponseisnotcommitted,theValvereturnswitha0lengthbody.Usefulformod_jk andreverseproxywheretheWebserveronlyoverridesthebodyifitisof0length(effectively,ithasnobody.)
commitOnReportIfyouhavesetthisattributeto true ,theStatusReportValvealwaystriestocommittheresponseevenwitha0lengthbody.Ifyousetitto false ,thenValvesfurtherupthechainmaychangetheresponse.
cacheFiles
Ifyousetthisattributeto true ,theValvecachesthecontentofthestaticpagesasjava.lang.ref.WeakReference<String> .Oncecached,tcRuntimemakesnoattempttoreadthefilesystemunlessthegarbagecollectorclearstheweakreferences.
removeExceptionIfyousetthisattributeto true ,theValveremovesthe Globals.EXCEPTION_ATTR fromtherequestattribute.Valvesfurtherupinthechainwillnolongerhaveaccesstotheexceptionthatcausedtheerror.
error.XXXSpecifiesthattcRuntimeshouldactuponthe XXX statuscodebydisplayingeitherthespecifiedURI,file,ormessagestring.Seethepreviousdiscussionfordetails.
EnablingThreadDiagnostics
©CopyrightPivotalSoftwareInc,2013-2016 36 3.x
ThreadDiagnosticsValve collectsdiagnosticinformationfromtcRuntimerequestthreads.IfthethreadhasJDBCactivityonaDataSource,thecollecteddiagnosticscanincludetheJDBCquery,dependingonhowyouconfigure ThreadDiagnosticsValve .ThecollectedinformationisexposedthroughJMXMBeans.
Thediagnosticscollectedforathreadincludethefollowing:
TheURIoftherequest
Thequeryportionoftherequeststring
Timetherequestbegan
Timetherequestcompleted
Totaldurationoftherequest
Thenumberofgarbagecollectionsthatoccurredduringtherequest
Thetimespentingarbagecollection
Numberofsuccessfulconnectionrequests
Numberoffailedconnectionrequests
Timespentwaitingforconnections
Textofeachqueryexecuted
Executiontimeforeachquery
Statusofeachquery
Executiontimeforallqueries
Stacktracesforfailedqueries
SettingUpThreadDiagnosticsValveSetup ThreadDiagnosticsValve byaddinga Valve childelementtothe Engine or Host elementin conf/server.xml andconfiguringaDataSource,ifyouwantJDBCdiagnostics.
Ifyouincludethe diagnostics templateinthe tcruntime-instance create command,theconfigurationisdoneforyou,includingcreatingaDataSourcewhoseactivitywillbeincludedinthediagnostics.Forexample:
prompt$./tcruntime-instance.shcreate-tdiagnosticsmyInstance
WhenyoucreateatcRuntimeinstanceusingthe diagnostics template,thefollowing Valve elementisinsertedasachildofthe Engine elementintheconf/server.xml fileofthenewinstance.
<ValveclassName="com.springsource.tcserver.serviceability.request.ThreadDiagnosticsValve"loggingInterval="10000"notificationInterval="60000"hreshold="10000"/>
Youcan,ofcourse,addthe Valve elementmanually.ThefollowingtabledescribestheattributesyoucansetontheValve elementforThreadDiagnosticsValve .
Table5.PropertiesofThreadDiagnosticsValve
Attribute Description
className Themanagedclass: com.springsource.tcserver.serviceability.request.ThreadDiagnosticsValve .Required.
thresholdTheminimumtime(milliseconds)arequestmustlasttobereported.Arequestmustexceedthistimetoqualify.Thedefaultis 500 .
history Thenumberofqualifiedrequeststokeepinthehistory.Thedefaultis 1000 .
loggingInterval Theminimumnumberofmillisecondsbetweenloggingrequests,topreventflooding.Thedefaultis 5000 .
notificationInterval TheminimumnumberofmillisecondsbetweenJMXnotifications,toavoidflooding.Thedefaultis 5000 .
logExtendedDataIf true ,adetailedmessageisloggedforthethread,includingthethreadname,priority,id,andstacktraces.Default:false .
©CopyrightPivotalSoftwareInc,2013-2016 37 3.x
ConfiguringJDBCDiagnosticsThe ThreadDiagnosticsValve monitorsaDataSourceifitisconfiguredwiththe ThreadQueryReport jdbcInterceptor.Furthermore,the ThreadQueryReportinterceptorisautomaticallyaddedwhentheDataSourceiscreatedwith com.springsource.tcserver.serviceability.request.DataSourceFactory .Therefore,ifyoudonotwantJDBCdiagnostics,settheDataSource factory attributeto org.apache.tomcat.jdbc.pool.DataSourceFactory instead.Anotheroptionistouseorg.apache.tomcat.jdbc.pool.DataSourceFactory andexplicitlyadd com.springsource.tcserver.serviceability.request.ThreadQueryReport totheDataSource’s jdbcInterceptorsattributein server.xml ,whichenablesJDBCdiagnostics.
ThefollowingexampleistheDataSourceaddedto server.xml whenyouusethe diagnostics templatetocreateatcRuntimeinstance:
<Resourceauth="Container"driverClassName="com.mysql.jdbc.Driver"factory="com.springsource.tcserver.serviceability.request.DataSourceFactory"initialSize="10"jdbcInterceptors="ConnectionState;StatementFinalizer;SlowQueryReportJmx(threshold=10000)"jmxEnabled="true"logAbandoned="true"maxActive="100"maxWait="10000"minEvictableIdleTimeMillis="30000"minIdle="10"name="jdbc/TestDB"password="password"removeAbandoned="true"removeAbandonedTimeout="60"testOnBorrow="true"testOnReturn="false"testWhileIdle="true"timeBetweenEvictionRunsMillis="5000"type="javax.sql.DataSource"url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"username="root"validationInterval="30000"validationQuery="SELECT1"/>
Eventhoughthe jdbcInterceptors attributedoesnotinclude ThreadQueryReport ,diagnosticswillbeproducedforthisDataSourcebecauseitusesthecom.springsource.tcserver.serviceability.request.DataSourceFactory .
ConfiguringatcRuntimeInstancetoObtainItsJMXCredentialsfromLDAPBydefault,theuserconfiguredtoaccessatcRuntimeinstanceviaJMXisconfiguredinthe jmxremote.access and jmxremote.password filesintheINSTANCE-DIR/conf directory.Monitoringapplications,suchasVMwareHyperic,mustinturnspecifythisusersothattheapplicationisabletomonitorandmanagethetcRuntimeinstanceusingJMX.Sometimes,however,itispreferableforthetcRuntimeinstancetouseLDAPtostoreandobtaintheJMXusercredentials.Thetasksrequiredtoconfigurethisusecaseisdescribedinthissection.
PrerequisitesCreate,orgetthelocationof,theappropriateLDAPconfigurationfile.TheformatofthefileshouldreflecttheLdapLoginModule class.ThefollowingexampleshowsasnippetfromanLDAPconfigurationfilewhichwillbelaterreferencedinthetcRuntimeinstanceconfiguration:
CorporateLDAP{com.sun.security.auth.module.LdapLoginModuleREQUIREDuserProvider="ldap://ldap.corporate.com/CN=Users,DC=corporate,DC=com"authIdentity="{USERNAME}"userFilter="(&samAccountName={USERNAME})(userPrincipalName={USERNAME})(cn={USERNAME}))(objectClass=user))"authzIdentity="admin"useSSL=false;};
Procedure1. ModifytheenvironmentfileofthetcRuntimeinstance( INSTANCE-DIR/bin/setenv.sh onUnixor INSTANCE-DIR\bin\setenv.bat onWindows)byadding
the -Djava.security.auth.login.config=ldap-config-file optiontothe JAVA_OPTS environmentvariable,where ldap-config-file isthenameoftheLDAPconfigurationfile.Forexample,onUnixthevariablemightlooklikethefollowing:
©CopyrightPivotalSoftwareInc,2013-2016 38 3.x
JAVA_OPTS="$JVM_OPTS$AGENT_PATHS$JAVA_AGENTS$JAVA_LIBRARY_PATH-Djava.security.auth.login.config=ldap.config"
Intheexample,theLDAPconfigurationfileiscalled ldap.config anditislocationinthesamedirectoryasthetcRuntime’s setenv.sh file.Useanabsolutefilenameiftheconfigurationfileisinadifferentlocation.
2. Modifythe INSTANCE-DIR/config/server.xml configurationfileofthetcRuntimeinstancebyaddingthe ldapConfigEntry attributetothecom.springsource.tcserver.serviceability.rmi.JmxSocketListener Listener,specifyingtheappropriateentryintheLDAPconfigurationfile.Forexample,assumeyouwanttousethe CorporateLDAP LDAPconfigurationentryshowninthePrerequisites;thecorresponding server.xml filewouldlooklikethefollowing:
<ListenerclassName="com.springsource.tcserver.serviceability.rmi.JmxSocketListener"ldapConfigEntry="CorporateLDAP"port="${base.jmx.port}"bind="127.0.0.1"useSSL="false"passwordFile="${catalina.base}/conf/jmxremote.password"accessFile="${catalina.base}/conf/jmxremote.access"authenticate="true"/>
Important:The ldapConfigEntry option,ifsetcorrectly,overridesthe passwordFile option.However,ifthetcRuntimeinstanceisunabletofindtheLDAPconfigurationfilethatyouspecifiedinthe setenv.sh|bat file,oryoudonotspecifyanLDAPentryforthe JmxSocketListener asshownaboveoritdoesnotexistintheLDAPconfigurationfile,thetcRuntimeinstancelogsawarningandtriestousethe passwordFile optioninstead.
3. RestartthetcRuntimeinstanceforyourchangestotakeeffect.
BashCompletionWhenyouinstalltcServerviaaRPMpackageormanuallysetupbashcompletion anduseaBashshellbashcompletionisavailablefortcruntime-instance.sh,tcruntime-ctl.sh,andtcruntime-admin.sh.
Thecompletionfeaturemaybeusedbypressingthe<tab>keyafterthecommand.Thiswillattempttoautocompletethecommand.Pressing<tab>twicewillshowalistofavailablewordswhichcouldbeusedtocompletethecommand.
tcruntime-instance.shPressing<tab>keywillhelpcompletethecommandlineoptions.Thefollowingisanexampleofusingbashcompletionwithtcruntime-instance.sh.
tcruntime-instance.shcr<tabmy-instance--la<tab>c<tab>
Thiswillproducethefollowingfulltextcommandline
tcruntime-instance.shcreatemy-instance--layoutcombined
tcruntime-ctl.shAswithtcruntime-instance.shbashcompletionisavailable.Thiscommandhastheaddedfeatureofautocompletinginstancenames.Inthefollowingexampletherearethreeinstancesnamed“instance”,“demo”,“test”.
tcruntime-ctl.shd<tab>start
Thiswillproducethefollowingfulltextcommandline
tcruntime-ct.shdemostart
tcruntime-admin.shAswiththeothertwocommandsbashcompletionisavailable.Bashcompletiondoesnotcurrentlysupportcompletingruntimeversionsoftemplatenames.Thefollowingisanexampleofcompletionfordownloadingtheredis-session-managertemplatefromthePivotalTemplateRepository.
©CopyrightPivotalSoftwareInc,2013-2016 39 3.x
tcruntime-admin.shget-t<tab>redis-session-manager
Thiswillproducethefollowingfulltextcommandline
tcruntime-admin.shget-templateredis-session-manager
©CopyrightPivotalSoftwareInc,2013-2016 40 3.x
CreatingandManagingtcServerTemplatesAtemplateprovidesconfigurationinformationandfilestosupportafeatureorapplicationonatcRuntimeinstance.Thebuilt-intemplatesthatshipwithtcServermakeitsimpletoconfiguretcRuntimefeaturessuchasSSLorJMXortoaddamanagementapplicationtoaninstanceatcreationtime,suchasSpringInsight.
Youcancreateyourowntemplatesbycreatingasubdirectoryinthe templates directoryofyourtcServerinstallationdirectoryandpopulatingitwithfilesaccordingtotheinstructionsinthissection.Youcould,forexample,constructatemplatethatallowscreatingatcRuntimeinstancewithawebapplicationorsetofwebapplicationsreadytodeploy,withacustomconfigurationspecifiedatthe tcruntime-instancecreate commandlineorthroughinteractiveprompts.
Atemplateisadirectorycontainingfilesthatthe tcruntime-instancecreate commandprocesseswhenitcreatesanewtcRuntimeinstance.SomefilesarecopieddirectlytothenewtcRuntimeinstance.OtherfilesareappliedtoconfigurationfilesinthetcRuntimeinstance;thatis,theyareusedtoalterthecontentofstandardconfigurationfiles,suchas conf/server.xml .
Filesyouplaceinthetemplatedirectorythatarenotinterpretedspeciallybytheinstancecreationscriptsarecopiedintothenewinstance.Forexample,ifyourwebapplicationrequiresJARlibraries,youcancreatea lib subdirectoryandplacetheJARfilesthere.IfyouhaveaWARfiletodeploy,putitinawebapps subdirectoryanditwillbecopiedtothe webapps subdirectoryofthenewtcRuntimeinstance.
Thetargetplatform(WindowsorUnix)andtheJVM(SunHotSpotorIBMJ9)arerecognizedatinstancecreationtimeandvariablesarehandledaccordingly,filesomittedfromthecopywhenappropriate.YourLinuxtcRuntimeinstanceswillnothaveunneeded .bat or .dll files.Pathnamesandenvironmentvariablesareautomaticallyhandledwiththecorrectsyntaxforthetargetplatform.
PartsofaTemplateAtemplatedirectorycontainsatminimuma README.txt file.Theothercontentsdependonthepurposeofthetemplate.Thefollowingsectionsdescribethekindsoffilesthatatemplatecanhave.
README.txt
Environment
XMLConfigurationFragments
LoggingPropertiesFragment
ModifyingPropertiesFiles
OtherFiles
README.txtAtemplatemusthavea README.txt fileinitsrootdirectory.Thisfileisasynopsisoftheconfigurationandcontentthatthetemplateprovidestoaninstance.Thefileshouldnothavethenameofthetemplate,butaversionandbuilddateareconsideredbestpractices.Whenindoubt,lookattheexamplesprovidedbythetemplatespackagedintcRuntime.
Whenaninstanceiscreated,thecontentofthe README.txt filesineachtemplatearecombinedintoasingle README.txt filethatisplacedintherootofthecreatedinstance.Thecombined README.txt filedocumentsthetemplates’contributionstothenewlycreatedinstance.
Followingisthe README.txt filethatistheresultofcreatinganinstanceusingthe base , bio ,and bio-ssl templates.
©CopyrightPivotalSoftwareInc,2013-2016 41 3.x
OperatingSystemFamily:unixVirtualMachineArchitecture:x64VirtualMachineName:hotspot========================================================================================================================Template:baseVersion:2.8.0.RELEASEBuildDate:20110729092530
*SetsXmxto512M*SetsXssto192K*Addsacontrolscripttotheinstance*AddstheWindowsservicewrapperlibraries*Addsadefaultjmxremoteconfigurationwitharead/writeusercalled'admin'withapasswordof'springsource'*AddsadefaultJULIloggingconfiguration*Addsadefaultserverconfigurationcontaining:*AJREmemoryleakpreventionlistener*AtcRuntimeDeployerlistener*AJMXsocketlistener*ALockOutRealmtopreventattemptstoguessuserpasswordsviaabrute-forceattack*Anin-memoryuserdatabase*Athreadpoolthathasupto300threads*Ahostthatuses'webapps'asitsappbase*AnAccessLogValve*AddsadefaultTomcatuserconfigurationthatisempty*Addsaninit.dscriptconfiguredtostarttheinstanceasaspecificuser*Addsarootwebapplication========================================================================================================================Template:base-tomcat-7Version:2.8.0.RELEASEBuildDate:20110729092530
*AddsTomcat7-specificThreadLocalLeakPreventionListener*AddsTomcat7-specificcatalina.properties*AddsTomcat7-specificdefaultcatalina.policytobeusedwhenstartingwiththe-securityoption*AddsTomcat7-specificJspServletconfiguration*AddsTomcat7-specificweb-appdeclaration========================================================================================================================Template:nioVersion:2.8.0.RELEASEBuildDate:20110729092530
*AddsaNon-blockingIO(NIO)connectorforHTTP========================================================================================================================Template:nio-sslVersion:2.8.0.RELEASEBuildDate:20110729092530
*AddsaNon-blockingIO(NIO)connectorforHTTPS*AddssamplecertificateandkeyfilesthatcanbeusedtotesttheSSLconfiguration
NOTE:Thesamplecertificateandkeyfilesarenotsuitableforproductionsystems.========================================================================================================================
EnvironmentAtemplatemaycontributea bin/setenv.properties filecontainingplatform-agnosticenvironmentalconfiguration.Thisfileisturnedinto bin/setenv.sh onUnixmachinesand bin/setenv.bat and conf/wrapper.conf filesonWindowsmachines.Thefilemaycontainpropertieswithanyofthefollowingwell-knownkeys.
Table1.setenv.propertiesKeys
Key Description
class.path.# AddsaJARtotheJavaclasspath.
java.library.path.# Thepathtoanativelibrary.Itisaddedtothe java.library.path intheJVMcommandline.
java.opt.# AJVMoptiontobeaddedtotheJVMcommandline.
Eachofthesekeyscanbedeclaredmultipletimesbyincrementingitsdigitsuffix.Anexampledeclaringtwoentriesfor java.library.path follows.
java.library.path.1=${catalina.base}/bin/amd64-linuxjava.library.path.2=${pivotal.tools.location:/usr/lib/vmware-tools}/lib/libvmGuestLib.so
Youcanspecifyyourownenvironmentvariables bin/setenv.properties .Notethatyouwhenyoudefinesuchvariables,youmustappendthevariablename
©CopyrightPivotalSoftwareInc,2013-2016 42 3.x
withanumericsuffix,forexample: premyapp.options.1=-Dproperty1=value1myapp.options.2=-Dproperty2=value2
ThecustompropertiesconvertasMYAPP.OPTIONS=“value1value2”inthe CATALINA_BASE/bin/setenv.sh (Unix)or CATALINA_BASE/bin/setenv.bat (Windows)file.
AutomaticBoilerplateDecoration
Entriesforthe setenv.properties keysdonotneedtohaveboilerplatetextattached.Whenthetemplateisprocessed,thevaluesareprocessedtocreatecommandlineoptionswiththecorrectplatform-andJVM-specificsyntax.Thefollowingtabledescribeswhatwillbeprependedtoeachentry.
Table2.AutomaticBoilerplateDecoration
java.agent.1=value-1java.agent.2=value-2
-javaagent:value-1-javaagent:value-2
agent.path.1=value-1agent.path.2=value-2
-agentpath:value-1-agentpath:value-2
class.path.1=value-1class.path.2=value-2
value-1:value-2
java.library.path.1=value-1java.library.path.2=value-2
-Djava.library.path=value-1:value-2
myapp.options.1=value1myapp.options.2=value2
MYAPP_OPTIONS="-Dproperty1=value1-Dproperty2=value2"
MemoryandStackSizeJAVA_OPTSFiltering
ThereareafewcommonpropertiesthatareregularlysettocontrolmemoryandstacksizeoftheVM.Incaseswhereduplicatevaluesforthesearefoundduetothecombinationoftemplates,thelargestvalueofeachwillbechosen.Thelistofthesepropertiesfollows.
-Xmx
-Xms
-Xss
-XX:MaxPermSize
JVMTypeSpecificProperties
ToensurethatapropertyisonlyusedforaspecificJVMtype,thewell-knownkeyscanbequalifiedwithvaluesofthe vm.name property.Thevaluemustbelocatedbetweenthebasekeyandtheincrementingdigit,delimitedby’ . ’characters.Forexample:
java.opt.hotspot.1=+XX:MaxPermSize=1024Mjava.opt.j9.2=-Xaggressive
OSFamilySpecificProperties
©CopyrightPivotalSoftwareInc,2013-2016 43 3.x
Toensurethatapropertyisonlyusedforaspecificoperatingsystemfamily,thewell-knownkeyscanbequalifiedwithvaluesofthe os.family property.Thevaluemustbelocatedbetweenthebasekeyandtheincrementingdigit,delimitedby’ . ’characters.Anexampleusingthe os.family propertyfollows.
java.library.path.unix.1=${pivotal.tools.location:/usr/lib/vmware-tools}/lib/libvmGuestLib.sojava.library.path.windows.2=${pivotal.tools.location:C:\ProgramFiles\Pivotal\PivotalTools}
VMArchitectureSpecificProperties
ToensurethatapropertyisonlyusedforaspecificVMarchitecture,thewell-knownkeyscanbequalifiedwithvaluesofthe vm.arch property.Thevaluemustbelocatedbetweenthebasekeyandtheincrementingdigit,delimitedby’ . ’characters.Anexampleusingthe vm.arch propertyfollows.
java.library.path.unix.x64.1=${catalina.base}/bin/amd64-linuxjava.library.path.unix.x86.2=${catalina.base}/bin/x86-linux
CombiningValuesinQualifiedProperties
Thewell-knownkeyscanbequalifiedwithvaluesofanycombinationoftheimplicitproperties.Thesevaluesmustbelocatedbetweenthebasekeyandtheincrementingdigit,delimitedby’ . ’characters,butcanbeinanyorder.Anexampleusingthe os.family , vm.arch ,and vm.name propertiesfollows.
java.library.path.unix.x64.hotspot.1=${catalina.base}/bin/amd64-linux
XMLConfigurationFragmentsAtemplatemaycontributeanyofthefollowingXMLconfigurationfiles.
conf/server-fragment.xml
conf/web-fragment.xml
conf/context-fragment.xml
conf/tomcat-users-fragment.xml
ThesefilescontributetothestandardTomcatconfigurationfileofthesamename,lessthe "-fragment “portionofthename.InsidethefileisanXMLfragmentthatdescribeswhatistobeadded,removed,orupdatedintherespectiveconfigurationfile.TheXMLfragmentdescribesitscontributionsusingthe add: and remove: keywordsonelementsandattributesandthe update: keyword,whichcanonlybeusedonattributes.Inaddition,otherXMLelementsaredefinedtodescribeasingleXMLelementthatthecontributionsshouldactupon.TheXMLelementsthatexistcanbethoughtofasadirectexampleofanXPathexpression.ForexampletheXPathexpression //Server/Service[@name="Catalina"] wouldberepresentedasfollows.
<?xmlversion='1.0'encoding='utf-8'?><Server><Servicename="Catalina"></Service></Server>
AmorecomplexexampleoftheXPathexpression //Server/Service[@name="Catalina"]/Engine[@name="Catalina"][@defaultHost="localhost"] isrepresentedasfollows.
<?xmlversion='1.0'encoding='utf-8'?><Server><Servicename="Catalina"><Enginename="Catalina"defaultHost="localhost"></Engine></Service></Server>
OnceanelementhasbeenspecifiedusinganXMLfragment,contributionscanthenbespecified.Theycouldbeupdatesandadditionsofattributes,asillustratedinthefollowingexample.
©CopyrightPivotalSoftwareInc,2013-2016 44 3.x
<?xmlversion='1.0'encoding='utf-8'?><Server><ListenerclassName="com.springsource.tcserver.serviceability.rmi.JmxSocketListener"update:useSSL="true"add:useJdkClientFactory="true"passwordFile="${catalina.base}/conf/jmxremote.password"accessFile="${catalina.base}/conf/jmxremote.access"add:keystoreFile="${catalina.base}/conf/tcserver.keystore"add:keystorePass="changeme"add:truststoreFile="${catalina.base}/conf/tcserver.keystore"add:truststorePass="changeme"update:authenticate="false"/></Server>
Whenaddinganelement,oncetheelementhasbeenmarkedas add: ,itisunnecessarytoalsomarktheattributesofthenewelement.Anexampleofaddinganelementwithoutmarkingitsattributesfollows.
<?xmlversion='1.0'encoding='utf-8'?><Server><Servicename="Catalina"><add:Connectorexecutor="tomcatThreadPool"port="${http.port:8080}"protocol="org.apache.coyote.http11.Http11Protocol"connectionTimeout="20000"redirectPort="${https.port:8443}"acceptCount="100"maxKeepAliveRequests="15"/></Service></Server>
Itisunnecessarytomarkanysub-elementswith add: whentheparentelementismarked.Anexampleaddinganelementwithsub-elementswithoutmarkingitssub-elementsfollows.
<?xmlversion='1.0'encoding='utf-8'?><Server><Servicename="Catalina"><Enginename="Catalina"defaultHost="localhost"add:jvmRoute="${node.name:tc-runtime-1}"><add:ClusterclassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"channelSendOptions="8"><ManagerclassName="org.apache.catalina.ha.session.DeltaManager"expireSessionsOnShutdown="false"notifyListenersOnReplication="true"/><ChannelclassName="org.apache.catalina.tribes.group.GroupChannel"><MembershipclassName="org.apache.catalina.tribes.membership.McastService"address="203.0.113.4"port="45564"frequency="500"dropTime="3000"/><ReceiverclassName="org.apache.catalina.tribes.transport.nio.NioReceiver"address="auto"port="4000"autoBind="100"selectorTimeout="5000"maxThreads="6"/><SenderclassName="org.apache.catalina.tribes.transport.ReplicationTransmitter"><TransportclassName="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/></Sender><InterceptorclassName="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/><InterceptorclassName="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/></Channel><ValveclassName="org.apache.catalina.ha.tcp.ReplicationValve"filter=""/><ValveclassName="org.apache.catalina.ha.session.JvmRouteBinderValve"/><ClusterListenerclassName="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/><ClusterListenerclassName="org.apache.catalina.ha.session.ClusterSessionListener"/></add:Cluster></Engine></Service></Server>
SpecifyingtheLocationofaNewElementinanXMLConfigurationFile
WhenyouuseatemplateXMLfragmentfiletoaddanewelementtoanXMLconfigurationfile,thenewelementisaddedtothebottomoftheparentelementbydefault.Sometimes,however,youmightneedtospecifyanexactlocationforthenewelementintheXMLfile.Forexample,therearesome<Listener> elementsthatmustappearasthefirstchildelementsoftheroot <Server> elementatthetopofthe conf/server.xml file;iftheyareaddedtothebottomofthefile,thetcRuntimeinstancewillnotstart.
©CopyrightPivotalSoftwareInc,2013-2016 45 3.x
YouspecifytheexactlocationofthenewelementbyalsoincludingthesiblingelementthatshouldappearafterthenewelementintheXMLfragmentfile.Atinstance-creationtimewhenthetemplateisbeingapplied,ifthesiblingelementisfound,thenewelementwillbeaddedbeforeit.If,however,thesiblingelementisnotfound,thenewelementwillbeaddedatthebottomofitsparentelement(thedefaultbehavior).
Forexample,assumetheoriginal server.xml file,beforethetemplateisapplied,lookslikethefollowing(someelementsremovedforclarity):
<?xmlversion="1.0"?><Serverport="${base.shutdown.port}"shutdown="SHUTDOWN"><ListenerclassName="org.apache.catalina.core.JasperListener"/><ListenerclassName="org.apache.catalina.core.JreMemoryLeakPreventionListener"/><ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>...</Server>
Ifyouwantyourtemplatetoaddanew <Listener> elementrightbeforetheonewithclassname org.apache.catalina.core.JreMemoryLeakPreventionListener ,createtheXMLfragmentfilesimilartothefollowing:
<?xmlversion='1.0'encoding='utf-8'?><Server><add:ListenerclassName="com.springsource.tcserver.properties.SystemProperties"file.1="${catalina.base}/local/environment.properties"file.2="${catalina.base}/local/credentials.properties"immutable="false"trigger="now"/><ListenerclassName="org.apache.catalina.core.JreMemoryLeakPreventionListener"/></Server>
AfterthetemplateisappliedtoanewtcRuntimeinstance,the server.xml filewilllooklikethefollowing:
<?xmlversion="1.0"?><Serverport="${base.shutdown.port}"shutdown="SHUTDOWN"><ListenerclassName="org.apache.catalina.core.JasperListener"/><ListenerclassName="com.springsource.tcserver.properties.SystemProperties"file.1="${catalina.base}/local/environment.properties"file.2="${catalina.base}/local/credentials.properties"immutable="false"trigger="now"/><ListenerclassName="org.apache.catalina.core.JreMemoryLeakPreventionListener"/><ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>...</Server>
LoggingPropertiesFragmentAtemplatemaycontributea conf/logging-fragment.properties file.ThisfilecontributestothestandardTomcat conf/logging.properties file.Thepropertiesfragmentdescribesitscontributionsbyprefixingpropertykeyswiththe add. keyword,asshowninthefollowingexample.
##############################################################Valuesforcom.vmware.jem.levelare:#WARNING,INFO,CONFIG,FINE,FINER,FINEST#############################################################add.com.vmware.jem.level=${loggingLevel:INFO}add.com.vmware.jem.handlers=java.util.logging.ConsoleHandleradd.java.util.logging.ConsoleHandler.formatter=com.vmware.jem.BalloonLogFormatter
ModifyingPropertiesFilesThefollowingtabledescribestheprefixesthatyoucanaddtoyourcustomtemplatetomodifythepropertiesfilesinaninstance.
Table3.PropertiesFileModificationPrefixes
add.my-property=my-value1,my-value2
©CopyrightPivotalSoftwareInc,2013-2016 46 3.x
add Addsthepropertytothepropertiesfile.
Addsmy-property=my-value1,myvalue2tothepropertiesfile.
2.5+
append
Appendsthespecifiedvaluetotheendofthecurrentvalueofthatproperty.Theprefixaddsthepropertyifitdoesnotalreadyexist.
append.my-property=appended-value
Appendsthespecifiedvaluetotheexistingmy-propertypropertyvalue:
my-property=my-previous-value,appended-value
2.9.5+
append-delimiterChangesthedefaultdelimiter(acomma)tothespecifieddelimitercharacter.
append-delimiter.my-property=;
Changesthedelimitertoasemicolonforthemy-property=previous-value;appended-valuepropertyvalue
2.9.5+
deleteRemovesthepropertyfromthepropertiesfile.
delete.my-property=
Removesthemy-propertypropertyfromthepropertiesfile.
2.9.5+
updateReplacesthecurrentpropertyvaluewiththespecifiedvalue.
update.my-property=my-new-value
Replacesthecurrentmy-propertypropertyvaluewiththespecifiedvalue.
2.9.5+
OtherFilesAnyotherfileinthetemplatethatisnotspecificallyexcluded(seePlatformSpecificity)iscopieddirectlytotheinstance.PropertiesfilesandXMLfileshavetheircontentsubstitutedwhencopied.
Ifafileclasheswithafilecontributedbyanothertemplate,awarningisdisplayedtotheuserandthelaterfilewillreplacetheearlierfile.Orderingoftemplateapplicationisdependentonuserinputandmayvary.
PropertySubstitutionPropertysubstitutionallowsyoutocustomizetcRuntimeinstancesbyprovidinginstance-specificvaluesatcreationtime.The tcruntime-instance scriptscansforpropertyplaceholdersinfiles.Itsubstitutesavaluethatisderivedfromadefaultoranotherdefinedproperty,orsuppliedinteractivelybytheuserwhenthescriptisrunwiththe --interactive option.Propertysubstitutionoccursinthe bin/setenv.properties file,theloggingpropertiesfragment,allpropertiesfiles,andXMLcompleteandfragmentfiles.
Thesyntaxforaplaceholderisasfollows:
${property-name[:default-value]}
ImplicitPropertiesTemplatesareprovidedasasetofimplicitproperties,determinedatinstancecreationtime.Theyaregenerallyspecifictotheplatformwheretheinstanceiscreatedandthe JAVA_HOME theinstancewilluseatruntime.Thelistofimplicitpropertiesandtheirpossiblevaluesareshowninthefollowingtable.
©CopyrightPivotalSoftwareInc,2013-2016 47 3.x
Table4.ImplicitProperties
os.family
unix
windows
vm.arch
x64
x86
vm.name
hotspot
j9
catalina.base
$CATALINA_BASE
%CATALINA_BASE%
catalina.home
$CATALINA_HOME
%CATALINA_HOME%
ConfigurationPromptsWhenauserrunstheinstancecreationscriptininteractivemode,thescriptpromptsforanypropertynotspecifiedaspartofthecommand.Thestandardpromptis Pleaseenteravaluefor'%s'.Default'%s': whenadefaultisprovidedand Pleaseenteravaluefor'%s': whennodefaultisprovided.Thesepromptsaregenericandnotgoodathelpingtheuserselectausefulvalue.Youcanprovidemorehelpfulcustomprompttext.Todothis,atemplatemustcontainaresourcebundlecalled configuration-prompts.properties intherootofthetemplate.Thisbundlecontainsthetexttodisplaywhenpromptingforavalue.Inaddition,thepromptcanincludethedefaultvalueforthepropertybyembeddingthe ${default} placeholderinthetext.Forexample:
pivotal.tools.location=EnterthepathtothePivotaltoolsinstallation.Thedefaultpathis'${default}'\:
ThetemplateuseracceptsthedefaultbypressingEnterwithoutenteringavalue.
Configurationpromptscanbelocalizedforparticularlanguagesandcountries.Todothis,appendlanguageandcountrycodestothefilename.Forexample,aresourcebundlecontaininglocalizedpromptsforSpanishspeakerswouldbecalled configuration-prompts_es.properties .
PlatformSpecificityWhenatcRuntimeinstanceiscreated,somefilesarenotcreatedorcopiedtotheinstancebecausetheyarenotrequiredbythetargetplatform.Forexample,thereisnobenefittocopyingWindows .bat filestoaLinuxhost.Inaddition,somefilesareusedbythetemplate,ortodocumentthetemplate,andarenotcopiedintotheinstance.
FilesExcludedonUnixWhenatemplateisrenderedonaUnixplatform,Windowsplatform-specificfilesarenotrenderedintheinstance.Thisincludesfilesmatchedbythefollowingpatterns:
**/*.bat
**/*.dll
**/*.exe
**/amd64-winnt/**
**/x86-winnt/**
**/win32/**
**/winx86_64/**
FilesExcludedonWindows
©CopyrightPivotalSoftwareInc,2013-2016 48 3.x
WhenatemplateisrenderedonaWindowsplatform,Unixplatform-specificfilesarenotrenderedintheinstance.Thisincludesfilesmatchedbythefollowingpatterns:
**/*.sh
**/*.so
**/amd64-linux/**
**/x86-linux/**
TemplateFilesExcludedFilesmatchingthefollowingpatternsarenotcopieddirectlyintoatcRuntimeinstance:
README.txt
bin/setenv.properties
conf/*-fragment.properties
conf/*-fragment.xml
configuration-prompts(_([A-Za-z])+)?.properties
SplittingaTemplateforTomcatVersionsThe base templateisanexampleofatemplatethatprovidesdifferentoptionsdependingonwhetherthetargetinstanceusesTomcat7orTomcat8.ThisisageneralizedfeaturethatyoucanuseifyouhavedifferentconfigurationoptionsorfilecontributionsforTomcat7andTomcat8.
The base templatehasthreeparts:
TemplateName Description AvailableSince
base ThefilesinthisdirectoryareprocessedforbothTomcat7andTomcat8instances. 2.0
base-tomcat-7 ThefilesinthisdirectoryareprocessedonlyifthetargetinstanceusesaTomcat7runtime. 2.0
base-tomcat-8 ThefilesinthisdirectoryareprocessedonlyifthetargetinstanceusesaTomcat8runtime. 3.0
base-tomcat-85 ThefilesinthisdirectoryareprocessedonlyifthetargetinstanceusesaTomcat8.5runtime. 3.2
YoucancreateacustomtemplatewithdifferentoptionsfortcRuntime7,tcRuntime8,andtcRuntime8.5byusingthesamedirectorynamingconvention.
NoteIntcServer3.2,anytemplateswiththe -tomcat-8 extension,mustberenamedto -tomcat-85 ,otherwiseitwillnotbeseenasatcRuntime8.5template.
ManagingTemplatesThe get-template commandenablesatcServeradmintodownloadandinstallatemplatefromthetcServertemplateRepository,aremotelocationusingeitherthehttporhttpsprotocol,alocalzipfile,ordirectorypath.
UsageExecute get-template withthecommand:
tcruntime-admin.shget-template<name>[OPTIONS]
Thefollowingoptionsareavailable:
Table5.get-templateoptions
Option Description AvailableSince
©CopyrightPivotalSoftwareInc,2013-2016 49 3.x
-d ,--source-directory
Designatedthe <name> valueasalocaldirectory. 3.2.0
-e ,--templates-directory
Customtemplatedirectorylocationtodownloadandinstallthetemplate. 3.2.0
-f , --file Designatesthe <name> valueasalocalfilepathtothetemplate. 3.1.0
-h , --help Printsusageinformationfor get-template . 3.1.0
-l , --list Liststheavailabletemplatesinthetemplaterepository. 3.2.0
--no-overwriteDonotoverwritethetemplatedirectoryifitalreadyexists.Ifneither–no-overwriteor–overwritearespecifiedthenitwillprompttooverwrite.
3.2.0
--overwriteOverwritethetemplatedirectoryifitalreadyexists.Ifneither–no-overwriteor–overwritearespecifiedthenitwillprompttooverwrite.
3.2.0
-p ,--password<password>
PasswordtousewithanauthenticatedURL.Ifthisoptionisomittedandusernameisspecifiedthenyouwillbepromptedtoenterpassword.
3.1.0
-u , --url DesignatesthesourcetemplatelocationasaURL[default].OnlyhttporhttpsURLsaresupported. 3.1.0
-U ,--username<username>
UsernametousewithanauthenticatedURL. 3.1.0
Option Description AvailableSince
ExamplesListingthecontentsofthetemplaterepository:
./tcruntime-admin.shget-template--listAvailableTemplates:
redis-session-manager-OverridesdefaultsessionmanagerandstoresHTTPsessionsinRedisinstancegemfire-session-manager-OverridesdefaultsessionmanagerandstoresHTTPsessionsinGemFireinstancespring-insight-operations-SpringInsightOperations
RetrievetheGemFiresessionmanagertemplatefromthetemplaterepository:
./tcruntime-admin.shget-templategemfire-session-manager
Todownloadandinstallatemplatefromawebserver:
./tcruntime-admin.shget-templatehttp://templates.example.com/default_template.zip--url
Touseafileavailableonthelocalfilesystem:
./tcruntime-admin.shget-template/var/templates/default_template.zip--file
Touseadirectoryonthelocalfilesystem:
./tcruntime-admin.shget-template/var/templates/default_template--source-directory
©CopyrightPivotalSoftwareInc,2013-2016 50 3.x
ManagingPlannedandUnplannedOutagesThissectiondescribeshowtomanagebothplannedandunplannedoutagesofPivotaltcServer.
ManagingPlannedOutagesInaplannedoutage,youscheduleatimewhentcRuntimeinstanceswillbebrieflyunavailablesothatyoucanperformmaintenanceontheinstanceordeployedapplications,createcoldbackups,andsoon.TheproceduredescribeshowtostopalltcRuntimeinstances.
Procedure1. IfyouareusingaWebServerasaload-balancerorproxyinfrontofoneormoretcRuntimeinstances,drainallcurrentlyopenedsessionsbetween
theWebServerandthetcRuntimeinstances.Forexample,ifyouareusingPivotalWebServer,youcansimplystoptheinstanceusingthe httpdctl command,asshowninthefollowingUnixsample:
prompt#cd/opt/pivotal/pivotal-web-server/myserver/binprompt#./httpctlstop
Intheprecedingexample,thePivotalWebServerinstanceislocatedinthe /opt/pivotal/pivotal-web-server/myserver directory.The stop commandforciblyendsallsessions.TospecifythatyouwanttheWebServerinstancetowaituntilallsessionsendgracefully,usethegracefulstop command:
prompt#./httpdctlgracefulstop
2. OnthecomputeronwhichthetcRuntimeinstancesareinstalled,stopallinstances.Forexample,onUnix:
prompt$cd/opt/pivotal/pivotal-tc-server-standardprompt$./tcruntime-ctl.sh-n/var/opt/pivotal/pivotal-tc-server-standardmyserverstop
Intheprecedingexample,PivotaltcServerisinstalledin /opt/pivotal/pivotal-tc-server-standard ,thenameoftheinstanceis myserver ,andtheinstancedirectoryis /var/opt/pivotal/pivotal-tc-server-standard .SeeStartingandStoppingtcRuntimeInstances foradditionaldetails,suchasWindowsinstructions.
WhenyoustoptcRuntimeinstances,theWebapplicationsthataredeployedtotheinstancesarenotavailabletousers.Youcannowsafelyperformmaintenanceontheinstance,suchasupdateitsconfigurationandcreateacoldbackup.
ManagingUnplannedOutagesAnunplannedoutageisonethatyoudonotschedule.Unplannedoutagescanbeminor,suchasapowerfailurethatcausesthetcServercomputertoshutdownungracefully,ormorecriticaloutagessuchasahard-diskfailure.
Typically,ifyouhavefullyrestoredandrestartedthecomputeronwhichtcServerisinstalled,allyouneedtodonextisstartthetcRuntimeinstances.Checkthe catalina.out and catalina.log logfilesinthe INSTANCE-DIR/logs directorytoensurethatnofailuresoccurredduringstartupandthattheconfigurationfilesarenotcorrupted.Invokeyourdeployedapplicationstoverifythattheyareworkingcorrectly.
IfthelogfilesindicatethatthetcRuntimeinstancedidnotstartbecause,forexample,theconfigurationfilesarecorrupted,oryourdeployedapplicationsdonotseemtobeworkingcorrectly,youshouldrestoretheinstancedirectoryfromarecentcoldbackup.Thefollowingproceduredescribeshowtodothis.
Procedure1. EnsurethatyouhaveyouhavearecentcoldbackupofthetcRuntimeinstancethatcontainsthelastknowngoodconfigurationanddeployedWeb
applications.
2. Ifnecessary,stopalltcRuntimeinstances.Forexample,onUnix:
©CopyrightPivotalSoftwareInc,2013-2016 51 3.x
prompt$cd/opt/pivotal/pivotal-tc-server-standardprompt$./tcruntime-ctl.shmyserverstop-n/var/opt/pivotal/pivotal-tc-server-standard
Intheprecedingexample,PivotaltcServerisinstalledin /opt/pivotal/pivotal-tc-server-standard ,thenameoftheinstanceis myserver ,andtheinstancedirectoryis /var/opt/pivotal/pivotal-tc-server-standard .SeeStartingandStoppingtcRuntimeInstances foradditionaldetails,suchasWindowsinstructions.
3. Changetotheparentdirectoryoftheinstance,thenrenametheinstancedirectory.Forexample:
prompt$cd/var/opt/pivotal/pivotal-tc-server-standardprompt$mvmyservermyserver-backup
Note:Thisisjustaprecautionarystep;youcanremovethistemporarybackuponceyoufullyrestoretheinstancefromthecoldbackup.
4. Unziporun-taryourbackupappropriately.Forexample,ifyoucreatedaTARfileonUnixasdescribedinBackingUptcServerandtheTARfileiscalled myserverBackup-20120922.tar ,executethefollowingcommands:
prompt$cd/var/opt/pivotal/pivotal-tc-server-standardprompt$tarxvfmyserverBackup-20120922.tar
5. StarttheinstancetomakeyourWebapplicationsavailableagain:
prompt$cd/var/opt/pivotal/pivotal-tc-server-standard/myserver/binprompt$./tcruntime-ctl.shstart
Theprecedingcommandshowshowtostarttheinstanceusingthe tcruntime-ctl.sh commandfromtheinstance’s bin directorywhichisthesameasusingthe tcruntime-ctl.sh commandfromthetcServerinstallationdirectory.Usethemethodthatismostconvenienttoyourenvironment.
6. Checkthe logs/catalina.out and logs/catalina.date.log filestoensurethattheinstancestartedwithouterrors,theninvokeyourWebapplicationsandensurethattheyareworkingcorrectly.
IfyoulostalldataonthecomputeronwhichtcServerwasinstalled,firstre-installtcServer andthenfollowtheprecedingproceduretorestoreeachtcRuntimeinstance..
BackingUpPivotaltcServerWhenbackinguptcServer,youneedtocreateonlybackupsofyourtcRuntimeinstances;youdonotneedtobackupthetcServerinstallationitselfbecauseyoucanalwaysreinstallitfromyouroriginaldistributionifnecessary.
Pivotalrecommendsthatyoualwaysmakecoldbackupsofyourinstances,whichmeansyouZIPorTARuptheinstancedirectoryafterstoppingtheinstance.
AhotbackupreferstocreatingaZIPorTARfileoftheinstancedirectorywithoutfirststoppingtheinstance.AlthoughonUnixthismethodmightbepossible,andyouwilllikelybeabletofullyrestoretheinstancefromthehotbackup,MicrosoftWindowsmaypreventyoufromevencreatingthehotbackupinthefirstplaceduetofile-lockingissuesduetotcRuntimeprocessesholdinglocksonfilesthatyouaretryingtobackup.Forthisreason,Pivotaldoesnotrecommendhotbackups.
Thefollowingproceduredescribeshowtoperformacoldbackup.
Procedure1. FullyshutdownthetcRuntimeinstancesandanyload-balancingWebServerasdescribedinManagingPlannedOutages.
2. CreateaZIPoraTARfileofeachtcRuntimeinstancedirectory.Forexample,ifyourinstancesarelocatedinthe /var/opt/pivotal/pivotal-tc-server-standard
directory,andyouwanttocreateaTARfileonUnixofthe myserver instance:
prompt$cd/var/opt/pivotal/pivotal-tc-server-standardprompt$tarcvfmyserverBackup-20120922.tarmyserver
ThiscreatesaTARfilecalled myserverBackup-20120922.tar withthetop-mostlevelbeingtheinstancedirectory( myserver inthiscase.)
©CopyrightPivotalSoftwareInc,2013-2016 52 3.x
EnablingClusteringforHighAvailabilityClusteringOverviewClusteringreferstogroupingoneormoretcRuntimeinstancessothattheyappeartoworkasasingleserver.Aclusterprovides:
Sessionreplication.Whenaclient,typicallyusingabrowser,connectstoatcRuntimeinstance,tcRuntimecreatesasessionObjectthatitusestomanageallsubsequentinteractionbetweenitselfandthatclient.DependingonhowtheWebapplicationwasprogrammed,thesessionObjectcancontainalotofusefulinformation,suchasusersecuritycredentials,currentitemsinauser’sshoppingcart,andsoon.IfthetcRuntimeinstanceispartofacluster,thesessionisautomaticallycopiedtoeachmemberoftheclustergroup,andisupdatedeachtimethesessionismodified,suchaswhentheuseraddsanewitemtotheirshoppingcart.ThismeansthatifthefirsttcRuntimeinstancecrashes,anytcRuntimeinstanceinthegroupcanimmediatelytakeoverthesessionwithoutinterruption,completelyhidingtheservercrashfromtheclientwhocontinuestoworkasifnothinghadhappened.ThiscapabilitygreatlyincreasestheusabilityofWebapplications.YoucanusethePivotalGemFireHTTPSessionManagementModuletoprovideHTTPsessionmanagementforatcServercluster.ThemoduleprovidestcServertemplatestoconfigureGemFiresessionmanagementineitherapeer-to-peerconfigurationorclient/serverconfiguration.Inthepeer-to-peerconfiguration,eachtcRuntimeinstancebecomesaGemFirepeer,usingmulticasttodiscovereachotherandreplicatingsessiondatabetweenthem.Intheclient-serverconfiguration,yourunaGemFirecacheserverandtcRuntimeinstancesreplicatesessiondatatothecacheserver.SeetheGemStonedocumentationforhelpobtainingthetemplatesandconfiguringGemStoneHTTPSessionManagement.
Contextattributereplication.AcontextrepresentsaWebapplicationthatisdeployedtoatcRuntimeinstance.Inthesamewaythatclientsessionscanbereplicated,theWebapplicationcontextitselfcanalsobereplicatedtoallmembersofaclustergroup.
AtcRuntimeclustercanbeassmallastwoserverinstanceshostedonthesamecomputertohundredsoftcRuntimeinstanceshostedonmanydifferentcomputersofdifferentoperatingsystems.
Typically,youconfigureatcRuntimeclustertousemulticastforthecommunicationbetweenmemberservers.TheclusteristhenuniquelyidentifiedbythecombinationofitsmulticastIPaddressandport.Eachmemberoftheclustermusthavethesamemulticastaddressandportconfiguredsothattheclustercanautomaticallydiscovereachmemberandreactappropriatelyifamemberdoesnotrespond.Youcancreatemultipleclusters,suchasonefortestingandanotherforproduction,byconfiguringdifferentmulticastaddress/portsforeachcluster.
InadditiontocreatingatcRuntimecluster,youmightalsowanttoconfigurealoadbalancerinfrontoftheclustersoastosplituptheincomingrequestsbetweenmultipletcRuntimeinstances.LoadbalancingattemptstodirectrequeststothetcRuntimeinstancewiththesmallestloadatthatpointintime.TheloadbalancercanalsodetectwhenatcRuntimeinstancehasfailed,inwhichcaseitstopsdirectingrequeststoituntilthetcRuntimeinstancerestarts,addingtothehighavailabilityoftcRuntime.YoucanusePivotalWebServertoprovideloadbalancingfortcServer.See“ConfiguringLoadBalancingBetweenTwoorMoretcRuntimeInstances”inPivotalWebServerInstallationandConfigurationforinstructions.
SeeHighLevelStepsforCreatingandUsingtcRuntimeClustersforthebasicstepstogetstartedwithtcRuntimeclusters.
AdditionalClusterDocumentationfromApacheForadditionalinformationaboutconfiguringtcRuntimeclusters,see:
Clustering/SessionReplicationHOW-TO
ConfigurationReferencefortheClusterObject
High-LevelStepsforCreatingandUsingtcRuntimeClustersThefollowingprocedureoutlinesthemaintasksyouperformtocreateandconfigureatcRuntimeclusterfromtwoormoretcRuntimeinstances.
1. PrepareyourWebapplicationssotheycanbedeployedtoaclusterandtakefulladvantageofthetcRuntimeclusteringfeatures.SeeWebApplicationRequirementsforUsingSessionReplication.
2. Besurethatyouhavecorrectlyconfiguredyournetworktoenablemulticast,whichisthetypicalmethodofcommunicationbetweenclustermembers.SeeNetworkConsiderations.
3. ConfigureyourtcRuntimeinstancesintoasimpleclusterusingthedefaultvaluesformostoftheconfigurationoptions.SeeConfiguringaSimpletcRuntimeCluster.
4. Ifthedefaultconfigurationdoesnotsuityourneeds,configureotherclusterconfigurationoptions.SeeAdvancedClusterConfigurationOptions.
5. StartyourclusterbystartingallthetcRuntimeinstancesthatmakeuptheclustergroup.Youcandothismanually,asdescribedin“StartingandStoppingtcRuntimeInstances”inGettingStartedwithPivotaltcServer,orbyusingtheHQUserInterface.
©CopyrightPivotalSoftwareInc,2013-2016 53 3.x
WebApplicationRequirementsforUsingSessionReplicationInadditiontoconfiguringtheclusterfromaserveradministrationpointofview,makesureyourWebapplicationmeetstheserequirements:
AllservletandJSPsessiondatamustbeserializable.InJavaterms,thismeansthateveryfieldinthesessionobjectmusteitherimplementthejava.io.Serializable interfaceoritmustbe transient .
tcRuntimeusescookiestotracksessionstate,whichmeansthattheWebapplicationURLsforaparticularsessionalwayslookthesame.Iftheydonot,thetcRuntimeinstancecreatesanewsessioneachtimeaclientsendsamessage,whichessentiallydisablessessionreplicationforthatWebapplication.
ConfigureyourWebapplicationtobedistributable,thatis,suitableforrunninginadistributedenvironmentsuchasatcRuntimecluster.Youcandothisinoneoftwoways:
Addthe <distributable/> elementtotheweb.xmldeploymentdescriptorofyourWebapplication; <distributable/> isachild-elementoftheroot <web-app> element.The web.xml fileislocatedinthe WEB-INF directoryofyourWebapplication.Forexample:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4">
<distributable/>
<display-name>HelloWorldApplication</display-name><servlet>...<web-app>
Ifyoudonotwanttochangethe web.xml deploymentdescriptorfileofyourWebapplication,youcanusethetcRuntime-specific <Contextdistributable="true"> elementtospecifythatoneorallWebapplicationsaredistributable.YoucanspecifythiselementintheCATALINA_BASE/conf/context.xml fileifyouwanttomakeALLWebapplicationsofaparticulartcRuntimeinstancedistributable.Forexample:
<?xmlversion="1.0"encoding="ISO-8859-1"?>
<Contextdistributable="true">...</Context>
Youcanalsoaddthiselementtospecificcontextfilestonarrowitsscope.Fordetails,seeTheContextContainer .
Toenableapplicationcontextreplication,specifythatyourapplicationcontextusethe org.apache.catalina.ha.context.ReplicatedContext contextimplementation,ratherthanthedefault( org.apache.catalina.core.StandardContext ).Asdescribedintheprecedingbullet,youcanupdatetheCATALINA_BASE/conf/context.xml fileasshown:
<?xmlversion="1.0"encoding="ISO-8859-1"?><Contextdistributable="true"className="org.apache.catalina.ha.context.ReplicatedContext">...</Context>
NetworkConsiderationsBesurethatmulticastisworkingoneachcomputerthathostsmembersofthetcRuntimecluster.
IfthecomputersthathostyourtcRuntimeclusteralsohostotherapplicationsthatusemulticastcommunications,besurethattheotherapplicationsdonotusethesamemulticastaddressandportasthetcRuntimecluster.ThisprecautioneliminatesunnecessaryprocessingofirrelevantmessagesbythetcRuntimecluster.Inadditiontooverheadanddecreasedperformance,unnecessaryprocessingcandelayclustercommunications,causingaclustermembertobemarkedfailedwheninfactitisalivebutbroadcastofitsheartbeatmessagesistakingtoolong.
ConfiguringaSimpletcRuntimeClusterInthissectionyousetupasimpletcRuntimeclusterthatusesdefaultvaluesformostconfigurationoptions.Adescriptionofthisdefaultclusterconfigurationfollowstheprocedure.
1. ForeachtcRuntimeinstancethatwillbeamemberofthecluster,updateits CATALINA_BASE/conf/server.xml byaddinga <Cluster> child-elementof
©CopyrightPivotalSoftwareInc,2013-2016 54 3.x
the <Engine> element,asshowninthefollowingexample(onlyrelevantsectionsshown):
<?xmlversion='1.0'encoding='utf-8'?><Serverport="-1"shutdown="SHUTDOWN">...<Servicename="Catalina">...<Enginename="Catalina"defaultHost="localhost"><ClusterclassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>...</Engine></Service></Server>
The server.xml fileformanytcRuntimeinstancesalreadycontainsacommented-out <Cluster> ;inwhichcase,simplyremovethecommenttags.Youcanalsoaddthe <Cluster> elementtothe <Host> elementofthe server.xml file,thusenablingclusteringinallvirtualhostsofthetcRuntimeinstance.Whenyouaddthe <Cluster> elementinsidethe <Engine> element,theclusterappendsthehostnameofeachsessionmanagertothemanager’snamesothattwocontextsthathavethesamenamebutarepartoftwodifferenthostsaredistinguishable.
2. IfyouwillrunmorethanonetcRuntimeinstanceonthesamecomputer,besurethevariousTCP/IPlistenportsforeachtcRuntimeinstanceareunique.Youconfigurethelistenportsusingthe port and redirectPort attributesofthe <Connector> elementinthe server.xml file.SeeSimpletcRuntimeConfiguration.
3. Iftheclusterishostedonmorethanonecomputer,time-synchronizethecomputerswiththeNetworkTimeProtocol(NTP).SeeTheNetworkTimeProtocol .
Theclusterthatresultsfromtheprecedingprocedurehasthefollowingconfiguration:
Theclusterisenabledwithall-to-allsessionreplication,whereinasessionononememberoftheclusterthatismodifiedbytheclientisreplicatedtoallothermembersofthecluster,evenmembersinwhichtheapplicationisnotdeployed.Thisistherecommendedsessionreplicationschemeforsmallclusters,butastheclustergainsmembers,Pivotalrecommendsaprimary-secondaryreplicationschemeinwhichsessiondataisreplicatedtoasinglebackupmember,andonlytomembersinwhichtheapplicationisdeployed.SeeReplicatingaSessiontoaSingleBackupMember.
Themulticastaddressis 203.0.113.4 .
Themulticastportis 45564 .
Themembersoftheclustersendoutheartbeats(tobroadcastthattheyarealiveandwell)every500milliseconds.
Ifaheartbeatisnotreceivedfromamemberoftheclusterafter3000milliseconds,theclusterisnotifiedandthemembermaybemarkedfailed.
TheIPaddressthatmembersoftheclusterbroadcasttotheothermembersisthelocalvalueofjava.net.InetAddress.getLocalHost().getHostAddress() .
TheTCP/IPportthatmembersusetolistenforreplicationmessagesisthefirstavailableserversocketinrange4000-4100.
ForadditionaldetailedinformationabouttcRuntimeclustersandadescriptionofthedefaultclusterconfiguration,seeClustering/SessionReplicationHOW-TO .
AdvancedClusterConfigurationOptionsThissectiondescribesasmallsubsetoftheclusterconfigurationoptionsthataremoreadvancedthanthosedescribedinConfiguringaSimpletcRuntimeCluster,whichdescribeshowtosetupaverysimpleclusterusingmostlydefaultvalues.Readthissectionifthedefaultclustervaluesdonotsuityourneeds.
Inallcasestheconfigurationrequiresyoutoaddchildelementsorattributestothebasic <Cluster> element.
Thissectionincludesthefollowingsubsections:
ChangingtheDefaultMulticastAddressandPort
ChangingtheMaximumTimeAfterWhichanUnresponsiveClusterMemberisDropped
ReplicatingaSessiontoaSingleBackupMember
tcRuntimeclustersarehighlyconfigurableandthissectiondescribesonlyafewusecases.Formoreinformation,seeClustering/SessionReplicationHOW-TO .
ChangingtheDefaultMulticastAddressandPortThedefaultmulticastaddressandportofaclusterare 203.0.113.4 and 45564 ,respectively.Sometimesyouneedtochangethesevalues;forexample,
©CopyrightPivotalSoftwareInc,2013-2016 55 3.x
supposeyouwanttoconfiguretwoclustersonthesamecomputer,onefortestingandoneforproduction.Theeasiestwaytosetthisupistospecifydifferentmulticast/portcombinationsforthetwoclusters.
Tochangethemulticastaddressandportofacluster,updatethe server.xml fileforeachtcRuntimeinstancethatisamemberoftheclusterandaddorupdatethe <Membership> childelementofthe <Channel> element,whichitselfisachildmemberofthe <Cluster> element.
<ClusterclassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"><ChannelclassName="org.apache.catalina.tribes.group.GroupChannel">
<MembershipclassName="org.apache.catalina.tribes.membership.McastService"address="203.0.113.5"port="55564"/>
</Channel>
</Cluster>
Usethe address and port attributesofthe <Membership> elementtosetthemulticastaddressandport;intheprecedingexample,thenewvaluesare203.0.113.5 and 55564 ,respectively.
Formoreinformationonthe <Membership> element,itsdefaultbehavior,andtheattributesyoucansettofurtherconfigureit,seeTheClusterMembershipObject .
ChangingtheMaximumTimeAfterWhichanUnresponsiveClusterMemberIsDroppedThedefaultimplementationoftheclustergroupnotificationisbuiltonmulticastheartbeatssentusingUDPpacketstoamulticastIPaddress.Asdescribedinthegeneralclusterdocumentation,yougroupclustermembersbyspecifyingthesamemulticastaddress/portcombination(eitherusingthedefaultvaluesorcustomvalues).Eachmemberthensendsoutaheartbeatwithinagiveninterval(frequency);thisheartbeatisusedfordynamicdiscovery.Theclustermembershiplistenerlistensfortheseheartbeats;ifthemembershiplistenerdoesnotreceiveaheartbeatfromanodewithinacertaintimeframe(droptime),theclusterconsidersthemembersuspectandnotifiesthechanneltotakeappropriateaction.
Thedefaultfrequencyatwhichmemberssendheartbeats(500milliseconds)istypicallyadequate.Onhigh-latencynetworks,youmightwanttoincreasethedefaultvalueofthedroptime(3000milliseconds)toprotectagainstfalsepositives.
Tochangethedroptime,updatethe server.xml fileforeachtcRuntimeinstancethatisamemberoftheclusterandaddorupdatethe <Membership> childelementofthe <Channel> element,whichitselfisachildmemberofthe <Cluster> element.
<ClusterclassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"><ChannelclassName="org.apache.catalina.tribes.group.GroupChannel"><MembershipclassName="org.apache.catalina.tribes.membership.McastService"dropTime="6000"/></Channel>
</Cluster>
Usethe dropTime attributeofthe <Membership> elementtosetthedroptime;intheprecedingexample,thenewdroptimevalueis 6000 milliseconds.
Formoreinformationonthe <Membership> element,itsdefaultbehavior,andtheattributesyoucansettofurtherconfigureit,seeTheClusterMembershipObject .
ReplicatingaSessiontoaSingleBackupMemberThedefaultclusterconfigurationusestheDeltaManagerobjecttoenableall-to-allsessionreplication,whichmeansthattheclusterreplicatesthesessioninformation(typicallysessiondeltas)toalltheothernodesinthecluster,includingnodesinwhichtheapplicationisnotevendeployed.(Inthiscontext,anodereferstoatcRuntimeinstancethatisamemberofthecluster.)All-to-allreplicationworkswellforsmallerclustersthataremadeupofjustafewnodes.However,theDeltaManagerrequiresthatallnodesintheclusterbehomogeneousandthatallnodesmustdeploythesameapplicationsandbeexactreplicas.
Therefore,ifyouhaveconfiguredalargeclusterwithmanynodes,oryoufindtherequirementsoftheDeltaManagertoolimiting,PivotalrecommendsthatyouconfiguretheclustersothatitreplicatestojustasinglebackupnodebyusingtheBackupManagerobject.Theclusterensuresthatthenodetowhichitreplicatesalsohastheapplicationdeployed.Thelocationofthebackupnodeisknowntoallnodesinthecluster.Finally,becausetheclusterisreplicatingtojustonenode,theclustersupportsheterogeneousdeployment.
Toconfigureuseofasinglebackupnodeforsessionreplication,addorupdate <Manager> childelementofthe <Cluster> elementinthe server.xml filesforalltcRuntimeinstancesthataremembersofthecluster,asshowninthefollowingsnippet:
©CopyrightPivotalSoftwareInc,2013-2016 56 3.x
<ClusterclassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"><ManagerclassName="org.apache.catalina.ha.session.BackupManager"/></Cluster>
ForadditionalinformationabouttheBackupManager,itsdefaultbehavior,andtheattributesyoucansetonthe <Manager >element,seeTheClusterManagerObject .
©CopyrightPivotalSoftwareInc,2013-2016 57 3.x
MonitoringtcRuntimeInstancesUsingHypericVMwarevCenterHypericmonitorsoperatingsystems,middleware,andapplicationsrunninginphysical,virtualandcloudenvironments.ForinformationonvCenterHyperic,includingHypericServerinstallationinstructions,seetheVMwarevCenterHypericdocumentation .
TwoversionsoftheHypericAgentpluginareavailable:
tcRuntime8PluginPivotalprovidesanewHypericAgentpluginfortcRuntime8tomonitoryourinstancesofPivotaltcServeronanycomputer,allSpring-poweredapplications,andavarietyofotherplatformsandapplicationserverssuchasApacheTomcatusingVMwarevCenterHypericServer.Hypericprovidesasingleconsolewithpowerfuldashboardsfromwhichyoucaneasilycheckthehealthofyourapplications.ThecapabilitytomanagetcServerinstancesisnotavailable.
WithHypericServeryoucan:
ManagethelifecycleoftcRuntimeinstancesbystarting,stopping,andrestartinglocalorremoteinstances.
InadditiontotheprecedingtcRuntime-relatedactions,Hypericperformsthesestandardtasks:
Inventoriestheresourcesonyournetwork.
Monitorsyourresources.
Alertsyoutoproblemswithresources.
Controlstheresources.
tcRuntime7(version2.9.x)PluginThelegacyversion2.9.xHypericAgentpluginfortcRuntime7isalsosupported.Thispluginprovidesmanagementandmonitoringcapability.
WithHypericServer,youcan:
ManagethelifecycleoftcRuntimeinstancesbystarting,stopping,andrestartinglocalorremoteinstances.
SimilarlymanagethelifecycleofagroupoftcRuntimeinstancesthataredistributedoveranetworkofcomputers.
ConfigureasingleinstanceoftcRuntime.ConfigurationoptionsincludethevariousportnumberstowhichthetcRuntimeinstancelistens,JVMoptionssuchasheapsizeandenablingdebugging,defaultservervaluesforJSPsandstaticcontent,JDBCdatasources,varioustcRuntimeconnectors,andsoon.
ConfigureagroupoftcRuntimeinstancesusingthe tcsadmin command.
DeployaWebapplicationfromanaccessiblefilesystem,eitherlocalorremote.YoucandeploytobothasingletcRuntimeinstanceortoapredefinedgroupofservers.
ManagethelifecycleofapplicationsdeployedtoasingletcRuntimeinstanceorgroupofinstances.Applicationlifecycleoperationsincludestart,stop,redeploy,undeploy,andreload.
InadditiontotheprecedingtcRuntime-relatedactions,Hypericperformsthesestandardtasks:
Inventoriestheresourcesonyournetwork.
Monitorsyourresources.
Alertsyoutoproblemswithresources.
Controlstheresources.
FordetailedinformationonusingtheHyperAgentplugintomanageyourtcServerinstances,seetheVMwarevCenterHypericdocumentation .
UserPermissionsRequiredtoUsethetcServerHypericPlug-inFeaturesForsimplicity,itisoftenassumedinthisdocumentationthatyoulogintotheHypericuserinterfaceastheHypericsuper-user( hqadmin )whenyouwanttomanageatcRuntimeinstance.Thisisnotrequired,ofcourse.Youcanalsologinasanon-superuserandstillusethetcServerHypericpluginfeatures,aslongastheuserhasthecorrectpermissions.
©CopyrightPivotalSoftwareInc,2013-2016 58 3.x
InHyperic,usersareassignedroles,whichinturnareassignedapermissionlevel(None,Read-Only,Read-Write,orFull)toeachHypericinventorytype(platforms,servers,services,groups,andapplications)Forgeneralinformationaboutwhateachpermissionmeanswithrespecttoserverresources(suchasatcRuntimeinstance)inHyperic,see“CreatingandManagingRolesinvCenterHyperic”intheVMwarevCenterHypericdocumentation.ForgeneralinformationaboutthedefaultusersinHypericandcreatingnewones,see“CreatingandManagingUserAccounts.”
ThefollowingtabledescribestheadditionaleffectsthatsomeoftheHypericpermissionshaveonthetcServerHypericpluginfeatures.UsethistabletodeterminewhichroleyoushouldassignauserthatwillbemanagingtcRuntimeinstances.
Table1.HypericPermissionEffectsontcServerHypericPlug-inFeatures
Read-Only
Allowstheusertoviewinstancesofthetype,butnotcreate,edit,ordeletethem.ForPlatforms,Servers,Services,Groups,alsoenablesRead-Onlyaccesstoalertdefinitionsfortheinventorytype.
ViewthedeployedWebapplicationsintheViews>ApplicationManagementtab.
ViewthecurrentconfigurationofatcRuntimeinstanceintheViews>ServerConfigurationtab.
Read-Write
Allowstheusertoviewandeditinstancesofthetype,butnotcreateordeletethem.
ForPlatforms,Servers,Services,Groups,providesFullaccesstoalertdefinitionsfortheinventorytype;permissiontomanagealerts(enable/disable,fix,acknowledge)fortheinventorytype;andpermissiontoperformsupportedcontroloperationsonresourcesoftheinventorytype.
UpdatethefieldsintheViews>ServerConfigurationtabandthenpushthedatatotheconfigurationfilesassociatedwiththetcRuntimeinstance,suchas server.xml .
UsetheapplicationlifecyclecommandsoftheViews>ApplicationManagementtabtostart,stop,reload,orundeployaWebapplication.
Full
Allowsuserstocreate,edit,delete,andviewinstanceofthetype.
ForPlatforms,Servers,Services,Groups,providesFullaccesstoalertdefinitionsfortheinventorytype;permissiontomanagealerts(enable/disable,fix,acknowledge)fortheinventorytype;andpermissiontoperformsupportedcontroloperationsonresourcesoftheinventorytype.
ManagingtcRuntime-RelatedHypericAlertstcServerincludesafullsetofdiagnosticfeaturesthatmakeiteasytotroubleshootproblemswithtcRuntimeinstancesandtheapplicationsthatyoudeploytothem.Foreachdiagnosticfeature,thetcServerHypericplug-inhasoneormorecorrespondingpreconfiguredalerts.
AfterHyperictriggersanalertassociatedwithadiagnosticfeature(becausetheassociatedconditionhasbeenmet),HypericdisablesthealertuntilanadministratormarksitasFixed.YoucanuseHyperictofurtherconfigurethisalertwithadditionalcontrolactionsorevendisableit,asdescribedinthefollowingsections:
ViewingandChangingthePreconfiguredAlerts
ViewingandChangingtheMetricCollectionInterval
DeadlockDetection
ExcessiveTimeinGarbageCollection
SloworFailedRequests
JDBCConnectionMonitoring
ViewingandChangingthePreconfiguredAlerts
©CopyrightPivotalSoftwareInc,2013-2016 59 3.x
ThepreconfiguredHypericalertsassociatedtothediagnosticfeaturesoftcRuntimeworkononeoftwoHypericresources:eitherthetcRuntimeinstanceitself,orwithaserviceofthetcRuntimeinstance.Thisinformationisimportanttoknowbecauseitdetermineshowyouview,andoptionallychange,aparticularalert.
ThefollowingtablelistseachpreconfiguredalertandtheHypericresourcetypetowhichitisassociated.TheresourcetypeSpringSourcetcRuntime7.0
referstothetcRuntimeinstanceitself;theresourcetype SpringSourcetcRuntime7.0Service
,suchas SpringSourcetcRuntime7.0ThreadDiagnostics
,referstoa
serviceofthetcRuntimeinstance.
Note:ThetcRuntimeversionisassociatedwiththecoreversionofTomcatonwhichtheruntimeisbased,ratherthantheversionofthetcServerbundle.
Thethirdcolumninthetableindicateswhetherthealertistriggeredbyametricconditionoranevent/loglevelcondition.Iftheformer,thenameofthemetricisdisplayed;ifthelatter,thespecificstringinthelog(ifany)thattriggersthealertisdisplayed.
Table2.PreconfiguredtcRuntimeAlerts
AlertName AssociatedHypericResourceType MetricorEvents/LogLevelBased?
DeadlocksDetected SpringSourcetcRuntime7.0andPivotaltcRuntime8.0 Metric(DeadlocksDetected)
ExcessiveTimeSpentinGarbageCollection
SpringSourcetcRuntime7.0andPivotaltcRuntime8.0Metric(PercentUpTimeinGarbageCollection)
SloworFailedRequestSpringSourcetcServer7.0ThreadDiagnosticsandPivotaltcServer8.0ThreadDiagnostics
Events/LogsLevel.
JDBCConnectionAbandoned
SpringSourcetcServer7.0TomcatJDBCConnectionPoolGlobalandPivotaltcServer8.0TomcatJDBCConnectionPoolGlobal
Events/LogsLevel(CONNECTIONABANDONED)
JDBCConnectionFailedSpringSourcetcServer7.0TomcatJDBCConnectionPoolGlobalandPivotaltcServer8.0TomcatJDBCConnectionPoolGlobal
Events/LogsLevel(CONNECTIONFAILED)
JDBCQueryFailedSpringSourcetcServer7.0TomcatJDBCConnectionPoolGlobalandPivotaltcServer8.0TomcatJDBCConnectionPoolGlobal
Events/LogsLevel(FAILEDQUERY)
SlowJDBCQuerySpringSourcetcServer7.0TomcatJDBCConnectionPoolGlobalandPivotaltcServer8.0TomcatJDBCConnectionPoolGlobal
Events/LogsLevel(SLOWQUERY)
Thefollowingproceduresummarizeshowtoviewandchangepreconfiguredalerts.ForadetailedtutorialthatshowshowtoviewandchangetheDeadlocksDetectedalert,see“Tutorial:UsingHyperictoConfigureandManagetcRuntimeInstances”inGettingStartedwithPivotaltcServer.
1. Browsetotheresourcetowhichthealertisassociated,asdescribedintheprecedingtable.See“GettingStartedwiththeHypericUserInterface”inGettingStartedwithPivotaltcServerforinformationaboutbrowsingtoHypericresources.
2. ClicktheAlerttab.
3. ClicktheConfigurebutton.Atableofalertscurrentlyconfiguredfortheresourceisdisplayed.
4. Clickthenameofthealert.TheAlertDefinitionpageforthealertisdisplayed.Thedefinitionpagehasthreesections:thetopAlertPropertiessectionprovidesgeneralpropertiesofthealert;themiddleConditionSetsectiondescribestheconditionsthattriggerthealert;andaseriesoftabsatthebottomenableyoutoconfiguretheparticularcontrolactionthatoccursifthealertistriggered,theescalationscheme,whoshouldbenotifiedifthealertistriggered,andsoon.
5. Ifyouwanttochangethegeneralproperties,conditions,controlactions,andsoonofthealert,clicktheappropriateEDIT…button,makeyourchanges,thenclickOK.
6. Todisablethealert,gobacktotheAlertDefinitionstable,selectthenameofthealertbycheckingtheboxtotheleftofitsname,thenselectNo fortheSetActivedrop-downlistandclickthearrowtotheright.
Theremainderofthischapterdescribeseachalertinmoredetail,includinganyspecialinstructionstoenablethealert.
ViewingandChangingtheMetricCollectionIntervalAsshowninthePreconfiguredtcRuntimeAlertstable,thetwoalertsassociatedwiththetcRuntimeinstanceitselfusemetricsintheirconditiontodeterminewhetherthealertshouldbetriggered.Thefollowingproceduredescribeshowyoucanview,andoptionallychange,thecollectionintervalforDeadlockDetectionandExcessiveTimeinGarbageCollection.
©CopyrightPivotalSoftwareInc,2013-2016 60 3.x
1. ClicktheAdministrationtabatthetopoftheHypericuserinterface.
2. IntheHypericServerSettingssection,clicktheMonitoringDefaultslink.
3. Scrolldownuntilyoufindthe SpringSourcetcRuntime7.0 or SpringSourcetcRuntime8.0 entryintheServerTypestable,andthenclicktheEDITTEMPLATEMETRIClinktotheright.ApageshowsallmetricsassociatedwiththetcRuntimeinstance.Forexample,underUtilizationyouwillfindtheDeadlocksDetectedmetric.Bydefault,theCollectionIntervalcolumnshowsthatHypericServercollectsinformationaboutthismetricevery2minutes.
4. Tochangethecollectionintervalforaspecificmetric,selectitbyclickingtheboxtotheleftofitsname.
5. EnterthenewcollectionintervalatthebottomofthepageintheCollectionIntervalforSelectedfield,specifywhetheritisinminutesorhours,thenclickthearrowtotheright.
DeadlockDetectionThetcRuntimeautomaticallydetectswhetherathreaddeadlockoccursinatcRuntimeinstanceoranapplicationdeployedtotheinstance.
Theout-of-the-boxHypericalertistriggerediftheDeadlocksDetectedmetricexceeds0.Hypericchecksthemetriceverytwominutestoseewhethertheconditionismet.Hypericappliesthisalerttoallauto-discoveredtcRuntimeinstancesandenablesitbydefault.ThisalertisassociatedwiththetcRuntimeinstanceitself.
ForadetailedtutorialthatshowshowtoviewandchangetheDeadlocksDetectedalert,see“Tutorial:UsingHyperictoConfigureandManagetcRuntimeInstances”inGettingStartedwithPivotaltcServer.
ExcessiveTimeinGarbageCollectionAHypericmetricrepresentsthepercentageofprocessuptime(0-100)thatthetcRuntimeinstancehasspentingarbagecollection.
Thealertistriggeredwhenthetotalgarbagecollectiontimeisexcessive(bydefault,40%ofprocessuptime.)Hypericchecksthismetricevery5minutestoseeiftheconditionhasbeenmet.Hypericappliesthisalerttoallauto-discoveredtcRuntimeinstancesandenablesitbydefault.
EnablingtheSloworFailedRequestAlertWhenclientsbeginconnectingandusingaWebapplicationdeployedtoatcRuntimeinstance,theymayencountersloworfailedrequests.AlthoughthetcRuntimeinstancelogstheseerrorsinthelogfilesbydefault,itisoftendifficulttopinpointtheexactoriginoftheerrorandhowtogoaboutfixingit.Byenablingthreaddiagnostics,tcRuntimeprovidesadditionalinformationtohelpyoutroubleshoottheproblem.
Afailedrequestisonethatsimplydidnotexecute;aslowrequestisarequestthattakeslongerthanacertainthreshold.Thedefaultthresholdis500milliseconds.
Whenyouenablethreaddiagnostics,youcanviewthefollowingcontextualinformationaboutasloworfailedclientrequest:
Timeanddateofthesloworfailedrequest.
ExactURLinvokedbytheclientthatresultedinasloworfailedrequest.
Exacterrorreturnedbytherequest.
Databasequeriesthatwereexecutedaspartoftherequestandhowlongeachonetook.
Whetheranydatabaseconnectionfailedorsucceeded.
Whetherthedatabasehadanyotherconnectivityproblems.
Whetherthedatabaseconnectionpoolranoutofconnections.
Whetheranygarbagecollectionoccurredduringtherequest,andifso,howlongittook.
TheassociatedHypericalertistriggeredifaclientrequesttotcRuntimeisslow(overaconfiguredthreshold)orifitfailed.
Thisalertisnotenabledbydefault.Explicitlyenableitasfollows:
1. BrowsetotheViews>ServerConfigurationconsolepageforthetcRuntimeinstance.
2. ClicktheServicestab.
3. Inthetable,clicktheserviceyouwanttoconfigure;thedefaulttcRuntimeserviceiscalled Catalina .
©CopyrightPivotalSoftwareInc,2013-2016 61 3.x
4. IntheThreadDiagnosticssection,checktheEnableThreadDiagnosticsproperty.
5. Atthebottomofthepage,clickSave.
6. ClickthenecessarylinksandbuttonstopushconfigurationchangestothetcRuntimeinstanceandrestarttheinstance.
EnablingJDBCConnectionMonitoringHypericincludesaservicecalled SpringSourcetcRuntime7.0TomcatJDBCConnectionPool
Globalthatrepresentsanyhigh-concurrencyTomcatJDBCdatasources
youmighthaveconfiguredforyourtcRuntimeinstance.Thisservicemonitorsthehealthofthedatasource,suchaswhetheritsconnectiontothedatabasehasfailedorwasabandoned,andwhethertheJDBCqueriesthatclientsexecutearetakingtoolong.HypericcreatesthisservicewhenyoucreateanewTomcatJDBCdatasource;oneinstanceofaserviceexistsperdatasource.
FourHypericalertsareassociatedwiththisdiagnosticfeature;theyaretriggeredasfollows:
JDBCConnectionFailed:Aparticularhigh-concurrencyJDBCconnectionthatusesaconfigureddatasourcefails.
JDBCConnectionAbandoned:Aparticularhigh-concurrencyJDBCconnectionthatusesaconfigureddatasourceisabandonedbythedatabaseserver.
JDBCQueryFailed:Ahigh-concurrencyJDBCqueryfails.
SlowJDBCQuery:Ahigh-concurrencyJDBCquerytakestoolongtoexecute.
ToreceivemonitoringinformationfortheprecedingJDBCalerts,enablelogtrackingforthisservice:
1. Browsetothe SpringSource tc Runtime 7.0 Tomcat JDBC Connection Pool Global serviceassociatedwithyourJDBCdatasource.
2. ClicktheInventorytab.
3. IntheConfigurationPropertiessection,besurethattheservice.log_track.enablepropertyischecked.CheckingthisboxsubscribesHyperictoJMXnotificationssentfromthetcRuntimeinstance,whichthengetdisplayedinHypericaslogevents.
HyperictcServerPluginMetricsThetablebelowdefinesthemetricsthattheHypericpluginfortcServerreports.Thefollowinginformationislistedforeachmetric:
Attribute/MetricName.ThenameofametricistypicallythesameastheMBeanattributethatprovidesthemetricvalue.
Units.Theunitsinwhichthemetricisreported.
Detection.TheMBeanfromwhichthemetricisobtained,ortheprocessbywhichitisobtained.
On/Off.Indicateswhethertheplugin,bydefault,reportsthemetric.
Description.
Category.TheHypericservicetypeortoplevelservertypetowhichthemetricapplies.
Table3.MetricDefinitions
ThreadCount ms java.lang: type=Threading Off ThreadCount Thread
CurrentThreadCpuTime ms java.lang: type=Threading OffCPUTimeusedbythecurrentthread Thread
CurrentThreadUserTime ms java.lang: type=Threading OffTimethecurrentthreadexecutedinusermode
Thread
DaemonThreadCount java.lang: type=Threading OffNumberofdaemonthreads
Thread
PeakThreadCount java.lang: type=Threading OffHighestamountofthreadsexecuting
Thread
Totalnumberofthreadsthathave
©CopyrightPivotalSoftwareInc,2013-2016 62 3.x
TotalStartedThreadCount java.lang: type=Threading Off beencreatedorstartedduringlifeofVM.
Thread
FreeSwapSpaceSize B java.lang: type=Threading OffTheamountoffreeswapspace
OperatingSystem
FreePhysicalMemorySize B java.lang: type=OperatingSystem OffTheamountoffreephysicalmemory
OperatingSystem
ProcessCpuTime ns java.lang: type=OperatingSystem OffTimetheCPUhasspentexecutingtheprocess
OperatingSystem
OpenFileDescriptorCount java.lang: type=OperatingSystem OffNumberofopenfiledescriptorfortheprocess
OperatingSystem
SystemLoadAverage java.lang: type=OperatingSystem OffTheaveragesystemload
OperatingSystem
Uptime ms java.lang: type=OperatingSystem OnTimetheprocesshasbeenrunning
Runtime
DataSourceContextAvailability
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
OnAvailabilityoftheDataSourceContext
DataSourceContext
DataSourceContextnumActive
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
OnCurrentnumberofactiveconnections
DataSourceContext
DataSourceContextnumIdle
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
OnCurrentnumberofidleconnections
DataSourceContext
DataSourceContextmaxOpenPreparedStatements
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
OffMaximumOpenedPreparedStatements
DataSourceContext
DataSourceContextmaxWait
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
Off MaximumWaitDataSourceContext
DataSourceContextpercentActiveConnections
TcRuntime7.0.x:${domain}:type= DataSource,context= *,host=*,class= javax.sql.DataSource,name=*
TcRuntime8.0.x:${domain}:type= DataSource,context= *,host=*,class=
OffPercentageofActiveConnections
DataSourceContext
©CopyrightPivotalSoftwareInc,2013-2016 63 3.x
javax.sql.DataSource,name=*
ManagerAvailability
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OnAvailabilityoftheManagermbean
Manager
activeSessions
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
Off ActiveSessions Manager
expiredSessions
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
Off ExpiredSessions Manager
maxActive
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffMaximumActiveSessions
Manager
processingTime sec
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffProcessingtimepersession
Manager
rejectedSessions
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
Off RejectedSessions Manager
sessionAverageAliveTime
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffSessionAverageAliveTime
Manager
sessionCounter
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
Off SessionCounter Manager
sessionCreateRate
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffSessionsCreatedperminute
Manager
sessionExpireRate
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffSessionsDestroyedperminute
Manager
sessionMaxAliveTime sec
TcRuntime7.0.x:${domain}:type= Manager,context=*,host=*
TcRuntime8.0.x:${domain}:type= Manager,context=*,host=*
OffSessionMaxAliveTime
Manager
©CopyrightPivotalSoftwareInc,2013-2016 64 3.x
HeapMemoryUsage.used B java.lang: type=Memory On HeapMemoryUsed Memory
HeapMemoryUsage.committed B java.lang: type=Memory OnHeapMemoryCommitted
Memory
HeapMemoryUsage.max B java.lang: type=Memory OnHeapMemoryMaximum
Memory
HeapMemory.free Bjava.lang: type=Memory(calculatedfrommax-used)
OnThecalculatedamountoffreememory
Memory
deadLockedThreadCount JMXNotification OnThenumberofdeadlocksdetectedoninstance
DeadlockNotification
tcRuntimeAvailability Processscan OnDetectionoftcRuntimeavailability
Availability
percentUpTimeSpent Calculationofgarbagecollectionfrommbeans
On%oftimespentingarbagecollection
GarbageCollection
ThreadDiagnosticsContextAvailability
Mbeanscan: tcServer:type=Serviceability, name=DiagnosticsValve,context=* ,host=*,engine=*
On
DetectionofThreadDiagnosticsContextonDiagnosticsValve
ThreadDiagnostics
ThreadDiagnosticsEngineAvailability
tcServer:type= Serviceability,name= DiagnosticsValve,engine=*
On
DetectionofThreadDiagnosticsContextonDiagnosticsValve
ThreadDiagnostics
ThreadDiagnosticsHostAvailability
tcServer:type= Serviceability,name= DiagnosticsValve,host= *,engine=*
On
DetectionofThreadDiagnosticsContextonDiagnosticsValve
ThreadDiagnostics
DataSourceGlobalAvailability Catalina:type= DataSource,class= javax.sql.DataSource,name=*
On DataSourceGlobal
DataSourceGlobalnumActive Catalina:type= DataSource,class= javax.sql.DataSource,name=*
OnCurrentnumberofactiveconnections
DataSourceGlobal
DataSourceGlobalnumIdle Catalina:type= DataSource,class= javax.sql.DataSource,name=*
OnCurrentnumberofidleconnections
DataSourceGlobal
DataSourceGlobalmaxOpenPreparedStatements
Catalina:type= DataSource,class= javax.sql.DataSource,name=*
OffMaximumOpenedPreparedStatements
DataSourceGlobal
DataSourceGlobalmaxWait msCatalina:type= DataSource,class= javax.sql.DataSource,name=*
Off MaximumWait DataSourceGlobal
DataSourceGlobalpercentActiveConnections
Catalina:type= DataSource,class= javax.sql.DataSource,name=* Off
PercentageofActiveConnections
DataSourceGlobal
TomcatJDBCConnectionPoolContextAvailability
TcRuntime7.0.x: tomcat.jdbc:name= *,context= *,type=ConnectionPool,host= *,class=*
TcRuntime8.0.x:tomcat.jdbc:name= *,context= *,type=ConnectionPool,host=
OnDetectionofConnectionpoolcontext
TomcatJDBCConnectionPool
©CopyrightPivotalSoftwareInc,2013-2016 65 3.x
*,class=*
TomcatJDBCConnectionPoolGlobal
java.lang: type= GarbageCollector,name=* On
DetectionofConnectionpoolglobal
TomcatJDBCConnectionPool
CollectionCount java.lang: type= GarbageCollector,name=* Off
CollectionCountofGCs
GarbageCollector
CollectionTime ${domain}:j2eeType=WebModule,name= *,J2EEApplication=*,J2EEServer=* Off
CollectionTimeofGCs
GarbageCollector
WebModuleAvailability ${domain}:j2eeType=WebModule,name= *,J2EEApplication= *,J2EEServer=* On
Availabilityofeachwebappdeployed
WebModuleStats
processingTime sec ${domain}:type= ThreadPool,name=* OnProcessingtimeofeachwebapp
WebModuleStats
ThreadPoolsAvailability ${domain}:type= ThreadPool,name=* OnAvailabilityoftheThreadPoolconfigured
ThreadPool
currentThreadCount ${domain}:type= ThreadPool,name=* OnThecurrentthreadcountoftheThreadPool
ThreadPool
currentThreadBusy ${domain}:type= ThreadPool,name=* OnThecurrentcountofbusythreadsinthepool
ThreadPool
percentAllocatedThread ${domain}:type= ThreadPool,name=* OffPercentageoftheallocatedthreads
ThreadPool
percentActiveThreads ${domain}:type= ThreadPool,name=* OffPercentageofactivethreads
ThreadPool
ExecutorAvailability ${domain}:type= Executor,name=* OnAvailabilityoftheExecutormbean
Executor
maxThreads ${domain}:type= Executor,name=* OnMaxnumberofthreadsintheexecutor
Executor
poolSize ${domain}:type= Executor,name=* OnThecurrentsizeofthepoolofthreads
Executor
activeCount ${domain}:type= Executor,name=* OnTheactivethreadsinthepool
Executor
queueSize ${domain}:type= Executor,name=* OnSizeofthequeueforthepool
Executor
ServletAvailability ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
OnAvailabilityoftheServlet
ServletMonitor
classLoadTime ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
Off Classloadtime ServletMonitor
errorCount ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
OnErrorcountontheservlet
ServletMonitor
loadTime ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
OffErrorcountontheservlet
ServletMonitor
processingTime ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
OnProcessingtimeoftheservlet
ServletMonitor
©CopyrightPivotalSoftwareInc,2013-2016 66 3.x
requestCount ${domain}:j2eeType= Servlet,name= *,WebModule= *,J2EEApplication= *,J2EEServer= *
OnThenumberofrequestsontheservlet
ServletMonitor
JSPMonitorAvailability ${domain}:type= JspMonitor,name= jsp,WebModule= *,J2EEApplication= *,J2EEServer= *
OnAvailabilityoftheJSPMonitormbean
JSPMonitor
jspCount ${domain}:type= JspMonitor,name= jsp,WebModule= *,J2EEApplication= *,J2EEServer= *
On TheJSPcount JSPMonitor
jspReloadCount ${domain}:type= JspMonitor,name=jsp,WebModule= *,J2EEApplication= *,J2EEServer= *
OnThenumberofJSPreloads
JSPMonitor
GlobalRequestProcessorAvailability
${domain}:type= GlobalRequestProcessor,name=*
OnAvailabilityoftheGlobalRequestProcessor
GlobalRequestProcessor
bytesSent ${domain}:type= GlobalRequestProcessor,name=*
OffNumberofbytessentbytherequestprocessor
GlobalRequestProcessor
bytesReceived ${domain}:type= GlobalRequestProcessor,name=*
OffNumberofbytesreceivedbytherequestprocessor
GlobalRequestProcessor
errorCount ${domain}:type= GlobalRequestProcessor,name=*
OnNumberoferrorsthatoccurredintherequestprocessor
GlobalRequestProcessor
processingTime ${domain}:type= GlobalRequestProcessor,name=*
On
Timetherequestprocessorhasspentprocessingdata
GlobalRequestProcessor
requestCount ${domain}:type= GlobalRequestProcessor,name=*
OnNumberofrequestsprocessed
GlobalRequestProcessor
CacheAvailability
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OnAvailabilityoftheCachembean Cache
accessCount
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OnNumberoftimesthecachewasaccessed
Cache
cacheMaxSize KB
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OffMaximumsizeofthecache
Cache
cacheSize KB
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OffCurrentsizeofthecache
Cache
desiredEntryAccessRatio
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Off
Theratioofhits/missesofthecache
Cache
©CopyrightPivotalSoftwareInc,2013-2016 67 3.x
Cache,host=*,context=*
hitsCount
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OffThenumberofhitsforthecache
Cache
maxAllocateIterations
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
Off
Maximumallowednumberofremovalsduringamakespaceaction
Cache
spareNotFoundEntries
TcRuntime7.0.x:${domain}:type= Cache,host=*,context=*
TcRuntime8.0.x:${domain}:type= Cache,host=*,context=*
OffThespareamountofnotfoundentries
Cache
©CopyrightPivotalSoftwareInc,2013-2016 68 3.x