我正在搞乱谷歌提供的示例代码,我希望确定一个实例何时准备好工作。它们具有操作'DONE'
状态,并且它们具有实例'RUNNING'
状态,但在实际使用该实例之前仍有延迟。在没有等待设定的时间段的情况下等待这种情况的最佳方法是什么(因为如果实例准备好的话,这会浪费时间)?
我修改了他们的wait_for_operation
功能,因此它使用了isUp
:
# [START wait_for_operation]
def wait_for_operation(compute, project, zone, operation):
print('Waiting for operation to finish...')
while True:
result = compute.zoneOperations().get(
project=project,
zone=zone,
operation=operation).execute()
if result['status'] == 'DONE':
print("done.")
print("result:")
print(result)
if 'error' in result:
raise Exception(result['error'])
print("before ex")
instStatus = compute.instances().get(
project=project,
zone=zone,
instance='inst-test1').execute()
print("after ex")
if instStatus['status'] == 'RUNNING':
if isUp("10.xxx.xx.xx"):
print("instStatus = ")
print(instStatus)
return result
else:
print("wasn't replying to ping")
time.sleep(1)
# [END wait_for_operation]
def isUp(hostname):
giveFeedback = False
if platform.system() == "Windows":
response = os.system("ping "+hostname+" -n 1")
else:
response = os.system("ping -c 1 " + hostname)
isUpBool = False
if response == 0:
if giveFeedback:
print( hostname + 'is up!')
isUpBool = True
else:
if giveFeedback:
print( hostname + 'is down!')
return isUpBool
请参阅Matthew对原始isUp
代码的回答:Pinging servers in Python
其他大多数代码都来自这里: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/compute/api/create_instance.py
GCP状态链接: https://cloud.google.com/compute/docs/instances/checking-instance-status
我的代码有效,但有没有更好的方法使用实例状态或其他东西并避免整个isUp
/ ping内容?好像我的方法是一种不必要的解决方法。
显然我正在使用Python,而这只是用不必要的打印等来搞乱代码。
我有一个Windows 7工作站,我不想要求管理员权限和Linux实例。
编辑1:“准备工作”,我的意思是我可以向它发送命令,它会响应。
答案 0 :(得分:0)
您好我建议您使用全球运营。 https://cloud.google.com/compute/docs/reference/rest/beta/globalOperations/get
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'beta', credentials=credentials)
# Project ID for this request.
project = 'my-project' # TODO: Update placeholder value.
# Name of the Operations resource to return.
operation = 'my-operation' # TODO: Update placeholder value.
request = service.globalOperations().get(project=project, operation=operation)
response = request.execute()
# TODO: Change code below to process the `response` dict:
pprint(response)
答案 1 :(得分:0)
我使用的一种方法是在实例元数据中使用启动脚本create a field。然后,您可以使用您的代码检查实例状态,并查看是否已添加新元数据。然后,您可以避免ping服务器。另一个好处是,如果实例没有外部IP,则此方法仍然有效。
instStatus = compute.instances().get(
project=project,
zone=zone,
instance='inst-test1').execute()