File size: 2,445 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pinned checkouts and bounded subprocess execution for console generation."""
import datetime
import json
import os
import signal
import subprocess
import time

from .errors import require


def encoded(data):
    return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()


def now():
    return datetime.datetime.now(datetime.timezone.utc).isoformat()


def pin_checkout(checkout, expected_commit):
    result = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=checkout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=15)
    require(result.returncode == 0 and result.stdout.decode().strip() == expected_commit,
            'GENERATOR_COMMIT_MISMATCH', '生成器提交号与固定版本不符')
    result = subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--'], cwd=checkout, timeout=15)
    require(result.returncode == 0, 'GENERATOR_DIRTY', '生成器有未提交的跟踪改动')
    result = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'], cwd=checkout, stdout=subprocess.PIPE, timeout=15)
    require(result.returncode == 0 and not any(p.endswith('.py') for p in result.stdout.decode().splitlines()),
            'GENERATOR_DIRTY', '生成器含未登记的Python源码')
    return {'kind': 'git_checkout', 'commit': expected_commit}


def stop(child):
    if child.poll() is None:
        try:
            os.killpg(child.pid, signal.SIGTERM)
        except ProcessLookupError:
            return
        try:
            child.wait(timeout=5)
        except subprocess.TimeoutExpired:
            os.killpg(child.pid, signal.SIGKILL)
            child.wait(timeout=5)


def execute(owner, command, cwd, env, log, limit):
    begin = time.monotonic()
    with log.open('wb') as stream:
        with owner.lock:
            require(not owner.closed, 'GENERATION_CLOSED', '服务已关闭')
            child = subprocess.Popen(command, cwd=cwd, env=env, stdout=stream,
                                     stderr=subprocess.STDOUT, start_new_session=True)
            owner.child = child
        try:
            code = child.wait(timeout=limit)
        except subprocess.TimeoutExpired:
            stop(child)
            code = 124
        finally:
            with owner.lock:
                owner.child = None
    return dict(argv=command, exit_code=code, wall_limit_s=limit,
                seconds=time.monotonic() - begin, log=str(log))