workflow.core 1.10.0__tar.gz → 1.11.1__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 (60) hide show
  1. {workflow_core-1.10.0 → workflow_core-1.11.1}/PKG-INFO +2 -1
  2. {workflow_core-1.10.0 → workflow_core-1.11.1}/pyproject.toml +1 -1
  3. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/configs.py +169 -10
  4. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/pipelines.py +10 -2
  5. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/run.py +10 -8
  6. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/buckets.py +3 -3
  7. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/configs.py +48 -0
  8. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/configure.py +43 -11
  9. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/execute.py +1 -4
  10. workflow_core-1.11.1/workflow/utils/format.py +89 -0
  11. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/renderers.py +38 -3
  12. {workflow_core-1.10.0 → workflow_core-1.11.1}/README.md +0 -0
  13. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/__init__.py +0 -0
  14. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/__init__.py +0 -0
  15. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/buckets.py +0 -0
  16. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/main.py +0 -0
  17. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/results.py +0 -0
  18. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/schedules.py +0 -0
  19. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/cli/workspace.py +0 -0
  20. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/daemons/__init__.py +0 -0
  21. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/daemons/audit.py +0 -0
  22. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/daemons/transfer.py +0 -0
  23. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/__init__.py +0 -0
  24. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/config.py +0 -0
  25. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/jsonschema.md +0 -0
  26. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/notify.py +0 -0
  27. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/work.py +0 -0
  28. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/definitions/workspace.py +0 -0
  29. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/examples/autocomplete.py +0 -0
  30. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/examples/function.py +0 -0
  31. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/examples/sample.svg +0 -0
  32. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/examples/sample.workflow.yml +0 -0
  33. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/exceptions.py +0 -0
  34. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/helpers/__init__.py +0 -0
  35. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/helpers/date.py +0 -0
  36. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/__init__.py +0 -0
  37. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/client.py +0 -0
  38. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/context.py +0 -0
  39. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/pipelines.py +0 -0
  40. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/results.py +0 -0
  41. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/http/schedules.py +0 -0
  42. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/__init__.py +0 -0
  43. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/archive/__init__.py +0 -0
  44. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/archive/http.py +0 -0
  45. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/archive/posix.py +0 -0
  46. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/archive/s3.py +0 -0
  47. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/lifecycle/attempt.py +0 -0
  48. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/__init__.py +0 -0
  49. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/decorators.py +0 -0
  50. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/logger.py +0 -0
  51. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/prompt.py +0 -0
  52. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/read.py +0 -0
  53. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/tmate.sh +0 -0
  54. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/validate.py +0 -0
  55. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/variables.py +0 -0
  56. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/utils/write.py +0 -0
  57. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/workspaces/__init__.py +0 -0
  58. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/workspaces/chimefrb.yml +0 -0
  59. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/workspaces/development.yml +0 -0
  60. {workflow_core-1.10.0 → workflow_core-1.11.1}/workflow/workspaces/site-dev.yml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: workflow.core
3
- Version: 1.10.0
3
+ Version: 1.11.1
4
4
  Summary: Workflow Core
5
5
  Home-page: https://github.com/chimefrb/workflow
6
6
  License: MIT
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.9
13
13
  Classifier: Programming Language :: Python :: 3.10
14
14
  Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
16
17
  Requires-Dist: click (>=8.1,<9.0)
17
18
  Requires-Dist: click-params (>=0.5,<0.6)
18
19
  Requires-Dist: docker (>=6.1)
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "workflow.core"
3
- version = "1.10.0"
3
+ version = "1.11.1"
4
4
  description = "Workflow Core"
5
5
  authors = ["Shiny Brar <charanjotbrar@gmail.com>"]
6
6
  license = "MIT"
@@ -2,19 +2,21 @@
2
2
 
3
3
  import json
4
4
  from typing import Any, Dict, List, Optional
5
+ from urllib.parse import urlencode
5
6
 
6
7
  import click
7
8
  import requests
8
9
  import yaml
9
10
  from rich import pretty
10
11
  from rich.console import Console
12
+ from rich.progress import BarColumn, Progress, TextColumn
11
13
  from rich.syntax import Syntax
12
- from rich.table import Table
14
+ from rich.table import Column, Table
13
15
  from rich.text import Text
14
16
  from yaml.loader import SafeLoader
