forked from fake-name/ReadableWebProxy
/
runScrape.py
227 lines (172 loc) · 5.32 KB
/
runScrape.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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!flask/bin/python
from WebMirror.Runner import PROCESSES
from settings import MAX_DB_SESSIONS
MAX_DB_SESSIONS = PROCESSES + 5
if __name__ == "__main__":
import logSetup
logSetup.initLogging()
# This HAS to be included before the app, to prevent circular dependencies.
import WebMirror.runtime_engines
import WebMirror.Runner
import WebMirror.rules
import traceback
import datetime
import config
import WebMirror.database as db
import WebMirror.LogBase as LogBase
import sqlalchemy.exc
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.executors.pool import ProcessPoolExecutor
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
import activePlugins
executors = {
'main_jobstore': ProcessPoolExecutor(10),
}
job_defaults = {
'coalesce': True,
'max_instances': 3,
}
SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{passwd}@{host}:5432/{database}'.format(user=config.C_DATABASE_USER, passwd=config.C_DATABASE_PASS, host=config.C_DATABASE_IP, database=config.C_DATABASE_DB_NAME)
jobstores = {
'main_jobstore' : SQLAlchemyJobStore(url=SQLALCHEMY_DATABASE_URI)
}
CALLABLE_LUT = {}
for item, dummy_interval in activePlugins.scrapePlugins.values():
CALLABLE_LUT[item.__name__] = item
class JobNameException(Exception):
pass
class JobCaller(LogBase.LoggerMixin):
loggerPath = "Main.PluginRunner"
def __init__(self, job_name):
if not job_name in CALLABLE_LUT:
raise JobNameException("Callable '%s' is not in the class lookup table: '%s'!" % (job_name, CALLABLE_LUT))
self.runModule = CALLABLE_LUT[job_name]
self.job_name = job_name
session = db.get_session()
try:
query = session.query(db.PluginStatus).filter(db.PluginStatus.plugin_name==job_name)
have = query.scalar()
if not have:
new = db.PluginStatus(plugin_name=job_name)
session.add(new)
session.commit()
except sqlalchemy.exc.OperationalError:
session.rollback()
except sqlalchemy.exc.InvalidRequestError:
session.rollback()
finally:
db.delete_session()
def doCall(self):
session = db.get_session()
item = session.query(db.PluginStatus).filter(db.PluginStatus.plugin_name==self.job_name).one()
if item.is_running:
session.commit()
self.log.error("Plugin %s is already running! Not doing re-entrant call!", self.job_name)
return
item.is_running = True
item.last_run = datetime.datetime.now()
session.commit()
try:
self._doCall()
except Exception:
item.last_error = datetime.datetime.now()
item.last_error_msg = traceback.format_exc()
raise
finally:
item.is_running = False
item.last_run_end = datetime.datetime.now()
session.commit()
db.delete_session()
# Should probably be a lambda? Laaaazy.
def _doCall(self):
instance = self.runModule()
instance._go()
@classmethod
def callMod(cls, passMod):
mod = cls(passMod)
mod.doCall()
def do_call(job_name):
caller = JobCaller(job_name)
while 1:
try:
caller.doCall()
break
except JobNameException:
print("Error! Invalid job name: '%s'!" % job_name)
break
except AttributeError:
traceback.print_exc()
print("Call error!")
def scheduleJobs(sched, timeToStart):
jobs = []
offset = 0
for key, value in activePlugins.scrapePlugins.items():
baseModule, interval = value
jobs.append((key, baseModule, interval, timeToStart+datetime.timedelta(seconds=60*offset)))
offset += 1
activeJobs = []
print("JobCaller: ", JobCaller)
print("JobCaller.callMod: ", JobCaller.callMod)
for jobId, callee, interval, startWhen in jobs:
jId = callee.__name__
print("JobID = ", jId)
activeJobs.append(jId)
if not sched.get_job(jId):
sched.add_job(do_call,
args = (callee.__name__, ),
trigger = 'interval',
seconds = interval,
start_date = startWhen,
id = jId,
max_instances = 1,
replace_existing = True,
jobstore = "main_jobstore",
misfire_grace_time = 2**30)
for job in sched.get_jobs('main_jobstore'):
if not job.id in activeJobs:
sched.remove_job(job.id, 'main_jobstore')
print("JobSetup call resetting run-states!")
session = db.get_session()
session.query(db.PluginStatus).update({db.PluginStatus.is_running : False})
session.commit()
db.delete_session()
print("Run-states reset.")
def go_sched():
sched = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
startTime = datetime.datetime.now()+datetime.timedelta(seconds=10)
scheduleJobs(sched, startTime)
sched.start()
def go_test():
import WebMirror.Engine
engine = WebMirror.Engine.SiteArchiver(None)
print(engine)
for x in range(100):
engine.getTask()
def go():
rules = WebMirror.rules.load_rules()
WebMirror.Runner.initializeStartUrls(rules)
WebMirror.Runner.resetInProgress()
runner = WebMirror.Runner.Crawler()
runner.run()
# print("Thread halted. App exiting.")
def profile():
import cProfile
import pstats
cProfile.run('go()', "run.stats")
p = pstats.Stats("run.stats")
p.sort_stats('cumulative')
p.print_stats(250)
if __name__ == "__main__":
import sys
print("Auxilliary modes: 'test', 'scheduler'.")
if "scheduler" in sys.argv:
MAX_DB_SESSIONS = 4
go_sched()
if "test" in sys.argv:
go_test()
else:
started = False
if not started:
started = True
go()