Project

General

Profile

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

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

    
28
import java.util.Vector;
29

    
30
import javax.servlet.http.HttpServletRequest;
31
import javax.servlet.http.HttpServletResponse;
32

    
33
import org.apache.log4j.Logger;
34
import org.dataone.client.CNode;
35
import org.dataone.client.D1Client;
36
import org.dataone.client.auth.CertificateManager;
37
import org.dataone.service.exceptions.BaseException;
38
import org.dataone.service.types.v1.Node;
39
import org.dataone.service.types.v1.NodeList;
40
import org.dataone.service.types.v1.NodeReference;
41
import org.dataone.service.types.v1.Session;
42

    
43
import edu.ucsb.nceas.metacat.IdentifierManager;
44
import edu.ucsb.nceas.metacat.admin.upgrade.dataone.GenerateORE;
45
import edu.ucsb.nceas.metacat.admin.upgrade.dataone.GenerateSystemMetadata;
46
import edu.ucsb.nceas.metacat.dataone.MNodeService;
47
import edu.ucsb.nceas.metacat.properties.PropertyService;
48
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
49
import edu.ucsb.nceas.metacat.util.RequestUtil;
50
import edu.ucsb.nceas.utilities.GeneralPropertyException;
51
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
52
import edu.ucsb.nceas.utilities.SortedProperties;
53

    
54
/**
55
 * Control the display of the database configuration page and the processing
56
 * of the configuration values.
57
 */