15
17
 
16
18
  from workflow.http.context import HTTPContext
17
- from workflow.utils import validate
19
+ from workflow.utils import format, validate
18
20
  from workflow.utils.renderers import render_config
19
21
 
20
22
  pretty.install()
@@ -48,7 +50,7 @@ def version():
48
50
  @configs.command("count", help="Count objects per collection.")
49
51
  def count():
50
52
  """Count objects in a database."""
51
- http = HTTPContext()
53
+ http = HTTPContext(backends=["configs"])
52
54
  counts = http.configs.count()
53
55
  table.add_column("Name", max_width=50, justify="left", style="blue")
54
56
  table.add_column("Count", max_width=50, justify="left")
@@ -75,7 +77,7 @@ def deploy(filename: click.Path):
75
77
  filename : click.Path
76
78
  File path.
77
79
  """
78
- http = HTTPContext()
80
+ http = HTTPContext(backends=["configs"])
79
81
  filepath: str = str(filename)
80
82
  data: Dict[str, Any] = {}
81
83
  with open(filepath) as reader:
@@ -148,7 +150,7 @@ def ls(name: Optional[str] = None, quiet: bool = False):
148
150
  projection = {"yaml": 0, "deployments": 0}
149
151
  if quiet:
150
152
  projection = {"id": 1}
151
- http = HTTPContext()
153
+ http = HTTPContext(backends=["configs"])
152
154
  objects = http.configs.get_configs(name=name, projection=json.dumps(projection))
153
155
 
154
156
  # ? Add columns for each key
@@ -188,7 +190,7 @@ def ls(name: Optional[str] = None, quiet: bool = False):
188
190
  )
189
191
  def ps(name: str, id: str, details: bool):
190
192
  """Show details for an object."""
191
- http = HTTPContext()
193
+ http = HTTPContext(backends=["configs", "pipelines"])
192
194
  query: str = json.dumps({"id": id})
193
195
  projection: str = json.dumps({})
194
196
  console_content = None
@@ -233,12 +235,12 @@ def ps(name: str, id: str, details: bool):
233
235
  console.print(console_content)
234
236
 
235
237
 
236
- @configs.command("stop", help="Stop managers for a Config.")
238
+ @configs.command("stop", help="Stop Pipelines related to a Config.")
237
239
  @click.argument("config", type=str, required=True)
238
240
  @click.argument("id", type=str, required=True)
239
241
  def stop(config: str, id: str):
240
242
  """Stop managers for a Config."""
241
- http = HTTPContext()
243
+ http = HTTPContext(backends=["configs"])
242
244
  stop_result = http.configs.stop(config, id)
243
245
  if not any(stop_result):
244
246
  text = Text("No configurations were stopped.", style="red")
@@ -258,12 +260,12 @@ def stop(config: str, id: str):
258
260
  console.print(table)
259
261
 
260
262
 
261
- @configs.command("rm", help="Remove a config.")
263
+ @configs.command("rm", help="Removes a config.")
262
264
  @click.argument("config", type=str, required=True)
263
265
  @click.argument("id", type=str, required=True)
264
266
  def rm(config: str, id: str):
265
267
  """Remove a config."""
266
- http = HTTPContext()
268
+ http = HTTPContext(backends=["configs"])
267
269
  content = None
268
270
  try:
269
271
  delete_result = http.configs.remove(config, id)
@@ -278,3 +280,160 @@ def rm(config: str, id: str):
278
280
  table.add_row(id)
279
281
  content = table
280
282
  console.print(content)
283
+
284
+
285
+ @configs.command("retry", help="Retry all Pipeline related to a Config.")
286
+ @click.argument("name", type=str, required=True)
287
+ @click.argument("id", type=str, required=True)
288
+ def retry(name: str, id: str):
289
+ """Retry all Pipeline related to a Config.
290
+
291
+ Parameters
292
+ ----------
293
+ name : str
294
+ Config name.
295
+ id : str
296
+ Config ID.
297
+ """
298
+ http = HTTPContext(backends=["configs"])
299
+ content = None
300
+ try:
301
+ retry_result = http.configs._retry(name, id)
302
+ except Exception as e:
303
+ text = Text(f"No configurations were retried.\nError: {e}", style="red")
304
+ content = text
305
+ else:
306
+ table.add_column(
307
+ retry_result["message"], max_width=50, justify="left", style="red"
308
+ )
309
+ content = table
310
+ console.print(content)
311
+
312
+
313
+ @configs.command("reformat", help="Reformat V1 YAML files to V2.")
314
+ @click.argument(
315
+ "filename",
316
+ type=click.Path(exists=True, dir_okay=False, readable=True),
317
+ required=True,
318
+ )
319
+ def reformat(filename: click.Path):
320
+ """Reformat YAML file to V2.
321
+
322
+ Parameters
323
+ ----------
324
+ filename : click.Path
325
+ Filename.
326
+ """
327
+ filepath: str = str(filename)
328
+ data: Dict[str, Any] = {}
329
+ with open(filepath) as reader:
330
+ data = yaml.load(reader, Loader=SafeLoader) # type: ignore
331
+
332
+ steps, matrix, version = format.needs_reformat(data)
333
+ if any([steps, matrix, version]):
334
+ console.print(Text("Version 1 YAML, reformatting...", style="red"))
335
+ data = format.reformat(
336
+ data=data,
337
+ r_steps=steps,
338
+ r_matrix=matrix,
339
+ r_version=version,
340
+ console=console,
341
+ )
342
+ else:
343
+ console.print(Text("Reformat not needed.", style="red"))
344
+ return
345
+
346
+ with open(filepath, "w") as file:
347
+ new_data: str = yaml.dump(data)
348
+ file.write(new_data)
349
+ console.print(f"Reformatted file {filename}", style="green")
350
+
351
+
352
+ @configs.command("migrate", help="Sends running Config to Pipelines V2.")
353
+ @click.argument("name", type=str, required=True)
354
+ @click.argument("base_url", type=str, required=True)
355
+ @click.option(
356
+ "status",
357
+ "-s",
358
+ "--status",
359
+ type=click.Choice(["success", "failure", "running", "queued", "cancelled"]),
360
+ default="running",
361
+ )
362
+ @click.option("delete", "-d", "--delete", is_flag=True, default=False)
363
+ def migrate(name: str, base_url: str, status: str, delete: bool):
364
+ """Migrates V1 Configs to V2.
365
+
366
+ Parameters
367
+ ----------
368
+ name : str
369
+ Configuration name.
370
+ base_url : str
371
+ Pipelines V1 backend URL.
372
+ status : str
373
+ Status filter.
374
+ delete : bool
375
+ WIP.
376
+ """
377
+ http = HTTPContext(backends=["configs"])
378
+ params = {
379
+ "skip": 0,
380
+ "length": 100,
381
+ "projection": json.dumps({}),
382
+ "query": json.dumps({"status": {"$in": status.split(",")}}),
383
+ "name": name,
384
+ }
385
+ url = f"{base_url}?{urlencode(params)}"
386
+ response = requests.get(url)
387
+ pipelines = response.json()
388
+ text_column = TextColumn("{task.description}", table_column=Column(ratio=1))
389
+ bar_column = BarColumn(bar_width=None, table_column=Column(ratio=2))
390
+ progress = Progress(text_column, bar_column, expand=True)
391
+
392
+ if not pipelines:
393
+ console.print(f"No Config objects were found under the name {name}")
394
+ return
395
+
396
+ console.print(
397
+ f"Migrating {len(pipelines)} Pipeline objects from {name} collection to V2.",
398
+ style="bright_green",
399
+ )
400
+ with progress:
401
+ for obj in pipelines:
402
+ task = progress.add_task(f"[cyan]Migrating {obj['id']}", total=1)
403
+ # ? Reformat
404
+ reformatted_obj = format.reformat(
405
+ data=obj,
406
+ r_steps=False,
407
+ r_matrix=False,
408
+ r_version=True,
409
+ )
410
+ yaml_url = (
411
+ f"{base_url}/inspect?"
412
+ f"{urlencode({'name': name, 'id': reformatted_obj['id']})}"
413
+ )
414
+ yaml_response = requests.get(yaml_url)
415
+ old_yaml = yaml_response.json()["yaml"]
416
+ new_yaml = format.reformat(
417
+ data=yaml.safe_load(old_yaml),
418
+ r_steps=True,
419
+ r_matrix=True,
420
+ r_version=True,
421
+ )
422
+ progress.update(task, advance=0.3)
423
+ reformatted_obj["yaml"] = yaml.dump(new_yaml)
424
+ # ? Stop monitoring on V1
425
+ stopped = False
426
+ if obj["status"] == "running":
427
+ stop_params = urlencode(
428
+ {"name": obj["name"], "query": json.dumps({"id": obj["id"]})}
429
+ )
430
+ stop_url = f"{base_url}/cancel?" f"{stop_params}"
431
+ stop_response = requests.put(stop_url)
432
+ if stop_response.ok:
433
+ stopped = True
434
+ progress.update(task, advance=0.3)
435
+ # ? Migrate
436
+ migration_response = http.configs.migrate(reformatted_obj)
437
+ if migration_response.ok:
438
+ progress.update(task, advance=0.4 if stopped else 0.7)
439
+ console.print("Migration completed", style="bright_green")
@@ -94,7 +94,15 @@ def count():
94
94
  @pipelines.command("ps", help="Get pipeline details.")
95
95
  # @click.argument("pipeline", type=str, required=True)
96
96
  @click.argument("id", type=str, required=True)
97
- def ps(id: str):
97
+ @click.option(
98
+ "-h",
99
+ "--history",
100
+ is_flag=True,
101
+ default=False,
102
+ show_default=True,
103
+ help="Show the execution history for the Pipeline.",
104
+ )
105
+ def ps(id: str, history: bool = False):
98
106
  """List a pipeline configuration in detail."""
99
107
  http = HTTPContext()
100
108
  query: str = json.dumps({"id": id})
@@ -131,7 +139,7 @@ def ps(id: str):
131
139
  max_width=column_max_width,
132
140
  justify="left",
133
141
  )
134
- text.append(render_pipeline(payload))
142
+ text.append(render_pipeline(payload, history=history))
135
143
  table.add_row(text)
136
144
  console_content = table
137
145
  finally:
@@ -208,17 +208,19 @@ def run(
208
208
  )
209
209
  else:
210
210
  # Missing Logging config in Workspace
211
- config.update({
212
- "logging": {
213
- "loki": {
214
- "tags": {
215
- # Assumes that there is only one bucket
216
- "pipeline": buckets[0],
217
- "site": site,
211
+ config.update(
212
+ {
213
+ "logging": {
214
+ "loki": {
215
+ "tags": {
216
+ # Assumes that there is only one bucket
217
+ "pipeline": buckets[0],
218
+ "site": site,
219
+ }
218
220
  }
219
221
  }
220
222
  }
221
- })
223
+ )
222
224
  loki_status: bool = configure.loki(logger=logger, config=config)
223
225
  logger.info(f"Loki Logs: {'✅' if loki_status else '❌'}")
224
226
  http: HTTPContext = HTTPContext(backends=["buckets"])
@@ -6,7 +6,7 @@ from urllib.parse import urlencode
6
6
  from requests.models import Response
7
7
  from tenacity import retry
8
8
  from tenacity.stop import stop_after_delay
9
- from tenacity.wait import wait_random
9
+ from tenacity.wait import wait_fixed, wait_random
10
10
 
11
11
  from workflow.http.client import Client
12
12
  from workflow.utils.logger import get_logger
@@ -123,7 +123,7 @@ class Buckets(Client):
123
123
  response.raise_for_status()
124
124
  return response.json()
125
125
 
126
- @retry(wait=wait_random(min=0.1, max=2), stop=(stop_after_delay(30)))
126
+ @retry(wait=wait_fixed(30), stop=(stop_after_delay(30)))
127
127
  def delete_ids(self, ids: List[str]) -> bool:
128
128
  """Delete works from the buckets backend with the given ids.
