cycl 0.2.1__tar.gz → 0.2.7__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 (45) hide show
  1. {cycl-0.2.1 → cycl-0.2.7}/PKG-INFO +33 -27
  2. cycl-0.2.7/README.md +24 -0
  3. {cycl-0.2.1 → cycl-0.2.7}/pyproject.toml +56 -11
  4. cycl-0.2.7/src/cycl/__init__.py +8 -0
  5. cycl-0.2.7/src/cycl/cli.py +128 -0
  6. cycl-0.2.7/src/cycl/cycl.py +74 -0
  7. cycl-0.2.7/src/cycl/models/export_data.py +162 -0
  8. {cycl-0.2.1 → cycl-0.2.7}/src/cycl/utils/cdk.py +15 -11
  9. {cycl-0.2.1 → cycl-0.2.7}/src/cycl/utils/testing.py +1 -1
  10. {cycl-0.2.1 → cycl-0.2.7}/src/cycl.egg-info/PKG-INFO +33 -27
  11. cycl-0.2.7/src/cycl.egg-info/SOURCES.txt +20 -0
  12. cycl-0.2.7/src/cycl.egg-info/requires.txt +23 -0
  13. cycl-0.2.1/.github/dependabot.yml +0 -11
  14. cycl-0.2.1/.github/workflows/ci.yml +0 -34
  15. cycl-0.2.1/.github/workflows/release.yml +0 -37
  16. cycl-0.2.1/.gitignore +0 -183
  17. cycl-0.2.1/Makefile +0 -41
  18. cycl-0.2.1/README.md +0 -38
  19. cycl-0.2.1/TODO.md +0 -21
  20. cycl-0.2.1/requirements-build.txt +0 -2
  21. cycl-0.2.1/requirements-dev.txt +0 -8
  22. cycl-0.2.1/requirements.txt +0 -2
  23. cycl-0.2.1/src/cycl/__init__.py +0 -6
  24. cycl-0.2.1/src/cycl/cli.py +0 -72
  25. cycl-0.2.1/src/cycl/cycl.py +0 -66
  26. cycl-0.2.1/src/cycl/utils/cfn.py +0 -57
  27. cycl-0.2.1/src/cycl.egg-info/SOURCES.txt +0 -36
  28. cycl-0.2.1/src/cycl.egg-info/requires.txt +0 -2
  29. cycl-0.2.1/tests/cli_test.py +0 -176
  30. cycl-0.2.1/tests/cycl_test.py +0 -445
  31. cycl-0.2.1/tests/utils/__init__.py +0 -0
  32. cycl-0.2.1/tests/utils/cdk_test.py +0 -208
  33. cycl-0.2.1/tests/utils/cfn_test.py +0 -171
  34. cycl-0.2.1/tests/utils/log_config_test.py +0 -17
  35. cycl-0.2.1/tests/utils/testing_test.py +0 -20
  36. {cycl-0.2.1 → cycl-0.2.7}/LICENSE +0 -0
  37. {cycl-0.2.1 → cycl-0.2.7}/setup.cfg +0 -0
  38. {cycl-0.2.1 → cycl-0.2.7}/src/cycl/__main__.py +0 -0
  39. {cycl-0.2.1/src/cycl/utils → cycl-0.2.7/src/cycl/models}/__init__.py +0 -0
  40. {cycl-0.2.1 → cycl-0.2.7}/src/cycl/py.typed +0 -0
  41. {cycl-0.2.1/tests → cycl-0.2.7/src/cycl/utils}/__init__.py +0 -0
  42. {cycl-0.2.1 → cycl-0.2.7}/src/cycl/utils/log_config.py +0 -0
  43. {cycl-0.2.1 → cycl-0.2.7}/src/cycl.egg-info/dependency_links.txt +0 -0
  44. {cycl-0.2.1 → cycl-0.2.7}/src/cycl.egg-info/entry_points.txt +0 -0
  45. {cycl-0.2.1 → cycl-0.2.7}/src/cycl.egg-info/top_level.txt +0 -0
