from os import devnull

from tornado.gen import sleep
from tornado.process import Subprocess


class Run:
    config = {
        'repeat': 60,
        'timeout': 3,
        'command': []
    }

    @staticmethod
    async def check(server, config):
        assert config['command']
        command = [
            c.format(server=server, config=config) for c in config['command']
        ]
        p = Subprocess(
            command,
            stdout=open(devnull, 'w'),
            stderr=open(devnull, 'w')
        )
        future = p.wait_for_exit()
        await sleep(config['timeout'])
        if future.done():
            return {'ok': not future.result()}
        future.cancel()
        return {"ok": False, 'timeout': False}
