-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
150 lines (131 loc) · 7.32 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import functions_framework
from google import auth
from google.auth.transport.requests import AuthorizedSession
from google.cloud import resourcemanager_v3
from datetime import datetime,timezone
from dateutil.parser import isoparse
PROJECT_ID = os.environ.get("PROJECT_ID", "the-foo-bar") # Update placeholder value when this environment variable is not set. 'Specified environment variable is not set.'
SHUTDOWN_SECONDS_METADATA_KEY = os.environ.get("SHUTDOWN_SECONDS_METADATA_KEY", "auto-shutdown-seconds") # Look for this key in notebooks metadata value, defaults to "auto-shutdown-seconds"
REGION_LIST = ["us-central1"] # will only stop instances in this list of regions
NOTEBOOKS_API_VERSION = os.environ.get("NOTEBOOKS_API_VERSION", "v1") # defaults to "v1" notebooks API which is User-Managed Notebooks (UmN). Workbench Instances (WbI) uses v2.
# https://cloud.google.com/python/docs/reference/cloudresourcemanager/latest/google.cloud.resourcemanager_v3.services.projects.ProjectsClient#google_cloud_resourcemanager_v3_services_projects_ProjectsClient_search_projects
def get_project_ids():
client = resourcemanager_v3.ProjectsClient()
# Construct the request argument
request = resourcemanager_v3.SearchProjectsRequest(
query="state:ACTIVE",
)
projects = client.search_projects(request=request)
# Iterate
project_ids = []
for project in projects:
print(project.project_id)
project_ids.append(project.project_id)
return project_ids
# Gets supported locations for the notebooks service given a Project ID - V1 API
# https://cloud.google.com/ai-platform/notebooks/docs/reference/rest/v1/projects.locations/list
# Gets supported locations for the notebooks service given a Project ID - V2 API
# https://cloud.google.com/ai-platform/notebooks/docs/reference/rest/v2/projects.locations/list
def get_instance_location_ids(project_id, version = 'v1'):
credentials, project = auth.default(scopes = ['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
# Get zone resources available to the project
response = authed_session.get(f"https://notebooks.googleapis.com/{version}/projects/{project_id}/locations")
locations_json = response.json()
location_ids = []
try:
locations = locations_json["locations"]
for location in locations:
location_ids.append(location["locationId"])
except:
location_ids = []
return location_ids
# Delete User-Managed Notebooks (UmN) using REST API Commands - V1 API
# Delete Workbench Instances (WbI) using REST API Commands - V2 API
# https://cloud.google.com/vertex-ai/docs/workbench/reference/rest
def delete_instance_rest(instance_name, version = 'v1'):
credentials, project = auth.default(scopes = ['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
response = authed_session.delete(f"https://notebooks.googleapis.com/{version}/{instance_name}")
return response
# Stop User-Managed Notebooks (UmN) using REST API Commands - V1 API
# Stop Workbench Instances (WbI) using REST API Commands - V2 API
# https://cloud.google.com/vertex-ai/docs/workbench/reference/rest
def stop_instance_rest(request):
version = NOTEBOOKS_API_VERSION
credentials, project = auth.default(scopes = ['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
project_ids = get_project_ids()
return_response = {}
for project_id in project_ids:
now_utc = datetime.now(timezone.utc)
location_ids = get_instance_location_ids(project_id, version)
for location_id in location_ids:
# this example only inspects instances in a region, exclude this to run for all zones
skip = False
for region in REGION_LIST:
if (region not in location_id) or (region == location_id):
skip = True
if skip:
continue
# Get AI Platform notebook instances
response = authed_session.get(f"https://notebooks.googleapis.com/{version}/projects/{project_id}/locations/{location_id}/instances")
instances_json = response.json()
# If the response is empty, continue
if not instances_json:
continue
instances = instances_json["instances"]
# Documentation
# https://cloud.google.com/ai-platform/notebooks/docs/reference/rest/v1/projects.locations.instances/stop
# https://cloud.google.com/ai-platform/notebooks/docs/reference/rest/v2/projects.locations.instances/stop
for instance in instances:
instance_name = instance["name"]
print("-------", "Instance name:", instance_name, "-------")
# print(json.dumps(instance, indent=4))
auto_shutdown_seconds = 0
try:
if version == 'v2':
print(instance["gceSetup"]["metadata"])
auto_shutdown_seconds = int(instance["gceSetup"]["metadata"][SHUTDOWN_SECONDS_METADATA_KEY])
else:
print(instance["metadata"])
auto_shutdown_seconds = int(instance["metadata"][SHUTDOWN_SECONDS_METADATA_KEY])
print(SHUTDOWN_SECONDS_METADATA_KEY, "metadata set to:", auto_shutdown_seconds)
except:
print(SHUTDOWN_SECONDS_METADATA_KEY, "metadata not set, skip...")
continue
if instance["state"] != "ACTIVE":
print("Instance isn't ACTIVE, skip...")
continue
update_time = instance["updateTime"]
update_time_iso = update_time.replace("Z", "+00:00")
print("timeNow:", now_utc.isoformat())
print("updatedTime:", update_time_iso)
t1 = isoparse(update_time_iso)
t2 = isoparse(now_utc.isoformat())
# get difference
delta = t2 - t1
delta_seconds = delta.total_seconds()
print("Difference in seconds between updatedTime and timeNow:", delta_seconds)
if (delta_seconds >= auto_shutdown_seconds) and delta_seconds >= 0:
print("Stopping server...")
response = authed_session.post(f"https://notebooks.googleapis.com/{version}/{instance_name}:stop")
print(response.json())
return_response[instance_name] = response.json()
else:
print("Shutdown threshold not hit, skip...")
return return_response