Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose:  A Class that implements main property configuration methods
4
 *  Copyright: 2008 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 *
8
 *   '$Author: tao $'
9
 *     '$Date: 2016-08-24 09:45:44 -0700 (Wed, 24 Aug 2016) $'
10
 * '$Revision: 9900 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat.admin;
28

    
29
import java.io.File;
30
import java.io.StringReader;
31
import java.util.Vector;
32

    
33
import javax.servlet.http.HttpServletRequest;
34
import javax.servlet.http.HttpServletResponse;
35

    
36
import org.apache.commons.io.FileUtils;
37
import org.apache.commons.io.IOUtils;
38
import org.apache.commons.io.filefilter.DirectoryFileFilter;
39
import org.apache.commons.io.filefilter.OrFileFilter;
40
import org.apache.commons.io.filefilter.WildcardFileFilter;
41
import org.apache.log4j.Logger;
42

    
43
import edu.ucsb.nceas.metacat.MetacatVersion;
44
import edu.ucsb.nceas.metacat.database.DBVersion;
45
import edu.ucsb.nceas.metacat.properties.PropertyService;
46
import edu.ucsb.nceas.metacat.service.ServiceService;
47
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
48
import edu.ucsb.nceas.metacat.shared.ServiceException;
49
import edu.ucsb.nceas.metacat.util.RequestUtil;
50
import edu.ucsb.nceas.metacat.util.SystemUtil;
51
import edu.ucsb.nceas.utilities.FileUtil;
52
import edu.ucsb.nceas.utilities.GeneralPropertyException;
53
import edu.ucsb.nceas.utilities.PropertiesMetaData;
54
import edu.ucsb.nceas.utilities.SortedProperties;
55
import edu.ucsb.nceas.utilities.UtilException;
56

    
57
/**
58
 * Control the display of the main properties configuration page and the 
59
 * processing of the configuration values.
60
 */
