test-dude.py 4.91 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
#!/usr/bin/env python3


import os
import datetime
import threading
import subprocess
from flask import Flask, request
from flask_restful import Resource, Api
from flask_jsonpify import jsonify


app = Flask(__name__, static_folder='.')
api = Api(app)


schedule = []
runners = []


class ScheduledTest:
    def __init__(self, template, path):
        self.template = template
        self.path = path
        self.state = 'SCHEDULED'
        self.added = datetime.datetime.now()
        self.lock = threading.Lock()

    def to_dict(self):
        return {
            'id': str(id(self)),
            'template': self.template,
            'state': self.state,
            'path': self.path,
            'added': self.added,
        }


class Runner(threading.Thread):
    def __init__(self, template, program=None):
        if program is None:
            program = ['python3', './templates/%s/test' % template]

        self.template = template
        self.program = program

        self.process = None
        self.job = None
        self.event = threading.Event()
        threading.Thread.__init__(self)
        self.start()

    def to_dict(self):
        return {
            'id': str(id(self)),
            'template': self.template,
            'program': ' '.join(self.program),
            'job': str(id(self.job)) if self.job is not None else None
        }

    def run(self):
        while 1:
            self.event.clear()
            my_queue = [
                s for s in schedule
                if s.state == 'SCHEDULED'
                and s.template == self.template
            ]
            my_queue.sort(key=lambda s: s.added)
            if len(my_queue) == 0:
                # No tasks for this thread, go to sleep
                self.event.wait(timeout=5)
                continue

            job = my_queue[0]

            with job.lock:
                # Check if we were the first thread to choose this job
                if job.state == 'SCHEDULED':
                    job.state = 'RUNNING'
                    self.job = job
                else:
                    # Some other thread is running this test
                    continue

            cmd = []
            cmd += self.program
            cmd += [self.job.path]
            print("Executing ``%s´´" % ' '.join(cmd))
            out_fd = open(os.path.join(self.job.path, 'test.stdout.log'), 'w')
            err_fd = open(os.path.join(self.job.path, 'test.stderr.log'), 'w')
            self.process = subprocess.Popen(
                cmd,
                stdout=out_fd,
                stderr=err_fd
            )
            self.process.wait()
            if self.process.returncode == 0:
                self.job.state = 'SUCCESSFUL'
            else:
                self.job.state = 'FAILED'
            self.process = None
            self.job = None


class Status(Resource):
    def get(self):
        print(request.data)
        return jsonify({
            'schedule': [t.to_dict() for t in schedule],
            'runners': [r.to_dict() for r in runners]
        })


class RestartJob(Resource):
    def get(self, job_id):
        job = [job for job in schedule if str(id(job)) == job_id]
        job = job[0] if len(job) > 0 else None
        if job is None:
            return 'Job not found', 404

        with job.lock:
            if job.state != 'RUNNING':
                job.state = 'SCHEDULED'
                return jsonify({'success': True})
            else:
                return 'Job is already running', 400


class ScheduleJob(Resource):
    def post(self):
        if not request.is_json:
            return 'Please send me JSON', 400
        data = request.get_json()
        print(data)
        if 'path' not in data:
            return 'path expected', 400
        if 'template' not in data:
            return 'template expected', 400

        schedule.append(ScheduledTest(data['template'], data['path']))

        result = {'success': True}
        return jsonify(result)


api.add_resource(Status, '/status')
api.add_resource(ScheduleJob, '/schedule_test')
api.add_resource(RestartJob, '/restart_test/<string:job_id>')


@app.route('/')
def root():
    return app.send_static_file('index.html')


@app.route('/view_log/<string:job_id>/<int:log_id>')
def view_log(job_id, log_id):
    job = [job for job in schedule if str(id(job)) == job_id]
    job = job[0] if len(job) > 0 else None
    if job is None:
        return 'Job not found', 404

    log_name = [
        'make.stdout.log', 'make.stderr.log',
        'test.stdout.log', 'test.stderr.log',
    ][log_id]
    log_path = os.path.join(job.path, log_name)
    if not os.path.isfile(log_path):
        return 'Log not found', 404
    with open(log_path, 'r') as f:
        return f.read()


if __name__ == '__main__':
    runners.append(Runner('maixduino'))
    runners.append(Runner('f7'))
    runners.append(Runner('uno'))
    runners.append(Runner('esp32'))
    runners.append(Runner('bluepill'))
    app.run(port='5002')