/
handlers.py
2364 lines (2013 loc) · 84.7 KB
/
handlers.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
# Define all the service endpoint handlers here.
import bisect
import json
import logging
import os
import pathlib
import posixpath
import re
import tempfile
import time
import urllib
from functools import wraps
from typing import List, Set
import requests
from flask import Response, current_app, jsonify, request, send_file
from google.protobuf import descriptor
from google.protobuf.json_format import ParseError
from mlflow.entities import DatasetInput, ExperimentTag, FileInfo, Metric, Param, RunTag, ViewType
from mlflow.entities.model_registry import ModelVersionTag, RegisteredModelTag
from mlflow.entities.multipart_upload import MultipartUploadPart
from mlflow.environment_variables import MLFLOW_DEPLOYMENTS_TARGET
from mlflow.exceptions import MlflowException, _UnsupportedMultipartUploadException
from mlflow.models import Model
from mlflow.protos import databricks_pb2
from mlflow.protos.databricks_pb2 import (
INVALID_PARAMETER_VALUE,
RESOURCE_DOES_NOT_EXIST,
)
from mlflow.protos.mlflow_artifacts_pb2 import (
AbortMultipartUpload,
CompleteMultipartUpload,
CreateMultipartUpload,
DeleteArtifact,
DownloadArtifact,
MlflowArtifactsService,
UploadArtifact,
)
from mlflow.protos.mlflow_artifacts_pb2 import (
ListArtifacts as ListArtifactsMlflowArtifacts,
)
from mlflow.protos.model_registry_pb2 import (
CreateModelVersion,
CreateRegisteredModel,
DeleteModelVersion,
DeleteModelVersionTag,
DeleteRegisteredModel,
DeleteRegisteredModelAlias,
DeleteRegisteredModelTag,
GetLatestVersions,
GetModelVersion,
GetModelVersionByAlias,
GetModelVersionDownloadUri,
GetRegisteredModel,
ModelRegistryService,
RenameRegisteredModel,
SearchModelVersions,
SearchRegisteredModels,
SetModelVersionTag,
SetRegisteredModelAlias,
SetRegisteredModelTag,
TransitionModelVersionStage,
UpdateModelVersion,
UpdateRegisteredModel,
)
from mlflow.protos.service_pb2 import (
CreateExperiment,
CreateRun,
DeleteExperiment,
DeleteRun,
DeleteTag,
GetExperiment,
GetExperimentByName,
GetMetricHistory,
GetMetricHistoryBulkInterval,
GetRun,
ListArtifacts,
LogBatch,
LogInputs,
LogMetric,
LogModel,
LogParam,
MlflowService,
RestoreExperiment,
RestoreRun,
SearchExperiments,
SearchRuns,
SetExperimentTag,
SetTag,
UpdateExperiment,
UpdateRun,
)
from mlflow.server.validation import _validate_content_type
from mlflow.store.artifact.artifact_repo import MultipartUploadMixin
from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository
from mlflow.store.db.db_types import DATABASE_ENGINES
from mlflow.tracking._model_registry import utils as registry_utils
from mlflow.tracking._model_registry.registry import ModelRegistryStoreRegistry
from mlflow.tracking._tracking_service import utils
from mlflow.tracking._tracking_service.registry import TrackingStoreRegistry
from mlflow.tracking.registry import UnsupportedModelRegistryStoreURIException
from mlflow.utils.file_utils import local_file_uri_to_path
from mlflow.utils.mime_type_utils import _guess_mime_type
from mlflow.utils.promptlab_utils import _create_promptlab_run_impl
from mlflow.utils.proto_json_utils import message_to_json, parse_dict
from mlflow.utils.string_utils import is_string_type
from mlflow.utils.uri import is_local_uri, validate_path_is_safe, validate_query_string
from mlflow.utils.validation import _validate_batch_log_api_req
_logger = logging.getLogger(__name__)
_tracking_store = None
_model_registry_store = None
_artifact_repo = None
STATIC_PREFIX_ENV_VAR = "_MLFLOW_STATIC_PREFIX"
class TrackingStoreRegistryWrapper(TrackingStoreRegistry):
def __init__(self):
super().__init__()
self.register("", self._get_file_store)
self.register("file", self._get_file_store)
for scheme in DATABASE_ENGINES:
self.register(scheme, self._get_sqlalchemy_store)
self.register_entrypoints()
@classmethod
def _get_file_store(cls, store_uri, artifact_uri):
from mlflow.store.tracking.file_store import FileStore
return FileStore(store_uri, artifact_uri)
@classmethod
def _get_sqlalchemy_store(cls, store_uri, artifact_uri):
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
return SqlAlchemyStore(store_uri, artifact_uri)
class ModelRegistryStoreRegistryWrapper(ModelRegistryStoreRegistry):
def __init__(self):
super().__init__()
self.register("", self._get_file_store)
self.register("file", self._get_file_store)
for scheme in DATABASE_ENGINES:
self.register(scheme, self._get_sqlalchemy_store)
self.register_entrypoints()
@classmethod
def _get_file_store(cls, store_uri):
from mlflow.store.model_registry.file_store import FileStore
return FileStore(store_uri)
@classmethod
def _get_sqlalchemy_store(cls, store_uri):
from mlflow.store.model_registry.sqlalchemy_store import SqlAlchemyStore
return SqlAlchemyStore(store_uri)
_tracking_store_registry = TrackingStoreRegistryWrapper()
_model_registry_store_registry = ModelRegistryStoreRegistryWrapper()
def _get_artifact_repo_mlflow_artifacts():
"""
Get an artifact repository specified by ``--artifacts-destination`` option for ``mlflow server``
command.
"""
from mlflow.server import ARTIFACTS_DESTINATION_ENV_VAR
global _artifact_repo
if _artifact_repo is None:
_artifact_repo = get_artifact_repository(os.environ[ARTIFACTS_DESTINATION_ENV_VAR])
return _artifact_repo
def _is_serving_proxied_artifacts():
"""
Returns:
True if the MLflow server is serving proxied artifacts (i.e. acting as a proxy for
artifact upload / download / list operations), as would be enabled by specifying the
--serve-artifacts configuration option. False otherwise.
"""
from mlflow.server import SERVE_ARTIFACTS_ENV_VAR
return os.environ.get(SERVE_ARTIFACTS_ENV_VAR, "false") == "true"
def _is_servable_proxied_run_artifact_root(run_artifact_root):
"""
Determines whether or not the following are true:
- The specified Run artifact root is a proxied artifact root (i.e. an artifact root with scheme
``http``, ``https``, or ``mlflow-artifacts``).
- The MLflow server is capable of resolving and accessing the underlying storage location
corresponding to the proxied artifact root, allowing it to fulfill artifact list and
download requests by using this storage location directly.
Args:
run_artifact_root: The Run artifact root location (URI).
Returns:
True if the specified Run artifact root refers to proxied artifacts that can be
served by this MLflow server (i.e. the server has access to the destination and
can respond to list and download requests for the artifact). False otherwise.
"""
parsed_run_artifact_root = urllib.parse.urlparse(run_artifact_root)
# NB: If the run artifact root is a proxied artifact root (has scheme `http`, `https`, or
# `mlflow-artifacts`) *and* the MLflow server is configured to serve artifacts, the MLflow
# server always assumes that it has access to the underlying storage location for the proxied
# artifacts. This may not always be accurate. For example:
#
# An organization may initially use the MLflow server to serve Tracking API requests and proxy
# access to artifacts stored in Location A (via `mlflow server --serve-artifacts`). Then, for
# scalability and / or security purposes, the organization may decide to store artifacts in a
# new location B and set up a separate server (e.g. `mlflow server --artifacts-only`) to proxy
# access to artifacts stored in Location B.
#
# In this scenario, requests for artifacts stored in Location B that are sent to the original
# MLflow server will fail if the original MLflow server does not have access to Location B
# because it will assume that it can serve all proxied artifacts regardless of the underlying
# location. Such failures can be remediated by granting the original MLflow server access to
# Location B.
return (
parsed_run_artifact_root.scheme in ["http", "https", "mlflow-artifacts"]
and _is_serving_proxied_artifacts()
)
def _get_proxied_run_artifact_destination_path(proxied_artifact_root, relative_path=None):
"""
Resolves the specified proxied artifact location within a Run to a concrete storage location.
Args:
proxied_artifact_root: The Run artifact root location (URI) with scheme ``http``,
``https``, or `mlflow-artifacts` that can be resolved by the MLflow server to a
concrete storage location.
relative_path: The relative path of the destination within the specified
``proxied_artifact_root``. If ``None``, the destination is assumed to be
the resolved ``proxied_artifact_root``.
Returns:
The storage location of the specified artifact.
"""
parsed_proxied_artifact_root = urllib.parse.urlparse(proxied_artifact_root)
assert parsed_proxied_artifact_root.scheme in ["http", "https", "mlflow-artifacts"]
if parsed_proxied_artifact_root.scheme == "mlflow-artifacts":
# If the proxied artifact root is an `mlflow-artifacts` URI, the run artifact root path is
# simply the path component of the URI, since the fully-qualified format of an
# `mlflow-artifacts` URI is `mlflow-artifacts://<netloc>/path/to/artifact`
proxied_run_artifact_root_path = parsed_proxied_artifact_root.path.lstrip("/")
else:
# In this case, the proxied artifact root is an HTTP(S) URL referring to an mlflow-artifacts
# API route that can be used to download the artifact. These routes are always anchored at
# `/api/2.0/mlflow-artifacts/artifacts`. Accordingly, we split the path on this route anchor
# and interpret the rest of the path (everything after the route anchor) as the run artifact
# root path
mlflow_artifacts_http_route_anchor = "/api/2.0/mlflow-artifacts/artifacts/"
assert mlflow_artifacts_http_route_anchor in parsed_proxied_artifact_root.path
proxied_run_artifact_root_path = parsed_proxied_artifact_root.path.split(
mlflow_artifacts_http_route_anchor
)[1].lstrip("/")
return (
posixpath.join(proxied_run_artifact_root_path, relative_path)
if relative_path is not None
else proxied_run_artifact_root_path
)
def _get_tracking_store(backend_store_uri=None, default_artifact_root=None):
from mlflow.server import ARTIFACT_ROOT_ENV_VAR, BACKEND_STORE_URI_ENV_VAR
global _tracking_store
if _tracking_store is None:
store_uri = backend_store_uri or os.environ.get(BACKEND_STORE_URI_ENV_VAR, None)
artifact_root = default_artifact_root or os.environ.get(ARTIFACT_ROOT_ENV_VAR, None)
_tracking_store = _tracking_store_registry.get_store(store_uri, artifact_root)
utils.set_tracking_uri(store_uri)
return _tracking_store
def _get_model_registry_store(registry_store_uri=None):
from mlflow.server import BACKEND_STORE_URI_ENV_VAR, REGISTRY_STORE_URI_ENV_VAR
global _model_registry_store
if _model_registry_store is None:
store_uri = (
registry_store_uri
or os.environ.get(REGISTRY_STORE_URI_ENV_VAR, None)
or os.environ.get(BACKEND_STORE_URI_ENV_VAR, None)
)
_model_registry_store = _model_registry_store_registry.get_store(store_uri)
registry_utils.set_registry_uri(store_uri)
return _model_registry_store
def initialize_backend_stores(
backend_store_uri=None, registry_store_uri=None, default_artifact_root=None
):
_get_tracking_store(backend_store_uri, default_artifact_root)
try:
_get_model_registry_store(registry_store_uri)
except UnsupportedModelRegistryStoreURIException:
pass
def _assert_string(x):
assert isinstance(x, str)
def _assert_intlike(x):
try:
x = int(x)
except ValueError:
pass
assert isinstance(x, int)
def _assert_bool(x):
assert isinstance(x, bool)
def _assert_floatlike(x):
try:
x = float(x)
except ValueError:
pass
assert isinstance(x, float)
def _assert_array(x):
assert isinstance(x, list)
def _assert_required(x):
assert x is not None
# When parsing JSON payloads via proto, absent string fields
# are expressed as empty strings
assert x != ""
def _assert_less_than_or_equal(x, max_value, message=None):
if x > max_value:
raise AssertionError(message) if message else AssertionError()
def _assert_intlike_within_range(x, min_value, max_value, message=None):
if not min_value <= x <= max_value:
raise AssertionError(message) if message else AssertionError()
def _assert_item_type_string(x):
assert all(isinstance(item, str) for item in x)
_TYPE_VALIDATORS = {
_assert_intlike,
_assert_string,
_assert_bool,
_assert_floatlike,
_assert_array,
_assert_item_type_string,
}
def _validate_param_against_schema(schema, param, value, proto_parsing_succeeded=False):
"""
Attempts to validate a single parameter against a specified schema. Examples of the elements of
the schema are type assertions and checks for required parameters. Returns None on validation
success. Otherwise, raises an MLFlowException if an assertion fails. This method is intended
to be called for side effects.
Args:
schema: A list of functions to validate the parameter against.
param: The string name of the parameter being validated.
value: The corresponding value of the `param` being validated.
proto_parsing_succeeded: A boolean value indicating whether proto parsing succeeded.
If the proto was successfully parsed, we assume all of the types of the parameters in
the request body were correctly specified, and thus we skip validating types. If proto
parsing failed, then we validate types in addition to the rest of the schema. For
details, see https://github.com/mlflow/mlflow/pull/5458#issuecomment-1080880870.
"""
for f in schema:
if f in _TYPE_VALIDATORS and proto_parsing_succeeded:
continue
try:
f(value)
except AssertionError as e:
if e.args:
message = e.args[0]
elif f == _assert_required:
message = f"Missing value for required parameter '{param}'."
else:
message = (
f"Invalid value {value} for parameter '{param}' supplied."
f" Hint: Value was of type '{type(value).__name__}'."
)
raise MlflowException(
message=(
message + " See the API docs for more information about request parameters."
),
error_code=INVALID_PARAMETER_VALUE,
)
return None
def _get_request_json(flask_request=request):
_validate_content_type(flask_request, ["application/json"])
return flask_request.get_json(force=True, silent=True)
def _get_request_message(request_message, flask_request=request, schema=None):
from querystring_parser import parser
if flask_request.method == "GET" and len(flask_request.query_string) > 0:
# This is a hack to make arrays of length 1 work with the parser.
# for example experiment_ids%5B%5D=0 should be parsed to {experiment_ids: [0]}
# but it gets parsed to {experiment_ids: 0}
# but it doesn't. However, experiment_ids%5B0%5D=0 will get parsed to the right
# result.
query_string = re.sub("%5B%5D", "%5B0%5D", flask_request.query_string.decode("utf-8"))
request_dict = parser.parse(query_string, normalized=True)
# Convert atomic values of repeated fields to lists before calling protobuf deserialization.
# Context: We parse the parameter string into a dictionary outside of protobuf since
# protobuf does not know how to read the query parameters directly. The query parser above
# has no type information and hence any parameter that occurs exactly once is parsed as an
# atomic value. Since protobuf requires that the values of repeated fields are lists,
# deserialization will fail unless we do the fix below.
for field in request_message.DESCRIPTOR.fields:
if (
field.label == descriptor.FieldDescriptor.LABEL_REPEATED
and field.name in request_dict
):
if not isinstance(request_dict[field.name], list):
request_dict[field.name] = [request_dict[field.name]]
request_json = request_dict
else:
request_json = _get_request_json(flask_request)
# Older clients may post their JSON double-encoded as strings, so the get_json
# above actually converts it to a string. Therefore, we check this condition
# (which we can tell for sure because any proper request should be a dictionary),
# and decode it a second time.
if is_string_type(request_json):
request_json = json.loads(request_json)
# If request doesn't have json body then assume it's empty.
if request_json is None:
request_json = {}
proto_parsing_succeeded = True
try:
parse_dict(request_json, request_message)
except ParseError:
proto_parsing_succeeded = False
schema = schema or {}
for schema_key, schema_validation_fns in schema.items():
if schema_key in request_json or _assert_required in schema_validation_fns:
value = request_json.get(schema_key)
if schema_key == "run_id" and value is None and "run_uuid" in request_json:
value = request_json.get("run_uuid")
_validate_param_against_schema(
schema=schema_validation_fns,
param=schema_key,
value=value,
proto_parsing_succeeded=proto_parsing_succeeded,
)
return request_message
def _response_with_file_attachment_headers(file_path, response):
mime_type = _guess_mime_type(file_path)
filename = pathlib.Path(file_path).name
response.mimetype = mime_type
content_disposition_header_name = "Content-Disposition"
if content_disposition_header_name not in response.headers:
response.headers[content_disposition_header_name] = f"attachment; filename={filename}"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Content-Type"] = mime_type
return response
def _send_artifact(artifact_repository, path):
file_path = os.path.abspath(artifact_repository.download_artifacts(path))
# Always send artifacts as attachments to prevent the browser from displaying them on our web
# server's domain, which might enable XSS.
mime_type = _guess_mime_type(file_path)
file_sender_response = send_file(file_path, mimetype=mime_type, as_attachment=True)
return _response_with_file_attachment_headers(file_path, file_sender_response)
def catch_mlflow_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except MlflowException as e:
response = Response(mimetype="application/json")
response.set_data(e.serialize_as_json())
response.status_code = e.get_http_status_code()
return response
return wrapper
def _disable_unless_serve_artifacts(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not _is_serving_proxied_artifacts():
return Response(
(
f"Endpoint: {request.url_rule} disabled due to the mlflow server running "
"with `--no-serve-artifacts`. To enable artifacts server functionality, "
"run `mlflow server` with `--serve-artifacts`"
),
503,
)
return func(*args, **kwargs)
return wrapper
def _disable_if_artifacts_only(func):
@wraps(func)
def wrapper(*args, **kwargs):
from mlflow.server import ARTIFACTS_ONLY_ENV_VAR
if os.environ.get(ARTIFACTS_ONLY_ENV_VAR):
return Response(
(
f"Endpoint: {request.url_rule} disabled due to the mlflow server running "
"in `--artifacts-only` mode. To enable tracking server functionality, run "
"`mlflow server` without `--artifacts-only`"
),
503,
)
return func(*args, **kwargs)
return wrapper
@catch_mlflow_exception
def get_artifact_handler():
from querystring_parser import parser
query_string = request.query_string.decode("utf-8")
request_dict = parser.parse(query_string, normalized=True)
run_id = request_dict.get("run_id") or request_dict.get("run_uuid")
path = request_dict["path"]
path = validate_path_is_safe(path)
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_repo = _get_artifact_repo_mlflow_artifacts()
artifact_path = _get_proxied_run_artifact_destination_path(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_repo = _get_artifact_repo(run)
artifact_path = path
return _send_artifact(artifact_repo, artifact_path)
def _not_implemented():
response = Response()
response.status_code = 404
return response
# Tracking Server APIs
@catch_mlflow_exception
@_disable_if_artifacts_only
def _create_experiment():
request_message = _get_request_message(
CreateExperiment(),
schema={
"name": [_assert_required, _assert_string],
"artifact_location": [_assert_string],
"tags": [_assert_array],
},
)
tags = [ExperimentTag(tag.key, tag.value) for tag in request_message.tags]
# Validate query string in artifact location to prevent attacks
parsed_artifact_location = urllib.parse.urlparse(request_message.artifact_location)
if parsed_artifact_location.fragment or parsed_artifact_location.params:
raise MlflowException(
"'artifact_location' URL can't include fragments or params.",
error_code=INVALID_PARAMETER_VALUE,
)
validate_query_string(parsed_artifact_location.query)
experiment_id = _get_tracking_store().create_experiment(
request_message.name, request_message.artifact_location, tags
)
response_message = CreateExperiment.Response()
response_message.experiment_id = experiment_id
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _get_experiment():
request_message = _get_request_message(
GetExperiment(), schema={"experiment_id": [_assert_required, _assert_string]}
)
response_message = get_experiment_impl(request_message)
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
def get_experiment_impl(request_message):
response_message = GetExperiment.Response()
experiment = _get_tracking_store().get_experiment(request_message.experiment_id).to_proto()
response_message.experiment.MergeFrom(experiment)
return response_message
@catch_mlflow_exception
@_disable_if_artifacts_only
def _get_experiment_by_name():
request_message = _get_request_message(
GetExperimentByName(), schema={"experiment_name": [_assert_required, _assert_string]}
)
response_message = GetExperimentByName.Response()
store_exp = _get_tracking_store().get_experiment_by_name(request_message.experiment_name)
if store_exp is None:
raise MlflowException(
f"Could not find experiment with name '{request_message.experiment_name}'",
error_code=RESOURCE_DOES_NOT_EXIST,
)
experiment = store_exp.to_proto()
response_message.experiment.MergeFrom(experiment)
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _delete_experiment():
request_message = _get_request_message(
DeleteExperiment(), schema={"experiment_id": [_assert_required, _assert_string]}
)
_get_tracking_store().delete_experiment(request_message.experiment_id)
response_message = DeleteExperiment.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _restore_experiment():
request_message = _get_request_message(
RestoreExperiment(), schema={"experiment_id": [_assert_required, _assert_string]}
)
_get_tracking_store().restore_experiment(request_message.experiment_id)
response_message = RestoreExperiment.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _update_experiment():
request_message = _get_request_message(
UpdateExperiment(),
schema={
"experiment_id": [_assert_required, _assert_string],
"new_name": [_assert_string, _assert_required],
},
)
if request_message.new_name:
_get_tracking_store().rename_experiment(
request_message.experiment_id, request_message.new_name
)
response_message = UpdateExperiment.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _create_run():
request_message = _get_request_message(
CreateRun(),
schema={
"experiment_id": [_assert_string],
"start_time": [_assert_intlike],
"run_name": [_assert_string],
},
)
tags = [RunTag(tag.key, tag.value) for tag in request_message.tags]
run = _get_tracking_store().create_run(
experiment_id=request_message.experiment_id,
user_id=request_message.user_id,
start_time=request_message.start_time,
tags=tags,
run_name=request_message.run_name,
)
response_message = CreateRun.Response()
response_message.run.MergeFrom(run.to_proto())
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _update_run():
request_message = _get_request_message(
UpdateRun(),
schema={
"run_id": [_assert_required, _assert_string],
"end_time": [_assert_intlike],
"status": [_assert_string],
"run_name": [_assert_string],
},
)
run_id = request_message.run_id or request_message.run_uuid
run_name = request_message.run_name if request_message.HasField("run_name") else None
end_time = request_message.end_time if request_message.HasField("end_time") else None
status = request_message.status if request_message.HasField("status") else None
updated_info = _get_tracking_store().update_run_info(run_id, status, end_time, run_name)
response_message = UpdateRun.Response(run_info=updated_info.to_proto())
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _delete_run():
request_message = _get_request_message(
DeleteRun(), schema={"run_id": [_assert_required, _assert_string]}
)
_get_tracking_store().delete_run(request_message.run_id)
response_message = DeleteRun.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _restore_run():
request_message = _get_request_message(
RestoreRun(), schema={"run_id": [_assert_required, _assert_string]}
)
_get_tracking_store().restore_run(request_message.run_id)
response_message = RestoreRun.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _log_metric():
request_message = _get_request_message(
LogMetric(),
schema={
"run_id": [_assert_required, _assert_string],
"key": [_assert_required, _assert_string],
"value": [_assert_required, _assert_floatlike],
"timestamp": [_assert_intlike, _assert_required],
"step": [_assert_intlike],
},
)
metric = Metric(
request_message.key, request_message.value, request_message.timestamp, request_message.step
)
run_id = request_message.run_id or request_message.run_uuid
_get_tracking_store().log_metric(run_id, metric)
response_message = LogMetric.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _log_param():
request_message = _get_request_message(
LogParam(),
schema={
"run_id": [_assert_required, _assert_string],
"key": [_assert_required, _assert_string],
"value": [_assert_string],
},
)
param = Param(request_message.key, request_message.value)
run_id = request_message.run_id or request_message.run_uuid
_get_tracking_store().log_param(run_id, param)
response_message = LogParam.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _log_inputs():
request_message = _get_request_message(
LogInputs(),
schema={
"run_id": [_assert_required, _assert_string],
"datasets": [_assert_required, _assert_array],
},
)
run_id = request_message.run_id
datasets = [
DatasetInput.from_proto(proto_dataset_input)
for proto_dataset_input in request_message.datasets
]
_get_tracking_store().log_inputs(run_id, datasets=datasets)
response_message = LogInputs.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _set_experiment_tag():
request_message = _get_request_message(
SetExperimentTag(),
schema={
"experiment_id": [_assert_required, _assert_string],
"key": [_assert_required, _assert_string],
"value": [_assert_string],
},
)
tag = ExperimentTag(request_message.key, request_message.value)
_get_tracking_store().set_experiment_tag(request_message.experiment_id, tag)
response_message = SetExperimentTag.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _set_tag():
request_message = _get_request_message(
SetTag(),
schema={
"run_id": [_assert_required, _assert_string],
"key": [_assert_required, _assert_string],
"value": [_assert_string],
},
)
tag = RunTag(request_message.key, request_message.value)
run_id = request_message.run_id or request_message.run_uuid
_get_tracking_store().set_tag(run_id, tag)
response_message = SetTag.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _delete_tag():
request_message = _get_request_message(
DeleteTag(),
schema={
"run_id": [_assert_required, _assert_string],
"key": [_assert_required, _assert_string],
},
)
_get_tracking_store().delete_tag(request_message.run_id, request_message.key)
response_message = DeleteTag.Response()
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _get_run():
request_message = _get_request_message(
GetRun(), schema={"run_id": [_assert_required, _assert_string]}
)
response_message = get_run_impl(request_message)
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
def get_run_impl(request_message):
response_message = GetRun.Response()
run_id = request_message.run_id or request_message.run_uuid
response_message.run.MergeFrom(_get_tracking_store().get_run(run_id).to_proto())
return response_message
@catch_mlflow_exception
@_disable_if_artifacts_only
def _search_runs():
request_message = _get_request_message(
SearchRuns(),
schema={
"experiment_ids": [_assert_array],
"filter": [_assert_string],
"max_results": [_assert_intlike, lambda x: _assert_less_than_or_equal(int(x), 50000)],
"order_by": [_assert_array, _assert_item_type_string],
},
)
response_message = SearchRuns.Response()
run_view_type = ViewType.ACTIVE_ONLY
if request_message.HasField("run_view_type"):
run_view_type = ViewType.from_proto(request_message.run_view_type)
filter_string = request_message.filter
max_results = request_message.max_results
experiment_ids = request_message.experiment_ids
order_by = request_message.order_by
page_token = request_message.page_token
run_entities = _get_tracking_store().search_runs(
experiment_ids, filter_string, run_view_type, max_results, order_by, page_token
)
response_message.runs.extend([r.to_proto() for r in run_entities])
if run_entities.token:
response_message.next_page_token = run_entities.token
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
@_disable_if_artifacts_only
def _list_artifacts():
request_message = _get_request_message(
ListArtifacts(),
schema={
"run_id": [_assert_string, _assert_required],
"path": [_assert_string],
"page_token": [_assert_string],
},
)
response_message = ListArtifacts.Response()
if request_message.HasField("path"):
path = request_message.path
path = validate_path_is_safe(path)
else:
path = None
run_id = request_message.run_id or request_message.run_uuid
run = _get_tracking_store().get_run(run_id)
if _is_servable_proxied_run_artifact_root(run.info.artifact_uri):
artifact_entities = _list_artifacts_for_proxied_run_artifact_root(
proxied_artifact_root=run.info.artifact_uri,
relative_path=path,
)
else:
artifact_entities = _get_artifact_repo(run).list_artifacts(path)
response_message.files.extend([a.to_proto() for a in artifact_entities])
response_message.root_uri = run.info.artifact_uri
response = Response(mimetype="application/json")
response.set_data(message_to_json(response_message))
return response
@catch_mlflow_exception
def _list_artifacts_for_proxied_run_artifact_root(proxied_artifact_root, relative_path=None):
"""
Lists artifacts from the specified ``relative_path`` within the specified proxied Run artifact
root (i.e. a Run artifact root with scheme ``http``, ``https``, or ``mlflow-artifacts``).
Args:
proxied_artifact_root: The Run artifact root location (URI) with scheme ``http``,
``https``, or ``mlflow-artifacts`` that can be resolved by the