STRIDES / NIHCloudLabGCP

Documentation and tutorials on using GCP for biomedical research
https://cloud.nih.gov/resources/cloudlab/
20 stars 16 forks source link

Explore Shutdown Script as Jupyter Notebook cell #41

Closed kyleoconnell-NIH closed 1 year ago

kyleoconnell-NIH commented 1 year ago

Paste the following into a Jupyter cell and see if it forces shutdown after a certain time idle.

from google.cloud import notebooks_v1

project_id="projectid" location="east1-a"

client = notebooks_v1.NotebookServiceClient()

def get_all_instances(project, location):

request = notebooks_v1.ListInstancesRequest(
    parent=f"projects/{project_id}/locations/{location}"
)
page_result = client.list_instances(request=request)
instances = list(page_result)

#The following line would print data for all instances
#print(instances)

return instances

def stop_instance(instance_name):

print(f"Stopping instance {instance_name}")

request = notebooks_v1.StopInstanceRequest(
    name=instance_name
)

operation = client.stop_instance(request=request)

print("Waiting for operation to complete...")

response = operation.result()

print(response.state)

all_instances = get_all_instances(project_id, location) first_instance = all_instances[0]

Double check instance name while testing to prevent accidents :)

notebook_instance_name = "notebook-name" full_notebook_instance_name = f"projects/{project_id}/locations/{location}/instances/{notebook_instance_name}" if first_instance.name == full_notebook_instance_name: stop_instance(first_instance.name)

kyleoconnell-NIH commented 1 year ago

We just added the idle shutdown documentation to the Vertex AI docs, which we updated in the most recent PR