-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslurmdb_validation.test.py
More file actions
361 lines (293 loc) · 11.8 KB
/
slurmdb_validation.test.py
File metadata and controls
361 lines (293 loc) · 11.8 KB
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
import unittest
import json
import os
import tempfile
import pymysql
from slurmdb import SlurmDB, _find_slurm_conf
from slurm_schema import extract_schema, extract_schema_from_dump
class SlurmDBValidationTests(unittest.TestCase):
def test_invalid_cluster_rejected(self):
with self.assertRaises(ValueError):
SlurmDB(cluster="bad;DROP TABLE")
def test_invalid_port_rejected(self):
with self.assertRaises(ValueError):
SlurmDB(port=70000)
def test_valid_config_allowed(self):
db = SlurmDB(host="localhost", port=3306, user="slurm", password="", database="slurm_acct_db", cluster="cluster1")
self.assertEqual(db.cluster, "cluster1")
def test_slurm_conf_from_service_file(self):
with tempfile.TemporaryDirectory() as tmp:
svc = os.path.join(tmp, "slurmctld.service")
slurm_conf = os.path.join(tmp, "slurm.conf")
with open(svc, "w") as fh:
fh.write(f"ConditionPathExists={slurm_conf}\n")
with open(slurm_conf, "w") as fh:
fh.write("ClusterName=test\n")
slurmdbd = os.path.join(tmp, "slurmdbd.conf")
with open(slurmdbd, "w") as fh:
fh.write("StorageHost=localhost\n")
path = _find_slurm_conf([svc])
self.assertEqual(path, slurm_conf)
db = SlurmDB(slurm_conf=path)
self.assertEqual(db._config_file, slurmdbd)
def test_invalid_time_format(self):
db = SlurmDB()
with self.assertRaises(ValueError):
db._validate_time("not-a-date", "start_time")
def test_validate_time_parses_date_strings(self):
db = SlurmDB()
ts = db._validate_time("1970-01-02", "start_time")
# 1970-01-02 is 86400 seconds from the epoch
self.assertEqual(ts, 86400)
def test_parse_mem_converts_units(self):
db = SlurmDB()
self.assertEqual(db._parse_mem("1G"), 1.0)
self.assertEqual(db._parse_mem("1024M"), 1.0)
self.assertEqual(db._parse_mem("1T"), 1024.0)
self.assertAlmostEqual(db._parse_mem("1048576K"), 1.0)
def test_aggregate_usage_handles_int_timestamps(self):
db = SlurmDB()
db.fetch_usage_records = lambda start, end: [
{
'account': 'acct',
'user_name': 'user',
'time_start': 0,
'time_end': 3600,
'tres_alloc': 'cpu=2,node=1',
'mem_req': '1024M',
}
]
agg, totals = db.aggregate_usage(0, 3600)
self.assertIn('1970-01', agg)
self.assertAlmostEqual(agg['1970-01']['acct']['core_hours'], 2.0)
self.assertAlmostEqual(totals['daily']['1970-01-01'], 2.0)
def test_cpus_alloc_fallback(self):
db = SlurmDB()
db.fetch_usage_records = lambda start, end: [
{
'account': 'acct',
'user_name': 'user',
'time_start': 0,
'time_end': 3600,
'tres_alloc': '',
'cpus_alloc': 2,
}
]
agg, totals = db.aggregate_usage(0, 3600)
self.assertAlmostEqual(agg['1970-01']['acct']['core_hours'], 2.0)
def test_aggregate_usage_includes_job_details(self):
db = SlurmDB()
db.fetch_usage_records = lambda start, end: [
{
'jobid': 123,
'job_name': 'jobname',
'account': 'acct',
'user_name': 'user',
'partition': 'p1',
'time_start': 0,
'time_end': 3600,
'tres_req': 'cpu=1,mem=1G',
'tres_alloc': 'cpu=1,mem=1G,gres/gpu:tesla=1',
'cpus_alloc': 1,
'state': 'COMPLETED',
}
]
agg, _ = db.aggregate_usage(0, 3600)
job = agg['1970-01']['acct']['users']['user']['jobs']['123']
self.assertEqual(job['job_name'], 'jobname')
self.assertEqual(job['partition'], 'p1')
self.assertEqual(job['start'], '1970-01-01T00:00:00')
self.assertEqual(job['end'], '1970-01-01T01:00:00')
self.assertEqual(job['elapsed'], 3600)
self.assertEqual(job['req_tres'], 'cpu=1,mem=1G')
self.assertEqual(job['alloc_tres'], 'cpu=1,mem=1G,gres/gpu:tesla=1')
self.assertEqual(job['state'], 'COMPLETED')
def test_close_closes_connection(self):
class FakeConn:
def __init__(self):
self.closed = False
def close(self):
self.closed = True
db = SlurmDB()
fake = FakeConn()
db._conn = fake
db.close()
self.assertTrue(fake.closed)
self.assertIsNone(db._conn)
def test_context_manager_closes_connection(self):
class FakeConn:
def __init__(self):
self.closed = False
def close(self):
self.closed = True
db = SlurmDB()
def fake_connect():
db._conn = FakeConn()
db.connect = fake_connect
with db as ctx:
self.assertIs(ctx, db)
self.assertIsNotNone(db._conn)
conn = db._conn
self.assertTrue(conn.closed)
self.assertIsNone(db._conn)
def test_get_tres_map_handles_missing_table(self):
db = SlurmDB()
db.connect = lambda: None
class FakeCursor:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
pass
def execute(self, query):
raise pymysql.err.ProgrammingError(1146, "Table 'slurm_acct_db.tres' doesn't exist")
def fetchall(self):
return []
class FakeConn:
def cursor(self):
return FakeCursor()
db._conn = FakeConn()
tmap = db._get_tres_map()
self.assertEqual(tmap, {})
def test_get_tres_map_uses_tres_table_when_missing_tres(self):
db = SlurmDB()
db.connect = lambda: None
class FakeCursor:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
pass
def execute(self, query):
self.query = query
if "tres_table" not in query:
raise pymysql.err.ProgrammingError(1146, "Table 'slurm_acct_db.tres' doesn't exist")
def fetchall(self):
if "tres_table" in self.query:
return [{"id": 1, "type": "cpu", "name": ""}]
return []
class FakeConn:
def cursor(self):
return FakeCursor()
db._conn = FakeConn()
tmap = db._get_tres_map()
self.assertEqual(tmap, {1: "cpu"})
def test_extract_schema_with_context_manager_closes_connection(self):
class FakeCursor:
def __init__(self, dbname):
self.dbname = dbname
def execute(self, query):
if query == "SHOW TABLES":
key = f"Tables_in_{self.dbname}"
self._fetchall = [{key: "example"}]
elif query.startswith("SHOW COLUMNS"):
self._fetchall = [{"Field": "col"}]
def fetchall(self):
return getattr(self, "_fetchall", [])
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
pass
class FakeConn:
def __init__(self, dbname):
self.closed = False
self.cursor_obj = FakeCursor(dbname)
def cursor(self):
return self.cursor_obj
def close(self):
self.closed = True
db = SlurmDB(database="mydb")
def fake_connect():
db._conn = FakeConn(db.database)
db.connect = fake_connect
with db as ctx:
extract_schema(ctx)
conn = ctx._conn
self.assertTrue(conn.closed)
self.assertIsNone(db._conn)
def test_fetch_usage_records_uses_cpus_req_if_alloc_missing(self):
with open('test/example_slurm_schema_for_testing.json') as fh:
schema = json.load(fh)
schema_sql = extract_schema_from_dump('test/example_slurmdb_for_testing.sql')
job_cols = schema.get('localcluster_job_table', [])
job_cols_sql = schema_sql.get('localcluster_job_table', [])
# ensure schema JSON and SQL dump agree on CPU columns
self.assertIn('cpus_req', job_cols)
self.assertIn('cpus_req', job_cols_sql)
self.assertNotIn('cpus_alloc', job_cols)
self.assertNotIn('cpus_alloc', job_cols_sql)
class FakeCursor:
def __init__(self):
self.queries = []
def execute(self, query, params=None):
self.queries.append(query)
if query.lower().startswith("show columns"):
column = params[0] if params else None
if column in job_cols:
self._fetchone = {'Field': column}
else:
self._fetchone = None
else:
self._fetchall = []
def fetchone(self):
return getattr(self, "_fetchone", None)
def fetchall(self):
return getattr(self, "_fetchall", [])
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
pass
class FakeConn:
def __init__(self):
self.cursor_obj = FakeCursor()
def cursor(self):
return self.cursor_obj
db = SlurmDB(cluster="localcluster")
db._conn = FakeConn()
db.connect = lambda: None
db.fetch_usage_records(0, 0)
queries = db._conn.cursor_obj.queries
self.assertIn("j.cpus_req AS cpus_alloc", queries[-1])
def test_fetch_usage_records_uses_job_name_column(self):
with open('test/example_slurm_schema_for_testing.json') as fh:
schema = json.load(fh)
schema_sql = extract_schema_from_dump('test/example_slurmdb_for_testing.sql')
job_cols = schema.get('localcluster_job_table', [])
job_cols_sql = schema_sql.get('localcluster_job_table', [])
# ensure schema JSON and SQL dump agree on job name column
self.assertIn('job_name', job_cols)
self.assertIn('job_name', job_cols_sql)
self.assertNotIn('name', job_cols)
self.assertNotIn('name', job_cols_sql)
class FakeCursor:
def __init__(self):
self.queries = []
def execute(self, query, params=None):
self.queries.append(query)
if query.lower().startswith("show columns"):
column = params[0] if params else None
if column in job_cols:
self._fetchone = {'Field': column}
else:
self._fetchone = None
else:
self._fetchall = []
def fetchone(self):
return getattr(self, "_fetchone", None)
def fetchall(self):
return getattr(self, "_fetchall", [])
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
pass
class FakeConn:
def __init__(self):
self.cursor_obj = FakeCursor()
def cursor(self):
return self.cursor_obj
db = SlurmDB(cluster="localcluster")
db._conn = FakeConn()
db.connect = lambda: None
db.fetch_usage_records(0, 0)
queries = db._conn.cursor_obj.queries
self.assertIn("j.job_name AS job_name", queries[-1])
if __name__ == '__main__':
unittest.main()