61
public class PropertiesAdmin extends MetacatAdmin {
62
    private static String BACKSLASH = "/";
63
    private static String DEFAULTMETACATCONTEXT = "metacat";
64
    private static String METACATPROPERTYAPPENDIX = "/WEB-INF/metacat.properties";
65
	private static PropertiesAdmin propertiesAdmin = null;
66
	private static Logger logMetacat = Logger.getLogger(PropertiesAdmin.class);
67

    
68
	/**
69
	 * private constructor since this is a singleton
70
	 */
71
	private PropertiesAdmin() {}
72

    
73
	/**
74
	 * Get the single instance of the MetaCatConfig.
75
	 * 
76
	 * @return the single instance of MetaCatConfig
77
	 */
78
	public static PropertiesAdmin getInstance() {
79
		if (propertiesAdmin == null) {
80
			propertiesAdmin = new PropertiesAdmin();
81
		}
82
		return propertiesAdmin;
83
	}
84
	
85
	/**
86
	 * Handle configuration of the main application properties
87
	 * 
88
	 * @param request
89
	 *            the http request object
90
	 * @param response
91
	 *            the http response to be sent back to the client
92
	 */
93
	public void configureProperties(HttpServletRequest request,
94
			HttpServletResponse response) throws AdminException {
95

    
96
		String processForm = request.getParameter("processForm");
97
		String formErrors = (String)request.getAttribute("formErrors");
98

    
99
		if (processForm == null || !processForm.equals("true") || formErrors != null) {
100
			// The servlet configuration parameters have not been set, or there
101
			// were form errors on the last attempt to configure, so redirect to
102
			// the web form for configuring metacat
103

    
104
			try {
105
				// Load the properties metadata file so that the JSP page can
106
				// use the metadata to construct the editing form
107
				PropertiesMetaData metadata = PropertyService.getMainMetaData();
108
				request.setAttribute("metadata", metadata);
109

    
110
				String externalDir = PropertyService.getRecommendedExternalDir();
111
				
112
				if (externalDir == null) {
113
					throw new AdminException("Could not initialize property configuration "
114
									+ "page recommended application backup directory was null");
115
				}
116
				
117
				// Attempt to discover the following properties.  These will show
118
				// up in the configuration fields if nothing else is provided.
119
				PropertyService.setPropertyNoPersist("application.context",
120
						ServiceService.getRealApplicationContext());
121
				PropertyService.setPropertyNoPersist("server.name", SystemUtil
122
						.discoverServerName(request));
123
				PropertyService.setPropertyNoPersist("server.httpPort", SystemUtil
124
						.discoverServerPort(request));
125
				PropertyService.setPropertyNoPersist("server.httpSSLPort",
126
						SystemUtil.discoverServerSSLPort(request));
127
				PropertyService.setPropertyNoPersist("application.deployDir",
128
						SystemUtil.discoverDeployDir(request));
129
				PropertyService.setPropertyNoPersist("application.datafilepath",
130
						externalDir + FileUtil.getFS() + "data");
131
				PropertyService.setPropertyNoPersist("application.inlinedatafilepath",
132
						externalDir + FileUtil.getFS() + "inline-data");
133
				PropertyService.setPropertyNoPersist("application.documentfilepath",
134
						externalDir + FileUtil.getFS() + "documents");
135
				PropertyService.setPropertyNoPersist("application.tempDir",
136
						externalDir + FileUtil.getFS() + "temporary");
137
				PropertyService.setPropertyNoPersist("replication.logdir",
138
						externalDir + FileUtil.getFS() + "logs");
139
				PropertyService.setPropertyNoPersist("solr.homeDir",
140
						externalDir + FileUtil.getFS() + "solr-home");
141

    
142
				PropertyService.persistProperties();
143
				PropertyService.syncToSettings();
144

    
145
				// Add the list of properties from metacat.properties to the request
146
				Vector<String> propertyNames = PropertyService.getPropertyNames();
147
				for (String propertyName : propertyNames) {
148
					request.setAttribute(propertyName, PropertyService.getProperty(propertyName));
149
				}
150

    
151
				// Check for any backup properties and apply them to the
152
				// request. These are properties from previous configurations. 
153
				// They keep the user from having to re-enter all values when 
154
				// upgrading. If this is a first time install, getBackupProperties 
155
				// will return null.
156
				SortedProperties backupProperties = null;
157
				if ((backupProperties = 
158
						PropertyService.getMainBackupProperties()) != null) {
159
					Vector<String> backupKeys = backupProperties.getPropertyNames();
160
					for (String key : backupKeys) {
161
						String value = backupProperties.getProperty(key);
162
						if (value != null) {
163
							request.setAttribute(key, value);
164
						}
165
					}
166
				}
167

    
168
				// Forward the request to the JSP page
169
				RequestUtil.forwardRequest(request, response,
170
						"/admin/properties-configuration.jsp", null);
171

    
172
			} catch (GeneralPropertyException gpe) {
173
				throw new AdminException("PropertiesAdmin.configureProperties - Problem getting or " + 
174
						"setting property while initializing system properties page: " + gpe.getMessage());
175
			} catch (MetacatUtilException mue) {
176
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while initializing "
177
						+ "system properties page:" + mue.getMessage());
178
			} catch (ServiceException se) {
179
				throw new AdminException("PropertiesAdmin.configureProperties - Service problem while initializing "
180
						+ "system properties page:" + se.getMessage());
181
			} 
182
		} else {
183
			// The configuration form is being submitted and needs to be
184
			// processed.
185
			Vector<String> validationErrors = new Vector<String>();
186
			Vector<String> processingErrors = new Vector<String>();
187
			Vector<String> processingSuccess = new Vector<String>();
188

    
189
			MetacatVersion metacatVersion = null;
190
			
191
			try {
192
				metacatVersion = SystemUtil.getMetacatVersion();
193
				
194
				// For each property, check if it is changed and save it
195
				Vector<String> propertyNames = PropertyService.getPropertyNames();
196
				for (String name : propertyNames) {
197
					PropertyService.checkAndSetProperty(request, name);
198
				}
199

    
200
				// we need to write the options from memory to the properties
201
				// file
202
				PropertyService.persistProperties();
203

    
204
				// Validate that the options provided are legitimate. Note that
205
				// we've allowed them to persist their entries. As of this point
206
				// there is no other easy way to go back to the configure form
207
				// and preserve their entries.
208
				validationErrors.addAll(validateOptions(request));
209
				
210
				// Try to create data directories if necessary.
211
				String dataDir = PropertyService.getProperty("application.datafilepath");
212
				try {
213
					FileUtil.createDirectory(dataDir);
214
				} catch (UtilException ue) {
215
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + dataDir +
216
					" : " + ue.getMessage();
217
					logMetacat.error(errorString);
218
					validationErrors.add(errorString);
219
				}
220
				
221
				// Try to create inline-data directories if necessary.
222
				String inlineDataDir = PropertyService.getProperty("application.inlinedatafilepath");
223
				try {
224
					FileUtil.createDirectory(inlineDataDir);
225
				} catch (UtilException ue) {
226
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + inlineDataDir +
227
						" : " + ue.getMessage();
228
					logMetacat.error(errorString);
229
					validationErrors.add(errorString);
230
				}
231
				
232
				// Try to create document directories if necessary.
233
				String documentfilepath = PropertyService.getProperty("application.documentfilepath");
234
				try {
235
					FileUtil.createDirectory(documentfilepath);
236
				} catch (UtilException ue) {	
237
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + documentfilepath +
238
						" : " + ue.getMessage();
239
					logMetacat.error(errorString);
240
					validationErrors.add(errorString);
241
				}
242
				
243
				// Try to create temporary directories if necessary.
244
				String tempDir = PropertyService.getProperty("application.tempDir");
245
				try {
246
					FileUtil.createDirectory(tempDir);
247
				} catch (UtilException ue) {		
248
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + tempDir +
249
						" : " + ue.getMessage();
250
					logMetacat.error(errorString);
251
					validationErrors.add(errorString);
252
				}
253
				
254
				// Try to create temporary directories if necessary.
255
				String replLogDir = PropertyService.getProperty("replication.logdir");
256
				try {
257
					FileUtil.createDirectory(replLogDir);
258
				} catch (UtilException ue) {		
259
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + replLogDir +
260
						" : " + ue.getMessage();
261
					logMetacat.error(errorString);
262
					validationErrors.add(errorString);
263
				}
264
				
265
				// Try to create and initialize the solr-home directory if necessary.
266
				String solrHomePath = PropertyService.getProperty("solr.homeDir");
267
				String indexContext = PropertyService.getProperty("index.context");
268
				boolean solrHomeExists = new File(solrHomePath).exists();
269
				if (!solrHomeExists) {
270
					try {
271
						String metacatWebInf = ServiceService.getRealConfigDir();
272
						String metacatIndexSolrHome = metacatWebInf + "/../../" + indexContext + "/WEB-INF/classes/solr-home";
273
						// only attempt to copy if we have the source directory to copy from
274
						File sourceDir = new File(metacatIndexSolrHome);
275
						if (sourceDir.exists()) {
276
							FileUtil.createDirectory(solrHomePath);
277
							OrFileFilter fileFilter = new OrFileFilter();
278
							fileFilter.addFileFilter(DirectoryFileFilter.DIRECTORY);
279
							fileFilter.addFileFilter(new WildcardFileFilter("*"));
280
							FileUtils.copyDirectory(new File(metacatIndexSolrHome), new File(solrHomePath), fileFilter );
281
						}
282
					} catch (Exception ue) {	
283
						String errorString = "PropertiesAdmin.configureProperties - Could not initialize directory: " + solrHomePath +
284
								" : " + ue.getMessage();
285
						logMetacat.error(errorString);
286
						validationErrors.add(errorString);
287
					}
288
				} else {
289
					// check it
290
					if (!FileUtil.isDirectory(solrHomePath)) {
291
						String errorString = "PropertiesAdmin.configureProperties - SOLR home is not a directory: " + solrHomePath;
292
						logMetacat.error(errorString);
293
						validationErrors.add(errorString);
294
					}
295
				}
296
				
297
				//modify some params of the index context
298
				this.modifyIndexContextParams(indexContext);
299
				
300
				// make sure hazelcast.xml uses a unique group name
301
				this.modifyHazelcastConfig();
302
				
303
				// set permissions on the registry cgi scripts, least on *nix systems
304
				try {
305
					String cgiFiles = 
306
							PropertyService.getProperty("application.deployDir") 
307
							+ FileUtil.getFS() 
308
							+ PropertyService.getProperty("application.context") 
309
							+ PropertyService.getProperty("application.cgiDir")
310
							+ FileUtil.getFS() 
311
							+ "*.cgi";
312
					String [] command = {"sh", "-c", "chmod +x " + cgiFiles};
313
					Runtime rt = Runtime.getRuntime();
314
					Process pr = rt.exec(command);
315
					int ret = pr.waitFor();
316
					if (ret > 0) {
317
						logMetacat.error(IOUtils.toString(pr.getErrorStream()));
318
					}
319
				} catch (Exception ignorable) {
320
					/// just a warning
321
					logMetacat.warn("Could not set permissions on the registry scripts: " + ignorable.getMessage(), ignorable);
322
				}
323
				
324
				// write the backup properties to a location outside the 
325
				// application directories so they will be available after
326
				// the next upgrade
327
				PropertyService.persistMainBackupProperties();
328

    
329
			} catch (GeneralPropertyException gpe) {
330
				String errorMessage = "PropertiesAdmin.configureProperties - Problem getting or setting property while "
331
						+ "processing system properties page: " + gpe.getMessage();
332
				logMetacat.error(errorMessage);
333
				processingErrors.add(errorMessage);
334
			} 
335
			
336
			try {
337
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
338
					RequestUtil.clearRequestMessages(request);
339
					RequestUtil.setRequestFormErrors(request, validationErrors);
340
					RequestUtil.setRequestErrors(request, processingErrors);
341
					RequestUtil.forwardRequest(request, response, "/admin", null);
342
				} else {
343
					// Now that the options have been set, change the
344
					// 'propertiesConfigured' option to 'true'
345
					PropertyService.setProperty("configutil.propertiesConfigured",
346
							PropertyService.CONFIGURED);
347
					
348
					// if the db version is already the same as the metacat version,
349
					// update metacat.properties. Have to do this after
350
					// propertiesConfigured is set to CONFIGURED
351
					DBVersion dbVersion = DBAdmin.getInstance().getDBVersion();
352
					if (dbVersion != null && metacatVersion != null && 
353
							dbVersion.compareTo(metacatVersion) == 0) {
354
						PropertyService.setProperty("configutil.databaseConfigured", 
355
								PropertyService.CONFIGURED);
356
					}
357
					
358
					// Reload the main metacat configuration page
359
					processingSuccess.add("Properties successfully configured");
360
					RequestUtil.clearRequestMessages(request);
361
					RequestUtil.setRequestSuccess(request, processingSuccess);
362
					RequestUtil.forwardRequest(request, response, 
363
							"/admin?configureType=configure&processForm=false", null);
364
				}
365
			} catch (MetacatUtilException mue) {
366
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while processing system "
367
						+ "properties page: " + mue.getMessage());
368
			} catch (GeneralPropertyException gpe) {
369
				throw new AdminException("PropertiesAdmin.configureProperties - problem with properties while "
370
						+ "processing system properties page: " + gpe.getMessage());
371
			}
