Skip to content

Commit f753467

Browse files
authored
Optimize GCP list usable subnets across regions (#2494)
1 parent f149f83 commit f753467

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/dstack/_internal/core/backends/gcp/resources.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,16 @@ def check_vpc(
5353
if shared_vpc_project_id:
5454
vpc_project_id = shared_vpc_project_id
5555
try:
56+
usable_subnets = list_project_usable_subnets(
57+
subnetworks_client=subnetworks_client, project_id=vpc_project_id
58+
)
5659
for region in regions:
5760
get_vpc_subnet_or_error(
5861
subnetworks_client=subnetworks_client,
5962
vpc_project_id=vpc_project_id,
6063
vpc_name=vpc_name,
6164
region=region,
65+
usable_subnets=usable_subnets,
6266
)
6367
except google.api_core.exceptions.NotFound:
6468
raise ComputeError(f"Failed to find VPC project {vpc_project_id}")
@@ -212,18 +216,28 @@ def _get_network_interfaces(
212216
return network_interfaces
213217

214218

219+
def list_project_usable_subnets(
220+
subnetworks_client: compute_v1.SubnetworksClient,
221+
project_id: str,
222+
) -> List[compute_v1.UsableSubnetwork]:
223+
request = compute_v1.ListUsableSubnetworksRequest(project=project_id)
224+
return [s for s in subnetworks_client.list_usable(request=request)]
225+
226+
215227
def get_vpc_subnet_or_error(
216228
subnetworks_client: compute_v1.SubnetworksClient,
217229
vpc_project_id: str,
218230
vpc_name: str,
219231
region: str,
232+
usable_subnets: Optional[List[compute_v1.UsableSubnetwork]] = None,
220233
) -> str:
221234
"""
222235
Returns resource name of any usable subnet in a given VPC
223236
(e.g. "projects/example-project/regions/europe-west4/subnetworks/example-subnet")
224237
"""
225-
request = compute_v1.ListUsableSubnetworksRequest(project=vpc_project_id)
226-
for subnet in subnetworks_client.list_usable(request=request):
238+
if usable_subnets is None:
239+
usable_subnets = list_project_usable_subnets(subnetworks_client, vpc_project_id)
240+
for subnet in usable_subnets:
227241
network_name = subnet.network.split("/")[-1]
228242
subnet_url = subnet.subnetwork
229243
subnet_resource_name = remove_prefix(subnet_url, "https://www.googleapis.com/compute/v1/")

0 commit comments

Comments
 (0)