58
public class D1Admin extends MetacatAdmin {
59

    
60
	private static D1Admin instance = null;
61
	private Logger logMetacat = Logger.getLogger(D1Admin.class);
62

    
63
	/**
64
	 * private constructor since this is a singleton
65
	 */
66
	private D1Admin() throws AdminException {
67

    
68
	}
69

    
70
	/**
71
	 * Get the single instance of D1Admin.
72
	 * 
73
	 * @return the single instance of D1Admin
74
	 */
75
	public static D1Admin getInstance() throws AdminException {
76
		if (instance == null) {
77
			instance = new D1Admin();
78
		}
79
		return instance;
80
	}
81

    
82
	/**
83
	 * Handle configuration of the database the first time that Metacat starts
84
	 * or when it is explicitly called. Collect necessary update information
85
	 * from the administrator.
86
	 * 
87
	 * @param request
88
	 *            the http request information
89
	 * @param response
90
	 *            the http response to be sent back to the client
91
	 */
92
	public void configureDataONE(HttpServletRequest request,
93
			HttpServletResponse response) throws AdminException {
94

    
95
		String processForm = request.getParameter("processForm");
96
		String bypass = request.getParameter("bypass");
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
				
106
				// get the current configuration values
107
				String cnURL = PropertyService.getProperty("D1Client.CN_URL");
108
				String nodeName = PropertyService.getProperty("dataone.nodeName");
109
				String nodeDescription = PropertyService.getProperty("dataone.nodeDescription");
110
				String memberNodeId = PropertyService.getProperty("dataone.nodeId");
111
				String nodeSynchronize = PropertyService.getProperty("dataone.nodeSynchronize");
112
				String subject = PropertyService.getProperty("dataone.subject");
113
				String contactSubject = PropertyService.getProperty("dataone.contactSubject");
114
				String certpath = PropertyService.getProperty("D1Client.certificate.file");
115
				
116
				//the synch schedule
117
				String year = PropertyService.getProperty("dataone.nodeSynchronization.schedule.year");
118
				String mon = PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon");
119
				String mday = PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday");
120
				String wday = PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday");
121
				String hour = PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour");
122
				String min = PropertyService.getProperty("dataone.nodeSynchronization.schedule.min");
123
				String sec = PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec");
124
				
125
				// the replication policies
126
                String nodeReplicate = PropertyService.getProperty("dataone.nodeReplicate");
127
                String numReplicas = PropertyService.getProperty("dataone.replicationpolicy.default.numreplicas");
128
                String preferredNodeList = PropertyService.getProperty("dataone.replicationpolicy.default.preferredNodeList");
129
                String blockedNodeList = PropertyService.getProperty("dataone.replicationpolicy.default.blockedNodeList");
130
				
131
				boolean synchronize = false;
132
				if (nodeSynchronize != null) {
133
					synchronize = Boolean.parseBoolean(nodeSynchronize);
134
				}
135
				boolean replicate = false;
136
				if (nodeReplicate != null) {
137
					replicate = Boolean.parseBoolean(nodeReplicate);
138
				}
139
				request.setAttribute("D1Client.CN_URL", cnURL);
140
				request.setAttribute("dataone.nodeName", nodeName);
141
				request.setAttribute("dataone.nodeDescription", nodeDescription);
142
				request.setAttribute("dataone.nodeId", memberNodeId);
143
				request.setAttribute("dataone.nodeSynchronize", Boolean.toString(synchronize));
144
				request.setAttribute("dataone.subject", subject);
145
				request.setAttribute("dataone.contactSubject", contactSubject);
146
				request.setAttribute("D1Client.certificate.file", certpath);
147
				
148
				// synch schedule
149
				request.setAttribute("dataone.nodeSynchronization.schedule.year", year);
150
				request.setAttribute("dataone.nodeSynchronization.schedule.mon", mon);
151
				request.setAttribute("dataone.nodeSynchronization.schedule.mday", mday);
152
				request.setAttribute("dataone.nodeSynchronization.schedule.wday", wday);
153
				request.setAttribute("dataone.nodeSynchronization.schedule.hour", hour);
154
				request.setAttribute("dataone.nodeSynchronization.schedule.min", min);
155
				request.setAttribute("dataone.nodeSynchronization.schedule.sec", sec);
156

    
157
				// replication policies
158
                request.setAttribute("dataone.nodeReplicate", Boolean.toString(replicate));
159
                request.setAttribute("dataone.replicationpolicy.default.numreplicas", numReplicas);
160
                request.setAttribute("dataone.replicationpolicy.default.preferredNodeList", preferredNodeList);
161
                request.setAttribute("dataone.replicationpolicy.default.blockedNodeList", blockedNodeList);
162

    
163

    
164
				// try the backup properties
165
				SortedProperties backupProperties = null;
166
				if ((backupProperties = 
167
						PropertyService.getMainBackupProperties()) != null) {
168
					Vector<String> backupKeys = backupProperties.getPropertyNames();
169
					for (String key : backupKeys) {
170
						String value = backupProperties.getProperty(key);
171
						if (value != null) {
172
							request.setAttribute(key, value);
173
						}
174
					}
175
				}
176
				
177
				// set the configuration state so we know how to render the UI page buttons
178
				// if we have already configured once, we cannot skip this page
179
				request.setAttribute("configutil.dataoneConfigured", PropertyService.getProperty("configutil.dataoneConfigured"));
180
				
181
				// do we know if this is an update, pending verification, or a new registration?
182
				memberNodeId = (String) request.getAttribute("dataone.nodeId");
183
				boolean update = isNodeRegistered(memberNodeId);
184
				request.setAttribute("dataone.isUpdate", Boolean.toString(update));
185
				request.setAttribute("dataone.mn.registration.submitted", PropertyService.getProperty("dataone.mn.registration.submitted"));
186
				
187
				// enable the services?
188
				request.setAttribute("dataone.mn.services.enabled", PropertyService.getProperty("dataone.mn.services.enabled"));
189
				
190
				// Forward the request to the JSP page
191
				RequestUtil.forwardRequest(request, response, "/admin/dataone-configuration.jsp", null);
192
			} catch (GeneralPropertyException gpe) {
193
				throw new AdminException("D1Admin.configureDataONE - Problem getting or " + 
194
						"setting property while initializing system properties page: " + gpe.getMessage());
195
			} catch (MetacatUtilException mue) {
196
				throw new AdminException("D1Admin.configureDataONE - utility problem while initializing "
197
						+ "system properties page:" + mue.getMessage());
198
			} 
199
		} else if (bypass != null && bypass.equals("true")) {
200
			Vector<String> processingErrors = new Vector<String>();
201
			Vector<String> processingSuccess = new Vector<String>();
202
			
203
			// Bypass the D1 configuration. 
204
			// This will keep Metacat running
205
			try {
206
				PropertyService.setProperty("configutil.dataoneConfigured", PropertyService.BYPASSED);
207
				
208
			} catch (GeneralPropertyException gpe) {
209
				String errorMessage = "D1Admin.configureDataONE - Problem getting or setting property while "
210
					+ "processing system properties page: " + gpe.getMessage();
211
				logMetacat.error(errorMessage);
212
				processingErrors.add(errorMessage);
213
			}
214
			try {
215
				if (processingErrors.size() > 0) {
216
					RequestUtil.clearRequestMessages(request);
217
					RequestUtil.setRequestErrors(request, processingErrors);
218
					RequestUtil.forwardRequest(request, response, "/admin", null);
219
				} else {			
220
					// Reload the main metacat configuration page
221
					processingSuccess.add("DataONE configuration successfully bypassed");
222
					RequestUtil.clearRequestMessages(request);
223
					RequestUtil.setRequestSuccess(request, processingSuccess);
224
					RequestUtil.forwardRequest(request, response, 
225
							"/admin?configureType=configure&processForm=false", null);
226
				}
227
			} catch (MetacatUtilException mue) {
228
				throw new AdminException("D1Admin.configureDataONE - utility problem while processing dataone page: "
229
						+ mue.getMessage());
230
			} 
231
		
232
		} else {
233
			// The configuration form is being submitted and needs to be
234
			// processed, setting the properties in the configuration file
235
			// then restart metacat
236

    
237
			// The configuration form is being submitted and needs to be
238
			// processed.
239
			Vector<String> validationErrors = new Vector<String>();
240
			Vector<String> processingErrors = new Vector<String>();
241
			Vector<String> processingSuccess = new Vector<String>();
242

    
243
			try {
244
				// Validate that the options provided are legitimate. Note that
245
				// we've allowed them to persist their entries. As of this point
246
				// there is no other easy way to go back to the configure form
247
				// and preserve their entries.
248
				validationErrors.addAll(validateOptions(request));
249
				
250
				String cnURL = (String)request.getParameter("D1Client.CN_URL");
251
				String nodeName = (String)request.getParameter("dataone.nodeName");
252
				String nodeDescription = (String)request.getParameter("dataone.nodeDescription");
253
				String memberNodeId = (String)request.getParameter("dataone.nodeId");
254
				String nodeSynchronize = (String)request.getParameter("dataone.nodeSynchronize");
255
				String subject = (String)request.getParameter("dataone.subject");
256
				String contactSubject = (String)request.getParameter("dataone.contactSubject");
257
				String certpath = (String)request.getParameter("D1Client.certificate.file");
258
				
259
				// the synch schedule
260
				String year = (String) request.getParameter("dataone.nodeSynchronization.schedule.year");
261
				String mon = (String) request.getParameter("dataone.nodeSynchronization.schedule.mon");
262
				String mday = (String) request.getParameter("dataone.nodeSynchronization.schedule.mday");
263
				String wday = (String) request.getParameter("dataone.nodeSynchronization.schedule.wday");
264
				String hour = (String) request.getParameter("dataone.nodeSynchronization.schedule.hour");
265
				String min = (String) request.getParameter("dataone.nodeSynchronization.schedule.min");
266
				String sec = (String) request.getParameter("dataone.nodeSynchronization.schedule.sec");
267
				
268
				// the replication policies
269
                String nodeReplicate = (String)request.getParameter("dataone.nodeReplicate");
270
                String numReplicas = (String)request.getParameter("dataone.replicationpolicy.default.numreplicas");
271
                String preferredNodeList = (String)request.getParameter("dataone.replicationpolicy.default.preferredNodeList");
272
                String blockedNodeList = (String)request.getParameter("dataone.replicationpolicy.default.blockedNodeList");
273

    
274
				boolean synchronize = false;
275
				if (nodeSynchronize != null) {
276
					synchronize = Boolean.parseBoolean(nodeSynchronize);
277
				}
278
				boolean replicate = false;
279
				if (nodeReplicate != null) {
280
					replicate = Boolean.parseBoolean(nodeReplicate);
281
				}
282
				
283
				// enable services as a whole?
284
                boolean servicesEnabled = false;
285
                String servicesEnabledString = (String) request.getParameter("dataone.mn.services.enabled");
286
                if (servicesEnabledString != null) {
287
                	servicesEnabled = Boolean.parseBoolean(servicesEnabledString);
288
                }
289
				
290
				// process the values, checking for nulls etc..
291
				if (nodeName == null ) {
292
					validationErrors.add("nodeName cannot be null");
293
				} else {
294
					
295
					PropertyService.setProperty("D1Client.CN_URL", cnURL);
296
					PropertyService.setPropertyNoPersist("dataone.nodeName", nodeName);
297
					PropertyService.setPropertyNoPersist("dataone.nodeDescription", nodeDescription);					
298
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronize", Boolean.toString(synchronize));
299
					PropertyService.setPropertyNoPersist("dataone.subject", subject);
300
					PropertyService.setPropertyNoPersist("dataone.contactSubject", contactSubject);
301
					PropertyService.setPropertyNoPersist("D1Client.certificate.file", certpath);
302
					
303
					// the synch schedule
304
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.year", year);
305
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.mon", mon);
306
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.mday", mday);
307
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.wday", wday);
308
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.hour", hour);
309
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.min", min);
310
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronization.schedule.sec", sec);
311
					
312
					// the replication policies
313
	                PropertyService.setPropertyNoPersist("dataone.nodeReplicate", Boolean.toString(replicate));
314
	                PropertyService.setPropertyNoPersist("dataone.replicationpolicy.default.numreplicas", numReplicas);
315
                    PropertyService.setPropertyNoPersist("dataone.replicationpolicy.default.preferredNodeList", preferredNodeList);
316
                    PropertyService.setPropertyNoPersist("dataone.replicationpolicy.default.blockedNodeList", blockedNodeList);
317

    
318
                    // services
319
					PropertyService.setPropertyNoPersist("dataone.mn.services.enabled", Boolean.toString(servicesEnabled));
320
					
321
					// get the current node id so we know if we updated the value
322
					String existingMemberNodeId = PropertyService.getProperty("dataone.nodeId");
323
					
324
					// update the property value
325
		            PropertyService.setPropertyNoPersist("dataone.nodeId", memberNodeId);
326
					
327
		            // persist them all
328
					PropertyService.persistProperties();
329
					
330
					// save a backup in case the form has errors, we reload from these
331
					PropertyService.persistMainBackupProperties();
332
					
333
			        // Register/update as a DataONE Member Node					
334
					registerDataONEMemberNode();
335
					
336
					// did we end up changing the member node id from what it used to be?
337
					if (!existingMemberNodeId.equals(memberNodeId)) {
338
						// update all existing system Metadata for this node id
339
						IdentifierManager.getInstance().updateAuthoritativeMemberNodeId(existingMemberNodeId, memberNodeId);
340
					}
341
					
342
					// dataone system metadata generation
343
					// NOTE: commented this out - we can generate this after the registration/configuration
344
					// it will be more controlled and deliberate that way -BRL
345
//					boolean smGenerated = Boolean.parseBoolean(PropertyService.getProperty("dataone.systemmetadata.generated"));
346
//					if (!smGenerated) {
347
//						GenerateSystemMetadata systemMetadataUpgrade = new GenerateSystemMetadata();
348
//				        systemMetadataUpgrade.upgrade();
349
//				        // NOTE: this runs in a thread and marks SM generated when thatthread completes
350
//					}
351
//
352
//					// Generate ORE, if we haven't
353
//					boolean oreGenerated = Boolean.parseBoolean(PropertyService.getProperty("dataone.ore.generated"));
354
//					if (!oreGenerated) {
355
//						GenerateORE gore = new GenerateORE();
356
//						gore.upgrade();
357
//						PropertyService.setProperty("dataone.ore.generated", Boolean.TRUE.toString());
358
//					}
359
					
360
					// write the backup properties to a location outside the
361
					// application directories so they will be available after
362
					// the next upgrade
363
					PropertyService.persistMainBackupProperties();
364
					
365
				}
366
			} catch (GeneralPropertyException gpe) {
367
				String errorMessage = "D1Admin.configureDataONE - Problem getting or setting property while "
368
						+ "processing system properties page: " + gpe.getMessage();
369
				logMetacat.error(errorMessage);
370
				processingErrors.add(errorMessage);
371
			} catch (Exception e) {
372
				String errorMessage = "D1Admin.configureDataONE error: " + e.getMessage();
373
				logMetacat.error(errorMessage);
374
				processingErrors.add(errorMessage);
375
			}
376

    
377
			try {
378
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
379
					RequestUtil.clearRequestMessages(request);
380
					RequestUtil.setRequestFormErrors(request, validationErrors);
381
					RequestUtil.setRequestErrors(request, processingErrors);
382
					RequestUtil.forwardRequest(request, response, "/admin", null);
383
				} else {
384
					// Now that the options have been set, change the
385
					// 'dataoneConfigured' option to 'true'
386
					PropertyService.setProperty("configutil.dataoneConfigured",
387
							PropertyService.CONFIGURED);
388
					
389
					// Reload the main metacat configuration page
390
					processingSuccess.add("DataONE successfully configured");
391
					RequestUtil.clearRequestMessages(request);
392
					RequestUtil.setRequestSuccess(request, processingSuccess);
393
					RequestUtil.forwardRequest(request, response, 
394
							"/admin?configureType=configure&processForm=false", null);
395
				}
396
			} catch (MetacatUtilException mue) {
397
				throw new AdminException("D1Admin.configureDataONE - utility problem while processing dataone configuration: "
398
					 + mue.getMessage());
399
			} catch (GeneralPropertyException gpe) {
400
				throw new AdminException("D1Admin.configureDataONE - problem with properties while "
401
						+ "processing geoservices configuration page: " + gpe.getMessage());
402
			}
