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

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


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