129
129
 
@@ -148,7 +148,7 @@ class Buckets(Client):
148
148
  tags: Optional[List[str]] = None,
149
149
  parent: Optional[str] = None,
150
150
  force: bool = False,
151
- limit: Optional[int] = 100
151
+ limit: Optional[int] = 100,
152
152
  ) -> bool:
153
153
  """Delete works belonging to a pipeline from the buckets backend.
154
154
 
@@ -44,6 +44,28 @@ class Configs(Client):
44
44
  response.raise_for_status()
45
45
  return response.json()
46
46
 
47
+ @retry(
48
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
49
+ )
50
+ def migrate(self, data: Dict[str, Any]) -> Dict[str, Any]:
51
+ """Migrates V1 objects to V2.
52
+
53
+ Parameters
54
+ ----------
55
+ data : Dict[str, Any]
56
+ Object payload.
57
+
58
+ Returns
59
+ -------
60
+ Dict[str, Any]
61
+ Backend JSON response.
62
+ """
63
+ with self.session as session:
64
+ url = f"{self.baseurl}/configs/migrate"
65
+ response: Response = session.post(url, json=data)
66
+ response.raise_for_status()
67
+ return response.json()
68
+
47
69
  def count(self) -> Dict[str, Any]:
48
70
  """Count all documents in a collection.
