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

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

Adjust messaging so FULL report is made available to info editor for email

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