mlrun 1.7.0rc13__py3-none-any.whl → 1.7.0rc21__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mlrun might be problematic. Click here for more details.

Files changed (156) hide show
  1. mlrun/__init__.py +10 -1
  2. mlrun/__main__.py +23 -111
  3. mlrun/alerts/__init__.py +15 -0
  4. mlrun/alerts/alert.py +144 -0
  5. mlrun/api/schemas/__init__.py +4 -3
  6. mlrun/artifacts/__init__.py +8 -3
  7. mlrun/artifacts/base.py +36 -253
  8. mlrun/artifacts/dataset.py +9 -190
  9. mlrun/artifacts/manager.py +46 -42
  10. mlrun/artifacts/model.py +9 -141
  11. mlrun/artifacts/plots.py +14 -375
  12. mlrun/common/constants.py +65 -3
  13. mlrun/common/formatters/__init__.py +19 -0
  14. mlrun/{runtimes/mpijob/v1alpha1.py → common/formatters/artifact.py} +6 -14
  15. mlrun/common/formatters/base.py +113 -0
  16. mlrun/common/formatters/function.py +46 -0
  17. mlrun/common/formatters/pipeline.py +53 -0
  18. mlrun/common/formatters/project.py +51 -0
  19. mlrun/{runtimes → common/runtimes}/constants.py +32 -4
  20. mlrun/common/schemas/__init__.py +10 -5
  21. mlrun/common/schemas/alert.py +92 -11
  22. mlrun/common/schemas/api_gateway.py +56 -0
  23. mlrun/common/schemas/artifact.py +15 -5
  24. mlrun/common/schemas/auth.py +2 -0
  25. mlrun/common/schemas/client_spec.py +1 -0
  26. mlrun/common/schemas/frontend_spec.py +1 -0
  27. mlrun/common/schemas/function.py +4 -0
  28. mlrun/common/schemas/model_monitoring/__init__.py +15 -3
  29. mlrun/common/schemas/model_monitoring/constants.py +58 -7
  30. mlrun/common/schemas/model_monitoring/grafana.py +9 -5
  31. mlrun/common/schemas/model_monitoring/model_endpoints.py +86 -2
  32. mlrun/common/schemas/pipeline.py +0 -9
  33. mlrun/common/schemas/project.py +6 -11
  34. mlrun/common/types.py +1 -0
  35. mlrun/config.py +36 -8
  36. mlrun/data_types/to_pandas.py +9 -9
  37. mlrun/datastore/base.py +41 -9
  38. mlrun/datastore/datastore.py +6 -2
  39. mlrun/datastore/datastore_profile.py +56 -4
  40. mlrun/datastore/hdfs.py +5 -0
  41. mlrun/datastore/inmem.py +2 -2
  42. mlrun/datastore/redis.py +2 -2
  43. mlrun/datastore/s3.py +5 -0
  44. mlrun/datastore/sources.py +147 -7
  45. mlrun/datastore/store_resources.py +7 -7
  46. mlrun/datastore/targets.py +129 -9
  47. mlrun/datastore/utils.py +42 -0
  48. mlrun/datastore/v3io.py +1 -1
  49. mlrun/db/auth_utils.py +152 -0
  50. mlrun/db/base.py +55 -11
  51. mlrun/db/httpdb.py +346 -107
  52. mlrun/db/nopdb.py +52 -10
  53. mlrun/errors.py +11 -0
  54. mlrun/execution.py +24 -9
  55. mlrun/feature_store/__init__.py +0 -2
  56. mlrun/feature_store/api.py +12 -47
  57. mlrun/feature_store/feature_set.py +9 -0
  58. mlrun/feature_store/feature_vector.py +8 -0
  59. mlrun/feature_store/ingestion.py +7 -6
  60. mlrun/feature_store/retrieval/base.py +9 -4
  61. mlrun/feature_store/retrieval/conversion.py +9 -9
  62. mlrun/feature_store/retrieval/dask_merger.py +2 -0
  63. mlrun/feature_store/retrieval/job.py +9 -3
  64. mlrun/feature_store/retrieval/local_merger.py +2 -0
  65. mlrun/feature_store/retrieval/spark_merger.py +16 -0
  66. mlrun/frameworks/_dl_common/loggers/tensorboard_logger.py +7 -12
  67. mlrun/frameworks/parallel_coordinates.py +2 -1
  68. mlrun/frameworks/tf_keras/__init__.py +4 -1
  69. mlrun/k8s_utils.py +10 -11
  70. mlrun/launcher/base.py +4 -3
  71. mlrun/launcher/client.py +5 -3
  72. mlrun/launcher/local.py +8 -2
  73. mlrun/launcher/remote.py +8 -2
  74. mlrun/lists.py +6 -2
  75. mlrun/model.py +62 -20
  76. mlrun/model_monitoring/__init__.py +1 -1
  77. mlrun/model_monitoring/api.py +41 -18
  78. mlrun/model_monitoring/application.py +5 -305
  79. mlrun/model_monitoring/applications/__init__.py +11 -0
  80. mlrun/model_monitoring/applications/_application_steps.py +157 -0
  81. mlrun/model_monitoring/applications/base.py +280 -0
  82. mlrun/model_monitoring/applications/context.py +214 -0
  83. mlrun/model_monitoring/applications/evidently_base.py +211 -0
  84. mlrun/model_monitoring/applications/histogram_data_drift.py +132 -91
  85. mlrun/model_monitoring/applications/results.py +99 -0
  86. mlrun/model_monitoring/controller.py +3 -1
  87. mlrun/model_monitoring/db/__init__.py +2 -0
  88. mlrun/model_monitoring/db/stores/__init__.py +0 -2
  89. mlrun/model_monitoring/db/stores/base/store.py +22 -37
  90. mlrun/model_monitoring/db/stores/sqldb/models/__init__.py +43 -21
  91. mlrun/model_monitoring/db/stores/sqldb/models/base.py +39 -8
  92. mlrun/model_monitoring/db/stores/sqldb/models/mysql.py +27 -7
  93. mlrun/model_monitoring/db/stores/sqldb/models/sqlite.py +5 -0
  94. mlrun/model_monitoring/db/stores/sqldb/sql_store.py +246 -224
  95. mlrun/model_monitoring/db/stores/v3io_kv/kv_store.py +232 -216
  96. mlrun/model_monitoring/db/tsdb/__init__.py +100 -0
  97. mlrun/model_monitoring/db/tsdb/base.py +329 -0
  98. mlrun/model_monitoring/db/tsdb/helpers.py +30 -0
  99. mlrun/model_monitoring/db/tsdb/tdengine/__init__.py +15 -0
  100. mlrun/model_monitoring/db/tsdb/tdengine/schemas.py +240 -0
  101. mlrun/model_monitoring/db/tsdb/tdengine/stream_graph_steps.py +45 -0
  102. mlrun/model_monitoring/db/tsdb/tdengine/tdengine_connector.py +397 -0
  103. mlrun/model_monitoring/db/tsdb/v3io/__init__.py +15 -0
  104. mlrun/model_monitoring/db/tsdb/v3io/stream_graph_steps.py +117 -0
  105. mlrun/model_monitoring/db/tsdb/v3io/v3io_connector.py +636 -0
  106. mlrun/model_monitoring/evidently_application.py +6 -118
  107. mlrun/model_monitoring/helpers.py +46 -1
  108. mlrun/model_monitoring/model_endpoint.py +3 -2
  109. mlrun/model_monitoring/stream_processing.py +57 -216
  110. mlrun/model_monitoring/writer.py +134 -124
  111. mlrun/package/utils/_formatter.py +2 -2
  112. mlrun/platforms/__init__.py +10 -9
  113. mlrun/platforms/iguazio.py +21 -202
  114. mlrun/projects/operations.py +19 -12
  115. mlrun/projects/pipelines.py +103 -109
  116. mlrun/projects/project.py +377 -137
  117. mlrun/render.py +15 -14
  118. mlrun/run.py +16 -47
  119. mlrun/runtimes/__init__.py +6 -3
  120. mlrun/runtimes/base.py +8 -7
  121. mlrun/runtimes/databricks_job/databricks_wrapper.py +1 -1
  122. mlrun/runtimes/funcdoc.py +0 -28
  123. mlrun/runtimes/kubejob.py +2 -1
  124. mlrun/runtimes/local.py +5 -2
  125. mlrun/runtimes/mpijob/__init__.py +0 -20
  126. mlrun/runtimes/mpijob/v1.py +1 -1
  127. mlrun/runtimes/nuclio/api_gateway.py +440 -208
  128. mlrun/runtimes/nuclio/application/application.py +170 -8
  129. mlrun/runtimes/nuclio/function.py +39 -49
  130. mlrun/runtimes/pod.py +21 -41
  131. mlrun/runtimes/remotesparkjob.py +9 -3
  132. mlrun/runtimes/sparkjob/spark3job.py +1 -1
  133. mlrun/runtimes/utils.py +6 -45
  134. mlrun/serving/server.py +2 -1
  135. mlrun/serving/states.py +53 -2
  136. mlrun/serving/v2_serving.py +5 -1
  137. mlrun/track/tracker.py +2 -1
  138. mlrun/utils/async_http.py +25 -5
  139. mlrun/utils/helpers.py +107 -75
  140. mlrun/utils/logger.py +39 -7
  141. mlrun/utils/notifications/notification/__init__.py +14 -9
  142. mlrun/utils/notifications/notification/base.py +1 -1
  143. mlrun/utils/notifications/notification/slack.py +61 -13
  144. mlrun/utils/notifications/notification/webhook.py +1 -1
  145. mlrun/utils/notifications/notification_pusher.py +147 -16
  146. mlrun/utils/regex.py +9 -0
  147. mlrun/utils/v3io_clients.py +0 -1
  148. mlrun/utils/version/version.json +2 -2
  149. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/METADATA +14 -6
  150. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/RECORD +154 -133
  151. mlrun/kfpops.py +0 -865
  152. mlrun/platforms/other.py +0 -305
  153. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/LICENSE +0 -0
  154. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/WHEEL +0 -0
  155. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/entry_points.txt +0 -0
  156. {mlrun-1.7.0rc13.dist-info → mlrun-1.7.0rc21.dist-info}/top_level.txt +0 -0
