# Path: galah/base/magic.py
# class memoize(object):
#    """
#    Decorator. Caches a function's return value each time it is called.
#    If called later with the same arguments, the cached value is returned
#    (not reevaluated).
# 
#    """
# 
#    def __init__(self, func):
#       self.func = func
#       self.cache = {}
# 
#    def __call__(self, *args):
#       if not isinstance(args, collections.Hashable):
#          # uncacheable. a list, for instance.
#          # better to not cache than blow up.
#          return self.func(*args)
# 
#       if args in self.cache:
#          return self.cache[args]
#       else:
#          value = self.func(*args)
#          self.cache[args] = value
#          return value
# 
#    def __repr__(self):
#       "Return the function's docstring."
# 
#       return self.func.__doc__
# 
#    def __get__(self, obj, objtype):
#       "Support instance methods."
# 
#       return functools.partial(self.__call__, obj)
# 
# Path: galah/base/config.py
# def load_config(domain):
#     """
#     Parses and loads up the Galah configuration file and extracts the
#     configuration data for the given domain (ex: "web" or "sheep").
# 
#     Global configuration options will always be returned, no matter the domain.
# 
#     The configuration file will only be loaded once per instance of the
#     interpreter, so feel free to call this function multiple times in many files
#     to avoid ugly dependency issues.
# 
#     """
# 
#     global loaded
# 
#     # Note whether this is the first time we're processing the configuraiton. If
#     # it is, we'll want to attach the global log handlers.
#     first_load = loaded is None
# 
#     # Load the configuration if it hasn't been loaded yet. Note this ensures
#     # that the configuration is only loaded once per instance of the
#     # interpreter
#     config_file = os.environ.get("GALAH_CONFIG_PATH",
#                                  "/etc/galah/galah.config")
#     if not loaded:
#         if os.path.isfile(config_file):
#             loaded = imp.load_source(
#                 "user_config_file", config_file
#             )
# 
#     local_config = {}
# 
#     # Note we make a **shallow** copy of the defaults here
#     user_config = dict(defaults)
# 
#     # If the configuration didn't load correctly, just use the defaults
#     if loaded:
#         user_config.update(loaded.config)
# 
#     # The prefix values we will look for when scanning the configuration file.
#     prefix = "%s/" % domain
#     global_prefix = "global/"
# 
#     # Grab all the configuration values for the given domain, and any global
#     # configuration values, then place the rest of the configuration values
#     # in there as well.
#     for k, v in user_config.items():
#         if k.startswith(prefix) and len(k) != len(prefix):
#             local_key = k[len(prefix):]
# 
#             local_config[local_key] = v
#         elif k.startswith(global_prefix) and len(k) != len(global_prefix):
#             global_key = k[len(global_prefix):]
# 
#             local_config[global_key] = v
#         elif "/" in k:
#             local_config[k] = v
# 
#     return local_config


import subprocess, ConfigParser, sys, os, datetime
from galah.base.magic import memoize
from galah.base.config import load_config
vzlistPath = "/usr/sbin/vzlist"
containerDirectory = None
nullFile = open("/dev/null", "w")

def check_call(*args, **kwargs):
    "Essentially subprocess.check_call. Added for compatibilty with <v2.5."

    returnValue = subprocess.call(*args, **kwargs)
    if returnValue != 0:
        raise SystemError((return_value, str(zparams[0])))
    else:
        return 0

def run_vzctl(zparams, timeout = config["VZCTL_RETRY_TIMEOUT"]):
    cmd = [vzctlPath] + zparams

    deadline = datetime.datetime.today() + timeout

    while True:
        return_value = subprocess.call(
            cmd, stdout = nullFile, stderr = nullFile
        )

        if return_value == 9 and datetime.datetime.today() < deadline:
            continue
        elif return_value != 0:
            raise SystemError((return_value, str(zparams[0])))
        else:
            return 0


# Path: galah/base/magic.py
# class memoize(object):
#    """
#    Decorator. Caches a function's return value each time it is called.
#    If called later with the same arguments, the cached value is returned
#    (not reevaluated).
# 
#    """
# 
#    def __init__(self, func):
#       self.func = func
#       self.cache = {}
# 
#    def __call__(self, *args):
#       if not isinstance(args, collections.Hashable):
#          # uncacheable. a list, for instance.
#          # better to not cache than blow up.
#          return self.func(*args)
# 
#       if args in self.cache:
#          return self.cache[args]
#       else:
#          value = self.func(*args)
#          self.cache[args] = value
#          return value
# 
#    def __repr__(self):
#       "Return the function's docstring."
# 
#       return self.func.__doc__
# 
#    def __get__(self, obj, objtype):
#       "Support instance methods."
# 
#       return functools.partial(self.__call__, obj)
# 
# Path: galah/base/config.py
# def load_config(domain):
#     """
#     Parses and loads up the Galah configuration file and extracts the
#     configuration data for the given domain (ex: "web" or "sheep").
# 
#     Global configuration options will always be returned, no matter the domain.
# 
#     The configuration file will only be loaded once per instance of the
#     interpreter, so feel free to call this function multiple times in many files
#     to avoid ugly dependency issues.
# 
#     """
# 
#     global loaded
# 
#     # Note whether this is the first time we're processing the configuraiton. If
#     # it is, we'll want to attach the global log handlers.
#     first_load = loaded is None
# 
#     # Load the configuration if it hasn't been loaded yet. Note this ensures
#     # that the configuration is only loaded once per instance of the
#     # interpreter
#     config_file = os.environ.get("GALAH_CONFIG_PATH",
#                                  "/etc/galah/galah.config")
#     if not loaded:
#         if os.path.isfile(config_file):
#             loaded = imp.load_source(
#                 "user_config_file", config_file
#             )
# 
#     local_config = {}
# 
#     # Note we make a **shallow** copy of the defaults here
#     user_config = dict(defaults)
# 
#     # If the configuration didn't load correctly, just use the defaults
#     if loaded:
#         user_config.update(loaded.config)
# 
#     # The prefix values we will look for when scanning the configuration file.
#     prefix = "%s/" % domain
#     global_prefix = "global/"
# 
#     # Grab all the configuration values for the given domain, and any global
#     # configuration values, then place the rest of the configuration values
#     # in there as well.
#     for k, v in user_config.items():
#         if k.startswith(prefix) and len(k) != len(prefix):
#             local_key = k[len(prefix):]
# 
#             local_config[local_key] = v
#         elif k.startswith(global_prefix) and len(k) != len(global_prefix):
#             global_key = k[len(global_prefix):]
# 
#             local_config[global_key] = v
#         elif "/" in k:
#             local_config[k] = v
# 
#     return local_config


# Path: galah/sheep/virtualsuites/vz/pyvz.py
import subprocess, ConfigParser, sys, os, datetime
from galah.base.magic import memoize
from galah.base.config import load_config

vzlistPath = "/usr/sbin/vzlist"
containerDirectory = None
nullFile = open("/dev/null", "w")

def check_call(*args, **kwargs):
    "Essentially subprocess.check_call. Added for compatibilty with <v2.5."

    returnValue = subprocess.call(*args, **kwargs)
    if returnValue != 0:
        raise SystemError((return_value, str(zparams[0])))
    else:
        return 0

def run_vzctl(zparams, timeout = config["VZCTL_RETRY_TIMEOUT"]):
    cmd = [vzctlPath] + zparams

    deadline = datetime.datetime.today() + timeout

    while True:
        return_value = subprocess.call(
            cmd, stdout = nullFile, stderr = nullFile
        )

        if return_value == 9 and datetime.datetime.today() < deadline:
            continue
        elif return_value != 0:
            raise SystemError((return_value, str(zparams[0])))
        else:
            return 0


@memoize