sagemaker-mlflow 0.1.1__tar.gz → 0.2.0.dev1__tar.gz

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.
Files changed (36) hide show
  1. {sagemaker_mlflow-0.1.1/sagemaker_mlflow.egg-info → sagemaker_mlflow-0.2.0.dev1}/PKG-INFO +4 -1
  2. sagemaker_mlflow-0.2.0.dev1/VERSION +1 -0
  3. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/requirements/integration_test_requirements.txt +1 -0
  4. sagemaker_mlflow-0.2.0.dev1/requirements/mypy_requirements.txt +6 -0
  5. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/requirements/prerelease_test_requirements.txt +1 -0
  6. sagemaker_mlflow-0.2.0.dev1/sagemaker_mlflow/auth.py +154 -0
  7. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/auth_provider.py +22 -3
  8. sagemaker_mlflow-0.2.0.dev1/sagemaker_mlflow/credential_cache.py +77 -0
  9. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/exceptions.py +6 -0
  10. sagemaker_mlflow-0.2.0.dev1/sagemaker_mlflow/mlflow_sagemaker_helpers.py +244 -0
  11. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/mlflow_sagemaker_registry_store.py +9 -5
  12. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/mlflow_sagemaker_request_header_provider.py +25 -1
  13. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/mlflow_sagemaker_store.py +8 -5
  14. sagemaker_mlflow-0.2.0.dev1/sagemaker_mlflow/presigned_url.py +70 -0
  15. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1/sagemaker_mlflow.egg-info}/PKG-INFO +4 -1
  16. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow.egg-info/SOURCES.txt +1 -0
  17. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow.egg-info/requires.txt +2 -0
  18. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/setup.py +8 -3
  19. sagemaker_mlflow-0.1.1/VERSION +0 -1
  20. sagemaker_mlflow-0.1.1/requirements/mypy_requirements.txt +0 -2
  21. sagemaker_mlflow-0.1.1/sagemaker_mlflow/auth.py +0 -97
  22. sagemaker_mlflow-0.1.1/sagemaker_mlflow/mlflow_sagemaker_helpers.py +0 -82
  23. sagemaker_mlflow-0.1.1/sagemaker_mlflow/presigned_url.py +0 -43
  24. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/LICENSE +0 -0
  25. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/MANIFEST.in +0 -0
  26. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/NOTICE +0 -0
  27. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/README.md +0 -0
  28. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/pyproject.toml +0 -0
  29. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/requirements/black_requirements.txt +0 -0
  30. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/requirements/flake8_requirements.txt +0 -0
  31. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/requirements/twine_requirements.txt +0 -0
  32. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow/__init__.py +0 -0
  33. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow.egg-info/dependency_links.txt +0 -0
  34. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow.egg-info/entry_points.txt +0 -0
  35. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/sagemaker_mlflow.egg-info/top_level.txt +0 -0
  36. {sagemaker_mlflow-0.1.1 → sagemaker_mlflow-0.2.0.dev1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sagemaker-mlflow
3
- Version: 0.1.1
3
+ Version: 0.2.0.dev1
4
4
  Summary: AWS Plugin for MLflow with SageMaker
5
5
  Home-page: https://github.com/aws/sagemaker-mlflow
6
6
  Author: Amazon Web Services
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.8
14
14
  Classifier: Programming Language :: Python :: 3.9
15
15
  Classifier: Programming Language :: Python :: 3.10
16
16
  Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
17
18
  Requires-Python: >= 3.8
18
19
  Description-Content-Type: text/markdown
19
20
  License-File: LICENSE
@@ -30,10 +31,12 @@ Requires-Dist: pytest-rerunfailures; extra == "test"
30
31
  Requires-Dist: pytest-timeout; extra == "test"
31
32
  Requires-Dist: pytest-xdist; extra == "test"
32
33
  Requires-Dist: scikit-learn; extra == "test"
34
+ Requires-Dist: moto; extra == "test"
33
35
  Provides-Extra: test-prerelease
34
36
  Requires-Dist: mlflow; extra == "test-prerelease"
35
37
  Requires-Dist: packaging; extra == "test-prerelease"
36
38
  Requires-Dist: pytest; extra == "test-prerelease"
39
+ Requires-Dist: moto; extra == "test-prerelease"
37
40
  Dynamic: author
38
41
  Dynamic: classifier
39
42
  Dynamic: description
@@ -0,0 +1 @@
1
+ 0.2.0.dev1
@@ -7,3 +7,4 @@ pytest-rerunfailures
7
7
  pytest-timeout
8
8
  pytest-xdist
9
9
  scikit-learn
10
+ moto
@@ -0,0 +1,6 @@
1
+ mypy
2
+ types-requests
3
+ numpy<=2.2.6
4
+ pyarrow<16
5
+ contourpy<1.3.3
6
+ datasets<4.1.0
@@ -0,0 +1,154 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+
14
+ from typing import Optional
15
+ import boto3
16
+ from requests.auth import AuthBase
17
+ from requests.models import PreparedRequest
18
+ import os
19
+
20
+ from botocore.auth import SigV4Auth
21
+ from botocore.awsrequest import AWSRequest
22
+ from hashlib import sha256
23
+ import functools
24
+ from sagemaker_mlflow.credential_cache import CredentialCache
25
+
26
+ PAYLOAD_BUFFER = 1024 * 1024
27
+ # Hardcode SHA256 hash for empty string to reduce latency for requests without a body
28
+ EMPTY_SHA256_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
29
+
30
+ # Default TTL for cached credentials (55 minutes - safe margin before AWS 1-hour expiration)
31
+ DEFAULT_CREDENTIAL_TTL_SECONDS = 3300
32
+
33
+
34
+ class AuthBoto(AuthBase):
35
+ # Class-level credential cache shared across instances
36
+ _credential_cache = CredentialCache()
37
+
38
+ def __init__(self, region: str, service_name: str, assume_role_arn: Optional[str] = None):
39
+ """
40
+ Constructor for Authorization Mechanism
41
+ :param region: AWS region (e.g., us-west-2)
42
+ :param service_name: AWS service name for signing
43
+ :param assume_role_arn: ARN of the role to assume (optional)
44
+ """
45
+ self._assume_role_arn = assume_role_arn
46
+ self.region = region
47
+
48
+ if assume_role_arn is not None:
49
+ # Use cached or fresh assumed role credentials
50
+ credentials = self._get_cached_credentials(assume_role_arn)
51
+ self.creds = boto3.Session(
52
+ aws_access_key_id=credentials["AccessKeyId"],
53
+ aws_secret_access_key=credentials["SecretAccessKey"],
54
+ aws_session_token=credentials["SessionToken"],
55
+ ).get_credentials()
56
+ else:
57
+ # Use current session credentials
58
+ session = boto3.Session()
59
+ self.creds = session.get_credentials()
60
+
61
+ self.sigv4 = SigV4Auth(self.creds, service_name, self.region)
62
+
63
+ def _get_cached_credentials(self, assume_role_arn: str) -> dict:
64
+ """
65
+ Get cached credentials or fetch new ones via STS assume role.
66
+
67
+ :param assume_role_arn: ARN of the role to assume
68
+ :return: AWS credentials dictionary
69
+ """
70
+ # Try to get credentials from cache first
71
+ cached_credentials = self._credential_cache.get_credentials(assume_role_arn)
72
+ if cached_credentials is not None:
73
+ return cached_credentials
74
+
75
+ # Cache miss - fetch new credentials via STS
76
+ session = boto3.Session()
77
+ sts_client = session.client("sts")
78
+ assumed_role_object = sts_client.assume_role(RoleArn=assume_role_arn, RoleSessionName="AuthBotoSagemakerMlFlow")
79
+ credentials = assumed_role_object["Credentials"]
80
+
81
+ # Get TTL from environment variable with default fallback
82
+ ttl_seconds = int(os.environ.get("SAGEMAKER_MLFLOW_ASSUME_ROLE_TTL_SECONDS", DEFAULT_CREDENTIAL_TTL_SECONDS))
83
+
84
+ # Validate TTL is within reasonable bounds (5 minutes to 1 hour)
85
+ ttl_seconds = max(300, min(ttl_seconds, 3600))
86
+
87
+ # Cache the credentials
88
+ self._credential_cache.set_credentials(assume_role_arn, credentials, ttl_seconds)
89
+
90
+ return credentials
91
+
92
+ def __call__(self, r: PreparedRequest) -> PreparedRequest:
93
+ """Method to return the prepared request
94
+ :param r: PreparedRequest Base mlflow request
95
+ :return: PreparedRequest Request with SigV4 signed headers
96
+ """
97
+
98
+ url = r.url
99
+ method = r.method
100
+ headers = r.headers
101
+ request_body = r.body
102
+ connection_header = headers["Connection"]
103
+
104
+ body_bytes = request_body or b""
105
+ if isinstance(body_bytes, str):
106
+ body_bytes = body_bytes.encode("utf-8")
107
+ headers["X-Amz-Content-SHA256"] = self.get_request_body_header(body_bytes)
108
+
109
+ # SageMaker Mlflow strips out this header before auth.
110
+ # But boto signs every header even its its uppercase or lower cased.
111
+ if "Connection" in headers:
112
+ connection_header = headers["Connection"]
113
+ del headers["Connection"]
114
+
115
+ # Mlflow encodes spaces as +, Auth prefers %20
116
+ if method == "GET" or method == "DELETE":
117
+ url = url.replace("+", "%20")
118
+
119
+ # Creating a new request with the SigV4 signed headers.
120
+ aws_request = AWSRequest(method=method, url=url, data=r.body, headers=headers)
121
+ self.sigv4.add_auth(aws_request)
122
+
123
+ # Adding back in the connection header.
124
+ final_headers = aws_request.headers
125
+ final_headers["Connection"] = connection_header
126
+ final_request = AWSRequest(method=method, url=url, data=r.body, headers=final_headers)
127
+
128
+ return final_request.prepare()
129
+
130
+ def get_request_body_header(self, request_body: bytes):
131
+ """Stripped down version of the botocore method.
132
+ :param request_body: request body
133
+ :return: hex_checksum
134
+ """
135
+ has_seek = hasattr(request_body, "seek")
136
+ has_tell = hasattr(request_body, "tell")
137
+ has_read = hasattr(request_body, "read")
138
+ if request_body and has_seek and has_tell and has_read:
139
+ # Type narrowing: we know request_body has file-like methods
140
+ file_obj = request_body # type: ignore[attr-defined]
141
+ position = file_obj.tell() # type: ignore[attr-defined]
142
+ read_chunksize = functools.partial(file_obj.read, PAYLOAD_BUFFER) # type: ignore[attr-defined]
143
+ checksum = sha256()
144
+ for chunk in iter(read_chunksize, b""):
145
+ checksum.update(chunk)
146
+ hex_checksum = checksum.hexdigest()
147
+ file_obj.seek(position) # type: ignore[attr-defined]
148
+ return hex_checksum
149
+ elif request_body:
150
+ # The request serialization has ensured that
151
+ # request.body is a bytes() type.
152
+ return sha256(request_body).hexdigest()
153
+ else:
154
+ return EMPTY_SHA256_HASH
@@ -13,10 +13,14 @@
13
13
 
14
14
  from sagemaker_mlflow.auth import AuthBoto
15
15
  from mlflow import get_tracking_uri
16
- from sagemaker_mlflow.mlflow_sagemaker_helpers import validate_and_parse_arn
16
+ import os
17
+
18
+ from sagemaker_mlflow.exceptions import ResourceTypeUnsupportedException
19
+ from sagemaker_mlflow.mlflow_sagemaker_helpers import SageMakerMLflowHostMetadataProvider
17
20
 
18
21
  AWS_SIGV4_PLUGIN_NAME = "arn"
19
22
 
23
+
20
24
  class AuthProvider:
21
25
  """Entry Point class to using the plugin. mlflow will call get_name
22
26
  to determine the name of the plugin. get_auth will be called
@@ -24,6 +28,9 @@ class AuthProvider:
24
28
  generate the Sig v4 token.
25
29
  """
26
30
 
31
+ def __init__(self):
32
+ self.host_metadata_provider = SageMakerMLflowHostMetadataProvider()
33
+
27
34
  def get_name(self) -> str:
28
35
  """Returns the name of the plugin"""
29
36
  return AWS_SIGV4_PLUGIN_NAME
@@ -35,5 +42,17 @@ class AuthProvider:
35
42
  AuthBoto: Callback Object which will calculate the header just before request submission.
36
43
  """
37
44
 
38
- arn = validate_and_parse_arn(get_tracking_uri())
39
- return AuthBoto(arn.region)
45
+ self.host_metadata_provider.set_arn(get_tracking_uri())
46
+ assume_role_arn = os.environ.get("SAGEMAKER_MLFLOW_ASSUME_ROLE_ARN")
47
+ return AuthBoto(self.host_metadata_provider.region, self._get_auth_service_name(), assume_role_arn)
48
+
49
+ def _get_auth_service_name(self):
50
+ resource_type = self.host_metadata_provider.resource_type
51
+
52
+ if resource_type == "mlflow-tracking-server":
53
+ return "sagemaker-mlflow"
54
+
55
+ if resource_type == "mlflow-app":
56
+ return "sagemaker"
57
+
58
+ raise ResourceTypeUnsupportedException(resource_type)
@@ -0,0 +1,77 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+
14
+ import threading
15
+ import time
16
+ from typing import Optional, Dict, Any
17
+
18
+
19
+ class CredentialCache:
20
+ """Thread-safe TTL cache for AWS STS assumed role credentials."""
21
+
22
+ def __init__(self) -> None:
23
+ self._cache: Dict[str, Dict[str, Any]] = {}
24
+ self._lock = threading.Lock()
25
+
26
+ def get_credentials(self, role_arn: str) -> Optional[Dict[str, Any]]:
27
+ """
28
+ Retrieve cached credentials for the given role ARN if they haven't expired.
29
+
30
+ Args:
31
+ role_arn (str): The ARN of the role for which to retrieve credentials
32
+
33
+ Returns:
34
+ Optional[Dict[str, Any]]: Cached credentials if valid, None if expired or not found
35
+ """
36
+ with self._lock:
37
+ if role_arn not in self._cache:
38
+ return None
39
+
40
+ cached_entry = self._cache[role_arn]
41
+ current_time = time.time()
42
+
43
+ if current_time >= cached_entry["expires_at"]:
44
+ # Credentials have expired, remove from cache
45
+ del self._cache[role_arn]
46
+ return None
47
+
48
+ return cached_entry["credentials"]
49
+
50
+ def set_credentials(self, role_arn: str, credentials: Dict[str, Any], ttl_seconds: int) -> None:
51
+ """
52
+ Store credentials in the cache with a TTL.
53
+
54
+ Args:
55
+ role_arn (str): The ARN of the role for which to cache credentials
56
+ credentials (Dict[str, Any]): The credentials to cache
57
+ ttl_seconds (int): Time-to-live in seconds
58
+ """
59
+ expires_at = time.time() + ttl_seconds
60
+
61
+ with self._lock:
62
+ self._cache[role_arn] = {"credentials": credentials, "expires_at": expires_at}
63
+ # Clean up expired entries periodically
64
+ self._cleanup_expired()
65
+
66
+ def _cleanup_expired(self) -> None:
67
+ """Remove expired entries from the cache to prevent memory leaks."""
68
+ current_time = time.time()
69
+ expired_keys = [key for key, entry in self._cache.items() if current_time >= entry["expires_at"]]
70
+
71
+ for key in expired_keys:
72
+ del self._cache[key]
73
+
74
+ def clear(self) -> None:
75
+ """Clear all cached credentials. Useful for testing."""
76
+ with self._lock:
77
+ self._cache.clear()
@@ -14,3 +14,9 @@
14
14
 
15
15
  class MlflowSageMakerException(Exception):
16
16
  pass
17
+
18
+
19
+ class ResourceTypeUnsupportedException(MlflowSageMakerException):
20
+ def __init__(self, resource_type: str):
21
+ message = f"Resource type {resource_type} Not supported."
22
+ super().__init__(message)
@@ -0,0 +1,244 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+
14
+ from sagemaker_mlflow.exceptions import MlflowSageMakerException, ResourceTypeUnsupportedException
15
+ import os
16
+ import logging
17
+ import warnings
18
+ from typing import Optional
19
+
20
+
21
+ class Arn:
22
+ """Constructor for Arn Object
23
+
24
+ .. deprecated::
25
+ The Arn class is deprecated. Use SageMakerMLflowHostMetadataProvider instead.
26
+
27
+ Args:
28
+ tracking_server_arn (str): Tracking Server Arn
29
+ """
30
+
31
+ def __init__(self, arn: str):
32
+ warnings.warn(
33
+ "The Arn class is deprecated. Use SageMakerMLflowHostMetadataProvider instead.",
34
+ DeprecationWarning,
35
+ stacklevel=2,
36
+ )
37
+ splitted_arn = arn.split(":")
38
+ self.partition = splitted_arn[1]
39
+ self.service = splitted_arn[2]
40
+ self.region = splitted_arn[3]
41
+ self.account = splitted_arn[4]
42
+ self.resource_type = splitted_arn[5].split("/")[0]
43
+ self.resource_id = splitted_arn[5].split("/")[1]
44
+
45
+ @property
46
+ def maybe_assume_role_arn(self) -> Optional[str]:
47
+ assume_role_arn = os.environ.get("SAGEMAKER_MLFLOW_ASSUME_ROLE_ARN")
48
+ if assume_role_arn:
49
+ # Validate the assume role ARN
50
+ try:
51
+ arn = self.__class__(assume_role_arn)
52
+ if arn.service != "iam" or not arn.resource_type or not arn.resource_id:
53
+ raise MlflowSageMakerException(f"{assume_role_arn} is not a valid arn")
54
+ except (IndexError, AttributeError):
55
+ raise MlflowSageMakerException(f"{assume_role_arn} is not a valid arn")
56
+ return assume_role_arn
57
+
58
+
59
+ def validate_and_parse_arn(tracking_server_arn: str) -> Arn:
60
+ """Validates and returns an arn from a string.
61
+
62
+ .. deprecated::
63
+ This function is deprecated. Use SageMakerMLflowHostMetadataProvider instead.
64
+
65
+ Args:
66
+ tracking_server_arn (str): Tracking Server Arn
67
+ Returns:
68
+ Arn: Arn Object
69
+ """
70
+ warnings.warn(
71
+ "validate_and_parse_arn is deprecated. Use SageMakerMLflowHostMetadataProvider instead.",
72
+ DeprecationWarning,
73
+ stacklevel=2,
74
+ )
75
+ arn = Arn(tracking_server_arn)
76
+ if arn.service != "sagemaker" or not arn.resource_type or not arn.resource_id:
77
+ raise MlflowSageMakerException(f"{tracking_server_arn} is not a valid arn")
78
+ return arn
79
+
80
+
81
+ def get_tracking_server_url(tracking_server_arn: str) -> str:
82
+ """Returns the url used by SageMaker MLflow
83
+
84
+ .. deprecated::
85
+ This function is deprecated. Use SageMakerMLflowHostMetadataProvider.construct_tracking_server_url instead.
86
+
87
+ Args:
88
+ tracking_server_arn (str): Tracking Server Arn
89
+ Returns:
90
+ str: Tracking Server URL.
91
+ """
92
+ warnings.warn(
93
+ "get_tracking_server_url is deprecated. Use "
94
+ "SageMakerMLflowHostMetadataProvider.construct_tracking_server_url instead.",
95
+ DeprecationWarning,
96
+ stacklevel=2,
97
+ )
98
+ custom_endpoint = os.environ.get("SAGEMAKER_MLFLOW_CUSTOM_ENDPOINT", "")
99
+ if custom_endpoint:
100
+ logging.info(f"Using custom endpoint {custom_endpoint}")
101
+ return custom_endpoint
102
+ arn = validate_and_parse_arn(tracking_server_arn)
103
+ dns_suffix = get_dns_suffix(arn.partition)
104
+ endpoint = f"https://{arn.region}.experiments.sagemaker.{dns_suffix}"
105
+ return endpoint
106
+
107
+
108
+ def get_dns_suffix(partition: str) -> str:
109
+ """Returns a DNS suffix for a partition
110
+
111
+ .. deprecated::
112
+ This function is deprecated. Use SageMakerMLflowHostMetadataProvider._get_dns_suffix instead.
113
+
114
+ Args:
115
+ partition (str): Partition that the tracking server resides in.
116
+ Returns:
117
+ str: DNS suffix of the partition
118
+ """
119
+ warnings.warn(
120
+ "get_dns_suffix is deprecated. Use SageMakerMLflowHostMetadataProvider._get_dns_suffix instead.",
121
+ DeprecationWarning,
122
+ stacklevel=2,
123
+ )
124
+ if partition == "aws":
125
+ return "aws"
126
+ elif partition == "aws-us-gov":
127
+ return "aws"
128
+ else:
129
+ raise MlflowSageMakerException(f"Partition {partition} Not supported.")
130
+
131
+
132
+ class SageMakerMLflowHostMetadataProvider:
133
+ """Provider for SageMaker MLflow host metadata and endpoint construction.
134
+
135
+ This class handles parsing SageMaker MLflow ARNs and constructing appropriate
136
+ tracking server URLs for both mlflow-tracking-server and mlflow-app resources.
137
+ """
138
+
139
+ def set_arn(self, sagemaker_mlflow_host_arn: str):
140
+ """Parse and set the SageMaker MLflow host ARN.
141
+
142
+ Args:
143
+ sagemaker_mlflow_host_arn: The SageMaker MLflow ARN to parse
144
+
145
+ Raises:
146
+ MlflowSageMakerException: If the ARN is invalid
147
+ """
148
+ self.arn = sagemaker_mlflow_host_arn
149
+ splitted_arn = sagemaker_mlflow_host_arn.split(":")
150
+ self.partition = splitted_arn[1]
151
+ self.service = splitted_arn[2]
152
+ self.region = splitted_arn[3]
153
+ self.account = splitted_arn[4]
154
+ self.resource_type = splitted_arn[5].split("/")[0]
155
+ self.resource_id = splitted_arn[5].split("/")[1]
156
+
157
+ self._validate_arn()
158
+
159
+ def construct_tracking_server_url(self):
160
+ """Construct the tracking server URL for the configured ARN.
161
+
162
+ Returns:
163
+ str: The tracking server URL
164
+
165
+ Raises:
166
+ MlflowSageMakerException: If the ARN is invalid
167
+ ResourceTypeUnsupportedException: If the resource type is unsupported
168
+ """
169
+ self._validate_arn()
170
+
171
+ custom_endpoint = os.environ.get("SAGEMAKER_MLFLOW_CUSTOM_ENDPOINT", "")
172
+ if custom_endpoint:
173
+ logging.info(f"Using custom endpoint {custom_endpoint}")
174
+ return custom_endpoint
175
+
176
+ return self._get_endpoint()
177
+
178
+ def _validate_arn(self):
179
+ """Validate that the parsed ARN is a valid SageMaker ARN.
180
+
181
+ Raises:
182
+ MlflowSageMakerException: If the ARN is invalid
183
+ """
184
+ if self.service != "sagemaker" or not self.resource_type or not self.resource_id:
185
+ raise MlflowSageMakerException(f"{self.arn} is not a valid arn")
186
+
187
+ def _get_dns_suffix(self) -> str:
188
+ """Get the DNS suffix for the AWS partition.
189
+
190
+ Returns:
191
+ str: The DNS suffix ('aws' for standard and GovCloud partitions)
192
+
193
+ Raises:
194
+ MlflowSageMakerException: If the partition is not supported
195
+ """
196
+ if self.partition == "aws":
197
+ return "aws"
198
+ elif self.partition == "aws-us-gov":
199
+ return "aws"
200
+ else:
201
+ raise MlflowSageMakerException(f"Partition {self.partition} Not supported.")
202
+
203
+ def _get_endpoint(self) -> str:
204
+ """Get the endpoint URL based on the resource type.
205
+
206
+ Returns:
207
+ str: The endpoint URL for the MLflow service
208
+
209
+ Raises:
210
+ ResourceTypeUnsupportedException: If the resource type is not supported
211
+ """
212
+ dns_suffix = self._get_dns_suffix()
213
+
214
+ if self.resource_type == "mlflow-tracking-server":
215
+ return f"https://{self.region}.experiments.sagemaker.{dns_suffix}"
216
+
217
+ if self.resource_type == "mlflow-app":
218
+ return f"https://mlflow.sagemaker.{self.region}.app.{dns_suffix}"
219
+
220
+ raise ResourceTypeUnsupportedException(self.resource_type)
221
+
222
+ @property
223
+ def maybe_assume_role_arn(self) -> Optional[str]:
224
+ """Get the assume role ARN from environment variable if configured.
225
+
226
+ Returns:
227
+ Optional[str]: The assume role ARN if configured, None otherwise
228
+
229
+ Raises:
230
+ MlflowSageMakerException: If the assume role ARN is invalid
231
+ """
232
+ assume_role_arn = os.environ.get("SAGEMAKER_MLFLOW_ASSUME_ROLE_ARN")
233
+ if assume_role_arn:
234
+ # Validate the assume role ARN
235
+ try:
236
+ splitted_arn = assume_role_arn.split(":")
237
+ service = splitted_arn[2]
238
+ resource_type = splitted_arn[5].split("/")[0] if "/" in splitted_arn[5] else None
239
+ resource_id = splitted_arn[5].split("/")[1] if "/" in splitted_arn[5] else None
240
+ if service != "iam" or not resource_type or not resource_id:
241
+ raise MlflowSageMakerException(f"{assume_role_arn} is not a valid arn")
242
+ except (IndexError, AttributeError):
243
+ raise MlflowSageMakerException(f"{assume_role_arn} is not a valid arn")
244
+ return assume_role_arn
@@ -1,9 +1,13 @@
1
1
  from mlflow.store.model_registry.rest_store import RestStore
2
- from sagemaker_mlflow.mlflow_sagemaker_helpers import get_tracking_server_url
3
2
  from mlflow.utils import rest_utils
4
3
  from functools import partial
5
4
  import os
6
5
 
6
+ from sagemaker_mlflow.mlflow_sagemaker_helpers import SageMakerMLflowHostMetadataProvider
7
+
8
+ host_metadata_provider = SageMakerMLflowHostMetadataProvider()
9
+
10
+
7
11
  class MlflowSageMakerRegistryStore(RestStore):
8
12
 
9
13
  store_uri = ""
@@ -31,16 +35,16 @@ _TRACKING_CLIENT_CERT_PATH_ENV_VAR = "MLFLOW_TRACKING_CLIENT_CERT_PATH"
31
35
 
32
36
  def get_host_creds(store_uri):
33
37
  """Configuring mlflow's client"""
34
- tracking_server_url = get_tracking_server_url(store_uri)
38
+ host_metadata_provider.set_arn(store_uri)
39
+
35
40
  return rest_utils.MlflowHostCreds(
36
- host=tracking_server_url,
41
+ host=host_metadata_provider.construct_tracking_server_url(),
37
42
  username=os.environ.get(_TRACKING_USERNAME_ENV_VAR),
38
43
  password=os.environ.get(_TRACKING_PASSWORD_ENV_VAR),
39
44
  token=os.environ.get(_TRACKING_TOKEN_ENV_VAR),
40
45
  auth="arn",
41
46
  # aws_sigv4="False", # Auth provider is used instead for now
42
- ignore_tls_verification=os.environ.get(_TRACKING_INSECURE_TLS_ENV_VAR)
43
- == "true",
47
+ ignore_tls_verification=os.environ.get(_TRACKING_INSECURE_TLS_ENV_VAR) == "true",
44
48
  client_cert_path=os.environ.get(_TRACKING_CLIENT_CERT_PATH_ENV_VAR),
45
49
  server_cert_path=os.environ.get(_TRACKING_SERVER_CERT_PATH_ENV_VAR),
46
50
  )
@@ -12,12 +12,22 @@
12
12
  # language governing permissions and limitations under the License.
13
13
 
14
14
 
15
+ from typing import Dict
16
+
15
17
  from mlflow.tracking.request_header.abstract_request_header_provider import RequestHeaderProvider
16
18
  from mlflow import get_tracking_uri
17
19
 
20
+ from sagemaker_mlflow.exceptions import ResourceTypeUnsupportedException
21
+ from sagemaker_mlflow.mlflow_sagemaker_helpers import SageMakerMLflowHostMetadataProvider
22
+
23
+
18
24
  class MlflowSageMakerRequestHeaderProvider(RequestHeaderProvider):
19
25
  """RequestHeaderProvider provided through plugin system"""
20
26
 
27
+ def __init__(self):
28
+ self.host_metadata_provider = SageMakerMLflowHostMetadataProvider()
29
+ super().__init__()
30
+
21
31
  def in_context(self):
22
32
  """Activates the plugin"""
23
33
  return True
@@ -28,4 +38,18 @@ class MlflowSageMakerRequestHeaderProvider(RequestHeaderProvider):
28
38
  Returns:
29
39
  dict: Dictionary containing the headers that are needed for routing.
30
40
  """
31
- return { "x-mlflow-sm-tracking-server-arn": get_tracking_uri() }
41
+
42
+ self.host_metadata_provider.set_arn(get_tracking_uri())
43
+ return self._get_arn_header()
44
+
45
+ def _get_arn_header(self) -> Dict[str, str]:
46
+ resource_type = self.host_metadata_provider.resource_type
47
+ arn = self.host_metadata_provider.arn
48
+
49
+ if resource_type == "mlflow-tracking-server":
50
+ return {"x-mlflow-sm-tracking-server-arn": arn}
51
+
52
+ if resource_type == "mlflow-app":
53
+ return {"x-sm-mlflow-app-arn": arn}
54
+
55
+ raise ResourceTypeUnsupportedException(resource_type)
@@ -15,7 +15,10 @@ from mlflow.store.tracking.rest_store import RestStore
15
15
  from mlflow.utils import rest_utils
16
16
  import os
17
17
  from functools import partial
18
- from sagemaker_mlflow.mlflow_sagemaker_helpers import get_tracking_server_url
18
+
19
+ from sagemaker_mlflow.mlflow_sagemaker_helpers import SageMakerMLflowHostMetadataProvider
20
+
21
+ host_metadata_provider = SageMakerMLflowHostMetadataProvider()
19
22
 
20
23
  # Extra environment variables which take precedence for setting the basic/bearer
21
24
  # auth on http requests.
@@ -43,16 +46,16 @@ class MlflowSageMakerStore(RestStore):
43
46
 
44
47
  def get_host_creds(store_uri) -> rest_utils.MlflowHostCreds:
45
48
  """Configuring mlflow's client"""
46
- tracking_server_url = get_tracking_server_url(store_uri)
49
+ host_metadata_provider.set_arn(store_uri)
50
+
47
51
  return rest_utils.MlflowHostCreds(
48
- host=tracking_server_url,
52
+ host=host_metadata_provider.construct_tracking_server_url(),
49
53
  username=os.environ.get(_TRACKING_USERNAME_ENV_VAR),
50
54
  password=os.environ.get(_TRACKING_PASSWORD_ENV_VAR),
51
55
  token=os.environ.get(_TRACKING_TOKEN_ENV_VAR),
52
56
  auth="arn",
53
57
  # aws_sigv4="False", # Auth provider is used instead for now
54
- ignore_tls_verification=os.environ.get(_TRACKING_INSECURE_TLS_ENV_VAR)
55
- == "true",
58
+ ignore_tls_verification=os.environ.get(_TRACKING_INSECURE_TLS_ENV_VAR) == "true",
56
59
  client_cert_path=os.environ.get(_TRACKING_CLIENT_CERT_PATH_ENV_VAR),
57
60
  server_cert_path=os.environ.get(_TRACKING_SERVER_CERT_PATH_ENV_VAR),
58
61
  )
@@ -0,0 +1,70 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+
14
+ import os
15
+
16
+ import boto3
17
+ import mlflow
18
+
19
+ from sagemaker_mlflow.exceptions import ResourceTypeUnsupportedException
20
+ from sagemaker_mlflow.mlflow_sagemaker_helpers import SageMakerMLflowHostMetadataProvider
21
+
22
+ host_metadata_provider = SageMakerMLflowHostMetadataProvider()
23
+
24
+
25
+ def get_presigned_url(url_expiration_duration=300, session_duration=5000) -> str:
26
+ """Creates a presigned url
27
+
28
+ :param url_expiration_duration: First use expiration time of the presigned url
29
+ :param session_duration: Session duration of the presigned url
30
+
31
+ :returns: Authorized Url
32
+
33
+ """
34
+ host_metadata_provider.set_arn(mlflow.get_tracking_uri())
35
+
36
+ custom_endpoint = os.environ.get("SAGEMAKER_ENDPOINT_URL", "")
37
+ assume_role_arn = os.environ.get("SAGEMAKER_MLFLOW_ASSUME_ROLE_ARN")
38
+
39
+ session = boto3.Session()
40
+ if assume_role_arn is not None:
41
+ sts_client = session.client("sts")
42
+ assumed_role_object = sts_client.assume_role(RoleArn=assume_role_arn, RoleSessionName="AuthBotoSagemakerMlFlow")
43
+ credentials = assumed_role_object["Credentials"]
44
+ session = boto3.Session(
45
+ aws_access_key_id=credentials["AccessKeyId"],
46
+ aws_secret_access_key=credentials["SecretAccessKey"],
47
+ aws_session_token=credentials["SessionToken"],
48
+ )
49
+
50
+ if not custom_endpoint:
51
+ sagemaker_client = session.client("sagemaker", region_name=host_metadata_provider.region)
52
+ else:
53
+ sagemaker_client = session.client(
54
+ "sagemaker", endpoint_url=custom_endpoint, region_name=host_metadata_provider.region
55
+ )
56
+
57
+ config = {"ExpiresInSeconds": url_expiration_duration, "SessionExpirationDurationInSeconds": session_duration}
58
+
59
+ resource_type = host_metadata_provider.resource_type
60
+
61
+ if resource_type == "mlflow-tracking-server":
62
+ config["TrackingServerName"] = host_metadata_provider.resource_id
63
+ response = sagemaker_client.create_presigned_mlflow_tracking_server_url(**config)
64
+ elif resource_type == "mlflow-app":
65
+ config["Arn"] = host_metadata_provider.arn
66
+ response = sagemaker_client.create_presigned_mlflow_app_url(**config)
67
+ else:
68
+ raise ResourceTypeUnsupportedException(resource_type)
69
+
70
+ return response["AuthorizedUrl"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sagemaker-mlflow
3
- Version: 0.1.1
3
+ Version: 0.2.0.dev1
4
4
  Summary: AWS Plugin for MLflow with SageMaker
5
5
  Home-page: https://github.com/aws/sagemaker-mlflow
6
6
  Author: Amazon Web Services
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.8
14
14
  Classifier: Programming Language :: Python :: 3.9
15
15
  Classifier: Programming Language :: Python :: 3.10
16
16
  Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
17
18
  Requires-Python: >= 3.8
18
19
  Description-Content-Type: text/markdown
19
20
  License-File: LICENSE
@@ -30,10 +31,12 @@ Requires-Dist: pytest-rerunfailures; extra == "test"
30
31
  Requires-Dist: pytest-timeout; extra == "test"
31
32
  Requires-Dist: pytest-xdist; extra == "test"
32
33
  Requires-Dist: scikit-learn; extra == "test"
34
+ Requires-Dist: moto; extra == "test"
33
35
  Provides-Extra: test-prerelease
34
36
  Requires-Dist: mlflow; extra == "test-prerelease"
35
37
  Requires-Dist: packaging; extra == "test-prerelease"
36
38
  Requires-Dist: pytest; extra == "test-prerelease"
39
+ Requires-Dist: moto; extra == "test-prerelease"
37
40
  Dynamic: author
38
41
  Dynamic: classifier
39
42
  Dynamic: description
@@ -15,6 +15,7 @@ requirements/twine_requirements.txt
15
15
  sagemaker_mlflow/__init__.py
16
16
  sagemaker_mlflow/auth.py
17
17
  sagemaker_mlflow/auth_provider.py
18
+ sagemaker_mlflow/credential_cache.py
18
19
  sagemaker_mlflow/exceptions.py
19
20
  sagemaker_mlflow/mlflow_sagemaker_helpers.py
20
21
  sagemaker_mlflow/mlflow_sagemaker_registry_store.py
@@ -11,8 +11,10 @@ pytest-rerunfailures
11
11
  pytest-timeout
12
12
  pytest-xdist
13
13
  scikit-learn
14
+ moto
14
15
 
15
16
  [test_prerelease]
16
17
  mlflow
17
18
  packaging
18
19
  pytest
20
+ moto
@@ -55,7 +55,7 @@ setup(
55
55
  packages=find_packages(),
56
56
  author="Amazon Web Services",
57
57
  license="Apache License 2.0",
58
- url = 'https://github.com/aws/sagemaker-mlflow',
58
+ url="https://github.com/aws/sagemaker-mlflow",
59
59
  classifiers=[
60
60
  "Development Status :: 5 - Production/Stable",
61
61
  "Intended Audience :: Developers",
@@ -66,6 +66,7 @@ setup(
66
66
  "Programming Language :: Python :: 3.9",
67
67
  "Programming Language :: Python :: 3.10",
68
68
  "Programming Language :: Python :: 3.11",
69
+ "Programming Language :: Python :: 3.12",
69
70
  ],
70
71
  # Require MLflow as a dependency of the plugin, so that plugin users can
71
72
  # simply install the plugin and then immediately use it with MLflow
@@ -75,8 +76,12 @@ setup(
75
76
  entry_points={
76
77
  "mlflow.tracking_store": "arn=sagemaker_mlflow.mlflow_sagemaker_store:MlflowSageMakerStore",
77
78
  "mlflow.request_auth_provider": "arn=sagemaker_mlflow.auth_provider:AuthProvider",
78
- "mlflow.request_header_provider": "arn=sagemaker_mlflow.mlflow_sagemaker_request_header_provider:MlflowSageMakerRequestHeaderProvider",
79
- "mlflow.model_registry_store": "arn=sagemaker_mlflow.mlflow_sagemaker_registry_store:MlflowSageMakerRegistryStore"
79
+ "mlflow.request_header_provider": (
80
+ "arn=sagemaker_mlflow.mlflow_sagemaker_request_header_provider:" "MlflowSageMakerRequestHeaderProvider"
81
+ ),
82
+ "mlflow.model_registry_store": (
83
+ "arn=sagemaker_mlflow.mlflow_sagemaker_registry_store:" "MlflowSageMakerRegistryStore"
84
+ ),
80
85
  },
81
86
  version=read_version(),
82
87
  description="AWS Plugin for MLflow with SageMaker",
@@ -1 +0,0 @@
1
- 0.1.1
@@ -1,2 +0,0 @@
1
- mypy
2
- types-requests
@@ -1,97 +0,0 @@
1
- # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License"). You
4
- # may not use this file except in compliance with the License. A copy of
5
- # the License is located at
6
- #
7
- # http://aws.amazon.com/apache2.0/
8
- #
9
- # or in the "license" file accompanying this file. This file is
10
- # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
- # ANY KIND, either express or implied. See the License for the specific
12
- # language governing permissions and limitations under the License.
13
-
14
- import boto3
15
- from requests.auth import AuthBase
16
- from requests.models import PreparedRequest
17
-
18
- from botocore.auth import SigV4Auth
19
- from botocore.awsrequest import AWSRequest
20
- from hashlib import sha256
21
- import functools
22
-
23
- SERVICE_NAME = "sagemaker-mlflow"
24
- PAYLOAD_BUFFER = 1024 * 1024
25
- # Hardcode SHA256 hash for empty string to reduce latency for requests without a body
26
- EMPTY_SHA256_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
27
-
28
-
29
- class AuthBoto(AuthBase):
30
-
31
- def __init__(self, region: str):
32
- """Constructor for Authorization Mechanism
33
- :param region: AWS region eg us-west-2
34
- """
35
-
36
- session = boto3.Session()
37
- self.creds = session.get_credentials()
38
- self.region = region
39
- self.sigv4 = SigV4Auth(self.creds, SERVICE_NAME, self.region)
40
-
41
- def __call__(self, r: PreparedRequest) -> PreparedRequest:
42
- """Method to return the prepared request
43
- :param r: PreparedRequest Base mlflow request
44
- :return: PreparedRequest Request with SigV4 signed headers
45
- """
46
-
47
- url = r.url
48
- method = r.method
49
- headers = r.headers
50
- request_body = r.body
51
- connection_header = headers["Connection"]
52
-
53
- headers["X-Amz-Content-SHA256"] = self.get_request_body_header(request_body)
54
-
55
- # SageMaker Mlflow strips out this header before auth.
56
- # But boto signs every header even its its uppercase or lower cased.
57
- if "Connection" in headers:
58
- connection_header = headers["Connection"]
59
- del headers["Connection"]
60
-
61
- # Mlflow encodes spaces as +, Auth prefers %20
62
- if method == "GET" or method == "DELETE":
63
- url = url.replace("+", "%20")
64
-
65
- # Creating a new request with the SigV4 signed headers.
66
- aws_request = AWSRequest(method=method, url=url, data=r.body, headers=headers)
67
- self.sigv4.add_auth(aws_request)
68
-
69
- # Adding back in the connection header.
70
- final_headers = aws_request.headers
71
- final_headers["Connection"] = connection_header
72
- final_request = AWSRequest(
73
- method=method, url=url, data=r.body, headers=final_headers
74
- )
75
-
76
- return final_request.prepare()
77
-
78
- def get_request_body_header(self, request_body: bytes):
79
- """Stripped down version of the botocore method.
80
- :param request_body: request body
81
- :return: hex_checksum
82
- """
83
- if request_body and hasattr(request_body, "seek"):
84
- position = request_body.tell()
85
- read_chunksize = functools.partial(request_body.read, PAYLOAD_BUFFER)
86
- checksum = sha256()
87
- for chunk in iter(read_chunksize, b""):
88
- checksum.update(chunk)
89
- hex_checksum = checksum.hexdigest()
90
- request_body.seek(position)
91
- return hex_checksum
92
- elif request_body:
93
- # The request serialization has ensured that
94
- # request.body is a bytes() type.
95
- return sha256(request_body).hexdigest()
96
- else:
97
- return EMPTY_SHA256_HASH
@@ -1,82 +0,0 @@
1
- # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License"). You
4
- # may not use this file except in compliance with the License. A copy of
5
- # the License is located at
6
- #
7
- # http://aws.amazon.com/apache2.0/
8
- #
9
- # or in the "license" file accompanying this file. This file is
10
- # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
- # ANY KIND, either express or implied. See the License for the specific
12
- # language governing permissions and limitations under the License.
13
-
14
- from sagemaker_mlflow.exceptions import MlflowSageMakerException
15
- import os
16
- import logging
17
-
18
- class Arn:
19
-
20
- """ Constructor for Arn Object
21
- Args:
22
- tracking_server_arn (str): Tracking Server Arn
23
- """
24
- def __init__(self, arn: str):
25
- splitted_arn = arn.split(":")
26
- self.partition = splitted_arn[1]
27
- self.service = splitted_arn[2]
28
- self.region = splitted_arn[3]
29
- self.account = splitted_arn[4]
30
- self.resource_type = splitted_arn[5].split("/")[0]
31
- self.resource_id = splitted_arn[5].split("/")[1]
32
-
33
-
34
- def validate_and_parse_arn(tracking_server_arn: str) -> Arn:
35
- """Validates and returns an arn from a string.
36
-
37
- Args:
38
- tracking_server_arn (str): Tracking Server Arn
39
- Returns:
40
- Arn: Arn Object
41
- """
42
- arn = Arn(tracking_server_arn)
43
- if (
44
- arn.service != "sagemaker"
45
- or not arn.resource_type
46
- or not arn.resource_id
47
- ):
48
- raise MlflowSageMakerException(f"{tracking_server_arn} is not a valid arn")
49
- return arn
50
-
51
- def get_tracking_server_url(tracking_server_arn: str) -> str:
52
- """Returns the url used by SageMaker MLflow
53
-
54
- Args:
55
- tracking_server_arn (str): Tracking Server Arn
56
- Returns:
57
- str: Tracking Server URL.
58
- """
59
- custom_endpoint = os.environ.get("SAGEMAKER_MLFLOW_CUSTOM_ENDPOINT", "")
60
- if custom_endpoint:
61
- logging.info(f"Using custom endpoint {custom_endpoint}")
62
- return custom_endpoint
63
- arn = validate_and_parse_arn(tracking_server_arn)
64
- dns_suffix = get_dns_suffix(arn.partition)
65
- endpoint = f"https://{arn.region}.experiments.sagemaker.{dns_suffix}"
66
- return endpoint
67
-
68
-
69
- def get_dns_suffix(partition: str) -> str:
70
- """Returns a DNS suffix for a partition
71
-
72
- Args:
73
- partition (str): Partition that the tracking server resides in.
74
- Returns:
75
- str: DNS suffix of the partition
76
- """
77
- if partition == "aws":
78
- return "aws"
79
- elif partition == "aws-us-gov":
80
- return "aws"
81
- else:
82
- raise MlflowSageMakerException(f"Partition {partition} Not supported.")
@@ -1,43 +0,0 @@
1
- # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License"). You
4
- # may not use this file except in compliance with the License. A copy of
5
- # the License is located at
6
- #
7
- # http://aws.amazon.com/apache2.0/
8
- #
9
- # or in the "license" file accompanying this file. This file is
10
- # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
- # ANY KIND, either express or implied. See the License for the specific
12
- # language governing permissions and limitations under the License.
13
-
14
- import os
15
-
16
- import boto3
17
- import mlflow
18
- from sagemaker_mlflow.mlflow_sagemaker_helpers import validate_and_parse_arn
19
-
20
-
21
- def get_presigned_url(url_expiration_duration=300, session_duration=5000) -> str:
22
- """ Creates a presigned url
23
-
24
- :param url_expiration_duration: First use expiration time of the presigned url
25
- :param session_duration: Session duration of the presigned url
26
-
27
- :returns: Authorized Url
28
-
29
- """
30
- arn = validate_and_parse_arn(mlflow.get_tracking_uri())
31
- custom_endpoint = os.environ.get("SAGEMAKER_ENDPOINT_URL", "")
32
- if not custom_endpoint:
33
- sagemaker_client = boto3.client("sagemaker", region_name=arn.region)
34
- else:
35
- sagemaker_client = boto3.client("sagemaker", endpoint_url=custom_endpoint, region_name=arn.region)
36
-
37
- config = {
38
- "TrackingServerName": arn.resource_id,
39
- "ExpiresInSeconds": url_expiration_duration,
40
- "SessionExpirationDurationInSeconds": session_duration
41
- }
42
- response = sagemaker_client.create_presigned_mlflow_tracking_server_url(**config)
43
- return response["AuthorizedUrl"]