IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Jan 11, 2012, 11:19:21 PM (15 years ago)
Author:
mhuber
Message:

merged latest r33093 trunk changes to meh_branches/ppsub_test

Location:
branches/meh_branches/ppsub_test
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/meh_branches/ppsub_test

  • branches/meh_branches/ppsub_test/ippToPsps/jython/ipptopspsdb.py

    r32122 r33098  
    2020        super(IppToPspsDb, self).__init__(logger, doc, "ipptopspsdatabase")
    2121
    22     '''
    23     Creates a new batch
    24     '''
    25     def createNewBatch(self, batchType, stageID, survey, dvoDb, datastoreProduct):
    26 
    27         sql = "INSERT INTO batch ( \
    28                batch_type, \
    29                stage_id, \
    30                survey, \
    31                dvo_db, \
    32                datastore_product \
    33                ) VALUES ( \
    34                '" + batchType + "', \
    35                " + str(stageID) + ", \
    36                '" + survey + "', \
    37                '" + dvoDb + "', \
    38                '" + datastoreProduct + "' \
    39                )"
    40 
    41         self.execute(sql)
    42 
    43         sql = "SELECT MAX(batch_id) FROM batch"
    44 
    45         batchID = -1;
    46 
    47         try:
    48             rs = self.executeQuery(sql)
    49             rs.first()
    50             batchID = rs.getInt(1)
    51         except:
    52             self.logger.exception("Unable to get batch ID")
    53 
    54         self.logger.debug("Created new batch in ippToPsps database with batchID = %d" % batchID)
    55 
    56         return batchID;
    57 
    58     '''
    59     Returns a list of processed batch IDs that are merged but not yet deleted
    60     '''
    61     def getMergedButNotDeletedBatchIDs(self, epoch, dvoGpc1Label):
     22        self.MAX_FAILS = 5
     23
     24    '''
     25    Returns a list of merged batch IDs that are merged but not yet deleted
     26    '''
     27    def getMergedButNotDeletedBatchIDs(self, batchType, epoch, dvoGpc1Label, column):
    6228
    6329        sql = "SELECT DISTINCT batch_id \
    6430               FROM batch \
    6531               WHERE timestamp > '" + epoch + "' \
    66                AND dvo_db = '" + dvoGpc1Label + "' \
    67                AND merged \
    68                AND !deleted"
     32               AND batch_type = '" + batchType + "' \
     33               AND dvo_db = '" + dvoGpc1Label + "' \
     34               AND merged = 1 \
     35               AND " + column + " = 0"
    6936
    7037        ids = []
     
    8350
    8451    '''
    85     Returns a list of processed batch IDs that are not yet merged for this epoch and dvo label
    86     '''
    87     def getProcessedButUnmergedBatchIDs(self, epoch, dvoGpc1Label):
     52    Returns a list of processed batch IDs that have been loaded to the ODM but not yet deleted
     53    '''
     54    def getLoadedToODMButNotDeletedBatchIDs(self, batchType, epoch, dvoGpc1Label, column):
    8855
    8956        sql = "SELECT DISTINCT batch_id \
    9057               FROM batch \
    9158               WHERE timestamp > '" + epoch + "' \
    92                AND dvo_db = '" + dvoGpc1Label + "' \
    93                AND loaded_to_datastore \
    94                AND !merged"
    95 
    96         ids = []
    97         try:
    98             rs = self.executeQuery(sql)
    99             while (rs.next()):
    100                 ids.append(rs.getInt(1))
    101         except:
    102             self.logger.exception("Can't query for processed batch ids in ipptopsps Db")
    103 
    104         rs.close()
    105 
    106         self.logger.debug("Found %d processed and un-merged items" % len(ids))
    107 
    108         return ids
    109 
    110     '''
    111     Returns a list of IDs for this batch type, epoch and dvo label (i.e. either
    112             cam_ids or stack_ids) for which the spefified column is true (=1)
    113     '''
    114     def getStageIDs(self, batchType, epoch, dvoGpc1Label, column):
    115 
    116         sql = "SELECT DISTINCT stage_id \
     59               AND batch_type = '" + batchType + "' \
     60               AND dvo_db = '" + dvoGpc1Label + "' \
     61               AND (loaded_to_ODM = -1 OR merge_worthy = 1) \
     62               AND " + column + " = 0"
     63
     64        ids = []
     65        try:
     66            rs = self.executeQuery(sql)
     67            while (rs.next()):
     68                ids.append(rs.getInt(1))
     69        except:
     70            self.logger.exception("Can't query for merged batch ids in ipptopsps Db")
     71
     72        rs.close()
     73
     74        self.logger.debug("Found %d merged but un-deleted items" % len(ids))
     75
     76        return ids
     77
     78    '''
     79    Returns a list of merged batch IDs that are not deleted from local disk
     80    '''
     81    def getMergedButNotDeletedFromLocalDisk(self, batchType, epoch, dvoGpc1Label):
     82        return self.getMergedButNotDeletedBatchIDs(batchType, epoch, dvoGpc1Label, "deleted_local")
     83
     84    '''
     85    Returns a list of processed batch IDs that are loaded to the ODM, but not deleted from local disk
     86    '''
     87    def getLoadedToODMButNotDeletedFromLocalDisk(self, batchType, epoch, dvoGpc1Label):
     88        return self.getLoadedToODMButNotDeletedBatchIDs(batchType, epoch, dvoGpc1Label, "deleted_local")
     89
     90    '''
     91    Returns a list of processed batch IDs that are loaded to the ODM, but not deleted from datastore
     92    '''
     93    def getLoadedToODMButNotDeletedFromDatastore(self, batchType, epoch, dvoGpc1Label):
     94        return self.getLoadedToODMButNotDeletedBatchIDs(batchType, epoch, dvoGpc1Label, "deleted_datastore")
     95
     96    '''
     97    Returns a list of processed batch IDs that are loaded to the ODM, but not deleted from DXLayer
     98    '''
     99    def getLoadedToODMButNotDeletedFromDXLayer(self, batchType, epoch, dvoGpc1Label):
     100        return self.getLoadedToODMButNotDeletedBatchIDs(batchType, epoch, dvoGpc1Label, "deleted_dxlayer")
     101
     102
     103    '''
     104    Returns a list of processed batch IDs that are not loaded to the datastore
     105    NB we have a date constraint here because, before this time, it is possible that
     106    a test batch would be labelled as processed but not loaded to datastore, and we would NOT
     107    want to load a test batch to PSPS
     108
     109    We also check that these batches are more than 4 HOURs old, so that we don't attempt to
     110    publish something simulataneously with the client that it producing it
     111    '''
     112    def getProcessedButFailedDatastoreBatchIDs(self, epoch, dvoGpc1Label, batchType):
     113
     114        sql = "SELECT DISTINCT batch_id \
     115               FROM batch \
     116               WHERE timestamp > '" + epoch + "' \
     117               AND batch_type = '" + batchType + "' \
     118               AND dvo_db = '" + dvoGpc1Label + "' \
     119               AND processed = 1\
     120               AND loaded_to_datastore != 1 \
     121               AND timestamp > '2011-10-27' \
     122               AND timestamp < now() -  INTERVAL 4 HOUR"
     123
     124        ids = []
     125        try:
     126            rs = self.executeQuery(sql)
     127            while (rs.next()):
     128                ids.append(rs.getInt(1))
     129        except:
     130            self.logger.exception("Can't query for processed batch ids not loaded to datastore ipptopsps Db")
     131
     132        rs.close()
     133
     134        self.logger.debug("Found %d processed but-not-on-datastore items" % len(ids))
     135
     136        return ids
     137
     138    '''
     139    Returns a list of processed batch IDs that are not yet loaded to the ODM
     140    NOTE we exclude batches already deleted from the datastore, as sometimes we delete stuff prior to loading to ODM if there is a known problem with the batch
     141    '''
     142    def getUnloadedBatchIDs(self, epoch, dvoGpc1Label, batchType):
     143
     144        sql = "SELECT batch_id \
     145               FROM batch \
     146               WHERE timestamp > '" + epoch + "' \
     147               AND dvo_db = '" + dvoGpc1Label + "' \
     148               AND loaded_to_datastore = 1 \
     149               AND batch_type = '" + batchType + "' \
     150               AND loaded_to_ODM = 0 \
     151               AND deleted_datastore = 0"
     152
     153        ids = []
     154        try:
     155            rs = self.executeQuery(sql)
     156            while (rs.next()):
     157                ids.append(rs.getInt(1))
     158        except:
     159            self.logger.exception("Can't query for unloaded batch ids in ipptopsps Db")
     160
     161        rs.close()
     162
     163        self.logger.debug("Found %d unloaded items" % len(ids))
     164
     165        return ids
     166
     167    '''
     168    Returns a list of processed batch IDs that are not yet merge_worthy and that have not failed to load
     169    NOTE we exclude batches already deleted from the datastore, as sometimes we delete stuff prior to loading to ODM if there is a known problem with the batch
     170    '''
     171    def getUnmergeWorthyBatchIDs(self, epoch, dvoGpc1Label, batchType):
     172
     173        sql = "SELECT batch_id \
     174               FROM batch \
     175               WHERE timestamp > '" + epoch + "' \
     176               AND dvo_db = '" + dvoGpc1Label + "' \
     177               AND loaded_to_datastore = 1 \
     178               AND batch_type = '" + batchType + "' \
     179               AND merge_worthy = 0 \
     180               AND loaded_to_ODM != -1 \
     181               AND deleted_datastore = 0"
     182
     183        ids = []
     184        try:
     185            rs = self.executeQuery(sql)
     186            while (rs.next()):
     187                ids.append(rs.getInt(1))
     188        except:
     189            self.logger.exception("Can't query for un-mergeworthy batch ids in ipptopsps Db")
     190
     191        rs.close()
     192
     193        self.logger.debug("Found %d unloaded items" % len(ids))
     194
     195        return ids
     196
     197    '''
     198    Returns a list of processed batch IDs that are merge_worthy, but not yet merged, for this epoch and dvo label
     199    '''
     200    def getUnmergedBatchIDs(self, epoch, dvoGpc1Label, batchType):
     201
     202        sql = "SELECT batch_id \
     203               FROM batch \
     204               WHERE timestamp > '" + epoch + "' \
     205               AND dvo_db = '" + dvoGpc1Label + "' \
     206               AND merge_worthy = 1 \
     207               AND batch_type = '" + batchType + "' \
     208               AND merged != 1"
     209
     210        ids = []
     211        try:
     212            rs = self.executeQuery(sql)
     213            while (rs.next()):
     214                ids.append(rs.getInt(1))
     215        except:
     216            self.logger.exception("Can't query for unmerged batch ids in ipptopsps Db")
     217
     218        rs.close()
     219
     220        self.logger.debug("Found %d un-merged items" % len(ids))
     221
     222        return ids
     223
     224    '''
     225    Returns a list of batch IDs for this epoch and dvo label for which the specified column is set to value
     226    '''
     227    def getBatchIDs(self, epoch, dvoGpc1Label, column, value):
     228
     229        sql = "SELECT DISTINCT batch_id \
     230               FROM batch \
     231               WHERE timestamp > '" + epoch + "' \
     232               AND dvo_db = '" + dvoGpc1Label + "' \
     233               AND " + column + " = " + str(value)
     234
     235        ids = []
     236        try:
     237            rs = self.executeQuery(sql)
     238            while (rs.next()):
     239                ids.append(rs.getInt(1))
     240        except:
     241            self.logger.exception("Can't query for batch ids with " + column + " = " + str(value) + " in ipptopsps Db")
     242
     243        rs.close()
     244
     245        self.logger.debug("Found %d batches with %s = %d" % (len(ids), column, value))
     246
     247        return ids
     248
     249    '''
     250    Returns the total detections published to the datastore for this epoch, dvo label and batch type
     251    '''
     252    def getTotalDetectionsPublished(self, batchType, epoch, dvoGpc1Label):
     253
     254        sql = "SELECT SUM(total_detections) \
    117255               FROM batch \
    118256               WHERE batch_type = '" + batchType + "' \
    119257               AND timestamp > '" + epoch + "' \
    120258               AND dvo_db = '" + dvoGpc1Label + "' \
    121                AND " + column + " = 1"
    122 
    123         ids = []
    124         try:
    125             rs = self.executeQuery(sql)
    126             while (rs.next()):
    127                 ids.append(rs.getInt(1))
    128         except:
    129             self.logger.exception("Can't query for ids with " + column + " = 1 in ipptopsps Db")
     259               AND processed = 1 \
     260               AND loaded_to_datastore = 1"
     261
     262        total = -1
     263        try:
     264            rs = self.executeQuery(sql)
     265            rs.first()
     266            total =  rs.getLong(1)
     267        except:
     268            self.logger.exception("Can't query for total detections published")
     269
     270        rs.close()
     271
     272        self.logger.debug("Found %d detections" % total)
     273
     274        return total
     275
     276    '''
     277    Returns a list of IDs for this batch type, epoch and dvo label (i.e. either
     278            cam_ids or stack_ids) for which the specified column is set to value
     279    '''
     280    def getStageIDs(self, batchType, epoch, dvoGpc1Label, column, value):
     281
     282        sql = "SELECT DISTINCT stage_id \
     283               FROM batch \
     284               WHERE batch_type = '" + batchType + "' \
     285               AND timestamp > '" + epoch + "' \
     286               AND dvo_db = '" + dvoGpc1Label + "' \
     287               AND " + column + " = " + str(value)
     288
     289        ids = []
     290        try:
     291            rs = self.executeQuery(sql)
     292            while (rs.next()):
     293                ids.append(rs.getInt(1))
     294        except:
     295            self.logger.exception("Can't query for ids with " + column + " = " + str(value) + " in ipptopsps Db")
    130296
    131297        rs.close()
     
    136302
    137303    '''
     304    Series of getter methods that utilise getBatchIDs() method above
     305    '''
     306    def getloadedToDatastoreBatchIDs(self, epoch, dvoGpc1Label):
     307        return self.getBatchIDs(epoch, dvoGpc1Label, "loaded_to_datastore", 1)
     308    def getFailedLoadedToODMBatchIDs(self, epoch, dvoGpc1Label):
     309        return self.getBatchIDs(epoch, dvoGpc1Label, "loaded_to_ODM", -1)
     310
     311    '''
     312    TODO remove these
    138313    Series of getter methods that utilise getStageIDs() method above
    139314    '''
    140315    def getProcessedIDs(self, batchType, epoch, dvoGpc1Label):
    141         return self.getStageIDs(batchType, epoch, dvoGpc1Label, "processed")
    142     def getloadedToDatastoreIDs(self, batchType, epoch, dvoGpc1Label):
    143         return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_datastore")
     316        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "processed", 1)
     317    def getFailedProcessedIDs(self, batchType, epoch, dvoGpc1Label):
     318        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "processed", -1)
     319    def getLoadedToDatastoreIDs(self, batchType, epoch, dvoGpc1Label):
     320        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_datastore", 1)
     321    def getFailedLoadedToDatastoreIDs(self, batchType, epoch, dvoGpc1Label):
     322        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_datastore", -1)
    144323    def getLoadedToODMIDs(self, batchType, epoch, dvoGpc1Label):
    145         return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_ODM")
    146     def getMergeWothyIDs(self, batchType, epoch, dvoGpc1Label):
    147         return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merge_worthy")
     324        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_ODM", 1)
     325    def getFailedLoadedToODMIDs(self, batchType, epoch, dvoGpc1Label):
     326        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "loaded_to_ODM", -1)
     327    def getMergeWorthyIDs(self, batchType, epoch, dvoGpc1Label):
     328        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merge_worthy", 1)
     329    def getFailedMergeWorthyIDs(self, batchType, epoch, dvoGpc1Label):
     330        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merge_worthy", -1)
    148331    def getMergedIDs(self, batchType, epoch, dvoGpc1Label):
    149         return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merged")
     332        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merged", 1)
     333    def getFailedMergedIDs(self, batchType, epoch, dvoGpc1Label):
     334        return self.getStageIDs(batchType, epoch, dvoGpc1Label, "merged", -1)
     335
     336    '''
     337    Returns a list of stages
     338    '''
     339    def getStages(self):
     340        return ['processed', 'loaded_to_datastore', 'loaded_to_ODM', 'merge_worthy', 'deleted_datastore', 'deleted_dxlayer', 'merged', 'deleted_local' ]
     341
     342    '''
     343    Returns a count of batches processed in the specified time period.
     344    '''
     345    def countBatchesInLastPeriod(self, batchType, epoch, dvoGpc1Label, interval):
     346
     347        sql = "SELECT COUNT(batch_id) \
     348               FROM batch \
     349               WHERE batch_type = '" + batchType + "' \
     350               AND processed = 1 \
     351               AND timestamp > '" + epoch + "' \
     352               AND dvo_db = '" + dvoGpc1Label + "' \
     353               AND timestamp BETWEEN now() - INTERVAL " + interval + " AND now()"
     354
     355        try:
     356            rs = self.executeQuery(sql)
     357            if rs.first(): return rs.getInt(1)
     358        except:
     359            self.logger.exception("Unable to count batches in interval")
     360            return 0
    150361
    151362    '''
     
    155366    def getTimeOfLastBatchPublished(self, batchType, epoch, dvoGpc1Label):
    156367
    157         minutes = None
    158 
    159         sql = "SELECT TIMESTAMPDIFF(MINUTE, timestamp, now()) \
     368        seconds = None
     369
     370        sql = "SELECT TIMESTAMPDIFF(SECOND, timestamp, now()) \
    160371               FROM batch \
    161372               WHERE batch_type = '" + batchType + "' \
    162                AND loaded_to_datastore \
     373               AND loaded_to_datastore = 1 \
    163374               AND timestamp > '" + epoch + "' \
    164375               AND dvo_db = '" + dvoGpc1Label + "' \
     
    167378        try:
    168379            rs = self.executeQuery(sql)
    169             if rs.first(): minutes = rs.getFloat(1)
     380            if rs.first(): seconds = rs.getFloat(1)
    170381        except:
    171382            self.logger.exception("Unable to get last batch published")
    172383
    173         if not minutes: return "Never"
    174 
     384        if not seconds: return "Never"
     385
     386        minutes = seconds/60.0
    175387        hours = minutes/60.0
    176         days = float(hours)/24.0
    177         weeks = float(days)/7.0
    178 
    179         if minutes < 60: return "%.1f minutes ago" % minutes
     388        days = hours/24.0
     389        weeks = days/7.0
     390
     391        if seconds < 60: return "%.1f secs ago" % seconds
     392        elif minutes < 60: return "%.1f mins ago" % minutes
    180393        elif hours < 48: return "%.1f hours ago" % hours
    181394        elif days < 7: return "%.1f days ago" % days
     
    183396
    184397    '''
    185     TODO
    186     '''
    187     def getBatchesPerDay(self, batchType, startTime, endTime=""):
    188 
    189         bph = self.getBatchesPerHour(batchType, startTime, endTime)
    190         return bph * 24
    191 
    192     '''
    193     TODO
    194     '''
    195     def getBatchesPerHour(self, batchType, startTime, endTime=""):
    196 
    197         bpm = self.getBatchesPerMinute(batchType, startTime, endTime)
    198         return bpm * 60
    199 
    200     '''
    201     TODO
    202     '''
    203     def getAverageTimePerBatch(self, batchType, startTime, endTime=""):
    204 
    205         sql = "SELECT (TIMESTAMPDIFF(MINUTE, min(timestamp), max(timestamp)) / COUNT(*)) \
    206                FROM batch \
    207                WHERE timestamp > '" + startTime + "' and batch_type = '" + batchType + "'"
    208 
    209         try:
    210             rs = self.executeQuery(sql)
    211             rs.first()
    212             time = rs.getDouble(1)
    213         except:
    214             self.logger.exception("Unable to get batches per minute")
    215 
    216         return time
    217 
    218     '''
    219     TODO
    220     '''
    221     def getBatchesPerMinute(self, batchType, startTime, endTime=""):
    222 
    223         sql = "SELECT (count(*) / TIMESTAMPDIFF(MINUTE, min(timestamp), max(timestamp)) ) \
    224                FROM batch \
    225                WHERE timestamp > '" + startTime + "' and batch_type = '" + batchType + "'"
    226 
    227         try:
    228             rs = self.executeQuery(sql)
    229             rs.first()
    230             bpm = rs.getDouble(1)
    231         except:
    232             self.logger.exception("Unable to get batches per minute")
    233 
    234         return bpm
    235 
    236     '''
    237398    Updates min/max object ID on this table and batch
    238399    '''
    239     def updateMinMaxObjID(self, batchID, minObjID, maxObjID):
     400    def updateDetectionStats(self, batchID, minObjID, maxObjID, totalDetections):
    240401
    241402        sql = "UPDATE batch SET \
    242403               min_obj_id = " + str(minObjID) + ", \
    243                max_obj_id = " + str(maxObjID) + " \
     404               max_obj_id = " + str(maxObjID) + ", \
     405               total_detections = " + str(totalDetections) + " \
    244406               WHERE batch_id = " + str(batchID)
    245407
     
    257419        self.execute(sql)
    258420
    259 
    260421    '''
    261422    Updates batch processed field
     
    265426
    266427    '''
    267     Updates batch deleted field
    268     '''
    269     def updateDeleted(self, batchID, deleted):
    270         self.updateColumn(batchID, "deleted", deleted)
     428    Updates batch deleted local field
     429    '''
     430    def updateDeletedLocal(self, batchID, value):
     431        self.updateColumn(batchID, "deleted_local", value)
     432
     433    '''
     434    Updates batch deleted datastore field
     435    '''
     436    def updateDeletedDatastore(self, batchID, value):
     437        self.updateColumn(batchID, "deleted_datastore", value)
     438
     439    '''
     440    Updates batch deleted dxlayer field
     441    '''
     442    def updateDeletedDxlayer(self, batchID, value):
     443        self.updateColumn(batchID, "deleted_dxlayer", value)
    271444
    272445    '''
     
    281454    def updateOdmStatus(self, batchID, odmStatus):
    282455
     456        if odmStatus['LOADFAILED'] == 1: loadedToODM = -1
     457        else: loadedToODM = odmStatus['LOADEDTOODM']
    283458        sql = "UPDATE batch \
    284                SET loaded_to_ODM = " + str(odmStatus['LOADEDTOODM']) + ", \
     459               SET loaded_to_ODM = " + str(loadedToODM) + ", \
    285460               merge_worthy = " + str(odmStatus['MERGEWORTHY']) + ", \
    286461               merged = " + str(odmStatus['MERGED']) + " \
     
    290465
    291466    '''
    292     Have we already processed and published this batch?
    293     '''
    294     def alreadyProcessed(self, stage_id):
     467    Is someone processing this item right now? Checks whether this was attempted within the last 2 HOUR
     468    '''
     469    def processingNow(self, batchType, stage_id, epoch, dvoGpc1Label):
    295470
    296471        sql = "SELECT COUNT(*) \
    297472               FROM batch \
    298473               WHERE stage_id = " + str(stage_id) + " \
    299                AND processed \
    300                AND loaded_to_datastore"
     474               AND batch_type = '" + batchType + "' \
     475               AND dvo_db = '" + dvoGpc1Label + "' \
     476               AND timestamp BETWEEN now() - INTERVAL 4 HOUR AND now()"
    301477
    302478        try:
     
    304480            rs.first()
    305481            if rs.getInt(1) > 0:
    306                 self.logger.error("Batch with stage_id = "+str(stage_id) + " has already been processed and published to datastore")
     482                self.logger.errorPair(str(stage_id) + " is already being processed", "skipping")
    307483                return True
    308484            else:
    309485                return False
    310486        except:
     487            self.logger.exception("Unable to check whether this batch is being processed")
     488
     489    '''
     490    Gets the batch type of this batch
     491    '''
     492    def getBatchType(self, batch_id):
     493
     494        sql = "SELECT batch_type \
     495               FROM batch \
     496               WHERE batch_id = " + str(batch_id)
     497
     498        batch_type = "NA"
     499        try:
     500            rs = self.executeQuery(sql)
     501            rs.first()
     502            batch_type = rs.getString(1)
     503        except:
    311504            self.logger.exception("Unable to check whether this batch has already been processed")
    312 
     505 
     506        return batch_type
     507
     508    '''
     509    Have we already processed this stage_id?
     510    '''
     511    def alreadyProcessed(self, batchType, stage_id, epoch, dvoGpc1Label):
     512
     513        sql = "SELECT COUNT(*) \
     514               FROM batch \
     515               WHERE stage_id = " + str(stage_id) + " \
     516               AND batch_type = '" + batchType + "' \
     517               AND timestamp > '" + epoch + "' \
     518               AND dvo_db = '" + dvoGpc1Label + "' \
     519               AND processed = 1"
     520
     521        try:
     522            rs = self.executeQuery(sql)
     523            rs.first()
     524            if rs.getInt(1) > 0:
     525                self.logger.errorPair(str(stage_id) + " has already been published", "skipping")
     526                return True
     527            else:
     528                return False
     529        except:
     530            self.logger.exception("Unable to check whether this batch has already been processed")
     531
     532    '''
     533    Has this stage_id consistently failed to process?
     534    '''
     535    def consistentlyFailed(self, batchType, stage_id, epoch, dvoGpc1Label):
     536
     537        sql = "SELECT COUNT(*) \
     538               FROM batch \
     539               WHERE stage_id = " + str(stage_id) + " \
     540               AND batch_type = '" + batchType + "' \
     541               AND timestamp > '" + epoch + "' \
     542               AND dvo_db = '" + dvoGpc1Label + "' \
     543               AND processed = -1"
     544
     545        try:
     546            rs = self.executeQuery(sql)
     547            rs.first()
     548            if rs.getInt(1) >= self.MAX_FAILS:
     549                self.logger.errorPair(str(stage_id) + " has failed %d times" % self.MAX_FAILS, "skipping")
     550                return True
     551            else:
     552                return False
     553        except:
     554            self.logger.exception("Unable to check whether this batch has consistently failed")
     555
     556    '''
     557    Returns a list of stage_ids that have failed the max number of times
     558    '''
     559    def getConsistentlyFailedIDs(self, batchType, epoch, dvoGpc1Label):
     560
     561        sql = "SELECT DISTINCT stage_id, COUNT(stage_id) AS numoccur \
     562               FROM batch \
     563               WHERE batch_type = '" + batchType + "' \
     564               AND timestamp > '" + epoch + "' \
     565               AND dvo_db = '" + dvoGpc1Label + "' \
     566               AND processed = -1 \
     567               GROUP BY stage_id HAVING numoccur >= " + str(self.MAX_FAILS)
     568
     569        ids = []
     570        try:
     571            rs = self.executeQuery(sql)
     572            while (rs.next()):
     573                ids.append(rs.getInt(1))
     574        except:
     575            self.logger.exception("Can't query for consistantly failed ids in ipptopsps Db")
     576
     577        rs.close()
     578
     579        self.logger.debug("Found %d consistantly failed stage_ids for batch type='%s'" % (len(ids), batchType))
     580
     581        return ids
     582
     583    '''
     584    Locks the batch table. This will wait if the lock is held by someone else
     585    '''
     586    def lockBatchTable(self):
     587        self.lockTable("batch")
     588
     589    '''
     590    Creates a new batch. This is done with a locked table in order that no two clients can start work on the same item
     591    '''
     592    def createNewBatch(self, batchType, stageID, survey, epoch, dvoDb, datastoreProduct, force):
     593
     594        batchID = -1;
     595
     596        if force or \
     597            (not self.alreadyProcessed(batchType, stageID, epoch, dvoDb) \
     598            and not self.processingNow(batchType, stageID, epoch, dvoDb) \
     599            and not self.consistentlyFailed(batchType, stageID, epoch, dvoDb)):
     600
     601            sql = "INSERT INTO batch ( \
     602                   batch_type, \
     603                   stage_id, \
     604                   survey, \
     605                   dvo_db, \
     606                   datastore_product \
     607                   ) VALUES ( \
     608                       '" + batchType + "', \
     609                       " + str(stageID) + ", \
     610                       '" + survey + "', \
     611                       '" + dvoDb + "', \
     612                       '" + datastoreProduct + "' \
     613                       )"
     614
     615            self.execute(sql)
     616
     617            sql = "SELECT MAX(batch_id) FROM batch"
     618
     619            try:
     620                rs = self.executeQuery(sql)
     621                rs.first()
     622                batchID = rs.getInt(1)
     623                self.logger.debug("Created new batch in ippToPsps database with batchID = %d" % batchID)
     624            except:
     625                self.logger.exception("Unable to get batch ID")
     626                batchID = -1
     627
     628        return batchID;
    313629     
    314630
     
    346662        self.execute(sql)
    347663
     664    '''
     665    Resets a batch ready for re-loading to the datastore
     666    '''
     667    def resetBatch(self, batchID):
     668
     669        sql = "UPDATE batch SET \
     670               loaded_to_datastore = 0, \
     671               loaded_to_ODM = 0, \
     672               merge_worthy = 0, \
     673               merged = 0, \
     674               deleted_datastore = 0, \
     675               deleted_dxlayer = 0, \
     676               comment = 'This batch was reset, ready for re-load to datastore' \
     677               WHERE batch_id = " + str(batchID)
     678
     679        self.execute(sql)
    348680
    349681    '''
Note: See TracChangeset for help on using the changeset viewer.