Repository navigation
Expand file tree
/
Copy pathDButils.py
More file actions
3900 lines (3395 loc) · 144 KB
/
Copy pathDButils.py
File metadata and controls
3900 lines (3395 loc) · 144 KB
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
"""Direct interfacing to dbprocessing databases.
Provides interface specific to dbprocessing databases (not general SQL
databases) and performs most functionality for retrieving, changing, etc.
of records.
"""
from __future__ import absolute_import
from __future__ import print_function
import collections
try:
import collections.abc
except ImportError: # Python 2
collections.abc = collections
import datetime
import getpass
import glob
import itertools
import os
import os.path
import posixpath
import socket # to get the local hostname
import sys
from operator import itemgetter, attrgetter
try:
import urllib.parse # python 3
except ImportError:
import urllib
urllib.parse = urllib
try:
str_classes = (str, unicode)
except NameError:
str_classes = (str,)
import sqlalchemy
import sqlalchemy.engine
import sqlalchemy.schema
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 tables
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):
"""Error in accessing the database"""
pass
class DBProcessingError(Exception):
"""Higher-level error (used only for failures in logging)"""
pass
class FilenameParse(Exception):
"""Not used"""
pass
class DBNoData(Exception):
"""Expected data not found in the database"""
pass
def postgresql_url(databasename):
"""Build postgresl database URL
Environment variable ``PGUSER`` is required. Will also use ``PGHOST``,
``PGPORT`` (requires ``PGHOST``), ``PGPASSWORD`` to define database
server to connect to. Anything unspecified is postgresql default.
Parameters
----------
databasename : :class:`str`
Name of the database
Returns
-------
:class:`str`
Full postgresql URL, suitable for use in
:func:`~sqlalchemy.create_engine`
"""
# If no host, defaults to Unix domain on localhost.
hostport = os.environ.get('PGHOST', '')
if 'PGPORT' in os.environ:
hostport = '{}:{}'.format(hostport, os.environ['PGPORT'])
userpass = os.environ['PGUSER']
if 'PGPASSWORD' in os.environ:
userpass = '{}:{}'.format(userpass, urllib.parse.quote_plus(
os.environ['PGPASSWORD']))
db_url = 'postgresql://{userpass}@{hostport}/{database}'.format(
userpass=userpass, hostport=hostport, database=databasename)
return db_url
class DButils(object):
"""Utility routines for DBProcessing class
All of these may be user called but are meant to
be internal routines for DBProcessing
.. warning::
It is strongly encouraged to make sure the database is closed before
the program terminates, either by calling :meth:`closeDB` or deleting
instances of this object (with an explicit :ref:`del <del>` or by
allowing it to go out of scope.) If this object still exists at
interpreter exit, it will attempt to close the database, but the
functionality to do so may have already been torn down. See for
example `Python issue 39513 <https://bugs.python.org/issue39513>`_.
"""
def __init__(self, mission='Test', db_var=None, echo=False, engine=None):
"""
Initialize the DButils class
Parameters
----------
mission : :class:`str`
Name of the mission. This may be the name of a .sqlite file
or the name of a Postgresql database; see
:ref:`scripts_specifying_database` for Postgresql support
(implemented by :func:`postgresql_url`).
echo : :class:`bool`, default False
if True, the Engine will log all statements as well as a
repr() of their parameter lists to the logger
engine : :class:`str`, optional
DB engine to connect to (e.g sqlite, postgresql).
Defaults to sqlite if mission is an existing file, else
postgresql.
Other Parameters
----------------
db_var
Does nothing
"""
self.dbIsOpen = False
if mission is None:
raise DBError("Must input database name to create DButils instance")
if engine is None:
engine = 'sqlite' if os.path.isfile(os.path.expanduser(mission))\
else 'postgresql'
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()
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):
"""
Print out something useful when one prints the class instance
Returns
-------
str
DBProcessing class instance for mission <mission name>
"""
return 'DBProcessing class instance for mission ' + self.mission + ', version: ' + __version__
####################################
###### DB and Tables ###############
####################################
def openDB(self, engine, db_var=None, verbose=False, echo=False):
"""Setup python to talk to the database
Parameters
----------
engine : :class:`str`
DB engine to connect to
verbose : :class:`bool`, default False
if True, will print out extra debugging
echo : :class:`bool`, default False
if True, the Engine will log all statements as well as a
repr() of their parameter lists to the logger
Other Parameters
----------------
db_var
Does nothing
"""
if self.dbIsOpen == True:
return
if engine == 'sqlite':
if not os.path.isfile(os.path.expanduser(self.mission)):
raise ValueError("DB file specified doesn't exist")
db_url = '{0}:///{1}'.format(engine, os.path.expanduser(
self.mission))
self.mission = os.path.abspath(os.path.expanduser(self.mission))
elif engine == 'postgresql':
db_url = postgresql_url(self.mission)
else:
raise DBError('Unknown engine {}'.format(engine))
try:
engineIns = sqlalchemy.create_engine(db_url, echo=echo)
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" % (engineIns))
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
Parameters
----------
verbose : :class:`bool`, default False
if True, will print out extra debugging
"""
DBlogging.dblogger.debug("Entered _createTableObjects()")
## ask for the table names form the database (does not grab views)
inspector = sqlalchemy.inspect(self.engine)
table_names = inspector.get_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
Ensures not doing 2 at the same time
Returns
-------
:class:`bool` or :class:`int`
False or the current process id
Examples
--------
>>> 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
Parameters
----------
comment : :class:`str`
the comment to enter into the processing log DB
Returns
-------
:class:`bool`
True - Success, False - Failure
"""
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],
getpass.getuser(),
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
Parameters
----------
currently_processing : :class:`bool`
is the db currently processing?
processing_start_time : :class:`~datetime.datetime`
the time the processing started
mission_id : :class:`int`
the :sql:column:`~mission.mission_id` the processing is for
user : :class:`str`
the user doing the processing
hostname : :class:`str`
the hostname that initiated the processing
pid : :class:`int`, optional
the process id that did the processing, default null
processing_end_time : :class:`~datetime.datetime`, optional
the time the processing stopped, default null
comment : :class:`str`
comment about the processing run
Returns
-------
Logging
instance of the class for the :sql:table:`logging` table.
"""
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
Parameters
----------
comment : :class:`str`
a comment to insert into the DB
"""
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 if the file existence on disk matches database record
Parameters
----------
file_id : :class:`int`
:sql:column:`~file.file_id` of the file to check
fix : :class:`bool`, default False
set to have the DB fixed to match the file system
this is **NOT** sure to be safe
Returns
-------
:class:`bool`
True if consistent, False otherwise
"""
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.ProcessqueueLen()
self.session.query(self.Processqueue).delete()
self.commitDB()
DBlogging.dblogger.info("Processqueue was cleared")
return length
def ProcessqueueRemove(self, item, commit = True):
"""
remove a file from the queue by name or number
Parameters
----------
item : :class:`int` or :class:`str`
:sql:column:`~file.filename` or :sql:column:`~file.file_id`
of file to remove from the process queue.
commit : :class:`bool`, default True
Commit changes to the database when done.
"""
# if the input is a file name need to handle that
if isinstance(item, str_classes) \
or not isinstance(item, collections.abc.Iterable):
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
Parameters
----------
version_bump : :class:`bool`, default False
Include the version bump information
Returns
-------
:class:`list`
All :sql:column:`~file.file_id` in the process queue, optionally
the :sql:column:`~processqueue.version_bump` information as well.
"""
pqdata = self.session.query(self.Processqueue).all()
if version_bump:
ans = list(zip(map(attrgetter('file_id'), pqdata), map(attrgetter('version_bump'), pqdata)))
else:
ans = list(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 : :class:`int` or :class:`str`
the :sql:column:`~file.file_id` or :sql:column:`~file.filename`
to put on the process queue.
Returns
-------
file_id : :class:`int`
:sql:column:`~file.file_id` of the file placed on queue,
as 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.select()))).all()
fileid = list(map(itemgetter(0), fileid)) # nested tuples to list
pq = set(self.ProcessqueueGetAll())
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
.. warning::
This might break things if an id is added that does not exist;
it's meant to be fast and used after getting the ids.
IS safe against adding ids that are already in the queue.
Parameters
----------
fileid : :class:`int` or :class:`~collections.abc.Iterable`
the :sql:column:`~file.file_id` or sequence of file ids to add
Returns
-------
num : :class:`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
Returns
-------
:class:`int`
Count of files in the 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 : :class:`int`
the index in the queue to pop
Returns
-------
file_id : :class:`int`
the :sql:column:`~processqueue.file_id` of the :sql:table:`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 : :class:`int`
the :sql:column:`~processqueue.file_id` of the :sql:table:`file`
popped from the queue
"""
if index < 0: # enable the python from the end indexing
index = self.ProcessqueueLen() + 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):
"""Keep only latest version of each file in the process queue.
This is determined by :sql:column:`~file.product_id` and
:sql:column:`~file.utc_file_date`. Also sorts queue by level, date
Parameters
----------
dryrun : :class:`bool`, default False
Do not actually make changes to the queue.
"""
# 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.ProcessqueueLen()))
# pqdata = self.ProcessqueueGetAll(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.ProcessqueueFlush()
# # self.ProcessqueuePush(ans)
# if not any(version_bumps2):
# self.ProcessqueuePush(file_entries2)
# else:
# itertools.starmap(self.ProcessqueuePush, mixed_entries)
# # for v in mixed_entries:
# # itertools.startmap(self.ProcessqueuePush, v)
# else:
# print(
# '<dryrun> Queue cleaned leaving {0} of {1} entries'.format(len(file_entries2), self.ProcessqueueLen()))
#
# DBlogging.dblogger.debug(
# "Done in ProcessqueueClean(), there are {0} entries left".format(self.ProcessqueueLen()))
# # 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.ProcessqueueLen()))
pqdata = self.ProcessqueueGetAll(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.ProcessqueueFlush()
if not version_bump:
self.ProcessqueueRawadd(list(zip(*entries))[0])
else:
for f in pqdata:
self.Processqueueadd(f)
else:
print(
'<dryrun> Queue cleaned leaving {0} of {1} entries'.format(len(file_entries2), self.ProcessqueueLen()))
DBlogging.dblogger.debug(
"Done in ProcessqueueClean(), there are {0} entries left".format(self.ProcessqueueLen()))
def fileIsNewest(self, filename, debug=False):
"""
quesry the database, is this filename or file_id newest version?
Parameters
----------
filename : :class:`int` or :class:`str`
filename or file_id
Returns
-------
:class:`bool`
True 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
Parameters
----------
filename : :class:`str` or :class:`~collections.abc.Iterable`
name of the file to remove (or a list of names)
recursive : :class:`bool`, default False
remove all files that depend on the given file
Other Parameters
----------------
verbose : :class:`bool`, default False
if True, will print out extra debugging
trust_id : :class:`bool`, default False
if True, assumes ``filename`` is a valid file id
commit : :class:`bool`, default True
Commit changes to the database when done.
Examples
--------
>>> pnl._purgeFileFromDB('Test-one_R0_evinst-L1_20100401_v0.1.1.cdf')
"""
# if not an iterable make it a iterable
if isinstance(filename, str_classes) \
or not isinstance(filename, collections.abc.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.ProcessqueueRemove(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
Returns
-------
:class:`dict`
dictionaries of satellite, mission objects
"""
ans = []
sats = self.session.query(self.Satellite).all()
ans = [self.getTraceback('Satellite', x.satellite_id) for x in sats]
return ans
def getAllInstruments(self):
"""
Return dictionaries of instrument traceback dictionaries
Returns
-------
:class:`dict`
dictionaries of instrument traceback dictionaries
"""
ans = []
insts = self.session.query(self.Instrument).all()
ans = [self.getTraceback('Instrument', x.instrument_id) for x in insts]
return ans
def getAllCodes(self, active=True):
"""
Return a list of all codes
Parameters
----------
active : :class:`bool`, default False
Only return codes which are marked :sql:column:`~code.active_code`
and :sql:column:`~code.newest_version`.
Returns
-------
:class:`list`
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 = [self.getTraceback('Code', x.code_id) for x in 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
All parameters are optional; if not specified, default is "all".
Parameters
----------
fullPath : :class:`bool`, default True
Return full path (if False, just filename)
startDate : :class:`~datetime.datetime`, optional
First date to include, based on
:sql:column:`~file.utc_file_date`
endDate : :class:`~datetime.datetime`, optional
Last date to include (inclusive)
level : :class:`float`, optional
Only include files of this level.
product : :class:`int`, optional
:sql:column:`~product.product_id` of files to include
code : :class:`int`, optional
Only return files created by code with ID of
:sql:column:`~code.code_id`
instrument : :class:`int`, optional
Only return files with instrument
:sql:column:`~instrument.instrument_id`
exists : :class:`bool`, default False
Only return files that exist on disk, based on
:sql:column:`~file.exists_on_disk`.
newest_version : :class:`bool`, default False
Only return files that are the newest version
(of their product and date)
limit : :class:`int`
Limit number of results, default all
Returns
-------
:class:`list` of :class:`str`
Filename of all files matching requirements.
"""
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 list(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.
Parameters
----------
mission_name : :class:`str`
the name of the mission
rootdir : :class:`str`
the root directory of the mission
incoming_dir : :class:`str`