machine_list.py 2.28 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
import threading, os

from utils import log

class MachineWaiterThread(threading.Thread):
    def __init__(self, machine, tasks):
        threading.Thread.__init__(self)
        self.machine = machine
        self.tasks = tasks

    def run(self):
        try:
            for task in self.tasks:
                ret = task.wait()
                if ret != 0:
                    log("ERROR: task '" + task.description + "' failed " +
                        "on machine " + self.machine.name)
                task.postaction()
            self.machine.unbusy()
        except BaseException, e:
            log("ERROR: MachineWaiterThread: " + str(e))
            os._exit(1)

class Machine():
    def __init__(self, machine, cond):
        self.name = machine
        self.free = True
        self.cond = cond
    def busy(self, tasks):
        waiter = MachineWaiterThread(self, tasks)
        waiter.start()
    def unbusy(self):
        self.cond.acquire()
        self.free = True
        self.cond.notify()
        self.cond.release()

class MachineList():
    def __init__(self, list):
        self.list = []
        self.cond = threading.Condition()
        for m in list:
            self.list.append(Machine(m, self.cond))

    def get_free_machine(self):
        try:
            self.cond.acquire()
            while True:
                free_machine = None
                for m in self.list:
                    if m.free == True:
                        free_machine = m
                        break
                if free_machine != None:
                    break
                self.cond.wait()
            free_machine.free = False
            self.cond.release()
        except BaseException, e:
            log("ERROR: machine_list: " + str(e))
            os._exit(1)
        return free_machine

    def wait_all_free(self):
        try:
            self.cond.acquire()
            while True:
                all_free = True
                for m in self.list:
                    if m.free == False:
                        all_free = False
                        break
                if all_free == True:
                    break
                self.cond.wait()
            self.cond.release()
        except BaseException, e:
            log("ERROR: machine_list: " + str(e))
            os._exit(1)