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

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

Updated handling of directories - put in absolute production paths in badc user buildout

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