This repository has been archived by the owner on Jan 12, 2022. It is now read-only.
forked from albertz/RandomFtpGrabber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskSystem.py
171 lines (140 loc) · 4.56 KB
/
TaskSystem.py
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
import sys
from queue import Queue
from threading import Event, Thread, Lock, RLock
import better_exchook
import Persistence
import Logging
kNumWorkers = 5
kMinQueuedActions = kNumWorkers # fill workerQueue always up to N elements, via the watcher thread
kSuggestedMaxQueuedActions = kNumWorkers * 2
# Reloads should work.
if "mainLoopQueue" not in vars():
mainLoopQueue = Queue()
if "exitEvent" not in vars():
exitEvent = Event()
if "workerQueue" not in vars():
workerQueue = None # type: Queue
if "currentWork" not in vars():
currentWorkSet = None # type: set
if "workerQueueSet" not in vars():
workerQueueSet = set()
if "lock" not in vars():
lock = RLock()
def setup():
import Action
global workerQueue
global currentWorkSet
if workerQueue is None:
workerQueue = Persistence.load("workerQueue.db", Queue, env=vars(Action))
if currentWorkSet is None:
currentWorkSet = Persistence.load("currentWork.db", set, env=vars(Action))
_init_watcher_thread()
_init_worker_threads()
def queue_work(func):
"""
:param Action.BaseAction func:
"""
with lock:
if func in workerQueueSet:
Logging.log("queueWork: already in queue: %r" % func)
return # ignore
currentWorkSet.add(func)
# noinspection PyUnresolvedReferences
currentWorkSet.save()
workerQueue.put(func)
# noinspection PyUnresolvedReferences
workerQueue.save()
workerQueueSet.add(func)
def reached_suggested_max_queue():
return len(currentWorkSet) >= kSuggestedMaxQueuedActions
def main_loop():
"""
We assume this runs in the main-thread.
"""
while True:
func = mainLoopQueue.get()
func()
def watcher_loop():
import main
import Action
better_exchook.install()
while not exitEvent.isSet():
if main.DownloadOnly:
if len(currentWorkSet) == 0:
queue_work(Action.CheckDownloadsFinished())
exitEvent.wait(1)
continue
if workerQueue.qsize() >= kMinQueuedActions:
exitEvent.wait(1)
continue
func = Action.get_new_action()
workerQueue.put(func)
if "workers" not in vars():
workers = []
if "watcher" not in vars():
watcher = None
class WorkerThread(Thread):
def __init__(self, idx):
"""
:param int idx:
"""
super(WorkerThread, self).__init__(name="Worker %i/%i" % (idx + 1, kNumWorkers))
self.idx = idx
self.daemon = True
self.cur_item = None
self.lock = Lock()
def run(self):
better_exchook.install()
while True:
with lock:
func = workerQueue.get()
if func in workerQueueSet:
workerQueueSet.remove(func)
Logging.log("Next work item: %s" % func, "remaining: %i" % workerQueue.qsize())
with self.lock:
self.cur_item = func
try:
func()
except SystemExit:
return
except Exception:
Logging.log_exception("Worker", *sys.exc_info())
finally:
# Note: func() can add itself back to the work-queue.
with lock:
if func not in workerQueueSet:
if func in currentWorkSet:
currentWorkSet.remove(func)
# noinspection PyUnresolvedReferences
currentWorkSet.save()
def __str__(self):
with self.lock:
return "%s, %s" % (self.name, self.cur_item)
def _init_worker_threads():
if len(workers) >= kNumWorkers:
return
assert not workers # needs fixing otherwise
# Build up set of actions in the queue.
current_work_real = set()
for func in list(workerQueue.queue):
current_work_real.add(func)
# Add all missing actions.
# Those are actions which have been run when we quit last time.
missing_work = currentWorkSet - current_work_real
for func in missing_work:
workerQueue.put(func)
# Fixup current work set.
currentWorkSet.update(current_work_real)
workerQueueSet.update(currentWorkSet)
# Now init the threads.
for i in range(kNumWorkers - len(workers)):
thread = WorkerThread(idx=i)
workers.append(thread)
thread.start()
def _init_watcher_thread():
global watcher
if watcher:
return
watcher = Thread(target=watcher_loop, name="Watcher")
watcher.daemon = True
watcher.start()