@@ -1,11 +1,12 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: cycl
3
- Version: 0.2.1
3
+ Version: 0.2.7
4
4
  Summary: CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region.
5
+ License: MIT
5
6
  Project-URL: Repository, http://github.com/tcm5343/cycl
7
+ Project-URL: Documentation, https://tcm5343.github.io/cycl/index.html
6
8
  Keywords: aws,cdk,cycle,circular,dependency,infrastructure,boto3,cloud
7
9
  Classifier: Intended Audience :: Developers
8
- Classifier: License :: OSI Approved :: MIT License
9
10
  Classifier: Natural Language :: English
10
11
  Classifier: Programming Language :: Python :: 3.10
11
12
  Classifier: Programming Language :: Python :: 3.11
@@ -15,11 +16,30 @@ Classifier: Programming Language :: Python :: 3.9
15
16
  Classifier: Programming Language :: Python :: 3
16
17
  Classifier: Programming Language :: Python
17
18
  Classifier: Topic :: Software Development
18
- Requires-Python: >=3.8
19
+ Requires-Python: >=3.9
19
20
  Description-Content-Type: text/markdown
20
21
  License-File: LICENSE
21
22
  Requires-Dist: boto3~=1.0
22
23
  Requires-Dist: networkx~=3.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: boto3-stubs[essential]==1.37.13; extra == "dev"
26
+ Requires-Dist: mypy==1.15.0; extra == "dev"
27
+ Requires-Dist: pytest-cov==6.0.0; extra == "dev"
28
+ Requires-Dist: pytest-subtests==0.14.1; extra == "dev"
29
+ Requires-Dist: pytest-sugar==1.0.0; extra == "dev"
30
+ Requires-Dist: pytest==8.3.4; extra == "dev"
31
+ Requires-Dist: ruff==0.9.9; extra == "dev"
32
+ Requires-Dist: types-networkx==3.4.2.20250312; extra == "dev"
33
+ Provides-Extra: doc
34
+ Requires-Dist: myst-parser==4.0.1; extra == "doc"
35
+ Requires-Dist: sphinx_rtd_theme==3.0.2; extra == "doc"
36
+ Requires-Dist: sphinx-argparse==0.5.2; extra == "doc"
37
+ Requires-Dist: sphinx-autobuild==2024.10.3; extra == "doc"
38
+ Requires-Dist: sphinx==8.1.3; extra == "doc"
39
+ Provides-Extra: dist
40
+ Requires-Dist: build==1.2.2.post1; extra == "dist"
41
+ Requires-Dist: twine==6.1.0; extra == "dist"
42
+ Dynamic: license-file
23
43
 
24
44
  # cycl
25
45
 