mlrun/db/httpdb.py CHANGED
@@ -15,7 +15,6 @@
15
15
  import enum
16
16
  import http
17
17
  import re
18
- import tempfile
19
18
  import time
20
19
  import traceback
21
20
  import typing
@@ -26,11 +25,13 @@ from os import path, remove
26
25
  from typing import Optional, Union
27
26
  from urllib.parse import urlparse
28
27
 
29
- import kfp
30
28
  import requests
31
29
  import semver
30
+ from mlrun_pipelines.utils import compile_pipeline
32
31
 
33
32
  import mlrun
33
+ import mlrun.common.formatters
34
+ import mlrun.common.runtimes
34
35
  import mlrun.common.schemas
35
36
  import mlrun.common.types
36
37
  import mlrun.model_monitoring.model_endpoint
@@ -38,6 +39,8 @@ import mlrun.platforms
38
39
  import mlrun.projects
39
40
  import mlrun.runtimes.nuclio.api_gateway
40
41
  import mlrun.utils
42
+ from mlrun.alerts.alert import AlertConfig
43
+ from mlrun.db.auth_utils import OAuthClientIDTokenProvider, StaticTokenProvider
41
44
  from mlrun.errors import MLRunInvalidArgumentError, err_to_str
42
45
 
43
46
  from ..artifacts import Artifact
@@ -50,7 +53,6 @@ from ..utils import (
50
53
  datetime_to_iso,
51
54
  dict_to_json,
52
55
  logger,
53
- new_pipe_metadata,
54
56
  normalize_name,
55
57
  version,
56
58
  )
@@ -138,17 +140,28 @@ class HTTPRunDB(RunDBInterface):
138
140
  endpoint += f":{parsed_url.port}"
139
141
  base_url = f"{parsed_url.scheme}://{endpoint}{parsed_url.path}"
140
142
 
143
+ self.base_url = base_url
141
144
  username = parsed_url.username or config.httpdb.user
142
145
  password = parsed_url.password or config.httpdb.password
146
+ self.token_provider = None
147
+
148
+ if config.auth_with_client_id.enabled:
149
+ self.token_provider = OAuthClientIDTokenProvider(
150
+ token_endpoint=mlrun.get_secret_or_env("MLRUN_AUTH_TOKEN_ENDPOINT"),
151
+ client_id=mlrun.get_secret_or_env("MLRUN_AUTH_CLIENT_ID"),
152
+ client_secret=mlrun.get_secret_or_env("MLRUN_AUTH_CLIENT_SECRET"),
153
+ timeout=config.auth_with_client_id.request_timeout,
154
+ )
155
+ else:
156
+ username, password, token = mlrun.platforms.add_or_refresh_credentials(
157
+ parsed_url.hostname, username, password, config.httpdb.token
158
+ )
143
159
 
144
- username, password, token = mlrun.platforms.add_or_refresh_credentials(
145
- parsed_url.hostname, username, password, config.httpdb.token
146
- )
160
+ if token:
161
+ self.token_provider = StaticTokenProvider(token)
147
162
 
148
- self.base_url = base_url
149
163
  self.user = username
150
164
  self.password = password
151
- self.token = token
152
165
 
153
166
  def __repr__(self):
154
167
  cls = self.__class__.__name__
@@ -202,7 +215,7 @@ class HTTPRunDB(RunDBInterface):
202
215
  :param version: API version to use, None (the default) will mean to use the default value from config,
203
216
  for un-versioned api set an empty string.
204
217
 