372
		}
373
	}
374
	
375
	/**
376
	 * In the web.xml of the Metacat-index context, there is a parameter:
377
	 * <context-param>
378
     * <param-name>metacat.properties.path</param-name>
379
     * <param-value>/metacat/WEB-INF/metacat.properties</param-value>
380
     * <description>The metacat.properties file for sibling metacat deployment. Note that the context can change</description>
381
     *  </context-param>
382
     *  It points to the default metacat context - knb. If we rename the context, we need to change the value of there.
383
	 */
384
	private void modifyIndexContextParams(String indexContext) {
385
	    if(indexContext != null) {
386
	        try {
387
	            String metacatContext = PropertyService.getProperty("application.context");
388
	            //System.out.println("the metacat context is ========================="+metacatContext);
389
	            if(metacatContext != null && !metacatContext.equals(DEFAULTMETACATCONTEXT)) {
390
	                String indexConfigFile = 
391
	                                PropertyService.getProperty("application.deployDir")
392
	                                + FileUtil.getFS()
393
	                                + indexContext
394
	                                + FileUtil.getFS() 
395
	                                + "WEB-INF"
396
	                                + FileUtil.getFS()
397
	                                + "web.xml";
398
	                //System.out.println("============================== the web.xml file is "+indexConfigFile);
399
	                String configContents = FileUtil.readFileToString(indexConfigFile, "UTF-8");
400
	                //System.out.println("============================== the content of web.xml file is "+configContents);
401
	                configContents = configContents.replace(BACKSLASH+DEFAULTMETACATCONTEXT+METACATPROPERTYAPPENDIX, BACKSLASH+metacatContext+METACATPROPERTYAPPENDIX);
402
	                FileUtil.writeFile(indexConfigFile, new StringReader(configContents), "UTF-8");
403
	            }
404
                
405
            } catch (Exception e) {
406
                String errorMessage = "PropertiesAdmin.configureProperties - Problem getting/setting the \"metacat.properties.path\" in the web.xml of the index context : " + e.getMessage();
407
                logMetacat.error(errorMessage);
408
            }
409
	    }
410
	}