49
71
 
@@ -163,3 +185,29 @@ class Configs(Client):
163
185
  response.raise_for_status()
164
186
  server_info = response.json()
165
187
  return {"client": client_info, "server": server_info}
188
+
189
+ @retry(
190
+ reraise=True, wait=wait_random(min=0.3, max=1.8), stop=(stop_after_delay(15))
191
+ )
192
+ def _retry(self, name: str, id: str) -> Dict[str, Any]:
193
+ """Makes POST request to /retry endpoint.
194
+
195
+ Parameters
196
+ ----------
197
+ name : str
198
+ Config name.
199
+ id : str
200
+ Config ID.
201
+
202
+ Returns
203
+ -------
204
+ Dict[str, Any]
205
+ Response payload.
206
+ """
207
+ with self.session as session:
208
+ body = {"id": id, "name": name}
209
+ response: Response = session.post(
210
+ url=f"{self.baseurl}/configs/retry", json=body
211
+ )
212
+ response.raise_for_status()
213
+ return response.json()
@@ -91,7 +91,7 @@ def loki(logger: Logger, config: Dict[str, Any]) -> bool:
91
91
  return status
92
92
 
93
93
 
94
- def arguments(arguments: Optional[Dict[str, Any]]) -> List[str]:
94
+ def arguments(func: Callable[..., Any], work: Work) -> List[str]:
95
95
  """Return a list of CLI arguments.
96
96
 
97
97
  Args:
@@ -101,14 +101,44 @@ def arguments(arguments: Optional[Dict[str, Any]]) -> List[str]:
101
101
  List[str]: List of CLI arguments
102
102
  """