205
- :return: `requests.Response` HTTP response object
218
+ :returns: `requests.Response` HTTP response object
206
219
  """
207
220
  url = self.get_base_api_url(path, version)
208
221
  kw = {
@@ -218,17 +231,19 @@ class HTTPRunDB(RunDBInterface):
218
231
 
219
232
  if self.user:
220
233
  kw["auth"] = (self.user, self.password)
221
- elif self.token:
222
- # Iguazio auth doesn't support passing token through bearer, so use cookie instead
223
- if mlrun.platforms.iguazio.is_iguazio_session(self.token):
224
- session_cookie = f'j:{{"sid": "{self.token}"}}'
225
- cookies = {
226
- "session": session_cookie,
227
- }
228
- kw["cookies"] = cookies
229
- else:
230
- if "Authorization" not in kw.setdefault("headers", {}):
231
- kw["headers"].update({"Authorization": "Bearer " + self.token})
234
+ elif self.token_provider:
235
+ token = self.token_provider.get_token()
236
+ if token:
237
+ # Iguazio auth doesn't support passing token through bearer, so use cookie instead
238
+ if self.token_provider.is_iguazio_session():
239
+ session_cookie = f'j:{{"sid": "{token}"}}'
240
+ cookies = {
241
+ "session": session_cookie,
242
+ }
243
+ kw["cookies"] = cookies
244
+ else:
245
+ if "Authorization" not in kw.setdefault("headers", {}):
246
+ kw["headers"].update({"Authorization": "Bearer " + token})
232
247
 
233
248
  if mlrun.common.schemas.HeaderNames.client_version not in kw.setdefault(
234
249
  "headers", {}
@@ -517,6 +532,10 @@ class HTTPRunDB(RunDBInterface):
517
532
  server_cfg.get("model_endpoint_monitoring_endpoint_store_connection")
518
533
  or config.model_endpoint_monitoring.endpoint_store_connection
519
534
  )
535
+ config.model_endpoint_monitoring.tsdb_connection = (
536
+ server_cfg.get("model_monitoring_tsdb_connection")
537
+ or config.model_endpoint_monitoring.tsdb_connection
538
+ )
520
539
  config.packagers = server_cfg.get("packagers") or config.packagers
521
540
  server_data_prefixes = server_cfg.get("feature_store_data_prefixes") or {}
522
541
  for prefix in ["default", "nosql", "redisnosql"]:
@@ -576,7 +595,7 @@ class HTTPRunDB(RunDBInterface):
576
595
  if offset < 0:
577
596
  raise MLRunInvalidArgumentError("Offset cannot be negative")
578
597
  if size is None:
579
- size = int(config.httpdb.logs.pull_logs_default_size_limit)
598
+ size = int(mlrun.mlconf.httpdb.logs.pull_logs_default_size_limit)
580
599
  elif size == -1:
581
600
  logger.warning(
582
601
  "Retrieving all logs. This may be inefficient and can result in a large log."
@@ -622,33 +641,35 @@ class HTTPRunDB(RunDBInterface):
622
641
 
623
642
  state, text = self.get_log(uid, project, offset=offset)
624
643
  if text:
625
- print(text.decode(errors=config.httpdb.logs.decode.errors))
644
+ print(text.decode(errors=mlrun.mlconf.httpdb.logs.decode.errors))
626
645
  nil_resp = 0
627
646
  while True:
628
647
  offset += len(text)
629
648
  # if we get 3 nil responses in a row, increase the sleep time to 10 seconds
630
649
  # TODO: refactor this to use a conditional backoff mechanism
631
650
  if nil_resp < 3:
632
- time.sleep(int(config.httpdb.logs.pull_logs_default_interval))
651
+ time.sleep(int(mlrun.mlconf.httpdb.logs.pull_logs_default_interval))
633
652
  else:
634
653
  time.sleep(
635
- int(config.httpdb.logs.pull_logs_backoff_no_logs_default_interval)
654
+ int(
655
+ mlrun.mlconf.httpdb.logs.pull_logs_backoff_no_logs_default_interval
656
+ )
636
657
  )
637
658
  state, text = self.get_log(uid, project, offset=offset)
638
659
  if text:
639
660
  nil_resp = 0
640
661
  print(
641
- text.decode(errors=config.httpdb.logs.decode.errors),
662
+ text.decode(errors=mlrun.mlconf.httpdb.logs.decode.errors),
642
663
  end="",
643
664
  )
644
665
  else:
645
666
  nil_resp += 1
646
667
 
647
668
  if watch and state in [
648
- mlrun.runtimes.constants.RunStates.pending,
649
- mlrun.runtimes.constants.RunStates.running,
650
- mlrun.runtimes.constants.RunStates.created,
651
- mlrun.runtimes.constants.RunStates.aborting,
669
+ mlrun.common.runtimes.constants.RunStates.pending,
670
+ mlrun.common.runtimes.constants.RunStates.running,
671
+ mlrun.common.runtimes.constants.RunStates.created,
672
+ mlrun.common.runtimes.constants.RunStates.aborting,
652
673
  ]:
653
674
  continue
654
675
  else:
@@ -737,7 +758,10 @@ class HTTPRunDB(RunDBInterface):
737
758
  uid: Optional[Union[str, list[str]]] = None,
738
759
  project: Optional[str] = None,
739
760
  labels: Optional[Union[str, list[str]]] = None,
740
- state: Optional[str] = None,
761
+ state: Optional[
762
+ mlrun.common.runtimes.constants.RunStates
763
+ ] = None, # Backward compatibility
764
+ states: typing.Optional[list[mlrun.common.runtimes.constants.RunStates]] = None,
741
765
  sort: bool = True,
742
766
  last: int = 0,
743
767
  iter: bool = False,
@@ -775,7 +799,8 @@ class HTTPRunDB(RunDBInterface):
775
799
  :param labels: A list of labels to filter by. Label filters work by either filtering a specific value
776
800
  of a label (i.e. list("key=value")) or by looking for the existence of a given
777
801
  key (i.e. "key").
778
- :param state: List only runs whose state is specified.
802
+ :param state: Deprecated - List only runs whose state is specified (will be removed in 1.9.0)
803
+ :param states: List only runs whose state is one of the provided states.
779
804
  :param sort: Whether to sort the result according to their start time. Otherwise, results will be
780
805
  returned by their internal order in the DB (order will not be guaranteed).
781
806
  :param last: Deprecated - currently not used (will be removed in 1.8.0).
@@ -811,11 +836,19 @@ class HTTPRunDB(RunDBInterface):
811
836
  FutureWarning,
812
837
  )
813
838
 
839
+ if state:
840
+ # TODO: Remove this in 1.9.0
841
+ warnings.warn(
842
+ "'state' is deprecated and will be removed in 1.9.0. Use 'states' instead.",
843
+ FutureWarning,
844
+ )
845
+
814
846
  if (
815
847
  not name
816
848
  and not uid
817
849
  and not labels
818
850
  and not state
851
+ and not states
819
852
  and not last
820
853
  and not start_time_from
821
854
  and not start_time_to
@@ -834,7 +867,9 @@ class HTTPRunDB(RunDBInterface):
834
867
  "name": name,
835
868
  "uid": uid,
836
869
  "label": labels or [],
837
- "state": state,
870
+ "state": mlrun.utils.helpers.as_list(state)
871
+ if state is not None
872
+ else states or None,
838
873
  "sort": bool2str(sort),
839
874
  "iter": bool2str(iter),
840
875
  "start_time_from": datetime_to_iso(start_time_from),
@@ -961,7 +996,7 @@ class HTTPRunDB(RunDBInterface):
961
996
  error = f"read artifact {project}/{key}"
962
997
  # explicitly set artifacts format to 'full' since old servers may default to 'legacy'
963
998
  params = {
964
- "format": mlrun.common.schemas.ArtifactsFormat.full.value,
999
+ "format": mlrun.common.formatters.ArtifactFormat.full.value,
965
1000
  "tag": tag,
966
1001
  "tree": tree,
967
1002
  "uid": uid,
@@ -971,7 +1006,18 @@ class HTTPRunDB(RunDBInterface):
971
1006
  resp = self.api_call("GET", endpoint_path, error, params=params, version="v2")
972
1007
  return resp.json()
973
1008
 
974
- def del_artifact(self, key, tag=None, project="", tree=None, uid=None):
1009
+ def del_artifact(
1010
+ self,
1011
+ key,
1012
+ tag=None,
1013
+ project="",
1014
+ tree=None,
1015
+ uid=None,
1016
+ deletion_strategy: mlrun.common.schemas.artifact.ArtifactsDeletionStrategies = (
1017
+ mlrun.common.schemas.artifact.ArtifactsDeletionStrategies.metadata_only
1018
+ ),
1019
+ secrets: dict = None,
1020
+ ):
975
1021
  """Delete an artifact.
