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

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

corrected bug in indentation...

  • 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        def processDataCentre(self, dataCentre, harvestDir = None, dataFormat = None):
26                '''
27                Ingest documents from the specified data centre
28                @param dataCentre: data centre to ingest docs from
29                @keyword harvestDir: directory to get docs from - NB, this will override that
30                specified in the associated config file.  Typically this is used when a manual
31                harvest has retrieved docs to a local dir (see OAIInfoEditor.lib.harvester).
32                @param dataFormat: format of data to ingest.  Overrides config file settings.
33                @return isSuccess, outMessage: isSuccess = True if ingest completes ok
34                outMessage = summary of ingest process
35                '''
36                self._no_files_ingested = 0
37                self._no_problem_files = 0
38                self._error_messages = ''
39                self.dataCentre = dataCentre
40                self._base_dir = os.getcwd() + "/" # this is the base dir that the script is ran from
41                self._setupDataCentreDirs()
42               
43                #Change os directory to that with the harvested documents in it.
44                os.chdir(self._base_dir)                # - to run on Windows under cygwin, use the following
45                #os.putenv('PATH', 'C:\\opt\\cygwin\\bin')
46               
47                self.getConfigDetails(dataCentre)
48                # override default settings with input keyword values, if set
49                if harvestDir:
50                        self._harvest_home = harvestDir
51                if dataFormat:
52                        self._datacentre_format = dataFormat
53               
54                # check harvest dir exists and that there are any records to harvest?
55                if not os.path.exists(self._harvest_home):
56                        logging.error("Harvest directory for dataCentre %s (%s) could not be found - exiting" \
57                                                 %(dataCentre, self._harvest_home))
58                        return
59                elif len(os.listdir(self._harvest_home)) == 0:
60                        logging.info("Nothing to harvest this time from %s" %dataCentre)
61                        return
62
63                commandline = "find " + self._harvest_home + " -type f -print | xargs -i cp \{\} " + self.originals_dir
64                logging.info("Executing : " + commandline)
65                status = os.system(commandline)
66
67                if status !=0:
68                    sys.exit("Failed at making pristine copy stage")
69               
70                self._setupXQueries()
71       
72                # Process the resulting files and put the data into the postgres DB
73                # - firstly set up a db connection to use
74                self._getPostgresDBConnection()
75
76                numfilesproc = self._convertAndIngestFiles(self.originals_dir, self.discovery_dir, dataCentre)
77               
78                outMessage = "OAI Document ingest processing complete:\n"
79                logging.info("oai_document_ingest processing complete:")
80                isSuccess = False
81                if self._no_problem_files == 0:
82                        logging.info("All files successfully processed - cleaning harvest directory")
83                        FileUtilities.cleanDir(self._harvest_home)
84                        isSuccess = True
85                else:
86                        logging.error("Problems experienced with %s files" %self._no_problem_files)
87                        logging.error("- harvest directory will not be cleared until these have been fixed and the script has been reran")
88               
89                logging.info(self.lineSeparator)
90                message = 'Number of files processed = %s\n' %numfilesproc
91                logging.info(message)
92                outMessage += message
93                message = "Number of files ingested = %s\n" %self._no_files_ingested
94                logging.info(message)
95                outMessage += message
96                if self._error_messages:
97                        outMessage += 'Errors: %s' %self._error_messages
98                logging.info(self.lineSeparator)
99                print "Script finished running."
100                return isSuccess, outMessage
101
102       
103        def usage(self):
104                '''
105                Display input params for the script
106                '''
107                print "Usage: python oai_document_ingester.py [OPTION] <datacentre>"
108                print " - where:\n   <datacentre> is the data centre to ingest data from; and options are:"
109                print " -v - verbose mode for output logging"
110                print " -d - debug mode for output logging"
111        #print " -i - 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"
112       
113        sys.exit(2)
114               
115       
116if __name__=="__main__":
117    print "sksh"
118    print "================================="
119    print "RUNNING: oai_document_ingester.py"
120    #ingester = oai_document_ingester()
121    #args = ingester._setupCmdLineOptions()
122    #ingester.processDataCentre(args[0])
Note: See TracBrowser for help on using the repository browser.