streamflow-postgresql 0.0.4__tar.gz → 0.0.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {streamflow-postgresql-0.0.4/streamflow_postgresql.egg-info → streamflow-postgresql-0.0.5}/PKG-INFO +1 -1
  2. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/pyproject.toml +0 -1
  3. streamflow-postgresql-0.0.5/requirements.txt +2 -0
  4. streamflow-postgresql-0.0.5/streamflow_postgresql/database.py +539 -0
  5. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql/schemas/postgresql.json +2 -2
  6. streamflow-postgresql-0.0.5/streamflow_postgresql/version.py +1 -0
  7. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5/streamflow_postgresql.egg-info}/PKG-INFO +1 -1
  8. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/requires.txt +2 -3
  9. streamflow-postgresql-0.0.4/requirements.txt +0 -3
  10. streamflow-postgresql-0.0.4/streamflow_postgresql/database.py +0 -610
  11. streamflow-postgresql-0.0.4/streamflow_postgresql/version.py +0 -1
  12. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/LICENSE +0 -0
  13. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/MANIFEST.in +0 -0
  14. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/README.md +0 -0
  15. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/bandit-requirements.txt +0 -0
  16. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/lint-requirements.txt +0 -0
  17. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/setup.cfg +0 -0
  18. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql/__init__.py +0 -0
  19. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql/plugin.py +0 -0
  20. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql/schemas/postgresql.sql +0 -0
  21. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/SOURCES.txt +0 -0
  22. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/dependency_links.txt +0 -0
  23. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/entry_points.txt +0 -0
  24. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/top_level.txt +0 -0
  25. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/streamflow_postgresql.egg-info/zip-safe +0 -0
  26. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/test-requirements.txt +0 -0
  27. {streamflow-postgresql-0.0.4 → streamflow-postgresql-0.0.5}/tests/test_persistence.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: streamflow-postgresql
3
- Version: 0.0.4
3
+ Version: 0.0.5
4
4
  Summary: StreamFlow PostgreSQL plugin
5
5
  Author-email: Iacopo Colonnelli <iacopo.colonnelli@unito.it>
6
6
  License: LGPL-3.0-or-later
@@ -36,7 +36,6 @@ Repository = "https://github.com/alpha-unito/streamflow-postgresql"
36
36
  [project.entry-points]
37
37
  "unito.streamflow.plugin" = {"unito.postgresql" = "streamflow_postgresql.plugin:PostgreSQLStreamFlowPlugin"}
38
38
 
39
-
40
39
  [tool.setuptools]
