-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsite.py
288 lines (249 loc) · 9.75 KB
/
website.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import socket
from datetime import datetime, timedelta
from urllib.parse import urlparse
from scrapy.utils.misc import load_object
from twisted.application.service import IServiceCollection
from twisted.web import resource, static
from scrapyd.interfaces import IEggStorage, IPoller, ISpiderScheduler
from scrapyd.jobstorage import job_items_url, job_log_url
from jh_scrapyd import is_debug, is_unified_queue, get_config_by_jh
class PrefixHeaderMixin:
def get_base_path(self, txrequest):
return txrequest.getHeader(self.prefix_header) or ''
class Root(resource.Resource):
def __init__(self, config, app):
resource.Resource.__init__(self)
# TODO Reset the tuning mode and assign configuration objects
self.config = config
self.debug = is_debug()
self.runner = config.get('runner')
self.prefix_header = config.get('prefix_header')
logsdir = config.get('logs_dir')
itemsdir = config.get('items_dir')
self.local_items = itemsdir and (urlparse(itemsdir).scheme.lower() in ['', 'file'])
self.app = app
self.nodename = config.get('node_name', socket.gethostname())
self.putChild(b'', Home(self, self.local_items))
if logsdir:
self.putChild(b'logs', static.File(logsdir.encode('ascii', 'ignore'), 'text/plain'))
if self.local_items:
self.putChild(b'items', static.File(itemsdir, 'text/plain'))
self.putChild(b'jobs', Jobs(self, self.local_items))
services = config.items('services', ())
for servName, servClsName in services:
servCls = load_object(servClsName)
self.putChild(servName.encode('utf-8'), servCls(self))
self.update_projects()
def update_projects(self):
self.poller.update_projects()
self.scheduler.update_projects()
@property
def launcher(self):
app = IServiceCollection(self.app, self.app)
return app.getServiceNamed('launcher')
@property
def scheduler(self):
return self.app.getComponent(ISpiderScheduler)
@property
def eggstorage(self):
return self.app.getComponent(IEggStorage)
@property
def poller(self):
# TODO
return self.app.getComponent(IPoller)
class Home(PrefixHeaderMixin, resource.Resource):
def __init__(self, root, local_items):
resource.Resource.__init__(self)
self.root = root
self.local_items = local_items
self.prefix_header = root.prefix_header
def render_GET(self, txrequest):
vars = {
'base_path': self.get_base_path(txrequest),
}
s = """\
<html>
<head><title>Scrapyd</title></head>
<body>
<h1>Scrapyd</h1>
<ul>
<li><a href="%(base_path)s/jobs">Jobs</a></li>
"""
if self.local_items:
s += '<li><a href="%(base_path)s/items/">Items</a></li>\n'
s += """\
<li><a href="%(base_path)s/logs/">Logs</a></li>
<li><a href="https://scrapyd.readthedocs.io/en/latest/">Documentation</a></li>
</ul>
""" % vars
if self.root.scheduler.list_projects():
s += '<p>Available projects:<p>\n<ul>\n'
for project_name in sorted(self.root.scheduler.list_projects()):
s += f'<li>{project_name}</li>\n'
s += '</ul>\n'
else:
s += '<p>No projects available.</p>\n'
s += """
<h2>How to schedule a spider?</h2>
<p>To schedule a spider you need to use the API (this web UI is only for
monitoring)</p>
<p>Example using <a href="https://curl.se/">curl</a>:</p>
<p><code>curl http://localhost:6800/schedule.json -d project=default -d spider=somespider</code></p>
<p>For more information about the API, see the
<a href="https://scrapyd.readthedocs.io/en/latest/">Scrapyd documentation</a></p>
</body>
</html>
"""
txrequest.setHeader('Content-Type', 'text/html; charset=utf-8')
s = (s % vars).encode('utf8')
txrequest.setHeader('Content-Length', str(len(s)))
return s
def microsec_trunc(timelike):
if hasattr(timelike, 'microsecond'):
ms = timelike.microsecond
else:
ms = timelike.microseconds
return timelike - timedelta(microseconds=ms)
class Jobs(PrefixHeaderMixin, resource.Resource):
def __init__(self, root, local_items):
resource.Resource.__init__(self)
self.root = root
self.local_items = local_items
self.prefix_header = root.prefix_header
cancel_button = """
<form method="post" action="{base_path}/cancel.json">
<input type="hidden" name="project" value="{project}"/>
<input type="hidden" name="job" value="{jobid}"/>
<input type="submit" style="float: left;" value="Cancel"/>
</form>
""".format
header_cols = [
'Project', 'Spider',
'Job', 'PID',
'Start', 'Runtime', 'Finish',
'Log', 'Items',
'Cancel',
]
def gen_css(self):
css = [
'#jobs>thead td {text-align: center; font-weight: bold}',
'#jobs>tbody>tr:first-child {background-color: #eee}',
]
if not self.local_items:
col_idx = self.header_cols.index('Items') + 1
css.append('#jobs>*>tr>*:nth-child(%d) {display: none}' % col_idx)
if b'cancel.json' not in self.root.children:
col_idx = self.header_cols.index('Cancel') + 1
css.append('#jobs>*>tr>*:nth-child(%d) {display: none}' % col_idx)
return '\n'.join(css)
def prep_row(self, cells):
if not isinstance(cells, dict):
assert len(cells) == len(self.header_cols)
else:
cells = [cells.get(k) for k in self.header_cols]
cells = ['<td>%s</td>' % ('' if c is None else c) for c in cells]
return '<tr>%s</tr>' % ''.join(cells)
def prep_doc(self):
return (
'<html>'
'<head>'
'<title>Scrapyd</title>'
'<style type="text/css">' + self.gen_css() + '</style>'
'</head>'
'<body><h1>Jobs</h1>'
'<p><a href="./">Go up</a></p>'
+ self.prep_table() +
'</body>'
'</html>'
)
def prep_table(self):
# pending tasks numbers
pending_total_count = self._get_tab_pending_count()
return (
'<table id="jobs" border="1">'
'<thead>' + self.prep_row(self.header_cols) + '</thead>'
'<tbody>'
+ '<tr><th colspan="'+str(len(self.header_cols))+'">Pending('+str(pending_total_count)+')</th></tr>'
+ self.prep_tab_pending() +
'</tbody>'
'<tbody>'
+ '<tr><th colspan="%d">Running</th></tr>' % len(self.header_cols)
+ self.prep_tab_running() +
'</tbody>'
'<tbody>'
+ '<tr><th colspan="%d">Finished</th></tr>' % len(self.header_cols)
+ self.prep_tab_finished() +
'</tbody>'
'</table>'
)
def prep_tab_pending(self):
# TODO Number of pending displays
count = get_config_by_jh('tab_pending_count', -1)
return '\n'.join(
self.prep_row({
"Project": project if not is_unified_queue() else m['_project'],
"Spider": m['name'],
"Job": m['_job'],
"Cancel": self.cancel_button(project=project, jobid=m['_job'], base_path=self.base_path),
})
for project, queue in self._get_tab_pending_queues().items()
for m in queue.list(count)
)
def prep_tab_running(self):
return '\n'.join(
self.prep_row({
"Project": p.project,
"Spider": p.spider,
"Job": p.job,
"PID": p.pid,
"Start": microsec_trunc(p.start_time),
"Runtime": microsec_trunc(datetime.now() - p.start_time),
"Log": f'<a href="{self.base_path}{job_log_url(p)}">Log</a>',
"Items": f'<a href="{self.base_path}{job_items_url(p)}">Items</a>',
"Cancel": self.cancel_button(project=p.project, jobid=p.job, base_path=self.base_path),
})
for p in self.root.launcher.processes.values()
)
def prep_tab_finished(self):
return '\n'.join(
self.prep_row({
"Project": p.project,
"Spider": p.spider,
"Job": p.job,
"Start": microsec_trunc(p.start_time),
"Runtime": microsec_trunc(p.end_time - p.start_time),
"Finish": microsec_trunc(p.end_time),
"Log": f'<a href="{self.base_path}{job_log_url(p)}">Log</a>',
"Items": f'<a href="{self.base_path}{job_items_url(p)}">Items</a>',
})
for p in self.root.launcher.finished
)
def render(self, txrequest):
self.base_path = self.get_base_path(txrequest)
doc = self.prep_doc()
txrequest.setHeader('Content-Type', 'text/html; charset=utf-8')
doc = doc.encode('utf-8')
txrequest.setHeader('Content-Length', str(len(doc)))
return doc
def _get_tab_pending_count(self) -> int:
"""Get the total number of pending tasks"""
total = 0
i = 0
for project, queue in self.root.poller.queues.items():
if is_unified_queue() and i > 0:
# When unifying the queue, only one calculation is needed
break
total += queue.count()
i += 1
return total
def _get_tab_pending_queues(self) -> dict:
"""Get pending tasks"""
ret = {}
i = 0
for project, queue in self.root.poller.queues.items():
if is_unified_queue() and i > 0:
# When unifying the queue, only one calculation is needed
break
ret[project] = queue
i += 1
return ret