411
	
412
	/**
413
	 * Changes the Hazelcast group name to match the current context
414
	 * This ensures we do not share the same group if multiple Metacat 
415
	 * instances are running in the same Tomcat container.
416
	 */
417
	private void modifyHazelcastConfig() {
418
        try {
419
            String metacatContext = PropertyService.getProperty("application.context");
420
            //System.out.println("the metacat context is ========================="+metacatContext);
421
            if (metacatContext != null) {
422
                String hzConfigFile = 
423
                                PropertyService.getProperty("application.deployDir")
424
                                + FileUtil.getFS()
425
                                + metacatContext
426
                                + FileUtil.getFS() 
427
                                + "WEB-INF"
428
                                + FileUtil.getFS()
429
                                + "hazelcast.xml";
430
                //System.out.println("============================== the web.xml file is "+indexConfigFile);
431
                String configContents = FileUtil.readFileToString(hzConfigFile, "UTF-8");
432
                //System.out.println("============================== the content of web.xml file is "+configContents);
433
                configContents = configContents.replace("<name>metacat</name>", "<name>" + metacatContext + "</name>");
434
                FileUtil.writeFile(hzConfigFile, new StringReader(configContents), "UTF-8");
435
            }
436
            
437
        } catch (Exception e) {
438
            String errorMessage = "PropertiesAdmin.configureProperties - Problem setting groupName in hazelcast.xml: " + e.getMessage();
439
            logMetacat.error(errorMessage);
440
        }
441
	}
442

    
443
	/**
444
	 * Validate the most important configuration options submitted by the user.
445
	 * 
446
	 * @param request
447
	 *            the http request object
448
	 * 
449
	 * @return a vector holding error message for any fields that fail
450
	 *         validation.
451
	 */
452
	protected Vector<String> validateOptions(HttpServletRequest request) {
453
		Vector<String> errorVector = new Vector<String>();
454

    
455
		// Test database connectivity
456
		try {
457
			String dbError = DBAdmin.getInstance().validateDBConnectivity(
458
					request.getParameter("database.driver"),
459
					request.getParameter("database.connectionURI"),
460
					request.getParameter("database.user"),
461
					request.getParameter("database.password"));
462
			if (dbError != null) {
463
				errorVector.add(dbError);
464
			}
465
		} catch (AdminException ae) {
466
			errorVector.add("Could not instantiate database admin: "
467
					+ ae.getMessage());
468
		}
469

    
470
		return errorVector;
471
	}
472
	
473

    
474
}
(11-11/13)