-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathviews.py
More file actions
2262 lines (1982 loc) · 97.3 KB
/
views.py
File metadata and controls
2262 lines (1982 loc) · 97.3 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
import copy
import functools
import json
import logging
import os
import pathlib
import re
import textwrap
import typing
from collections import defaultdict, namedtuple
from typing import Callable, List, Optional, Tuple, Union
from urllib.parse import urlparse
import flask
import flask_cors
from flask import (
Blueprint,
Flask,
abort,
current_app,
g,
jsonify,
make_response,
redirect,
request,
send_from_directory,
url_for,
)
import openeo.metadata
from openeo.util import Rfc3339, TimingLogger, deep_get, dict_no_none, rfc3339
from openeo.utils.version import ComparableVersion
from pyproj import CRS
import shapely.geometry
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.middleware.proxy_fix import ProxyFix
from openeo_driver.backend import (
BatchJobMetadata,
BatchJobs,
ErrorSummary,
JobListing,
OpenEoBackendImplementation,
ServiceMetadata,
UserDefinedProcessMetadata,
function_has_argument,
is_not_implemented,
)
from openeo_driver.config import OpenEoBackendConfig, get_backend_config
from openeo_driver.constants import (
DEFAULT_LOG_LEVEL_PROCESSING,
DEFAULT_LOG_LEVEL_RETRIEVAL,
ITEM_LINK_PROPERTY,
JOB_STATUS,
STAC_EXTENSION,
)
from openeo_driver.datacube import DriverMlModel
from openeo_driver.errors import (
FeatureUnsupportedException,
FilePathInvalidException,
InternalException,
JobNotFinishedException,
NotFoundException,
OpenEOApiException,
ProcessGraphInvalidException,
ProcessGraphMissingException,
ProcessGraphNotFoundException,
ProcessUnsupportedException,
ServiceNotFoundException,
)
from openeo_driver.integrations.s3.bucket_details import BucketDetails
from openeo_driver.jobregistry import PARTIAL_JOB_STATUS
from openeo_driver.processgraph import ProcessGraphFlatDict, extract_default_job_options_from_process_graph
from openeo_driver.save_result import SaveResult, to_save_result
from openeo_driver.users import User, user_id_b64_decode, user_id_b64_encode
from openeo_driver.users.auth import HttpAuthHandler
from openeo_driver.util.geometry import BoundingBox, reproject_geometry
from openeo_driver.util.logging import ExtraLoggingFilter, FlaskRequestCorrelationIdLogging
from openeo_driver.util.stac import sniff_stac_extension_prefix
from openeo_driver.utils import EvalEnv, filter_supported_kwargs, smart_bool
_log = logging.getLogger(__name__)
ApiVersionInfo = namedtuple("ApiVersionInfo", ["version", "supported", "wellknown", "production"])
# TODO: move this version info listing and default version configurable too?
# TODO #382 deprecate API_VERSIONS in favor of OPENEO_API_VERSIONS
# Available OpenEO API versions: map of URL version component to API version info
OPENEO_API_VERSIONS = API_VERSIONS = {
"1.0.0": ApiVersionInfo(version="1.0.0", supported=True, wellknown=False, production=True),
"1.0": ApiVersionInfo(version="1.0.0", supported=True, wellknown=True, production=True),
"1.0.1": ApiVersionInfo(version="1.0.1", supported=True, wellknown=False, production=True),
"1.1.0": ApiVersionInfo(version="1.1.0", supported=True, wellknown=False, production=False),
"1.1": ApiVersionInfo(version="1.1.0", supported=True, wellknown=True, production=True),
"1.2": ApiVersionInfo(version="1.2.0", supported=True, wellknown=True, production=True),
"1": ApiVersionInfo(version="1.2.0", supported=True, wellknown=False, production=True),
}
# TODO #382 deprecate API_VERSION_DEFAULT in favor of OPENEO_API_VERSION_DEFAULT
OPENEO_API_VERSION_DEFAULT = API_VERSION_DEFAULT = "1.2"
_log.info(f"{OPENEO_API_VERSIONS=} {OPENEO_API_VERSION_DEFAULT=}")
STREAM_CHUNK_SIZE_DEFAULT = 10 * 1024
class OpenEoApiApp(Flask):
def __init__(self, import_name):
super().__init__(import_name=import_name)
# Make sure app handles reverse proxy aspects (e.g. HTTPS) correctly.
self.wsgi_app = ProxyFix(self.wsgi_app)
# Setup up general CORS headers (for all HTTP methods)
flask_cors.CORS(
self,
origins="*",
send_wildcard=True,
supports_credentials=False,
allow_headers=["Content-Type", "Authorization", "Range"],
expose_headers=["Location", "OpenEO-Identifier", "OpenEO-Costs", "Link","Accept-Ranges","Content-Range", "Content-Encoding"]
)
def make_default_options_response(self):
# Customization of OPTIONS response
rv = super().make_default_options_response()
rv.status_code = 204
rv.content_type = "application/json"
return rv
def build_app(
backend_implementation: OpenEoBackendImplementation,
error_handling=True,
import_name=__name__,
) -> OpenEoApiApp:
"""
Build Flask app serving the endpoints that are implemented in given backend implementation
After building the flask app you can configure it with standard flask configuration tools
(https://flask.palletsprojects.com/en/2.0.x/config/).
Some example patterns used in various places:
# Build app
app = build_app(backend_implementation=backend_implementation)
# Directly set config values
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'oeo.net'
:param backend_implementation:
:param import_name:
:return:
"""
app = OpenEoApiApp(import_name=import_name)
@app.url_defaults
def _add_version(endpoint, values):
"""Blueprint.url_defaults handler to automatically add "version" argument in `url_for` calls."""
# TODO #382 use key "openeo_api_version" for clarity instead of "version"?
if "version" not in values and current_app.url_map.is_endpoint_expecting(
endpoint, "version"
):
values["version"] = g.get("request_version", OPENEO_API_VERSION_DEFAULT)
@app.url_value_preprocessor
def _pull_version(endpoint, values):
"""Get API version from request and store in global context"""
# TODO #382 use key "openeo_api_version" for clarity instead of "version"?
version = (values or {}).pop("version", OPENEO_API_VERSION_DEFAULT)
if not (version in OPENEO_API_VERSIONS and OPENEO_API_VERSIONS[version].supported):
raise OpenEOApiException(
status_code=501,
code="UnsupportedApiVersion",
message="Unsupported version component in URL: {v!r}. Available versions: {s!r}".format(
v=version, s=[k for k, v in OPENEO_API_VERSIONS.items() if v.supported]
)
)
g.request_version = version
g.openeo_api_version = OPENEO_API_VERSIONS[version].version
@app.before_request
def _before_request():
FlaskRequestCorrelationIdLogging.before_request()
backend_implementation.set_request_id(FlaskRequestCorrelationIdLogging.get_request_id())
# Log some info about request
data = request.data
if len(data) > 1000:
data = repr(data[:1000] + b'...') + ' ({b} bytes)'.format(b=len(data))
else:
data = repr(data)
_log.info("Handling {method} {url} with data {data}".format(
method=request.method, url=request.url, data=data
))
@app.after_request
def _after_request(response):
request_id = FlaskRequestCorrelationIdLogging.get_request_id()
backend_implementation.after_request(request_id)
response.headers["Request-Id"] = request_id
return response
if error_handling:
register_error_handlers(app=app, backend_implementation=backend_implementation)
# Note: /.well-known/openeo should be available directly under domain, without version prefix.
@app.route('/.well-known/openeo', methods=['GET'])
@backend_implementation.cache_control
def well_known_openeo():
return jsonify(
{
"versions": [
{
"url": url_for("openeo.index", version=k, _external=True),
"api_version": v.version,
"production": v.production,
}
for k, v in OPENEO_API_VERSIONS.items()
if v.wellknown
]
}
)
@app.route('/', methods=['GET'])
def redirect_root():
return redirect(url_for('openeo.index'))
auth = HttpAuthHandler(
oidc_providers=backend_implementation.oidc_providers(),
user_access_validation=backend_implementation.user_access_validation,
config=backend_implementation.config,
)
# Allow access to auth handler from other parts of the app
app.extensions["auth_handler"] = auth
api_reg = EndpointRegistry()
bp = Blueprint("openeo", import_name=__name__)
register_views_general(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
register_views_auth(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.catalog:
register_views_catalog(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.processing:
register_views_processing(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.batch_jobs:
register_views_batch_jobs(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.secondary_services:
register_views_secondary_services(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.user_defined_processes:
register_views_udp(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
if backend_implementation.user_files:
register_views_user_files(
blueprint=bp, backend_implementation=backend_implementation, api_endpoint=api_reg, auth_handler=auth
)
app.register_blueprint(bp, url_prefix='/openeo', name="openeo_old") # TODO: do we still need this?
app.register_blueprint(bp, url_prefix='/openeo/<version>')
# Build endpoint metadata dictionary
# TODO: find another way to pass this to `index()`
global _openeo_endpoint_metadata
_openeo_endpoint_metadata = api_reg.get_path_metadata(bp)
# Load flask settings from config.
app.config.from_mapping(get_backend_config().flask_settings)
return app
def requested_api_version() -> ComparableVersion:
"""
Get the currently requested API version
(`ApiVersionInfo.version` which is typically in "major.minor.patch" resolution)
as a ComparableVersion object
"""
return ComparableVersion(g.openeo_api_version)
def register_error_handlers(app: flask.Flask, backend_implementation: OpenEoBackendImplementation):
"""Register error handlers to the app"""
# Dedicated log channel for unhandled exceptions (unhandled by the view functions internally)
_log = logging.getLogger(f"{__name__}.error")
@app.errorhandler(HTTPException)
def handle_http_exceptions(error: HTTPException):
"""Error handler for werkzeug HTTPException"""
# Convert to OpenEOApiException based handling
return handle_openeoapi_exception(OpenEOApiException(
message=str(error),
code="NotFound" if isinstance(error, NotFound) else "Internal",
status_code=error.code
))
@app.errorhandler(OpenEOApiException)
def handle_openeoapi_exception(error: OpenEOApiException, log_message: Optional[str] = None):
"""Error handler for OpenEOApiException"""
_log.error(log_message or repr(error), extra={"openeo_error_code": error.code}, exc_info=True)
# most_recent_exception = sys.exc_info()[1]
# fmt = Format(max_value_str_len=1000)
# _log.error(
# "Sync request error stack trace with locals",
# extra={"exc_info_with_locals": format_exc(most_recent_exception, fmt=fmt)},
# )
error_dict = error.to_dict()
return jsonify(error_dict), error.status_code
@app.errorhandler(Exception)
def handle_error(error: Exception):
"""Generic error handler"""
# TODO: is it possible to eliminate this custom summarize_exception/ErrorSummary handling?
error = backend_implementation.summarize_exception(error)
if isinstance(error, ErrorSummary):
log_message = error.summary
if error.is_client_error:
api_error = OpenEOApiException(message=error.summary, code="BadRequest", status_code=400)
else:
api_error = InternalException(message=error.summary)
else:
log_message = repr(error)
api_error = InternalException(message=repr(error))
return handle_openeoapi_exception(api_error, log_message=log_message)
def response_204_no_content():
return make_response('', 204, {"Content-Type": "application/json"})
EndpointMetadata = namedtuple("EndpointMetadata", ["hidden", "for_version"])
class EndpointRegistry:
"""
Registry of OpenEO API endpoints, to be used as decorator with flask view functions.
Allows setting some additional metadata and automatic generation of
the OpenEO API endpoints listing in the "capabilities" endpoint.
"""
def __init__(self):
self._endpoints = {}
def add_endpoint(self, view_func: Callable, hidden=False, version: Callable = None):
"""Register endpoint metadata"""
self._endpoints[view_func.__name__] = EndpointMetadata(hidden=hidden, for_version=version)
return view_func
def __call__(self, view_func: Callable = None, *, hidden=False, version: Callable = None):
if view_func is None:
# Decorator with arguments: return wrapper to call with decorated function.
return functools.partial(self.add_endpoint, hidden=hidden, version=version)
else:
# Argument-less decorator call: we already have the function to wrap, use default options.
return self.add_endpoint(view_func)
def get_path_metadata(self, blueprint: Blueprint) -> List[Tuple[str, set, EndpointMetadata]]:
"""
Join registered blueprint routes with endpoint metadata
and get a listing of (path, methods, metadata) tuples
:return:
"""
app = Flask("dummy")
app.register_blueprint(blueprint)
metadata = []
for rule in app.url_map.iter_rules():
if rule.endpoint.startswith(blueprint.name + '.'):
name = rule.endpoint.split('.', 1)[1]
if name in self._endpoints:
metadata.append((rule.rule, rule.methods.difference({'HEAD', 'OPTIONS'}), self._endpoints[name]))
return metadata
@staticmethod
def get_capabilities_endpoints(metadata: List[Tuple[str, set, EndpointMetadata]], api_version) -> List[dict]:
"""
Extract "capabilities" endpoint listing from metadata list
"""
endpoint_methods = defaultdict(set)
for path, methods, info in metadata:
if not info.hidden and (info.for_version is None or info.for_version(api_version)):
endpoint_methods[path].update(methods)
endpoints = [
{"path": p.replace('<', '{').replace('>', '}'), "methods": list(ms)}
for p, ms in endpoint_methods.items()
]
return endpoints
def register_views_general(
blueprint: Blueprint, backend_implementation: OpenEoBackendImplementation, api_endpoint: EndpointRegistry,
auth_handler: HttpAuthHandler
):
@blueprint.route('/')
@backend_implementation.cache_control
def index():
backend_config: OpenEoBackendConfig = get_backend_config()
api_version = requested_api_version().to_string()
title = backend_config.capabilities_title
backend_version = backend_config.capabilities_backend_version
service_id = backend_config.capabilities_service_id or re.sub(r"\s+", "", f"{title.lower()}-{backend_version}")
# TODO only list endpoints that are actually supported by the backend.
endpoints = EndpointRegistry.get_capabilities_endpoints(_openeo_endpoint_metadata, api_version=api_version)
deploy_metadata = backend_config.capabilities_deploy_metadata
capabilities = {
"stac_extensions": [
STAC_EXTENSION.PROCESSING,
],
"version": api_version, # Deprecated pre-0.4.0 API version field
"api_version": api_version, # API version field since 0.4.0
"backend_version": backend_version,
"stac_version": "0.9.0", # TODO #363 bump to 1.x.y?
"type": "Catalog",
"conformsTo": backend_implementation.conformance_classes(),
"id": service_id,
"title": title,
"description": textwrap.dedent(backend_config.capabilities_description).strip(),
"production": OPENEO_API_VERSIONS[g.request_version].production,
"endpoints": endpoints,
"billing": backend_implementation.capabilities_billing(),
# TODO: deprecate custom _backend_deploy_metadata
"_backend_deploy_metadata": deploy_metadata,
"processing:software": deploy_metadata.get("versions", {}),
"links": [
{
"rel": "version-history",
"href": url_for("well_known_openeo", _external=True),
"type": "application/json",
},
{
"rel": "data",
"href": url_for("openeo.collections", _external=True),
"type": "application/json",
},
{
"rel": "conformance",
"href": url_for("openeo.conformance", _external=True),
"type": "application/json",
},
{
"rel": "terms-of-service",
"href": "https://openeo.cloud/aup",
"type": "text/html",
},
{
"rel": "privacy-policy",
"href": "https://terrascope.be/en/privacy-policy",
"type": "text/html",
}
]
}
capabilities = backend_implementation.postprocess_capabilities(capabilities)
return jsonify(capabilities)
@blueprint.route('/conformance')
@backend_implementation.cache_control
def conformance():
"""
Lists all conformance classes specified in OGC standards that the server conforms to.
see https://api.openeo.org/#operation/conformance
"""
return jsonify(
{
"conformsTo": backend_implementation.conformance_classes(),
}
)
@blueprint.route('/health')
def health():
response = backend_implementation.health_check(options=request.args)
if isinstance(response, str):
# Legacy style
response = jsonify({"health": response})
elif not isinstance(response, flask.Response):
response = jsonify(response)
return response
@api_endpoint(version=ComparableVersion("1.0.0").accept_lower)
@blueprint.route('/output_formats')
@backend_implementation.cache_control
def output_formats():
# TODO deprecated endpoint, remove it when v0.4 API support is not necessary anymore
return jsonify(backend_implementation.file_formats()["output"])
@api_endpoint(version=ComparableVersion("1.0.0").or_higher)
@blueprint.route('/file_formats')
@backend_implementation.cache_control
def file_formats():
return jsonify(backend_implementation.file_formats())
@api_endpoint(version=ComparableVersion("1.0.0").or_higher)
@blueprint.route('/processing_parameters')
@backend_implementation.cache_control
def processing_parameters():
return jsonify(backend_implementation.processing_parameters())
@api_endpoint
@blueprint.route('/udf_runtimes')
@backend_implementation.cache_control
def udf_runtimes():
runtimes = backend_implementation.udf_runtimes.get_udf_runtimes()
return jsonify(runtimes)
@blueprint.route('/.well-known/openeo')
def versioned_well_known_openeo():
# Clients might request this for version discovery. Avoid polluting (error) logs by explicitly handling this.
error = NotFoundException(
message="Not a well-known openEO URI",
id="r-" + re.sub("[^a-z0-9]+", "", flask.request.path, flags=re.I),
)
return make_response(jsonify(error.to_dict()), error.status_code)
@blueprint.route('/CHANGELOG', methods=['GET'])
@backend_implementation.cache_control
def changelog():
changelog = backend_implementation.changelog()
if isinstance(changelog, pathlib.Path) and changelog.exists():
return flask.send_file(changelog, mimetype="text/plain")
elif isinstance(changelog, str):
return make_response((changelog, {"Content-Type": "text/plain"}))
else:
return changelog
@blueprint.route('/_debug/echo', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
def debug_echo():
return jsonify({
"url": request.url,
"path": request.path,
"method": request.method,
"headers": dict(request.headers.items()),
"args": request.args,
"data": repr(request.get_data()),
"remote_addr": request.remote_addr,
"environ": {k: request.environ.get(k) for k in ["HTTP_USER_AGENT", "SERVER_PROTOCOL", "wsgi.url_scheme"]}
})
@blueprint.route('/_debug/error', methods=["GET", "POST"])
@blueprint.route('/_debug/error/basic/<v>', methods=["GET", "POST"])
def debug_error_basic(v: str = None):
if v == "NotImplementedError":
raise NotImplementedError
elif v == "ErrorSummary":
raise ErrorSummary(exception=ValueError(-123), is_client_error=False, summary="No negatives please.")
raise Exception("Computer says no.")
@blueprint.route('/_debug/error/api', methods=["GET", "POST"])
@blueprint.route('/_debug/error/api/<int:status>/<code>', methods=["GET", "POST"])
def debug_error_api(status: int = None, code: str = None):
raise OpenEOApiException(message="Computer says no.", code=code, status_code=status)
@blueprint.route('/_debug/error/http', methods=["GET", "POST"])
@blueprint.route('/_debug/error/http/<int:status>', methods=["GET", "POST"])
def debug_error_http(status: int = 500):
abort(status, "Computer says no.")
def register_views_auth(
blueprint: Blueprint, backend_implementation: OpenEoBackendImplementation, api_endpoint: EndpointRegistry,
auth_handler: HttpAuthHandler
):
if backend_implementation.config.enable_basic_auth:
@api_endpoint
@blueprint.route("/credentials/basic", methods=["GET"])
@auth_handler.requires_http_basic_auth
def credentials_basic():
access_token, user_id = auth_handler.authenticate_basic(request)
resp = {"access_token": access_token}
if requested_api_version().below("1.0.0"):
resp["user_id"] = user_id
return jsonify(resp)
if backend_implementation.config.enable_oidc_auth:
@api_endpoint
@blueprint.route("/credentials/oidc", methods=["GET"])
@auth_handler.public
@backend_implementation.cache_control
def credentials_oidc():
providers = backend_implementation.oidc_providers()
return jsonify(
{
"providers": [p.export_for_api() for p in providers],
}
)
@api_endpoint
@blueprint.route("/me", methods=["GET"])
@auth_handler.requires_bearer_auth
def me(user: User):
return jsonify(
dict_no_none(
{
"user_id": user.user_id,
"name": user.get_name(),
"info": user.info,
"roles": sorted(user.get_roles()) or None,
"default_plan": user.get_default_plan(),
# TODO more fields
}
)
)
def _extract_process_graph(post_data: dict) -> ProcessGraphFlatDict:
"""
Extract process graph dictionary from POST data
see https://github.com/Open-EO/openeo-api/pull/262
:return: process graph in flat graph format
"""
try:
if requested_api_version().at_least("1.0.0"):
pg = post_data["process"]["process_graph"]
else:
# API v0.4 style
pg = post_data['process_graph']
except (KeyError, TypeError) as e:
raise ProcessGraphMissingException from e
if not isinstance(pg, dict):
# TODO: more validity checks for (flat) process graph?
raise ProcessGraphInvalidException
return ProcessGraphFlatDict(pg)
def _extract_job_options(post_data: dict, to_ignore: typing.Container[str]) -> Union[dict, None]:
"""
Extract "job options" from request data:
look for an explicit "job_options" property or collect non-predefined top-level properties
"""
if "job_options" in post_data:
# Return explicit "job_options" property as is
job_options = post_data["job_options"]
_log.debug(f"_extract_job_options from 'job_options' property: {job_options!r}")
else:
# Collect all non-deny-listed top-level properties
job_options = {k: v for k, v in post_data.items() if k not in to_ignore} or None
_log.debug(f"_extract_job_options from top-level: {job_options!r}")
return job_options
def register_views_processing(
blueprint: Blueprint, backend_implementation: OpenEoBackendImplementation, api_endpoint: EndpointRegistry,
auth_handler: HttpAuthHandler
):
@api_endpoint(hidden=is_not_implemented(backend_implementation.processing.validate))
@blueprint.route('/validation', methods=["POST"])
def validation():
post_data = request.get_json()
try:
process_graph = post_data["process_graph"]
except (KeyError, TypeError) as e:
raise ProcessGraphMissingException
env = EvalEnv(
{
"backend_implementation": backend_implementation,
# TODO #382 Deprecated field "version", use "openeo_api_version" instead
"version": g.openeo_api_version,
"openeo_api_version": g.openeo_api_version,
"user": None,
"validation": True
}
)
errors = backend_implementation.processing.validate(process_graph=process_graph, env=env)
return jsonify({"errors": errors})
@api_endpoint
@blueprint.route('/result', methods=['POST'])
@auth_handler.requires_bearer_auth
def result(user: User):
post_data = request.get_json()
process_graph = _extract_process_graph(post_data)
budget = post_data.get("budget")
plan = post_data.get("plan")
log_level = _assert_valid_log_level(post_data.get("log_level", DEFAULT_LOG_LEVEL_PROCESSING))
job_options = _extract_job_options(
post_data, to_ignore=["process", "process_graph", "budget", "plan", "log_level"]
)
job_option_defaults = extract_default_job_options_from_process_graph(
process_graph=process_graph, processing_mode="synchronous"
)
if job_option_defaults:
_log.info(f"Extending {job_options=} with extracted {job_option_defaults=}")
job_options = {**job_option_defaults, **(job_options or {})}
request_id = FlaskRequestCorrelationIdLogging.get_request_id()
env = EvalEnv(
{
"backend_implementation": backend_implementation,
# TODO #382 Deprecated field "version", use "openeo_api_version" instead
"version": g.openeo_api_version,
"openeo_api_version": g.openeo_api_version,
"pyramid_levels": "highest",
"user": user,
"require_bounds": True,
"correlation_id": request_id,
"node_caching": False,
# TODO: more explicit way of passing the job_options instead of putting it in the evaluation env?
"job_options": job_options,
"sync_job": True,
"log_level": log_level,
}
)
try:
result = backend_implementation.processing.evaluate(process_graph=process_graph, env=env)
_log.info(f"`POST /result`: {type(result)}")
if result is None:
# TODO: is it still necessary to handle `None` as an error condition?
raise InternalException(message="Process graph evaluation gave no result")
if isinstance(result, flask.Response):
# TODO: handle flask.Response in `to_save_result` too?
response = result
else:
if not isinstance(result, SaveResult):
# Implicit save result (using default/best effort format and options)
result = to_save_result(data=result)
response = result.create_flask_response()
costs = backend_implementation.request_costs(
success=True, user=user, request_id=request_id, job_options=job_options
)
if costs:
# TODO not all costs are accounted for so don't expose in "OpenEO-Costs" yet
response.headers["OpenEO-Costs-experimental"] = costs
except Exception:
# TODO: also send "OpenEO-Costs" header on failure
backend_implementation.request_costs(
success=False, user=user, request_id=request_id, job_options=job_options
)
raise
# Add request id as "OpenEO-Identifier" like we do for batch jobs.
# TODO: follow-up standardization at https://github.com/Open-EO/openeo-api/pull/533
response.headers["OpenEO-Identifier"] = request_id
return response
@blueprint.route('/execute', methods=['POST'])
@auth_handler.requires_bearer_auth
def execute(user: User):
# TODO: This is not an official endpoint, does this "/execute" still have to be exposed as route?
_log.warning(f"Request to non-standard `/execute` endpoint by {user.user_id}")
return result(user=user)
@api_endpoint
@blueprint.route('/processes', methods=['GET'])
@backend_implementation.cache_control
def processes():
process_registry = backend_implementation.processing.get_process_registry(api_version=requested_api_version())
api_version = requested_api_version()
exclusion_list = get_backend_config().processes_exclusion_list.get(api_version.to_string())
processes_listing = process_registry.get_processes_listing(exclusion_list=exclusion_list)
return flask.jsonify(processes_listing.to_response_dict())
@api_endpoint
@blueprint.route('/processes/<namespace>', methods=['GET'])
@backend_implementation.cache_control
def processes_from_namespace(namespace):
# TODO: this endpoint is in draft at the moment
# see https://github.com/Open-EO/openeo-api/issues/310, https://github.com/Open-EO/openeo-api/pull/348
# TODO: unify with `/processes` endpoint?
_log.warning(f"Non-standard processes_from_namespace with {namespace=}")
full = smart_bool(request.args.get("full", False))
target_version = None
# TODO: convention for user namespace? use '@' instead of "u:"
if namespace.startswith("u:") and backend_implementation.user_defined_processes:
user_id = namespace.partition("u:")[-1]
user_udps = [
p for p in backend_implementation.user_defined_processes.list_for_user(user_id).udps if p.public
]
processes = [udp.to_api_dict(full=full) for udp in user_udps]
elif ":" not in namespace:
process_registry = backend_implementation.processing.get_process_registry(
api_version=requested_api_version()
)
target_version = process_registry.target_version
processes = process_registry.get_specs(namespace=namespace)
if not full:
# Strip some fields
processes = [
{k: v for k, v in p.items() if k not in ["process_graph"]}
for p in processes
]
else:
raise OpenEOApiException("Could not handle namespace {n!r}".format(n=namespace))
# TODO: pagination links?
return jsonify(
{
"version": target_version,
"processes": processes,
"links": [],
}
)
@api_endpoint
@blueprint.route('/processes/<namespace>/<process_id>', methods=['GET'])
@backend_implementation.cache_control
def processes_details(namespace, process_id):
# TODO: this endpoint is in draft at the moment
# see https://github.com/Open-EO/openeo-api/issues/310, https://github.com/Open-EO/openeo-api/pull/348
_log.warning(f"Non-standard processes_details with {namespace=} {process_id=}")
if namespace.startswith("u:") and backend_implementation.user_defined_processes:
user_id = namespace.partition("u:")[-1]
udp = backend_implementation.user_defined_processes.get(user_id=user_id, process_id=process_id)
if not udp or not udp.public:
raise ProcessUnsupportedException(process=process_id, namespace=namespace)
if udp.public:
udp = _add_udp_canonical_link(udp=udp, user_id=user_id)
process = udp.to_api_dict(full=True)
elif ":" not in namespace:
process_registry = backend_implementation.processing.get_process_registry(
api_version=requested_api_version()
)
process = process_registry.get_spec(name=process_id, namespace=namespace)
else:
raise OpenEOApiException("Could not handle namespace {n!r}".format(n=namespace))
return jsonify(process)
def _properties_from_job_info(job_info: BatchJobMetadata) -> dict:
to_datetime = Rfc3339(propagate_none=True).datetime
properties = dict_no_none(
{
"title": job_info.title,
"description": job_info.description,
"created": to_datetime(job_info.created),
"updated": to_datetime(job_info.updated),
"card4l:specification": "SR",
"card4l:specification_version": "5.0",
"processing:facility": get_backend_config().processing_facility,
"processing:software": get_backend_config().processing_software,
}
)
properties["datetime"] = None
start_datetime = to_datetime(job_info.start_datetime)
end_datetime = to_datetime(job_info.end_datetime)
if start_datetime == end_datetime:
properties["datetime"] = start_datetime
else:
if start_datetime:
properties["start_datetime"] = start_datetime
if end_datetime:
properties["end_datetime"] = end_datetime
if job_info.instruments:
properties["instruments"] = job_info.instruments
if job_info.epsg:
properties["proj:epsg"] = job_info.epsg
if job_info.proj_bbox:
properties["proj:bbox"] = job_info.proj_bbox
if job_info.proj_shape:
properties["proj:shape"] = job_info.proj_shape
properties["card4l:processing_chain"] = job_info.process
return properties
def _assert_valid_log_level(level: str) -> str:
valid_levels = ["debug", "info", "warning", "error"]
if level not in valid_levels:
raise OpenEOApiException(
code="InvalidLogLevel",
status_code=400,
message=f"Invalid log level {level}. Should be one of {valid_levels}.",
)
return level
def register_views_batch_jobs(
blueprint: Blueprint, backend_implementation: OpenEoBackendImplementation, api_endpoint: EndpointRegistry,
auth_handler: HttpAuthHandler
):
stac_item_media_type = "application/geo+json"
@api_endpoint
@blueprint.route('/jobs', methods=['POST'])
@auth_handler.requires_bearer_auth
def create_job(user: User):
# TODO: wrap this job specification in a 1.0-style ProcessGrahpWithMetadata?
post_data = request.get_json()
process_graph = _extract_process_graph(post_data)
# TODO: preserve original non-process_graph process fields too?
process = {"process_graph": process_graph}
job_options = _extract_job_options(
post_data, to_ignore=["process", "process_graph", "title", "description", "plan", "budget", "log_level"]
)
job_option_defaults = extract_default_job_options_from_process_graph(
process_graph=process_graph, processing_mode="batch_job"
)
if job_option_defaults:
_log.info(f"Extending {job_options=} with extracted {job_option_defaults=}")
job_options = {**job_option_defaults, **(job_options or {})}
metadata = {k: post_data[k] for k in ["title", "description", "plan", "budget"] if k in post_data}
metadata["log_level"] = _assert_valid_log_level(post_data.get("log_level", DEFAULT_LOG_LEVEL_PROCESSING))
job_info = backend_implementation.batch_jobs.create_job(
# TODO: remove this case of `filter_supported_kwargs`
# when we are significantly past openeo-geopyspark-driver 0.60.1 (mid 2025-02)
**filter_supported_kwargs(
callable=backend_implementation.batch_jobs.create_job,
user_id=user.user_id,
user=user,
),
process=process,
api_version=g.openeo_api_version,
metadata=metadata,
job_options=job_options,
)
job_id = job_info.id
_log.info(f"`POST /jobs` created batch job {job_id}")
response = make_response("", 201)
response.headers['Location'] = url_for('.get_job_info', job_id=job_id, _external=True)
response.headers['OpenEO-Identifier'] = str(job_id)
return response
@api_endpoint
@blueprint.route('/jobs', methods=['GET'])
@auth_handler.requires_bearer_auth
def list_jobs(user: User):
# TODO: openEO API currently prescribes no pagination by default (unset limit)
# This is however not very scalable, so we might want to set a default limit here.
# Also see https://github.com/Open-EO/openeo-api/issues/550
limit = flask.request.args.get("limit", type=int)
request_parameters = flask.request.args
# TODO #332 settle on receiving just `JobListing` here and eliminate other options/code paths.
listing = backend_implementation.batch_jobs.get_user_jobs(
user_id=user.user_id, limit=limit, request_parameters=request_parameters
)
# TODO #332 while eliminating old `get_user_jobs` API above, also just settle on JobListing based return,
# and drop all this legacy cruft
if isinstance(listing, list):
jobs = listing
links = []
extra = {}
elif isinstance(listing, dict):
jobs = listing["jobs"]
links = listing.get("links", [])
# TODO: this "extra" whitelist is from experimental
# "federation extension API" https://github.com/Open-EO/openeo-api/pull/419
extra = {k: listing[k] for k in ["federation:missing"] if k in listing}
elif isinstance(listing, JobListing):
data = listing.to_response_dict(
build_url=lambda params: flask.url_for(".list_jobs", **params, _external=True),
api_version=requested_api_version(),
)
return flask.jsonify(data)
else:
raise InternalException(f"Invalid user jobs listing {type(listing)}")
resp = dict(
jobs=[
m.to_api_dict(full=False, api_version=requested_api_version())
for m in jobs
],
links=links,
**extra
)
return jsonify(resp)
@api_endpoint
@blueprint.route('/jobs/<job_id>', methods=['GET'])