-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEDClient.py
More file actions
2183 lines (1867 loc) · 90.8 KB
/
EDClient.py
File metadata and controls
2183 lines (1867 loc) · 90.8 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
"""
Python Module: 'EDClient' (ECHO Data Client)
Atmospheric Sciences Research Center
Python Env : Anaconda Python (2.7.10)
Revision History:
Version Modification Details
v1.0.0, July 2015 mcb, ASRC
Initial release
v1.1.0, November 2015 mcb, ASRC
Added temporal search capability
v1.2.0, February 2016 mcb, ASRC
Added optional DB tracking capability
"""
import os
import argparse
import datetime as dt
import requests
import math
import lxml.etree as ET
import pycurl
import MySQLdb
from lxml.etree import XMLSyntaxError
from re import sub as resub
__version__ = "1.2.0"
# We should ignore SIGPIPE when using pycurl.NOSIGNAL - see
# the libcurl tutorial for more info.
try:
import signal
from signal import SIGPIPE, SIG_IGN
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
except ImportError:
EDClog.write("EDClient::Problem importing and resetting signals\n")
raise SystemExit
class runManager(object):
def __init__(self):
self.dtStamp = dt.datetime.now()
self.dtStamp = self.dtStamp.replace(microsecond=0)
self.dtString = self.dtStamp.isoformat('T')
self.dtString = self.dtString.replace("-", "_")
self.dtString = self.dtString.replace(":", "_")
self.logfilename = "./EDClient_" + self.dtString + ".log"
self.setLogFH(self.logfilename)
self.setCmdLineArgs()
def setLogFH(self, fname):
try:
self.logfh = open(fname, 'w')
except IOError:
EDClog.write("runManager::setLogFH\n")
EDClog.write("\t***ERROR: Could not open ECHO Data Client Log File ({})\n".format(fname))
raise SystemExit
def getLogFH(self):
return (self.logfh)
def setCmdLineArgs(self):
parser = argparse.ArgumentParser()
parser.add_argument("xmlfile", help="Your ECHO Download Request File (XML format)", type=str)
parser.add_argument("-o", "--opmode", help="Operation mode ('Q' for query only (default), 'D' for download)",
type=str, default='Q')
parser.add_argument("-r", "--resultsize", help="Allowable # of data files to download (Max=2000,Default=1000)",
type=int, default=1000)
parser.add_argument("-s", "--downloadlimit", help="Maximum download size in MegaBytes (Max=5120,Default=3072)",
type=int, default=3072)
args = parser.parse_args()
self.XMLcfgFile = args.xmlfile
self.opMode = args.opmode
self.MAXdataFiles = args.resultsize
self.dwnloadSize = args.downloadlimit
def getopMode(self):
return self.opMode
def getXMLfile(self):
return self.XMLcfgFile
def getMaxFiles(self):
return self.MAXdataFiles
def getDwnLoadLimit(self):
return self.dwnloadSize
class ECHOrequest(object):
"""
This class will validate the ECHO Request information, and keep
track of all collections (and granules) that are requested in
the XML configuration file
"""
# Create an instance of a parser object, and give it the ability
# to remove comments from XML data
parser = ET.XMLParser(remove_comments=True)
def __init__(self, runMgr):
"""EDClient_2015_11_24T08_47_12.log
:param cla: Command line arguments
"""
self.xmlConfigFile = runMgr.getXMLfile()
self.maxDataFiles = runMgr.getMaxFiles()
self.dwnloadLimit = runMgr.getDwnLoadLimit()
self.directoryRoot = ""
self.availDiskSpaceMB = 0.0
self.dataSetQueries = []
self.numDatasetQueries = 0
self.numCollections = 0
self.havePendDwnld = False # assume no pending downloads
self.pdlfile = "pendingDwnld.xml"
# Check to see if there are any pending downloads that
# will need to be processed
if os.access(self.pdlfile, os.F_OK):
try:
self.pdlFH = open(self.pdlfile, 'r')
except IOError:
EDClog.write("ECHOrequest::__init__\n")
EDClog.write("\t***WARNING: Pending download file exists but\n")
EDClog.write("\t***couldn't open file for reading {}\n".format(self.pdlfile))
else:
self.havePendDwnld = True
# Container to hold dataset (collection) objects
self.collContainer = []
if not self.validateRequest():
raise SystemExit
if not self.loadDataSetQueries():
raise SystemExit
if not self.setDiskSpaceAvail():
raise SystemExit
def validateRequest(self):
"""
Using the download request object, check to make sure the XML file can be opened,
return False if not. Then attempt to load the XML content through the lxml etree
parse method. If an error occurs, return False. If all tests pass, the 'EDR' object
will contain the XML root contained in the 'edrRoot' variable, and will then return True.
"""
EDClog.write("ECHOrequest::validateRequest\n")
try:
self.xmlFileObj = open(self.xmlConfigFile, 'r')
except IOError:
EDClog.write("\tCould not open ECHO Download Query File: " + self.xmlConfigFile)
return False
try:
self.edrTree = ET.parse(self.xmlFileObj, self.parser) # Use XML 'parser' define as class variable
except ET.ParseError:
EDClog.write(
"\tCould not parse download request file (" + self.xmlConfigFile + ") please check XML syntax\n")
return False
# Now assign the XML root to 'edrRoot' and check that the root element
# has children
self.edrRoot = self.edrTree.getroot()
if (len(self.edrRoot) == 0):
EDClog.write("\tDownload XML request file has no dataset specifications\n")
return False
# Get DB tracking flag from XML request file, exit if missing
self.dbFlag = self.edrRoot.get('useDB', default="")
if (self.dbFlag != 'True' and self.dbFlag != 'False'):
EDClog.write("\tuseDB flag not set to True or False, check XML request file\n")
return False
dbroot = self.edrRoot.get("dbRoot")
dataroot = self.edrRoot.get("dataRoot")
if dbroot is None or dataroot is None:
EDClog.write("\tMissing DB path or DATA path in XML request file, both required\n")
return False
if dbroot == dataroot:
EDClog.write("\tDB root and DATA root cannot be same path, fix XML request file\n")
return False
if self.dbFlag == 'True':
self.directoryRoot = dbroot
else:
self.directoryRoot = dataroot
# Check to make sure that the directory root exists, and is
# writeable by the user running the script
if (not os.access(self.directoryRoot, os.F_OK)):
EDClog.write("\tDirectory root path in XML request file does not exist\n")
return False
if (not os.access(self.directoryRoot, os.W_OK)):
EDClog.write("\tYou do not have permission to write to " + self.directoryRoot + "\n")
return False
# Check specified number of data files to download.
if (self.maxDataFiles < 1 or self.maxDataFiles > 2000):
EDClog.write("\tInvalid result set size (" + str(self.maxDataFiles) + "), should be >= 1 and <= 2000\n")
return False
# Check download size (MegaBytes). Current maximum is 5GB (5120MB)
if (self.dwnloadLimit <= 0 or self.dwnloadLimit > 5120):
EDClog.write("\tInvalid download size (" + str(self.dwnloadLimit) + "), should be > 0 and <= 5120\n")
return False
# Set available disk space using directory root.
if not self.setDiskSpaceAvail():
EDClog.write("\tCouldn't determine available disk space\n")
return False
EDClog.write("\tRequest valid, continuing\n")
return True
def loadDataSetQueries(self):
"""
Method: loadDataSetQueries
Intent: Build a list of dataset download request queries. This method
validates the XML download request input on the fly and returns
False if problems are found with the input. If no problems are
found, the "EDR" object will contain a new list of the dataset
query objects, and will return True.
"""
bb = {} # spatial bounding box dictionary
vinfo = ""
sdatetime = ""
edatetime = ""
temporal_start_day = ""
temporal_end_day = ""
EDClog.write("ECHOrequest::loadDataSetQueries\n")
for dataset in self.edrRoot:
vFlag = False # dataset criteria flags for version,
bbFlag = False # boundingbox,
tFlag = False
shortName = dataset.get("shortname") # get shortname attribute of dataset
for criteria in dataset:
critname = criteria.tag
if (critname == "boundingbox"):
if ((criteria.get("w") is None) or (criteria.get("s") is None) or
(criteria.get("e") is None) or (criteria.get("n") is None)):
EDClog.write("\tInvalid bounding box attribute in XML input, (valid are 'w','s','e','n')")
return False
else:
bb['w'] = criteria.get('w')
bb['s'] = criteria.get('s')
bb['e'] = criteria.get('e')
bb['n'] = criteria.get('n')
bbFlag = True
elif (critname == "version"):
vinfo = criteria.get("v")
vFlag = True
elif (critname == "temporal"):
tFlag = True
temporalSearchType = criteria.get('type', default="")
if len(temporalSearchType) == 0:
EDClog.write(
"\tMissing temporal search type in XML request file, valid are ('static', 'recurring')")
return False
if (temporalSearchType == "static"):
stFlag = False
etFlag = False
for tcrit in criteria:
if (tcrit.tag == "startdatetime"):
sdatetime = tcrit.get("dtstr", default="")
stFlag = True
if (tcrit.tag == "enddatetime"):
edatetime = tcrit.get("dtstr", default="")
etFlag = True
if (not (stFlag and etFlag)):
EDClog.write("\tMissing elements in static temporal search criteria")
return False
elif (temporalSearchType == "recurring"):
yearFlag = False
startFlag = False
endFlag = False
for tcrit in criteria:
if (tcrit.tag == "year"):
yr_start = tcrit.get("yr_start", default="")
yr_end = tcrit.get("yr_end", default="")
if (len(yr_start) != 0 and len(yr_end) != 0):
if (int(yr_start) > int(yr_end)):
EDClog.write("\tStart year past end year in temporal recurring search criteria")
return False
yearFlag = True
if (tcrit.tag == "start"):
mon_start = tcrit.get("mon_start", default="")
day_start = tcrit.get("day_start", default="")
tim_start = tcrit.get("tim_start", default="")
if (len(mon_start) != 0 and len(day_start) != 0 and len(tim_start) != 0):
if (int(mon_start) < 1 or int(mon_start) > 12):
EDClog.write("\tInvalid start month in temporal recurring search criteria");
return False
if (int(day_start) < 1 or int(day_start) > 31):
EDClog.write("\tInvalid start day in temporal recurring search criteria")
return False
startFlag = True
if (tcrit.tag == "end"):
mon_end = tcrit.get("mon_end", default="")
day_end = tcrit.get("day_end", default="")
tim_end = tcrit.get("tim_end", default="")
if (len(mon_end) != 0 and len(day_end) != 0 and len(tim_end) != 0):
if (int(mon_end) < 1 or int(mon_end) > 12):
EDClog.write("\tInvalid end month in temporal recurring search criteria")
return False
if (int(day_end) < 1 or int(day_end) > 31):
EDClog.write("\tInvalid end day in temporal recurring search criteria")
return False
endFlag = True
if (int(mon_start) > int(mon_end)):
EDClog.write("\tMonth start past month end in temporal recurring search criteria")
return False
if (not (yearFlag and startFlag and endFlag)):
EDClog.write("\tInvalid or missing recurring temporal search criteria")
return False
# Now, since this is a request for a temporal recurring search we need to
# figure out the starting and ending year days based on the use request.
# Bit of a trick here. The ECHO REST specification for a temporal search
# (https://api.echo.nasa.gov/catalog-rest/catalog-docs/index.html) is as
# follows:
#
# At least one of a temporal_start or temporal_end datetime string which
# is then followed by a temporal_start_day and/or temporal_end_day (day
# of year). But because a year might be a leap year we need to make
# sure the temporal_start_day and temporal_end_day encapsulate the recurring
# date range the user requested. To do this, we calculate the day of year
# for the starting month/day for all years and take the minimum and use it
# as the temporal_start_day, and then calculate the day of year for the
# ending month/day for all years and take the maximum and use it as the
# temporal_end_day.
temporal_start_list = []
temporal_end_list = []
intMonStart = int(mon_start)
intDayStart = int(day_start)
intMonEnd = int(mon_end)
intDayEnd = int(day_end)
for yr in range(int(yr_start), int(yr_end) + 1):
sDate = dt.date(yr, intMonStart, intDayStart)
sdoy = sDate.toordinal() - dt.date(yr, 1, 1).toordinal() + 1
temporal_start_list.append(sdoy)
eDate = dt.date(yr, intMonEnd, intDayEnd)
edoy = eDate.toordinal() - dt.date(yr, 1, 1).toordinal() + 1
temporal_end_list.append(edoy)
temporal_start_day = min(temporal_start_list)
temporal_end_day = max(temporal_end_list)
# Now build the 'sdatetime' and 'edatetime' strings for a recurring
# temporal search. Note that the month/day components are used to
# create bounds to encapsulate the user desired starting and ending
# day of year values.
sdatetime = yr_start + '-01-01T' + tim_start
edatetime = yr_end + '-12-31T' + tim_end
else:
EDClog.write("\tInvalid temporal search type, (valid are 'static', 'recurring')")
return False
else:
EDClog.write(
"\tInvalid dataset search criteria (" + critname + ") specified in XML download request file")
return False
if (not (bbFlag and vFlag and tFlag)):
EDClog.write("\tMissing bounding box, version, or temporal criteria in XML input")
return False
self.numDatasetQueries += 1
dsQuery = ECHOdsQuery(shortName, vinfo, bb, temporalSearchType,
sdatetime, edatetime, temporal_start_day, temporal_end_day)
self.dataSetQueries.append(dsQuery)
EDClog.write("\tSuccessful.\n")
return True
def setDiskSpaceAvail(self):
"""
Determine how much disk space is available using directory root
provided by the user. Note that when the ECHO download request
object was created and validated, the directory root was checked
for existence and writeable.
"""
try:
st = os.statvfs(self.directoryRoot)
except OSError:
EDClog.write("ECHOrequest::setDiskSpaceAvail\n")
EDClog.write("\t***ERROR: Couldn't run statvfs on directory root\n")
return False
else:
self.availDiskSpaceMB = st.f_bavail * st.f_frsize / math.pow(1024, 2)
return True
def getDiskSpaceAvail(self):
return self.availDiskSpaceMB
def getDirRoot(self):
return self.directoryRoot
def getReqData(self, eClient):
"""
Retrieve all requested collection and granule information from the ECHO
web service using the 'eClient' object interface
"""
# Keep track of a 'collection counter' (numCollections) since we can't
# rely on every collection/dataset request to be successful (return
# 1, and only 1, collection)
# self.numCollections set to 0 (zero) in __init__
for i in range(self.numDatasetQueries):
queryStr = self.dataSetQueries[i].getDSqueryStr()
collElemRoot = eClient.makeDatasetQuery(queryStr, "echo10")
if ((len(collElemRoot) == 0) or (len(collElemRoot) > 1)):
EDClog.write("ECHOrequest::getReqData\n\t***IGNORING REQUEST\n")
EDClog.write("\tYour dataset query: " + queryStr +
" returned " + str(len(collElemRoot)) +
" results, should be 1, check your query criteria\n")
EDClog.write(ET.tostring(collElemRoot, pretty_print=True))
else:
# If we reach this block we are confident there is 1, and only 1 result
# from the collection query. Create a new collection object with a
# collection element root reference.
result = collElemRoot.find('result')
collID = result.get("echo_dataset_id")
try:
shortName = result.find('Collection').find('ShortName').text
except AttributeError:
shortName = "NoShortName"
try:
archCenter = result.find('Collection').find('ArchiveCenter').text
except AttributeError:
archCenter = "NoArchiveCenter"
try:
collDesc = result.find('Collection').find('Description').text
except AttributeError:
collDesc = "NoDescription"
else:
# v1.2.0 Bug fix. The MODIS data description has embedded unicode
# characters that cause trouble when trying to print the collection
# description as an ASCII string.
collDesc = collDesc.encode('utf-8')
try:
begDateTime = result.find('Collection').find('Temporal').find('RangeDateTime').find(
'BeginningDateTime').text
except AttributeError:
begDateTime = "null"
else:
# Remove trailing 'Z' from datetime value (for DB insert)
begDateTime = resub('[Z]', '', begDateTime)
try:
endDateTime = result.find('Collection').find('Temporal').find('RangeDateTime').find(
'EndingDateTime').text
except AttributeError:
endDateTime = "null"
else:
# Remove trailing 'Z' from datetime value
endDateTime = resub('[Z]', '', endDateTime)
# Locate the additional attributes and extract Digital Object Identifier,
# if one exists.
doiname = "NoDOI"
doiauth = "NoDOIauth"
for attr in collElemRoot.iter('AdditionalAttribute'):
attrname = attr.find('Name').text
if (attrname == 'identifier_product_doi'):
try:
doiname = attr.find('Value').text
except:
doiname = "NoDOI"
if (attrname == 'identifier_product_doi_authority'):
try:
doiauth = attr.find('Value').text
except:
doiauth = "NoDOIauth"
doi = doiauth + '/' + doiname
self.collContainer.append(ECHOcollection(collID, shortName, archCenter,
collDesc, begDateTime, endDateTime,
doi))
# EDClog.write(ET.tostring(collElemRoot, pretty_print=True))
granElemRoot = eClient.makeGranuleQuery(
self.collContainer[self.numCollections].collID,
self.dataSetQueries[i].getSpatialstr(),
self.dataSetQueries[i].getTemporalStr(),
self.maxDataFiles, "echo10")
# EDClog.write(ET.tostring(granElemRoot, pretty_print=True))
# remember, 'self' is the ECHOrequest object, 'collContainer' stores
# the collections objects, which have a method 'getGranules'
self.collContainer[self.numCollections].getGranules(granElemRoot)
self.numCollections += 1
def getHavePendDwnld(self):
return self.havePendDwnld
def getDBflag(self):
return self.dbFlag
def loadPendDwnld(self):
try:
pendTree = ET.parse(self.pdlFH, self.parser) # Use XML 'parser' define as class variable
except ET.ParseError:
EDClog.write("ECHOrequest::loadPendDwnld\n")
EDClog.write("\t***INTERNAL ERROR***\n")
EDClog.write("\tCould not parse pending download file (" + self.pdlfile + ")\n")
raise SystemExit
self.pdlFH.close()
pendRoot = pendTree.getroot()
for c in pendRoot.findall('collection'):
collID = c.find('collID').text
collIndex = self.inCollections(collID)
if collIndex == -1:
# This pending download collection is NOT in the current
# collection container, so add it as a new collection object
shortName = c.find('shortName').text
archCtr = c.find('archCenter').text
collDesc = c.find('collDesc').text
CbegDateTime = c.find('begDateTime').text
CendDateTime = c.find('endDateTime').text
doi = c.find('doi').text
self.collContainer.append(ECHOcollection(collID, shortName, archCtr, collDesc,
CbegDateTime, CendDateTime, doi))
self.numCollections += 1
collIndex = self.numCollections - 1 # 0 based index
else:
EDClog.write("ECHOrequest::loadPendDwnld\n")
EDClog.write("\tPending collection {} already in collection container\n".format(collID))
granRoot = c.find('granules')
for g in granRoot:
polyPoints = []
accessURLs = []
granID = g.find('granID').text
numDwnldTrys = int(g.find('dwnldtrys').text) + 1
granuleUR = g.find('granuleUR').text
sizeMB = float(g.find('sizeMB').text)
GbegDateTime = g.find('begDateTime').text
GendDateTime = g.find('endDateTime').text
spatial = g.find('spatial')
ppts = spatial.find('polyPoints')
if ppts is None:
hasPolyPoints = 0
w_bound = float(spatial.find('w_bound').text)
s_bound = float(spatial.find('s_bound').text)
e_bound = float(spatial.find('e_bound').text)
n_bound = float(spatial.find('n_bound').text)
else:
hasPolyPoints = 1
w_bound = -180.0
s_bound = -90.0
e_bound = 180.0
n_bound = 90.0
for pp in ppts:
lat = float(pp.find('latitude').text)
lon = float(pp.find('longitude').text)
polyPoints.append((lat, lon))
accessURLs.append((g.find('accessURL').text, "NoMimeType"))
localFileName = g.find('localFileName').text
granIndex = self.inGranules(collID, granID)
if granIndex == -1:
# Granule not already in the granule container, add it
self.collContainer[collIndex].granContainer.append(
ECHOgranule(granID, granuleUR, sizeMB,
GbegDateTime, GendDateTime, hasPolyPoints, polyPoints,
w_bound, s_bound, e_bound, n_bound,
accessURLs, localFileName, numDwnldTrys + 1))
else:
EDClog.write("ECHOrequest::loadPendDwnld\n")
EDClog.write("\tPending granule {} already in granule container\n".format(granID))
EDClog.write("\tIncrementing # of download trys\n")
self.collContainer[collIndex].granContainer[granIndex].setnumtrys(numDwnldTrys + 1)
def inCollections(self, cid):
"""
:param cid: A Collection ID
"""
index = 0
for c in self.collContainer:
if c.collID == cid:
return index
index += 1
return -1
def inGranules(self, cid, gid):
"""
:param cid: The Collection Object ID
:param gid: Granule ID to search for in the collection
"""
index = 0
for coll in self.collContainer:
if coll.collID == cid:
for g in coll.granContainer:
if g.egid == gid:
return index
index += 1
return -1
def zapPending(self):
"""
Close and remove the pending download file
"""
self.pdlFH.close()
try:
os.remove(self.pdlfile)
except OSError:
EDClog.write("ECHOrequest::zapPending\n")
EDClog.write("\t****SEVERE: Couldn't remove old pending download file\n".format(self.pdlfile))
raise SystemExit
def savePending(self):
"""
If any downloads failed (status codes -1 (file transfer failed) or -2
(directory make fail), save them as "pending" downloads
"""
haveNewPending = False
for c in self.collContainer:
if c.getFailedStatus():
haveNewPending = True
if haveNewPending:
xmlroot = ET.Element("data")
for c in self.collContainer:
if c.getFailedStatus():
# At least one granule in this collection encountered a download
# failure (-1) or granule directory make failure (-2), or the
# whole collection failed (-2) if the collection directory make failed
coll = ET.SubElement(xmlroot, "collection")
coll_id = ET.SubElement(coll, 'collID')
coll_id.text = c.getid()
coll_sn = ET.SubElement(coll, "shortName")
coll_sn.text = c.getshortname()
coll_ac = ET.SubElement(coll, "archCenter")
coll_ac.text = c.getarchcenter()
coll_desc = ET.SubElement(coll, "collDesc")
coll_desc.text = c.getdesc()
coll_bdt = ET.SubElement(coll, 'begDateTime')
coll_bdt.text = c.getbegdate()
coll_edt = ET.SubElement(coll, 'endDateTime')
coll_edt.text = c.getenddate()
coll_doi = ET.SubElement(coll, 'doi')
coll_doi.text = c.getdoi()
grans = ET.SubElement(coll, "granules")
for g in c.granContainer:
if g.getDownloadStatus() < 0:
gran = ET.SubElement(grans, "granule")
gran_id = ET.SubElement(gran, "granID")
gran_id.text = g.getgranuleid()
gran_trys = ET.SubElement(gran, "dwnldtrys")
gran_trys.text = str(g.getnumtrys())
gran_stat = ET.SubElement(gran, "dwnldstat")
gran_stat.text = str(g.getDownloadStatus())
gran_ur = ET.SubElement(gran, "granuleUR")
gran_ur.text = g.getgranuleur()
gran_size = ET.SubElement(gran, "sizeMB")
gran_size.text = str(g.getGranuleSizeMB())
gran_bdt = ET.SubElement(gran, 'begDateTime')
gran_bdt.text = g.getgranulebd()
gran_edt = ET.SubElement(gran, 'endDateTime')
gran_edt.text = g.getgranuleed()
gran_spatial = ET.SubElement(gran, 'spatial')
if g.getPolyPointStatus():
gran_ppts = ET.SubElement(gran_spatial, 'polyPoints')
ppts = g.getPolyPoints()
for lat, lon in ppts:
pp = ET.SubElement(gran_ppts, 'polyPoint')
pp_lat = ET.SubElement(pp, 'latitude')
pp_lat.text = str(lat)
pp_lon = ET.SubElement(pp, 'longitude')
pp_lon.text = str(lon)
else:
wb = ET.SubElement(gran_spatial, 'w_bound')
wb.text = str(g.getgranulewb())
sb = ET.SubElement(gran_spatial, 's_bound')
sb.text = str(g.getgranulesb())
eb = ET.SubElement(gran_spatial, 'e_bound')
eb.text = str(g.getgranuleeb())
nb = ET.SubElement(gran_spatial, 'n_bound')
nb.text = str(g.getgranulenb())
gran_accurl = ET.SubElement(gran, 'accessURL')
granuleURL, mimeType = g.accessURLs[0]
gran_accurl.text = granuleURL
gran_lf = ET.SubElement(gran, 'localFileName')
gran_lf.text = g.getLocalFileName()
# Things get a little weird here. If there was a pending download
# file, it was read, and processed. Now we have "new" pending
# downloads and must save them, in XML format. We must first try
# to remove and reopen in write mode the old file. If we fail to
# remove and reopen the file, we'll write the pending data to the
# log file and, in earnest, let the user know that manual
# intervention is required after the run
EDClog.write("ECHOrequest::savePending\n")
EDClog.write("\tAttempting to save pending download information...\n")
pendingFileOk = True
try:
self.pdlFH = open(self.pdlfile, 'w')
except IOError:
EDClog.write(
"\t****SEVERE: Couldn't reopen pending download file for writing {}\n".format(self.pdlfile))
pendingFileOk = False
else:
try:
self.pdlFH.write(ET.tostring(xmlroot, pretty_print=True))
except IOError:
EDClog.write("\t****SEVERE: Failed to write to pending download file {}\n".format(self.pdlfile))
pendingFileOk = False
if not pendingFileOk:
EDClog.write("\t****SEVERE: Writing pending download data to log file instead\n")
EDClog.write("\t****SEVERE: You must manually delete old pending download file\n")
EDClog.write("\t****SEVERE: and populate new file with XML data that follows.\n")
EDClog.write(ET.tostring(xmlroot, pretty_print=True))
else:
EDClog.write("\tSuccessful.\n")
class ECHOdsQuery(object):
def __init__(self,
sname, # ECHO dataset short name
ver, # ECHO dataset version
bbox, # ECHO dataset bounding box dictionary
tst, # temporal search type (static or recurring)
sdt, # ECHO dataset start date/time
edt, # ECHO dataset end date/time
tsd, ted): # temporal start and end day values
self.snStr = "?shortName=" + sname
self.vStr = "&version=" + ver
self.bbStr = "&bounding_box=" + bbox['w'] + ',' + bbox['s'] + ',' + bbox['e'] + ',' + bbox['n']
if (tst == "static"):
self.tStr = "&temporal=" + sdt + ',' + edt
else:
# Recurring temporal search
self.tStr = "&temporal=" + sdt + ',' + edt + ',' + str(tsd) + ',' + str(ted)
self.w_bound = bbox['w']
self.s_bound = bbox['s'] # spatial elements to be transferred
self.e_bound = bbox['e'] # to corresponding collection object
self.n_bound = bbox['n']
def getDSqueryStr(self):
return (self.snStr + self.vStr + self.bbStr + self.tStr)
def getSpatialstr(self):
return self.bbStr
def getTemporalStr(self):
return self.tStr
class ECHOclient(object):
"""
Create an ECHO web service client class. When the client
object is created a login attempt is made to the web service.
This class will be used to handle all communication with
the ECHO web service
"""
echoURL = 'https://api.echo.nasa.gov'
echoRestURL = echoURL + "/echo-rest"
echoLoginURL = echoRestURL + "/tokens"
echoProvURL = echoRestURL + "/providers"
echoCatalogURL = echoURL + "/catalog-rest/echo_catalog"
echoCollectionURL = echoCatalogURL + "/datasets"
echoGranuleURL = echoCatalogURL + "/granules"
def __init__(self, maxfiles):
self.maxFiles = maxfiles
self.login()
def login(self):
reqHeaders = {'Content-type': 'application/xml'}
Xmltree = ET.parse('ECHOlogin.xml')
reqDataXml = ET.tostring(Xmltree)
EDClog.write("ECHOclient::login\n")
try:
wsResponse = requests.post(self.echoLoginURL, data=reqDataXml, headers=reqHeaders)
except requests.exceptions.ConnectionError:
EDClog.write("\t***FATAL ERROR: Couldn't make connection to ECHO web service\n")
self.ECHO_TOKEN = "Failed"
else:
# ECHO returns its response in XML format. Use the ElementTree
# method 'fromstring' to encode the XML at 'xmlTreeRoot' (Note:
# <response>.content is the content in bytes NOT unicode which lxml
# ElementTree expects. Create an instance of an XML tree from
# 'ElementTree' class (not currently used). Inside the XML
# document, the ECHO token id is exposed as the 'id' element
try:
tokenRespRoot = ET.fromstring(wsResponse.content)
except XMLSyntaxError:
EDClog.write("\t***FATAL ERROR: XML Syntax Error on login response\n")
self.ECHO_TOKEN = "Failed"
else:
self.ECHO_TOKEN = tokenRespRoot.find('id').text
if self.ECHO_TOKEN == "Failed":
raise SystemExit
else:
EDClog.write("\tSuccessful.\n")
def getProviders(self):
"""
Get a list of data providers from ECHO and store provider ID (key)
and organization name (value) in a dictionary
"""
self.echoProviders = {}
reqHeaders = {'Content-type': 'application/xml',
'Echo-Token': self.ECHO_TOKEN}
provRes = requests.get(self.echoProvURL, headers=reqHeaders)
try:
provRoot = ET.fromstring(provRes.content)
except XMLSyntaxError:
EDClog.write(">>>>Error: ECHOclient.getProviders : XML Syntax Error on provider response")
else:
# Dump XML tree for debugging....
# print(ET.tostring(provRoot))
for prov in provRoot.findall('provider'):
p_id = prov.find('provider_id').text
p_org = prov.find('organization_name').text
self.echoProviders[p_id] = p_org
def listProviders(self):
pkeys = sorted(self.echoProviders.keys())
n = 1
for kw in pkeys:
EDClog.write("{} : {} : {}".format(n, kw, self.echoProviders[kw]))
n += 1
def makeDatasetQuery(self, dsQueryStr, responseFormat):
queryURL = self.echoCollectionURL + '.' + responseFormat + dsQueryStr
reqHeaders = {'Content-type': 'application/xml',
'Echo-Token': self.ECHO_TOKEN}
queryResponse = requests.get(queryURL, headers=reqHeaders)
try:
respRoot = ET.fromstring(queryResponse.content)
except XMLSyntaxError:
EDClog.write(">>>>Error: ECHOclient.makeDatasetQuery : XML Syntax Error on dataset query response")
# In the event of a failure getting the full XML response, create an empty response element root
# to pass back to the caller
respRoot = ET.Element("results")
return respRoot
def makeGranuleQuery(self, echoDSid, boundingBoxStr, temporalStr, maxFiles, responseFormat):
queryURL = self.echoGranuleURL + '.' + responseFormat
queryURL += "?echo_collection_id[]=" + echoDSid + boundingBoxStr + temporalStr
queryURL += "&page_size=" + str(self.maxFiles)
reqHeaders = {'Content-type': 'application/xml',
'Echo-Token': self.ECHO_TOKEN}
# GET request. Note the values stored in the 'headers' dictionary
# are stored as strings! This got me the first time when trying to
# use 'hitsReceived'
queryResponse = requests.get(queryURL, headers=reqHeaders)
hitsReceived = int(queryResponse.headers['echo-hits'])
if (hitsReceived > maxFiles):
EDClog.write("ECHOclient::makeGranuleQuery\n")
EDClog.write("\tYour query (" + queryURL + ")")
EDClog.write("\tgot " + str(
hitsReceived) + " hits, increase 'resultsize' via command line, or refine download request\n")
EDClog.write("\t<Note: forcing 0 collection results because of the volume of hits>\n")
respRoot = ET.Element("results")
else:
try:
respRoot = ET.fromstring(queryResponse.content)
except XMLSyntaxError:
EDClog.write("ECHOclient::makeGranuleQuery\n")
EDClog.write("\t****Error: XML Syntax Error on granule query response")
# In the event of a failure getting the full XML response, create an empty response element root
# to pass back to the caller
respRoot = ET.Element("results")
return respRoot
def logout(self):
tokenURL = self.echoLoginURL + '/' + self.ECHO_TOKEN
logoutResp = requests.delete(tokenURL)
EDClog.write("ECHOclient::logout\n")
EDClog.write("\t***ECHO logout (status: " + str(logoutResp.status_code) + ")\n")
class ECHOcollection(object):
"""
Collection and Dataset are interchangeable names to the same type of object
"""
def __init__(self,
cid, csn, cac, ccd, bdt, edt, doi):
self.collID = cid
self.shortName = csn
self.archCenter = cac
self.collDesc = ccd
self.begDateTime = bdt
self.endDateTime = edt
self.doi = doi
self.granContainer = []
self.numGranules = 0
self.haveFailedDwnlds = False
self.dbInsertFailed = False
def showCollectionInfo(self):
EDClog.write("\n#######################\n")
EDClog.write("##Collection id : {}\n".format(self.collID))
EDClog.write("##Collection shortname: {}\n".format(self.shortName))
EDClog.write("##Collection Arch Ctr : {}\n".format(self.archCenter))
EDClog.write("##Collection Desc : {}\n".format(self.collDesc))
EDClog.write("##Begin Date/Time : {}\n".format(self.begDateTime))
EDClog.write("##End Date/Time : {}\n".format(self.endDateTime))
EDClog.write("##Data Obj. Identifier: {}\n".format(self.doi))
def getGranules(self,
geRoot):
self.granRoot = geRoot
self.numGranules = len(self.granRoot)
if (self.numGranules > 0):
for granule in self.granRoot.findall('result'):
polyPoints = [] # list of polypoint tuples
accessURLs = []
w_bound = -180.0
e_bound = 180.0
s_bound = -90.0
n_bound = 90.0
egid = granule.get("echo_granule_id")
spatialGeometry = granule.find('Granule').find('Spatial').find(
'HorizontalSpatialDomain').find('Geometry')
if spatialGeometry is None:
# No spatial geometry information, which means it's orbit
# information. For now, just store global extent in the
# boundary fields (default initialization above)
HasPolyPoints = 0
else:
boundingRect = spatialGeometry.find('BoundingRectangle')
if boundingRect is None:
boundaryPoints = spatialGeometry.find('GPolygon').find('Boundary')
if boundaryPoints is None:
EDClog.write("ECHOcollection::getGranules\n")
EDClog.write(
"\t***FATAL ERROR: Missing bounding rectangle or Polygon points for granule {}\n".format(
egid))
raise SystemExit
else:
HasPolyPoints = 1
for point in boundaryPoints.findall('Point'):
pt_longitude = float(point.find('PointLongitude').text)
pt_latitude = float(point.find('PointLatitude').text)
polyPoints.append((pt_latitude, pt_longitude))
else: