#!/usr/bin/python

import vm
from time import sleep, time

class host(object):
    def __init__(self, machine):
        self.machine = machine
    def setup(self):
        pass
    def teardown(self):
        pass

class cluster(object):
    def __init__(self, count=None, spec=None, machine=vm.sshtestmachine):
        if spec is None:
            spec = count*[host]
        self.machines = {}
        self._all = []
        for proto in spec:
            m = machine()
            p = proto(m)
            t = (m, p)
            self._all.append(t)
            self.machines.setdefault(proto, []).append(t)
    def setup(self):
        while any(not m.ready() for (m, p) in self._all):
            sleep(7)
        for (m, p) in self._all:
            p.setup()
    def teardown(self):
        for (m, p) in self._all:
            p.teardown()
            m.shutdown()
        start = time()
        while True:
            still = [m for (m, p) in self._all if m.alive()]
            if not still:
                break
            sleep(7)
            if time() > (start + 300):
                for m in still:
                    m.shoot()
