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 6.0 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
  1. import sys
  2. import os
  3. from pathlib import Path
  4. import subprocess as sp
  5. from invoke import task
  6. import psycopg2
  7. import logging
  8. _log = logging.getLogger(__name__)
  9. data_dir = Path('data')
  10. tgt_dir = Path('target')
  11. bin_dir = tgt_dir / 'release'
  12. numspaces = dict(work=100000000, edition=200000000, rec=300000000,
  13. gr_work=400000000, gr_book=500000000,
  14. isbn=900000000)
  15. def db_url():
  16. if 'DB_URL' in os.environ:
  17. return os.environ['DB_URL']
  18. host = os.environ.get('PGHOST', 'localhost')
  19. port = os.environ.get('PGPORT', None)
  20. db = os.environ['PGDATABASE']
  21. user = os.environ.get('PGUSER', None)
  22. pw = os.environ.get('PGPASSWORD', None)
  23. url = 'postgresql://'
  24. if user:
  25. url += user
  26. if pw:
  27. url += ':' + pw
  28. url += '@'
  29. url += host
  30. if port:
  31. url += ':' + port
  32. url += '/' + db
  33. return url
  34. def psql(c, script):
  35. c.run(f'psql -v ON_ERROR_STOP=on -f {script}')
  36. @task
  37. def init(c):
  38. "Make sure initial database structure are in place"
  39. try:
  40. is_initialized = not start('init', fail=False)
  41. except psycopg2.Error as e:
  42. _log.warning('PostgreSQL error: %s', e)
  43. _log.info('Will try to initialize database')
  44. is_initialized = False
  45. if not is_initialized:
  46. psql(c, 'common-schema.sql')
  47. finish('init')
  48. @task
  49. def build(c, debug=False):
  50. "Compile the Rust support executables"
  51. global bin_dir
  52. if debug:
  53. _log.info('compiling support executables in debug mode')
  54. c.run('cargo build')
  55. bin_dir = tgt_dir / 'debug'
  56. else:
  57. _log.info('compiling support executables')
  58. c.run('cargo build --release')
  59. @task
  60. def clean(c):
  61. "Clean up intermediate & generated files"
  62. _log.info('cleaning Rust build')
  63. c.run('cargo clean')
  64. _log.info('cleaning cluster CSV')
  65. for f in data_dir.glob('*clusters.csv'):
  66. _log.debug('rm %s', f)
  67. f.unlink()
  68. for f in data_dir.glob('*-edges.csv.gz'):
  69. _log.debug('rm %s', f)
  70. f.unlink()
  71. for f in data_dir.glob('*-isbns.csv.gz'):
  72. _log.debug('rm %s', f)
  73. f.unlink()
  74. @task
  75. def test(c, debug=False):
  76. "Run tests on the import & support code."
  77. global bin_dir
  78. if debug:
  79. _log.info('testing support executables in debug mode')
  80. c.run('cargo test')
  81. else:
  82. _log.info('testing support executables')
  83. c.run('cargo test --release')
  84. def pipeline(steps, outfile=None):
  85. last = sp.DEVNULL
  86. if outfile is not None:
  87. outfd = os.open(outfile, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o666)
  88. else:
  89. outfd = None
  90. procs = []
  91. for step in steps[:-1]:
  92. _log.debug('running %s', step)
  93. proc = sp.Popen(step, stdin=last, stdout=sp.PIPE)
  94. last = proc.stdout
  95. procs.append(proc)
  96. proc = sp.Popen(steps[-1], stdin=last, stdout=outfd)
  97. procs.append(proc)
  98. for p, s in zip(procs, steps):
  99. rc = p.wait()
  100. if rc != 0:
  101. _log.error(f'{s[0]} exited with code {rc}')
  102. raise RuntimeError('subprocess failed')
  103. class database:
  104. def __init__(self, autocommit = False, dbc=None):
  105. self.autocommit = autocommit
  106. self.connection = dbc
  107. self.need_close = False
  108. def __enter__(self):
  109. if self.connection is None:
  110. _log.debug('connecting to database')
  111. self.connection = psycopg2.connect("")
  112. self.need_close = True
  113. if self.autocommit:
  114. self.connection.set_session(autocommit=True)
  115. return self.connection
  116. def __exit__(self, *args):
  117. if self.need_close:
  118. _log.debug('closing DB connection')
  119. self.connection.close()
  120. self.need_close = False
  121. def check_prereq(step, dbc=None):
  122. _log.debug('checking prereq %s', step)
  123. with database(dbc=dbc, autocommit=True) as db:
  124. with db.cursor() as cur:
  125. cur.execute('''
  126. SELECT finished_at FROM import_status
  127. WHERE step = %s AND finished_at IS NOT NULL
  128. ''', [step])
  129. res = cur.fetchone()
  130. if not res:
  131. _log.error('prerequisite step %s not completed', step)
  132. raise RuntimeError('prerequisites not met')
  133. def start(step, force=False, fail=True, dbc=None):
  134. _log.debug('starting step %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
  140. ''', [step])
  141. res = cur.fetchone()
  142. if res:
  143. date, = res
  144. if date:
  145. if force:
  146. _log.warning('step %s already completed at %s, continuing anyway', step, date)
  147. elif fail:
  148. _log.error('step %s already completed at %s', step, date)
  149. raise RuntimeError('step {} already completed'.format(step))
  150. else:
  151. _log.info('step %s already completed at %s', step, date)
  152. return False
  153. else:
  154. _log.warning('step %s already started, did it fail?', step)
  155. cur.execute('''
  156. INSERT INTO import_status (step)
  157. VALUES (%s)
  158. ON CONFLICT (step)
  159. DO UPDATE SET started_at = now(), finished_at = NULL
  160. ''', [step])
  161. return True
  162. def finish(step, dbc=None):
  163. _log.debug('finishing step %s')
  164. with database(dbc=dbc, autocommit=True) as db:
  165. with db.cursor() as cur:
  166. cur.execute('''
  167. UPDATE import_status
  168. SET finished_at = now()
  169. WHERE step = %s
  170. RETURNING finished_at - started_at
  171. ''', [step])
  172. row = cur.fetchone()
  173. if row is None:
  174. raise RuntimeError("couldn't update step!")
  175. elapsed, = row
  176. _log.info('finished step %s in %s', step, elapsed)
Tip!

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

Comments

Loading...