403
		}
404
	}
405
	
406
	private boolean isNodeRegistered(String nodeId) {
407
		// check if this is new or an update
408
        boolean exists = false;
409
        try {
410
	        NodeList nodes = D1Client.getCN().listNodes();
411
	        for (Node n: nodes.getNodeList()) {
412
	        	if (n.getIdentifier().getValue().equals(nodeId)) {
413
	        		exists = true;
414
	        		break;
415
	        	}
416
	        }
417
        } catch (BaseException e) {
418
            logMetacat.error("Could not check for node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
419
        } 
420
        return exists;
421
	}
422

    
423
	/**
424
	 * Register as a member node on the DataONE network.  The node description is
425
	 * retrieved from the getCapabilities() service, and so this should only be called
426
	 * after the properties have been properly set up in Metacat.
427
	 */
428
	private void registerDataONEMemberNode() throws BaseException, PropertyNotFoundException, GeneralPropertyException {
429
        
430
        logMetacat.debug("Get the Node description.");
431
        Node node = MNodeService.getInstance(null).getCapabilities();
432
        logMetacat.debug("Setting client certificate location.");
433
        String mnCertificatePath = PropertyService.getProperty("D1Client.certificate.file");
434
        CertificateManager.getInstance().setCertificateLocation(mnCertificatePath);
435
        CNode cn = D1Client.getCN();
436
        
437
        // check if this is new or an update
438
        boolean update = isNodeRegistered(node.getIdentifier().getValue());
439
        
440
        // Session is null, because the libclient code automatically sets up an
441
        // SSL session for us using the client certificate provided
442
        Session session = null;
443
        if (update) {
444
        	logMetacat.debug("Updating node with DataONE. " + cn.getNodeBaseServiceUrl());
445
            boolean result = cn.updateNodeCapabilities(session, node.getIdentifier(), node);
446
        } else {
447
            logMetacat.debug("Registering node with DataONE. " + cn.getNodeBaseServiceUrl());
448
            NodeReference mnodeRef = cn.register(session, node);            
449
			
450
			// save that we submitted registration
451
			PropertyService.setPropertyNoPersist("dataone.mn.registration.submitted", Boolean.TRUE.toString());
452
            
453
            // persist the properties
454
            PropertyService.persistProperties();
455
        }
456
        
457
	}
458

    
459
	/**
460
	 * Validate the most important configuration options submitted by the user.
461
	 * 
462
	 * @return a vector holding error message for any fields that fail
463
	 *         validation.
464
	 */
465
	protected Vector<String> validateOptions(HttpServletRequest request) {
466
		Vector<String> errorVector = new Vector<String>();
467

    
468
		// TODO MCD validate options.
469

    
470
		return errorVector;
471
	}
472
}
(4-4/12)