Repository navigation
Expand file tree
/
Copy pathscheduler.py
More file actions
206 lines (150 loc) · 6.96 KB
/
Copy pathscheduler.py
File metadata and controls
206 lines (150 loc) · 6.96 KB
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
'''
Fair queue for runs.
At most `max_runs` projects hold a slot at a time, at most `per_client` of them belong
to one client. A project needs a slot to compile and to run its program, and keeps it
until it is released. Waiting projects are served in turns: the next free slot goes to
the client that was served least recently, so a client with a hundred queued runs cannot
hold up the others.
Projects have a weight, the memory they are expected to need. A project gets a slot only
while the weights of all projects with a slot fit into `capacity()`, so many light or a
few heavy projects run at once. A lighter project may overtake one that does not fit,
until that one has waited for `patience` seconds. A single project always gets a slot.
While projects wait, a project that holds a slot without activity for `idle_limit`
seconds is evicted: a few forgotten interactive programs must not block the server for
the whole run time limit.
A project is any object with the attributes `client_id`, `pending` (a list), `busy`
(True while it must not be evicted), `active` (time of its last activity), `weight`
and `queued` (set here, the time it started to wait).
'''
import threading
import time
# An idle project below this weight is not worth evicting for a lack of memory.
MIN_EVICT = 16
def run_all(works) -> None:
for work in works:
work()
class Scheduler:
def __init__(self, max_runs: int, per_client: int, idle_limit: float, evict,
capacity=lambda: float("inf"), patience: float = 15):
self.max_runs = max_runs
self.per_client = per_client
self.idle_limit = idle_limit
self.evict = evict # called with a project that has to give up its slot
self.capacity = capacity # weight that all projects with a slot may have together
self.patience = patience
self.lock = threading.Lock()
self.running = [] # projects that hold a slot
self.waiting = [] # projects that wait for one, in order of arrival
self.served = {} # client id -> number of the last slot the client got
self.count = 0
def submit(self, project, work) -> bool:
'''
Run `work` in this thread if the project holds a slot or gets one right away.
Otherwise queue it, it then runs in a thread of its own. Returns False if queued.
'''
with self.lock:
holds_slot = project in self.running
if not holds_slot:
project.pending.append(work)
if project not in self.waiting:
project.queued = time.time()
self.waiting.append(project)
if holds_slot:
work()
return True
return self.dispatch(inline=project)
def release(self, project) -> None:
'''Give up the slot or the place in the queue of a project.'''
with self.lock:
if project in self.running:
self.running.remove(project)
if project in self.waiting:
self.waiting.remove(project)
project.pending = []
self.dispatch()
def queue_length(self, project) -> int:
'''
0 if the project can run right away, else the number of waiting projects
including this one.
'''
with self.lock:
if project in self.running:
return 0
free = (not self.waiting and len(self.running) < self.max_runs
and self._load().get(project.client_id, 0) < self.per_client
and self._fits(project))
return 0 if free else len(self.waiting) + (project not in self.waiting)
def forget(self, client_id) -> None:
with self.lock:
self.served.pop(client_id, None)
def dispatch(self, inline=None) -> bool:
'''
Hand free slots to waiting projects. The work of `inline` runs in the calling
thread, all other work in new threads. Returns True if `inline` got a slot.
'''
granted = []
with self.lock:
while True:
project = self._next()
if project is None:
break
self.waiting.remove(project)
self.running.append(project)
self.count += 1
self.served[project.client_id] = self.count
project.active = time.time()
granted.append((project, project.pending))
project.pending = []
victim = self._idle() if self.waiting else None
mine = None
for project, works in granted:
if project is inline:
mine = works
else:
threading.Thread(target=run_all, args=(works,), daemon=True).start()
if victim is not None:
self.evict(victim)
if mine is not None:
run_all(mine)
return mine is not None
def _fits(self, project) -> bool:
'''Enough capacity for the weight of the project? A single project always fits.'''
return not self.running or project.weight <= self.capacity() - sum(p.weight for p in self.running)
def _load(self) -> dict:
load = {}
for project in self.running:
load[project.client_id] = load.get(project.client_id, 0) + 1
return load
def _next(self):
'''The waiting project whose turn it is, or None. Call with the lock held.'''
if len(self.running) >= self.max_runs:
return None
load = self._load()
now = time.time()
# sorted() is stable, so a client's own projects stay in order
for project in sorted((p for p in self.waiting if load.get(p.client_id, 0) < self.per_client),
key=lambda p: self.served.get(p.client_id, 0)):
if self._fits(project):
return project
if now - project.queued > self.patience:
return None # nothing lighter overtakes it any more
return None
def _idle(self):
'''
The longest idle project whose slot a waiting project could use, or None.
Call with the lock held.
'''
load = self._load()
limit = time.time() - self.idle_limit
idle = [p for p in self.running if not p.busy and p.active < limit]
# a client at its own limit makes room itself
capped = {p.client_id for p in self.waiting if load.get(p.client_id, 0) >= self.per_client}
own = [p for p in idle if p.client_id in capped]
if own:
return min(own, key=lambda p: p.active)
if all(p.client_id in capped for p in self.waiting):
return None
# the others wait for a slot, then the longest idle project goes, or for memory
if len(self.running) >= self.max_runs:
return min(idle, key=lambda p: p.active, default=None)
return max((p for p in idle if p.weight >= MIN_EVICT), key=lambda p: p.weight, default=None)