103
103
  args: List[str] = []
104
- if arguments:
105
- for key, value in arguments.items():
106
- if not value:
107
- args.append(f"{key}")
108
- elif value and len(key) == 2:
109
- args.append(f"{key} {value}")
110
- elif value and len(key) > 2:
111
- args.append(f"{key}={value}")
104
+
105
+ for parameter in func.params: # type: ignore
106
+ parameter_name_in_cli = parameter.opts[-1]
107
+ paraneter_name_in_function = parameter.name
108
+ parameter_value_in_work = work.parameters.get( # type: ignore
109
+ paraneter_name_in_function, None
110
+ )
111
+
112
+ if parameter_value_in_work:
113
+ if isinstance(parameter_value_in_work, list):
114
+ parameter_value_in_work = " ".join(parameter_value_in_work)
115
+
116
+ if isinstance(parameter, click.Argument):
117
+ # If argument, then the parameter is purely positional without a key
118
+ args.append(f"{parameter_value_in_work}")
119
+ elif isinstance(parameter, click.Option):
120
+ if hasattr(parameter, "is_flag") and parameter.is_flag:
121
+ # If is_flag=True,
122
+ # then the parameter is a flag and doesn't have a value
123
+ args.append(f"{parameter_name_in_cli}")
124
+ else:
125
+ if len(parameter_name_in_cli) == 2:
126
+ # Short options
127
+ # (often denoted by a single hyphen and a single letter like -r)
128
+ # are commonly written with a space
129
+ # between the option and its value
130
+ args.append(
131
+ f"{parameter_name_in_cli} {parameter_value_in_work}"
132
+ )
133
+ elif len(parameter_name_in_cli) > 2:
134
+ # Long options
135
+ # (often denoted by two hyphens and a word like --recursive)
136
+ # are commonly written with an equals sign
137
+ # between the option and its value
138
+ args.append(
139
+ f"{parameter_name_in_cli}={parameter_value_in_work}"
140
+ )
141
+
112
142
  return args