976
1022
 
977
1023
  :param key: Identifying key of the artifact.
@@ -979,6 +1025,8 @@ class HTTPRunDB(RunDBInterface):
979
1025
  :param project: Project that the artifact belongs to.
980
1026
  :param tree: The tree which generated this artifact.
981
1027
  :param uid: A unique ID for this specific version of the artifact (the uid that was generated in the backend)
1028
+ :param deletion_strategy: The artifact deletion strategy types.
1029
+ :param secrets: Credentials needed to access the artifact data.
982
1030
  """
983
1031
 
984
1032
  endpoint_path = f"projects/{project}/artifacts/{key}"
@@ -987,9 +1035,17 @@ class HTTPRunDB(RunDBInterface):
987
1035
  "tag": tag,
988
1036
  "tree": tree,
989
1037
  "uid": uid,
1038
+ "deletion_strategy": deletion_strategy,
990
1039
  }
991
1040
  error = f"del artifact {project}/{key}"
992
- self.api_call("DELETE", endpoint_path, error, params=params, version="v2")
1041
+ self.api_call(
1042
+ "DELETE",
1043
+ endpoint_path,
1044
+ error,
1045
+ params=params,
1046
+ version="v2",
1047
+ body=dict_to_json(secrets),
1048
+ )
993
1049
 
994
1050
  def list_artifacts(
995
1051
  self,
@@ -1004,6 +1060,7 @@ class HTTPRunDB(RunDBInterface):
1004
1060
  kind: str = None,
1005
1061
  category: Union[str, mlrun.common.schemas.ArtifactCategories] = None,
1006
1062
  tree: str = None,
1063
+ producer_uri: str = None,
1007
1064
  ) -> ArtifactList:
1008
1065
  """List artifacts filtered by various parameters.
1009
1066
 
@@ -1032,9 +1089,12 @@ class HTTPRunDB(RunDBInterface):
1032
1089
  :param best_iteration: Returns the artifact which belongs to the best iteration of a given run, in the case of
1033
1090
  artifacts generated from a hyper-param run. If only a single iteration exists, will return the artifact
1034
1091
  from that iteration. If using ``best_iter``, the ``iter`` parameter must not be used.
1035
- :param kind: Return artifacts of the requested kind.
1036
- :param category: Return artifacts of the requested category.
1037
- :param tree: Return artifacts of the requested tree.
1092
+ :param kind: Return artifacts of the requested kind.
1093
+ :param category: Return artifacts of the requested category.
1094
+ :param tree: Return artifacts of the requested tree.
1095
+ :param producer_uri: Return artifacts produced by the requested producer URI. Producer URI usually
1096
+ points to a run and is used to filter artifacts by the run that produced them when the artifact producer id
1097
+ is a workflow id (artifact was created as part of a workflow).
1038
1098
  """
1039
1099
 
1040
1100
  project = project or config.default_project
@@ -1052,7 +1112,8 @@ class HTTPRunDB(RunDBInterface):
1052
1112
  "kind": kind,
1053
1113
  "category": category,
1054
1114
  "tree": tree,
1055
- "format": mlrun.common.schemas.ArtifactsFormat.full.value,
1115
+ "format": mlrun.common.formatters.ArtifactFormat.full.value,
1116
+ "producer_uri": producer_uri,
1056
1117
  }
1057
1118
  error = "list artifacts"
1058
1119
  endpoint_path = f"projects/{project}/artifacts"
@@ -1142,7 +1203,32 @@ class HTTPRunDB(RunDBInterface):
1142
1203
  project = project or config.default_project
1143
1204
  path = f"projects/{project}/functions/{name}"
1144
1205
  error_message = f"Failed deleting function {project}/{name}"
1145
- self.api_call("DELETE", path, error_message)
1206
+ response = self.api_call("DELETE", path, error_message, version="v2")
1207
+ if response.status_code == http.HTTPStatus.ACCEPTED:
1208
+ logger.info(
1209
+ "Function is being deleted", project_name=project, function_name=name
1210
+ )
1211
+ background_task = mlrun.common.schemas.BackgroundTask(**response.json())
1212
+ background_task = self._wait_for_background_task_to_reach_terminal_state(
1213
+ background_task.metadata.name, project=project
1214
+ )
1215
+ if (
1216
+ background_task.status.state
1217
+ == mlrun.common.schemas.BackgroundTaskState.succeeded
1218
+ ):
1219
+ logger.info(
1220
+ "Function deleted", project_name=project, function_name=name
1221
+ )
1222
+ elif (
1223
+ background_task.status.state
1224
+ == mlrun.common.schemas.BackgroundTaskState.failed
1225
+ ):
1226
+ logger.info(
1227
+ "Function deletion failed",
1228
+ reason=background_task.status.error,
1229
+ project_name=project,
1230
+ function_name=name,
1231
+ )
1146
1232
 
1147
1233
  def list_functions(self, name=None, project=None, tag=None, labels=None):
1148
1234
  """Retrieve a list of functions, filtered by specific criteria.
