/
DButils.py
2695 lines (2351 loc) · 108 KB
/
DButils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
from __future__ import print_function
import collections
import datetime
import pdb
import glob
import itertools
import os.path
import pwd
import socket # to get the local hostname
import sys
from collections import namedtuple
from operator import itemgetter, attrgetter
import sqlalchemy
import sqlalchemy.sql.expression
from sqlalchemy import Table
from sqlalchemy.orm import mapper
from sqlalchemy.orm import sessionmaker
import sqlalchemy.orm.exc
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.exc import ArgumentError
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql import func
from sqlalchemy import and_
from .Diskfile import calcDigest, DigestError
from . import DBlogging
from . import DBstrings
from . import Version
from . import Utils
from . import __version__
#########################################################
## NOTES, read these if new to this module
#########################################################
# - functions are in transition from returning the thing the name says e.g. getFileID returns a number to
# instead returning the sqlalchemy object that meets the criteria so getFileID would return a File instance
# and the user would then have to get the ID by using File.file_id. This makes for fewer functions and is
# significantly cleaner in a few spots
class DBError(Exception):
pass
class DBProcessingError(Exception):
pass
class FilenameParse(Exception):
pass
class DBNoData(Exception):
pass
class DButils(object):
"""
Utility routines for the DBProcessing class, all of these may be user called but are meant to
be internal routines for DBProcessing
"""
def __init__(self, mission='Test', db_var=None, echo=False, engine='sqlite'):
"""
Initialize the DButils class
:param mission: Name of the mission
:type mission: str
:param db_var: Does nothing.
:param echo: if True, the Engine will log all statements as well as a repr() of their parameter lists to the logger
:type echo: bool
:param engine: DB engine to connect to
:type engine: str
"""
self.dbIsOpen = False
if mission is None:
raise (DBError("Must input database name to create DButils instance"))
self.mission = mission
# Expose the format/regex routines of DBformatter
fmtr = DBstrings.DBformatter()
self.format = fmtr.format
self.re = fmtr.re
self.openDB(db_var=db_var, engine=engine, echo=echo)
self._createTableObjects()
try:
self._patchProcessQueue()
except AttributeError:
raise (AttributeError('{0} is not a valid database'.format(mission)))
self.MissionDirectory = self.getMissionDirectory()
self.CodeDirectory = self.getCodeDirectory()
self.InspectorDirectory = self.getInspectorDirectory()
def __del__(self):
"""
try and clean up a little bit
"""
self.closeDB()
def __repr__(self):
"""
@summary: Print out something useful when one prints the class instance
:return: DBProcessing class instance for mission <mission name>
"""
return 'DBProcessing class instance for mission ' + self.mission + ', version: ' + __version__
def _patchProcessQueue(self):
self.Processqueue.flush = self._processqueueFlush
self.Processqueue.remove = self._processqueueRemoveItem
self.Processqueue.getAll = self._processqueueGetAll
self.Processqueue.push = self._processqueuePush
self.Processqueue.len = self._processqueueLen
self.Processqueue.pop = self._processqueuePop
self.Processqueue.get = self._processqueueGet
self.Processqueue.clean = self._processqueueClean
self.Processqueue.rawadd = self._processqueueRawadd
# TODO to do thus cleaner and allow for [] to work on the classes
# ...info here...
# metaclass that is dbutils aware
# get __getitem__ to be a class mo
####################################
###### DB and Tables ###############
####################################
def openDB(self, engine, db_var=None, verbose=False, echo=False):
"""
Setup python to talk to the database, this is where it is, name and password.
:param engine: DB engine to connect to
:type engine: str
:param db_var: Does nothing.
:param echo: if True, the Engine will log all statements as well as a repr() of their parameter lists to the logger
:type echo: bool
:param verbose: if True, will print out extra debugging
:type verbose: bool
"""
if self.dbIsOpen == True:
return
try:
if not os.path.isfile(os.path.expanduser(self.mission)):
raise (ValueError("DB file specified doesn't exist"))
engineIns = sqlalchemy.create_engine('{0}:///{1}'.format(engine, os.path.expanduser(self.mission)),
echo=echo)
self.mission = os.path.abspath(os.path.expanduser(self.mission))
DBlogging.dblogger.info("Database Connection opened: {0} {1}".format(str(engineIns), self.mission))
except (DBError, ArgumentError):
(t, v, tb) = sys.exc_info()
raise (DBError('Error creating engine: ' + str(v)))
try:
metadata = sqlalchemy.MetaData(bind=engineIns)
# a session is what you use to actually talk to the DB, set one up with the current engine
Session = sessionmaker(bind=engineIns)
session = Session()
self.engine = engineIns
self.metadata = metadata
self.session = session
self.dbIsOpen = True
if verbose: print("DB is open: %s" % (engineInsR))
return
except Exception as msg:
raise (DBError('Error opening database: %s' % (msg)))
def _createTableObjects(self, verbose=False):
"""
cycle through the database and build classes for each of the tables
"""
DBlogging.dblogger.debug("Entered _createTableObjects()")
## ask for the table names form the database (does not grab views)
table_names = self.engine.table_names()
## create a dictionary of all the table names that will be used as class names.
## this uses the db table name as the table name and a cap 1st letter as the class
## when interacting using python use the class
table_dict = { }
for val in table_names:
table_dict[val.title()] = val
## dynamically create all the classes (c1)
## dynamically create all the tables in the db (c2)
## dynamically create all the mapping between class and table (c3)
## this just saves a lot of typing and is equivalent to:
## class Missions(object):
## pass
## missions = Table('missions', metadata, autoload=True)
## mapper(Missions, missions)
for val in table_dict:
if verbose: print(val)
if not hasattr(self, val): # then make it
myclass = type(str(val), (object,), dict())
tableobj = Table(table_dict[val], self.metadata, autoload=True)
mapper(myclass, tableobj)
setattr(self, str(val), myclass)
if verbose: print("Class %s created" % (val))
if verbose: DBlogging.dblogger.debug("Class %s created" % (val))
#####################################
#### Do processing and input to DB
#####################################
def currentlyProcessing(self):
"""
Checks the db to see if it is currently processing, don't want to do 2 at the same time
:return: false or the pid
:rtype: bool or long
>>> pnl.currentlyProcessing()
"""
DBlogging.dblogger.info("Checking currently_processing")
sq = self.session.query(self.Logging).filter_by(currently_processing=True).all()
if len(sq) == 1:
DBlogging.dblogger.warning("currently_processing is set. PID: {0}".format(sq[0].pid))
return sq[0].pid
elif len(sq) == 0:
return False
else:
DBlogging.dblogger.error("More than one currently_processing flag set, fix the DB")
raise (DBError("More than one currently_processing flag set, fix the DB"))
def resetProcessingFlag(self, comment):
"""
Query the db and reset a processing flag
:param comment: the comment to enter into the processing log DB
:type comment: str
:return: True - Success, False - Failure
:rtype: bool
"""
sq2 = self.session.query(self.Logging).filter_by(currently_processing=True).count()
if sq2 and comment is None:
raise (ValueError("Must enter a comment to override DB lock"))
sq = self.session.query(self.Logging).filter_by(currently_processing=True)
for val in sq:
val.currently_processing = False
val.processing_end = datetime.datetime.utcnow()
val.comment = 'Overridden:' + comment + ':' + __version__
DBlogging.dblogger.error("Logging lock overridden: %s" % ('Overridden:' + comment + ':' + __version__))
self.session.add(val)
if sq2:
self.commitDB()
def startLogging(self):
"""
Add an entry to the logging table in the DB, logging
"""
# this is the logging of the processing, no real use for it yet but maybe we will in the future
# helps to know is the process ran and if it succeeded
if self.currentlyProcessing():
raise (DBError('A Currently Processing flag is still set, cannot process now'))
# save this class instance so that we can finish the logging later
self.__p1 = self.addLogging(True,
datetime.datetime.utcnow(),
## for now there is one mission only per DB
# self.getMissionID(self.mission),
self.session.query(self.Mission.mission_id).first()[0],
pwd.getpwuid(os.getuid())[0],
socket.gethostname(),
pid=os.getpid())
DBlogging.dblogger.info("Logging started: %d: %s, PID: %s, M_id: %s, user: %s, hostname: %s" %
(self.__p1.logging_id, self.__p1.processing_start_time, self.__p1.pid,
self.__p1.mission_id, self.__p1.user, self.__p1.hostname))
def addLogging(self,
currently_processing,
processing_start_time,
mission_id,
user,
hostname,
pid=None,
processing_end_time=None,
comment=None):
"""
Add an entry to the logging table
:param currently_processing: is the db currently processing?
:type currently_processing: bool
:param processing_start_time: the time the processing started
:type processing_start_time: datetime.datetime
:param mission_id: the mission id the processing if for
:type mission_id: int
:param user: the user doing the processing
:type user: str
:param hostname: the hostname that initiated the processing
:type hostname: str
:keyword pid: the process id that id the processing
:type pid: int
:keyword processing_end_time: the time the processing stopped
:type processing_end_time: datetime.datetime
:keyword comment: comment about the processing run
:type comment: str
:return: instance of the Logging class
:rtype: Logging
"""
l1 = self.Logging()
l1.currently_processing = currently_processing
l1.processing_start_time = processing_start_time
l1.mission_id = mission_id
l1.user = user
l1.hostname = hostname
l1.pid = pid
l1.processing_end_time = processing_end_time
l1.comment = comment
self.session.add(l1)
self.commitDB()
return l1 # so we can use the same session to stop the logging
def stopLogging(self, comment):
"""
Finish the entry to the processing table in the DB, logging
:param comment: (optional) a comment to insert into he DB
:type param: str
"""
try:
self.__p1
except:
DBlogging.dblogger.warning("Logging was not started, can't stop")
raise (DBProcessingError("Logging was not started"))
# clean up the logging, we are done processing and we can release the lock (currently_processing) and
# put in the complete time
self.__p1.processing_end = datetime.datetime.utcnow()
self.__p1.currently_processing = False
self.__p1.comment = comment + ':' + __version__
self.session.add(self.__p1)
self.commitDB()
DBlogging.dblogger.info("Logging stopped: %s comment '%s' " % (self.__p1.processing_end, self.__p1.comment))
del self.__p1
def checkDiskForFile(self, file_id, fix=False):
"""
Check the file system to see if the file exits or not as it says in the db
:param file_id: id of the file to check
:type file_id: int
:keyword fix: (optional) set to have the DB fixed to match the file system
this is **NOT** sure to be safe
:type fix: bool
:returns: Return true is consistent, False otherwise
:rtype: bool
"""
sq = self.getEntry('File', file_id)
if sq.exists_on_disk:
file_path = self.getFileFullPath(sq.file_id)
if not os.path.exists(file_path):
if fix:
sq.exists_on_disk = False
self.session.add(sq)
self.commitDB()
return self.checkDiskForFile(file_id) # call again to get the True
else:
return False
else:
return True
else:
return True
def _processqueueFlush(self):
"""
remove everything from the process queue
This is as optimized as it can be
"""
length = self.Processqueue.len()
self.session.query(self.Processqueue).delete()
self.commitDB()
DBlogging.dblogger.info("Processqueue was cleared")
return length
def _processqueueRemoveItem(self, item, commit = True):
"""
remove a file from the queue by name or number
"""
# if the input is a file name need to handle that
if not hasattr(item, '__iter__'):
item = [item]
for ii, v in enumerate(item):
item[ii] = self.getFileID(v)
sq = self.session.query(self.Processqueue).filter(self.Processqueue.file_id.in_(item))
for v in sq:
self.session.delete(v)
if sq and commit:
self.commitDB()
def _processqueueGetAll(self, version_bump=False):
"""
Return the entire contents of the process queue
"""
pqdata = self.session.query(self.Processqueue).all()
if version_bump:
ans = zip(map(attrgetter('file_id'), pqdata), map(attrgetter('version_bump'), pqdata))
else:
ans = map(attrgetter('file_id'), pqdata)
DBlogging.dblogger.debug("Entire Processqueue was read: {0} elements returned".format(len(ans)))
return ans
def _processqueuePush(self, fileid, version_bump=None, MAX_ADD=150):
"""
Push a file onto the process queue (onto the right)
Parameters
==========
fileid : (int, string)
the file id (or name to put on the process queue)
Returns
=======
file_id : int
the file_id that was passed in, but grabbed from the db
"""
if not hasattr(fileid, '__iter__'):
fileid = [fileid]
else:
# do this in chunks as too many entries breaks things
if len(fileid) > MAX_ADD:
outval = []
for v in Utils.chunker(fileid, MAX_ADD):
outval.extend(self._processqueuePush(v, version_bump=version_bump))
return outval
# first filter() takes care of putting in values that are not in the DB. It is silent
# second filter() takes care of not reading files that are already in the queue
subq = self.session.query(self.Processqueue.file_id).subquery()
fileid = (self.session.query(self.File.file_id)
.filter(self.File.file_id.in_(fileid))
.filter(~self.File.file_id.in_(subq))).all()
fileid = list(map(itemgetter(0), fileid)) # nested tuples to list
pq = set(self.Processqueue.getAll())
fileid = set(fileid).difference(pq)
outval = []
objs = []
for f in fileid:
pq1 = self.Processqueue()
pq1.file_id = f
pq1.version_bump = version_bump
objs.append(pq1)
outval.append(pq1.file_id)
DBlogging.dblogger.debug("File added to process queue {0}:{1}".format(fileid, '---'))
if fileid:
self.session.add_all(objs)
self.commitDB()
# pqid = self.session.query(self.Processqueue.file_id).all()
return outval
def _processqueueRawadd(self, fileid, version_bump=None, commit=True):
"""
raw add file ids to the process queue
*** this might break things if an id is added that does not exist
*** meant to be fast and used after getting the ids
*** IS safe against adding ids that are already in the queue
Parameters
==========
fileid : (int, listlike)
the file id (or lisklike of file ids)
Returns
=======
num : int
the number of entries added to the processqueue
"""
current_q = set(self._processqueueGetAll())
if not hasattr(fileid, '__iter__'):
fileid = [fileid]
fileid = set(fileid)
# drop all the values in the current_q from fileid
files_to_add = fileid.difference(current_q)
# are there any left?
if len(files_to_add) != 0:
for f in files_to_add:
pq1 = self.Processqueue()
pq1.file_id = f
pq1.version_bump = version_bump
self.session.add(pq1)
DBlogging.dblogger.debug("File added to process queue {0}:{1}".format(fileid, '---'))
if commit:
self.commitDB() # commit once for all the adds
return len(files_to_add)
def _processqueueLen(self):
"""
Return the number of files in the process queue
"""
return self.session.query(self.Processqueue).count()
def _processqueuePop(self, index=0):
"""
pop a file off the process queue (from the left)
Other Parameters
================
index : int
the index in the queue to pop
Returns
=======
file_id : int
the file_id of the file popped from the queue
"""
val = self._processqueueGet(index=index, instance=True)
self.session.delete(val)
self.commitDB()
return (val.file_id, val.version_bump)
def _processqueueGet(self, index=0, instance=False):
"""
Get the file at the head of the queue (from the left)
Returns
=======
file_id : int
the file_id of the file popped from the queue
"""
if index < 0: # enable the python from the end indexing
index = self.Processqueue.len() + index
sq = self.session.query(self.Processqueue).offset(index).first()
if instance:
ans = sq
else:
ans = (sq.file_id, sq.version_bump)
return ans
def _processqueueClean(self, dryrun=False):
"""
go through the process queue and clear out lower versions of the same files
this is determined by product and utc_file_date
also sorts by level, date
"""
# BAL 30 March 2017 Trying a different method here that might be cleaner
# # TODO this might break with weekly input files
# DBlogging.dblogger.debug("Entering _processqueueClean(), there are {0} entries".format(self.Processqueue.len()))
# pqdata = self.Processqueue.getAll(version_bump=True)
#
# file_ids = list(map(itemgetter(0), pqdata))
# version_bumps = list(map(itemgetter(1), pqdata))
#
# # speed this up using a sql in_ call not looping over getEntry for each one
# # this gets all the file objects for the processqueue file_ids
# subq = self.session.query(self.Processqueue.file_id).subquery()
# file_entries = self.session.query(self.File).filter(self.File.file_id.in_(subq)).all()
#
# file_entries2 = self.file_id_Clean(file_entries)
#
# # ==============================================================================
# # # sort keep on dates, then sort keep on level
# # ==============================================================================
# # this should make them in order for each level
# file_entries2 = sorted(file_entries2, key=lambda x: x.utc_file_date, reverse=1)
# file_entries2 = sorted(file_entries2, key=lambda x: x.data_level)
# # apply same sort/filter to version_bumps
# version_bumps2 = (version_bumps[file_entries.index(v)] for v in file_entries2)
#
# file_entries2 = [val.file_id for val in file_entries2]
# mixed_entries = itertools.izip(file_entries2, version_bumps2)
#
# ## now we have a list of just the newest file_id's
# if not dryrun:
# self.Processqueue.flush()
# # self.Processqueue.push(ans)
# if not any(version_bumps2):
# self.Processqueue.push(file_entries2)
# else:
# itertools.starmap(self.Processqueue.push, mixed_entries)
# # for v in mixed_entries:
# # itertools.startmap(self.Processqueue.push, v)
# else:
# print(
# '<dryrun> Queue cleaned leaving {0} of {1} entries'.format(len(file_entries2), self.Processqueue.len()))
#
# DBlogging.dblogger.debug(
# "Done in _processqueueClean(), there are {0} entries left".format(self.Processqueue.len()))
# # BAL 30 March 2017 new version
# # get all the files from the process queue
DBlogging.dblogger.debug("Entering _processqueueClean(), there are {0} entries".format(self.Processqueue.len()))
pqdata = self.Processqueue.getAll(version_bump=True)
# all we need to do is look at each file and see if it is latest version or not, if it is not drop it
entries = []
version_bump = False
for i, pq in enumerate(pqdata):
# print(i, len(pqdata))
if pq[1] is not None:
entries.append(pq) # if the version_bump is these it needs to stay in the queue
version_bump = True
else:
if self.fileIsNewest(pq[0]):
entries.append(pq) # if the file is newest_version than we keep it
if not dryrun:
self.Processqueue.flush()
if not version_bump:
self.Processqueue.rawadd(zip(*entries)[0])
else:
for f in pqdata:
self.Processqueue.add(f)
else:
print(
'<dryrun> Queue cleaned leaving {0} of {1} entries'.format(len(file_entries2), self.Processqueue.len()))
DBlogging.dblogger.debug(
"Done in _processqueueClean(), there are {0} entries left".format(self.Processqueue.len()))
def fileIsNewest(self, filename, debug=False):
"""
quesry the database, is this filename or file_id newest version?
@param filename: filename or file_id
@return: Ture is file is lastest_version, False is not
"""
file = self.getEntry('File', filename)
product_id = file.product_id
if debug: print('product_id', product_id )
date = file.utc_file_date
if debug: print('date', date)
file_id = file.file_id
if debug: print('file_id', file_id, file.filename)
latest = self.getFilesByProductDate(product_id, [date]*2, newest_version=True)
if len(latest) > 1:
raise(DBError("More than one latest for a product date"))
latest_id = latest[0].file_id
if debug: print('latest_id', latest_id)
return file_id == latest_id
def _purgeFileFromDB(self, filename=None, recursive=False, verbose=False, trust_id=False, commit=True):
"""
removes a file from the DB
:param filename: name of the file to remove (or a list of names)
:param recursive: remove all files that depend on the Given
if recursive then it removes all files that depend on the one to remove
>>> pnl._purgeFileFromDB('Test-one_R0_evinst-L1_20100401_v0.1.1.cdf')
"""
if not hasattr(filename, '__iter__'): # if not an iterable make it a iterable
filename = [filename]
for ii, f in enumerate(filename):
if not trust_id:
try:
f = self.getFileID(f)
except DBNoData:
pass
else:
pass # just use the id without a lookup
if recursive:
ids = self.session.query(self.Filefilelink.resulting_file).filter_by(source_file=f).all()
for fid in ids:
self._purgeFileFromDB(filename=fid.resulting_file, recursive=True, verbose=verbose)
if verbose:
print(ii, len(filename), f)
# we need to look in each table that could have a reference to this file and delete that
try: ## processqueue
self.Processqueue.remove(f)
except DBNoData:
pass
try: ## filefilelink
self.delFilefilelink(f)
except DBNoData:
pass
try: ## filecodelink
self.delFilecodelink(f)
except DBNoData:
pass
try: ## file
self.session.delete(self.getEntry('File', f))
except DBNoData:
pass
DBlogging.dblogger.info("File removed from db {0}".format(f))
if commit:
self.commitDB()
def getAllSatellites(self):
"""
Return dictionaries of satellite, mission objects
:return: dictionaries of satellite, mission objects
:rtype: dict
"""
ans = []
sats = self.session.query(self.Satellite).all()
ans = map(lambda x: self.getTraceback('Satellite', x.satellite_id), sats)
return ans
def getAllInstruments(self):
"""
Return dictionaries of instrument traceback dictionaries
:return: dictionaries of instrument traceback dictionaries
:rtype: dict
"""
ans = []
insts = self.session.query(self.Instrument).all()
ans = map(lambda x: self.getTraceback('Instrument', x.instrument_id), insts)
return ans
def getAllCodes(self, active=True):
"""
Return a list of all codes
"""
ans = []
if active:
codes = self.session.query(self.Code).filter(and_(self.Code.newest_version, self.Code.active_code)).all()
else:
codes = self.session.query(self.Code).all()
ans = map(lambda x: self.getTraceback('Code', x.code_id), codes)
return ans
def getAllFilenames(self,
fullPath=True,
startDate=None,
endDate=None,
level=None,
product=None,
code=None,
instrument=None,
exists=None,
newest_version=False,
limit=None):
"""
Return all the file names in the database
:param bool fullPath: Return the fullPath or just filename
:param int level: Filter by given level
:param int product: Filter by given product
:param int limit: Limit number of results
:return: List of strs with the filename
:rtype: list
"""
files = self.getFiles(startDate, endDate, level, product, code, instrument, exists, newest_version, limit)
if fullPath:
# Get file_id instead, saves time since getFileFullPath gets the ID anyway
names = [d.file_id for d in files]
# This is probobly slow, but hopfully not slow enough to be an issue
return map(self.getFileFullPath, names)
else:
return [d.filename for d in files]
def addMission(self,
mission_name,
rootdir,
incoming_dir,
codedir=None,
inspectordir=None,
errordir=None):
"""
Add a mission to the database
Optional directories which are not specified will be inserted
into the database as nulls, and the default will be determined
at runtime.
:param mission_name: the name of the mission
:type mission_name: str
:param rootdir: the root directory of the mission
:type rootdir: str
:param str incoming_dir: directory for incoming files
:param str codedir: directory containing codes (optional; see
:meth:`getCodeDirectory`)
:param str inspectordir: directory containing product inspectors
(optional; see :meth:`getInspectorDirectory`)
:param str errordir: directory to contain error files (optional;
see :meth:`getErrorPath`)
"""
mission_name = str(mission_name)
rootdir = str(rootdir)
try:
m1 = self.Mission()
except AttributeError:
raise (DBError("Class Mission not found was it created?"))
m1.mission_name = mission_name
m1.rootdir = rootdir.replace('{MISSION}', mission_name)
m1.incoming_dir = incoming_dir.replace('{MISSION}', mission_name)
m1.codedir = None if codedir is None \
else codedir.replace('{MISSION}', mission_name)
m1.inspectordir = None if inspectordir is None\
else inspectordir.replace('{MISSION}', mission_name)
if hasattr(m1, 'newest_version'):
# Old DBs will not have this, new ones will
m1.errordir = None if errordir is None \
else errordir.replace('{MISSION}', mission_name)
self.session.add(m1)
self.commitDB()
return m1.mission_id
def addSatellite(self,
satellite_name, mission_id):
"""
Add a satellite to the database
:param satellite_name: the name of the mission
:type satellite_name: str
"""
satellite_name = str(satellite_name)
s1 = self.Satellite()
s1.mission_id = mission_id
s1.satellite_name = satellite_name.replace('{MISSION}', self.getEntry('Mission', mission_id).mission_name)
self.session.add(s1)
self.commitDB()
return s1.satellite_id
def addProcess(self,
process_name,
output_product,
output_timebase,
extra_params=None,
trigger=None):
"""
Add a process to the database
:param process_name: the name of the process
:type process_name: str
:param output_product: the output product id
:type output_product: int
:keyword extra_params: extra parameters to pass to the code
:type extra_params: str
"""
if output_timebase not in ['RUN', 'ORBIT', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY', 'FILE']:
raise (ValueError("output_timebase invalid choice"))
p1 = self.Process()
p1.output_product = output_product
p1.process_name = process_name
p1.extra_params = Utils.toNone(extra_params)
p1.output_timebase = output_timebase
self.session.add(p1)
self.commitDB()
# self.updateProcessSubs(p1.process_id)
return p1.process_id
def addProduct(self,
product_name,
instrument_id,
relative_path,
format,
level,
product_description):
"""
Add a product to the database
:param product_name: the name of the product
:type product_name: str
:param instrument_id: the instrument the product is from
:type instrument_id: int
:param relative_path: relative path for the product
:type relative_path: str
:param format: the format of the product files
:type format: str
"""
p1 = self.Product()
p1.instrument_id = instrument_id
p1.product_name = product_name
p1.relative_path = relative_path
p1.format = format
p1.level = level
p1.product_description = product_description
self.session.add(p1)
self.commitDB()
return p1.product_id
def updateProductSubs(self, product_id):
"""
Update an existing product performing the {} replacements
"""
# need to do {} replacement, have to do it as a modification
p1 = self.getEntry('Product', product_id)
product_id = p1.product_id
product_name = self._nameSubProduct(p1.product_name, product_id)
p1.product_name = product_name
relative_path = self._nameSubProduct(p1.relative_path, product_id)
p1.relative_path = relative_path
fmt = self._nameSubProduct(p1.format, product_id)
p1.format = fmt
self.session.add(p1)
self.commitDB()
def updateInspectorSubs(self, insp_id):
"""
Update an existing inspector performing the {} replacements
"""
# need to do {} replacement, have to do it as a modification
p1 = self.getEntry('Inspector', insp_id)
insp_id = p1.inspector_id
relative_path = self._nameSubInspector(p1.relative_path, insp_id)
p1.relative_path = relative_path
self.session.add(p1)
self.commitDB()
def updateProcessSubs(self, proc_id):
"""
Update an existing product performing the {} replacements
"""
# need to do {} replacement, have to do it as a modification
p1 = self.getEntry('Process', proc_id)
proc_id = p1.process_id
process_name = self._nameSubProcess(p1.process_name, proc_id)
p1.process_name = process_name
extra_params = self._nameSubProcess(p1.extra_params, proc_id)
p1.extra_params = extra_params
self.session.add(p1)
self.commitDB()
def addproductprocesslink(self,
input_product_id,
process_id,
optional,
yesterday=0,
tomorrow=0):
"""
Add a product process link to the database
:param input_product_id: id of the product to link
:type input_product_id: int
:param process_id: id of the process to link
:type process_id: int
:param optional: if the input product is necessary
:type optional: boolean
:param yesterday: How many extra days back do you need
:type yesterday: int
:param tomorrow: How many extra days forward do you need
:type tomorrow: int
"""
ppl1 = self.Productprocesslink()
ppl1.input_product_id = self.getProductID(input_product_id)
ppl1.process_id = self.getProcessID(process_id)
ppl1.optional = optional
#Backwards compatability with old databases
if hasattr(ppl1, 'yesterday'):
ppl1.yesterday = yesterday;
ppl1.tomorrow = tomorrow;
self.session.add(ppl1)
self.commitDB()
return ppl1.input_product_id, ppl1.process_id
def addFilecodelink(self,
resulting_file_id,
source_code):
"""
Add a file code link to the database
:param resulting_file_id: id of the product to link
:type resulting_file_id: int
:param source_code: id of the code
:type source_code: int
"""
fcl1 = self.Filecodelink()
fcl1.resulting_file = resulting_file_id
fcl1.source_code = source_code
self.session.add(fcl1)
self.commitDB()
return fcl1.resulting_file, fcl1.source_code
def delInspector(self, i):