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

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

Comments

Loading...