@@ -1443,6 +1529,7 @@ class HTTPRunDB(RunDBInterface):
1443
1529
  ):
1444
1530
  """
1445
1531
  Deploy a Nuclio function.
1532
+
1446
1533
  :param func: Function to build.
1447
1534
  :param builder_env: Kaniko builder pod env vars dict (for config/credentials)
1448
1535
  """
@@ -1488,16 +1575,15 @@ class HTTPRunDB(RunDBInterface):
1488
1575
  """
1489
1576
 
1490
1577
  try:
1578
+ normalized_name = normalize_name(func.metadata.name)
1491
1579
  params = {
1492
- "name": normalize_name(func.metadata.name),
1580
+ "name": normalized_name,
1493
1581
  "project": func.metadata.project,
1494
1582
  "tag": func.metadata.tag,
1495
1583
  "last_log_timestamp": str(last_log_timestamp),
1496
1584
  "verbose": bool2str(verbose),
1497
1585
  }
1498
- _path = (
1499
- f"projects/{func.metadata.project}/nuclio/{func.metadata.name}/deploy"
1500
- )
1586
+ _path = f"projects/{func.metadata.project}/nuclio/{normalized_name}/deploy"
1501
1587
  resp = self.api_call("GET", _path, params=params)
1502
1588
  except OSError as err:
1503
1589
  logger.error(f"error getting deploy status: {err_to_str(err)}")
@@ -1793,14 +1879,11 @@ class HTTPRunDB(RunDBInterface):
1793
1879
  if isinstance(pipeline, str):
1794
1880
  pipe_file = pipeline
1795
1881
  else:
1796
- pipe_file = tempfile.NamedTemporaryFile(suffix=".yaml", delete=False).name
1797
- conf = new_pipe_metadata(
1882
+ pipe_file = compile_pipeline(
1798
1883
  artifact_path=artifact_path,
1799
1884
  cleanup_ttl=cleanup_ttl,
1800
- op_transformers=ops,
1801
- )
1802
- kfp.compiler.Compiler().compile(
1803
- pipeline, pipe_file, type_check=False, pipeline_conf=conf
1885
+ ops=ops,
1886
+ pipeline=pipeline,
1804
1887
  )
1805
1888
 
1806
1889
  if pipe_file.endswith(".yaml"):
@@ -1855,8 +1938,8 @@ class HTTPRunDB(RunDBInterface):
1855
1938
  page_token: str = "",
1856
1939
  filter_: str = "",
1857
1940
  format_: Union[
1858
- str, mlrun.common.schemas.PipelinesFormat
1859
- ] = mlrun.common.schemas.PipelinesFormat.metadata_only,
1941
+ str, mlrun.common.formatters.PipelineFormat
1942
+ ] = mlrun.common.formatters.PipelineFormat.metadata_only,
1860
1943
  page_size: int = None,
1861
1944
  ) -> mlrun.common.schemas.PipelinesOutput:
1862
1945
  """Retrieve a list of KFP pipelines. This function can be invoked to get all pipelines from all projects,
@@ -1902,8 +1985,8 @@ class HTTPRunDB(RunDBInterface):
1902
1985
  namespace: str = None,
1903
1986
  timeout: int = 30,
1904
1987
  format_: Union[
1905
- str, mlrun.common.schemas.PipelinesFormat
1906
- ] = mlrun.common.schemas.PipelinesFormat.summary,
1988
+ str, mlrun.common.formatters.PipelineFormat
1989
+ ] = mlrun.common.formatters.PipelineFormat.summary,
1907
1990
  project: str = None,
1908
1991
  ):
1909
1992
  """Retrieve details of a specific pipeline using its run ID (as provided when the pipeline was executed)."""
@@ -2545,8 +2628,8 @@ class HTTPRunDB(RunDBInterface):
2545
2628
  self,
2546
2629
  owner: str = None,
2547
2630
  format_: Union[
2548
- str, mlrun.common.schemas.ProjectsFormat
2549
- ] = mlrun.common.schemas.ProjectsFormat.name_only,
2631
+ str, mlrun.common.formatters.ProjectFormat
2632
+ ] = mlrun.common.formatters.ProjectFormat.name_only,
2550
2633
  labels: list[str] = None,
2551
2634
  state: Union[str, mlrun.common.schemas.ProjectState] = None,
2552
2635
  ) -> list[Union[mlrun.projects.MlrunProject, str]]:
@@ -2572,7 +2655,7 @@ class HTTPRunDB(RunDBInterface):
2572
2655
 
2573
2656
  error_message = f"Failed listing projects, query: {params}"
2574
2657
  response = self.api_call("GET", "projects", error_message, params=params)
2575
- if format_ == mlrun.common.schemas.ProjectsFormat.name_only:
2658
+ if format_ == mlrun.common.formatters.ProjectFormat.name_only:
2576
2659
  # projects is just a list of strings
2577
2660
  return response.json()["projects"]
2578
2661
 
@@ -3077,14 +3160,12 @@ class HTTPRunDB(RunDBInterface):
3077
3160
  :param labels: A list of labels to filter by. Label filters work by either filtering a specific value of a
3078
3161
  label (i.e. list("key=value")) or by looking for the existence of a given key (i.e. "key")
3079
3162
  :param metrics: A list of metrics to return for each endpoint, read more in 'TimeMetric'
3080
- :param start: The start time of the metrics. Can be represented by a string containing an RFC 3339
3081
- time, a Unix timestamp in milliseconds, a relative time (`'now'` or
3082
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, and `'d'` =
3083
- days), or 0 for the earliest time.
3084
- :param end: The end time of the metrics. Can be represented by a string containing an RFC 3339
3085
- time, a Unix timestamp in milliseconds, a relative time (`'now'` or
3086
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, and `'d'` =
3087
- days), or 0 for the earliest time.
3163
+ :param start: The start time of the metrics. Can be represented by a string containing an RFC 3339 time, a
3164
+ Unix timestamp in milliseconds, a relative time (`'now'` or `'now-[0-9]+[mhd]'`, where
3165
+ `m` = minutes, `h` = hours, `'d'` = days, and `'s'` = seconds), or 0 for the earliest time.
3166
+ :param end: The end time of the metrics. Can be represented by a string containing an RFC 3339 time, a
3167
+ Unix timestamp in milliseconds, a relative time (`'now'` or `'now-[0-9]+[mhd]'`, where
3168
+ `m` = minutes, `h` = hours, `'d'` = days, and `'s'` = seconds), or 0 for the earliest time.
3088
3169
  :param top_level: if true will return only routers and endpoint that are NOT children of any router
3089
3170
  :param uids: if passed will return a list `ModelEndpoint` object with uid in uids
