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: leinfelder $'
8
 *     '$Date: 2014-07-23 16:19:48 -0700 (Wed, 23 Jul 2014) $'
9
 * '$Revision: 8810 $'
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.v2.CNode;
35
import org.dataone.client.v2.itk.D1Client;
36
import org.dataone.client.auth.CertificateManager;
37
import org.dataone.configuration.Settings;
38
import org.dataone.service.exceptions.BaseException;
39
import org.dataone.service.types.v2.Node;
40
import org.dataone.service.types.v2.NodeList;
41
import org.dataone.service.types.v1.NodeReference;
42
import org.dataone.service.types.v1.Session;
43

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

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

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

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

    
67
	}
68

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

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

    
94
		String processForm = request.getParameter("processForm");
95
		String bypass = request.getParameter("bypass");
96
		String formErrors = (String) request.getAttribute("formErrors");
97

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

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

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

    
162

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

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

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

    
273
				boolean synchronize = false;
274
				if (nodeSynchronize != null) {
275
					synchronize = Boolean.parseBoolean(nodeSynchronize);
276
				}
277
				boolean replicate = false;
278
				if (nodeReplicate != null) {
279
					replicate = Boolean.parseBoolean(nodeReplicate);
280
				}
281
				
282
				// enable services as a whole?
283
                boolean servicesEnabled = false;
284
                String servicesEnabledString = (String) request.getParameter("dataone.mn.services.enabled");
285
                if (servicesEnabledString != null) {
286
                	servicesEnabled = Boolean.parseBoolean(servicesEnabledString);
287
                }
288
				
289
				// process the values, checking for nulls etc..
290
				if (nodeName == null ) {
291
					validationErrors.add("nodeName cannot be null");
292
				} else {
293
					
294
					PropertyService.setProperty("D1Client.CN_URL", cnURL);
295
					Settings.getConfiguration().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(PropertyService.getProperty("D1Client.CN_URL"));
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)