source: gs2-extensions/parallel-building/trunk/src/perllib/IncrementalBuildUtils.pm@ 24626

Last change on this file since 24626 was 24626, checked in by jmt12, 13 years ago

An (almost) complete copy of the perllib directory from a (circa SEP2011) head checkout from Greenstone 2 trunk - in order to try and make merging in this extension a little easier later on (as there have been some major changes to buildcol.pl commited in the main trunk but not in the x64 branch)

File size: 21.7 KB
Line 
1###########################################################################
2#
3# IncrementalBuildUtils.pm -- API to assist incremental building
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 2006 DL Consulting Ltd and New Zealand Digital Library Project
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., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25# /** Initial versions of these functions by John Thompson, revisions by
26# * and turning it into a package by John Rowe. Used heavily by
27# * basebuilder::remove_document() and getdocument.pl
28# *
29# * @version 1.0 Initial version by John Thompson
30# * @version 1.1 Addition of get_document and change of get_document_as_xml
31# * by John Rowe
32# * @version 2.0 Package version including seperation from calling code and
33# * modularisation by John Rowe
34# *
35# * @author John Thompson, DL Consulting Ltd.
36# * @author John Rowe, DL Consulting Ltd.
37# */
38###########################################################################
39package IncrementalBuildUtils;
40
41BEGIN {
42 die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
43 die "GSDLOS not set\n" unless defined $ENV{'GSDLOS'};
44
45 my $current_library_paths = join(":",@INC);
46 my $gsdl_perllib_path = $ENV{'GSDLHOME'} . '/perllib';
47 if ($current_library_paths !~ /$gsdl_perllib_path/)
48 {
49 print "IncrementalBuildUtils setting up environment!\n";
50 unshift (@INC, $gsdl_perllib_path); # [jmt12]
51 unshift (@INC, "$ENV{'GSDLHOME'}/perllib/cpan"); # [jmt12]
52 unshift (@INC, "$ENV{'GSDLHOME'}/perllib/plugins"); # [jmt12]
53 unshift (@INC, "$ENV{'GSDLHOME'}/perllib/classify"); # [jmt12]
54 }
55}
56
57use doc;
58use cfgread;
59use colcfg;
60use strict;
61use util;
62
63use ClassifyTreeModel;
64use IncrementalDocument;
65
66# Change debugging to 1 if you want verbose debugging output
67my $debug = 1;
68
69# Ensure the collection specific binaries are on the search path
70my $path_separator = ":";
71if($ENV{'GSDLOS'} =~ /win/) {
72 $path_separator = ";";
73}
74my $os_binary_path = &util::filename_cat($ENV{'GSDLHOME'}, "bin", $ENV{'GSDLOS'});
75if ($ENV{'PATH'} !~ /$os_binary_path/)
76{
77 $ENV{'PATH'} = $os_binary_path . $path_separator . $ENV{'PATH'};
78}
79my $script_path = &util::filename_cat($ENV{'GSDLHOME'}, "bin", "script");
80if ($ENV{'PATH'} !~ /$script_path/)
81{
82 $ENV{'PATH'} = $script_path . $path_separator . $ENV{'PATH'};
83}
84
85# /**
86# */
87sub addDocument()
88 {
89 my ($collection, $infodbtype, $doc_obj, $section, $updateindex) = @_;
90
91 $updateindex = 0 unless defined($updateindex);
92
93 print STDERR "IncrementalBuildUtils::addDocument('$collection',$infodbtype,$doc_obj,'$section')\n" unless !$debug;
94 # Gonna need to know in several places whether this is the top section
95 # of the document or not
96 my $is_top = ($section eq $doc_obj->get_top_section());
97
98 # Retrieve all of the metadata from this document object only - not any
99 # child documents
100 my $metadata = $doc_obj->get_all_metadata($section);
101 # Check and add the docnum first
102 my $found_docnum = 0;
103 foreach my $pair (@$metadata)
104 {
105 my ($key, $value) = (@$pair);
106 if ($key eq "docnum")
107 {
108 &setDocumentMetadata($collection, $infodbtype, $doc_obj->get_OID() . "$section", $key, "", $value, $updateindex);
109 $found_docnum = 1;
110 }
111 }
112
113 if (!$found_docnum)
114 {
115 die("Fatal Error! Tried to add document without providing docnum");
116 }
117
118 # Add it piece by piece - this depends on the loading of a blank document
119 # working the way it should.
120 foreach my $pair (@$metadata)
121 {
122 my ($key, $value) = (@$pair);
123 if ($key ne "Identifier" && $key ne "docnum" && $key !~ /^gsdl/ && defined $value && $value ne "")
124 {
125 # escape problematic stuff
126 $value =~ s/\\/\\\\/g;
127 $value =~ s/\n/\\n/g;
128 $value =~ s/\r/\\r/g;
129 if ($value =~ /-{70,}/)
130 {
131 # if value contains 70 or more hyphens in a row we need
132 # to escape them to prevent txt2db from treating them
133 # as a separator
134 $value =~ s/-/&\#045;/gi;
135 }
136 # Go ahead and set the metadata
137 &setDocumentMetadata($collection, $infodbtype, $doc_obj->get_OID() . "$section", $key, "", $value, $updateindex);
138 }
139 }
140 # We now have to load the browselist node too. We create a ClassifyTreeNode
141 # based on a dummy model.
142 # Note: only if section is the top section
143 if ($is_top)
144 {
145 my $dummy_model = new ClassifyTreeModel($collection, $infodbtype, "");
146 my $browselist_node = new ClassifyTreeNode($dummy_model, "browselist");
147 # Add the document
148 $browselist_node->addDocument($doc_obj->get_OID());
149 }
150 # We now recursively move through the document objects child sections,
151 # adding them too. As we do this we build up a contains list for this
152 # document.
153 my $section_ptr = $doc_obj->_lookup_section($section);
154 my @contains = ();
155 if (defined $section_ptr)
156 {
157 foreach my $subsection (@{$section_ptr->{'subsection_order'}}) {
158 &addDocument($collection, $infodbtype, $doc_obj, "$section.$subsection");
159 push(@contains, "\".$subsection");
160 }
161 }
162 # Done - clean up
163 }
164# /** addDocument() **/
165
166# /** Sets the metadata attached to a given document. This will update, at most,
167# * three different locations:
168# * 1. The Lucene index must be updated. This will involve removing any
169# * existing value and, if required, adding a new value in its place.
170# * 2. The info database must be updated. Again any existing value will be
171# * removed and, if required, a new value added.
172# * 3. Finally a check against the collect.cfg will be done to determine if
173# * the changed metadata would have an effect on a classifier and, if so
174# * the classifier tree will be updated to remove, add or replace any
175# * tree nodes or node 'contains lists' as necessary.
176# *
177# * Pseudo Code:
178# * ------------
179# * To add metadata to the document NT1
180# * A. Establish connection to Lucene
181# * B. Create a IncrementalDocument object for 'NT1' loading the information
182# * from the info database
183# * C. Check to see if this metadata is used to build a classifier(s) and if
184# * so create the appropriate ClassifyTreeModel(s)
185# * D. If removing or replacing metadata:
186# * i/ Call ??? to remove key-value from Lucene index
187# * ii/ Use removeMetadata() to clear value in IncrementalDocument
188# * iii/ Call removeDocument() in ClassifyTreeModel(s) as necessary
189# * E. If adding or replacing metadata:
190# * i/ Call ??? to add key-value from Lucene index
191# * ii/ Use addMetadata() to add value in IncrementalDocument
192# * iii/ Call addDocument() in ClassifyTreeModel(s) as necessary
193# * F. Complete Lucene transaction
194# * G. Save IncrementalDocument to info database
195# * Note: ClassifyTreeModel automatically updates the info database as necessary.
196# *
197# * @param $collection The name of the collection to update as a string
198# * @param $oid The unique identifier of a Greenstone document as a
199# * string
200# * @param $key The key of the metadata being added as a string
201# * @param $old_value The value of the metadata being removed/replaced
202# * or an empty string if adding metadata
203# * @param $new_value The value of the metadata being added/replacing
204# * or an empty string if removing metadata
205# * @param $updateindex 1 to get the index updated. This is used to prevent
206# * the indexes being changed when doing an incremental
207# * addition of a new document.
208# *
209# * @author John Thompson, DL Consulting Ltd.
210# */
211sub setDocumentMetadata()
212 {
213 my ($collection, $infodbtype, $oid, $key, $old_value, $new_value, $updateindex) = @_;
214 print STDERR "IncrementalBuildUtils::setDocumentMetadata('$collection',$infodbtype,'$oid','$key','$old_value','$new_value',$updateindex)\n" unless !$debug;
215 # A. Establish connection to Lucene
216 # This isn't required at the moment, but might be later if we implement
217 # Lucene daemon.
218 # B. Create a IncrementalDocument object for 'NT1' loading the information
219 # from the info database
220 print STDERR "* creating incremental document for $oid\n" unless !$debug;
221 my $doc_obj = new IncrementalDocument($collection, $infodbtype, $oid);
222 $doc_obj->loadDocument();
223 # C. Check to see if this metadata is used to build a classifier(s) and if
224 # so create the appropriate ClassifyTreeModel(s)
225 print STDERR "* load collection configuration\n" unless !$debug;
226 my $config_obj = &getConfigObj($collection);
227 my $clidx = 1;
228 my @classifier_tree_models = ();
229 foreach my $classifier (@{$config_obj->{'classify'}})
230 {
231 my $index = 0;
232 my $option_count = scalar(@{$classifier});
233 for ($index = 0; $index < $option_count; $index++)
234 {
235 if ($index + 1 < $option_count && @{$classifier}[$index] eq "-metadata" && @{$classifier}[$index + 1] eq $key)
236 {
237 # Create a tree model for this classifier
238 print STDERR "* creating a tree model for classifier: CL$clidx\n" unless !$debug;
239 my $tree_model_obj = new ClassifyTreeModel($collection, $infodbtype, "CL" . $clidx);
240 # And store it for later
241 push(@classifier_tree_models, $tree_model_obj);
242 }
243 }
244 $clidx++;
245 }
246 # D. If removing or replacing metadata:
247 if (defined($old_value) && $old_value =~ /[\w\d]+/)
248 {
249 print STDERR "* removing '$key'='$old_value' from info database for document $oid\n" unless !$debug;
250 # i/ Call ??? to remove key-value from Lucene index
251 # Moved elsewhere
252 # ii/ Use removeMetadata() to clear value in IncrementalDocument
253 $doc_obj->removeMetadata($key, $old_value);
254 # iii/ Call removeDocument() in ClassifyTreeModel(s) as necessary
255 foreach my $classifier_tree_model (@classifier_tree_models)
256 {
257 print STDERR "* removing '$old_value' from classifier tree\n" unless !$debug;
258 $classifier_tree_model->removeDocument($old_value, $oid, 1);
259 }
260 }
261 # E. If adding or replacing metadata:
262 if (defined($new_value) && $new_value =~ /[\w\d]+/)
263 {
264 print STDERR "* adding '$key'='$new_value' to info database for document $oid\n" unless !$debug;
265 # i/ Call ??? to add key-value from Lucene index
266 # Moved elsewhere
267 # ii/ Use addMetadata() to add value in IncrementalDocument
268 $doc_obj->addMetadata($key, $new_value);
269 # iii/ Call addDocument() in ClassifyTreeModel(s) as necessary
270 foreach my $classifier_tree_model (@classifier_tree_models)
271 {
272 print STDERR "* adding '$new_value' to classifier tree\n" unless !$debug;
273 $classifier_tree_model->addDocument($new_value, $oid);
274 }
275 }
276 # F. Complete Lucene transaction
277 if(defined($updateindex) && $updateindex)
278 {
279 print STDERR "* updating Lucene indexes\n" unless !$debug;
280 &callGS2LuceneEditor($collection, $doc_obj->getDocNum, $key, $old_value, $new_value);
281 }
282 # G. Save IncrementalDocument to info database
283 $doc_obj->saveDocument();
284 $doc_obj = 0;
285 }
286# /** setDocumentMetadata() **/
287
288# /**
289# *
290# */
291sub callGS2LuceneDelete()
292 {
293 my ($collection, $docnum) = @_;
294
295 # Some path information that is the same for all indexes
296 my $classpath = &util::filename_cat($ENV{'GSDLHOME'},"bin","java","LuceneWrap.jar");
297 my $java_lucene = "org.nzdl.gsdl.LuceneWrap.GS2LuceneDelete";
298 my $indexpath = &util::filename_cat($ENV{'GSDLHOME'},"collect",$collection,"index");
299 # Determine what indexes need to be changed by opening the collections
300 # index path and searching for directories named *idx
301 # If the directory doesn't exist, then there is no built index, and nothing
302 # for us to do.
303 if(opendir(INDEXDIR, $indexpath))
304 {
305 my @index_files = readdir(INDEXDIR);
306 closedir(INDEXDIR);
307 # For each index that matches or pattern, we call the java application
308 # to change the index (as necessary - not every index will include the
309 # document we have been asked to modify)
310 foreach my $actual_index_dir (@index_files)
311 {
312 next unless $actual_index_dir =~ /idx$/;
313 # Determine the path to the index to modify
314 my $full_index_dir = &util::filename_cat($indexpath, $actual_index_dir);
315 # Call java to remove the document
316 my $cmd = "java -classpath \"$classpath\" $java_lucene --index $full_index_dir --nodeid $docnum";
317 print STDERR "CMD: " . $cmd . "\n" unless !$debug;
318 # Run command
319 my $result = `$cmd 2>&1`;
320 print STDERR $result unless !$debug;
321 }
322 }
323 # Done
324 }
325# /** callGS2LuceneDelete() **/
326
327# /**
328# */
329sub callGS2LuceneEditor()
330 {
331 my ($collection, $docnum, $key, $old_value, $new_value) = @_;
332
333 # Some path information that is the same for all indexes
334 my $classpath = &util::filename_cat($ENV{'GSDLHOME'},"collect",$collection,"java","classes");
335 my $jarpath = &util::filename_cat($ENV{'GSDLHOME'},"bin","java","LuceneWrap.jar");
336 my $java_lucene = "org.nzdl.gsdl.LuceneWrap.GS2LuceneEditor";
337 my $indexpath = &util::filename_cat($ENV{'GSDLHOME'},"collect",$collection,"index");
338 # And some commands that don't change
339 my $java_args = "";
340 # Append the node id
341 $java_args .= "--nodeid $docnum ";
342 # We have to convert the given metadata key into its two letter field code.
343 # We do this by looking in the build.cfg file.
344 my $field = &getFieldFromBuildCFG($indexpath, $key);
345 # The metadata field to change
346 $java_args .= "--field $field ";
347 # And the old and new values as necessary
348 if(defined($old_value) && $old_value =~ /[\w\d]+/)
349 {
350 $java_args .= "--oldvalue \"$old_value\" ";
351 }
352 if(defined($new_value) && $new_value =~ /[\w\d]+/)
353 {
354 $java_args .= "--newvalue \"$new_value\" ";
355 }
356 # Determine what indexes need to be changed by opening the collections
357 # index path and searching for directories named *idx
358 # If the directory doesn't exist, then there is no built index, and nothing
359 # for us to do.
360 # We also check if the field is something other than "". It is entirely
361 # possible that we have been asked to update a metadata field that isn't
362 # part of any index, so this is where we break out of editing the index if
363 # we have
364 if($field =~ /^\w\w$/ && opendir(INDEXDIR, $indexpath))
365 {
366 my @index_files = readdir(INDEXDIR);
367 closedir(INDEXDIR);
368 # For each index that matches or pattern, we call the java application
369 # to change the index (as necessary - not every index will include the
370 # document we have been asked to modify)
371 foreach my $actual_index_dir (@index_files)
372 {
373 next unless $actual_index_dir =~ /idx$/;
374 # Determine the path to the index to modify
375 my $full_index_dir = &util::filename_cat($indexpath, $actual_index_dir);
376 # And prepend to the command java arguments
377 my $cur_java_args = "--index $full_index_dir " . $java_args;
378 print STDERR "CMD: java -classpath \"$classpath:$jarpath\" $java_lucene $cur_java_args 2>&1\n" unless !$debug;
379 # Run command
380 my $result = `java -classpath \"$classpath:$jarpath\" $java_lucene $cur_java_args 2>&1`;
381 print STDERR $result unless !$debug;
382 }
383 }
384 # Done
385 }
386# /** callGS2LuceneEditor() **/
387
388## Remove a document from the info database and Index.
389#
390# @param collection The collection to alter
391# @param oid The unique identifier of the document to be removed
392##
393sub deleteDocument()
394 {
395 my ($collection, $infodbtype, $oid) = @_;
396 # Load the incremental document to go with this oid, as we need some
397 # information from it.
398 my $doc_obj = new IncrementalDocument($collection, $infodbtype, $oid);
399 $doc_obj->loadDocument();
400 # Check if this object even exists by retrieving the docnum.
401 my $doc_num = $doc_obj->getDocNum();
402 print STDERR "Removing document docnum: $doc_num\n" unless !$debug;
403 if ($doc_num > -1)
404 {
405 # Now write a blank string to this oid in the info database
406 my $index_text_directory_path = &util::filename_cat($ENV{'GSDLHOME'}, "collect", $collection, "index", "text");
407 my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collection, $index_text_directory_path);
408 my $infodb_file_handle = &dbutil::open_infodb_write_handle($infodbtype, $infodb_file_path, "append");
409 &dbutil::write_infodb_entry($infodbtype, $infodb_file_handle, $oid, &dbutil::convert_infodb_string_to_hash(""));
410 # Remove reverse lookup
411 &dbutil::write_infodb_entry($infodbtype, $infodb_file_handle, $doc_num, &dbutil::convert_infodb_string_to_hash(""));
412 &dbutil::close_infodb_write_handle($infodbtype, $infodb_file_handle);
413
414 # And remove from the database
415 &callGS2LuceneDelete($collection, $doc_num);
416
417 # Regenerate the classifier trees.
418 print STDERR "* load collection configuration\n";# unless !$debug;
419 my $config_obj = &getConfigObj($collection);
420 my $clidx = 1;
421 my %classifier_tree_models = ();
422 foreach my $classifier (@{$config_obj->{'classify'}})
423 {
424 my $index = 0;
425 my $option_count = scalar(@{$classifier});
426 for ($index = 0; $index < $option_count; $index++)
427 {
428 if ($index + 1 < $option_count && @{$classifier}[$index] eq "-metadata")
429 {
430 my $key = @{$classifier}[$index + 1];
431 # Create a tree model for this classifier
432 print STDERR "* creating a tree model for classifier: CL" . $clidx . " [" . $key . "]\n";# unless !$debug;
433 my $tree_model_obj = new ClassifyTreeModel($collection, $infodbtype, "CL" . $clidx);
434 # And store it against its key for later
435 $classifier_tree_models{$key} = $tree_model_obj;
436 }
437 }
438 $clidx++;
439 }
440
441 # For each piece of metadata assigned to this document, if there is a
442 # matching classifier tree, remove the path from the tree.
443 print STDERR "* searching for classifier paths to be removed\n";
444
445 my $metadata = $doc_obj->getAllMetadata();
446 foreach my $pair (@$metadata)
447 {
448 my ($key, $value) = @$pair;
449 print STDERR "* testing " . $key . "=>" . $value . "\n";
450 if (defined($classifier_tree_models{$key}))
451 {
452 my $model = $classifier_tree_models{$key};
453 print STDERR "* removing '" . $value . "' from classifier " . $model->getRootNode()->getCLID() . "\n";
454 $model->removeDocument($value, $oid, 1);
455 }
456 }
457
458 # We also have to remove from browselist - the reverse process of
459 # adding to browselist shown above.
460 my $dummy_model = new ClassifyTreeModel($collection, $infodbtype, "");
461 my $browselist_node = new ClassifyTreeNode($dummy_model, "browselist");
462 # Add the document
463 $browselist_node->removeDocument($oid);
464 # Clean up
465 }
466 # else, no document, no need to delete.
467 }
468## deleteDocument() ##
469
470# /**
471# */
472sub getFieldFromBuildCFG()
473 {
474 my ($indexpath, $key) = @_;
475 my $field = "";
476 my $build_cfg = &util::filename_cat($indexpath, "build.cfg");
477 # If there isn't a build.cfg then the index hasn't been built and there is
478 # nothing to do
479 if(open(BUILDCFG, $build_cfg))
480 {
481 # For each line of the build configuration
482 my $line;
483 while($line = <BUILDCFG>)
484 {
485 # Only interested in the indexfieldmap line
486 if($line =~ /^indexfieldmap\s+/)
487 {
488 # Extract the field information by looking up the key pair
489 if($line =~ /\s$key->(\w\w)/)
490 {
491 $field = $1;
492 }
493 }
494 }
495 # Done with file
496 close(BUILDCFG);
497 }
498 # Return whatever we found
499 return $field;
500 }
501# /** getFieldFromBuildCFG() **/
502
503
504
505
506
507# /** Retrieve an object (associative array) containing information about the
508# * collection configuration.
509# * @param $collection The shortname of the collection as a string
510# * @return An associative array containing information from the collect.cfg
511# * @author John Thompson, DL Consulting Ltd.
512# */
513sub getConfigObj()
514 {
515 my ($collection) = @_;
516
517 #rint STDERR "getConfigObj()\n" unless !$debug;
518
519 my $colcfgname = &util::filename_cat($ENV{'GSDLHOME'}, "collect", $collection, "etc", "collect.cfg");
520 if (!-e $colcfgname)
521 {
522 die "IncrementalBuildUtils - couldn't find collect.cfg for collection $collection\n";
523 }
524 return &colcfg::read_collect_cfg ($colcfgname);
525 }
526# /** getConfigObj() **/
527
5281;
Note: See TracBrowser for help on using the repository browser.