3090
3171
  """
@@ -3133,13 +3214,13 @@ class HTTPRunDB(RunDBInterface):
3133
3214
  :param project: The name of the project
3134
3215
  :param endpoint_id: The unique id of the model endpoint.
3135
3216
  :param start: The start time of the metrics. Can be represented by a string containing an
3136
- RFC 3339 time, a Unix timestamp in milliseconds, a relative time (`'now'` or
3137
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, and `'d'` = days), or
3138
- 0 for the earliest time.
3217
+ RFC 3339 time, a Unix timestamp in milliseconds, a relative time
3218
+ (`'now'` or `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours,
3219
+ `'d'` = days, and `'s'` = seconds), or 0 for the earliest time.
3139
3220
  :param end: The end time of the metrics. Can be represented by a string containing an
3140
- RFC 3339 time, a Unix timestamp in milliseconds, a relative time (`'now'` or
3141
- `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours, and `'d'` = days), or
3142
- 0 for the earliest time.
3221
+ RFC 3339 time, a Unix timestamp in milliseconds, a relative time
3222
+ (`'now'` or `'now-[0-9]+[mhd]'`, where `m` = minutes, `h` = hours,
3223
+ `'d'` = days, and `'s'` = seconds), or 0 for the earliest time.
3143
3224
  :param metrics: A list of metrics to return for the model endpoint. There are pre-defined
3144
3225
  metrics for model endpoints such as predictions_per_second and
3145
3226
  latency_avg_5m but also custom metrics defined by the user. Please note that
@@ -3148,7 +3229,7 @@ class HTTPRunDB(RunDBInterface):
3148
3229
  :param feature_analysis: When True, the base feature statistics and current feature statistics will
3149
3230
  be added to the output of the resulting object.
3150
3231
 
3151
- :return: A `ModelEndpoint` object.
3232
+ :returns: A `ModelEndpoint` object.
3152
3233
  """
3153
3234
 
3154
3235
  path = f"projects/{project}/model-endpoints/{endpoint_id}"
@@ -3214,7 +3295,7 @@ class HTTPRunDB(RunDBInterface):
3214
3295
  project: str,
3215
3296
  base_period: int = 10,
3216
3297
  image: str = "mlrun/mlrun",
3217
- ):
3298
+ ) -> None:
3218
3299
  """
3219
3300
  Redeploy model monitoring application controller function.
3220
3301
 
@@ -3224,13 +3305,14 @@ class HTTPRunDB(RunDBInterface):
3224
3305
  :param image: The image of the model monitoring controller function.
3225
3306
  By default, the image is mlrun/mlrun.
3226
3307
  """
3227
-
3228
- params = {
3229
- "image": image,
3230
- "base_period": base_period,
3231
- }
3232
- path = f"projects/{project}/model-monitoring/model-monitoring-controller"
3233
- self.api_call(method="POST", path=path, params=params)
3308
+ self.api_call(
3309
+ method=mlrun.common.types.HTTPMethod.POST,
3310
+ path=f"projects/{project}/model-monitoring/model-monitoring-controller",
3311
+ params={
3312
+ "base_period": base_period,
3313
+ "image": image,
3314
+ },
3315
+ )
3234
3316
 
3235
3317
  def enable_model_monitoring(
3236
3318
  self,
@@ -3265,6 +3347,113 @@ class HTTPRunDB(RunDBInterface):
3265
3347
  },
3266
3348
  )
3267
3349
 
3350
+ def disable_model_monitoring(
3351
+ self,
3352
+ project: str,
3353
+ delete_resources: bool = True,
3354
+ delete_stream_function: bool = False,
3355
+ delete_histogram_data_drift_app: bool = True,
3356
+ delete_user_applications: bool = False,
3357
+ user_application_list: list[str] = None,
3358
+ ) -> bool:
3359
+ """
3360
+ Disable model monitoring application controller, writer, stream, histogram data drift application
3361
+ and the user's applications functions, according to the given params.
3362
+
3363
+ :param project: Project name.
3364
+ :param delete_resources: If True, it would delete the model monitoring controller & writer
3365
+ functions. Default True
3366
+ :param delete_stream_function: If True, it would delete model monitoring stream function,
3367
+ need to use wisely because if you're deleting this function
3368
+ this can cause data loss in case you will want to
3369
+ enable the model monitoring capability to the project.
3370
+ Default False.
3371
+ :param delete_histogram_data_drift_app: If True, it would delete the default histogram-based data drift
3372
+ application. Default False.
3373
+ :param delete_user_applications: If True, it would delete the user's model monitoring
3374
+ application according to user_application_list, Default False.
3375
+ :param user_application_list: List of the user's model monitoring application to disable.
3376
+ Default all the applications.
3377
+ Note: you have to set delete_user_applications to True
3378
+ in order to delete the desired application.
3379
+
3380
+ :returns: True if the deletion was successful, False otherwise.
3381
+ """
3382
+ response = self.api_call(
3383
+ method=mlrun.common.types.HTTPMethod.DELETE,
3384
+ path=f"projects/{project}/model-monitoring/disable-model-monitoring",
3385
+ params={
3386
+ "delete_resources": delete_resources,
3387
+ "delete_stream_function": delete_stream_function,
3388
+ "delete_histogram_data_drift_app": delete_histogram_data_drift_app,
3389
+ "delete_user_applications": delete_user_applications,
3390
+ "user_application_list": user_application_list,
3391
+ },
3392
+ )
3393
+ deletion_failed = False
3394
+ if response.status_code == http.HTTPStatus.ACCEPTED:
3395
+ if delete_resources:
3396
+ logger.info(
3397
+ "Model Monitoring is being disable",
3398
+ project_name=project,
3399
+ )
3400
+ if delete_user_applications:
3401
+ logger.info("User applications are being deleted", project_name=project)
3402
+ background_tasks = mlrun.common.schemas.BackgroundTaskList(
3403
+ **response.json()
3404
+ ).background_tasks
3405
+ for task in background_tasks:
3406
+ task = self._wait_for_background_task_to_reach_terminal_state(
3407
+ task.metadata.name, project=project
3408
+ )
3409
+ if (
3410
+ task.status.state
3411
+ == mlrun.common.schemas.BackgroundTaskState.succeeded
3412
+ ):
3413
+ continue
3414
+ elif (
3415
+ task.status.state == mlrun.common.schemas.BackgroundTaskState.failed
3416
+ ):
3417
+ deletion_failed = True
3418
+ return not deletion_failed
3419
+
3420
+ def delete_model_monitoring_function(
3421
+ self, project: str, functions: list[str]
3422
+ ) -> bool:
3423
+ """
3424
+ Delete a model monitoring application.
3425
+
3426
+ :param functions: List of the model monitoring function to delete.
3427
+ :param project: Project name.
3428
+
3429
+ :returns: True if the deletion was successful, False otherwise.
3430
+ """
3431
+ response = self.api_call(
3432
+ method=mlrun.common.types.HTTPMethod.DELETE,
3433
+ path=f"projects/{project}/model-monitoring/functions",
3434
+ params={"functions": functions},
3435
+ )
3436
+ deletion_failed = False
3437
+ if response.status_code == http.HTTPStatus.ACCEPTED:
3438
+ logger.info("User applications are being deleted", project_name=project)
3439
+ background_tasks = mlrun.common.schemas.BackgroundTaskList(
3440
+ **response.json()
3441
+ ).background_tasks
3442
+ for task in background_tasks:
3443
+ task = self._wait_for_background_task_to_reach_terminal_state(
3444
+ task.metadata.name, project=project
3445
+ )
3446
+ if (
3447
+ task.status.state
3448
+ == mlrun.common.schemas.BackgroundTaskState.succeeded
3449
+ ):
3450
+ continue
3451
+ elif (
3452
+ task.status.state == mlrun.common.schemas.BackgroundTaskState.failed
3453
+ ):
3454
+ deletion_failed = True
3455
+ return not deletion_failed
3456
+
3268
3457
  def deploy_histogram_data_drift_app(
3269
3458
  self, project: str, image: str = "mlrun/mlrun"
3270
3459
  ) -> None:
