PK!6 yoogcpm/__init__.py# -*- coding: utf-8 -*- from .__version__ import __version__ __program__ = "gcpm" from .__main__ import main PK!U=gcpm/__main__.py# -*- coding: utf-8 -*- """ Main module to launch gcpm cli. """ def main(): from .cli import cli cli() if __name__ == "__main__": main() PK!H2-gcpm/__version__.py__version__ = "0.1.5" PK!ԒFF gcpm/cli.py# -*- coding: utf-8 -*- """ Command line interface for core object """ from .core import Gcpm import fire class CliObject(object): """HTCondor pool manager for Google Cloud Platform.""" def __init__(self, config="~/.config/gcpm/gcpm.yml"): self.config = config def help(self): Gcpm.help() def show_config(self): Gcpm(config=self.config).show_config() def install(self): """Install service related files.""" Gcpm(config=self.config, service=True).install() def uninstall(self): """Uninstall service related files.""" Gcpm(config=self.config, service=True).uninstall() def run(self): """Main function to run the loop.""" Gcpm(config=self.config).run() def service(self): """Run the loop as service.""" Gcpm(config=self.config, service=True).run() def set_pool_password(self, pool_password): """Set pool_password file in google storage.""" Gcpm(config=self.config).get_gcs().upload_file(pool_password) def cli(): fire.Fire(CliObject) PK!ssgcpm/condor.py# -*- coding: utf-8 -*- """ Module to manage HTCondor information """ from .utils import proc def condor_q(opt=[]): return proc(["condor_q"] + opt) def condor_status(opt=[]): return proc(["condor_status"] + opt) def condor_config_val(opt=[]): return proc(["condor_config_val"] + opt) def condor_reconfig(opt=[]): return proc(["condor_reconfig"] + opt) pass def condor_wn(): wn_candidates = condor_status(["-autoformat", "Name"])[1].split() wn_candidates = [x.split(".")[0] for x in wn_candidates] wn_candidates2 = [] for wn in wn_candidates: if "@" in wn: wn_candidates2.append(wn.split("@")[1]) else: wn_candidates2.append(wn) wn_list = list(set(wn_candidates2)) return wn_list def condor_wn_exist(wn_name): if wn_name in condor_wn(): return True else: return False def condor_wn_status(): status = condor_status("-autoformat", "Name", "status")[1] status = {} for line in status.splitlines(): name, status = line.split() name = name.split(".")[0] if "@" in name: name = name.split("@")[1] status[name] = status return status def condor_idle_jobs(): qinfo = condor_q("-allusers", "-global", "-autoformat", "JobStatus", "RequestCpus")[1] idle_jobs = {} for line in qinfo.splitlines(): status, core = line.split() status = int(status) core = int(core) if status == 1: if core not in idle_jobs: idle_jobs[core] = 0 idle_jobs[core] += 1 return idle_jobs PK!dMD<D< gcpm/core.py# -*- coding: utf-8 -*- """ Core module to provides gcpm functions. """ import os import logging import copy import ruamel.yaml from time import sleep from .utils import expand from .files import make_startup_script, make_shutdown_script, make_service,\ make_logrotate, rm_service, rm_logrotate from .condor import condor_status, condor_config_val, condor_reconfig, \ condor_wn, condor_wn_status, condor_idle_jobs from .gce import Gce from .gcs import Gcs class Gcpm(object): """HTCondor pool manager for Google Cloud Platform.""" def __init__(self, config="", service=False): self.logger = None self.is_service = service if config == "": if self.is_service: self.config = "/etc/gcpm.yml" else: self.config = "~/.config/gcpm/gcpm.yml" else: self.config = config self.config = expand(self.config) if self.is_service: config_dir = "/var/cache/gcpm" else: config_dir = "~/.config/gcpm" config_dir = expand(config_dir) self.data = { "config_dir": config_dir, "oauth_file": config_dir + "/oauth", "service_account_file": "", "project": "", "zone": "", "machines": [], "max_cores": 0, "static": [], "prefix": "gcp-wn", "preemptible": 0, "off_timer": 0, "network_tag": [], "reuse": 0, "interval": 10, "head_info": "gcp", "head": "", "port": 9618, "domain": "", "admin": "", "owner": "", "wait_cmd": 0, "bucket": "", "storageClass": "REGIONAL", "location": "", "log_file": None, "log_level": logging.INFO, } self.update_config() log_options = { "format": '%(asctime)s %(message)s', "datefmt": '%b %d %H:%M:%S', } if self.data["log_file"] is not None: log_options["filename"] = self.data["log_file"] if type(self.data["log_level"]) is int\ or self.data["log_level"].isdigit(): log_options["level"] = int(self.data["log_level"]) else: log_options["level"] = self.data["log_level"].upper() log_options["level"] = "DEBUG" logging.basicConfig(**log_options) self.logger = logging.getLogger(__name__) self.services = {} self.gce = None self.gcs = None self.n_wait = 0 self.create_option = "" self.instances_gce = {} self.wns = {} self.prev_wns = {} self.wn_list = "" self.condor_wns = [] self.wn_starting = [] self.wn_deleting = [] self.full_wns = [] self.total_core_use = [] @staticmethod def help(): print(""" """) def check_config(self): return True def read_config(self): yaml = ruamel.yaml.YAML() if not os.path.isfile(self.config): print("GCPM setting file: %s does not exist" % self.config) else: with open(self.config) as stream: data = yaml.load(stream) for k, v in data.items(): self.data[k] = v self.prefix_core = {} for machine in self.data["machines"]: self.prefix_core[machine["core"]] = \ "%s-%dcore" % (self.data["prefix"], machine["core"]) if self.data["location"] == "": if self.data["storageClass"] == "MULTI_REGIONAL": self.data["location"] = self.data["zone"].split("-")[0] else: self.data["location"] = "-".join( self.data["zone"].split("-")[0:2]) if self.data["bucket"] == "": self.data["bucket"] = self.data["project"] + "_" + "gcpm_bucket" if self.data["head"] == "": if self.data["head_info"] == "hostname": self.data["head"] = os.uname()[1] elif self.data["head_info"] == "ip": import socket self.data["head"] = socket.gethostbyname(socket.gethostname()) elif self.data["head_info"] == "gcp": self.data["head"] = os.uname()[1] else: raise ValueError("Both %s and %s are empty" % ("head", "head_info")) if self.data["domain"] == "": self.data["domain"] = ".".join(os.uname()[1].split(".")[1:]) if self.data["wait_cmd"] == 1: self.n_wait = 100 def show_config(self): if self.logger is not None: self.logger.info(self.data) def make_scripts(self): for machine in self.data["machines"]: make_startup_script( filename="%s/startup-%dcore.sh" % (self.data["config_dir"], machine["core"]), core=machine["core"], mem=machine["mem"], disk=machine["disk"], image=machine["image"], preemptible=self.data["preemptible"], admin=self.data["admin"], head=self.data["head"], port=self.data["port"], domain=self.data["domain"], owner=self.data["owner"], bucket=self.data["bucket"], off_timer=self.data["off_timer"], ) make_shutdown_script( filename="%s/shutdown-%dcore.sh" % (self.data["config_dir"], machine["core"]), ) def update_config(self): orig_data = copy.deepcopy(self.data) self.read_config() self.check_config() if orig_data == self.data: return self.show_config() self.make_scripts() def install(self): make_service() make_logrotate(mkdir=False) def uninstall(self): rm_service() rm_logrotate() def get_gce(self): if self.gce is None: self.gce = Gce( oauth_file=self.data["oauth_file"], service_account_file=self.data["service_account_file"], project=self.data["project"], zone=self.data["zone"], ) return self.gce def get_gcs(self): if self.gcs is None: self.gcs = Gcs( oauth_file=self.data["oauth_file"], service_account_file=self.data["service_account_file"], project=self.data["project"], storageClass=self.data["storageClass"], location=self.data["location"], bucket=self.data["bucket"], ) return self.gcs def check_condor_status(self): if condor_status()[0] != 0: self.logger.error("HTCondor is not running!") raise def get_instances_wns(self): instances = {} for instance, info in self.get_instances_wns(): is_use = 0 for core, prefix in self.prefix_core.items(): if instance.startswith(prefix): is_use = 1 break if is_use: instances[instance] = info return instances def get_instances_running(self): return {x: y for x, y in self.get_instances_wns() if y["status"] == "RUNNING"} def get_instances_non_terminated(self): return {x: y for x, y in self.get_instances_wns() if y["status"] != "TERMINATED"} def get_instances_terminated(self): return {x: y for x, y in self.get_instances_wns() if y["status"] == "TERMINATED"} def add_gce_wns(self): for instance, info in self.get_instances_running(): if self.data["head_info"] == "gcp": ip = info["networkIP"] else: ip = info["natIP"] self.wns[instance] = ip def add_remaining_wns(self): # Check instance which is not running, but in condor_status # (should be in the list until it is removed from the status) for wn in condor_wn(): if wn not in self.wns: if wn in self.prev_wns: self.wns[wn] = self.prev_wns[wn] else: self.logger.warning( "%s is listed in the condor status, " "but no information can be taken from gce") def make_wn_list(self): wn_list = "" for name, ip in self.wns.items(): wn_list += \ " $wns condor@$(UID_DOMAIN)/%s condor_pool@$(UID_DOMAIN)/%s" \ % (ip, ip) def update_condor_collector(self): condor_config_val("-collector", "-set" "'WNS = %s'" % self.wn_list) condor_reconfig("-collector") def clean_wns(self): for wn in self.wn_starting: if wn in self.condor_wns: self.wn_starting.remove(wn) exist_list = self.wns.keys() + self.wn_starting + self.wn_deleting instances = [] for instance, info in self.get_instances_wns(): if info["status"] == "TERMINATED": continue instances.append(instance) # Delete condor_off instances if info["status"] == "RUNNING" and instance not in exist_list: self.wn_deleting.append(instance) if self.data["reuse"]: self.get_gce().stop_instance(instance, n_wait=self.n_wait, update=False) else: self.get_gce().delete_instance(instance, n_wait=self.n_wait, update=False) for wn in self.wn_deleting: if wn not in instances: self.wn_deleting.remove(wn) def check_terminated(self): if self.data["reuse"] == 1: return for instance, info in self.get_instances_terminated().items(): if instance in self.wn_starting + self.wn_deleting: continue self.wn_deleting.append(instance) self.get_gce().delete_instance(instance, n_wait=self.n_wait, update=False) def check_wns(self): self.check_terminated() self.full_wns = self.get_instances_non_terminated().keys() + \ self.wn_starting + self.wn_deleting self.total_core_use = 0 for wn in self.full_wns: for core, prefix in self.prefix_core: if wn.startswith(prefix): self.total_core_use += core break def update_wns(self): self.instances_gce = self.get_gce().get_instances(update=True) self.condor_wns = condor_wn() self.prev_wns = self.wns self.wns = {} for s in self.data["static"]: self.wns[s] = s self.add_gce_wns() self.add_remaining_wns() self.make_wn_list() self.update_condor_collector() self.clean_wns() self.check_wns() def check_for_core(self, machine, idle_jobs, wn_status): core = machine["core"] n_idle_jobs = idle_jobs[core] machines = {x: y for x, y in wn_status.items() if x.startswith.prefix_core[core]} n_machines = len(machines) unclaimed = [x for x, y in machines if y == "Unclaimed"] n_unclaimed = len(unclaimed) - n_idle_jobs - machine["idle"] for wn in self.wn_starting: if wn.startswith(self.prefix_core[core]): n_machines += 1 n_unclaimed += 1 if n_machines >= machine["max"]: return False if n_unclaimed > 0: return False if self.data["max_cores"] > 0: if self.total_core_use + core > self.data["max_cores"]: return False return True def start_terminated(self, core): if self.data["reuse"] != 1: return False for instance in self.get_instances_non_terminated(): if instance.startswith(self.prefix_core[core]): self.wn_starting.append(instance) self.get_gce().start_instance(instance, n_wait=self.n_wait, update=False) return True def new_instance(self, instance_name, machine): startup = "%s/startup-%dcore.sh" % (self.data["config_dir"], machine["core"]) shutdown = "%s/shutdown-%dcore.sh" % (self.data["config_dir"], machine["core"]) # memory must be N x 256 (MB) memory = int(machine["mem"]) / 256 * 256 if memory < machine["mem"]: memory += 256 option = { "name": instance_name, "machineType": "custom-%d-%d" % (machine["core"], memory), "tags": {"items": self.data["network_tags"]}, "disks": [ { "boot": True, "autoDelete": True, "initializeParams": { "diskSizeGb": machine["disk"], "sourceImage": "global/images/" + machine["image"] } } ], "metadata": { "items": [ {"key": "startup-script", "value": startup}, {"key": "shutdown-script", "value": shutdown}, ] }, "scheduling": { "preemptible": bool(self.data["preemptible"]) } } self.wn_starting.append(instance_name) self.get_gce().create_instance(intance=instance_name, option=option, n_wait=self.n_wait, update=False) def prepare_wns(self, idle_jobs, wn_status): created = False for machine in self.data["machines"]: if not self.check_for_core(machine, idle_jobs, wn_status): continue if self.start_terminated(): continue n = 1 while n < 10000: instance_name = "%s-%04d" % ( self.prefix_core[machine["core"]], n) if instance_name in self.full_wns: continue self.new_instance(instance_name, machine) created = True break return created def prepare_wns_wrapper(self): idle_jobs = condor_idle_jobs() wn_status = condor_wn_status() while True: if not self.prepare_wns(idle_jobs, wn_status): break def series(self): self.check_condor_status() self.update_config() self.update_wns() self.prepare_wns() sleep(self.data["interval"]) def run(self): self.logger.info("Starting") self.show_config() while True: self.logger.debug("loop top") self.series() PK!D\t gcpm/files.py# -*- coding: utf-8 -*- """ Module to mange Google Cloud Storage. """ import os from .utils import expand __SERVICE_FILE__ = "/usr/lib/systemd/system/gcpm.service" __LOGROTATE_FILE__ = "/etc/logrotate.d/gcpm.conf" def make_file(filename, content="", mkdir=True): filename = expand(filename) directory = os.path.dirname(filename) if not os.path.isdir(directory): if mkdir: os.makedirs(directory) else: return False with open(filename, mode='w') as f: f.write(content) return True def rm_file(filename): if not os.path.isfile(filename): return os.remove(filename) def make_startup_script(filename, core, mem, disk, image, preemptible, admin, head, port, domain, owner, bucket, off_timer=0, mkdir=True): content = """#!/usr/bin/env bash echo "{{\\"date\\": \\"$(date +%s)\\", \\"core\\": {core},\\"mem\\": {mem}, \ \\"disk\\": {disk}, \\"image\\": \\"{image}\\", \ \\"preemptible\\": {preemptible}}}" >/var/log/nodeinfo.log sed -i"" 's/FIXME_ADMIN/{admin}/' /etc/condor/config.d/00_config_local.config sed -i"" 's/FIXME_HOST/{head}/' /etc/condor/config.d/10_security.config sed -i"" 's/FIXME_PORT/{port}/' /etc/condor/config.d/10_security.config sed -i"" 's/FIXME_DOMAIN/{domain}/' /etc/condor/config.d/10_security.config sed -i"" "s/FIXME_PRIVATE_DOMAIN/$(hostname -d)/" \ /etc/condor/config.d/10_security.config sed -i"" 's/FIXME_OWNER/{owner}/' /etc/condor/config.d/20_workernode.config sed -i"" 's/FIXME_CORE/{core}/' /etc/condor/config.d/20_workernode.config sed -i"" 's/FIXME_MEM/{mem}/' /etc/condor/config.d/20_workernode.config gsutil cp "${bucket}/pool_password" /etc/condor/ chmod 600 /etc/condor/pool_password systemctl enable condor systemctl start condor while :;do condor_reconfig status="$(condor_status | grep "${{HOSTNAME}}")" if [ -n "$status" ];then break fi sleep 10 done date >> /root/condor_started""".format(core=core, mem=mem, disk=disk, image=image, preemptible=preemptible, admin=admin, head=head, port=port, domain=domain, owner=owner, bucket=bucket) if off_timer != 0: content += """ sleep {off_timer} condor_off -peaceful -startd date >> /root/condor_off""".format(off_timer=off_timer) make_file(filename, content, mkdir) def make_shutdown_script(filename, mkdir=True): content = """#!/usr/bin/env bash preempted=$(\ curl "http://metadata.google.internal/computeMetadata/v1/instance/preempted" \ -H "Metadata-Flavor: Google") echo "{{\\"date\\": \\"$(date +%s)\\", \\"preempted\\": ${{preempted}}}}" \ >>/var/log/shutdown.log""".format() make_file(filename, content, mkdir) def make_service(filename=__SERVICE_FILE__, mkdir=True): content = """[Unit] Description = HTCondor pool manager for Google Cloud Platform [Service] Environment = "PATH={path}" ExecStart = /usr/bin/gcpm service ExecStop = /usr/bin/kill -p $MAINPID Restart = always StandardOutput = syslog StandardError = syslog SyslogIdentifier = gcpm [Install] WantedBy = multi-user.target""".format(path=os.environ["PATH"]) make_file(filename, content, mkdir) def rm_service(filename=__SERVICE_FILE__): rm_file(filename) def make_logrotate(filename=__LOGROTATE_FILE__, mkdir=True): content = """/var/log/gcpm.log {{ missingok rotate 10 dateext delaycompress daily minsize 100M postrotate systemctl restart gcpm endscript }}""".format() make_file(filename, content, mkdir) def rm_logrotate(filename=__LOGROTATE_FILE__): rm_file(filename) PK!Z@N gcpm/gce.py# -*- coding: utf-8 -*- """ Module to mange Google Compute Engine. """ import logging from copy import deepcopy from time import sleep from .service import get_compute class Gce(object): def __init__(self, oauth_file="", service_account_file="", project="", zone=""): self.oauth_file = oauth_file self.service_account_file = service_account_file self.project = project self.zone = zone self.instances = {} self.compute_service = None self.n_wait = 100 self.wait_time = 10 self.logger = logging.getLogger(__name__) def compute(self): if self.compute_service is None: self.compute_service = get_compute( service_account_file=self.service_account_file, oauth_file=self.oauth_file, ) return self.compute_service def get_zones(self, **zone_filter): zones = [] for zone in self.compute().zones().list( project=self.project).execute()["items"]: is_ok = 1 for k, v in zone_filter.items(): if zone[k] != v: is_ok = 0 continue if is_ok == 1: zones.append(zone["name"]) return zones def get_instance(self, instance, update=True): if update: try: info = self.compute().instances().get( project=self.project, zone=self.zone, instance=instance).execute() except Exception: info = None else: if instance in self.instances.items(): info = self.instances[instance] else: info = None return info def update_instances(self): self.instances = {x["name"]: x for x in self.compute().instances().list( project=self.project, zone=self.zone).execute()["items"]} def get_instances(self, update=True, instance_filter={}): if update: self.update_instances() instances = {} for instance, info in self.instances.items(): is_ok = 1 for k, v in instance_filter.items(): if info[k] != v: is_ok = 0 continue if is_ok == 1: instances[instance] = info return instances def check_instance(self, instance, status="RUNNING", n_wait=-1, wait_time=-1, update=True): if n_wait == -1: n_wait = self.n_wait if wait_time == -1: wait_time = self.wait_time if n_wait <= 0: return True wait = n_wait info = self.get_instance(instance, update) while True: if status == "DELETED": if info is None: return True elif status == "INSERTED": if info is not None: return True else: if info is None: continue if info["status"] == status: return True wait = wait - 1 if wait <= 0: break sleep(wait_time) info = self.get_instance(instance) return False def start_instance(self, instance, n_wait=-1, wait_time=-1, update=True): if not self.check_instance(instance, "TERMINATED", 1, 1, update): self.logger.warning("%s is not TERMINATED status (status=%s)" % (instance, self.instances[instance]["status"])) return False self.compute().instances().start(project=self.project, zone=self.zone, instance=instance).execute() return self.check_instance(instance, "RUNNING", n_wait, wait_time) def stop_instance(self, instance, n_wait=-1, wait_time=-1, update=True): if not self.check_instance(instance, "RUNNING", 1, 1, update): self.logger.warning("%s is not RUNNING status (status=%s)" % (instance, self.instances[instance]["status"])) return False self.compute().instances().stop(project=self.project, zone=self.zone, instance=instance).execute() return self.check_instance(instance, "TERMINATED", n_wait, wait_time) def get_source_disk_image(self, family, project=""): if project == "": project = self.project image_response = self.compute().images().getFromFamily( project=project, family=family).execute() return image_response['selfLink'] def insert_instance(self, instance, n_wait=-1, wait_time=-1, option={}, update=True): if self.check_instance(instance, "INSERTED", 1, 1, update): self.logger.warning("%s already exists" % instance) return False opt = deepcopy(option) if "name" not in opt: opt["name"] = instance if not opt["machineType"].startswith("zones"): opt["machineType"] = "zones/%s/machineTypes/%s" % ( self.zone, opt["machineType"]) if "family" in opt: if "project" in opt: project = opt["project"] else: project = self.project source_disk_image = self.get_source_disk_image(opt["family"], project) del opt["family"] if "disks" not in opt: opt["disks"] = [{}] opt["disks"][0] = { "boot": True, "autoDelete": True, } if "initializeParams" not in opt["disks"][0]: opt["disks"][0]["initializeParams"] = {} opt["disks"][0]["initializeParams"]["sourceImage"] =\ source_disk_image if "networkInterfaces" not in opt: opt["networkInterfaces"] = [{ "network": "global/networks/default", "accessConfigs": [ {"type": "ONE_TO_ONE_NAT", "name": "External NAT"} ] }] if "disks" not in opt: opt["networkInterfaces"] = [{ "network": "global/networks/default", "accessConfigs": [ {"type": "ONE_TO_ONE_NAT", "name": "External NAT"} ] }] self.compute().instances().insert(project=self.project, zone=self.zone, body=opt).execute() if opt["disks"][0]["boot"]: return self.check_instance(instance, "RUNNING", n_wait, wait_time) else: return self.check_instance(instance, "INSERTED", n_wait, wait_time) def create_instance(self, instance, n_wait=-1, wait_time=-1, option={}, update=True): return self.insert_instance(instance, n_wait, wait_time, option, update) def delete_instance(self, instance, n_wait=-1, wait_time=-1, update=True): if self.check_instance(instance, "DELETED", 1, 1, update): self.logger.warning("%s does not exist)" % instance) return False self.compute().instances().delete( project=self.project, zone=self.zone, instance=instance, ).execute() return self.check_instance(instance, "DELETED", n_wait, wait_time) PK!?I gcpm/gcs.py# -*- coding: utf-8 -*- """ Module to mange Google Cloud Storage. """ import os import logging import googleapiclient from .service import get_storage from .utils import expand class Gcs(object): def __init__(self, oauth_file="", service_account_file="", project="", storageClass="", location="", bucket=""): self.oauth_file = oauth_file self.service_account_file = service_account_file self.project = project self.storageClass = storageClass self.location = location self.bucket = bucket self.storage_service = None self.logger = logging.getLogger(__name__) def storage(self): if self.storage_service is None: self.storage_service = get_storage( service_account_file=self.service_account_file, oauth_file=self.oauth_file, ) return self.storage_service def is_bucket(self): return True if self.bucket in self.get_buckets() else False def get_buckets(self): bucket_list = [x["name"] for x in self.storage().buckets().list( project=self.project).execute()["items"]] return bucket_list def delete_bucket(self): if not self.is_bucket(): return self.storage().buckets().delete(bucket=self.bucket).execute() def create_bucket(self): if self.is_bucket(): return body = {"name": self.bucket, "sotrageClass": self.storageClass, "location": self.location, } return self.storage().buckets().insert(project=self.project, body=body).execute() def upload_file(self, file_name): self.create_bucket() with open(expand(file_name), 'rb') as f: response = self.storage().objects().insert( bucket=self.bucket, media_body=googleapiclient.http.MediaIoBaseUpload( f, 'application/octet-stream'), name=os.path.basename(file_name)).execute() return response def delete_file(self, file_name): return self.storage().objects().delete( bucket=self.bucket, object=file_name).execute() PK!{鰹 gcpm/service.py# -*- coding: utf-8 -*- """ Module to provide google service management """ import os import sys from .utils import expand from .__init__ import __version__ from .__init__ import __program__ import httplib2 from google.oauth2 import service_account from oauth2client.file import Storage from oauth2client.tools import run_flow from oauth2client.tools import argparser from oauth2client.client import OAuth2WebServerFlow from apiclient.discovery import build __CLIENT_ID__ =\ "154689602688-rmimpcfc5d5th2nb2rbap02sujh0ehtg.apps.googleusercontent.com" __CLIENT_SECRET__ = "LouXW0cr1pkCoi8QtTOweld2" def service_from_oauth(oauth_file, api_name, api_version, scope): oauth_file = expand(oauth_file) oauth_dir = os.path.dirname(oauth_file) if not os.path.isdir(oauth_dir): os.makedirs(oauth_dir) storage = Storage(oauth_file) credentials = storage.get() if credentials is None or credentials.invalid: args, unknown = argparser.parse_known_args(sys.argv) credentials = run_flow( OAuth2WebServerFlow( client_id=__CLIENT_ID__, client_secret=__CLIENT_SECRET__, scope=scope, user_agent=__program__ + '/' + __version__), storage, args) http = httplib2.Http() http = credentials.authorize(http) service = build(api_name, api_version, http=http, cache_discovery=False) return service def service_from_service_account( service_account_file, api_name, api_version, scope): f = expand(service_account_file) credentials = service_account.Credentials.from_service_account_file( f, scopes=scope) service = build(api_name, api_version, credentials=credentials, cache_discovery=False) return service def get_service(service_account_file="", oauth_file="~/.config/gcpm/oauth", scope=["https://www.googleapis.com/auth/cloud-platform"], api_name="compute", api_version="v1"): if service_account_file == "": service = service_from_oauth( oauth_file=oauth_file, api_name=api_name, api_version=api_version, scope=scope) else: service = service_from_service_account( service_account_file=service_account_file, api_name=api_name, api_version=api_version, scope=scope) return service def get_compute(service_account_file="", oauth_file="~/.config/gcpm/oauth"): return get_service(service_account_file=service_account_file, oauth_file=oauth_file, scope=[ "https://www.googleapis.com/auth/compute" ], api_name="compute", api_version="v1") def get_storage(service_account_file="", oauth_file="~/.config/gcpm/oauth"): return get_service(service_account_file=service_account_file, oauth_file=oauth_file, scope=[ "https://www.googleapis.com/auth/cloud-platform" ], api_name="storage", api_version="v1") PK!ϭ~xx gcpm/utils.py# -*- coding: utf-8 -*- """ Module to provide utilities """ def expand(path): import os return os.path.expandvars(os.path.expanduser(path)) def proc(cmd): import subprocess p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() return (p.returncode, stdout, stderr) PK!Hy !"%gcpm-0.1.5.dist-info/entry_points.txtN+I/N.,()JO.ȵVy\\PK!#q,q,gcpm-0.1.5.dist-info/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2019] ["Michiru Kaneda "] 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 http://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. PK!HWYgcpm-0.1.5.dist-info/WHEEL A н#Z;/"b&F]xzwC;dhfCSTֻ0*Ri.4œh6-]{H, JPK!H"0gcpm-0.1.5.dist-info/METADATAW[s6~@}8")9Vdqw}Dig5IpЊ:@RS$\|RXqˣ_6R#v+^[Utx &uQp3`'36ι+]UfJR9%_|P*,GlimeFIvYTI![^'N݅LEi@z\t)xv]t)uH\e/SR|&AG޾9_oǃ8a8l08ɹ1r.7ш]Oa^՝hMe5+EK>jyQr.xF'r<*}/9}/9Y-`#^ɨr¢48 yWIs9; E7LV"]ר<^"o|_9_藏#QTHz{/LeeQ”ӺBZ&L xgg'^py&|>hI2VzqϤ->ӼLo nн1 jRd4햱#XH嘒"/ >Lj3v^s!tt9t@ܻXlݠmK%/ `a^DNC7r?fXxvc^ÇsVqDp`;:,jI<"w~v!@<$$6gE^%:xj<#__}aU~t]%SbUR;U"l2Pp k4}~y-6hL%`Eцzw i&5ڰd)py7Pa&|ҽ~%]mJ f9uN1BƬb4%N.ON loלÐD7j___@*`jP۰wmclҷ OmF#%hÐFiM20u3kj"cv&X3U]\܉|1;Lj̴}(f~˕J6-=iPK!H}gcpm-0.1.5.dist-info/RECORDmɮ@}_ f*E/ DeI d(dMl;*ŷw au[>?`7=1Oq&yJ^5^:ASQ͑0_!gd iֆQ-E68}D};SNu;2)iI;6,;CܤbTn#>ˌ1|Iq>,r|ǮpجO[+&\Pg-Cyb9ԗ`4%0ݝ=!~طzI>ҭ|XtT3pvNՒ!ݼQJ_4Ƨ?WliRT&PZP.9,]9pc ǁV[Av5'5b(R3CkVXz3=p[,am¯# %a)m|vn5j|2nE cP8Ӥַja/O }kXӎƈNsZ AVa` 31ad_ >ω@N~gr\ ħՆ~Y_~X:m~'-A WSqϰW7ZJ%>ɨDl?۪$-IG hڑڙɝ=^I8;\ǧTc.)ogۋ6#O? u an4*/Q-7aϠ&:p6܇c 5dI{b6\ys Mр~V-Q0 PK!6 yoogcpm/__init__.pyPK!U=gcpm/__main__.pyPK!H2-igcpm/__version__.pyPK!ԒFF gcpm/cli.pyPK!ssgcpm/condor.pyPK!dMD<D< gcpm/core.pyPK!D\t ,Igcpm/files.pyPK!Z@N Wgcpm/gce.pyPK!?I vgcpm/gcs.pyPK!{鰹 gcpm/service.pyPK!ϭ~xx gcpm/utils.pyPK!Hy !"%Ggcpm-0.1.5.dist-info/entry_points.txtPK!#q,q,gcpm-0.1.5.dist-info/LICENSEPK!HWYVgcpm-0.1.5.dist-info/WHEELPK!H"0gcpm-0.1.5.dist-info/METADATAPK!H}Pgcpm-0.1.5.dist-info/RECORDPK g