monkey/envs/monkey_zoo/blackbox/utils/gcp_machine_handlers.py

48 lines
1.9 KiB
Python
Raw Normal View History

2019-08-27 23:12:14 +08:00
import subprocess
2019-10-01 15:42:51 +08:00
import logging
2019-08-27 23:12:14 +08:00
class GCPHandler(object):
AUTHENTICATION_COMMAND = "gcloud auth activate-service-account --key-file=%s"
2019-08-28 19:56:35 +08:00
SET_PROPERTY_PROJECT = "gcloud config set project %s"
2019-08-27 23:12:14 +08:00
MACHINE_STARTING_COMMAND = "gcloud compute instances start %s --zone=%s"
MACHINE_STOPPING_COMMAND = "gcloud compute instances stop %s --zone=%s"
2019-08-28 19:56:35 +08:00
def __init__(self, key_path="../gcp_keys/gcp_key.json", zone="europe-west3-a", project_id="guardicore-22050661"):
2019-08-27 23:12:14 +08:00
self.zone = zone
try:
2019-08-28 19:56:35 +08:00
# pass the key file to gcp
2019-08-27 23:12:14 +08:00
subprocess.call(GCPHandler.get_auth_command(key_path), shell=True)
2019-10-01 15:42:51 +08:00
logging.info("GCP Handler passed key")
2019-08-28 19:56:35 +08:00
# set project
subprocess.call(GCPHandler.get_set_project_command(project_id), shell=True)
2019-10-01 15:42:51 +08:00
logging.info("GCP Handler set project")
logging.info("GCP Handler initialized successfully")
2019-08-27 23:12:14 +08:00
except Exception as e:
2019-10-01 15:42:51 +08:00
logging.error("GCP Handler failed to initialize: %s." % e)
2019-08-27 23:12:14 +08:00
def start_machines(self, machine_list):
2019-10-01 15:42:51 +08:00
logging.info("Setting up all GCP machines...")
2019-08-27 23:12:14 +08:00
try:
subprocess.call((GCPHandler.MACHINE_STARTING_COMMAND % (machine_list, self.zone)), shell=True)
2019-10-01 15:42:51 +08:00
logging.info("GCP machines successfully started.")
2019-08-27 23:12:14 +08:00
except Exception as e:
2019-10-01 15:42:51 +08:00
logging.error("GCP Handler failed to start GCP machines: %s" % e)
2019-08-27 23:12:14 +08:00
def stop_machines(self, machine_list):
try:
subprocess.call((GCPHandler.MACHINE_STOPPING_COMMAND % (machine_list, self.zone)), shell=True)
2019-10-01 15:42:51 +08:00
logging.info("GCP machines stopped successfully.")
2019-08-27 23:12:14 +08:00
except Exception as e:
2019-10-01 15:42:51 +08:00
logging.error("GCP Handler failed to stop network machines: %s" % e)
2019-08-27 23:12:14 +08:00
@staticmethod
def get_auth_command(key_path):
return GCPHandler.AUTHENTICATION_COMMAND % key_path
2019-08-28 19:56:35 +08:00
@staticmethod
def get_set_project_command(project):
return GCPHandler.SET_PROPERTY_PROJECT % project