113
143
 
114
144
 
@@ -142,7 +172,8 @@ def defaults(func: Callable[..., Any], work: Work) -> Work:
142
172
 
143
173
  if hasattr(parameter, "is_flag") and parameter.is_flag:
144
174
  if parameter_default_value is True:
145
- # Flags aren't assigned values, its CLI name is just included or not included
175
+ # Flags aren't assigned values
176
+ # its CLI name is just included or not included
146
177
  options[name_in_cli] = None
147
178
  else:
148
179
  options[name_in_cli] = parameter_default_value
@@ -151,7 +182,8 @@ def defaults(func: Callable[..., Any], work: Work) -> Work:
151
182
 
152
183
  if hasattr(parameter, "is_flag") and parameter.is_flag:
153
184
  if parameter_given_value is True:
154
- # Flags aren't assigned values, its CLI name is just included or not included
185
+ # Flags aren't assigned values
186
+ # its CLI name is just included or not included
155
187
  options[name_in_cli] = None
156
188
  else:
157
189
  options[name_in_cli] = parameter_given_value
@@ -36,13 +36,10 @@ def function(work: Work) -> Work:
36
36
  assert isinstance(work.function, str), "missing function to execute"
37
37
  func: Callable[..., Any] = validate.function(work.function)
38
38
  arguments: List[str] = []
39
- # Configure default values for the function
40
- work = configure.defaults(func, work)
41
- # Paramters to execute the function with
42
39
  parameters: Dict[str, Any] = work.parameters or {}
43
40
 
44
41
  if isinstance(func, click.Command):
45
- arguments = configure.arguments(parameters)
42
+ arguments = configure.arguments(func, work)
46
43
  logger.info(
47
44
  f"executing: {func.name}.main(args={arguments}, standalone_mode=False)"
48
45
  )
@@ -0,0 +1,89 @@
1
+ """Refomat functions."""
2
+
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ from rich.console import Console
6
+
7
+
8
+ def needs_reformat(data: Dict[str, Any]) -> Tuple[bool, bool, bool]:
9
+ """Determines if data needs reformat.
10
+
11
+ Parameters
12
+ ----------
13
+ data : Dict[str, Any]
14
+ Payload.
15
+
16
+ Returns
17
+ -------
18
+ Tuple[bool, bool, bool]
19
+ Tuple of fields that need reformat.
20
+ """
21
+ matrix = False
22
+ steps = False
23
+ version = False
24
+ if isinstance(data["pipeline"], dict):
25
+ if "steps" not in data["pipeline"].keys():
26
+ steps = True
27
+ if "matrix" in data.keys():
28
+ matrix = True
29
+ if data["version"] == "1" or isinstance(data["version"], int):
30
+ version = True
31
+ return steps, matrix, version
32
+
33
+
34
+ def reformat(
35
+ data: Dict[str, Any],
36
+ r_steps: bool,
37
+ r_matrix: bool,
38
+ r_version: bool,
39
+ console: Optional[Console] = None,
40
+ ) -> Dict[str, Any]:
41
+ """Reformats data to work on Pipeline V2 backend.
42
+
43
+ Parameters
44
+ ----------
45
+ data : Dict[str, Any]
46
+ Config payload.
47
+ r_steps: bool
48
+ If steps needs to be reformatted.
49
+ r_matrix : bool
50
+ If matrix needs to be reformatted.
51
+ r_version: bool,
52
+ If version needs to be reformatted.
53
+ console: Console,
54
+ Console object.
55
+
56
+ Returns
57
+ -------
58
+ Dict[str, Any]
59
+ Reformatted data.
60
+ """
61
+ # ? Reformat steps
62
+ if r_steps:
63
+ if console:
64
+ console.print("Reformatting steps.", style="green")
65
+ steps: List[Dict[str, Any]] = []
66
+ for step_name in data["pipeline"].keys():
67
+ step = data["pipeline"][step_name]
68
+ step["name"] = step_name.replace("_", "-")
69
+ steps.append(step)
70
+ data.pop("pipeline")
71
+ data["pipeline"] = {"steps": steps}
72
+
73
+ # ? Check top level matrix
74
+ if r_matrix:
75
+ if console:
76
+ console.print("Reformatting top level matrix.", style="green")
77
+ matrix: Optional[Dict[str, Any]] = None
78
+ if data.get("matrix", None):
79
+ matrix = data["matrix"]
80
+ data.pop("matrix")
81
+ data["pipeline"]["matrix"] = matrix
82
+
83
+ # ? Fix version
84
+ if r_version:
85
+ if console:
86
+ console.print("Fixing version.", style="green")
87
+ data["version"] = "2"
88
+
89
+ return data
@@ -11,13 +11,33 @@ from workflow.http.context import HTTPContext
11
11
  from workflow.utils.variables import status_colors, status_symbols
