1
|
// $Id$
|
2
|
/**
|
3
|
* Copyright (C) 2009 EDIT
|
4
|
* European Distributed Institute of Taxonomy
|
5
|
* http://www.e-taxonomy.eu
|
6
|
*
|
7
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
8
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
9
|
*/
|
10
|
|
11
|
package eu.etaxonomy.cdm.server;
|
12
|
|
13
|
import static eu.etaxonomy.cdm.server.AssumedMemoryRequirements.KB;
|
14
|
import static eu.etaxonomy.cdm.server.CommandOptions.CONTEXT_PATH_PREFIX;
|
15
|
import static eu.etaxonomy.cdm.server.CommandOptions.DATASOURCES_FILE;
|
16
|
import static eu.etaxonomy.cdm.server.CommandOptions.FORCE_SCHEMA_UPDATE;
|
17
|
import static eu.etaxonomy.cdm.server.CommandOptions.HELP;
|
18
|
import static eu.etaxonomy.cdm.server.CommandOptions.HTTP_PORT;
|
19
|
import static eu.etaxonomy.cdm.server.CommandOptions.JMX;
|
20
|
import static eu.etaxonomy.cdm.server.CommandOptions.LOG_DIR;
|
21
|
import static eu.etaxonomy.cdm.server.CommandOptions.WEBAPP;
|
22
|
import static eu.etaxonomy.cdm.server.CommandOptions.WEBAPP_CLASSPATH;
|
23
|
import static eu.etaxonomy.cdm.server.CommandOptions.WIN32SERVICE;
|
24
|
|
25
|
import java.io.BufferedReader;
|
26
|
import java.io.File;
|
27
|
import java.io.FileNotFoundException;
|
28
|
import java.io.FileOutputStream;
|
29
|
import java.io.FilenameFilter;
|
30
|
import java.io.IOException;
|
31
|
import java.io.InputStream;
|
32
|
import java.io.InputStreamReader;
|
33
|
import java.io.OutputStream;
|
34
|
import java.lang.management.ManagementFactory;
|
35
|
import java.net.URL;
|
36
|
import java.util.ArrayList;
|
37
|
import java.util.List;
|
38
|
import java.util.Properties;
|
39
|
import java.util.jar.Attributes;
|
40
|
import java.util.jar.JarFile;
|
41
|
import java.util.jar.Manifest;
|
42
|
import java.util.regex.Pattern;
|
43
|
|
44
|
import org.apache.commons.cli.CommandLine;
|
45
|
import org.apache.commons.cli.CommandLineParser;
|
46
|
import org.apache.commons.cli.GnuParser;
|
47
|
import org.apache.commons.cli.HelpFormatter;
|
48
|
import org.apache.commons.cli.ParseException;
|
49
|
import org.apache.commons.io.FileUtils;
|
50
|
import org.apache.log4j.Logger;
|
51
|
import org.apache.log4j.PatternLayout;
|
52
|
import org.apache.log4j.RollingFileAppender;
|
53
|
import org.eclipse.jetty.apache.jsp.JettyJasperInitializer;
|
54
|
import org.eclipse.jetty.jmx.MBeanContainer;
|
55
|
import org.eclipse.jetty.plus.annotation.ContainerInitializer;
|
56
|
import org.eclipse.jetty.security.HashLoginService;
|
57
|
import org.eclipse.jetty.server.Handler;
|
58
|
import org.eclipse.jetty.server.Server;
|
59
|
import org.eclipse.jetty.server.ServerConnector;
|
60
|
import org.eclipse.jetty.server.handler.ContextHandler;
|
61
|
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
|
62
|
import org.eclipse.jetty.util.log.Log;
|
63
|
import org.eclipse.jetty.webapp.WebAppClassLoader;
|
64
|
import org.eclipse.jetty.webapp.WebAppContext;
|
65
|
|
66
|
import eu.etaxonomy.cdm.server.instance.CdmInstance;
|
67
|
import eu.etaxonomy.cdm.server.instance.Configuration;
|
68
|
import eu.etaxonomy.cdm.server.instance.InstanceManager;
|
69
|
import eu.etaxonomy.cdm.server.instance.SharedAttributes;
|
70
|
import eu.etaxonomy.cdm.server.instance.Status;
|
71
|
import eu.etaxonomy.cdm.server.win32service.Win32Service;
|
72
|
|
73
|
|
74
|
/**
|
75
|
* A bootstrap class for starting Jetty Runner using an embedded war.
|
76
|
*
|
77
|
* @version $Revision$
|
78
|
*/
|
79
|
public final class Bootloader {
|
80
|
/**
|
81
|
*
|
82
|
*/
|
83
|
private static final String VERSION_PROPERTIES_FILE = "version.properties";
|
84
|
|
85
|
//private static final String DEFAULT_WARFILE = "target/";
|
86
|
|
87
|
|
88
|
|
89
|
private static final Logger logger = Logger.getLogger(Bootloader.class);
|
90
|
|
91
|
private static final String DATASOURCE_BEANDEF_FILE = "datasources.xml";
|
92
|
private static final String REALM_PROPERTIES_FILE = "cdm-server-realm.properties";
|
93
|
|
94
|
private static final String USERHOME_CDM_LIBRARY_PATH = System.getProperty("user.home")+File.separator+".cdmLibrary"+File.separator;
|
95
|
private static final String TMP_PATH = USERHOME_CDM_LIBRARY_PATH + "server" + File.separator;
|
96
|
private static final String LOG_PATH = USERHOME_CDM_LIBRARY_PATH + "log" + File.separator;
|
97
|
|
98
|
private static final String APPLICATION_NAME = "CDM Server";
|
99
|
private static final String WAR_POSTFIX = ".war";
|
100
|
|
101
|
private static final String CDM_WEBAPP = "cdm-webapp";
|
102
|
private static final String CDM_WEBAPP_VERSION = "cdm-webapp.version";
|
103
|
|
104
|
private static final String DEFAULT_WEBAPP_WAR_NAME = "default-webapp";
|
105
|
private static final File DEFAULT_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + DEFAULT_WEBAPP_WAR_NAME);
|
106
|
private static final File CDM_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + CDM_WEBAPP);
|
107
|
|
108
|
private final InstanceManager instanceManager = new InstanceManager(new File(USERHOME_CDM_LIBRARY_PATH, DATASOURCE_BEANDEF_FILE));
|
109
|
|
110
|
public List<CdmInstance> getCdmInstances() {
|
111
|
return instanceManager.getInstances();
|
112
|
}
|
113
|
|
114
|
public InstanceManager getInstanceManager(){
|
115
|
return instanceManager;
|
116
|
}
|
117
|
|
118
|
private File cdmRemoteWebAppFile = null;
|
119
|
private File defaultWebAppFile = null;
|
120
|
|
121
|
private String logPath = null;
|
122
|
|
123
|
private String webAppClassPath = null;
|
124
|
|
125
|
/**
|
126
|
* The contextPathPrefix is expected to be normalized:
|
127
|
* it ends with a slash and starts not with a slash character
|
128
|
*/
|
129
|
private String contextPathPrefix = "";
|
130
|
|
131
|
private Server server = null;
|
132
|
private final ContextHandlerCollection contexts = new ContextHandlerCollection();
|
133
|
|
134
|
private CommandLine cmdLine;
|
135
|
|
136
|
private boolean isRunningFromSource;
|
137
|
|
138
|
private boolean isRunningfromTargetFolder;
|
139
|
|
140
|
private boolean isRunningFromWarFile;
|
141
|
|
142
|
private String cdmlibServicesVersion = "";
|
143
|
private String cdmlibServicesLastModified = "";
|
144
|
|
145
|
|
146
|
/* thread save singleton implementation */
|
147
|
|
148
|
private static Bootloader bootloader = new Bootloader();
|
149
|
|
150
|
private Bootloader() {}
|
151
|
|
152
|
/**
|
153
|
* @return the thread save singleton instance of the Bootloader
|
154
|
*/
|
155
|
public synchronized static Bootloader getBootloader(){
|
156
|
return bootloader;
|
157
|
}
|
158
|
|
159
|
/* end of singleton implementation */
|
160
|
|
161
|
|
162
|
/**
|
163
|
* @param input
|
164
|
* @param output
|
165
|
* @param bufferSize
|
166
|
* @return
|
167
|
* @throws IOException
|
168
|
*/
|
169
|
public int writeStreamTo(final InputStream input, final OutputStream output, int bufferSize) throws IOException {
|
170
|
int available = Math.min(input.available(), 256 * KB);
|
171
|
byte[] buffer = new byte[Math.max(bufferSize, available)];
|
172
|
int answer = 0;
|
173
|
int count = input.read(buffer);
|
174
|
while (count >= 0) {
|
175
|
output.write(buffer, 0, count);
|
176
|
answer += count;
|
177
|
count = input.read(buffer);
|
178
|
}
|
179
|
return answer;
|
180
|
}
|
181
|
|
182
|
|
183
|
|
184
|
public void parseCommandOptions(String[] args) throws ParseException {
|
185
|
CommandLineParser parser = new GnuParser();
|
186
|
cmdLine = parser.parse( CommandOptions.getOptions(), args );
|
187
|
|
188
|
// print the help message
|
189
|
if(cmdLine.hasOption(HELP.getOpt())){
|
190
|
HelpFormatter formatter = new HelpFormatter();
|
191
|
formatter.setWidth(200);
|
192
|
formatter.printHelp( "java .. ", CommandOptions.getOptions() );
|
193
|
System.exit(0);
|
194
|
}
|
195
|
}
|
196
|
|
197
|
|
198
|
/**
|
199
|
* Finds the named war file either in the resources known to the class loader
|
200
|
* or in a target folder if the bootloader is started from within a maven project.
|
201
|
* Once found the war file is copied to the temp folder defined by {@link TMP_PATH}.
|
202
|
*
|
203
|
* The war file can optionally be unpacked.
|
204
|
*
|
205
|
* @param warName
|
206
|
* @param unpack
|
207
|
* unzip the war file after extraction
|
208
|
* @return
|
209
|
* @throws IOException
|
210
|
* @throws FileNotFoundException
|
211
|
*/
|
212
|
private File extractWar(String warName, boolean unpack) throws IOException, FileNotFoundException {
|
213
|
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
214
|
String warFileName = warName + WAR_POSTFIX;
|
215
|
|
216
|
// 1. find in classpath
|
217
|
URL resource = classLoader.getResource(warFileName);
|
218
|
if (resource == null) {
|
219
|
logger.error("Could not find the " + warFileName + " on classpath!");
|
220
|
|
221
|
File pomxml = new File("pom.xml");
|
222
|
if(pomxml.exists()){
|
223
|
logger.info("will try find the war in target folder of maven project");
|
224
|
// 2. try finding in target folder of maven project
|
225
|
File warFile = new File("target" + File.separator + warFileName);
|
226
|
logger.debug("looking for war file at " + warFile.getAbsolutePath());
|
227
|
if (warFile.canRead()) {
|
228
|
resource = warFile.toURI().toURL();
|
229
|
logger.info("Success! Using war file from " + resource.toString());
|
230
|
} else {
|
231
|
logger.error("Also could not find the " + warFileName + " in maven project, try excuting 'mvn install'");
|
232
|
System.exit(-1);
|
233
|
}
|
234
|
}
|
235
|
}
|
236
|
|
237
|
if (resource == null) {
|
238
|
// no way finding the war file :-(
|
239
|
System.exit(1);
|
240
|
}
|
241
|
|
242
|
|
243
|
File warFile = new File(TMP_PATH, warName + "-" + WAR_POSTFIX);
|
244
|
logger.info("Extracting " + warFileName + " to " + warFile + " ...");
|
245
|
|
246
|
writeStreamTo(resource.openStream(), new FileOutputStream(warFile), 8 * KB);
|
247
|
|
248
|
logger.info("Extracted " + warFileName);
|
249
|
|
250
|
if(unpack) {
|
251
|
try {
|
252
|
logger.info("Unpacking " + warFileName);
|
253
|
warFile = unzip(warFile, warName);
|
254
|
|
255
|
// get the 'Bundle-Version' and 'Bnd-LastModified' properties of the
|
256
|
// manifest file in the cdmlib services jar
|
257
|
if(warFile != null && warFile.isDirectory()) {
|
258
|
// generate the webapp lib dir path
|
259
|
String warLibDirAbsolutePath = warFile.getAbsolutePath() +
|
260
|
File.separator +
|
261
|
"WEB-INF" +
|
262
|
File.separator +
|
263
|
"lib";
|
264
|
File warLibDir = new File(warLibDirAbsolutePath);
|
265
|
if(warLibDir.exists()) {
|
266
|
// get the cdmlib-services jar
|
267
|
File [] files = warLibDir.listFiles(new FilenameFilter() {
|
268
|
@Override
|
269
|
public boolean accept(File dir, String name) {
|
270
|
return name.startsWith("cdmlib-services") && name.endsWith(".jar");
|
271
|
}
|
272
|
});
|
273
|
if(files != null && files.length > 0) {
|
274
|
// get the relevant info from the jar manifest
|
275
|
JarFile jarFile = new JarFile(files[0]);
|
276
|
Manifest manifest = jarFile.getManifest();
|
277
|
Attributes attributes = manifest.getMainAttributes();
|
278
|
// from the OSGI spec the LastModified value is " the number of milliseconds
|
279
|
// since midnight Jan. 1, 1970 UTC with the condition that a change must
|
280
|
// always result in a higher value than the previous last modified time
|
281
|
// of any bundle"
|
282
|
cdmlibServicesVersion = attributes.getValue("Bundle-Version");
|
283
|
logger.warn("cdmlib-services version : " + cdmlibServicesVersion);
|
284
|
cdmlibServicesLastModified = attributes.getValue("Bnd-LastModified");
|
285
|
logger.warn("cdmlib-services last modified timestamp : " + cdmlibServicesLastModified);
|
286
|
|
287
|
if(cdmlibServicesVersion == null || cdmlibServicesLastModified == null) {
|
288
|
throw new IllegalStateException("Invalid cdmlib-services manifest file");
|
289
|
}
|
290
|
} else {
|
291
|
throw new IllegalStateException("cdmlib-services jar not found ");
|
292
|
}
|
293
|
}
|
294
|
}
|
295
|
} catch (IOException e) {
|
296
|
logger.error("extractWar() - Unziping of war file " + warFile + " failed. Will return the war file itself instead of the extracted folder.", e);
|
297
|
}
|
298
|
}
|
299
|
|
300
|
return warFile;
|
301
|
}
|
302
|
|
303
|
|
304
|
public String getCdmlibServicesVersion() {
|
305
|
return cdmlibServicesVersion;
|
306
|
}
|
307
|
|
308
|
public String getCdmlibServicesLastModified() {
|
309
|
return cdmlibServicesLastModified;
|
310
|
}
|
311
|
/**
|
312
|
* @param extractWar
|
313
|
* @return
|
314
|
* @throws IOException
|
315
|
*/
|
316
|
private File unzip(File extractWar, String warName) throws IOException {
|
317
|
UnzipUtility unzip = new UnzipUtility();
|
318
|
|
319
|
File destDirectory = new File(TMP_PATH + File.separator + warName);
|
320
|
unzip.unzip(extractWar, destDirectory);
|
321
|
return destDirectory;
|
322
|
}
|
323
|
|
324
|
|
325
|
|
326
|
/**
|
327
|
* MAIN METHOD
|
328
|
*
|
329
|
* @param args
|
330
|
* @throws Exception
|
331
|
*/
|
332
|
public static void main(String[] args) throws Exception {
|
333
|
|
334
|
Bootloader bootloader = Bootloader.getBootloader();
|
335
|
|
336
|
bootloader.parseCommandOptions(args);
|
337
|
|
338
|
bootloader.startServer();
|
339
|
}
|
340
|
|
341
|
|
342
|
|
343
|
public void startServer() throws IOException,
|
344
|
FileNotFoundException, Exception, InterruptedException {
|
345
|
|
346
|
|
347
|
if(cmdLine.hasOption(LOG_DIR.getOpt())){
|
348
|
logPath = cmdLine.getOptionValue(LOG_DIR.getOpt());
|
349
|
} else {
|
350
|
logPath = LOG_PATH;
|
351
|
}
|
352
|
|
353
|
|
354
|
//assure LOG_PATH exists
|
355
|
File logPathFile = new File(logPath);
|
356
|
if(!logPathFile.exists()){
|
357
|
FileUtils.forceMkdir(new File(logPath));
|
358
|
}
|
359
|
|
360
|
//append logger
|
361
|
configureFileLogger();
|
362
|
|
363
|
logger.info("Starting "+APPLICATION_NAME);
|
364
|
logger.info("Using " + System.getProperty("user.home") + " as home directory. Can be specified by -Duser.home=<FOLDER>");
|
365
|
|
366
|
//assure TMP_PATH exists and clean it up
|
367
|
File tempDir = new File(TMP_PATH);
|
368
|
if(!tempDir.exists() && !tempDir.mkdirs()){
|
369
|
logger.error("Error creating temporary directory for webapplications " + tempDir.getAbsolutePath());
|
370
|
System.exit(-1);
|
371
|
} else {
|
372
|
if(FileUtils.deleteQuietly(tempDir)){
|
373
|
tempDir.mkdirs();
|
374
|
logger.info("Old webapplications successfully cleared");
|
375
|
}
|
376
|
}
|
377
|
tempDir = null;
|
378
|
|
379
|
|
380
|
// WEBAPP options
|
381
|
// prepare web application files to run either from war files (production mode)
|
382
|
// or from source (development mode)
|
383
|
if(cmdLine.hasOption(WEBAPP.getOpt())){
|
384
|
|
385
|
cdmRemoteWebAppFile = new File(cmdLine.getOptionValue(WEBAPP.getOpt()));
|
386
|
if(cdmRemoteWebAppFile.isDirectory()){
|
387
|
logger.info("using user defined web application folder: " + cdmRemoteWebAppFile.getAbsolutePath());
|
388
|
} else {
|
389
|
logger.info("using user defined warfile: " + cdmRemoteWebAppFile.getAbsolutePath());
|
390
|
}
|
391
|
|
392
|
updateServerRunMode();
|
393
|
|
394
|
// load the default-web-application from source if running in development mode mode
|
395
|
if(isRunningFromWarFile){
|
396
|
defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME, false);
|
397
|
} else {
|
398
|
defaultWebAppFile = new File("./src/main/webapp");
|
399
|
}
|
400
|
|
401
|
if(isRunningFromSource){
|
402
|
if(cmdLine.hasOption(WEBAPP_CLASSPATH.getOpt())){
|
403
|
String classPathOption = cmdLine.getOptionValue(WEBAPP_CLASSPATH.getOpt());
|
404
|
normalizeClasspath(classPathOption);
|
405
|
}
|
406
|
}
|
407
|
} else {
|
408
|
// read version number
|
409
|
String version = readCdmRemoteVersion();
|
410
|
cdmRemoteWebAppFile = extractWar(CDM_WEBAPP + "-" + version, true);
|
411
|
defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME, false);
|
412
|
}
|
413
|
|
414
|
|
415
|
// HTTP Port
|
416
|
int httpPort = 8080;
|
417
|
if(cmdLine.hasOption(HTTP_PORT.getOpt())){
|
418
|
try {
|
419
|
httpPort = Integer.parseInt(cmdLine.getOptionValue(HTTP_PORT.getOpt()));
|
420
|
logger.info(HTTP_PORT.getOpt()+" set to "+cmdLine.getOptionValue(HTTP_PORT.getOpt()));
|
421
|
} catch (NumberFormatException e) {
|
422
|
logger.error("Supplied portnumber is not an integer");
|
423
|
System.exit(-1);
|
424
|
}
|
425
|
}
|
426
|
|
427
|
if(cmdLine.hasOption(DATASOURCES_FILE.getOpt())){
|
428
|
File datasourcesFile = new File(cmdLine.getOptionValue(DATASOURCES_FILE.getOpt()));
|
429
|
if(datasourcesFile.canRead()) {
|
430
|
instanceManager.setDatasourcesFile(datasourcesFile);
|
431
|
} else {
|
432
|
logger.error("File set as " + DATASOURCES_FILE.getOpt()
|
433
|
+ " (" + cmdLine.getOptionValue(DATASOURCES_FILE.getOpt())
|
434
|
+ ") is not readable.");
|
435
|
}
|
436
|
}
|
437
|
|
438
|
if(cmdLine.hasOption(CONTEXT_PATH_PREFIX.getOpt())){
|
439
|
|
440
|
String cppo = cmdLine.getOptionValue(CONTEXT_PATH_PREFIX.getOpt());
|
441
|
if(cppo.equals("/")) {
|
442
|
this.contextPathPrefix = "";
|
443
|
} else {
|
444
|
Pattern pattern = Pattern.compile("^/*(.*?)/*$");
|
445
|
String replacement = "$1";
|
446
|
this.contextPathPrefix = pattern.matcher(cppo).replaceAll(replacement) + "/";
|
447
|
}
|
448
|
}
|
449
|
|
450
|
verifySystemResources();
|
451
|
|
452
|
// load the configured instances for the first time
|
453
|
instanceManager.reLoadInstanceConfigurations();
|
454
|
|
455
|
// in jetty 9 currently each connector uses
|
456
|
// 2 threads - 1 to select for IO activity and 1 to accept new connections.
|
457
|
// there fore we need to add 2 to the number of cores
|
458
|
// QueuedThreadPool threadPool = new QueuedThreadPool(JvmManager.availableProcessors() + + 200);
|
459
|
// server = new Server(threadPool);
|
460
|
server = new Server();
|
461
|
server.addLifeCycleListener(instanceManager);
|
462
|
ServerConnector connector=new ServerConnector(server);
|
463
|
connector.setPort(httpPort);
|
464
|
server.addConnector(connector );
|
465
|
|
466
|
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
|
467
|
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
|
468
|
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
|
469
|
|
470
|
|
471
|
// JMX support
|
472
|
if(cmdLine.hasOption(JMX.getOpt())){
|
473
|
logger.info("adding JMX support ...");
|
474
|
MBeanContainer mBeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
|
475
|
server.addEventListener(mBeanContainer);
|
476
|
server.addBean(Log.getLog());
|
477
|
}
|
478
|
|
479
|
if(cmdLine.hasOption(WIN32SERVICE.getOpt())){
|
480
|
Win32Service win32Service = new Win32Service();
|
481
|
win32Service.setServer(server);
|
482
|
server.setStopAtShutdown(true);
|
483
|
server.addBean(win32Service);
|
484
|
}
|
485
|
|
486
|
// add default servlet context
|
487
|
logger.info("preparing default WebAppContext");
|
488
|
WebAppContext defaultWebappContext = new WebAppContext();
|
489
|
|
490
|
setWebApp(defaultWebappContext, defaultWebAppFile);
|
491
|
|
492
|
// JSP
|
493
|
//
|
494
|
// configuring jsp according to http://eclipse.org/jetty/documentation/current/configuring-jsp.html
|
495
|
// from example http://eclipse.org/jetty/documentation/current/embedded-examples.html#embedded-webapp-jsp
|
496
|
// Set the ContainerIncludeJarPattern so that jetty examines these
|
497
|
// container-path jars for tlds, web-fragments etc.
|
498
|
// If you omit the jar that contains the jstl .tlds, the jsp engine will
|
499
|
// scan for them instead.
|
500
|
defaultWebappContext.setAttribute(
|
501
|
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
|
502
|
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
|
503
|
|
504
|
defaultWebappContext.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
|
505
|
|
506
|
// Context path
|
507
|
//
|
508
|
defaultWebappContext.setContextPath("/" + (contextPathPrefix.isEmpty() ? "" : contextPathPrefix.substring(0, contextPathPrefix.length() - 1)));
|
509
|
logger.info("defaultWebapp (manager) context path:" + defaultWebappContext.getContextPath());
|
510
|
defaultWebappContext.setTempDirectory(DEFAULT_WEBAPP_TEMP_FOLDER);
|
511
|
|
512
|
// configure security context
|
513
|
// see for reference * http://docs.codehaus.org/display/JETTY/Realms
|
514
|
// * http://wiki.eclipse.org/Jetty/Starting/Porting_to_Jetty_7
|
515
|
HashLoginService loginService = new HashLoginService();
|
516
|
loginService.setConfig(USERHOME_CDM_LIBRARY_PATH + REALM_PROPERTIES_FILE);
|
517
|
defaultWebappContext.getSecurityHandler().setLoginService(loginService);
|
518
|
|
519
|
// Important:
|
520
|
// the defaultWebappContext MUST USE the super classloader
|
521
|
// otherwise the status page (index.jsp) might not work
|
522
|
defaultWebappContext.setClassLoader(this.getClass().getClassLoader());
|
523
|
contexts.addHandler(defaultWebappContext);
|
524
|
|
525
|
logger.info("setting contexts ...");
|
526
|
server.setHandler(contexts);
|
527
|
logger.info("starting jetty ...");
|
528
|
// try {
|
529
|
|
530
|
server.start();
|
531
|
|
532
|
// } catch(org.springframework.beans.BeansException e){
|
533
|
// Throwable rootCause = null;
|
534
|
// while(e.getCause() != null){
|
535
|
// rootCause = e.getCause();
|
536
|
// }
|
537
|
// if(rootCause != null && rootCause.getClass().getSimpleName().equals("InvalidCdmVersionException")){
|
538
|
//
|
539
|
// logger.error("rootCause ----------->" + rootCause.getMessage());
|
540
|
//// for(CdmInstanceProperties props : configAndStatus){
|
541
|
//// if(props.getDataSourceName())
|
542
|
//// }
|
543
|
// }
|
544
|
// }
|
545
|
|
546
|
if(cmdLine.hasOption(WIN32SERVICE.getOpt())){
|
547
|
logger.info("jetty has started as win32 service");
|
548
|
} else {
|
549
|
server.join();
|
550
|
logger.info(APPLICATION_NAME+" stopped.");
|
551
|
System.exit(0);
|
552
|
}
|
553
|
}
|
554
|
|
555
|
/**
|
556
|
* @param classpath
|
557
|
*/
|
558
|
private void normalizeClasspath(String classpath) {
|
559
|
StringBuilder classPathBuilder = new StringBuilder((int) (classpath.length() * 1.2));
|
560
|
String[] cpEntries = classpath.split("[\\:]");
|
561
|
for(String cpEntry : cpEntries){
|
562
|
classPathBuilder.append(',');
|
563
|
// if(cpEntry.endsWith(".jar")){
|
564
|
// classPathBuilder.append("jar:");
|
565
|
// }
|
566
|
classPathBuilder.append(cpEntry);
|
567
|
}
|
568
|
webAppClassPath = classPathBuilder.toString();
|
569
|
}
|
570
|
|
571
|
public String readCdmRemoteVersion() throws IOException {
|
572
|
String version = "cdmlib version unreadable";
|
573
|
InputStream versionInStream = Bootloader.class.getClassLoader().getResourceAsStream(VERSION_PROPERTIES_FILE);
|
574
|
if (versionInStream != null){
|
575
|
Properties versionProperties = new Properties();
|
576
|
versionProperties.load(versionInStream);
|
577
|
version = versionProperties.getProperty(CDM_WEBAPP_VERSION, version);
|
578
|
}
|
579
|
return version;
|
580
|
}
|
581
|
|
582
|
/**
|
583
|
* Ensure the jsp engine is initialized correctly
|
584
|
*/
|
585
|
private List<ContainerInitializer> jspInitializers()
|
586
|
{
|
587
|
JettyJasperInitializer sci = new JettyJasperInitializer();
|
588
|
ContainerInitializer initializer = new ContainerInitializer(sci, null);
|
589
|
List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
|
590
|
initializers.add(initializer);
|
591
|
return initializers;
|
592
|
}
|
593
|
|
594
|
|
595
|
|
596
|
private void verifySystemResources() {
|
597
|
|
598
|
OsChecker osChecker = new OsChecker();
|
599
|
if(osChecker.isLinux()){
|
600
|
try {
|
601
|
Process p = Runtime.getRuntime().exec(new String[] { "bash", "-c", "ulimit -n" });
|
602
|
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
|
603
|
String line;
|
604
|
StringBuilder response = new StringBuilder();
|
605
|
while ((line = in.readLine()) != null) {
|
606
|
response.append(line);
|
607
|
}
|
608
|
logger.info("OS Limit (Linux): maximum number of open files: " + response);
|
609
|
} catch (IOException e) {
|
610
|
// TODO Auto-generated catch block
|
611
|
e.printStackTrace();
|
612
|
}
|
613
|
} else {
|
614
|
logger.info("verifySystemResources only implemented for linux");
|
615
|
}
|
616
|
}
|
617
|
|
618
|
|
619
|
/**
|
620
|
* Configures and adds a {@link RollingFileAppender} to the root logger
|
621
|
*
|
622
|
* The log files of the cdm-remote instances are configured by the
|
623
|
* {@link eu.etaxonomy.cdm.remote.config.LoggingConfigurer}
|
624
|
*/
|
625
|
private void configureFileLogger() {
|
626
|
|
627
|
PatternLayout layout = new PatternLayout("%d %p [%c] - %m%n");
|
628
|
try {
|
629
|
String logFile = logPath + File.separator + "cdmserver.log";
|
630
|
RollingFileAppender appender = new RollingFileAppender(layout, logFile);
|
631
|
appender.setMaxBackupIndex(3);
|
632
|
appender.setMaxFileSize("2MB");
|
633
|
Logger.getRootLogger().addAppender(appender);
|
634
|
logger.info("logging to :" + logFile);
|
635
|
} catch (IOException e) {
|
636
|
logger.error("Creating RollingFileAppender failed:", e);
|
637
|
}
|
638
|
}
|
639
|
|
640
|
|
641
|
/**
|
642
|
* Adds a new WebAppContext to the contexts of the running jetty instance.
|
643
|
* <ol>
|
644
|
* <li>Initialize WebAppContext:
|
645
|
* <ol>
|
646
|
* <li>set context path</li>
|
647
|
* <li>set tmp directory</li>
|
648
|
* <li>bind JndiDataSource</li>
|
649
|
* <li>set web app context attributes</li>
|
650
|
* <li>create and setup individual classloader for the instance</li>
|
651
|
* </ol>
|
652
|
* </li>
|
653
|
* <li>
|
654
|
* finally add the new webappcontext to the contexts of the jetty instance</li>
|
655
|
* </ol>
|
656
|
*
|
657
|
* @param instance
|
658
|
* @return the instance given as parameter of null in case the instance has
|
659
|
* {@link Status.#disabled} or if it is already added.
|
660
|
* @throws IOException
|
661
|
*/
|
662
|
public WebAppContext addCdmInstanceContext(CdmInstance instance) throws IOException {
|
663
|
|
664
|
Configuration conf = instance.getConfiguration();
|
665
|
if(!instance.isEnabled()){
|
666
|
logger.info(conf.getInstanceName() + " is disabled, possibly due to JVM memory limitations");
|
667
|
return null;
|
668
|
}
|
669
|
if(getContextFor(conf) != null){
|
670
|
logger.info(conf.getInstanceName() + " is alreaddy added to the contexts - skipping");
|
671
|
return null;
|
672
|
}
|
673
|
|
674
|
instance.setStatus(Status.initializing);
|
675
|
logger.info("preparing WebAppContext for '"+ conf.getInstanceName() + "'");
|
676
|
WebAppContext cdmWebappContext = new WebAppContext();
|
677
|
|
678
|
cdmWebappContext.setContextPath(constructContextPath(conf));
|
679
|
logger.info("contextPath: " + cdmWebappContext.getContextPath());
|
680
|
// set persistTempDirectory to prevent jetty from creating and deleting this directory for each instance,
|
681
|
// since this behaviour can cause conflicts during parallel start up of instances.
|
682
|
cdmWebappContext.setPersistTempDirectory(true);
|
683
|
|
684
|
|
685
|
// if(!instance.bindJndiDataSource()){
|
686
|
// // a problem with the datasource occurred skip this webapp
|
687
|
// cdmWebappContext = null;
|
688
|
// logger.error("a problem with the datasource occurred -> skipping /" + conf.getInstanceName());
|
689
|
// instance.setStatus(Status.error);
|
690
|
// return cdmWebappContext;
|
691
|
// }
|
692
|
|
693
|
cdmWebappContext.setAttribute(SharedAttributes.ATTRIBUTE_DATASOURCE_NAME, conf.getInstanceName());
|
694
|
cdmWebappContext.setAttribute(SharedAttributes.ATTRIBUTE_JDBC_JNDI_NAME, conf.getJdbcJndiName());
|
695
|
if(cmdLine.hasOption(FORCE_SCHEMA_UPDATE.getOpt())){
|
696
|
cdmWebappContext.getAttributes().setAttribute(SharedAttributes.ATTRIBUTE_FORCE_SCHEMA_UPDATE, "true");
|
697
|
}
|
698
|
setWebApp(cdmWebappContext, getCdmRemoteWebAppFile());
|
699
|
|
700
|
cdmWebappContext.setAttribute(SharedAttributes.ATTRIBUTE_CDM_LOGFILE,
|
701
|
logPath + File.separator + "cdm-"
|
702
|
+ conf.getInstanceName() + ".log");
|
703
|
|
704
|
if( isRunningFromSource ){
|
705
|
|
706
|
/*
|
707
|
* when running the webapp from {projectpath} src/main/webapp we
|
708
|
* must assure that each web application is using it's own
|
709
|
* classloader thus we tell the WebAppClassLoader where the
|
710
|
* dependencies of the webapplication can be found. Otherwise
|
711
|
* the system classloader would load these resources.
|
712
|
*/
|
713
|
WebAppClassLoader classLoader = new WebAppClassLoader(cdmWebappContext);
|
714
|
if(webAppClassPath != null){
|
715
|
logger.info("Running cdm-webapp from source folder: Adding class path supplied by option '-" + WEBAPP_CLASSPATH.getOpt() +" =" + webAppClassPath +"' to WebAppClassLoader");
|
716
|
classLoader.addClassPath(webAppClassPath);
|
717
|
} else {
|
718
|
throw new RuntimeException("Classpath cdm-webapp for missing while running cdm-webapp from source folder. Please supplied cdm-server option '-" + WEBAPP_CLASSPATH.getOpt() +"");
|
719
|
}
|
720
|
cdmWebappContext.setClassLoader(classLoader);
|
721
|
}
|
722
|
|
723
|
contexts.addHandler(cdmWebappContext);
|
724
|
instance.setWebAppContext(cdmWebappContext);
|
725
|
cdmWebappContext.addLifeCycleListener(instance);
|
726
|
instance.setStatus(Status.stopped);
|
727
|
|
728
|
return cdmWebappContext;
|
729
|
}
|
730
|
|
731
|
/**
|
732
|
* @param conf
|
733
|
* @return
|
734
|
*/
|
735
|
public String constructContextPath(Configuration conf) {
|
736
|
|
737
|
return "/" + contextPathPrefix + conf.getInstanceName();
|
738
|
}
|
739
|
|
740
|
/**
|
741
|
* Removes the given instance from the contexts. If the instance is running
|
742
|
* at the time of calling this method it will be stopped first.
|
743
|
* The JndiDataSource and the webapplicationContext will be released and removed.
|
744
|
*
|
745
|
* @param instance the instance to be removed
|
746
|
*
|
747
|
* @throws Exception in case stopping the instance fails
|
748
|
*/
|
749
|
public void removeCdmInstanceContext(CdmInstance instance) throws Exception {
|
750
|
|
751
|
if(instance.getWebAppContext() != null){
|
752
|
if(instance.getWebAppContext().isRunning()){
|
753
|
try {
|
754
|
instance.getWebAppContext().stop();
|
755
|
} catch (Exception e) {
|
756
|
instance.getProblems().add("Error while stopping instance: " + e.getMessage());
|
757
|
throw e;
|
758
|
}
|
759
|
}
|
760
|
contexts.removeHandler(instance.getWebAppContext());
|
761
|
instance.releaseWebAppContext();
|
762
|
} else {
|
763
|
// maybe something went wrong before, try to find the potentially lost
|
764
|
// contexts directly in the server
|
765
|
ContextHandler handler = getContextFor(instance.getConfiguration());
|
766
|
if(handler != null){
|
767
|
contexts.removeHandler(handler);
|
768
|
}
|
769
|
}
|
770
|
instance.unbindJndiDataSource();
|
771
|
}
|
772
|
|
773
|
/**
|
774
|
* Sets the webapp specified by the <code>webApplicationResource</code> to
|
775
|
* the given <code>context</code>.
|
776
|
*
|
777
|
* @param context
|
778
|
* @param webApplicationResource the resource can either be a directory containing
|
779
|
* a Java web application or *.war file.
|
780
|
*
|
781
|
*/
|
782
|
private void setWebApp(WebAppContext context, File webApplicationResource) {
|
783
|
if(webApplicationResource.isDirectory()){
|
784
|
context.setResourceBase(webApplicationResource.getAbsolutePath());
|
785
|
logger.debug("setting directory " + webApplicationResource.getAbsolutePath() + " as webapplication");
|
786
|
} else {
|
787
|
context.setWar(webApplicationResource.getAbsolutePath());
|
788
|
logger.debug("setting war file " + webApplicationResource.getAbsolutePath() + " as webapplication");
|
789
|
}
|
790
|
}
|
791
|
|
792
|
private void updateServerRunMode() {
|
793
|
String webappPathNormalized = cdmRemoteWebAppFile.getAbsolutePath().replace('\\', '/');
|
794
|
isRunningFromSource = webappPathNormalized.endsWith("src/main/webapp");
|
795
|
isRunningfromTargetFolder = webappPathNormalized.endsWith("cdm-webapp/target/cdmserver");
|
796
|
isRunningFromWarFile = !(isRunningFromSource || isRunningfromTargetFolder);
|
797
|
}
|
798
|
|
799
|
|
800
|
public Server getServer() {
|
801
|
return server;
|
802
|
}
|
803
|
|
804
|
public ContextHandler getContextFor(Configuration conf) {
|
805
|
return getContextFor(constructContextPath(conf));
|
806
|
}
|
807
|
|
808
|
public ContextHandler getContextFor(String contextPath) {
|
809
|
for( Handler handler : contexts.getHandlers()){
|
810
|
if(handler instanceof ContextHandler){
|
811
|
if(((ContextHandler)handler).getContextPath().equals(contextPath)){
|
812
|
return (ContextHandler)handler;
|
813
|
}
|
814
|
}
|
815
|
}
|
816
|
return null;
|
817
|
}
|
818
|
|
819
|
public ContextHandlerCollection getContexts() {
|
820
|
return contexts;
|
821
|
}
|
822
|
|
823
|
/**
|
824
|
* @return a File object pointing to the location of the cdm-webapp
|
825
|
*/
|
826
|
public File getCdmRemoteWebAppFile(){
|
827
|
if(cdmRemoteWebAppFile == null){
|
828
|
throw new RuntimeException("Invalid order of action. Server not yet started. The startServer() method must be called first. ");
|
829
|
}
|
830
|
return cdmRemoteWebAppFile;
|
831
|
}
|
832
|
}
|