/
backend.py
2099 lines (1740 loc) · 105 KB
/
backend.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
import datetime
import json
import logging
import os
import stat
import re
import shutil
import subprocess
import sys
import tempfile
import traceback
import uuid
from decimal import Decimal
from functools import lru_cache, partial, reduce
from pathlib import Path
from subprocess import CalledProcessError
from typing import Callable, Dict, Tuple, Optional, List, Union, Iterable, Mapping
from urllib.parse import urlparse
import flask
import geopyspark as gps
import pkg_resources
import requests
import shapely.geometry.base
from deprecated import deprecated
from geopyspark import TiledRasterLayer, LayerType
from py4j.java_gateway import JVMView, JavaObject
from py4j.protocol import Py4JJavaError
from pyspark import SparkContext
from pyspark.mllib.tree import RandomForestModel
from pyspark.version import __version__ as pysparkversion
from pystac import Collection
from shapely.geometry import box, Polygon
from openeo.internal.process_graph_visitor import ProcessGraphVisitor
from openeo.metadata import TemporalDimension, SpatialDimension, Band, BandDimension
from openeo.util import dict_no_none, rfc3339, deep_get
from openeo_driver import backend
from openeo_driver.ProcessGraphDeserializer import ConcreteProcessing
from openeo_driver.backend import (ServiceMetadata, BatchJobMetadata, OidcProvider, ErrorSummary, LoadParameters,
CollectionCatalog)
from openeo_driver.datacube import DriverVectorCube
from openeo_driver.datastructs import SarBackscatterArgs
from openeo_driver.delayed_vector import DelayedVector
from openeo_driver.dry_run import SourceConstraint
from openeo_driver.errors import (JobNotFinishedException, OpenEOApiException, InternalException,
ServiceUnsupportedException)
from openeo_driver.save_result import ImageCollectionResult
from openeo_driver.users import User
from openeo_driver.util.logging import FlaskRequestCorrelationIdLogging, FlaskUserIdLogging
from openeo_driver.util.utm import area_in_square_meters, auto_utm_epsg_for_geometry
from openeo_driver.utils import EvalEnv, to_hashable, generate_unique_id
from openeogeotrellis import sentinel_hub
from openeogeotrellis.configparams import ConfigParams
from openeogeotrellis.geopysparkdatacube import GeopysparkDataCube, GeopysparkCubeMetadata
from openeogeotrellis.geotrellis_tile_processgraph_visitor import GeotrellisTileProcessGraphVisitor
from openeogeotrellis.job_registry import JobRegistry
from openeogeotrellis.layercatalog import get_layer_catalog, check_missing_products
from openeogeotrellis.logs import elasticsearch_logs
from openeogeotrellis.ml.GeopySparkCatBoostModel import CatBoostClassificationModel
from openeogeotrellis.service_registry import (InMemoryServiceRegistry, ZooKeeperServiceRegistry,
AbstractServiceRegistry, SecondaryService, ServiceEntity)
from openeogeotrellis.traefik import Traefik
from openeogeotrellis.user_defined_process_repository import ZooKeeperUserDefinedProcessRepository, \
InMemoryUserDefinedProcessRepository
from openeogeotrellis.utils import kerberos, zk_client, to_projected_polygons, normalize_temporal_extent, \
truncate_job_id_k8s, dict_merge_recursive, single_value, add_permissions, get_jvm, mdc_include, mdc_remove
from openeogeotrellis.vault import Vault
JOB_METADATA_FILENAME = "job_metadata.json"
logger = logging.getLogger(__name__)
class GpsSecondaryServices(backend.SecondaryServices):
"""Secondary Services implementation for GeoPySpark backend"""
def __init__(self, service_registry: AbstractServiceRegistry):
self.service_registry = service_registry
def service_types(self) -> dict:
return {
"WMTS": {
"title": "Web Map Tile Service",
"configuration": {
"version": {
"type": "string",
"description": "The WMTS version to use.",
"default": "1.0.0",
"enum": [
"1.0.0"
]
},
"colormap": {
"type": "string",
"description": "The colormap to apply to single band layers",
"default": "YlGn"
}
},
"process_parameters": [
# TODO: we should at least have bbox and time range parameters here
],
"links": [],
}
}
def list_services(self, user_id: str) -> List[ServiceMetadata]:
return list(self.service_registry.get_metadata_all(user_id).values())
def service_info(self, user_id: str, service_id: str) -> ServiceMetadata:
return self.service_registry.get_metadata(user_id=user_id, service_id=service_id)
def remove_service(self, user_id: str, service_id: str) -> None:
self.service_registry.stop_service(user_id=user_id, service_id=service_id)
self._unproxy_service(service_id)
def remove_services_before(self, upper: datetime.datetime) -> None:
user_services = self.service_registry.get_metadata_all_before(upper)
for user_id, service in user_services:
self.service_registry.stop_service(user_id=user_id, service_id=service.id)
self._unproxy_service(service.id)
def _create_service(self, user_id: str, process_graph: dict, service_type: str, api_version: str,
configuration: dict) -> str:
# TODO: reduce code duplication between this and start_service()
from openeo_driver.ProcessGraphDeserializer import evaluate
if service_type.lower() != 'wmts':
raise ServiceUnsupportedException(service_type)
service_id = generate_unique_id(prefix="s")
image_collection = evaluate(
process_graph,
env=EvalEnv({
'version': api_version,
'pyramid_levels': 'all',
"backend_implementation": GeoPySparkBackendImplementation(),
})
)
if (isinstance(image_collection, ImageCollectionResult)):
image_collection = image_collection.cube
elif(not isinstance(image_collection,GeopysparkDataCube)):
logger.info("Can not create service for: " + str(image_collection))
raise OpenEOApiException("Can not create service for: " + str(image_collection))
wmts_base_url = os.getenv('WMTS_BASE_URL_PATTERN', 'http://openeo.vgt.vito.be/openeo/services/%s') % service_id
self.service_registry.persist(user_id, ServiceMetadata(
id=service_id,
process={"process_graph": process_graph},
url=wmts_base_url + "/service/wmts",
type=service_type,
enabled=True,
attributes={},
configuration=configuration,
created=datetime.datetime.utcnow()), api_version)
secondary_service = self._wmts_service(image_collection, configuration, wmts_base_url)
self.service_registry.register(service_id, secondary_service)
self._proxy_service(service_id, secondary_service.host, secondary_service.port)
return service_id
def start_service(self, user_id: str, service_id: str) -> None:
from openeo_driver.ProcessGraphDeserializer import evaluate
service: ServiceEntity = self.service_registry.get(user_id=user_id, service_id=service_id)
service_metadata: ServiceMetadata = service.metadata
service_type = service_metadata.type
process_graph = service_metadata.process["process_graph"]
api_version = service.api_version
configuration = service_metadata.configuration
if service_type.lower() != 'wmts':
raise ServiceUnsupportedException(service_type)
image_collection: GeopysparkDataCube = evaluate(
process_graph,
env=EvalEnv({
'version': api_version,
'pyramid_levels': 'all',
"backend_implementation": GeoPySparkBackendImplementation(),
})
)
wmts_base_url = os.getenv('WMTS_BASE_URL_PATTERN', 'http://openeo.vgt.vito.be/openeo/services/%s') % service_id
secondary_service = self._wmts_service(image_collection, configuration, wmts_base_url)
self.service_registry.register(service_id, secondary_service)
self._proxy_service(service_id, secondary_service.host, secondary_service.port)
def _wmts_service(self, image_collection, configuration: dict, wmts_base_url: str) -> SecondaryService:
random_port = 0
jvm = get_jvm()
wmts = jvm.be.vito.eodata.gwcgeotrellis.wmts.WMTSServer.createServer(random_port, wmts_base_url)
logger.info('Created WMTSServer: {w!s} ({u!s}/service/wmts, {p!r})'.format(w=wmts, u=wmts.getURI(), p=wmts.getPort()))
if "colormap" in configuration:
max_zoom = image_collection.pyramid.max_zoom
min_zoom = min(image_collection.pyramid.levels.keys())
reduced_resolution = max(min_zoom,max_zoom-4)
if reduced_resolution not in image_collection.pyramid.levels:
reduced_resolution = min_zoom
histogram = image_collection.pyramid.levels[reduced_resolution].get_histogram()
matplotlib_name = configuration.get("colormap", "YlGn")
#color_map = gps.ColorMap.from_colors(breaks=[x for x in range(0,250)], color_list=gps.get_colors_from_matplotlib("YlGn"))
color_map = gps.ColorMap.build(histogram, matplotlib_name)
srdd_dict = {k: v.srdd.rdd() for k, v in image_collection.pyramid.levels.items()}
wmts.addPyramidLayer("RDD", srdd_dict,color_map.cmap)
else:
srdd_dict = {k: v.srdd.rdd() for k, v in image_collection.pyramid.levels.items()}
wmts.addPyramidLayer("RDD", srdd_dict)
import socket
# TODO what is this host logic about?
host = [l for l in
([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1],
[[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in
[socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]])
if l][0][0]
return SecondaryService(host=host, port=wmts.getPort(), server=wmts)
def restore_services(self):
for user_id, service_metadata in self.service_registry.get_metadata_all_before(upper=datetime.datetime.max):
if service_metadata.enabled:
try:
self.start_service(user_id=user_id, service_id=service_metadata.id)
except:
logger.exception("Error while restoring service: " + str(service_metadata))
def _proxy_service(self, service_id, host, port):
if not ConfigParams().is_ci_context:
with zk_client() as zk:
Traefik(zk).proxy_service(service_id, host, port)
def _unproxy_service(self, service_id):
if not ConfigParams().is_ci_context:
with zk_client() as zk:
Traefik(zk).unproxy_service(service_id)
class SingleNodeUDFProcessGraphVisitor(ProcessGraphVisitor):
def __init__(self):
super().__init__()
self.udf_args = {}
def enterArgument(self, argument_id: str, value):
self.udf_args[argument_id] = value
def constantArgument(self, argument_id: str, value):
self.udf_args[argument_id] = value
class GeoPySparkBackendImplementation(backend.OpenEoBackendImplementation):
def __init__(self, use_zookeeper=True, opensearch_enrich=True):
# TODO: do this with a config instead of hardcoding rules?
self._service_registry = (
InMemoryServiceRegistry() if not use_zookeeper or ConfigParams().is_ci_context
else ZooKeeperServiceRegistry()
)
user_defined_processes = (
# choosing between DBs can be done in said config
InMemoryUserDefinedProcessRepository() if not use_zookeeper or ConfigParams().is_ci_context
else ZooKeeperUserDefinedProcessRepository(hosts=ConfigParams().zookeepernodes)
)
vault = Vault("https://vault.vgt.vito.be")
catalog = get_layer_catalog(vault, opensearch_enrich=opensearch_enrich)
jvm = get_jvm()
conf = SparkContext.getOrCreate().getConf()
principal = conf.get("spark.yarn.principal", conf.get("spark.kerberos.principal"))
key_tab = conf.get("spark.yarn.keytab", conf.get("spark.kerberos.keytab"))
super().__init__(
secondary_services=GpsSecondaryServices(service_registry=self._service_registry),
catalog=catalog,
batch_jobs=GpsBatchJobs(catalog, jvm, principal, key_tab, vault),
user_defined_processes=user_defined_processes,
processing=GpsProcessing(),
)
self._principal = principal
self._key_tab = key_tab
def health_check(self, options: Optional[dict] = None) -> dict:
mode = (options or {}).get("mode", "spark")
if mode == "spark":
# Check if we have a working (Py)Spark context
sc = SparkContext.getOrCreate()
count = sc.parallelize([1, 2, 3], numSlices=2).map(lambda x: x * x).sum()
res = {"mode": "spark", "status": "OK" if count == 14 else "FAIL", "count": count}
elif mode == "jvm":
# Check if we have a working jvm context
jvm = get_jvm()
pi = jvm.Math.PI
res = {"mode": "jvm", "status": "OK" if repr(pi).startswith("3.14") else "FAIL", "pi": repr(jvm.Math.PI)}
else:
res = {"mode": "basic", "status": "OK"}
return res
def oidc_providers(self) -> List[OidcProvider]:
# TODO Move these providers to config or bootstrap script?
default_client_egi = {
"id": "vito-default-client",
"grant_types": [
"authorization_code+pkce",
"urn:ietf:params:oauth:grant-type:device_code+pkce",
"refresh_token",
],
"redirect_urls": [
"https://editor.openeo.org",
"http://localhost:1410/",
]
}
return [
OidcProvider(
id="egi",
issuer="https://aai.egi.eu/auth/realms/egi/",
scopes=[
"openid", "email",
"eduperson_entitlement",
"eduperson_scoped_affiliation",
],
title="EGI Check-in",
default_clients=[default_client_egi],
),
# TODO: remove old EGI provider (issuer https://aai.egi.eu/oidc/)
OidcProvider(
id="egi-legacy",
issuer="https://aai.egi.eu/oidc/",
scopes=[
"openid", "email",
"eduperson_entitlement",
"eduperson_scoped_affiliation",
],
title="EGI Check-in (legacy)",
default_clients=[default_client_egi],
),
# TODO: provide only one EGI Check-in variation? Or only include EGI Check-in dev instance on openeo-dev?
OidcProvider(
id="egi-dev",
issuer="https://aai-dev.egi.eu/auth/realms/egi",
scopes=[
"openid", "email",
"eduperson_entitlement",
"eduperson_scoped_affiliation",
],
title="EGI Check-in (dev)",
default_clients=[default_client_egi],
),
OidcProvider(
id="keycloak",
issuer="https://sso.vgt.vito.be/auth/realms/terrascope",
scopes=["openid", "email"],
title="VITO Keycloak",
),
]
def file_formats(self) -> dict:
return {
"input": {
"GeoJSON": {
"gis_data_types": ["vector"],
"parameters": {},
}
},
"output": {
"GTiff": {
"title": "GeoTiff",
"gis_data_types": ["raster"],
"parameters": {
"tile_grid": {
"type": ["string", "null"],
"description": "Specifies the tile grid to use, for batch jobs only. By default, no tile grid is set, and one Geotiff is generated per date. If a tile grid is set, multiple geotiffs are generated per date, as defined by the specified tiling grid.",
"default": None,
"enum": ["wgs84-1degree", "utm-100km", "utm-20km", "utm-10km"]
},
"ZLEVEL": {
"type": "string",
"description": "Specifies the compression level used for DEFLATE compression. As a number from 1 to 9, lowest and fastest compression is 1 while 9 is highest and slowest compression.",
"default": "6"
},
"sample_by_feature": {
"type": "boolean",
"default": False,
"description": "Set to true to write one output tiff per feature and date. Spatial features can be specified using filter_spatial. This setting is used to sample a data cube at multiple locations in a single job."
},
"feature_id_property": {
"type": ["string", "null"],
"default": None,
"description": "Specifies the name of the feature attribute that is to be used as feature id, by processes that require it. Can be used to link a given output back to an input feature."
},
"overviews": {
"type": "string",
"description": "Specifies the strategy to generate overviews. The default, AUTO, allows the backend to choose an optimal configuration, depending on the size of the generated tiff, and backend capabilities.",
"default": "AUTO",
"enum": ["AUTO", "OFF"]
},
"colormap": {
"type": ["object", "null"],
"description": "Allows specifying a colormap, for single band geotiffs. The colormap is a dictionary mapping band values to colors, specified by an integer.",
"default": None
},
},
},
"PNG": {
"title": "Portable Network Graphics",
"gis_data_types": ["raster"],
"parameters": {
"colormap": {
"type": ["object", "null"],
"description": "Allows specifying a colormap, for single band PNGs. The colormap is a dictionary mapping band values to colors, either specified by an integer or an array of [R, G, B, A], where each value lies between 0.0 and 1.0.",
"default": None
},
}
},
"CovJSON": {
"title": "CoverageJSON",
"gis_data_types": ["other"], # TODO: also "raster", "vector", "table"?
"parameters": {},
},
"netCDF": {
"title": "Network Common Data Form",
"gis_data_types": ["other", "raster"], # TODO: also "raster", "vector", "table"?
"parameters": {
"sample_by_feature": {
"type": "boolean",
"default": False,
"description": "Set to true to write one output netCDF per feature, containing all bands and dates. Spatial features can be specified using filter_spatial. This setting is used to sample a data cube at multiple locations in a single job."
},
"feature_id_property": {
"type": ["string", "null"],
"default": None,
"description": "Specifies the name of the feature attribute that is to be used as feature id, by processes that require it. Can be used to link a given output back to an input feature."
}
},
},
"JSON": {
"gis_data_types": ["raster"],
"parameters": {},
},
"CSV": {
"title": "Comma Separated Values",
"gis_data_types": ["raster"],
"parameters": {}
}
}
}
def load_disk_data(
self, format: str, glob_pattern: str, options: dict, load_params: LoadParameters, env: EvalEnv
) -> GeopysparkDataCube:
logger.info("load_disk_data with format {f!r}, glob {g!r}, options {o!r} and load params {p!r}".format(
f=format, g=glob_pattern, o=options, p=load_params
))
if format != 'GTiff':
raise NotImplementedError("The format is not supported by the backend: " + format)
date_regex = options['date_regex']
if glob_pattern.startswith("hdfs:"):
kerberos(self._principal, self._key_tab)
metadata = GeopysparkCubeMetadata(metadata={}, dimensions=[
# TODO: detect actual dimensions instead of this simple default?
SpatialDimension(name="x", extent=[]), SpatialDimension(name="y", extent=[]),
TemporalDimension(name='t', extent=[]), BandDimension(name="bands", bands=[Band("unknown")])
])
# TODO: eliminate duplication with GeoPySparkLayerCatalog.load_collection
temporal_extent = load_params.temporal_extent
from_date, to_date = normalize_temporal_extent(temporal_extent)
metadata = metadata.filter_temporal(from_date, to_date)
spatial_extent = load_params.spatial_extent
if len(spatial_extent) == 0:
spatial_extent = load_params.global_extent
west = spatial_extent.get("west", None)
east = spatial_extent.get("east", None)
north = spatial_extent.get("north", None)
south = spatial_extent.get("south", None)
crs = spatial_extent.get("crs", None)
spatial_bounds_present = all(b is not None for b in [west, south, east, north])
if spatial_bounds_present:
metadata = metadata.filter_bbox(west=west, south=south, east=east, north=north, crs=crs)
bands = load_params.bands
if bands:
band_indices = [metadata.get_band_index(b) for b in bands]
metadata = metadata.filter_bands(bands)
else:
band_indices = None
jvm = get_jvm()
feature_flags = load_params.get("featureflags", {})
experimental = feature_flags.get("experimental", False)
datacubeParams, single_level = self.catalog.create_datacube_parameters(load_params, env)
extent = jvm.geotrellis.vector.Extent(float(west), float(south), float(east), float(north)) \
if spatial_bounds_present else None
factory = jvm.org.openeo.geotrellis.geotiff.PyramidFactory.from_disk(glob_pattern, date_regex)
if single_level:
if extent is None:
raise ValueError(f"Trying to load disk collection {glob_pattern} without extent.")
projected_polygons = jvm.org.openeo.geotrellis.ProjectedPolygons.fromExtent(extent, crs or "EPSG:4326")
pyramid = factory.datacube_seq(projected_polygons, from_date, to_date, {},"", datacubeParams)
else:
pyramid = (factory.pyramid_seq(extent, crs, from_date, to_date))
temporal_tiled_raster_layer = jvm.geopyspark.geotrellis.TemporalTiledRasterLayer
option = jvm.scala.Option
levels = {pyramid.apply(index)._1(): TiledRasterLayer(LayerType.SPACETIME, temporal_tiled_raster_layer(
option.apply(pyramid.apply(index)._1()), pyramid.apply(index)._2())) for index in
range(0, pyramid.size())}
image_collection = GeopysparkDataCube(
pyramid=gps.Pyramid(levels),
metadata=metadata
)
return image_collection.filter_bands(band_indices) if band_indices else image_collection
def load_result(self, job_id: str, user_id: Optional[str], load_params: LoadParameters,
env: EvalEnv) -> GeopysparkDataCube:
logger.info("load_result from job ID {j!r} with load params {p!r}".format(j=job_id, p=load_params))
spatial_extent = load_params.spatial_extent
west = spatial_extent.get("west", None)
east = spatial_extent.get("east", None)
north = spatial_extent.get("north", None)
south = spatial_extent.get("south", None)
crs = spatial_extent.get("crs", None)
spatial_bounds_present = all(b is not None for b in [west, south, east, north])
if job_id.startswith("http://") or job_id.startswith("https://"):
job_results_canonical_url = job_id
job_results = Collection.from_file(href=job_results_canonical_url)
def reproject(bbox: List[float], crs_from, crs_to) -> List[float]:
from pyproj import Transformer
transform = Transformer.from_crs(crs_from, crs_to, always_xy=True).transform
xmin, ymin = transform(xx=bbox[0], yy=bbox[1])
xmax, ymax = transform(xx=bbox[2], yy=bbox[3])
return [xmin, ymin, xmax, ymax]
def intersects_spatial_extent(item) -> bool:
if not spatial_bounds_present or item.bbox is None:
return True
spatial_extent_epsg4326 = reproject([west, south, east, north],
crs_from=crs or "EPSG:4326",
crs_to="EPSG:4326")
return Polygon.from_bounds(*spatial_extent_epsg4326).intersects(Polygon.from_bounds(*item.bbox))
uris_with_metadata = {asset.get_absolute_href(): (item.datetime.isoformat(),
asset.extra_fields.get("eo:bands", []))
for item in job_results.get_items()
if intersects_spatial_extent(item)
for asset in item.get_assets().values()
if asset.media_type == "image/tiff; application=geotiff"}
timestamped_uris = {uri: timestamp for uri, (timestamp, _) in uris_with_metadata.items()}
try:
eo_bands = single_value(eo_bands for _, eo_bands in uris_with_metadata.values())
band_names = [eo_band["name"] for eo_band in eo_bands]
except ValueError as e:
raise OpenEOApiException(message=f"Unsupported band information for job {job_id}: {str(e)}",
status_code=501)
def load_spatial_bounds_from_job_results():
overall_spatial_extent = job_results.extent.spatial.bboxes[0]
best_epsg = auto_utm_epsg_for_geometry(box(*overall_spatial_extent))
return reproject(overall_spatial_extent, 4326, best_epsg), best_epsg
load_spatial_bounds = load_spatial_bounds_from_job_results
else:
paths_with_metadata = {asset["href"]: (asset.get("datetime"), asset.get("bands", []))
for _, asset in self.batch_jobs.get_results(job_id=job_id, user_id=user_id).items()
if asset["type"] == "image/tiff; application=geotiff"}
if len(paths_with_metadata) == 0:
raise OpenEOApiException(message=f"Job {job_id} contains no results of supported type GTiff.",
status_code=501)
if not all(timestamp is not None for timestamp, _ in paths_with_metadata.values()):
raise OpenEOApiException(
message=f"Cannot load results of job {job_id} because they lack timestamp information.",
status_code=400)
timestamped_uris = {path: timestamp for path, (timestamp, _) in paths_with_metadata.items()}
try:
eo_bands = single_value(eo_bands for _, eo_bands in paths_with_metadata.values())
band_names = [eo_band.name for eo_band in eo_bands]
except ValueError as e:
raise OpenEOApiException(message=f"Unsupported band information for job {job_id}: {str(e)}",
status_code=501)
def load_spatial_bounds_from_job_info():
job_info = self.batch_jobs.get_job_info(job_id, user_id)
return [job_info.bbox[0], job_info.bbox[1], job_info.bbox[2], job_info.bbox[3]], job_info.epsg
load_spatial_bounds = load_spatial_bounds_from_job_info
metadata = GeopysparkCubeMetadata(metadata={}, dimensions=[
# TODO: detect actual dimensions instead of this simple default?
SpatialDimension(name="x", extent=[]), SpatialDimension(name="y", extent=[]),
TemporalDimension(name='t', extent=[]),
BandDimension(name="bands", bands=[Band(band_name) for band_name in band_names])
])
# TODO: eliminate duplication with load_disk_data
temporal_extent = load_params.temporal_extent
from_date, to_date = normalize_temporal_extent(temporal_extent)
metadata = metadata.filter_temporal(from_date, to_date)
bands = load_params.bands
if bands:
band_indices = [metadata.get_band_index(b) for b in bands]
metadata = metadata.filter_bands(bands)
else:
band_indices = None
jvm = get_jvm()
pyramid_factory = jvm.org.openeo.geotrellis.geotiff.PyramidFactory.from_uris(timestamped_uris)
single_level = env.get('pyramid_levels', 'all') != 'all'
if single_level:
existing_bbox, existing_epsg = load_spatial_bounds()
if spatial_bounds_present:
extent = jvm.geotrellis.vector.Extent(float(west), float(south), float(east), float(north))
else:
extent = jvm.geotrellis.vector.Extent(*[float(value) for value in existing_bbox])
crs = "EPSG:4326"
projected_polygons = jvm.org.openeo.geotrellis.ProjectedPolygons.fromExtent(extent, crs)
projected_polygons = (getattr(getattr(jvm.org.openeo.geotrellis, "ProjectedPolygons$"), "MODULE$")
.reproject(projected_polygons, existing_epsg))
metadata_properties = None
correlation_id = None
data_cube_parameters = jvm.org.openeo.geotrelliscommon.DataCubeParameters()
getattr(data_cube_parameters, "layoutScheme_$eq")("FloatingLayoutScheme")
pyramid = pyramid_factory.datacube_seq(projected_polygons, from_date, to_date, metadata_properties,
correlation_id, data_cube_parameters)
else:
extent = (jvm.geotrellis.vector.Extent(float(west), float(south), float(east), float(north))
if spatial_bounds_present else None)
pyramid = pyramid_factory.pyramid_seq(extent, crs, from_date, to_date)
metadata = metadata.filter_bbox(west=extent.xmin(), south=extent.ymin(), east=extent.xmax(),
north=extent.ymax(), crs=crs)
temporal_tiled_raster_layer = jvm.geopyspark.geotrellis.TemporalTiledRasterLayer
option = jvm.scala.Option
# noinspection PyProtectedMember
levels = {pyramid.apply(index)._1(): TiledRasterLayer(LayerType.SPACETIME, temporal_tiled_raster_layer(
option.apply(pyramid.apply(index)._1()), pyramid.apply(index)._2())) for index in
range(0, pyramid.size())}
image_collection = GeopysparkDataCube(
pyramid=gps.Pyramid(levels),
metadata=metadata
)
return image_collection.filter_bands(band_indices) if band_indices else image_collection
def load_ml_model(self, model_id: str) -> 'JavaObject':
def _create_model_dir():
def _set_permissions(job_dir: Path):
if not ConfigParams().is_kube_deploy:
try:
shutil.chown(job_dir, user = None, group = 'eodata')
except LookupError as e:
logger.warning(f"Could not change group of {job_dir} to eodata.")
add_permissions(job_dir, stat.S_ISGID | stat.S_IWGRP) # make children inherit this group
ml_models_path = GpsBatchJobs.get_job_output_dir('ml_models')
if not os.path.exists(ml_models_path):
logger.info("Creating directory: {}".format(ml_models_path))
os.makedirs(ml_models_path)
_set_permissions(ml_models_path)
# Use a random id to avoid collisions.
model_dir_path = ml_models_path / generate_unique_id(prefix="model")
if not os.path.exists(model_dir_path):
logger.info("Creating directory: {}".format(model_dir_path))
os.makedirs(model_dir_path)
_set_permissions(model_dir_path)
return str(model_dir_path)
if model_id.startswith('http'):
# Load the model using its STAC metadata file.
metadata = requests.get(model_id).json()
if deep_get(metadata, "properties", "ml-model:architecture", default=None) is None:
raise OpenEOApiException(
message=f"{model_id} does not specify a model architecture under properties.ml-model:architecture.",
status_code=400)
checkpoints = []
assets = metadata.get('assets', {})
for asset in assets:
if "ml-model:checkpoint" in assets[asset].get('roles', []):
checkpoints.append(assets[asset])
if len(checkpoints) == 0 or checkpoints[0].get("href", None) is None:
raise OpenEOApiException(
message=f"{model_id} does not contain a link to the ml model in its assets section.",
status_code=400)
# TODO: How to handle multiple models?
if len(checkpoints) > 1:
raise OpenEOApiException(
message=f"{model_id} contains multiple checkpoints.",
status_code=400)
# Get the url for the actual model from the STAC metadata.
model_url = checkpoints[0]["href"]
architecture = metadata["properties"]["ml-model:architecture"]
# Download the model to the ml_models folder and load it as a java object.
model_dir_path = _create_model_dir()
if architecture == "random-forest":
dest_path = Path(model_dir_path + "/randomforest.model.tar.gz")
with open(dest_path, 'wb') as f:
f.write(requests.get(model_url).content)
shutil.unpack_archive(dest_path, extract_dir=model_dir_path, format='gztar')
unpacked_model_path = str(dest_path).replace(".tar.gz", "")
logger.info("Loading ml_model using filename: {}".format(unpacked_model_path))
model: JavaObject = RandomForestModel._load_java(sc=gps.get_spark_context(), path="file:" + unpacked_model_path)
elif architecture == "catboost":
filename = Path(model_dir_path + "/catboost_model.cbm")
with open(filename, 'wb') as f:
f.write(requests.get(model_url).content)
logger.info("Loading ml_model using filename: {}".format(filename))
model: JavaObject = CatBoostClassificationModel.load_native_model(str(filename))
else:
raise NotImplementedError("The ml-model architecture is not supported by the backend: " + architecture)
return model
else:
# Load the model using a batch job id.
directory = GpsBatchJobs.get_job_output_dir(model_id)
# TODO: This also needs to support Catboost model
# TODO: This can be done by first reading ml_model_metadata.json in the batch job directory.
model_path = str(Path(directory) / "randomforest.model")
if Path(model_path).exists():
logger.info("Loading ml_model using filename: {}".format(model_path))
model: JavaObject = RandomForestModel._load_java(sc=gps.get_spark_context(), path="file:" + model_path)
elif Path(model_path+".tar.gz").exists():
packed_model_path = model_path+".tar.gz"
shutil.unpack_archive(packed_model_path, extract_dir=directory, format='gztar')
unpacked_model_path = str(packed_model_path).replace(".tar.gz", "")
model: JavaObject = RandomForestModel._load_java(sc=gps.get_spark_context(), path="file:" + unpacked_model_path)
else:
raise OpenEOApiException(
message=f"No random forest model found for job {model_id}",status_code=400)
return model
def visit_process_graph(self, process_graph: dict) -> ProcessGraphVisitor:
return GeoPySparkBackendImplementation.accept_process_graph(process_graph)
@classmethod
def accept_process_graph(cls, process_graph):
if len(process_graph) == 1 and next(iter(process_graph.values())).get('process_id') == 'run_udf':
return SingleNodeUDFProcessGraphVisitor().accept_process_graph(process_graph)
return GeotrellisTileProcessGraphVisitor().accept_process_graph(process_graph)
def summarize_exception(self, error: Exception) -> Union[ErrorSummary, Exception]:
if isinstance(error, Py4JJavaError):
java_exception = error.java_exception
while java_exception.getCause() is not None and java_exception != java_exception.getCause():
java_exception = java_exception.getCause()
java_exception_class_name = java_exception.getClass().getName()
java_exception_message = java_exception.getMessage()
no_data_found = (java_exception_class_name == 'java.lang.AssertionError'
and "Cannot stitch empty collection" in java_exception_message)
is_client_error = java_exception_class_name == 'java.lang.IllegalArgumentException' or no_data_found
summary = "Cannot construct an image because the given boundaries resulted in an empty image collection" if no_data_found else java_exception_message
return ErrorSummary(error, is_client_error, summary)
return error
def changelog(self) -> Union[str, Path]:
roots = []
if Path(__file__).parent.parent.name == "openeo-geopyspark-driver":
# Local dev path
roots.append(Path(__file__).parent.parent)
# Installed package/wheel location
roots.append(Path(sys.prefix) / "openeo-geopyspark-driver")
for root in roots:
if (root / "CHANGELOG.md").exists():
return root / "CHANGELOG.md"
return super().changelog()
def set_request_id(self, request_id: str):
sc = SparkContext.getOrCreate()
jvm = sc._gateway.jvm
mdc_include(sc, jvm, jvm.org.openeo.logging.JsonLayout.RequestId(), request_id)
def user_access_validation(self, user: User, request: flask.Request) -> User:
# TODO: add dedicated method instead of abusing this one?
sc = SparkContext.getOrCreate()
jvm = sc._gateway.jvm
user_id = user.user_id
mdc_include(sc, jvm, jvm.org.openeo.logging.JsonLayout.UserId(), user_id)
return user
def after_request(self):
sc = SparkContext.getOrCreate()
jvm = sc._gateway.jvm
for mdc_key in [jvm.org.openeo.logging.JsonLayout.RequestId(), jvm.org.openeo.logging.JsonLayout.UserId()]:
mdc_remove(sc, jvm, mdc_key)
def set_default_sentinel_hub_credentials(self, client_id: str, client_secret: str):
self.batch_jobs.set_default_sentinel_hub_credentials(client_id, client_secret)
self.catalog.set_default_sentinel_hub_credentials(client_id, client_secret)
def set_terrascope_access_token_getter(self, get_terrascope_access_token: Callable[[User, str], str]):
self.batch_jobs.set_terrascope_access_token_getter(get_terrascope_access_token)
class GpsProcessing(ConcreteProcessing):
def extra_validation(
self, process_graph: dict, env: EvalEnv, result, source_constraints: List[SourceConstraint]
) -> Iterable[dict]:
catalog = env.backend_implementation.catalog
for source_id, constraints in source_constraints:
source_id_proc, source_id_args = source_id
if source_id_proc == "load_collection":
collection_id = source_id_args[0]
metadata = GeopysparkCubeMetadata(catalog.get_collection_metadata(collection_id=collection_id))
if metadata.get("_vito", "data_source", "check_missing_products", default=None):
temporal_extent = constraints.get("temporal_extent")
spatial_extent = constraints.get("spatial_extent")
properties = constraints.get("properties", {})
if temporal_extent is None:
yield {"code": "UnlimitedExtent", "message": "No temporal extent given."}
if spatial_extent is None:
yield {"code": "UnlimitedExtent", "message": "No spatial extent given."}
if temporal_extent is None or spatial_extent is None:
return
products = check_missing_products(
collection_metadata=metadata,
temporal_extent=temporal_extent,
spatial_extent=spatial_extent,
properties=properties,
)
if products:
for p in products:
yield {
"code": "MissingProduct",
"message": f"Tile {p!r} in collection {collection_id!r} is not available."
}
class GpsBatchJobs(backend.BatchJobs):
_OUTPUT_ROOT_DIR = Path("/batch_jobs") if ConfigParams().is_kube_deploy else Path("/data/projects/OpenEO/")
def __init__(self, catalog: CollectionCatalog, jvm: JVMView, principal: str, key_tab: str, vault: Vault):
super().__init__()
self._catalog = catalog
self._jvm = jvm
self._principal = principal
self._key_tab = key_tab
self._default_sentinel_hub_client_id = None
self._default_sentinel_hub_client_secret = None
self._get_terrascope_access_token: Optional[Callable[[User, str], str]] = None
self._vault = vault
def set_default_sentinel_hub_credentials(self, client_id: str, client_secret: str):
self._default_sentinel_hub_client_id = client_id
self._default_sentinel_hub_client_secret = client_secret
def set_terrascope_access_token_getter(self, get_terrascope_access_token: Callable[[User, str], str]):
self._get_terrascope_access_token = get_terrascope_access_token
def create_job(
self, user_id: str, process: dict, api_version: str,
metadata: dict, job_options: dict = None
) -> BatchJobMetadata:
job_id = generate_unique_id(prefix="j")
title = metadata.get("title")
description = metadata.get("description")
with JobRegistry() as registry:
job_info = registry.register(
job_id=job_id,
user_id=user_id,
api_version=api_version,
specification=dict_no_none(
process_graph=process["process_graph"],
job_options=job_options,
),
title=title, description=description,
)
return BatchJobMetadata(
id=job_id, process=process, status=job_info["status"],
created=rfc3339.parse_datetime(job_info["created"]), job_options=job_options,
title=title, description=description,
)
def get_job_info(self, job_id: str, user_id: str) -> BatchJobMetadata:
with JobRegistry() as registry:
job_info = registry.get_job(job_id, user_id)
return JobRegistry.job_info_to_metadata(job_info)
def poll_sentinelhub_batch_processes(self, job_info: dict, sentinel_hub_client_alias: str,
vault_token: Optional[str]):
# TODO: split polling logic and resuming logic?
job_id, user_id = job_info['job_id'], job_info['user_id']
def batch_request_details(batch_process_dependency: dict) -> Dict[str, Tuple[str, Callable[[], None]]]:
"""returns an ID -> (status, retrier) for each batch request ID in the dependency"""
collection_id = batch_process_dependency['collection_id']
metadata = GeopysparkCubeMetadata(self._catalog.get_collection_metadata(collection_id))
layer_source_info = metadata.get("_vito", "data_source", default={})
endpoint = layer_source_info['endpoint']
bucket_name = layer_source_info.get('bucket', sentinel_hub.OG_BATCH_RESULTS_BUCKET)
logger.debug(f"Sentinel Hub client alias: {sentinel_hub_client_alias}", extra={'job_id': job_id,
'user_id': user_id})
if sentinel_hub_client_alias == 'default':
sentinel_hub_client_id = self._default_sentinel_hub_client_id
sentinel_hub_client_secret = self._default_sentinel_hub_client_secret
else:
sentinel_hub_client_id, sentinel_hub_client_secret = (
self._vault.get_sentinel_hub_credentials(sentinel_hub_client_alias, vault_token))
batch_processing_service = self._jvm.org.openeo.geotrellissentinelhub.BatchProcessingService(
endpoint, bucket_name, sentinel_hub_client_id, sentinel_hub_client_secret,
','.join(ConfigParams().zookeepernodes), f"/openeo/rlguard/access_token_{sentinel_hub_client_alias}"
)
batch_request_ids = (batch_process_dependency.get('batch_request_ids') or
[batch_process_dependency['batch_request_id']])
def retrier(request_id: str) -> Callable[[], None]:
def retry():
assert request_id is not None, "retry is for PARTIAL statuses but a 'None' request_id is DONE"
logger.warning(f"retrying Sentinel Hub batch process {request_id} for batch job {job_id}",
extra={'job_id': job_id, 'user_id': user_id})
batch_processing_service.restart_partially_failed_batch_process(request_id)
return retry
# TODO: prevent requests for duplicate (recycled) batch request IDs
return {request_id: (batch_processing_service.get_batch_process(request_id),
retrier(request_id)) for request_id in batch_request_ids if request_id is not None}
dependencies = job_info.get('dependencies') or []
batch_processes = reduce(partial(dict_merge_recursive, overwrite=True),
(batch_request_details(dependency) for dependency in dependencies))
batch_process_statuses = {batch_request_id: details.status()
for batch_request_id, (details, _) in batch_processes.items()}
logger.debug("Sentinel Hub batch process statuses for batch job {j}: {ss}"
.format(j=job_id, ss=batch_process_statuses), extra={'job_id': job_id, 'user_id': user_id})