Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

support.py 11 KB

You have to be logged in to leave a comment. Sign In
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
  1. import os
  2. import time
  3. from typing import NamedTuple, List
  4. from more_itertools import peekable
  5. import re
  6. from pathlib import Path
  7. import subprocess as sp
  8. from invoke import task
  9. import psycopg2
  10. import psycopg2.errorcodes
  11. import logging
  12. import inspect
  13. import ast
  14. from datetime import timedelta
  15. _log = logging.getLogger(__name__)
  16. data_dir = Path('data')
  17. tgt_dir = Path('target')
  18. bin_dir = tgt_dir / 'release'
  19. bdtool = bin_dir / 'bookdata'
  20. numspaces = dict(work=100000000, edition=200000000, rec=300000000,
  21. gr_work=400000000, gr_book=500000000,
  22. isbn=900000000)
  23. def db_url():
  24. if 'DB_URL' in os.environ:
  25. return os.environ['DB_URL']
  26. host = os.environ.get('PGHOST', 'localhost')
  27. port = os.environ.get('PGPORT', None)
  28. db = os.environ['PGDATABASE']
  29. user = os.environ.get('PGUSER', None)
  30. pw = os.environ.get('PGPASSWORD', None)
  31. url = 'postgresql://'
  32. if user:
  33. url += user
  34. if pw:
  35. url += ':' + pw
  36. url += '@'
  37. url += host
  38. if port:
  39. url += ':' + port
  40. url += '/' + db
  41. return url
  42. def psql(c, script, staged=False):
  43. if staged:
  44. with open(script, encoding='utf8') as f:
  45. parsed = SqlScript(f)
  46. with database() as dbc:
  47. parsed.execute(dbc)
  48. else:
  49. _log.info('running script %s', script)
  50. c.run(f'psql -v ON_ERROR_STOP=on -f {script}')
  51. @task
  52. def init(c):
  53. "Make sure initial database structure are in place"
  54. try:
  55. is_initialized = not start('init', fail=False)
  56. except psycopg2.Error as e:
  57. _log.warning('PostgreSQL error: %s', e)
  58. _log.info('Will try to initialize database')
  59. is_initialized = False
  60. if not is_initialized:
  61. psql(c, 'common-schema.sql')
  62. finish('init')
  63. @task
  64. def build(c, debug=False):
  65. "Compile the Rust support executables"
  66. if debug:
  67. _log.info('compiling support executables in debug mode')
  68. c.run('cargo build')
  69. else:
  70. _log.info('compiling support executables')
  71. c.run('cargo build --release')
  72. @task
  73. def clean(c):
  74. "Clean up intermediate & generated files"
  75. _log.info('cleaning Rust build')
  76. c.run('cargo clean')
  77. _log.info('cleaning cluster CSV')
  78. for f in data_dir.glob('*clusters.csv'):
  79. _log.debug('rm %s', f)
  80. f.unlink()
  81. for f in data_dir.glob('*-edges.csv.gz'):
  82. _log.debug('rm %s', f)
  83. f.unlink()
  84. for f in data_dir.glob('*-isbns.csv.gz'):
  85. _log.debug('rm %s', f)
  86. f.unlink()
  87. @task
  88. def test(c, debug=False):
  89. "Run tests on the import & support code."
  90. if debug:
  91. _log.info('testing support executables in debug mode')
  92. c.run('cargo test')
  93. else:
  94. _log.info('testing support executables')
  95. c.run('cargo test --release')
  96. def pipeline(steps, outfile=None):
  97. last = sp.DEVNULL
  98. if outfile is not None:
  99. outfd = os.open(outfile, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o666)
  100. else:
  101. outfd = None
  102. procs = []
  103. for step in steps[:-1]:
  104. _log.debug('running %s', step)
  105. proc = sp.Popen(step, stdin=last, stdout=sp.PIPE)
  106. last = proc.stdout
  107. procs.append(proc)
  108. proc = sp.Popen(steps[-1], stdin=last, stdout=outfd)
  109. procs.append(proc)
  110. for p, s in zip(procs, steps):
  111. rc = p.wait()
  112. if rc != 0:
  113. _log.error(f'{s[0]} exited with code {rc}')
  114. raise RuntimeError('subprocess failed')
  115. class database:
  116. def __init__(self, autocommit=False, dbc=None):
  117. self.autocommit = autocommit
  118. self.connection = dbc
  119. self.need_close = False
  120. def __enter__(self):
  121. if self.connection is None:
  122. _log.debug('connecting to database')
  123. self.connection = psycopg2.connect("")
  124. self.need_close = True
  125. if self.autocommit:
  126. self.connection.autocommit = True
  127. return self.connection
  128. def __exit__(self, *args):
  129. if self.need_close:
  130. _log.debug('closing DB connection')
  131. self.connection.close()
  132. self.need_close = False
  133. def check_prereq(step, dbc=None):
  134. _log.debug('checking prereq %s', step)
  135. with database(dbc=dbc, autocommit=True) as db:
  136. with db.cursor() as cur:
  137. cur.execute('''
  138. SELECT finished_at FROM import_status
  139. WHERE step = %s AND finished_at IS NOT NULL
  140. ''', [step])
  141. res = cur.fetchone()
  142. if not res:
  143. _log.error('prerequisite step %s not completed', step)
  144. raise RuntimeError('prerequisites not met')
  145. def start(step, force=False, fail=True, dbc=None):
  146. _log.debug('starting step %s', step)
  147. with database(dbc=dbc, autocommit=True) as db:
  148. with db.cursor() as cur:
  149. cur.execute('''
  150. SELECT finished_at FROM import_status
  151. WHERE step = %s
  152. ''', [step])
  153. res = cur.fetchone()
  154. if res:
  155. date, = res
  156. if date:
  157. if force:
  158. _log.warning('step %s already completed at %s, continuing anyway',
  159. step, date)
  160. elif fail:
  161. _log.error('step %s already completed at %s', step, date)
  162. raise RuntimeError('step {} already completed'.format(step))
  163. else:
  164. _log.info('step %s already completed at %s', step, date)
  165. return False
  166. else:
  167. _log.warning('step %s already started, did it fail?', step)
  168. cur.execute('''
  169. INSERT INTO import_status (step)
  170. VALUES (%s)
  171. ON CONFLICT (step)
  172. DO UPDATE SET started_at = now(), finished_at = NULL
  173. ''', [step])
  174. return True
  175. def finish(step, dbc=None):
  176. _log.debug('finishing step %s')
  177. with database(dbc=dbc, autocommit=True) as db:
  178. with db.cursor() as cur:
  179. cur.execute('''
  180. UPDATE import_status
  181. SET finished_at = now()
  182. WHERE step = %s
  183. RETURNING finished_at - started_at
  184. ''', [step])
  185. row = cur.fetchone()
  186. if row is None:
  187. raise RuntimeError("couldn't update step!")
  188. elapsed, = row
  189. _log.info('finished step %s in %s', step, elapsed)
  190. class ScriptChunk(NamedTuple):
  191. label: str
  192. allowed_errors: List[str]
  193. src: str
  194. use_transaction: bool = True
  195. class SqlScript:
  196. """
  197. Class for processing & executing SQL scripts.
  198. """
  199. _sep_re = re.compile(r'^---\s*(?P<inst>.*)')
  200. _icode_re = re.compile(r'#(?P<code>\w+)\s*(?P<args>.*\S)?\s*$')
  201. chunks: List[ScriptChunk]
  202. def __init__(self, file):
  203. if hasattr(file, 'read'):
  204. self._parse(peekable(file))
  205. else:
  206. with open(file, 'r', encoding='utf8') as f:
  207. self._parse(peekable(f))
  208. def _parse(self, lines):
  209. self.chunks = []
  210. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  211. while next_chunk is not None:
  212. if next_chunk:
  213. self.chunks.append(next_chunk)
  214. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  215. @classmethod
  216. def _parse_chunk(cls, lines: peekable, n: int):
  217. qlines = []
  218. chunk = cls._read_header(lines)
  219. qlines = cls._read_query(lines)
  220. # end of file, do we have a chunk?
  221. if qlines:
  222. if chunk.label is None:
  223. chunk = chunk._replace(label=f'Step {n}')
  224. return chunk._replace(src='\n'.join(qlines))
  225. elif qlines is not None:
  226. return False # empty chunk
  227. @classmethod
  228. def _read_header(cls, lines: peekable):
  229. label = None
  230. errs = []
  231. tx = True
  232. line = lines.peek(None)
  233. while line is not None:
  234. hm = cls._sep_re.match(line)
  235. if hm is None:
  236. break
  237. next(lines) # eat line
  238. line = lines.peek(None)
  239. inst = hm.group('inst')
  240. cm = cls._icode_re.match(inst)
  241. if cm is None:
  242. continue
  243. code = cm.group('code')
  244. args = cm.group('args')
  245. if code == 'step':
  246. label = args
  247. elif code == 'allow':
  248. err = getattr(psycopg2.errorcodes, args.upper())
  249. _log.debug('step allows error %s (%s)', args, err)
  250. errs.append(err)
  251. elif code == 'notx':
  252. _log.debug('chunk will run outside a transaction')
  253. tx = False
  254. else:
  255. _log.error('unrecognized query instruction %s', code)
  256. raise ValueError(f'invalid query instruction {code}')
  257. return ScriptChunk(label=label, allowed_errors=errs, src=None,
  258. use_transaction=tx)
  259. @classmethod
  260. def _read_query(cls, lines: peekable):
  261. qls = []
  262. line = lines.peek(None)
  263. while line is not None and not cls._sep_re.match(line):
  264. qls.append(next(lines))
  265. line = lines.peek(None)
  266. # trim lines
  267. while qls and not qls[0].strip():
  268. qls.pop(0)
  269. while qls and not qls[-1].strip():
  270. qls.pop(-1)
  271. if qls or line is not None:
  272. return qls
  273. else:
  274. return None # end of file
  275. def execute(self, dbc):
  276. for step in self.chunks:
  277. start = time.perf_counter()
  278. _log.info('Running ‘%s’', step.label)
  279. _log.debug('Query: %s', step.src)
  280. if step.use_transaction:
  281. with dbc, dbc.cursor() as cur:
  282. self._run_query(step, dbc, cur, True)
  283. else:
  284. with database(autocommit=True) as db2, db2.cursor() as cur:
  285. self._run_query(step, db2, cur, False)
  286. elapsed = time.perf_counter() - start
  287. elapsed = timedelta(seconds=elapsed)
  288. _log.info('Finished ‘%s’ in %s', step.label, elapsed)
  289. def _run_query(self, step, dbc, cur, commit):
  290. try:
  291. cur.execute(step.src)
  292. if commit:
  293. dbc.commit()
  294. except psycopg2.Error as e:
  295. if e.pgcode in step.allowed_errors:
  296. _log.info('Failed with acceptable error %s (%s)',
  297. e.pgcode, psycopg2.errorcodes.lookup(e.pgcode))
  298. else:
  299. _log.error('%s failed: %s', step.label, e)
  300. if e.pgerror:
  301. _log.info('Query diagnostics:\n%s', e.pgerror)
  302. raise e
  303. def _get_tasks(ns):
  304. for t in ns.tasks.values():
  305. yield (t.name, t)
  306. for cn, c in ns.collections.items():
  307. yield from ((f'{cn}.{tn}', t) for (tn, t) in _get_tasks(c))
  308. def _get_task_stage(task):
  309. func = task.body
  310. _re = re.compile(r"\s*s\.finish\('(?P<step>.*)'[\),]")
  311. lines, n = inspect.getsourcelines(func)
  312. for line in lines:
  313. m = _re.match(line)
  314. if m:
  315. return m.group('step')
  316. def get_steps(ns):
  317. steps = {}
  318. for name, task in _get_tasks(ns):
  319. _log.debug('looking for steps in %s', task)
  320. step = _get_task_stage(task)
  321. if step:
  322. _log.debug('found step %s', step)
  323. steps[step] = name
  324. return steps
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...