# Path: nuka/task.py
# def get_task_from_stack():
#     for info in inspect.stack(3):
#         f = info.frame
#         self = f.f_locals.get('self')
#         if isinstance(f.f_locals.get('self'), Base):
#             return self
# 
# Path: nuka/hosts/base.py
# RLIMIT_NOFILE = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
# MAX_PROCESSES = int(RLIMIT_NOFILE / 4)
# class HostGroup(OrderedDict):
# class TimeIt(object):
# class BaseHost(object):
# class Host(BaseHost):
# class LocalHost(BaseHost):
# class Chroot(BaseHost):
#     async def boot(self):
#     async def destroy(self):  # pragma: no cover
#     def __repr__(self):
#     def __init__(self, host, task=None, **kwargs):
#     def __enter__(self, *args, **kwargs):
#     def __exit__(self, *args, **kwargs):
#     def __init__(self, hostname=None, port='22', **vars):
#     def log(self):
#     def add_task(self, task):
#     def running_tasks(self):
#     def timeit(self, task=None, **kwargs):
#     def add_time(self, start=None, task=None, **kwargs):
#     def cancel(self):
#     def cancelled(self):
#     def fail(self, exc):
#     def failed(self):
#     def _get_best_addresses(self, public=True):
#     def public_ip(self):
#     def private_ip(self):
#     def __getattr__(self, attr):
#     def __str__(self):
#     def __repr__(self):
#     def bootstrap_command(self):
#     async def boot(self):  # pragma: no cover
#     async def get_inventory(self):  # pragma: no cover
#     async def destroy(self):  # pragma: no cover
#     async def acquire_session_slot(self):
#     def free_session_slot(self):
#     async def create_process(self, cmd, task=None, **kwargs):
#     async def run_command(self, cmd=None, stdin=None, task=None, **kwargs):
#     async def send_messages(self, message):  # pragma: no cover
#     def from_stdin(cls):
#     def __init__(self, *args, **kwargs):
#     def wraps_command_line(self, cmd, **kwargs):
#     def __init__(self):
#     def wraps_command_line(self, cmd, **kwargs):
#     def __init__(self, path):
#     def wraps_command_line(self, cmd, **kwargs):
# 
# Path: nuka/utils.py
# PY3 = sys.version_info[0] == 3
# ARCHIVE_EXTS = ('.gz', '.tar', '.zip')
# LOG = 60
# CHANGED = logging.WARNING + 1
# PROGRESS = logging.WARNING + 2
#     def next(o):
# def default_watcher(delay=5):
#     def watcher(task, process):
# def import_module(name):
# def makedirs(dirname, mod=None, own=None):
# def chmod(dst, mod, recursive=False):
# def chown(dst, own, recursive=False):
# def best_executable():
# def isexecutable(path):
#     def __init__(self, value, alphabet=None, length=16):
#     def iterator(self):
#     def next(self):
# def proto_dumps(data, content_type=u'plain'):
# def proto_dumps_std(data, std, content_type='plain'):
# def proto_dumps_std_threadsafe(data, std):
# def proto_loads_std(std):
# class secret(object):


from collections import defaultdict
from functools import partial
from libcloud.common.google import ResourceNotFoundError
from libcloud.compute.providers import get_driver
from libcloud.compute.types import Provider
from novaclient.client import Client as NovaClient
from novaclient.exceptions import NotFound
from nuka.task import get_task_from_stack
from nuka.hosts import base
from nuka import utils
        from compose.project import Project
        from compose import config
import ipaddress
import threading
import asyncio
import codecs
import time
import os
import nuka

class GCEHost(Host):
    """Host on GCE"""

    use_sudo = True
    provider = Provider.GCE

    def get_create_node_args(self, driver=None, task=None):
        node_args = super().get_create_node_args(driver=driver, task=task)

        # update ex_metadata ssh keys
        keys_list = nuka.config.get('ssh', {}).get('keys') or []
        keysfile = nuka.config.get('ssh', {}).get('keysfile')
        if keysfile:
            with codecs.open(os.path.expanduser(keysfile), 'r', 'utf8') as fd:
                for line in fd:
                    keys_list.append(line.strip())
        if keys_list:
            node_args.setdefault('ex_metadata', {})
            items = node_args['ex_metadata'].setdefault('items', [])
            if not [v for v in items if v["key"] == "sshKeys"]:
                keys = []
                for line in keys_list:
                    if ':' in line:
                        keys.append(line)
                    else:
                        keys.append(self.vars['user'] + ':' + line)
                keys = '\n'.join(keys)
                items.append({"value": keys, "key": "sshKeys"})