@@ -3492,7 +3681,7 @@ class HTTPRunDB(RunDBInterface):
3492
3681
  :param version: Get a specific version of the item. Default is ``None``.
3493
3682
  :param tag: Get a specific version of the item identified by tag. Default is ``latest``.
3494
3683
 
3495
- :return: http response with the asset in the content attribute
3684
+ :returns: http response with the asset in the content attribute
3496
3685
  """
3497
3686
  path = f"hub/sources/{source_name}/items/{item_name}/assets/{asset_name}"
3498
3687
  params = {
@@ -3523,9 +3712,10 @@ class HTTPRunDB(RunDBInterface):
3523
3712
  def list_api_gateways(self, project=None) -> mlrun.common.schemas.APIGatewaysOutput:
3524
3713
  """
3525
3714
  Returns a list of Nuclio api gateways
3715
+
3526
3716
  :param project: optional str parameter to filter by project, if not passed, default project value is taken
3527
3717
 
3528
- :return: :py:class:`~mlrun.common.schemas.APIGateways`.
3718
+ :returns: :py:class:`~mlrun.common.schemas.APIGateways`.
3529
3719
  """
3530
3720
  project = project or config.default_project
3531
3721
  error = "list api gateways"
@@ -3536,10 +3726,11 @@ class HTTPRunDB(RunDBInterface):
3536
3726
  def get_api_gateway(self, name, project=None) -> mlrun.common.schemas.APIGateway:
3537
3727
  """
3538
3728
  Returns an API gateway
3729
+
3539
3730
  :param name: API gateway name
3540
3731
  :param project: optional str parameter to filter by project, if not passed, default project value is taken
3541
3732
 
3542
- :return: :py:class:`~mlrun.common.schemas.APIGateway`.
3733
+ :returns: :py:class:`~mlrun.common.schemas.APIGateway`.
3543
3734
  """
3544
3735
  project = project or config.default_project
3545
3736
  error = "get api gateway"
@@ -3550,6 +3741,7 @@ class HTTPRunDB(RunDBInterface):
3550
3741
  def delete_api_gateway(self, name, project=None):
3551
3742
  """
3552
3743
  Deletes an API gateway
3744
+
3553
3745
  :param name: API gateway name
3554
3746
  :param project: Project name
3555
3747
  """
@@ -3568,11 +3760,12 @@ class HTTPRunDB(RunDBInterface):
3568
3760
  ) -> mlrun.common.schemas.APIGateway:
3569
3761
  """
3570
3762
  Stores an API Gateway.
3571
- :param api_gateway :py:class:`~mlrun.runtimes.nuclio.APIGateway`
3763
+
3764
+ :param api_gateway: :py:class:`~mlrun.runtimes.nuclio.APIGateway`
3572
3765
  or :py:class:`~mlrun.common.schemas.APIGateway`: API Gateway entity.
3573
3766
  :param project: project name. Mandatory if api_gateway is mlrun.common.schemas.APIGateway.
3574
3767
 
3575
- :return: :py:class:`~mlrun.common.schemas.APIGateway`.
3768
+ :returns: :py:class:`~mlrun.common.schemas.APIGateway`.
3576
3769
  """
3577
3770
 
3578
3771
  if isinstance(api_gateway, mlrun.runtimes.nuclio.api_gateway.APIGateway):
@@ -3590,6 +3783,7 @@ class HTTPRunDB(RunDBInterface):
3590
3783
  def trigger_migrations(self) -> Optional[mlrun.common.schemas.BackgroundTask]:
3591
3784
  """Trigger migrations (will do nothing if no migrations are needed) and wait for them to finish if actually
3592
3785
  triggered
3786
+
3593
3787
  :returns: :py:class:`~mlrun.common.schemas.BackgroundTask`.
3594
3788
  """
3595
3789
  response = self.api_call(
@@ -3612,6 +3806,7 @@ class HTTPRunDB(RunDBInterface):
3612
3806
  ):
3613
3807
  """
3614
3808
  Set notifications on a run. This will override any existing notifications on the run.
3809
+
3615
3810
  :param project: Project containing the run.
3616
3811
  :param run_uid: UID of the run.
3617
3812
  :param notifications: List of notifications to set on the run. Default is an empty list.
@@ -3637,6 +3832,7 @@ class HTTPRunDB(RunDBInterface):
3637
3832
  ):
3638
3833
  """
3639
3834
  Set notifications on a schedule. This will override any existing notifications on the schedule.
3835
+
3640
3836
  :param project: Project containing the schedule.
3641
3837
  :param schedule_name: Name of the schedule.
3642
3838
  :param notifications: List of notifications to set on the schedule. Default is an empty list.
@@ -3785,15 +3981,16 @@ class HTTPRunDB(RunDBInterface):
3785
3981
  ) -> str:
3786
3982
  """
3787
3983
  Loading a project remotely from the given source.
3984
+
3788
3985
  :param name: project name
3789
3986
  :param url: git or tar.gz or .zip sources archive path e.g.:
3790
- git://github.com/mlrun/demo-xgb-project.git
3791
- http://mysite/archived-project.zip
3792
- The git project should include the project yaml file.
3987
+ git://github.com/mlrun/demo-xgb-project.git
3988
+ http://mysite/archived-project.zip
3989
+ The git project should include the project yaml file.
3793
3990
  :param secrets: Secrets to store in project in order to load it from the provided url. For more
3794
- information see :py:func:`mlrun.load_project` function.
3991
+ information see :py:func:`mlrun.load_project` function.
3795
3992
  :param save_secrets: Whether to store secrets in the loaded project. Setting to False will cause waiting
3796
- for the process completion.
3993
+ for the process completion.
3797
3994
 
3798
3995
  :returns: The terminal state of load project process.