41
40
  packages = [
42
41
  "streamflow_postgresql"
@@ -0,0 +1,2 @@
1
+ asyncpg==0.28.0
2
+ streamflow==0.2.0.dev8
@@ -0,0 +1,539 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from typing import Any, MutableMapping, MutableSequence
6
+
7
+ import asyncpg
8
+ import pkg_resources
9
+ from streamflow.core import utils
10
+ from streamflow.core.context import StreamFlowContext
11
+ from streamflow.core.deployment import Target
12
+ from streamflow.core.persistence import DependencyType
13
+ from streamflow.core.utils import get_date_from_ns
14
+ from streamflow.core.workflow import Port, Status, Step, Token
15
+ from streamflow.persistence.base import CachedDatabase
16
+
17
+
18
+ class PostgreSQLConnectionPool:
19
+ def __init__(
20
+ self,
21
+ dbname: str,
22
+ hostname: str,
23
+ username: str,
24
+ password: str,
25
+ timeout: int,
26
+ maxsize: int = 10,
27
+ ):
28
+ self.dbname: str = dbname
29
+ self.hostname: str = hostname
30
+ self.username: str = username
31
+ self.password: str = password
32
+ self.timeout: int = timeout
33
+ self.maxsize: int = maxsize
34
+ self._pool: asyncpg.Pool | None = None
35
+
36
+ async def __aenter__(self):
37
+ if not self._pool:
38
+ self._pool = await asyncpg.create_pool(
39
+ database=self.dbname,
40
+ user=self.username,
41
+ password=self.password,
42
+ host=self.hostname,
43
+ timeout=self.timeout,
44
+ max_size=self.maxsize,
45
+ )
46
+ schema_path = pkg_resources.resource_filename(
47
+ __name__, os.path.join("schemas", "postgresql.sql")
48
+ )
49
+ with open(schema_path) as f:
50
+ async with self._pool.acquire() as conn:
51
+ async with conn.transaction():
52
+ await conn.execute(f.read())
53
+ return self._pool
54
+
55
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
56
+ pass
57
+
58
+ async def close(self):
59
+ if self._pool:
60
+ await self._pool.close()
61
+ self._pool = None
62
+
63
+
64
+ class PostgreSQLDatabase(CachedDatabase):
65
+ def __init__(
66
+ self,
67
+ context: StreamFlowContext,
68
+ dbname: str,
69
+ hostname: str,
70
+ username: str,
71
+ password: str,
72
+ timeout: int = 20,
73
+ maxConnections: int = 10,
74
+ ):
75
+ super().__init__(context)
76
+ self.pool: PostgreSQLConnectionPool = PostgreSQLConnectionPool(
77
+ dbname=dbname,
78
+ hostname=hostname,
79
+ username=username,
80
+ password=password,
81
+ timeout=timeout,
82
+ maxsize=maxConnections,
83
+ )
84
+
85
+ async def close(self):
86
+ await self.pool.close()
87
+
88
+ @classmethod
89
+ def get_schema(cls) -> str:
90
+ return pkg_resources.resource_filename(
91
+ __name__, os.path.join("schemas", "postgresql.json")
92
+ )
93
+
94
+ async def add_command(self, step_id: int, tag: str, cmd: str) -> int:
95
+ async with self.pool as pool:
96
+ async with pool.acquire() as conn:
97
+ async with conn.transaction():
98
+ return await conn.fetchval(
99
+ "INSERT INTO command(step, tag, cmd) "
100
+ "VALUES($1, $2, $3) "
101
+ "RETURNING id",
102
+ step_id,
103
+ tag,
104
+ cmd.encode("utf-8"),
105
+ )
106
+
107
+ async def add_dependency(
108
+ self, step: int, port: int, type: DependencyType, name: str
109
+ ) -> None:
110
+ async with self.pool as pool:
111
+ async with pool.acquire() as conn:
112
+ async with conn.transaction():
113
+ await conn.execute(
114
+ "INSERT INTO dependency(step, port, type, name) "
115
+ "VALUES($1, $2, $3, $4) "
116
+ "ON CONFLICT DO NOTHING",
117
+ step,
118
+ port,
119
+ type.value,
120
+ name,
121
+ )
122
+
123
+ async def add_deployment(
124
+ self,
125
+ name: str,
126
+ type: str,
127
+ config: str,
128
+ external: bool,
129
+ lazy: bool,
130
+ workdir: str | None,
131
+ ) -> int:
132
+ async with self.pool as pool:
133
+ async with pool.acquire() as conn:
134
+ async with conn.transaction():
135
+ return await conn.fetchval(
136
+ "INSERT INTO deployment(name, type, config, external, lazy, workdir) "
137
+ "VALUES ($1, $2, $3, $4, $5, $6) "
138
+ "RETURNING id",
139
+ name,
140
+ type,
141
+ config,
142
+ external,
143
+ lazy,
144
+ workdir,
145
+ )
146
+
147
+ async def add_port(
148
+ self, name: str, workflow_id: int, type: type[Port], params: str
149
+ ) -> int:
150
+ async with self.pool as pool:
151
+ async with pool.acquire() as conn:
152
+ async with conn.transaction():
153
+ return await conn.fetchval(
154
+ "INSERT INTO port(name, workflow, type, params) "
155
+ "VALUES($1, $2, $3, $4) "
156
+ "RETURNING id",
157
+ name,
158
+ workflow_id,
159
+ utils.get_class_fullname(type),
160
+ json.dumps(params),
161
+ )
162
+
163
+ async def add_provenance(self, inputs: MutableSequence[int], token: int):
164
+ async with self.pool as pool:
165
+ async with pool.acquire() as conn:
166
+ async with conn.transaction():
167
+ await conn.executemany(
168
+ "INSERT INTO provenance(dependee, depender) "
169
+ "VALUES($1, $2) "
170
+ "ON CONFLICT DO NOTHING",
171
+ [(i, token) for i in inputs],
172
+ )
173
+
174
+ async def add_step(
175
+ self, name: str, workflow_id: int, status: int, type: type[Step], params: str
176
+ ) -> int:
177
+ async with self.pool as pool:
178
+ async with pool.acquire() as conn:
179
+ async with conn.transaction():
180
+ return await conn.fetchval(
181
+ "INSERT INTO step(name, workflow, status, type, params) "
182
+ "VALUES($1, $2, $3, $4, $5) "
183
+ "RETURNING id",
184
+ name,
185
+ workflow_id,
186
+ status,
187
+ utils.get_class_fullname(type),
188
+ json.dumps(params),
189
+ )
190
+
191
+ async def add_target(
192
+ self,
193
+ deployment: int,
194
+ type: type[Target],
195
+ params: str,
196
+ locations: int = 1,
197
+ service: str | None = None,
198
+ workdir: str | None = None,
199
+ ) -> int:
200
+ async with self.pool as pool:
201
+ async with pool.acquire() as conn:
202
+ async with conn.transaction():
203
+ return await conn.fetchval(
204
+ "INSERT INTO target(params, type, deployment, locations, service, workdir) "
205
+ "VALUES ($1, $2, $3, $4, $5, $6) "
206
+ "RETURNING id",
207
+ json.dumps(params),
208
+ utils.get_class_fullname(type),
209
+ deployment,
210
+ locations,
211
+ service,
212
+ workdir,
213
+ )
214
+
215
+ async def add_token(
216
+ self, tag: str, type: type[Token], value: Any, port: int | None = None
217
+ ) -> int:
218
+ async with self.pool as pool:
219
+ async with pool.acquire() as conn:
220
+ async with conn.transaction():
221
+ return await conn.fetchval(
222
+ "INSERT INTO token(port, type, tag, value) "
223
+ "VALUES($1, $2, $3, $4) "
224
+ "RETURNING id",
225
+ port,
226
+ utils.get_class_fullname(type),
227
+ tag,
228
+ bytearray(value, "utf-8"),
229
+ )
230
+
231
+ async def add_workflow(self, name: str, params: str, status: int, type: str) -> int:
232
+ async with self.pool as pool:
233
+ async with pool.acquire() as conn:
234
+ async with conn.transaction():
235
+ return await conn.fetchval(
236
+ "INSERT INTO workflow(name, params, status, type) "
237
+ "VALUES($1, $2, $3, $4) "
238
+ "RETURNING id",
239
+ name,
240
+ json.dumps(params),
241
+ status,
242
+ type,
243
+ )
244
+
245
+ async def get_command(self, command_id: int) -> MutableMapping[str, Any]:
246
+ async with self.pool as pool:
247
+ async with pool.acquire() as conn:
248
+ row = await conn.fetchrow(
249
+ "SELECT * FROM command WHERE id = $1", command_id
250
+ )
251
+ return {
252
+ k: bytearray(v) if isinstance(v, memoryview) else v
253
+ for k, v in row.items()
254
+ }
255
+
256
+ async def get_commands_by_step(
257
+ self, step_id: int
258
+ ) -> MutableSequence[MutableMapping[str, Any]]:
259
+ async with self.pool as pool:
260
+ async with pool.acquire() as conn:
261
+ rows = await conn.fetch(
262
+ "SELECT * FROM command WHERE step = $1", step_id
263
+ )
264
+ return [
265
+ {
266
+ k: bytearray(v) if isinstance(v, memoryview) else v
267
+ for k, v in row.items()
268
+ }
269
+ for row in rows
270
+ ]
271
+
272
+ async def get_dependees(
273
+ self, token_id: int
274
+ ) -> MutableSequence[MutableMapping[str, Any]]:
275
+ async with self.pool as pool:
276
+ async with pool.acquire() as conn:
277
+ return await conn.fetch(
278
+ "SELECT * FROM provenance WHERE depender = $1",
279
+ token_id,
280
+ )
281
+
282
+ async def get_dependers(
283
+ self, token_id: int
284
+ ) -> MutableSequence[MutableMapping[str, Any]]:
285
+ async with self.pool as pool:
286
+ async with pool.acquire() as conn:
287
+ return await conn.fetch(
288
+ "SELECT * FROM provenance WHERE dependee = $1",
289
+ token_id,
290
+ )
291
+
292
+ async def get_deployment(self, deplyoment_id: int) -> MutableMapping[str, Any]:
293
+ async with self.pool as pool:
294
+ async with pool.acquire() as conn:
295
+ return await conn.fetchrow(
296
+ "SELECT * FROM deployment WHERE id = $1",
297
+ deplyoment_id,
298
+ )
299
+
300
+ async def get_input_ports(
301
+ self, step_id: int
302
+ ) -> MutableSequence[MutableMapping[str, Any]]:
303
+ async with self.pool as pool:
304
+ async with pool.acquire() as conn:
305
+ return await conn.fetch(
306
+ "SELECT * FROM dependency WHERE step = $1 AND type = $2",
307
+ step_id,
308
+ DependencyType.INPUT.value,
309
+ )
310
+
311
+ async def get_output_ports(
312
+ self, step_id: int
313
+ ) -> MutableSequence[MutableMapping[str, Any]]:
314
+ async with self.pool as pool:
315
+ async with pool.acquire() as conn:
316
+ return await conn.fetch(
317
+ "SELECT * FROM dependency WHERE step = $1 AND type = $2",
318
+ step_id,
319
+ DependencyType.OUTPUT.value,
320
+ )
321
+
322
+ async def get_port(self, port_id: int) -> MutableMapping[str, Any]:
323
+ async with self.pool as pool:
324
+ async with pool.acquire() as conn:
325
+ return await conn.fetchrow("SELECT * FROM port WHERE id = $1", port_id)
326
+
327
+ async def get_port_tokens(self, port_id: int) -> MutableSequence[int]:
328
+ async with self.pool as pool:
329
+ async with pool.acquire() as conn:
330
+ rows = await conn.fetch("SELECT * FROM port WHERE id = $1", port_id)
331
+ return [row["id"] for row in rows]
332
+
333
+ async def get_reports(
334
+ self, workflow: str, last_only: bool = False
335
+ ) -> MutableSequence[MutableSequence[MutableMapping[str, Any]]]:
336
+ async with self.pool as pool:
337
+ async with pool.acquire() as conn:
338
+ if last_only:
339
+ rows = await conn.fetch(
340
+ "SELECT c.id, s.name, c.start_time, c.end_time "
341
+ "FROM step AS s, command AS c "
342
+ "WHERE s.id = c.step "
343
+ "AND s.workflow = ("
344
+ "SELECT id FROM workflow "
345
+ "WHERE name = $1 "
346
+ "ORDER BY id DESC LIMIT 1)",
347
+ workflow,
348
+ )
349
+ return [[dict(r) for r in rows]]
350
+ else:
351
+ async with conn.transaction():
352
+ cursor = conn.cursor(
353
+ "SELECT s.workflow, c.id, s.name, c.start_time, c.end_time "
354
+ "FROM step AS s, command AS c "
355
+ "WHERE s.id = c.step "
356
+ "AND s.workflow IN (SELECT id FROM workflow WHERE name = $1) "
357
+ "ORDER BY s.workflow DESC",
358
+ workflow,
359
+ )
360
+ result = {}
361
+ async for row in cursor:
362
+ result.setdefault(row["workflow"], []).append(
363
+ {k: row[k] for k in row.keys() if k != "workflow"}
364
+ )
365
+ return list(result.values())
366
+
367
+ async def get_step(self, step_id: int) -> MutableMapping[str, Any]:
368
+ async with self.pool as pool:
369
+ async with pool.acquire() as conn:
370
+ return await conn.fetchrow("SELECT * FROM step WHERE id = $1", step_id)
371
+
372
+ async def get_target(self, target_id: int) -> MutableMapping[str, Any]:
373
+ async with self.pool as pool:
374
+ async with pool.acquire() as conn:
375
+ return await conn.fetchrow(
376
+ "SELECT * FROM target WHERE id = $1", target_id
377
+ )
378
+
379
+ async def get_token(self, token_id: int) -> MutableMapping[str, Any]:
380
+ async with self.pool as pool:
381
+ async with pool.acquire() as conn:
382
+ row = await conn.fetchrow("SELECT * FROM token WHERE id = $1", token_id)
383
+ return {
384
+ k: bytearray(v) if isinstance(v, memoryview) else v
385
+ for k, v in row.items()
386
+ }
387
+
388
+ async def get_workflow(self, workflow_id: int) -> MutableMapping[str, Any]:
389
+ async with self.pool as pool:
390
+ async with pool.acquire() as conn:
391
+ return await conn.fetchrow(
392
+ "SELECT * FROM workflow WHERE id = $1", workflow_id
393
+ )
394
+
395
+ async def get_workflow_ports(
396
+ self, workflow_id: int
397
+ ) -> MutableSequence[MutableMapping[str, Any]]:
398
+ async with self.pool as pool:
399
+ async with pool.acquire() as conn:
400
+ return await conn.fetch(
401
+ "SELECT * FROM port WHERE workflow = $1",
402
+ workflow_id,
403
+ )
404
+
405
+ async def get_workflow_steps(
406
+ self, workflow_id: int
407
+ ) -> MutableSequence[MutableMapping[str, Any]]:
408
+ async with self.pool as pool:
409
+ async with pool.acquire() as conn:
410
+ return await conn.fetch(
411
+ "SELECT * FROM step WHERE workflow = $1",
412
+ workflow_id,
413
+ )
414
+
415
+ async def get_workflows_by_name(
416
+ self, workflow_name: str, last_only: bool = False
417
+ ) -> MutableSequence[MutableMapping[str, Any]]:
418
+ async with self.pool as pool:
419
+ async with pool.acquire() as conn:
420
+ query = "SELECT * FROM workflow WHERE name = $1 ORDER BY id desc"
421
+ return (
422
+ [conn.fetchrow(query, workflow_name)]
423
+ if last_only
424
+ else conn.fetch(query, workflow_name)
425
+ )
426
+
427
+ async def get_workflows_list(
428
+ self, name: str | None
429
+ ) -> MutableSequence[MutableMapping[str, Any]]:
430
+ if name is not None:
431
+ return [
432
+ {
433
+ "end_time": get_date_from_ns(row["end_time"]),
434
+ "start_time": get_date_from_ns(row["start_time"]),
435
+ "status": Status(row["status"]).name,
436
+ "type": row["type"],
437
+ }
438
+ for row in await self.get_workflows_by_name(name, last_only=False)
439
+ ]
440
+ else:
441
+ async with self.pool as pool:
442
+ async with pool.acquire() as conn:
443
+ return await conn.fetch(
444
+ "SELECT name, type, COUNT(*) AS num "
445
+ "FROM workflow GROUP BY name, type "
446
+ "ORDER BY name DESC"
447
+ )
448
+
449
+ async def update_command(
450
+ self, command_id: int, updates: MutableMapping[str, Any]
451
+ ) -> int:
452
+ async with self.pool as pool:
453
+ async with pool.acquire() as conn:
454
+ async with conn.transaction():
455
+ await conn.execute(
456
+ "UPDATE command SET {} WHERE id = $1".format( # nosec
457
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
458
+ ),
459
+ command_id,
460
+ *updates.values(),
461
+ )
462
+ self.port_cache.pop(command_id, None)
463
+ return command_id
464
+
465
+ async def update_deployment(
466
+ self, deployment_id: int, updates: MutableMapping[str, Any]
467
+ ) -> int:
468
+ async with self.pool as pool:
469
+ async with pool.acquire() as conn:
470
+ async with conn.transaction():
471
+ await conn.execute(
472
+ "UPDATE deployment SET {} WHERE id = $1".format( # nosec
473
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
474
+ ),
475
+ deployment_id,
476
+ *updates.values(),
477
+ )
478
+ self.port_cache.pop(deployment_id, None)
479
+ return deployment_id
480
+
481
+ async def update_port(self, port_id: int, updates: MutableMapping[str, Any]) -> int:
482
+ async with self.pool as pool:
483
+ async with pool.acquire() as conn:
484
+ async with conn.transaction():
485
+ await conn.execute(
486
+ "UPDATE port SET {} WHERE id = $1".format( # nosec
487
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
488
+ ),
489
+ port_id,
490
+ *updates.values(),
491
+ )
492
+ self.port_cache.pop(port_id, None)
493
+ return port_id
494
+
495
+ async def update_step(self, step_id: int, updates: MutableMapping[str, Any]) -> int:
496
+ async with self.pool as pool:
497
+ async with pool.acquire() as conn:
498
+ async with conn.transaction():
499
+ await conn.execute(
500
+ "UPDATE step SET {} WHERE id = $1".format( # nosec
501
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
502
+ ),
503
+ step_id,
504
+ *updates.values(),
505
+ )
506
+ self.step_cache.pop(step_id, None)
507
+ return step_id
508
+
509
+ async def update_target(
510
+ self, target_id: int, updates: MutableMapping[str, Any]
511
+ ) -> int:
512
+ async with self.pool as pool:
513
+ async with pool.acquire() as conn:
514
+ async with conn.transaction():
515
+ await conn.execute(
516
+ "UPDATE target SET {} WHERE id = $1".format( # nosec
517
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
518
+ ),
519
+ target_id,
520
+ *updates.values(),
521
+ )
522
+ self.target_cache.pop(target_id, None)
523
+ return target_id
524
+
525
+ async def update_workflow(
526
+ self, workflow_id: int, updates: MutableMapping[str, Any]
527
+ ) -> int:
528
+ async with self.pool as pool:
529
+ async with pool.acquire() as conn:
530
+ async with conn.transaction():
531
+ await conn.execute(
532
+ "UPDATE workflow SET {} WHERE id = $1".format( # nosec
533
+ ", ".join([f"{k} = ${i+2}" for i, k in enumerate(updates)])
534
+ ),
535
+ workflow_id,
536
+ *updates.values(),
537
+ )
538
+ self.workflow_cache.pop(workflow_id, None)
539
+ return workflow_id
@@ -1,6 +1,6 @@
1
1
  {
2
- "$schema": "http://json-schema.org/draft-07/schema#",
3
- "$id": "postgresql.json",
2
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
3
+ "$id": "https://streamflow.di.unito.it/schemas/plugins/postgresql/postgresql.json",
4
4
  "type": "object",
5
5
  "properties": {
6
6
  "dbname": {
@@ -0,0 +1 @@
1
+ VERSION = "0.0.5"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: streamflow-postgresql
3
- Version: 0.0.4
3
+ Version: 0.0.5
4
4
  Summary: StreamFlow PostgreSQL plugin
5
5
  Author-email: Iacopo Colonnelli <iacopo.colonnelli@unito.it>
6
6
  License: LGPL-3.0-or-later
@@ -1,6 +1,5 @@
1
- aiopg==1.4.0
2
- psycopg2==2.9.7
3
- streamflow==0.2.0.dev7
1
+ asyncpg==0.28.0
2
+ streamflow==0.2.0.dev8
4
3
 
5
4
  [bandit]
6
5
  bandit==1.7.5
@@ -1,3 +0,0 @@
1
- aiopg==1.4.0
2
- psycopg2==2.9.7
3
- streamflow==0.2.0.dev7
@@ -1,610 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import os
4
- from typing import Any, MutableMapping, MutableSequence
5
-
6
- import aiopg
7
- import pkg_resources
8
- import psycopg2.extras
9
- from streamflow.core import utils
10
- from streamflow.core.context import StreamFlowContext
11
- from streamflow.core.deployment import Target
12
- from streamflow.core.persistence import DependencyType
13
- from streamflow.core.utils import get_date_from_ns
14
- from streamflow.core.workflow import Port, Status, Step, Token
15
- from streamflow.persistence.sqlite import CachedDatabase
16
-
17
-
18
- class PostgreSQLConnectionPool:
19
- def __init__(
20
- self,
21
- dbname: str,
22
- hostname: str,
23
- username: str,
24
- password: str,
25
- timeout: int,
26
- maxsize: int = 10,
27
- ):
28
- self.dbname: str = dbname
29
- self.hostname: str = hostname
30
- self.username: str = username
31
- self.password: str = password
32
- self.timeout: int = timeout
33
- self.maxsize: int = maxsize
34
- self._pool: aiopg.Pool | None = None
35
-
36
- async def __aenter__(self):
37
- if not self._pool:
38
- self._pool = await aiopg.create_pool(
39
- database=self.dbname,
40
- user=self.username,
41
- password=self.password,
42
- host=self.hostname,
43
- timeout=self.timeout,
44
- maxsize=self.maxsize,
45
- )
46
- schema_path = pkg_resources.resource_filename(
47
- __name__, os.path.join("schemas", "postgresql.sql")
48
- )
49
- with open(schema_path) as f:
50
- async with self._pool.acquire() as conn:
51
- async with conn.cursor() as cursor:
52
- await cursor.execute(f.read())
53
- return self._pool
54
-
55
- async def __aexit__(self, exc_type, exc_val, exc_tb):
56
- pass
57
-
58
- async def close(self):
59
- if self._pool:
60
- self._pool.close()
61
- await self._pool.wait_closed()
62
- self._pool = None
63
-
64
-
65
- class PostgreSQLDatabase(CachedDatabase):
66
- def __init__(
67
- self,
68
- context: StreamFlowContext,
69
- dbname: str,
70
- hostname: str,
71
- username: str,
72
- password: str,
73
- timeout: int = 20,
74
- maxConnections: int = 10,
75
- ):
76
- super().__init__(context)
77
- self.pool: PostgreSQLConnectionPool = PostgreSQLConnectionPool(
78
- dbname=dbname,
79
- hostname=hostname,
80
- username=username,
81
- password=password,
82
- timeout=timeout,
83
- maxsize=maxConnections,
84
- )
85
-
86
- async def close(self):
87
- await self.pool.close()
88
-
89
- @classmethod
90
- def get_schema(cls) -> str:
91
- return pkg_resources.resource_filename(
92
- __name__, os.path.join("schemas", "postgresql.json")
93
- )
94
-
95
- async def add_command(self, step_id: int, tag: str, cmd: str) -> int:
96
- async with self.pool as pool:
97
- async with pool.acquire() as db:
98
- async with db.cursor() as cursor:
99
- await cursor.execute(
100
- "INSERT INTO command(step, tag, cmd) "
101
- "VALUES(%(step)s, %(tag)s, %(cmd)s) "
102
- "RETURNING id",
103
- {"step": step_id, "tag": tag, "cmd": cmd},
104
- )
105
- return (await cursor.fetchone())[0]
106
-
107
- async def add_dependency(
108
- self, step: int, port: int, type: DependencyType, name: str
109
- ) -> None:
110
- async with self.pool as pool:
111
- async with pool.acquire() as db:
112
- async with db.cursor() as cursor:
113
- await cursor.execute(
114
- "INSERT INTO dependency(step, port, type, name) "
115
- "VALUES(%(step)s, %(port)s, %(type)s, %(name)s) "
116
- "ON CONFLICT DO NOTHING",
117
- {"step": step, "port": port, "type": type.value, "name": name},
118
- )
119
-
120
- async def add_deployment(
121
- self,
122
- name: str,
123
- type: str,
124
- config: str,
125
- external: bool,
126
- lazy: bool,
127
- workdir: str | None,
128
- ) -> int:
129
- async with self.pool as pool:
130
- async with pool.acquire() as db:
131
- async with db.cursor() as cursor:
132
- await cursor.execute(
133
- "INSERT INTO deployment(name, type, config, external, lazy, workdir) "
134
- "VALUES (%(name)s, %(type)s, %(config)s, %(external)s, %(lazy)s, %(workdir)s) "
135
- "RETURNING id",
136
- {
137
- "name": name,
138
- "type": type,
139
- "config": config,
140
- "external": external,
141
- "lazy": lazy,
142
- "workdir": workdir,
143
- },
144
- )
145
- return (await cursor.fetchone())[0]
146
-
147
- async def add_port(
148
- self, name: str, workflow_id: int, type: type[Port], params: str
149
- ) -> int:
150
- async with self.pool as pool:
151
- async with pool.acquire() as db:
152
- async with db.cursor() as cursor:
153
- await cursor.execute(
154
- "INSERT INTO port(name, workflow, type, params) "
155
- "VALUES(%(name)s, %(workflow)s, %(type)s, %(params)s) "
156
- "RETURNING id",
157
- {
158
- "name": name,
159
- "workflow": workflow_id,
160
- "type": utils.get_class_fullname(type),
161
- "params": params,
162
- },
163
- )
164
- return (await cursor.fetchone())[0]
165
-
166
- async def add_provenance(self, inputs: MutableSequence[int], token: int):
167
- provenance = [{"dependee": i, "depender": token} for i in inputs]
168
- async with self.pool as pool:
169
- async with pool.acquire() as db:
170
- async with db.cursor() as cursor:
171
- for prov in provenance:
172
- await cursor.execute(
173
- "INSERT INTO provenance(dependee, depender) "
174
- "VALUES(%(dependee)s, %(depender)s) "
175
- "ON CONFLICT DO NOTHING",
176
- prov,
177
- )
178
-
179
- async def add_step(
180
- self, name: str, workflow_id: int, status: int, type: type[Step], params: str
181
- ) -> int:
182
- async with self.pool as pool:
183
- async with pool.acquire() as db:
184
- async with db.cursor() as cursor:
185
- await cursor.execute(
186
- "INSERT INTO step(name, workflow, status, type, params) "
187
- "VALUES(%(name)s, %(workflow)s, %(status)s, %(type)s, %(params)s) "
188
- "RETURNING id",
189
- {
190
- "name": name,
191
- "workflow": workflow_id,
192
- "status": status,
193
- "type": utils.get_class_fullname(type),
194
- "params": params,
195
- },
196
- )
197
- return (await cursor.fetchone())[0]
198
-
199
- async def add_target(
200
- self,
201
- deployment: int,
202
- type: type[Target],
203
- params: str,
204
- locations: int = 1,
205
- service: str | None = None,
206
- workdir: str | None = None,
207
- ) -> int:
208
- async with self.pool as pool:
209
- async with pool.acquire() as db:
210
- async with db.cursor() as cursor:
211
- await cursor.execute(
212
- "INSERT INTO target(params, type, deployment, locations, service, workdir) "
213
- "VALUES (%(params)s, %(type)s, %(deployment)s, %(locations)s, %(service)s, %(workdir)s) "
214
- "RETURNING id",
215
- {
216
- "params": params,
217
- "type": utils.get_class_fullname(type),
218
- "deployment": deployment,
219
- "locations": locations,
220
- "service": service,
221
- "workdir": workdir,
222
- },
223
- )
224
- return (await cursor.fetchone())[0]
225
-
226
- async def add_token(
227
- self, tag: str, type: type[Token], value: Any, port: int | None = None
228
- ) -> int:
229
- async with self.pool as pool:
230
- async with pool.acquire() as db:
231
- async with db.cursor() as cursor:
232
- await cursor.execute(
233
- "INSERT INTO token(port, type, tag, value) "
234
- "VALUES(%(port)s, %(type)s, %(tag)s, %(value)s) "
235
- "RETURNING id",
236
- {
237
- "port": port,
238
- "type": utils.get_class_fullname(type),
239
- "tag": tag,
240
- "value": value,
241
- },
242
- )
243
- return (await cursor.fetchone())[0]
244
-
245
- async def add_workflow(self, name: str, params: str, status: int, type: str) -> int:
246
- async with self.pool as pool:
247
- async with pool.acquire() as db:
248
- async with db.cursor() as cursor:
249
- await cursor.execute(
250
- "INSERT INTO workflow(name, params, status, type) "
251
- "VALUES(%(name)s, %(params)s, %(status)s, %(type)s) "
252
- "RETURNING id",
253
- {
254
- "name": name,
255
- "params": params,
256
- "status": status,
257
- "type": type,
258
- },
259
- )
260
- return (await cursor.fetchone())[0]
261
-
262
- async def get_command(self, command_id: int) -> MutableMapping[str, Any]:
263
- async with self.pool as pool:
264
- async with pool.acquire() as db:
265
- async with db.cursor(
266
- cursor_factory=psycopg2.extras.RealDictCursor
267
- ) as cursor:
268
- await cursor.execute(
269
- "SELECT * FROM command WHERE id = %(id)s", {"id": command_id}
270
- )
271
- return await cursor.fetchone()
272
-
273
- async def get_commands_by_step(
274
- self, step_id: int
275
- ) -> MutableSequence[MutableMapping[str, Any]]:
276
- async with self.pool as pool:
277
- async with pool.acquire() as db:
278
- async with db.cursor(
279
- cursor_factory=psycopg2.extras.RealDictCursor
280
- ) as cursor:
281
- await cursor.execute(
282
- "SELECT * FROM command WHERE step = %(id)s", {"id": step_id}
283
- )
284
- return await cursor.fetchall()
285
-
286
- async def get_dependees(
287
- self, token_id: int
288
- ) -> MutableSequence[MutableMapping[str, Any]]:
289
- async with self.pool as pool:
290
- async with pool.acquire() as db:
291
- async with db.cursor(
292
- cursor_factory=psycopg2.extras.RealDictCursor
293
- ) as cursor:
294
- await cursor.execute(
295
- "SELECT * FROM provenance WHERE depender = %(id)s",
296
- {"id": token_id},
297
- )
298
- return await cursor.fetchall()
299
-
300
- async def get_dependers(
301
- self, token_id: int
302
- ) -> MutableSequence[MutableMapping[str, Any]]:
303
- async with self.pool as pool:
304
- async with pool.acquire() as db:
305
- async with db.cursor(
306
- cursor_factory=psycopg2.extras.RealDictCursor
307
- ) as cursor:
308
- await cursor.execute(
309
- "SELECT * FROM provenance WHERE dependee = %(id)s",
310
- {"id": token_id},
311
- )
312
- return await cursor.fetchall()
313
-
314
- async def get_deployment(self, deplyoment_id: int) -> MutableMapping[str, Any]:
315
- async with self.pool as pool:
316
- async with pool.acquire() as db:
317
- async with db.cursor(
318
- cursor_factory=psycopg2.extras.RealDictCursor
319
- ) as cursor:
320
- await cursor.execute(
321
- "SELECT * FROM deployment WHERE id = %(id)s",
322
- {"id": deplyoment_id},
323
- )
324
- return await cursor.fetchone()
325
-
326
- async def get_input_ports(
327
- self, step_id: int
328
- ) -> MutableSequence[MutableMapping[str, Any]]:
329
- async with self.pool as pool:
330
- async with pool.acquire() as db:
331
- async with db.cursor(
332
- cursor_factory=psycopg2.extras.RealDictCursor
333
- ) as cursor:
334
- await cursor.execute(
335
- "SELECT * FROM dependency WHERE step = %(step)s AND type = %(type)s",
336
- {"step": step_id, "type": DependencyType.INPUT.value},
337
- )
338
- return await cursor.fetchall()
339
-
340
- async def get_output_ports(
341
- self, step_id: int
342
- ) -> MutableSequence[MutableMapping[str, Any]]:
343
- async with self.pool as pool:
344
- async with pool.acquire() as db:
345
- async with db.cursor(
346
- cursor_factory=psycopg2.extras.RealDictCursor
347
- ) as cursor:
348
- await cursor.execute(
349
- "SELECT * FROM dependency WHERE step = %(step)s AND type = %(type)s",
350
- {"step": step_id, "type": DependencyType.OUTPUT.value},
351
- )
352
- return await cursor.fetchall()
353
-
354
- async def get_port(self, port_id: int) -> MutableMapping[str, Any]:
355
- async with self.pool as pool:
356
- async with pool.acquire() as db:
357
- async with db.cursor(
358
- cursor_factory=psycopg2.extras.RealDictCursor
359
- ) as cursor:
360
- await cursor.execute(
361
- "SELECT * FROM port WHERE id = %(id)s", {"id": port_id}
362
- )
363
- return await cursor.fetchone()
364
-
365
- async def get_port_tokens(self, port_id: int) -> MutableSequence[int]:
366
- async with self.pool as pool:
367
- async with pool.acquire() as db:
368
- async with db.cursor() as cursor:
369
- await cursor.execute(
370
- "SELECT * FROM port WHERE id = %(id)s", {"id": port_id}
371
- )
372
- return [row[0] for row in await cursor.fetchall()]
373
-
374
- async def get_reports(
375
- self, workflow: str, last_only: bool = False
376
- ) -> MutableSequence[MutableSequence[MutableMapping[str, Any]]]:
377
- async with self.pool as pool:
378
- async with pool.acquire() as db:
379
- async with db.cursor(
380
- cursor_factory=psycopg2.extras.RealDictCursor
381
- ) as cursor:
382
- if last_only:
383
- await cursor.execute(
384
- "SELECT c.id, s.name, c.start_time, c.end_time "
385
- "FROM step AS s, command AS c "
386
- "WHERE s.id = c.step "
387
- "AND s.workflow = (SELECT id FROM workflow WHERE name = %(workflow)s ORDER BY id DESC LIMIT 1)",
388
- {"workflow": workflow},
389
- )
390
- return [[dict(r) for r in await cursor.fetchall()]]
391
- else:
392
- await cursor.execute(
393
- "SELECT s.workflow, c.id, s.name, c.start_time, c.end_time "
394
- "FROM step AS s, command AS c "
395
- "WHERE s.id = c.step "
396
- "AND s.workflow IN (SELECT id FROM workflow WHERE name = %(workflow)s) "
397
- "ORDER BY s.workflow DESC",
398
- {"workflow": workflow},
399
- )
400
- result = {}
401
- async for row in cursor:
402
- result.setdefault(row["workflow"], []).append(
403
- {k: row[k] for k in row.keys() if k != "workflow"}
404
- )
405
- return list(result.values())
406
-
407
- async def get_step(self, step_id: int) -> MutableMapping[str, Any]:
408
- async with self.pool as pool:
409
- async with pool.acquire() as db:
410
- async with db.cursor(
411
- cursor_factory=psycopg2.extras.RealDictCursor
412
- ) as cursor:
413
- await cursor.execute(
414
- "SELECT * FROM step WHERE id = %(id)s", {"id": step_id}
415
- )
416
- return await cursor.fetchone()
417
-
418
- async def get_target(self, target_id: int) -> MutableMapping[str, Any]:
419
- async with self.pool as pool:
420
- async with pool.acquire() as db:
421
- async with db.cursor(
422
- cursor_factory=psycopg2.extras.RealDictCursor
423
- ) as cursor:
424
- await cursor.execute(
425
- "SELECT * FROM target WHERE id = %(id)s", {"id": target_id}
426
- )
427
- return await cursor.fetchone()
428
-
429
- async def get_token(self, token_id: int) -> MutableMapping[str, Any]:
430
- async with self.pool as pool:
431
- async with pool.acquire() as db:
432
- async with db.cursor(
433
- cursor_factory=psycopg2.extras.RealDictCursor
434
- ) as cursor:
435
- await cursor.execute(
436
- "SELECT * FROM token WHERE id = %(id)s", {"id": token_id}
437
- )
438
- return {
439
- k: bytearray(v) if isinstance(v, memoryview) else v
440
- for k, v in (await cursor.fetchone()).items()
441
- }
442
-
443
- async def get_workflow(self, workflow_id: int) -> MutableMapping[str, Any]:
444
- async with self.pool as pool:
445
- async with pool.acquire() as db:
446
- async with db.cursor(
447
- cursor_factory=psycopg2.extras.RealDictCursor
448
- ) as cursor:
449
- await cursor.execute(
450
- "SELECT * FROM workflow WHERE id = %(id)s", {"id": workflow_id}
451
- )
452
- return await cursor.fetchone()
453
-
454
- async def get_workflows_by_name(
455
- self, workflow_name: str, last_only: bool = False
456
- ) -> MutableSequence[MutableMapping[str, Any]]:
457
- async with self.pool as pool:
458
- async with pool.acquire() as db:
459
- async with db.cursor(
460
- cursor_factory=psycopg2.extras.RealDictCursor
461
- ) as cursor:
462
- await cursor.execute(
463
- "SELECT * FROM workflow WHERE name = %(name)s ORDER BY id desc",
464
- {"name": workflow_name},
465
- )
466
- return (
467
- [await cursor.fetchone()]
468
- if last_only
469
- else await cursor.fetchall()
470
- )
471
-
472
- async def get_workflow_ports(
473
- self, workflow_id: int
474
- ) -> MutableSequence[MutableMapping[str, Any]]:
475
- async with self.pool as pool:
476
- async with pool.acquire() as db:
477
- async with db.cursor(
478
- cursor_factory=psycopg2.extras.RealDictCursor
479
- ) as cursor:
480
- await cursor.execute(
481
- "SELECT * FROM port WHERE workflow = %(workflow)s",
482
- {"workflow": workflow_id},
483
- )
484
- return await cursor.fetchall()
485
-
486
- async def get_workflow_steps(
487
- self, workflow_id: int
488
- ) -> MutableSequence[MutableMapping[str, Any]]:
489
- async with self.pool as pool:
490
- async with pool.acquire() as db:
491
- async with db.cursor(
492
- cursor_factory=psycopg2.extras.RealDictCursor
493
- ) as cursor:
494
- await cursor.execute(
495
- "SELECT * FROM step WHERE workflow = %(workflow)s",
496
- {"workflow": workflow_id},
497
- )
498
- return await cursor.fetchall()
499
-
500
- async def list_workflows(
501
- self, name: str | None
502
- ) -> MutableSequence[MutableMapping[str, Any]]:
503
- async with self.pool as pool:
504
- async with pool.acquire() as db:
505
- if name is not None:
506
- return [
507
- {
508
- "end_time": get_date_from_ns(row["end_time"]),
509
- "start_time": get_date_from_ns(row["start_time"]),
510
- "status": Status(row["status"]).name,
511
- "type": row["type"],
512
- }
513
- for row in await self.get_workflows_by_name(
514
- name, last_only=False
515
- )
516
- ]
517
- else:
518
- async with db.cursor(
519
- cursor_factory=psycopg2.extras.RealDictCursor
520
- ) as cursor:
521
- await cursor.execute(
522
- "SELECT name, type, COUNT(*) AS num FROM workflow GROUP BY name, type ORDER BY name DESC"
523
- )
524
- return await cursor.fetchall()
525
-
526
- async def update_command(
527
- self, command_id: int, updates: MutableMapping[str, Any]
528
- ) -> int:
529
- async with self.pool as pool:
530
- async with pool.acquire() as db:
531
- async with db.cursor() as cursor:
532
- await cursor.execute(
533
- "UPDATE command SET {} WHERE id = %(id)s".format( # nosec
534
- ", ".join([f"{k} = %({k})s" for k in updates])
535
- ),
536
- {**updates, **{"id": command_id}},
537
- )
538
- self.port_cache.pop(command_id, None)
539
- return command_id
540
-
541
- async def update_deployment(
542
- self, deployment_id: int, updates: MutableMapping[str, Any]
543
- ) -> int:
544
- async with self.pool as pool:
545
- async with pool.acquire() as db:
546
- async with db.cursor() as cursor:
547
- await cursor.execute(
548
- "UPDATE deployment SET {} WHERE id = %(id)s".format( # nosec
549
- ", ".join([f"{k} = %({k})s" for k in updates])
550
- ),
551
- {**updates, **{"id": deployment_id}},
552
- )
553
- self.port_cache.pop(deployment_id, None)
554
- return deployment_id
555
-
556
- async def update_port(self, port_id: int, updates: MutableMapping[str, Any]) -> int:
557
- async with self.pool as pool:
558
- async with pool.acquire() as db:
559
- async with db.cursor() as cursor:
560
- await cursor.execute(
561
- "UPDATE port SET {} WHERE id = %(id)s".format( # nosec
562
- ", ".join([f"{k} = %({k})s" for k in updates])
563
- ),
564
- {**updates, **{"id": port_id}},
565
- )
566
- self.port_cache.pop(port_id, None)
567
- return port_id
568
-
569
- async def update_step(self, step_id: int, updates: MutableMapping[str, Any]) -> int:
570
- async with self.pool as pool:
571
- async with pool.acquire() as db:
572
- async with db.cursor() as cursor:
573
- await cursor.execute(
574
- "UPDATE step SET {} WHERE id = %(id)s".format( # nosec
575
- ", ".join([f"{k} = %({k})s" for k in updates])
576
- ),
577
- {**updates, **{"id": step_id}},
578
- )
579
- self.step_cache.pop(step_id, None)
580
- return step_id
581
-
582
- async def update_target(
583
- self, target_id: int, updates: MutableMapping[str, Any]
584
- ) -> int:
585
- async with self.pool as pool:
586
- async with pool.acquire() as db:
587
- async with db.cursor() as cursor:
588
- await cursor.execute(
589
- "UPDATE target SET {} WHERE id = %(id)s".format( # nosec
590
- ", ".join([f"{k} = %({k})s" for k in updates])
591
- ),
592
- {**updates, **{"id": target_id}},
593
- )
594
- self.target_cache.pop(target_id, None)
595
- return target_id
596
-
597
- async def update_workflow(
598
- self, workflow_id: int, updates: MutableMapping[str, Any]
599
- ) -> int:
600
- async with self.pool as pool:
601
- async with pool.acquire() as db:
602
- async with db.cursor() as cursor:
603
- await cursor.execute(
604
- "UPDATE workflow SET {} WHERE id = %(id)s".format( # nosec
605
- ", ".join([f"{k} = %({k})s" for k in updates])
606
- ),
607
- {**updates, **{"id": workflow_id}},
608
- )
609
- self.workflow_cache.pop(workflow_id, None)
610
- return workflow_id
@@ -1 +0,0 @@
1
- VERSION = "0.0.4"