12
12
 
13
13
 
14
- def render_pipeline(payload: Dict[str, Any]) -> Text:
14
+ def render_timestamp(timestamp: float) -> str:
15
+ """Converts a timestamp into a readable string.
16
+
17
+ Parameters
18
+ ----------
19
+ timestamp : float
20
+ Timestamp.
21
+
22
+ Returns
23
+ -------
24
+ str
25
+ Formatted timestamp.
26
+ """
27
+ from_dt: dt.datetime = dt.datetime.fromtimestamp(timestamp)
28
+ formatted_dt: str = dt.datetime.strftime(from_dt, "%m-%d-%Y, %H:%M:%S")
29
+ return formatted_dt
30
+
31
+
32
+ def render_pipeline(payload: Dict[str, Any], history: bool = False) -> Text:
15
33
  """Renders a pipeline to rich.Text().
16
34
 
17
35
  Parameters
18
36
  ----------
19
37
  payload : Dict[str, Any]
20
38
  Pipeline payload.
39
+ history : bool
40
+ If history field needs to be rendered.
21
41
 
22
42
  Returns
23
43
  -------
@@ -25,19 +45,31 @@ def render_pipeline(payload: Dict[str, Any]) -> Text:
25
45
  Rendered text.
26
46
  """
27
47
  steps_field = "steps"
48
+ history_field = "history"
28
49
  time_fields = ["creation", "start", "stop"]
29
50
  text = Text()
30
51
  for k, v in payload.items():
31
- key_value_text = Text()
52
+ if k == "history" and not history:
53
+ continue
32
54
  if not v:
33
55
  continue
56
+ key_value_text = Text()
34
57
  if k in time_fields and v:
35
- v = dt.datetime.fromtimestamp(v)
58
+ v = render_timestamp(float(v))
36
59
  if k == steps_field:
37
60
  key_value_text = Text(f"{k}: \n", style="bright_blue")
38
61
  for step in v:
39
62
  key_value_text.append(f" {step['name']}:")
40
63
  key_value_text.append(f"{status_symbols[step['status']]}\n")
64
+ elif k == history_field:
65
+ key_value_text = Text(f"{k}: \n", style="bright_blue")
66
+ for timestamp in v.keys():
67
+ rendered = render_timestamp(float(timestamp))
68
+ key_value_text.append(f" {rendered}:\n", style="bright_green")
69
+ for execution in v[timestamp].keys():
70
+ key_value_text.append(f"{' ' * 4}{execution}:\n")
71
+ for work in v[timestamp][execution]:
72
+ key_value_text.append(f"{' ' * 6}{work}\n", style="white")
41
73
  else:
42
74
  key_value_text = Text(f"{k}: ", style="bright_blue")
43
75
  key_value_text.append(
@@ -64,6 +96,7 @@ def render_config(http: HTTPContext, payload: Dict[str, Any]) -> Text:
64
96
  """
65
97
  text = Text()
66
98
  hidden_keys = ["yaml", "services", "name"]
99
+ time_fields = ["creation", "start", "stop"]
67
100
  query = json_dumps({"id": {"$in": payload["pipelines"]}})
68
101
  projection = json_dumps({"id": 1, "status": 1})
69
102
  pipelines_statuses = http.pipelines.get_pipelines(
@@ -76,6 +109,8 @@ def render_config(http: HTTPContext, payload: Dict[str, Any]) -> Text:
76
109
  if k in hidden_keys:
77
110
  continue
78
111
  key_value_text = Text()
112
+ if k in time_fields and v:
113
+ v = render_timestamp(float(v))
79
114
  if k == "pipelines":
80
115
  key_value_text.append(f"{k}: \n", style="bright_blue")
81
116
  for status in pipelines_statuses:
File without changes