@@ -28,34 +48,20 @@ Requires-Dist: networkx~=3.0
28
48
  [![PyPI Supported Python Versions](https://img.shields.io/pypi/pyversions/cycl.svg)](https://pypi.python.org/pypi/cycl/)
29
49
  [![Build Status](https://github.com/tcm5343/cycl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tcm5343/cycl/actions)
30
50
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
51
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v0.json)](https://github.com/charliermarsh/ruff)
52
+ ![Checked with mypy](https://img.shields.io/badge/mypy-checked-blue)
31
53
 
32
- cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin.
54
+ cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin (ECE 382C: Software Testing).
33
55
 
34
- ## Getting started
56
+ ## Documentation
35
57
 
36
- It is recommended to use `pipx` to install `cycl` but you can also use `pip` by simply running `pip install cycl`.
37
-
38
- ### CLI
39
-
40
- - `cycl check --exit-zero` - exit 0 regardless of result
41
- - `cycl check --log-level` - set the logging level (default: WARNING)
42
- - `cycl check --cdk-out /path/to/cdk.out` - path to cdk.out, where stacks are CDK synthesized to CFN templates
43
-
44
- ## How to use cycl?
45
-
46
- There are two main use cases for `cycl`.
47
-
48
- 1. In a pipeline. `cycl` is best used to detect circular dependencies before a deployment. If you're using the AWS CDK v2 (v1 support coming soon), simply synthesize you templates to a directory and pass that directory to `cycl` using `--cdk-out-path some-path-here`. This allows `cycl` to find all existing cycles and then those to be introduced by the deployment. This prevents the circular dependency from ever being introduced. If your pipeline deploys more than once, you should execute `cycl` before each deployment.
49
- 2. To perform analysis. While a CLI is best used in a pipeline, if you require analysis which is not currently supported, you can use the SDK. The SDK gives you all the information that `cycl` collects.
50
-
51
- ## Why use cycl?
52
-
53
- Over the lifetime of a project, circular references are bound to be introduced. They may not be noticed until you need to re-deploy some infrastructure. A good example is disaster recovery testing and potentially deploying all your infrastructure from scratch in a new region. This tool detects those changes.
58
+ Documentation for using `cycl` may be found [here](https://tcm5343.github.io/cycl/).
54
59
 
55
60
  ## Contributing
56
61
 
57
- `cycl` is being actively developed, instructions will come as it becomes more stable.
62
+ `cycl` is being actively developed, instructions will come as it becomes more stable. Run `make` to see the available targets and their descriptions. To run tests using `tox`, you must install `tox` and `pyenv`. A VScode dev container is coming soon.
58
63
 
59
64
  To run specific tests:
60
- `tox -e py39 -- ./tests/utils/cdk_test.py`
61
- `make test ARGS=./tests/utils/cdk_test.py`
65
+
66
+ * using tox: `tox -e py39 -- ./tests/utils/cdk_test.py`
67
+ * using pytest directly: `make test ARGS=./tests/utils/cdk_test.py`
cycl-0.2.7/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # cycl
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/cycl)](https://pypi.org/project/cycl/)
4
+ [![Downloads](https://static.pepy.tech/badge/cycl)](https://pypi.python.org/pypi/cycl/)
5
+ [![PyPI Supported Python Versions](https://img.shields.io/pypi/pyversions/cycl.svg)](https://pypi.python.org/pypi/cycl/)
6
+ [![Build Status](https://github.com/tcm5343/cycl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tcm5343/cycl/actions)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v0.json)](https://github.com/charliermarsh/ruff)
9
+ ![Checked with mypy](https://img.shields.io/badge/mypy-checked-blue)
10
+
11
+ cycl is a CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region. The successor to [circular-dependency-detector](https://github.com/tcm5343/circular-dependency-detector), which was built at the University of Texas at Austin (ECE 382C: Software Testing).
12
+
13
+ ## Documentation
14
+
15
+ Documentation for using `cycl` may be found [here](https://tcm5343.github.io/cycl/).
16
+
17
+ ## Contributing
18
+
19
+ `cycl` is being actively developed, instructions will come as it becomes more stable. Run `make` to see the available targets and their descriptions. To run tests using `tox`, you must install `tox` and `pyenv`. A VScode dev container is coming soon.
20
+
21
+ To run specific tests:
22
+
23
+ * using tox: `tox -e py39 -- ./tests/utils/cdk_test.py`
24
+ * using pytest directly: `make test ARGS=./tests/utils/cdk_test.py`
@@ -1,17 +1,20 @@
1
1
  [build-system]
2
- requires = ['setuptools>=64', 'setuptools-scm>=8']
2
+ requires = [
3
+ 'setuptools>=70',
4
+ 'wheel',
5
+ 'setuptools-git-versioning>=2.1',
6
+ ]
3
7
  build-backend = 'setuptools.build_meta'
4
8
 
5
9
  [project]
6
10
  name = 'cycl'
7
- version='0.2.1'
8
- requires-python = '>=3.8'
11
+ requires-python = '>=3.9'
9
12
  description = 'CLI and Python SDK to help identify cross-stack import/export circular dependencies, for a given AWS account and region.'
10
13
  readme = 'README.md'
14
+ license = {text = "MIT"}
11
15
  keywords = ['aws', 'cdk', 'cycle', 'circular', 'dependency', 'infrastructure', 'boto3', 'cloud']
12
16
  classifiers = [
13
17
  'Intended Audience :: Developers',
14
- 'License :: OSI Approved :: MIT License',
15
18
  'Natural Language :: English',
16
19
  'Programming Language :: Python :: 3.10',
17
20
  'Programming Language :: Python :: 3.11',
@@ -26,9 +29,37 @@ dependencies = [
26
29
  'boto3~=1.0',
27
30
  'networkx~=3.0',
28
31
  ]
32
+ dynamic = ['version']
33
+
34
+ [tool.setuptools-git-versioning]
35
+ enabled = true
36
+
37
+ [project.optional-dependencies]
38
+ dev = [
39
+ 'boto3-stubs[essential]==1.37.13',
40
+ 'mypy==1.15.0',
41
+ 'pytest-cov==6.0.0',
42
+ 'pytest-subtests==0.14.1',
43
+ 'pytest-sugar==1.0.0',
44
+ 'pytest==8.3.4',
45
+ 'ruff==0.9.9',
46
+ 'types-networkx==3.4.2.20250312',
47
+ ]
48
+ doc = [
49
+ 'myst-parser==4.0.1',
50
+ 'sphinx_rtd_theme==3.0.2',
51
+ 'sphinx-argparse==0.5.2',
52
+ 'sphinx-autobuild==2024.10.3',
53
+ 'sphinx==8.1.3',
54
+ ]
55
+ dist = [
56
+ 'build==1.2.2.post1',
57
+ 'twine==6.1.0', # not used in pipeline
58
+ ]
29
59
 
30
60
  [project.urls]
31
61
  Repository = 'http://github.com/tcm5343/cycl'
62
+ Documentation = 'https://tcm5343.github.io/cycl/index.html'
32
63
 
33
64
  [project.scripts]
34
65
  cycl = 'cycl.cli:app'
@@ -40,7 +71,14 @@ line-length = 125
40
71
  select = ['ALL']
41
72
  ignore = [
42
73
  'COM', # flake8-commas
43
- 'D', # pydocstyle
74
+ 'D100',
75
+ 'D101',
76
+ 'D102',
77
+ 'D103',
78
+ 'D104',
79
+ 'D105',
80
+ 'D106',
81
+ 'D107',
44
82
  'ERA001', # commented-out-code
45
83
  'FIX002', # line-contains-todo
46
84
  'Q000', # bad-quotes-inline-string
@@ -55,6 +93,10 @@ ignore = [
55
93
  'PLR2004', # magic-value-comparison
56
94
  'S101', # assert
57
95
  ]
96
+ 'docs/**' = [
97
+ 'INP001', # implicit-namespace-package
98
+ 'A001', # builtin-variable-shadowing
99
+ ]
58
100
  '__init__.py' = [
59
101
  'F401', # unused-import
60
102
  ]
@@ -64,6 +106,9 @@ quote-style = 'single'
64
106
  indent-style = 'space'
65
107
  docstring-code-format = true
66
108
 
109
+ [tool.ruff.lint.pydocstyle]
110
+ convention = 'google'
111
+
67
112
  [tool.coverage.run]
68
113
  branch = true
69
114
  source = ['./src']
@@ -74,7 +119,7 @@ show_missing = true
74
119
  skip_covered = true
75
120
  skip_empty = true
76
121
  exclude_lines = [
77
- "if TYPE_CHECKING:",
122
+ 'if TYPE_CHECKING:',
78
123
  ]
79
124
  omit = [
80
125
  '__*__.py',
@@ -85,14 +130,14 @@ log_cli_level = 'INFO'
85
130
  addopts = ['--import-mode=importlib']
86
131
 
87
132
  [tool.tox]
88
- env_list = ["py39", "py310", "py311", "py312", "py313"]
133
+ env_list = ['py39', 'py310', 'py311', 'py312', 'py313']
89
134
  skip_missing_interpreters = false
90
135
 
91
136
  [tool.tox.env_run_base]
92
137
  allowlist_externals = ['make']
93
- package = "editable"
94
- deps = '-rrequirements-dev.txt'
138
+ package = 'editable'
139
+ deps = ['.[dev]']
95
140
  commands = [
96
- ["make", "validate"],
97
- ["make", "test", "ARGS={posargs}"]
141
+ ['make', 'validate'],
142
+ ['make', 'test', 'ARGS={posargs}']
98
143
  ]
@@ -0,0 +1,8 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .cycl import build_graph, get_graph_data
4
+
5
+ try:
6
+ __version__ = version('cycl')
7
+ except PackageNotFoundError:
8
+ __version__ = 'v?'
@@ -0,0 +1,128 @@
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import pathlib
5
+ import sys
6
+ from logging import getLogger
7
+
8
+ import networkx as nx
9
+
10
+ from cycl import build_graph
11
+ from cycl.utils.log_config import configure_log
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ # def get_node_key_function(node_key: str, missing_tag: str = 'ignore') -> Callable[[ExportData], str]:
17
+ # if node_key.startswith("tag:"):
18
+ # tag_name = node_key.split(":", 1)[1]
19
+
20
+ # if missing_tag == 'error':
21
+ # return lambda x: x.tags[tag_name] # strict mode
22
+
23
+ # default_value = f"Unknown-{tag_name}" if missing_tag == 'default' else x.stack_name
24
+ # return lambda x: x.tags.get(tag_name, default_value)
25
+
26
+ # node_key_map = {
27
+ # 'stack_name': lambda x: x.stack_name,
28
+ # 'export_name': lambda x: x.export_name or 'NoExport',
29
+ # 'parent_id': lambda x: x.parent_id or 'NoParent',
30
+ # }
31
+
32
+ # return node_key_map.get(node_key, lambda x: x.stack_name)
33
+
34
+
35
+ def create_parser() -> argparse.ArgumentParser:
36
+ parser = argparse.ArgumentParser(prog='cycl', description='Check circular dependencies between imports and exports.')
37
+ sp = parser.add_subparsers(dest='cmd', required=True)
38
+
39
+ check_p = sp.add_parser('check', help='Check for cycles between AWS stack imports and exports.')
40
+ check_p.add_argument('--exit-zero', action='store_true', help='Exit zero regardless of cyclic chekc result.')
41
+
42
+ topo_p = sp.add_parser('topo', help='Find topological generations, if dependencies are acyclic')
43
+
44
+ # global options
45
+ for p in [check_p, topo_p]:
46
+ p.add_argument(
47
+ '--log-level',
48
+ choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
49
+ default='INFO',
50
+ help='Sets the logging level.',
51
+ )
52
+ p.add_argument(
53
+ '--cdk-out',
54
+ type=pathlib.Path,
55
+ help='EXPERIMENTAL : Path to cdk.out/, where the cdk synthesizes the cloud assembly output.',
56
+ )
57
+ p.add_argument(
58
+ '--ignore-nodes',
59
+ nargs='+',
60
+ default=[],
61
+ type=str,
62
+ help=(
63
+ "List of nodes to to ignore when building the graph. Don't repeat ``--ignore-nodes`` if you "
64
+ 'have multiple nodes (ex. ``--ignore-nodes v1 v2``).'
65
+ ),
66
+ )
67
+ p.add_argument(
68
+ '--ignore-edge',
69
+ nargs=2,
70
+ default=[],
71
+ action='append',
72
+ metavar=('u', 'v'),
73
+ help=(
74
+ 'Specify an edge to ignore by providing two nodes delimited by a space. ``--ignore-edge u v`` must be '
75
+ 'repeated for each edge provided.'
76
+ ),
77
+ )
78
+ # p.add_argument( # TODO
79
+ # '--node-key',
80
+ # type=str,
81
+ # choices=['stack_name', 'export_name', 'parent_id', 'tag:Environment'],
82
+ # default='stack_name',
83
+ # help='Specify which ExportData attribute to use as the graph node identifier.'
84
+ # )
85
+ # parser.add_argument(
86
+ # '--missing-tag',
87
+ # choices=['ignore', 'error', 'default'],
88
+ # default='ignore',
89
+ # help='How to handle missing tags: "ignore" (fallback to stack name), "error" (raise),
90
+ # or "default" (custom value).'
91
+ # )
92
+ return parser
93
+
94
+
95
+ def app() -> None:
96
+ parser = create_parser()
97
+
98
+ if len(sys.argv) == 1:
99
+ parser.print_help()
100
+ sys.exit(0)
101
+
102
+ args = parser.parse_args()
103
+ configure_log(getattr(logging, args.log_level))
104
+
105
+ dep_graph = build_graph(
106
+ cdk_out_path=args.cdk_out,
107
+ nodes_to_ignore=args.ignore_nodes,
108
+ edges_to_ignore=args.ignore_edge,
109
+ )
110
+
111
+ cycles = list(nx.simple_cycles(dep_graph))
112
+ for cycle in cycles:
113
+ print(f'cycle found between nodes: {cycle}')
114
+
115
+ if args.cmd == 'check':
116
+ if cycles and not args.exit_zero:
117
+ sys.exit(1)
118
+ elif args.cmd == 'topo':
119
+ if cycles:
120
+ log.error('graph is cyclic, topological generations can only be computed on an acyclic graph')
121
+ sys.exit(1)
122
+ generations = [sorted(generation) for generation in nx.topological_generations(dep_graph)]
123
+ print(json.dumps(generations, indent=2))
124
+ sys.exit(0)
125
+
126
+
127
+ if __name__ == '__main__':
128
+ app()
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ from logging import getLogger
4
+ from pathlib import Path
5
+
6
+ import boto3
7
+ import networkx as nx
8
+ from botocore.config import Config
9
+
10
+ from cycl.models.export_data import ExportData
11
+ from cycl.utils.cdk import get_exports_from_assembly
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ def get_graph_data(cdk_out_path: Path | None = None) -> dict[str, ExportData]:
17
+ cdk_out_imports: dict[str, list[ExportData]] = get_exports_from_assembly(Path(cdk_out_path)) if cdk_out_path else {}
18
+ log.info('cdk_out_imports: %s', cdk_out_imports)
19
+
20
+ boto_config = Config(retries={'max_attempts': 10, 'mode': 'adaptive'})
21
+ cfn_client = boto3.client('cloudformation', config=boto_config)
22
+
23
+ log.info('getting all exports')
24
+ exports = ExportData.get_all_exports(cfn_client=cfn_client)
25
+ for export_name, importing_stacks in cdk_out_imports.items():
26
+ if export_name not in exports:
27
+ log.warning(
28
+ 'found an export (%s) which has not been deployed yet about to be imported stack(s): (%s)',
29
+ export_name,
30
+ importing_stacks,
31
+ )
32
+
33
+ log.info('getting imports for %s exports', len(exports))
34
+ for export in exports.values():
35
+ if export.export_name: # TODO: i think this is a given, maybe enforce at object level, add unit test
36
+ export.get_all_imports(cfn_client=cfn_client)
37
+ export.importing_stacks += cdk_out_imports.get(export.export_name, []) # TODO: should we convert to method?
38
+ if len(export.importing_stacks) == 0:
39
+ log.warning('Export found with no import: %s from %s', export.export_name, export.stack_name)
40
+ return exports
41
+
42
+
43
+ def build_graph(
44
+ graph_data: dict[str, ExportData] | None = None,
45
+ cdk_out_path: Path | None = None,
46
+ # node_key: Callable[[ExportData], str] = lambda x: x.stack_name,
47
+ nodes_to_ignore: list[str] | None = None,
48
+ edges_to_ignore: list[list[str]] | None = None,
49
+ ) -> nx.MultiDiGraph:
50
+ nodes_to_ignore = nodes_to_ignore or []
51
+ edges_to_ignore = edges_to_ignore or []
52
+ graph_data = get_graph_data(cdk_out_path) if graph_data is None else graph_data
53
+
54
+ log.info('building dependency graph from graph data')
55
+ dep_graph: nx.MultiDiGraph = nx.MultiDiGraph()
56
+ for export in graph_data.values():
57
+ # export_key = node_key(export)
58
+ if export.stack_name in nodes_to_ignore:
59
+ continue
60
+
61
+ edges = []
62
+ for importing_stack in export.importing_stacks:
63
+ # importing_key = node_key(importing_stack)
64
+ if importing_stack.stack_name not in nodes_to_ignore:
65
+ edge = (export.stack_name, importing_stack.stack_name)
66
+ if list(edge) not in edges_to_ignore:
67
+ edges.append(edge)
68
+
69
+ if edges:
70
+ dep_graph.add_edges_from(ebunch_to_add=edges)
71
+ else:
72
+ # export key
73
+ dep_graph.add_node(export.stack_name)
74
+ return dep_graph
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+
3
+ from logging import getLogger
4
+ from typing import TYPE_CHECKING
5
+
6
+ import boto3
7
+ from botocore.exceptions import ClientError
8
+
9
+ if TYPE_CHECKING:
10
+ from mypy_boto3_cloudformation import CloudFormationClient
11
+ from mypy_boto3_cloudformation.type_defs import ListExportsOutputTypeDef
12
+
13
+ log = getLogger(__name__)
14
+
15
+
16
+ class ExportData:
17
+ def __init__(
18
+ self,
19
+ stack_name: str,
20
+ stack_id: str | None = None,
21
+ export_name: str | None = None,
22
+ export_value: str | None = None,
23
+ # parent_id: str | None = None,
24
+ # root_id: str | None = None,
25
+ # tags: dict[str, str] | None = None,
26
+ # outputs: list[str] | None = None,
27
+ importing_stacks: list[ExportData] | None = None,
28
+ ) -> None:
29
+ self.stack_name = stack_name
30
+ self.stack_id = stack_id
31
+ self.export_name = export_name
32
+ self.export_value = export_value
33
+ # self.parent_id = parent_id
34
+ # self.root_id = root_id
35
+ # self.tags = tags
36
+ # self.outputs = outputs or []
37
+ self.importing_stacks = importing_stacks or []
38
+
39
+ @classmethod
40
+ def from_list_exports(cls, list_exports_resp: ListExportsOutputTypeDef) -> dict[str, ExportData]:
41
+ """Convert an AWS CloudFormation list exports response into a dictionary of export name to ExportData instances.
42
+
43
+ Args:
44
+ list_exports_resp: A dictionary representing the list exports response,
45
+ where each entry contains export details with keys:
46
+ - 'ExportingStackId': The ID of the stack exporting the value.
47
+ - 'Name': The name of the export.
48
+ - 'Value': The exported value.
49
+
50
+ Returns:
51
+ A dictionary mapping export names to ExportData instances,
52
+ where each ExportData object contains information about the corresponding export.
53
+ """
54
+ return {
55
+ export['Name']: cls(
56
+ stack_name=cls.parse_name_from_id(export['ExportingStackId']),
57
+ stack_id=export['ExportingStackId'],
58
+ export_name=export['Name'],
59
+ export_value=export['Value'],
60
+ )
61
+ for export in list_exports_resp['Exports']
62
+ }
63
+
64
+ @classmethod
65
+ def get_all_exports(cls, cfn_client: CloudFormationClient | None = None) -> dict[str, ExportData]:
66
+ """Retrieve all AWS CloudFormation exports and return them as a dictionary of export name to ExportData instances.
67
+
68
+ Args:
69
+ cfn_client: A Boto3 CloudFormation client instance.
70
+ If not provided, a new client will be created.
71
+
72
+ Returns:
73
+ A dictionary mapping export names to ExportData instances,
74
+ where each ExportData object contains details about the corresponding export.
75
+
76
+ Note:
77
+ This function paginates through the AWS CloudFormation `list_exports` API to retrieve all exports.
78
+ """
79
+ cfn_client = cfn_client or boto3.client('cloudformation')
80
+
81
+ exports: dict[str, ExportData] = {}
82
+ resp = cfn_client.list_exports()
83
+ log.debug(resp)
84
+ exports.update(ExportData.from_list_exports(resp))
85
+ while token := resp.get('NextToken'):
86
+ resp = cfn_client.list_exports(NextToken=token)
87
+ log.debug(resp)
88
+ exports.update(ExportData.from_list_exports(resp))
89
+ log.debug(exports)
90
+ return exports
91
+
92
+ def __eq__(self, other: object) -> bool:
93
+ if not isinstance(other, ExportData):
94
+ return False
95
+ return vars(self) == vars(other)
96
+
97
+ def __hash__(self) -> int:
98
+ return hash(tuple((key, tuple(value) if isinstance(value, list) else value) for key, value in vars(self).items()))
99
+
100
+ def __repr__(self) -> str:
101
+ return f'ExportData(stack_name={self.stack_name!r}, export_name={self.export_name!r})'
102
+
103
+ def get_all_imports(self, cfn_client: CloudFormationClient | None = None) -> ExportData:
104
+ """Retrieve all stacks that import the current export and update the importing_stacks attribute.
105
+
106
+ Args:
107
+ cfn_client: A Boto3 CloudFormation client instance. If not provided, a new client will be created.
108
+
109
+ Returns:
110
+ The updated instance with importing stacks added to the `importing_stacks` attribute.
111
+
112
+ Note:
113
+ This function paginates through the AWS CloudFormation `list_imports` API to retrieve all importing stacks.
114
+ If the export is not imported by any stack, it logs a debug message instead of raising an error.
115
+ """
116
+ if self.export_name:
117
+ cfn_client = cfn_client or boto3.client('cloudformation')
118
+
119
+ try:
120
+ resp = cfn_client.list_imports(ExportName=self.export_name)
121
+ log.debug(resp)
122
+ self.importing_stacks.extend(
123
+ [ExportData(stack_name=importing_stack_name) for importing_stack_name in resp['Imports']]
124
+ )
125
+ while token := resp.get('NextToken'):
126
+ resp = cfn_client.list_imports(ExportName=self.export_name, NextToken=token)
127
+ log.debug(resp)
128
+ self.importing_stacks.extend(
129
+ [ExportData(stack_name=importing_stack_name) for importing_stack_name in resp['Imports']]
130
+ )
131
+ except ClientError as err:
132
+ if 'is not imported by any stack' not in repr(err):
133
+ raise
134
+ log.debug('') # TODO: refine msg
135
+ log.debug(self.importing_stacks)
136
+ else:
137
+ warning_msg = (
138
+ f'export_name not defined for {type(self).__name__}, which probably means {self.stack_name} '
139
+ 'imports an export but does not export any'
140
+ )
141
+ log.warning(warning_msg)
142
+ return self
143
+
144
+ @staticmethod
145
+ def parse_name_from_id(stack_id: str) -> str:
146
+ """Extract the stack name from a given stack ID.
147
+
148
+ Args:
149
+ stack_id: The full stack ID, typically in the format
150
+ 'arn:aws:cloudformation:region:account-id:stack/stack-name/guid'.
151
+
152
+ Returns:
153
+ The extracted stack name, or an empty string if parsing fails.
154
+
155
+ Note:
156
+ Logs a warning if the stack ID format is unexpected.
157
+ """
158
+ try:
159
+ return stack_id.split('/')[1]
160
+ except IndexError:
161
+ log.warning('Unable to parse name from stack_id: %s', stack_id)
162
+ return ''