3799
3996
  """
@@ -3879,7 +4076,7 @@ class HTTPRunDB(RunDBInterface):
3879
4076
  logger.warning(
3880
4077
  "Building a function image to ECR and loading an S3 source to the image may require conflicting access "
3881
4078
  "keys. Only the permissions granted to the platform's configured secret will take affect "
3882
- "(see mlrun.config.config.httpdb.builder.docker_registry_secret). "
4079
+ "(see mlrun.mlconf.httpdb.builder.docker_registry_secret). "
3883
4080
  "In case the permissions are limited to ECR scope, you may use pull_at_runtime=True instead",
3884
4081
  source=func.spec.build.source,
3885
4082
  load_source_on_run=func.spec.build.load_source_on_run,
@@ -3891,9 +4088,10 @@ class HTTPRunDB(RunDBInterface):
3891
4088
  ):
3892
4089
  """
3893
4090
  Generate an event.
3894
- :param name: The name of the event.
4091
+
4092
+ :param name: The name of the event.
3895
4093
  :param event_data: The data of the event.
3896
- :param project: The project that the event belongs to.
4094
+ :param project: The project that the event belongs to.
3897
4095
  """
3898
4096
  project = project or config.default_project
3899
4097
  endpoint_path = f"projects/{project}/events/{name}"
@@ -3907,43 +4105,54 @@ class HTTPRunDB(RunDBInterface):
3907
4105
  def store_alert_config(
3908
4106
  self,
3909
4107
  alert_name: str,
3910
- alert_data: Union[dict, mlrun.common.schemas.AlertConfig],
4108
+ alert_data: Union[dict, AlertConfig],
3911
4109
  project="",
3912
- ):
4110
+ ) -> AlertConfig:
3913
4111
  """
3914
4112
  Create/modify an alert.
4113
+
3915
4114
  :param alert_name: The name of the alert.
3916
4115
  :param alert_data: The data of the alert.
3917
- :param project: the project that the alert belongs to.
3918
- :return: The created/modified alert.
4116
+ :param project: The project that the alert belongs to.
4117
+ :returns: The created/modified alert.
3919
4118
  """
3920
4119
  project = project or config.default_project
3921
4120
  endpoint_path = f"projects/{project}/alerts/{alert_name}"
3922
4121
  error_message = f"put alert {project}/alerts/{alert_name}"
3923
- if isinstance(alert_data, mlrun.common.schemas.AlertConfig):
3924
- alert_data = alert_data.dict()
4122
+ alert_instance = (
4123
+ alert_data
4124
+ if isinstance(alert_data, AlertConfig)
4125
+ else AlertConfig.from_dict(alert_data)
4126
+ )
4127
+ alert_instance.validate_required_fields()
4128
+
4129
+ alert_data = alert_instance.to_dict()
3925
4130
  body = _as_json(alert_data)
3926
4131
  response = self.api_call("PUT", endpoint_path, error_message, body=body)
3927
- return mlrun.common.schemas.AlertConfig(**response.json())
4132
+ return AlertConfig.from_dict(response.json())
3928
4133
 
3929
- def get_alert_config(self, alert_name: str, project=""):
4134
+ def get_alert_config(self, alert_name: str, project="") -> AlertConfig:
3930
4135
  """
3931
4136
  Retrieve an alert.
4137
+
3932
4138
  :param alert_name: The name of the alert to retrieve.
3933
- :param project: The project that the alert belongs to.
3934
- :return: The alert object.
4139
+ :param project: The project that the alert belongs to.
4140
+
4141
+ :returns: The alert object.
3935
4142
  """
3936
4143
  project = project or config.default_project
3937
4144
  endpoint_path = f"projects/{project}/alerts/{alert_name}"
3938
4145
  error_message = f"get alert {project}/alerts/{alert_name}"
3939
4146
  response = self.api_call("GET", endpoint_path, error_message)
3940
- return mlrun.common.schemas.AlertConfig(**response.json())
4147
+ return AlertConfig.from_dict(response.json())
3941
4148
 
3942
- def list_alerts_configs(self, project=""):
4149
+ def list_alerts_configs(self, project="") -> list[AlertConfig]:
3943
4150
  """
3944
4151
  Retrieve list of alerts of a project.
4152
+
3945
4153
  :param project: The project name.
3946
- :return: All the alerts objects of the project.
4154
+
4155
+ :returns: All the alerts objects of the project.
3947
4156
  """
3948
4157
  project = project or config.default_project
3949
4158
  endpoint_path = f"projects/{project}/alerts"
@@ -3951,7 +4160,7 @@ class HTTPRunDB(RunDBInterface):
3951
4160
  response = self.api_call("GET", endpoint_path, error_message).json()
3952
4161
  results = []
3953
4162
  for item in response:
3954
- results.append(mlrun.common.schemas.AlertConfig(**item))
4163
+ results.append(AlertConfig(**item))
3955
4164
  return results
3956
4165
 
3957
4166
  def delete_alert_config(self, alert_name: str, project=""):
@@ -3968,6 +4177,7 @@ class HTTPRunDB(RunDBInterface):
3968
4177
  def reset_alert_config(self, alert_name: str, project=""):
3969
4178
  """
3970
4179
  Reset an alert.
4180
+
3971
4181
  :param alert_name: The name of the alert to reset.
3972
4182
  :param project: The project that the alert belongs to.
3973
4183
  """
@@ -3976,6 +4186,35 @@ class HTTPRunDB(RunDBInterface):
3976
4186
  error_message = f"post alert {project}/alerts/{alert_name}/reset"
3977
4187
  self.api_call("POST", endpoint_path, error_message)
3978
4188
 
4189
+ def get_alert_template(
4190
+ self, template_name: str
4191
+ ) -> mlrun.common.schemas.AlertTemplate:
4192
+ """
4193
+ Retrieve a specific alert template.
4194
+
4195
+ :param template_name: The name of the template to retrieve.
4196
+
4197
+ :returns: The template object.
4198
+ """
4199
+ endpoint_path = f"alert-templates/{template_name}"
4200
+ error_message = f"get template alert-templates/{template_name}"
4201
+ response = self.api_call("GET", endpoint_path, error_message)
4202
+ return mlrun.common.schemas.AlertTemplate(**response.json())
4203
+
4204
+ def list_alert_templates(self) -> list[mlrun.common.schemas.AlertTemplate]:
4205
+ """
4206
+ Retrieve list of all alert templates.
4207
+
4208
+ :returns: All the alert template objects in the database.
4209
+ """
4210
+ endpoint_path = "alert-templates"
4211
+ error_message = "get templates /alert-templates"
4212
+ response = self.api_call("GET", endpoint_path, error_message).json()
4213
+ results = []
4214
+ for item in response:
4215
+ results.append(mlrun.common.schemas.AlertTemplate(**item))
4216
+ return results
4217
+
3979
4218
 
3980
4219
  def _as_json(obj):
3981
4220
  fn = getattr(obj, "to_json", None)