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

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

Comments

Loading...