Skip to content

Commit 876cb33

Browse files
authored
fix: Fixed getting project ID when running on Vertex AI; Fixes #852 (#943)
1 parent 79aeec1 commit 876cb33

File tree

3 files changed

+128
-0
lines changed

3 files changed

+128
-0
lines changed

google/cloud/aiplatform/initializer.py

+20
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from google.cloud.aiplatform.constants import base as constants
3333
from google.cloud.aiplatform import utils
3434
from google.cloud.aiplatform.metadata import metadata
35+
from google.cloud.aiplatform.utils import resource_manager_utils
3536

3637
from google.cloud.aiplatform.compat.types import (
3738
encryption_spec as gca_encryption_spec_compat,
@@ -149,6 +150,25 @@ def project(self) -> str:
149150
if self._project:
150151
return self._project
151152

153+
# Project is not set. Trying to get it from the environment.
154+
# See https://github.com/googleapis/python-aiplatform/issues/852
155+
# See https://github.com/googleapis/google-auth-library-python/issues/924
156+
# TODO: Remove when google.auth.default() learns the
157+
# CLOUD_ML_PROJECT_ID env variable or Vertex AI starts setting GOOGLE_CLOUD_PROJECT env variable.
158+
project_number = os.environ.get("CLOUD_ML_PROJECT_ID")
159+
if project_number:
160+
# Try to convert project number to project ID which is more readable.
161+
try:
162+
project_id = resource_manager_utils.get_project_id(
163+
project_number=project_number, credentials=self.credentials,
164+
)
165+
return project_id
166+
except Exception:
167+
logging.getLogger(__name__).warning(
168+
"Failed to convert project number to project ID.", exc_info=True
169+
)
170+
return project_number
171+
152172
project_not_found_exception_str = (
153173
"Unable to find your project. Please provide a project ID by:"
154174
"\n- Passing a constructor argument"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# -*- coding: utf-8 -*-
2+
3+
# Copyright 2021 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
18+
import pytest
19+
20+
from google.cloud import aiplatform
21+
from google.cloud.aiplatform.compat.types import pipeline_state as gca_pipeline_state
22+
from tests.system.aiplatform import e2e_base
23+
24+
25+
@pytest.mark.usefixtures("prepare_staging_bucket", "delete_staging_bucket")
26+
class TestProjectIDInference(e2e_base.TestEndToEnd):
27+
28+
_temp_prefix = "temp-vertex-sdk-project-id-inference"
29+
30+
def test_project_id_inference(self, shared_state):
31+
# Collection of resources generated by this test, to be deleted during teardown
32+
shared_state["resources"] = []
33+
34+
aiplatform.init(
35+
location=e2e_base._LOCATION,
36+
staging_bucket=shared_state["staging_bucket_name"],
37+
)
38+
39+
worker_pool_specs = [
40+
{
41+
"machine_spec": {"machine_type": "n1-standard-2"},
42+
"replica_count": 1,
43+
"container_spec": {
44+
"image_uri": "python:3.9",
45+
"command": [
46+
"sh",
47+
"-exc",
48+
"""python3 -m pip install git+https://github.com/Ark-kun/python-aiplatform@fix--Fixed-getitng-project-ID-when-running-on-Vertex-AI#egg=google-cloud-aiplatform&subdirectory=.
49+
"$0" "$@"
50+
""",
51+
"python3",
52+
"-c",
53+
"""
54+
from google.cloud import aiplatform
55+
# Not initializing the Vertex SDK explicitly
56+
# Checking teh project ID
57+
print(aiplatform.initializer.global_config.project)
58+
assert not aiplatform.initializer.global_config.project.endswith("-tp")
59+
# Testing ability to list resources
60+
endpoints = aiplatform.Endpoint.list()
61+
print(endpoints)
62+
""",
63+
],
64+
"args": [],
65+
},
66+
}
67+
]
68+
69+
custom_job = aiplatform.CustomJob(
70+
display_name=self._make_display_name("custom"),
71+
worker_pool_specs=worker_pool_specs,
72+
)
73+
custom_job.run(
74+
enable_web_access=True, sync=False,
75+
)
76+
77+
shared_state["resources"].append(custom_job)
78+
79+
in_progress_done_check = custom_job.done()
80+
custom_job.wait_for_resource_creation()
81+
82+
completion_done_check = custom_job.done()
83+
84+
assert (
85+
custom_job.state
86+
== gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED
87+
)
88+
89+
# Check done() method works correctly
90+
assert in_progress_done_check is False
91+
assert completion_done_check is True

tests/unit/aiplatform/test_initializer.py

+17
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from google.cloud.aiplatform.metadata.metadata import metadata_service
2929
from google.cloud.aiplatform.constants import base as constants
3030
from google.cloud.aiplatform import utils
31+
from google.cloud.aiplatform.utils import resource_manager_utils
3132

3233
from google.cloud.aiplatform_v1.services.model_service import (
3334
client as model_service_client,
@@ -61,6 +62,22 @@ def mock_auth_default():
6162
monkeypatch.setattr(google.auth, "default", mock_auth_default)
6263
assert initializer.global_config.project == _TEST_PROJECT
6364

65+
def test_infer_project_id(self):
66+
cloud_project_number = "123"
67+
68+
def mock_get_project_id(project_number: str, **_):
69+
assert project_number == cloud_project_number
70+
return _TEST_PROJECT
71+
72+
with mock.patch.object(
73+
target=resource_manager_utils,
74+
attribute="get_project_id",
75+
new=mock_get_project_id,
76+
), mock.patch.dict(
77+
os.environ, {"CLOUD_ML_PROJECT_ID": cloud_project_number}, clear=True
78+
):
79+
assert initializer.global_config.project == _TEST_PROJECT
80+
6481
def test_init_location_sets_location(self):
6582
initializer.global_config.init(location=_TEST_LOCATION)
6683
assert initializer.global_config.location == _TEST_LOCATION

0 commit comments

Comments
 (0)