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

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

Debugged ATOM feed ingestion to deal with revised eXist atom architecture

  • 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                self._setupDataCentreDirs()
48               
49                #Change os directory to that with the harvested documents in it.
50                os.chdir(self._base_dir)
51               
52                               
53                # - to run on Windows under cygwin, use the following
54                #os.putenv('PATH', 'C:\\opt\\cygwin\\bin')
55               
56
57                self.getConfigDetails(dataCentre)
58                # override default settings with input keyword values, if set
59                if harvestDir:
60                        self._harvest_home = harvestDir
61                if dataFormat:
62                        self._datacentre_format = dataFormat
63
64               
65                # check harvest dir exists and that there are any records to harvest?
66                if self.indFileToIngest == "":
67                        if not os.path.exists(self._harvest_home):
68                                logging.error("Harvest directory for dataCentre %s (%s) could not be found - exiting" \
69                                                 %(dataCentre, self._harvest_home))
70                                return
71                        elif len(os.listdir(self._harvest_home)) == 0:
72                                logging.info("Nothing to harvest this time from %s" %dataCentre)
73                                return
74                       
75                        commandline = "find " + self._harvest_home + " -type f -print | xargs -i cp \{\} " + self.originals_dir
76                        logging.info("Executing : " + commandline)
77                        status = os.system(commandline)
78               
79                else:
80                        #must be looking for an individual file to upload
81                        if not os.path.exists(self.indFileToIngest):
82                                logging .warn("Specified file does not exist")
83                                return
84                       
85                        # Create/clear the 'in' directory pristine copy of the discovery records
86                        #fileUtils.setUpDir(originals_dir)
87                        commandline = "cp " + self.indFileToIngest + " " +  self.originals_dir
88                        logging.info("Executing : " + commandline)
89                        status = os.system(commandline)
90
91               
92                if status !=0:
93                    sys.exit("Failed at making pristine copy stage")
94               
95                self._setupXQueries()
96
97                # Process the resulting files and put the data into the postgres DB
98                # - firstly set up a db connection to use
99                self._getPostgresDBConnection()
100
101                numfilesproc, processingReport = self._convertAndIngestFiles(self.originals_dir, self.discovery_dir, dataCentre, True)
102               
103                outMessage = "OAI Document ingest processing complete:\n"
104                logging.info("oai_document_ingest processing complete:")
105                isSuccess = False
106                if self._no_problem_files == 0:
107                        logging.info("All files successfully processed - cleaning harvest directory")
108                        #FileUtilities.cleanDir(self._harvest_home) # TODO: uncomment this!
109                        isSuccess = True
110                else:
111                        logging.error("Problems experienced with %s files" %self._no_problem_files)
112                        logging.error("- harvnegest directory will not be cleared until these have been fixed and the script has been reran")
113               
114                logging.info(self.lineSeparator)
115                message = 'Number of files processed = %s\n' %numfilesproc
116                logging.info(message)
117                outMessage += message
118                message = "Number of files created = %s\n" %self._no_files_ingested
119                logging.info(message)
120                outMessage += message
121                message = "Number of files updated = %s\n" %self._no_files_changed
122                logging.info(message)
123                outMessage += message
124               
125                #Changed message to include more detail (SJD) but also now add any errors
126                if self._error_messages:
127                        outMessage += 'Errors: %s' %self._error_messages
128                        processingReport += 'Errors: %s' %self._error_messages
129
130
131               
132                print "Script finished running."
133                return isSuccess, processingReport
134
135        def setIndFileToIngest(self, indFileToIngest):
136                '''
137                Method to set individual file to ingest if "individualFile" is invoked
138                '''
139                self.indFileToIngest = indFileToIngest
140
141       
142        def usage(self):
143                '''
144                Display input params for the script
145                '''
146                print "Usage: python oai_document_ingester.py [OPTION] <datacentre>"
147                print " - where:\n   <datacentre> is the data centre to ingest data from; and options are:"
148                print " -v - verbose mode for output logging"
149                print " -d - debug mode for output logging"
150                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"
151
152                sys.exit(2)
153               
154       
155if __name__=="__main__":
156
157        print "================================="
158        print "RUNNING: oai_document_ingester.py"
159       
160       
161        ingester = oai_document_ingester()     
162        args = ingester._setupCmdLineOptions()
163        ingester.processDataCentre(args[0])
Note: See TracBrowser for help on using the repository browser.