# Path: nuka/task.py
# def get_task_from_stack():
#     for info in inspect.stack(3):
#         f = info.frame
#         self = f.f_locals.get('self')
#         if isinstance(f.f_locals.get('self'), Base):
#             return self
# 
# Path: nuka/hosts/base.py
# RLIMIT_NOFILE = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
# MAX_PROCESSES = int(RLIMIT_NOFILE / 4)
# class HostGroup(OrderedDict):
# class TimeIt(object):
# class BaseHost(object):
# class Host(BaseHost):
# class LocalHost(BaseHost):
# class Chroot(BaseHost):
#     async def boot(self):
#     async def destroy(self):  # pragma: no cover
#     def __repr__(self):
#     def __init__(self, host, task=None, **kwargs):
#     def __enter__(self, *args, **kwargs):
#     def __exit__(self, *args, **kwargs):
#     def __init__(self, hostname=None, port='22', **vars):
#     def log(self):
#     def add_task(self, task):
#     def running_tasks(self):
#     def timeit(self, task=None, **kwargs):
#     def add_time(self, start=None, task=None, **kwargs):
#     def cancel(self):
#     def cancelled(self):
#     def fail(self, exc):
#     def failed(self):
#     def _get_best_addresses(self, public=True):
#     def public_ip(self):
#     def private_ip(self):
#     def __getattr__(self, attr):
#     def __str__(self):
#     def __repr__(self):
#     def bootstrap_command(self):
#     async def boot(self):  # pragma: no cover
#     async def get_inventory(self):  # pragma: no cover
#     async def destroy(self):  # pragma: no cover
#     async def acquire_session_slot(self):
#     def free_session_slot(self):
#     async def create_process(self, cmd, task=None, **kwargs):
#     async def run_command(self, cmd=None, stdin=None, task=None, **kwargs):
#     async def send_messages(self, message):  # pragma: no cover
#     def from_stdin(cls):
#     def __init__(self, *args, **kwargs):
#     def wraps_command_line(self, cmd, **kwargs):
#     def __init__(self):
#     def wraps_command_line(self, cmd, **kwargs):
#     def __init__(self, path):
#     def wraps_command_line(self, cmd, **kwargs):
# 
# Path: nuka/utils.py
# PY3 = sys.version_info[0] == 3
# ARCHIVE_EXTS = ('.gz', '.tar', '.zip')
# LOG = 60
# CHANGED = logging.WARNING + 1
# PROGRESS = logging.WARNING + 2
#     def next(o):
# def default_watcher(delay=5):
#     def watcher(task, process):
# def import_module(name):
# def makedirs(dirname, mod=None, own=None):
# def chmod(dst, mod, recursive=False):
# def chown(dst, own, recursive=False):
# def best_executable():
# def isexecutable(path):
#     def __init__(self, value, alphabet=None, length=16):
#     def iterator(self):
#     def next(self):
# def proto_dumps(data, content_type=u'plain'):
# def proto_dumps_std(data, std, content_type='plain'):
# def proto_dumps_std_threadsafe(data, std):
# def proto_loads_std(std):
# class secret(object):


# Path: nuka/hosts/cloud.py
from collections import defaultdict
from functools import partial
from libcloud.common.google import ResourceNotFoundError
from libcloud.compute.providers import get_driver
from libcloud.compute.types import Provider
from novaclient.client import Client as NovaClient
from novaclient.exceptions import NotFound
from nuka.task import get_task_from_stack
from nuka.hosts import base
from nuka import utils
        from compose.project import Project
        from compose import config
import ipaddress
import threading
import asyncio
import codecs
import time
import os
import nuka


class GCEHost(Host):
    """Host on GCE"""

    use_sudo = True
    provider = Provider.GCE

    def get_create_node_args(self, driver=None, task=None):
        node_args = super().get_create_node_args(driver=driver, task=task)

        # update ex_metadata ssh keys
        keys_list = nuka.config.get('ssh', {}).get('keys') or []
        keysfile = nuka.config.get('ssh', {}).get('keysfile')
        if keysfile:
            with codecs.open(os.path.expanduser(keysfile), 'r', 'utf8') as fd:
                for line in fd:
                    keys_list.append(line.strip())
        if keys_list:
            node_args.setdefault('ex_metadata', {})
            items = node_args['ex_metadata'].setdefault('items', [])
            if not [v for v in items if v["key"] == "sshKeys"]:
                keys = []
                for line in keys_list:
                    if ':' in line:
                        keys.append(line)
                    else:
                        keys.append(self.vars['user'] + ':' + line)
                keys = '\n'.join(keys)
                items.append({"value": keys, "key": "sshKeys"})


        self.log.debug4(nuka.utils.json.dumps(node_args, indent=2))