-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathOptimizeRasters.py
7438 lines (7070 loc) · 341 KB
/
OptimizeRasters.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
# ------------------------------------------------------------------------------
# Copyright 2024 Esri
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------------
# Name: OptimizeRasters.py
# Description: Optimizes rasters via gdal_translate/gdaladdo
# Version: 20241024
# Requirements: Python
# Required Arguments: -input -output
# Optional Arguments: -mode -cache -config -quality -prec -pyramids
# -tempinput -tempoutput -subs -clouddownload -cloudupload
# -inputprofile -outputprofile -op -job -inputprofile -outputprofile
# -inputbucket -outputbucket -rasterproxypath -clouddownloadtype -clouduploadtype
# -usetoken
# Usage: python.exe OptimizeRasters.py <arguments>
# Note: OptimizeRasters.xml (config) file is placed alongside OptimizeRasters.py
# OptimizeRasters.py is entirely case-sensitive, extensions/paths in the config
# file are case-sensitive and the program will fail if the correct paths are not
# entered at the cmd-line/UI or in the config file.
# Author: Esri Imagery Workflows team
# ------------------------------------------------------------------------------
# !/usr/bin/env python
# IMPORTANT> Set (CRUN_IN_AWSLAMBDA) to (True) when the OptimizeRasters.py is used within the (lambda_function.zip) to act as a lambda function.
import tarfile
import mimetypes
import fnmatch
from datetime import datetime, timedelta
import binascii
import hashlib
import json
import ctypes
import math
import argparse
import shutil
import subprocess
from xml.dom import minidom
import time
import threading
import mmap
import base64
import os
import sys
def getBooleanValue(value):
if (value is None):
return False
if (isinstance(value, bool)):
return value
val = value
if (not isinstance(val, str)):
val = str(val)
val = val.lower()
if val in ['true', 'yes', 't', '1', 'y']:
return True
return False
CRUN_IN_AWSLAMBDA = getBooleanValue(
os.environ.get('OR_RUNTIME_AWSLAMBDA', False))
CDISABLE_GDAL_CHECK = getBooleanValue(os.environ.get('OR_DISABLE_GDAL', False))
CDisableVersionCheck = getBooleanValue(
os.environ.get('OR_DISABLE_VER_CHECK', False))
if (sys.version_info[0] < 3):
import ConfigParser
from urllib import urlopen, urlencode, quote
from urlparse import urlparse
else:
import configparser as ConfigParser
from urllib.request import urlopen
from urllib.parse import urlencode, urlparse, quote
# ends
# enum error codes
eOK = 0
eFAIL = 1
# ends
CEXEEXT = '.exe'
CONST_OUTPUT_EXT = '.%s' % ('mrf')
CloudOGTIFFExt = '.cogtiff'
COGTIFFAuxFile = '.tif.cogtiff.aux.xml'
UpdateOrjobStatus = 'updateOrjobStatus'
CreateOverviews = 'createOverviews'
DefJpegQuality = 85
# const related to (Reporter) class
CRPT_SOURCE = 'SOURCE'
CRPT_COPIED = 'COPIED'
CRPT_PROCESSED = 'PROCESSED'
CRPT_UPLOADED = 'UPLOADED'
CRPT_HEADER_KEY = 'config'
CPRT_HANDLER = 'handler_resume_reporter'
CRPT_YES = 'yes'
CRPT_NO = 'no'
CRPT_UNDEFINED = ''
# ends
# user hsh const
USR_ARG_UPLOAD = 'upload'
USR_ARG_DEL = 'del'
# ends
# PL
CPLANET_IDENTIFY = 'api.planet.com'
SigAlibaba = 'aliyuncs.com'
# Del delay
CDEL_DELAY_SECS = 20
# ends
CPRJ_NAME = 'ProjectName'
CLOAD_RESTORE_POINT = '__LOAD_RESTORE_POINT__'
CCMD_ARG_INPUT = '__CMD_ARG_INPUT__'
CVSICURL_PREFIX = '/vsicurl/'
# utility const
CSIN_UPL = 'SIN_UPL'
CINC_SUB = 'INC_SUB'
COP_UPL = 'upload'
COP_DNL = 'download'
COP_RPT = 'report'
COP_NOCONVERT = 'noconvert'
COP_LAMBDA = 'lambda'
COP_COPYONLY = 'copyonly'
COP_CREATEJOB = 'createjob'
# ends
# clone specific
CCLONE_PATH = 'clonepath'
# ends
# -cache path
CCACHE_PATH = 'cache'
# ends
# resume constants
CRESUME = '_RESUME_'
CRESUME_MSG_PREFIX = '[Resume]'
CRESUME_ARG = 'resume'
CRESUME_ARG_VAL_RETRYALL = 'retryall'
CRESUME_HDR_INPUT = 'input'
CRESUME_HDR_OUTPUT = 'output'
InputProfile = 'inputprofile'
OutputProfile = 'outputprofile'
# ends
CINPUT_PARENT_FOLDER = 'Input_ParentFolder'
CUSR_TEXT_IN_PATH = 'hashkey'
CRASTERPROXYPATH = 'rasterproxypath'
CTEMPOUTPUT = 'tempoutput'
CTEMPINPUT = 'tempinput'
CISTEMPOUTPUT = 'istempoutput'
CISTEMPINPUT = 'istempinput'
CHASH_DEF_INSERT_POS = 2
CHASH_DEF_CHAR = '#'
CHASH_DEF_SPLIT_CHAR = '@'
UseToken = 'usetoken'
UseTokenOnOuput = 'usetokenonoutput'
CTimeIt = 'timeit'
# const node-names in the config file
CCLOUD_AMAZON = 'amazon'
CCLOUD_AZURE = 'azure'
CCLOUD_GOOGLE = 'google'
CDEFAULT_TIL_PROCESSING = 'DefaultTILProcessing'
# Azure constants
COUT_AZURE_PARENTFOLDER = 'Out_Azure_ParentFolder'
COUT_AZURE_ACCOUNTNAME = 'Out_Azure_AccountName'
COUT_AZURE_ACCOUNTKEY = 'Out_Azure_AccountKey'
COUT_AZURE_CONTAINER = 'Out_Azure_Container'
COUT_AZURE_ACCESS = 'Out_Azure_Access'
COUT_AZURE_PROFILENAME = 'Out_Azure_ProfileName'
CIN_AZURE_PARENTFOLDER = 'In_Azure_ParentFolder'
CIN_AZURE_CONTAINER = 'In_Azure_Container'
COP = 'Op'
# ends
# google constants
COUT_GOOGLE_BUCKET = 'Out_Google_Bucket'
COUT_GOOGLE_PROFILENAME = 'Out_Google_ProfileName'
CIN_GOOGLE_PARENTFOLDER = 'In_Google_ParentFolder'
COUT_GOOGLE_PARENTFOLDER = 'Out_Google_ParentFolder'
# ends
CCLOUD_UPLOAD_THREADS = 20 # applies to both (azure and amazon/s3)
CCLOUD_UPLOAD = 'CloudUpload'
CCLOUD_UPLOAD_OLD_KEY = 'Out_S3_Upload'
COUT_CLOUD_TYPE = 'Out_Cloud_Type'
COUT_S3_PARENTFOLDER = 'Out_S3_ParentFolder'
COUT_S3_ACL = 'Out_S3_ACL'
CIN_S3_PARENTFOLDER = 'In_S3_ParentFolder'
CIN_S3_PREFIX = 'In_S3_Prefix'
CIN_CLOUD_TYPE = 'In_Cloud_Type'
COUT_VSICURL_PREFIX = 'Out_VSICURL_Prefix'
CINOUT_S3_DEFAULT_DOMAIN = 's3.amazonaws.com'
DefS3Region = 'us-east-1'
COUT_DELETE_AFTER_UPLOAD_OBSOLETE = 'Out_S3_DeleteAfterUpload'
COUT_DELETE_AFTER_UPLOAD = 'DeleteAfterUpload'
CFGLogPath = 'LogPath'
TarGz = 'tarGz'
TarGzExt = '.tar.gz'
# ends
# const
CCFG_FILE = 'OptimizeRasters.xml'
CCFG_GDAL_PATH = 'GDALPATH'
# ends
# til related
CTIL_EXTENSION_ = '.til'
# ends
CCACHE_EXT = '.mrf_cache'
CMRF_DOC_ROOT = 'MRF_META' # <{CMRF_DOC_ROOT}> mrf XML root node
CMRF_DOC_ROOT_LEN = len(CMRF_DOC_ROOT) + 2 # includes '<' and '>' in XML node.
# global dbg flags
CS3_MSG_DETAIL = False
CS3_UPLOAD_RETRIES = 3
# ends
# S3Storage direction
CS3STORAGE_IN = 0
CS3STORAGE_OUT = 1
# ends
class TimeIt(object):
Name = 'Name'
Conversion = 'Conversion'
Overview = 'Overview'
Download = 'Download'
Upload = 'Upload'
def __init__(self):
pass
@staticmethod
def timeOperation(func):
def wrapper(*args, **kwargs):
sTime = time.time()
result = func(*args, **kwargs)
if (not result):
return result
eTime = time.time()
if ('name' in kwargs):
if (kwargs['name'] is None):
return result
prevIndex = -1
for i in range(0, len(kwargs['store'].timedInfo['files'])):
if kwargs['name'] in kwargs['store'].timedInfo['files'][i][TimeIt.Name]:
prevIndex = i
break
if (prevIndex == -1):
kwargs['store'].timedInfo['files'].append(
{TimeIt.Name: kwargs['name']})
prevIndex = len(kwargs['store'].timedInfo['files']) - 1
method = 'processing' # default method
if ('method' in kwargs):
method = kwargs['method']
if ('store' in kwargs):
kwargs['store'].timedInfo['files'][prevIndex][method] = '%.3f' % (
eTime - sTime)
return result
return wrapper
class UI(object):
def __init__(self, profileName=None):
self._profileName = profileName
self._errorText = []
self._availableBuckets = []
@property
def errors(self):
return iter(self._errorText)
class ProfileEditorUI(UI):
TypeAmazon = 'amazon'
TypeAzure = 'azure'
TypeGoogle = 'google'
TypeAlibaba = 'alibaba'
def __init__(self, profileName, storageType, accessKey, secretkey, credentialProfile=None, **kwargs):
super(ProfileEditorUI, self).__init__(profileName)
self._accessKey = accessKey
self._secretKey = secretkey
self._storageType = storageType
self._credentialProfile = credentialProfile
self._properties = kwargs
def validateCredentials(self):
try:
azure_storage = None
if (self._storageType == self.TypeAmazon or
self._storageType == self.TypeAlibaba):
import boto3
import botocore.config
import botocore
session = boto3.Session(self._accessKey, self._secretKey,
profile_name=self._credentialProfile if self._credentialProfile else None)
awsCredentials = ConfigParser.RawConfigParser()
rootPath = '.aws'
AwsEndpoint = 'aws_endpoint_url'
AwsAddressingStyle = 'addressing_style'
useAddrStyle = 'virtual'
if (self._credentialProfile):
if (self._storageType == self.TypeAlibaba):
rootPath = '.OptimizeRasters/Alibaba'
userHome = '{}/{}/{}'.format(os.path.expanduser(
'~').replace('\\', '/'), rootPath, 'credentials')
awsCredentials.read(userHome)
if (not awsCredentials.has_section(self._credentialProfile)):
return False
endPoint = awsCredentials.get(self._credentialProfile, AwsEndpoint) if awsCredentials.has_option(
self._credentialProfile, AwsEndpoint) else None
useAddrStyle = awsCredentials.get(self._credentialProfile, AwsAddressingStyle) if awsCredentials.has_option(
self._credentialProfile, AwsAddressingStyle) else useAddrStyle
if (AwsEndpoint in self._properties):
endPoint = self._properties[AwsEndpoint]
if (AwsAddressingStyle in self._properties):
useAddrStyle = self._properties[AwsAddressingStyle]
useAlibaba = endPoint and endPoint.lower().find(SigAlibaba) != -1
con = session.resource('s3', endpoint_url=endPoint, config=botocore.config.Config(
s3={'addressing_style': useAddrStyle}))
# this will throw if credentials are invalid.
[self._availableBuckets.append(i.name)
for i in con.buckets.all()]
elif (self._storageType == self.TypeAzure):
azure_storage = Azure(
self._accessKey, self._secretKey, self._credentialProfile, None)
azure_storage.init()
# this will throw.
[self._availableBuckets.append(
i.name) for i in azure_storage._blobSrvCli.list_containers()]
elif (self._storageType == self.TypeGoogle):
with open(self._profileName, 'r') as reader:
serviceJson = json.load(reader)
Project_Id = 'project_id'
if (Project_Id not in serviceJson):
raise Exception(
'(Project_Id) key isn\'t found in file ({})'.format(self._profileName))
os.environ['GCLOUD_PROJECT'] = serviceJson[Project_Id]
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = self._profileName
try:
from google.cloud import storage
gs = storage.Client()
except Exception as e:
self._errorText.append(str(e))
return False
[self._availableBuckets.append(bucket.name)
for bucket in gs.list_buckets()]
else:
raise Exception('Invalid storage type')
except Exception as e:
MsgInvalidCredentials = 'Invalid Credentials>'
if (self._storageType == self.TypeAmazon or
self._storageType == self.TypeAlibaba):
try:
from botocore.exceptions import ClientError
except ImportError as e:
self._errorText.append(str(e))
return False
if (isinstance(e, ClientError)):
exCode = e.response['Error']['Code'].lower()
if (exCode not in ['invalidaccesskeyid', 'signaturedoesnotmatch']):
# the user may not have the access rights to list buckets but the bucket keys/contents could be accessed if the bucket name is known.
return True
elif (exCode in ['accessdenied']):
# the user has valid credentials but without the bucketlist permission.
return True
elif (self._storageType == self.TypeAzure):
if (azure_storage):
# It's assumed, SAS string credentials aren't allowed to list buckets and the bucket name is picked from the SAS string.
if (azure_storage._SASToken):
self._availableBuckets.append(azure_storage._SASBucket)
return True
self._errorText.append(MsgInvalidCredentials)
self._errorText.append(str(e))
return False
return True
class OptimizeRastersUI(ProfileEditorUI):
def __init__(self, profileName, storageType):
super(OptimizeRastersUI, self).__init__(
profileName, storageType, None, None, profileName)
def getAvailableBuckets(self):
ret = self.validateCredentials()
response = {'response': {'results': ret, 'buckets': []}}
if (not ret):
return response
response['response']['buckets'] = self._availableBuckets
return response
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("sullAvailExtendedVirtual", ctypes.c_ulonglong),
]
def __init__(self):
self.dwLength = ctypes.sizeof(self)
super(MEMORYSTATUSEX, self).__init__()
self.isLinux = os.name == 'posix'
self.CMINSIZEALLOWED = 5242880
def memoryStatus(self):
if (not self.isLinux):
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(self))
return self
def getFreeMem(self):
if (self.isLinux):
try:
return int(int(os.popen("free -b").readlines()[1].split()[2]) * .01)
except Exception as e:
return self.CMINSIZEALLOWED
# download file isn't split in chunks, for now usage is set to 0.01
return int(self.memoryStatus().ullAvailPhys * .01)
def memoryPerDownloadChunk(self):
return self.getFreeMem()
# get upload payload size per thread for the total cloud upload threads required.
def memoryPerUploadChunk(self, totalThreads):
memPerChunk = self.getFreeMem() / totalThreads
if (memPerChunk < self.CMINSIZEALLOWED):
memPerChunk = self.CMINSIZEALLOWED
return memPerChunk
class Lambda:
account_name = 'aws_access_key_id'
account_key = 'aws_secret_access_key'
account_region = 'region'
account_sns = 'sns_arn'
queue_length = 'queuelength'
def __init__(self, base=None):
self._sns_aws_access_key = \
self._sns_aws_secret_access_key = None
self._sns_region = 'us-east-1'
self._sns_ARN = None
self._sns_connection = None
self._aws_credentials = None # aws credential file.
self._base = base
def initSNS(self, keyProfileName):
if (not keyProfileName):
return False
self._aws_credentials = ConfigParser.RawConfigParser()
userHome = '{}/{}/{}'.format(os.path.expanduser(
'~').replace('\\', '/'), '.aws', 'credentials')
with open(userHome) as fptr:
self._aws_credentials.read_file(fptr)
if (not self._aws_credentials.has_section(keyProfileName)):
return False
self._sns_aws_access_key = self._aws_credentials.get(
keyProfileName, self.account_name) if self._aws_credentials.has_option(keyProfileName, self.account_name) else None
self._sns_aws_secret_access_key = self._aws_credentials.get(
keyProfileName, self.account_key) if self._aws_credentials.has_option(keyProfileName, self.account_key) else None
if (self._aws_credentials.has_option(keyProfileName, self.account_region)):
self._sns_region = self._aws_credentials.get(
keyProfileName, self.account_region)
self._sns_ARN = self._aws_credentials.get(keyProfileName, self.account_sns) if self._aws_credentials.has_option(
keyProfileName, self.account_sns) else None
if (not self._sns_aws_access_key or
not self._sns_aws_secret_access_key):
return False
try:
import boto3
session = boto3.Session(aws_access_key_id=self._sns_aws_access_key,
aws_secret_access_key=self._sns_aws_secret_access_key, region_name=self._sns_region)
self._sns_connection = session.resource('sns')
self._sns_connection.meta.client.get_topic_attributes(
TopicArn=self._sns_ARN)
except ImportError as e:
self._base.message('({})/Lambda'.format(str(e)),
self._base.const_critical_text)
return False
except Exception as e:
self._base.message('SNS/init\n{}'.format(str(e)),
self._base.const_critical_text)
return False
return True
def _updateCredentials(self, doc, direction='In'):
inProfileNode = doc.getElementsByTagName(
'{}_S3_AWS_ProfileName'.format(direction))
inKeyIDNode = doc.getElementsByTagName('{}_S3_ID'.format(direction))
inKeySecretNode = doc.getElementsByTagName(
'{}_S3_Secret'.format(direction))
rptProfile = self._base.getUserConfiguration.getValue(
'{}_S3_AWS_ProfileName'.format(direction))
# gives a chance to overwrite the profile name in the parameter file with the orjob one.
_resumeReporter = self._base.getUserConfiguration.getValue(
CPRT_HANDLER)
# unless the orjob was edited manually, the profile name on both would be the same.
if (_resumeReporter):
selectProfile = InputProfile if direction == 'In' else OutputProfile
if (selectProfile in _resumeReporter._header):
rptProfile = _resumeReporter._header[selectProfile]
CERR_MSG = 'Credential keys don\'t exist/invalid'
if ((not len(inProfileNode) or
not inProfileNode[0].hasChildNodes() or
not inProfileNode[0].firstChild) and
not rptProfile):
if (not len(inKeyIDNode) or
not len(inKeySecretNode)):
self._base.message(CERR_MSG, self._base.const_critical_text)
return False
if (not inKeyIDNode[0].hasChildNodes() or
not inKeyIDNode[0].firstChild):
self._base.message(CERR_MSG, self._base.const_critical_text)
return False
else:
keyProfileName = rptProfile if rptProfile else inProfileNode[0].firstChild.nodeValue
if (not self._aws_credentials.has_section(keyProfileName)):
return False
parentNode = doc.getElementsByTagName('Defaults')
if (not len(parentNode)):
self._base.message('Unable to update credentials',
self._base.const_critical_text)
return False
_sns_aws_access_key = self._aws_credentials.get(
keyProfileName, self.account_name) if self._aws_credentials.has_option(keyProfileName, self.account_name) else None
_sns_aws_secret_access_key = self._aws_credentials.get(
keyProfileName, self.account_key) if self._aws_credentials.has_option(keyProfileName, self.account_key) else None
if (len(inKeyIDNode)):
if (inKeyIDNode[0].hasChildNodes() and
inKeyIDNode[0].firstChild.nodeValue):
_sns_aws_access_key = inKeyIDNode[0].firstChild.nodeValue
parentNode[0].removeChild(inKeyIDNode[0])
inKeyIDNode = doc.createElement('{}_S3_ID'.format(direction))
inKeyIDNode.appendChild(
doc.createTextNode(str(_sns_aws_access_key)))
parentNode[0].appendChild(inKeyIDNode)
if (len(inKeySecretNode)):
if (inKeySecretNode[0].hasChildNodes() and
inKeySecretNode[0].firstChild.nodeValue):
_sns_aws_secret_access_key = inKeySecretNode[0].firstChild.nodeValue
parentNode[0].removeChild(inKeySecretNode[0])
inKeySecretNode = doc.createElement(
'{}_S3_Secret'.format(direction))
inKeySecretNode.appendChild(
doc.createTextNode(str(_sns_aws_secret_access_key)))
parentNode[0].appendChild(inKeySecretNode)
if (inProfileNode.length):
parentNode[0].removeChild(inProfileNode[0])
if (not _sns_aws_access_key or
not _sns_aws_secret_access_key):
self._base.message(CERR_MSG, self._base.const_critical_text)
return False
return True
def submitJob(self, orjob):
if (not self._sns_connection or
not orjob):
return False
_orjob = Report(Base())
if (not _orjob.init(orjob) or
not _orjob.read()):
self._base.message('Job file read error',
self._base.const_critical_text)
return False
orjobName = os.path.basename(orjob)
orjobWOExt = orjobName.lower().replace(Report.CJOB_EXT, '')
configPath = _orjob._header['config']
configName = '{}.xml'.format(orjobWOExt)
if (CTEMPINPUT in _orjob._header):
_orjob._header[CTEMPINPUT] = '/tmp/{}/tempinput'.format(orjobWOExt)
if (CTEMPOUTPUT in _orjob._header):
_orjob._header[CTEMPOUTPUT] = '/tmp/{}/tempoutput'.format(
orjobWOExt)
if (CRASTERPROXYPATH in _orjob._header):
_orjob._header['store{}'.format(
CRASTERPROXYPATH)] = _orjob._header[CRASTERPROXYPATH]
_orjob._header[CRASTERPROXYPATH] = '/tmp/{}/{}'.format(
orjobWOExt, CRASTERPROXYPATH)
if ('config' in _orjob._header):
_orjob._header['config'] = '/tmp/{}'.format(configName)
configContent = ''
try:
with open(configPath, 'rb') as f:
configContent = f.read()
except Exception as e:
self._base.message('{}'.format(str(e)),
self._base.const_critical_text)
return False
try:
doc = minidom.parseString(configContent)
# skip looking into the parameter file for credentials if the input is a direct HTTP link with no reqruirement to pre-download the raster/file before processing.
if (not _orjob._isInputHTTP):
if (not self._updateCredentials(doc, 'In')):
return False
if (not self._updateCredentials(doc, 'Out')):
return False
configContent = doc.toprettyxml()
except Exception as e:
self._base.message(str(e), self._base.const_critical_text)
return False
orjobHeader = ''
for hdr in _orjob._header:
# lambda works with AWS key pairs and not profile names.
if (hdr in [InputProfile, OutputProfile]):
continue
orjobHeader += '# {}={}\n'.format(hdr, _orjob._header[hdr])
length = len(_orjob._input_list)
jobQueue = self._base.getUserConfiguration.getValue(self.queue_length)
if (not jobQueue):
# read from orjob/reporter if not in at cmd-line
jobQueue = _orjob._header[self.queue_length] if self.queue_length in _orjob._header else None
if (not jobQueue or
jobQueue and
(jobQueue <= 0 or
jobQueue > length)):
jobQueue = length
i = 0
errLambda = False
functionJobs = []
functionName = None
useLambdaFunction = False
lambdaArgs = _orjob.operation.split(':')
if (len(lambdaArgs) > 2):
if (lambdaArgs[1].lower() == 'function'):
# preserve case in lambda functions.
functionName = lambdaArgs[2]
useLambdaFunction = True
self._base.message('Invoke using ({})'.format(
'Function' if useLambdaFunction else 'SNS'))
while (i < length):
orjobContent = ''
for j in range(i, i + jobQueue):
if (j == length):
break
f = _orjob._input_list[j]
if (f.endswith('/')):
i += 1
continue # skip folder entries
if (not orjobContent):
orjobContent += orjobHeader
orjobContent += '{}\n'.format(f)
i += 1
if (not orjobContent):
continue
store = {'orjob': {'file': '{}_{}{}'.format(orjobWOExt, i, Report.CJOB_EXT), 'content': orjobContent}, 'config': {
'file': configName, 'content': configContent}}
message = json.dumps(store)
if (useLambdaFunction):
functionJobs.append(message)
else:
if (not self.invokeSNS(message)):
errLambda = True
if (useLambdaFunction and
not self.invokeFunction(functionName, functionJobs)):
errLambda = True
return not errLambda
def invokeSNS(self, message):
publish = None
try:
publish = self._sns_connection.meta.client.publish(
TopicArn=self._sns_ARN, Message=message, Subject='OR')
CPUBLISH_META = 'ResponseMetadata'
if (CPUBLISH_META in publish and
'RequestId' in publish[CPUBLISH_META]):
self._base.message('Lambda working on the (RequestID) [{}]...'.format(
publish[CPUBLISH_META]['RequestId']))
except Exception as e:
self._base.message('{}'.format(str(e)),
self._base.const_critical_text)
return False
return True
def invokeFunction(self, functionName, message):
if (not functionName or
not message):
return False
try:
payloads = []
MaxJobs = len(message)
for i in range(0, MaxJobs):
payload = {'Records': [{'Sns': {'Message': message[i]}}]}
payloads.append(payload)
timeStart = datetime.now()
pool = ThreadPool(LambdaFunction, base=self._base, function_name=functionName,
aws_access_key_id=self._sns_aws_access_key, aws_secret_access_key=self._sns_aws_secret_access_key)
pool.init(maxWorkers=100)
for i in range(0, len(payloads)):
pool.addWorker(payloads[i], i)
pool.run()
self._base.getUserConfiguration.getValue(
CPRT_HANDLER).write() # update .orjob status
self._base.message('duration> {}s'.format(
(datetime.now() - timeStart).total_seconds()))
if (pool.isErrorDetected):
return False
except Exception as e:
self._base.message('{}'.format(str(e)),
self._base.const_critical_text)
return False
return True
class LambdaFunction(threading.Thread):
Base = 'base'
def __init__(self, kwargs):
threading.Thread.__init__(self)
self.daemon = True
self.function = None
self.kwargs = kwargs
self.result = None
self.base = None
if (self.Base in kwargs and
isinstance(kwargs[self.Base], Base)):
self.base = kwargs[self.Base]
pass
def init(self, payload, jobID=0):
FunctionName = 'function_name'
if (FunctionName in self.kwargs):
self.function = self.kwargs[FunctionName]
if (self.function is None):
return False
self.payload = payload
self.jobID = jobID
return True
@property
def response(self):
return self.result
def message(self, message, messageType=0):
if (self.base is not None):
if (hasattr(self.base, 'message')):
return self.base.message(message, messageType)
print(message)
def run(self):
try:
import boto3
import boto3.session
session = boto3.session.Session()
client = session.client('lambda', aws_access_key_id=self.kwargs['aws_access_key_id'] if 'aws_access_key_id' in self.kwargs else None,
aws_secret_access_key=self.kwargs['aws_secret_access_key'] if 'aws_secret_access_key' in self.kwargs else None)
self.result = client.invoke(FunctionName=self.function, InvocationType='RequestResponse',
Payload=json.dumps(self.payload))
respJSON = json.loads(self.result['Payload'].read())
if (not respJSON):
return None
respStatus = respJSON['status'] if 'status' in respJSON else None
if (self.base is not None):
report = self.base.getUserConfiguration.getValue(CPRT_HANDLER)
report.syncRemoteToLocal(respJSON)
self.message(
'Completed/{}/Status [{}]'.format(self.jobID, str(respStatus)))
except Exception as e:
# 2 for critical
self.message('{}'.format(
e), self.base.const_critical_text if self.base else 2)
if (self.base is not None):
self.base.getUserConfiguration.setValue(
CCFG_LAMBDA_INVOCATION_ERR, True)
return False
return True
class ThreadPool(object):
DefMaxWorkers = 1
Job = 'job'
JobID = 'jobID'
Base = 'base'
def __init__(self, function, **kwargs):
self.maxWorkers = self.DefMaxWorkers
self.function = function
self.kwargs = kwargs
self.base = None
if (self.Base in kwargs and
isinstance(kwargs[self.Base], Base)):
self.base = kwargs[self.Base]
self.work = []
self._isErrorDetected = False
def init(self, maxWorkers=DefMaxWorkers):
try:
self.maxWorkers = int(maxWorkers)
if (self.maxWorkers < 1):
self.maxWorkers = self.DefMaxWorkers
except BaseException:
self.maxWorkers = self.DefMaxWorkers
def addWorker(self, job, jobID=None):
self.work.append({self.Job: job, self.JobID: jobID})
def message(self, message, messageType=0):
if (self.base is not None):
if (hasattr(self.base, 'message')):
return self.base.message(message, messageType)
print(message)
@property
def isErrorDetected(self):
return self._isErrorDetected
def run(self):
lenBuffer = self.maxWorkers
threads = []
workers = 0
maxWorkers = len(self.work)
while (1):
len_threads = len(threads)
while (len_threads):
alive = [t.is_alive() for t in threads]
countDead = sum(not x for x in alive)
if (countDead):
lenBuffer = countDead
threads = [t for t in threads if t.is_alive()]
break
buffer = []
for i in range(0, lenBuffer):
if (workers == maxWorkers):
break
buffer.append(self.work[workers])
workers += 1
if (not buffer and
not threads):
break
for f in buffer:
try:
t = self.function(self.kwargs)
isJobID = self.JobID in f
if (not t.init(f[self.Job], f[self.JobID] if isJobID else 0)):
return False
t.daemon = True
if (isJobID):
self.message('Started/{}'.format(f[self.JobID]))
t.start()
threads.append(t)
except Exception as e:
self.message(str(e))
continue
if (self.base is not None):
if (self.base.getUserConfiguration.getValue(CCFG_LAMBDA_INVOCATION_ERR)):
self._isErrorDetected = True
return False
return True
class RasterAssociates(object):
RasterAuxExtensions = ['.lrc', '.idx', '.pjg', '.ppng', '.pft', '.pjp',
'.pzp', '.tif.cog.pzp', '.tif.cog.idx', '.tif.cogtiff.aux.xml']
def __init__(self):
self._info = {}
def _stripExtensions(self, relatedExts):
return ';'.join([x.strip() for x in relatedExts.split(';') if x.strip()])
# relatedExts can be a ';' delimited list.
def addRelatedExtensions(self, primaryExt, relatedExts):
if (not primaryExt or
not primaryExt.strip() or
not relatedExts):
return False
for p in primaryExt.split(';'):
p = p.strip()
if (not p):
continue
if (p in self._info):
self._info[p] += ';{}'.format(
self._stripExtensions(relatedExts))
continue
self._info[p] = self._stripExtensions(relatedExts)
return True
@staticmethod
def removeRasterProxyAncillaryFiles(inputPath):
# remove ancillary extension files that are no longer required for (rasterproxy) files on the client side.
refBasePath = inputPath[:-len(CONST_OUTPUT_EXT)]
errorEntries = []
for ext in RasterAssociates.RasterAuxExtensions:
try:
path = refBasePath + ext
if (os.path.exists(path)):
if (path.endswith(COGTIFFAuxFile)):
os.rename(path, path.replace(CloudOGTIFFExt, ''))
continue
os.remove(path)
except Exception as e:
errorEntries.append('{}'.format(str(e)))
return errorEntries
@staticmethod
def findExtension(path):
if (not path):
return False
pos = path.rfind('.')
ext = None
while (pos != -1):
ext = path[pos + 1:]
pos = path[:pos].rfind('.')
return ext
def findPrimaryExtension(self, relatedExt):
_relatedExt = self.findExtension(relatedExt)
if (not _relatedExt):
return False
for primaryExt in self._info:
if (self._info[primaryExt].find(_relatedExt) != -1):
splt = self._info[primaryExt].split(';')
if (_relatedExt in splt):
return primaryExt
return None
def getInfo(self):
return self._info
class Base(object):
# log status types enums
const_general_text = 0
const_warning_text = 1
const_critical_text = 2
const_status_text = 3
# ends
def __init__(self, msgHandler=None, msgCallback=None, userConfig=None):
self._m_log = msgHandler
self._m_msg_callback = msgCallback
self._m_user_config = userConfig
self._lastMsg = ''
if (self._m_msg_callback):
if (self._m_log):
self._m_log.isPrint = False
def init(self):
self.hashInfo = {}
self.timedInfo = {'files': []}
self._modifiedProxies = []
return True
def message(self, msg, status=const_general_text):
if (msg):
self._lastMsg = msg
if (self._m_log):
self._m_log.Message(msg, status)
if (self._m_msg_callback):
self._m_msg_callback(msg, status)
def isLinux(self):
return sys.platform.lower().startswith(('linux', 'darwin'))
def convertToTokenPath(self, inputPath, direction=CS3STORAGE_IN):
if (not inputPath):
return None
tokenPath = None
if (direction == CS3STORAGE_IN):
if (not self.getBooleanValue(self.getUserConfiguration.getValue(UseToken))):
return tokenPath
else:
if (not self.getBooleanValue(self.getUserConfiguration.getValue(UseTokenOnOuput))):
return tokenPath
if (self.getBooleanValue(self.getUserConfiguration.getValue('iss3' if direction == CS3STORAGE_IN else CCLOUD_UPLOAD))):
cloudHandler = self.getSecuredCloudHandlerPrefix(direction)
if (not cloudHandler):
return None
currPrefix = self.getUserConfiguration.getValue(
CIN_S3_PREFIX if direction == CS3STORAGE_IN else COUT_VSICURL_PREFIX, False)