source: TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/oai_document_ingester.py @ 6186

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/oai_document_ingester.py@6186
Revision 6186, 6.6 KB checked in by sdonegan, 10 years ago (diff)

Added ability to take processing info from a config file (not in svn for obvious reasons!).

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2'''
3 Main script to do the document ingest from the OAI harvested files to the
4 discovery postgres DB.  NB, can be ran for all datacentres using the run_all_ingest.py script
5 or can specify an individual datacentre to run the ingester on.
6 As well as doing the ingest, a backup directory is created to store the created moles files.
7'''
8import os, sys, logging
9# annoyingly, an import (CSML file, I think) sets the logging config during imports - so set this
10# here to get there first - since you can only set the config once
11logging.basicConfig(level=logging.DEBUG,
12                    format='%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s')
13from time import strftime
14import ndg.common.src.lib.fileutilities as FileUtilities
15from abstractdocumentingester import AbstractDocumentIngester
16
17class oai_document_ingester(AbstractDocumentIngester):
18        '''
19        Class to handle the ingest of files from the OAI harvester to the discovery service postgres DB
20        - including running the various transforms and parsings to get all doc types and spatiotemporal
21        data in the correct form in the DB
22        @return outMessage: string summary of ingest outcome
23        '''
24       
25        indFileToIngest=""
26
27        def processDataCentre(self, dataCentre, harvestDir = None, dataFormat = None):
28                '''
29                indFileToIngest=None
30                Ingest documents from the specified data centre
31                @param dataCentre: data centre to ingest docs from
32                @keyword harvestDir: directory to get docs from - NB, this will override that
33                specified in the associated config file.  Typically this is used when a manual
34                harvest has retrieved docs to a local dir (see OAIInfoEditor.lib.harvester).
35                @param dataFormat: format of data to ingest.  Overrides config file settings.
36                @return isSuccess, outMessage: isSuccess = True if ingest completes ok
37                outMessage = summary of ingest process
38                '''
39                self._no_files_ingested = 0
40                self._no_files_changed = 0
41                self._no_files_deleted = 0
42                self._no_problem_files = 0
43               
44                self._error_messages = ''
45                self.dataCentre = dataCentre
46                #self._base_dir = os.getcwd() + "/" # this is the base dir that the script is ran from
47
48                #extract relevant directories etc from processing config gile
49                self.processingDict = self.getProcessingConfig('/home/badc/buildouts/oai_document_ingester/ingestAutomation-upgrade/OAIBatch/oai_document_ingester.config')
50                #self._code_dir = "/home/badc/buildouts/oai_document_ingester/ingestAutomation-upgrade/OAIBatch/" # this is the base dir that the script is ran from
51                #self._base_dir = "/home/badc/discovery_docs/ingestDocs/"
52               
53                self._code_dir = self.processingDict['code_directory']
54                self._base_dir = self.processingDict['base_directory']
55               
56                self._setupDataCentreDirs()
57               
58                #Change os directory to that with the harvested documents in it.
59                os.chdir(self._base_dir)
60                                               
61                # - to run on Windows under cygwin, use the following
62                #os.putenv('PATH', 'C:\\opt\\cygwin\\bin')
63               
64                self.getConfigDetails(dataCentre)
65                # override default settings with input keyword values, if set
66                if harvestDir:
67                        self._harvest_home = harvestDir
68                if dataFormat:
69                        self._datacentre_format = dataFormat
70
71               
72                # check harvest dir exists and that there are any records to harvest?
73                if self.indFileToIngest == "":
74                        if not os.path.exists(self._harvest_home):
75                                logging.error("Harvest directory for dataCentre %s (%s) could not be found - exiting" \
76                                                 %(dataCentre, self._harvest_home))
77                                return
78                        elif len(os.listdir(self._harvest_home)) == 0:
79                                logging.info("Nothing to harvest this time from %s" %dataCentre)
80                                return
81                       
82                        commandline = "find " + self._harvest_home + " -type f -print | xargs -i cp \{\} " + self.originals_dir
83                        logging.info("Executing : " + commandline)
84                        status = os.system(commandline)
85               
86                else:
87                        #must be looking for an individual file to upload
88                        if not os.path.exists(self.indFileToIngest):
89                                logging .warn("Specified file does not exist")
90                                return
91                       
92                        # Create/clear the 'in' directory pristine copy of the discovery records
93                        #fileUtils.setUpDir(originals_dir)
94                        commandline = "cp " + self.indFileToIngest + " " +  self.originals_dir
95                        logging.info("Executing : " + commandline)
96                        status = os.system(commandline)
97
98               
99                if status !=0:
100                    sys.exit("Failed at making pristine copy stage")
101               
102                self._setupXQueries()
103
104                # Process the resulting files and put the data into the postgres DB
105                # - firstly set up a db connection to use
106                self._getPostgresDBConnection()
107
108                numfilesproc, processingReport = self._convertAndIngestFiles(self.originals_dir, self.discovery_dir, dataCentre, True)
109               
110                outMessage = "OAI Document ingest processing complete:\n"
111                logging.info("oai_document_ingest processing complete:")
112                isSuccess = False
113                if self._no_problem_files == 0:
114                        logging.info("All files successfully processed - cleaning harvest directory")
115                        #FileUtilities.cleanDir(self._harvest_home) # TODO: uncomment this!
116                        isSuccess = True
117                else:
118                        logging.error("Problems experienced with %s files" %self._no_problem_files)
119                        logging.error("- harvnegest directory will not be cleared until these have been fixed and the script has been reran")
120               
121                logging.info(self.lineSeparator)
122                message = 'Number of files processed = %s\n' %numfilesproc
123                logging.info(message)
124                outMessage += message
125                message = "Number of files created = %s\n" %self._no_files_ingested
126                logging.info(message)
127                outMessage += message
128                message = "Number of files updated = %s\n" %self._no_files_changed
129                logging.info(message)
130                outMessage += message
131               
132                #Changed message to include more detail (SJD) but also now add any errors
133                if self._error_messages:
134                        outMessage += 'Errors: %s' %self._error_messages
135                        processingReport += 'Errors: %s' %self._error_messages
136
137
138               
139                print "Script finished running."
140                return isSuccess, processingReport
141
142        def setIndFileToIngest(self, indFileToIngest):
143                '''
144                Method to set individual file to ingest if "individualFile" is invoked
145                '''
146                self.indFileToIngest = indFileToIngest
147
148       
149        def usage(self):
150                '''
151                Display input params for the script
152                '''
153                print "Usage: python oai_document_ingester.py [OPTION] <datacentre>"
154                print " - where:\n   <datacentre> is the data centre to ingest data from; and options are:"
155                print " -v - verbose mode for output logging"
156                print " -d - debug mode for output logging"
157                print " individualFile= - specify individual file to upload rather than batch processing as defined in properties file.  \n      (NOTE: script still uses properties file for other parameters)\n"
158
159                sys.exit(2)
160               
161       
162if __name__=="__main__":
163
164        print "================================="
165        print "RUNNING: oai_document_ingester.py"
166       
167       
168        ingester = oai_document_ingester()     
169        args = ingester._setupCmdLineOptions()
170        ingester.processDataCentre(args[0])
Note: See TracBrowser for help on using the repository browser.