upgrade-assurance-cli 1.0.1__py3-none-any.whl

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.
@@ -0,0 +1,8 @@
1
+ # my_package/__init__.py
2
+ from importlib.metadata import version as get_version
3
+ from importlib.metadata import PackageNotFoundError
4
+
5
+ try:
6
+ __version__ = get_version("upgrade-assurance-cli")
7
+ except PackageNotFoundError:
8
+ __version__ = "dev-or-unknown"
File without changes
@@ -0,0 +1,107 @@
1
+ import multiprocessing
2
+ import pathlib
3
+ import enum
4
+ from xml.etree.ElementTree import tostring
5
+
6
+ import requests
7
+ from panos.firewall import Firewall
8
+
9
+ from upgrade_assurance_cli.cli.runner import (
10
+ get_firewall_proxy_from_args,
11
+ setup_logger_for_runners,
12
+ )
13
+ from upgrade_assurance_cli.cli.utils import log
14
+
15
+
16
+ class BackupTypeEnum(str, enum.Enum):
17
+ configuration = "configuration"
18
+ device_state = "device-state"
19
+
20
+
21
+ class ExporterArguments:
22
+ def __init__(
23
+ self,
24
+ username,
25
+ password,
26
+ hostname,
27
+ output_file,
28
+ export_type=BackupTypeEnum.configuration,
29
+ ):
30
+ self.output_file = output_file
31
+ self.username = username
32
+ self.password = password
33
+ self.hostname = hostname
34
+ self.export_type = export_type
35
+
36
+ @property
37
+ def device_str(self):
38
+ return f"{self.hostname}".replace(":", "-")
39
+
40
+
41
+ def get_device_state(firewall: Firewall, verify: bool = False):
42
+ """Patch variation of the device state command as does not seem to work within XAPI"""
43
+ url = f"https://{firewall.hostname}:{firewall.port}/api"
44
+ params = {
45
+ "type": "export",
46
+ "category": "device-state",
47
+ }
48
+ if firewall.serial:
49
+ panorama = firewall.panorama()
50
+ api_key = panorama.api_key
51
+ url = f"https://{panorama.hostname}:{firewall.port}/api"
52
+ params["device"] = firewall.serial
53
+ else:
54
+ api_key = firewall.api_key
55
+
56
+ params = {
57
+ "key": api_key,
58
+ "type": "export",
59
+ "category": "device-state",
60
+ }
61
+
62
+ return requests.post(url, params=params, verify=verify)
63
+
64
+
65
+ def export_config(exec_arguments: ExporterArguments):
66
+ """Exports teh device configuration from the firewall.
67
+
68
+ This supports running-configuration and device-state exports.
69
+ """
70
+ firewall = get_firewall_proxy_from_args(
71
+ exec_arguments.username,
72
+ exec_arguments.password,
73
+ exec_arguments.hostname,
74
+ )
75
+ file_log = setup_logger_for_runners(exec_arguments.device_str)
76
+ file_log.info(
77
+ f"Exporting {exec_arguments.export_type.value} for {exec_arguments.device_str}"
78
+ )
79
+ write_bytes = b""
80
+ if exec_arguments.export_type == BackupTypeEnum.device_state:
81
+ result = get_device_state(firewall._fw, verify=False)
82
+ output_file = str(pathlib.Path(exec_arguments.output_file)) + ".tgz"
83
+ write_bytes = result.content
84
+
85
+ elif exec_arguments.export_type == BackupTypeEnum.configuration:
86
+ result = firewall._fw.xapi.export(category=exec_arguments.export_type.value)
87
+ output_file = str(pathlib.Path(exec_arguments.output_file)) + ".xml"
88
+ write_bytes = tostring(result)
89
+
90
+ if not write_bytes:
91
+ log.critical(
92
+ f"Could not export {exec_arguments.export_type.value} from device."
93
+ )
94
+ return
95
+
96
+ file_log.info(f"Saving config to {output_file}")
97
+
98
+ with open(output_file, "wb") as file:
99
+ file.write(write_bytes)
100
+
101
+
102
+ def pooled_take_config_backup(exec_args: list[ExporterArguments], parallel: int = 4):
103
+ log.info(f"Exporting configuration using multiprocessing ({parallel})")
104
+ with multiprocessing.Pool(parallel) as pool:
105
+ pool.map(export_config, exec_args)
106
+
107
+ log.info(f"Exports complete.")
@@ -0,0 +1,344 @@
1
+ import enum
2
+ import datetime
3
+ import json
4
+ import pathlib
5
+ import os
6
+ from typing import Annotated
7
+
8
+ from panos_upgrade_assurance.check_firewall import CheckFirewall
9
+ from panos_upgrade_assurance.exceptions import SnapshotNoneComparisonException
10
+ from panos_upgrade_assurance.snapshot_compare import SnapshotCompare
11
+ from panos_upgrade_assurance.utils import ConfigParser
12
+ from typer import Typer, Argument, Option
13
+ from rich import print, table
14
+
15
+ from upgrade_assurance_cli.cli.exporter import (
16
+ ExporterArguments,
17
+ pooled_take_config_backup,
18
+ BackupTypeEnum,
19
+ )
20
+ from upgrade_assurance_cli.cli.report import (
21
+ generate_reports_from_store,
22
+ details_from_filename,
23
+ read_snapshot_report,
24
+ get_snapshot_data_report,
25
+ )
26
+ from upgrade_assurance_cli.cli.runner import (
27
+ pooled_run_readiness_checks_on_devices,
28
+ CheckExecutionArgs,
29
+ pooled_run_snapshot_checks_on_devices,
30
+ )
31
+ from upgrade_assurance_cli.cli.utils import (
32
+ log,
33
+ load_config,
34
+ parse_file_to_devices,
35
+ ENCODING,
36
+ TestConfigs,
37
+ )
38
+
39
+ SHORT_HELP_TEXT = """PAN-OS Upgrade Assurance CLI"""
40
+
41
+ HELP_TEXT = f"""{SHORT_HELP_TEXT}
42
+
43
+ Provides access to the readiness and snapshot comparison tests via a handy CLI interface.
44
+ """
45
+
46
+ app = Typer(help=HELP_TEXT, short_help=SHORT_HELP_TEXT)
47
+
48
+ DEVICE_ARGUMENT = Annotated[
49
+ list[str],
50
+ Argument(
51
+ help="Device IP or FQDN. If using Panorama to proxy commands, specify in the format <panorama_ip>:<serial>. "
52
+ "Multiple are supported at the command line. "
53
+ "Alternatively, a path to a file containing a list of devices - one per line - may be passed.",
54
+ ),
55
+ ]
56
+ USERNAME_OPTION = Annotated[
57
+ str, Option(help="Username", envvar="UA_USERNAME", prompt="username")
58
+ ]
59
+ PASSWORD_OPTION = Annotated[
60
+ str,
61
+ Option(
62
+ envvar="UA_PASSWORD",
63
+ help="Password",
64
+ prompt="password",
65
+ hide_input=True,
66
+ ),
67
+ ]
68
+ CONFIG_OPTION = Annotated[
69
+ pathlib.Path,
70
+ Option(
71
+ help="Path To Configuration file",
72
+ ),
73
+ ]
74
+
75
+
76
+ class LogLevelEnum(enum.Enum):
77
+ DEBUG = "DEBUG"
78
+ INFO = "INFO"
79
+
80
+
81
+ @app.callback()
82
+ def setup(log_level: Annotated[LogLevelEnum, Option()] = LogLevelEnum.INFO):
83
+ log.setLevel(level=log_level.value)
84
+ log.debug("Debug logging enabled")
85
+ log.info("Informational logging enabled")
86
+
87
+
88
+ class FormatEnum(str, enum.Enum):
89
+ cli_table = "cli_table"
90
+
91
+
92
+ @app.command()
93
+ def report(
94
+ result_store_path: Annotated[
95
+ pathlib.Path, Option(help="Location of the results")
96
+ ] = "store",
97
+ format: Annotated[
98
+ FormatEnum, Option(help="Format for the report")
99
+ ] = FormatEnum.cli_table,
100
+ device: Annotated[
101
+ str, Option(help="Device string for single device report")
102
+ ] = None,
103
+ ):
104
+ """Read all the check results and generate a report.
105
+
106
+ This command enumerates all the reports in the store and returns a report of all the results, including a timestamp,
107
+ to the CLI.
108
+
109
+ Alternatively, you can pass a device string in the same format
110
+ """
111
+ reports = generate_reports_from_store(result_store_path)
112
+
113
+ if format == FormatEnum.cli_table:
114
+ if device:
115
+ print(reports.device_readiness_report_as_rich_table(device))
116
+ print(reports.device_snapshot_report_as_rich_table(device))
117
+ else:
118
+ print(reports.counts_as_rich_table())
119
+ print(reports.pass_or_fail_as_rich_string())
120
+
121
+
122
+ def get_devices_from_argument(device: list[str]):
123
+ device_list = []
124
+ for d in device:
125
+ if pathlib.Path(d).is_file():
126
+ device_list += parse_file_to_devices(pathlib.Path(d))
127
+ else:
128
+ device_list.append(d)
129
+
130
+ return device_list
131
+
132
+
133
+ @app.command()
134
+ def readiness(
135
+ username: USERNAME_OPTION,
136
+ password: PASSWORD_OPTION,
137
+ device: DEVICE_ARGUMENT,
138
+ result_store_path: Annotated[
139
+ pathlib.Path, Option(help="Path to store the results")
140
+ ] = "store",
141
+ config_path: CONFIG_OPTION = None,
142
+ parallel: Annotated[
143
+ int, Option(help="Number of concurrent connections to make")
144
+ ] = 2,
145
+ ):
146
+ """Runs the 'readiness' or pre-check upgrade commands
147
+
148
+ This command will generate a consolidated report and print it to the console. For more complex reporting behavior,
149
+ use the `report` command.
150
+ """
151
+ check_config = load_config(config_path).pre_checks
152
+
153
+ device_list = get_devices_from_argument(device)
154
+
155
+ os.makedirs(result_store_path, exist_ok=True)
156
+ timestamp = int(datetime.datetime.now(tz=datetime.UTC).timestamp())
157
+ log.info(f"Starting readiness check process on {len(device_list)} devices")
158
+ exec_args = [
159
+ CheckExecutionArgs(
160
+ username=username,
161
+ password=password,
162
+ hostname=d,
163
+ check_configuration=check_config,
164
+ output_file=result_store_path.joinpath(
165
+ f"readiness_{d}_{timestamp}.json".replace(":", "-")
166
+ ),
167
+ )
168
+ for d in device_list
169
+ ]
170
+ pooled_run_readiness_checks_on_devices(exec_args, parallel=parallel)
171
+ reports = generate_reports_from_store(result_store_path)
172
+ if len(device_list) == 1:
173
+ log.info("Only one device was provided - displaying latest results only")
174
+ print(reports.device_readiness_report_as_rich_table(device_list[0]))
175
+ return
176
+
177
+ print(reports.counts_as_rich_table())
178
+
179
+
180
+ @app.command()
181
+ def snapshot(
182
+ username: USERNAME_OPTION,
183
+ password: PASSWORD_OPTION,
184
+ device: DEVICE_ARGUMENT,
185
+ snapshot_store_path: Annotated[
186
+ pathlib.Path, Option(help="Path to store the snapshot reports")
187
+ ] = "snapshots",
188
+ config_path: CONFIG_OPTION = None,
189
+ parallel: Annotated[
190
+ int, Option(help="Number of concurrent connections to make")
191
+ ] = 2,
192
+ ):
193
+ """Takes an operational snapshot of the given devices.
194
+
195
+ For each device passed, a snapshot will be taken and saved in the passed snapshot store. This can be then used to
196
+ compare with subsequent snapshots. This command does NOT run any tests, it just pulls the data for later
197
+ processing.
198
+ """
199
+ check_config = load_config(config_path).snapshot_config
200
+
201
+ os.makedirs(snapshot_store_path, exist_ok=True)
202
+
203
+ device_list = get_devices_from_argument(device)
204
+ timestamp = int(datetime.datetime.now(tz=datetime.UTC).timestamp())
205
+
206
+ exec_args = [
207
+ CheckExecutionArgs(
208
+ username=username,
209
+ password=password,
210
+ hostname=d,
211
+ check_configuration=check_config,
212
+ output_file=snapshot_store_path.joinpath(
213
+ f"snapshot_{d}_{timestamp}.json".replace(":", "-")
214
+ ),
215
+ )
216
+ for d in device_list
217
+ ]
218
+ pooled_run_snapshot_checks_on_devices(exec_args, parallel=parallel)
219
+ log.info(
220
+ f"snapshot process has finished. {len(exec_args)} snapshots saved to {snapshot_store_path}."
221
+ )
222
+ if len(exec_args) == 1:
223
+ print(get_snapshot_data_report(exec_args[0].output_file).data_as_rich_table())
224
+
225
+
226
+ @app.command()
227
+ def compare_snapshots(
228
+ left: Annotated[pathlib.Path, Argument(help="First snapshot")],
229
+ right: Annotated[pathlib.Path, Argument(help="Second snapshot")],
230
+ config_path: CONFIG_OPTION = None,
231
+ result_store_path: Annotated[
232
+ pathlib.Path, Option(help="Path to store the results")
233
+ ] = "store",
234
+ ):
235
+ """Compares the result of two given snapshots and creates a report. The report is saved, but it is also displayed automatically for convenience"""
236
+ report_config = load_config(config_path).snapshot_comparison_config
237
+
238
+ os.makedirs(result_store_path, exist_ok=True)
239
+ left_data = json.load(open(left))
240
+ right_data = json.load(open(right))
241
+ comparison = SnapshotCompare(left_data, right_data)
242
+
243
+ _, left_device, left_timestamp = details_from_filename(str(left))
244
+ _, right_device, right_timestamp = details_from_filename(str(right))
245
+ if left_device != right_device:
246
+ log.error(
247
+ f"{left_device} is not the same as {right_device} - are you comparing the right reports?"
248
+ )
249
+
250
+ output_file = result_store_path.joinpath(
251
+ f"snapshotr_{right_device}_{right_timestamp}.json".replace(":", "-")
252
+ )
253
+ try:
254
+ result = comparison.compare_snapshots(report_config)
255
+ log.info(f"Saving snapshot comparison result to {output_file}.")
256
+ json.dump(result, open(output_file, "w", encoding=ENCODING))
257
+
258
+ reports = read_snapshot_report(output_file)
259
+ print(reports.device_snapshot_report_as_rich_table(left_device))
260
+ except SnapshotNoneComparisonException as e:
261
+ log.critical(e)
262
+ print(
263
+ "[bold red]Snapshot comparison is not possible as one, or both, of the snapshots contain null data values."
264
+ " The most likely cause is a device connectivity failure when taking the snapshot data from the device."
265
+ "[/bold red]"
266
+ )
267
+
268
+
269
+ @app.command()
270
+ def show_configuration(
271
+ config_path: CONFIG_OPTION = None,
272
+ ):
273
+ """Displays all the configured tests as they will be run. This is useful to show the defaults for this tool or validate your own provided configuration file."""
274
+ config = load_config(config_path)
275
+ checker = CheckFirewall(None)
276
+ parsed_readiness_config = ConfigParser(
277
+ valid_elements=set(checker._check_method_mapping.keys()),
278
+ requested_config=config.pre_checks,
279
+ explicit_elements=CheckFirewall.EXPLICIT_CHECKS,
280
+ ).prepare_config()
281
+
282
+ snaps_list = ConfigParser(
283
+ valid_elements=set(checker._snapshot_method_mapping.keys()),
284
+ requested_config=config.snapshot_config,
285
+ ).prepare_config()
286
+
287
+ comparison = SnapshotCompare(None, None)
288
+ parsed_comparison_config = ConfigParser(
289
+ valid_elements=set(comparison._functions_mapping.keys()),
290
+ requested_config=config.snapshot_comparison_config,
291
+ ).prepare_config()
292
+
293
+ parsed_config_object = TestConfigs(
294
+ pre_checks=parsed_readiness_config,
295
+ snapshot_config=snaps_list,
296
+ snapshot_comparison_config=parsed_comparison_config,
297
+ )
298
+ print(json.dumps(parsed_config_object.model_dump(), indent=4))
299
+
300
+
301
+ @app.command()
302
+ def backup(
303
+ username: USERNAME_OPTION,
304
+ password: PASSWORD_OPTION,
305
+ device: DEVICE_ARGUMENT,
306
+ export_type: Annotated[
307
+ BackupTypeEnum, Option(help="Type of backup to take")
308
+ ] = BackupTypeEnum.configuration,
309
+ backup_path: Annotated[
310
+ pathlib.Path, Option(help="Path to store backups in")
311
+ ] = "backups",
312
+ parallel: Annotated[
313
+ int, Option(help="Number of concurrent connections to make")
314
+ ] = 2,
315
+ ):
316
+ """Backup the configuration of one or more devices to the provided backup_path."""
317
+ os.makedirs(backup_path, exist_ok=True)
318
+
319
+ device_list = get_devices_from_argument(device)
320
+ timestamp = int(datetime.datetime.now(tz=datetime.UTC).timestamp())
321
+
322
+ exec_args = [
323
+ ExporterArguments(
324
+ username=username,
325
+ password=password,
326
+ hostname=d,
327
+ output_file=backup_path.joinpath(
328
+ f"backup_{d}_{timestamp}".replace(":", "-")
329
+ ),
330
+ export_type=export_type,
331
+ )
332
+ for d in device_list
333
+ ]
334
+ log.info(f"Taking {export_type} backups of {len(exec_args)} devices")
335
+ pooled_take_config_backup(exec_args, parallel=parallel)
336
+
337
+
338
+ @app.command()
339
+ def version():
340
+ from upgrade_assurance_cli import __version__
341
+
342
+ print(
343
+ f"Upgrade Assurance CLI version [bold bright_magenta]{__version__}[/bold bright_magenta]"
344
+ )
@@ -0,0 +1,327 @@
1
+ import json
2
+ import pathlib
3
+ import enum
4
+ import datetime
5
+ import sys
6
+
7
+ from rich.table import Table
8
+
9
+
10
+ class ReportTypeEnum(str, enum.Enum):
11
+ readiness = "readiness"
12
+ snapshot = "snapshotr"
13
+
14
+
15
+ class BadDeviceStringException(Exception):
16
+ pass
17
+
18
+
19
+ class SnapshotReport:
20
+ def __init__(self, device, report, timestamp):
21
+ self.timestamp = int(timestamp)
22
+ self.datetime = datetime.datetime.fromtimestamp(self.timestamp)
23
+ self.device = device
24
+ self.report = report
25
+ self.report_type = ReportTypeEnum.snapshot
26
+
27
+ @property
28
+ def count_failed_checks(self) -> int:
29
+ return len([k for k, v in self.report.items() if v and not v.get("passed")])
30
+
31
+ @property
32
+ def count_passed_checks(self) -> int:
33
+ return len([k for k, v in self.report.items() if v and v.get("passed")])
34
+
35
+ def checks_as_table(self):
36
+ table = [
37
+ ["check_name", "passed", "missing", "added", "count_change_percentage"]
38
+ ]
39
+ for check_name, check_value in self.report.items():
40
+ row = [check_name]
41
+ if check_value:
42
+ for i in table[0][1:]:
43
+ result = check_value.get(i)
44
+ if isinstance(result, dict):
45
+ result = result.get("passed")
46
+ row.append(result)
47
+ else:
48
+ # In the case where there is some problem wih the snapshot report, assume all tests have failed
49
+ for _ in table[0][1:]:
50
+ row.append(False)
51
+ table.append(row)
52
+
53
+ return table
54
+
55
+
56
+ class ReadinessCheckReport:
57
+ def __init__(
58
+ self,
59
+ device: str,
60
+ report: dict[str, dict],
61
+ timestamp: int | str,
62
+ ):
63
+ self.timestamp = int(timestamp)
64
+ self.datetime = datetime.datetime.fromtimestamp(self.timestamp)
65
+ self.device = device
66
+ self.report = report
67
+ self.report_type = ReportTypeEnum.readiness
68
+
69
+ @property
70
+ def count_failed_checks(self) -> int:
71
+ return len([k for k, v in self.report.items() if not v.get("state")])
72
+
73
+ @property
74
+ def count_passed_checks(self) -> int:
75
+ return len([k for k, v in self.report.items() if v.get("state")])
76
+
77
+ @staticmethod
78
+ def calc_change_reason_from_snapshot_report(result: dict):
79
+ failed_list = []
80
+ for check_type, check_result in result.items():
81
+ if isinstance(check_result, dict):
82
+ if not check_result.get("passed"):
83
+ failed_list.append(check_type)
84
+
85
+ return ", ".join(failed_list)
86
+
87
+ def checks_as_table(self):
88
+ table = [["check_name", "passed", "check_status", "reason"]]
89
+ for k, check in self.report.items():
90
+ state = check["state"]
91
+ status = check["status"]
92
+ reason = check["reason"]
93
+
94
+ table.append([k, state, status, reason])
95
+ return table
96
+
97
+
98
+ class CheckReports:
99
+ def __init__(self):
100
+ self.readiness_reports: list[ReadinessCheckReport] = []
101
+ self.snapshot_reports: list[SnapshotReport] = []
102
+
103
+ def add_readiness_report(self, report: ReadinessCheckReport):
104
+ self.readiness_reports.append(report)
105
+
106
+ def add_snapshot_report(self, report: SnapshotReport):
107
+ self.snapshot_reports.append(report)
108
+
109
+ @property
110
+ def failed_reports(self):
111
+ return [
112
+ r
113
+ for r in self.readiness_reports + self.snapshot_reports
114
+ if r.count_failed_checks > 0
115
+ ]
116
+
117
+ @property
118
+ def passed_reports(self):
119
+ return [
120
+ r
121
+ for r in self.readiness_reports + self.snapshot_reports
122
+ if r.count_failed_checks == 0
123
+ ]
124
+
125
+ def exit_by_status(self):
126
+ if self.failed_reports:
127
+ sys.exit(1)
128
+
129
+ sys.exit(0)
130
+
131
+ def pass_or_fail_as_rich_string(self):
132
+ if len(self.failed_reports) > 0:
133
+ return "[red]❌ Some devices failed checks![/red]"
134
+
135
+ return "✅ All devices passed."
136
+
137
+ def counts_as_rich_table(self):
138
+ list_table = self.counts_as_table()
139
+ table = Table()
140
+ for c in list_table[0]:
141
+ table.add_column(c)
142
+
143
+ for r in list_table[1:]:
144
+ failed_count = r[3]
145
+ style = "green"
146
+ if failed_count > 0:
147
+ style = "bold red"
148
+ new_row_items = [str(i) for i in r]
149
+ table.add_row(*new_row_items, style=style)
150
+
151
+ return table
152
+
153
+ @property
154
+ def reports(self):
155
+ return self.snapshot_reports + self.readiness_reports
156
+
157
+ def counts_as_table(self) -> list[list[str | int]]:
158
+ table = [
159
+ [
160
+ "timestamp",
161
+ "report_type",
162
+ "device",
163
+ "failed_checks_count",
164
+ "passed_checks_count",
165
+ ]
166
+ ]
167
+ for report in self.sorted_reports:
168
+ table.append(
169
+ [
170
+ report.datetime.isoformat(),
171
+ report.report_type.value,
172
+ report.device,
173
+ report.count_failed_checks,
174
+ report.count_passed_checks,
175
+ ]
176
+ )
177
+ return table
178
+
179
+ @property
180
+ def sorted_reports(self):
181
+ return sorted(self.reports, key=lambda d: d.timestamp)
182
+
183
+ def get_latest_report_by_device(self, device_str: str, reports: list):
184
+ sorted_reports = sorted(
185
+ [d for d in reports if d.device == device_str],
186
+ key=lambda d: d.timestamp,
187
+ reverse=True,
188
+ )
189
+ if not sorted_reports:
190
+ return None
191
+
192
+ return sorted_reports[0]
193
+
194
+ def device_readiness_report_as_rich_table(self, device_str: str):
195
+ report = self.get_latest_report_by_device(device_str, self.readiness_reports)
196
+ if not report:
197
+ return f"[yellow]No Readiness report found for {device_str}[/yellow]"
198
+
199
+ list_table = report.checks_as_table()
200
+ table = Table(
201
+ caption=f"READINESS Checks were ran at {report.datetime.isoformat()}"
202
+ )
203
+ for c in list_table[0]:
204
+ table.add_column(c)
205
+
206
+ for r in list_table[1:]:
207
+ style = "green"
208
+ if not r[1]:
209
+ style = "bold red"
210
+ new_row_items = [str(i) for i in r]
211
+ table.add_row(*new_row_items, style=style)
212
+
213
+ return table
214
+
215
+ def device_snapshot_report_as_rich_table(self, device_str: str):
216
+ report = self.get_latest_report_by_device(device_str, self.snapshot_reports)
217
+ if not report:
218
+ return f"[yellow]No Snapshot report found for {device_str}[/yellow]"
219
+ table = Table(
220
+ caption=f"SNAPSHOT Report was ran at {report.datetime.isoformat()}"
221
+ )
222
+ table_list = report.checks_as_table()
223
+ for header in table_list[0]:
224
+ table.add_column(f"{header}")
225
+
226
+ for r in table_list[1:]:
227
+ style = "green"
228
+ if not r[1]:
229
+ style = "bold red"
230
+ new_row_items = [str(i) for i in r]
231
+
232
+ table.add_row(*new_row_items, style=style)
233
+
234
+ return table
235
+
236
+
237
+ def details_from_filename(filename: str) -> tuple[str, str, str]:
238
+ """Gets the device name, the check type and the timestamp based on the filename."""
239
+ filename = filename.replace(".json", "")
240
+ check_type, device, timestamp = filename.split("_")
241
+ return check_type, device, timestamp
242
+
243
+
244
+ def read_snapshot_report(path: pathlib.Path):
245
+ """Reads a single report and returns it"""
246
+ check_type, device, timestamp = details_from_filename(path.name)
247
+ reports = CheckReports()
248
+ report = SnapshotReport(
249
+ timestamp=timestamp,
250
+ device=device,
251
+ report=json.load(open(path)),
252
+ )
253
+ reports.add_snapshot_report(report)
254
+ return reports
255
+
256
+
257
+ def generate_reports_from_store(store_path: pathlib.Path):
258
+ """Returns the completed readiness check report based on the generated check results in
259
+ the store path"""
260
+
261
+ reports = CheckReports()
262
+ file: pathlib.Path
263
+ for file in store_path.iterdir():
264
+ if file.is_file() and file.suffix == ".json":
265
+ check_type, device, timestamp = details_from_filename(file.name)
266
+ if check_type == ReportTypeEnum.readiness.value:
267
+ report = ReadinessCheckReport(
268
+ timestamp=timestamp,
269
+ device=device,
270
+ report=json.load(open(file)),
271
+ )
272
+ reports.add_readiness_report(report)
273
+ elif check_type == ReportTypeEnum.snapshot:
274
+ report = SnapshotReport(
275
+ timestamp=timestamp,
276
+ device=device,
277
+ report=json.load(open(file)),
278
+ )
279
+ reports.add_snapshot_report(report)
280
+
281
+ return reports
282
+
283
+
284
+ class SnapshotData:
285
+ def __init__(
286
+ self,
287
+ device: str,
288
+ data: dict[str, dict],
289
+ timestamp: int | str,
290
+ ):
291
+ self.timestamp = int(timestamp)
292
+ self.datetime = datetime.datetime.fromtimestamp(self.timestamp)
293
+ self.device = device
294
+ self.data = data
295
+
296
+ def data_as_table(self):
297
+ table = [["type", "state"]]
298
+
299
+ for snapshot_type, data in self.data.items():
300
+ table.append([snapshot_type, data.get("state")])
301
+
302
+ return table
303
+
304
+ def data_as_rich_table(self):
305
+ table = Table(caption=f"SNAPSHOT Taken at {self.datetime.isoformat()}")
306
+ table_list = self.data_as_table()
307
+ for c in table_list[0]:
308
+ table.add_column(c)
309
+
310
+ for r in table_list[1:]:
311
+ style = "green"
312
+ if not r[1]:
313
+ style = "bold red"
314
+ new_row_items = [str(i) for i in r]
315
+ table.add_row(*new_row_items, style=style)
316
+
317
+ return table
318
+
319
+
320
+ def get_snapshot_data_report(path: pathlib.Path):
321
+ """Returns a `SnapshotData` instance representing a taken snapshot"""
322
+ if path.is_file() and path.suffix == ".json":
323
+ check_type, device, timestamp = details_from_filename(path.name)
324
+ report = SnapshotData(device, json.load(open(path)), timestamp)
325
+ return report
326
+
327
+ raise FileNotFoundError(f"{path} not found.")
@@ -0,0 +1,134 @@
1
+ import multiprocessing
2
+ import json
3
+
4
+ from panos.firewall import Firewall
5
+ from panos.panorama import Panorama
6
+
7
+ from upgrade_assurance_cli.cli.utils import log, ENCODING
8
+ from panos_upgrade_assurance.firewall_proxy import FirewallProxy
9
+ from panos_upgrade_assurance.check_firewall import CheckFirewall
10
+ import logging
11
+
12
+
13
+ def get_firewall_proxy_from_args(
14
+ username: str, password: str, device: str
15
+ ) -> FirewallProxy:
16
+ """Returns a FirewallProxy object based on the arguments passed to this function"""
17
+ d = device.split(":")
18
+ if len(d) == 2:
19
+
20
+ panorama_hostname, firewall_serial = d
21
+ fw = Firewall(
22
+ api_username=username,
23
+ api_password=password,
24
+ serial=firewall_serial,
25
+ )
26
+ panorama = Panorama(
27
+ api_username=username,
28
+ api_password=password,
29
+ hostname=panorama_hostname,
30
+ )
31
+ panorama.add(fw)
32
+ return FirewallProxy(fw)
33
+
34
+ return FirewallProxy(
35
+ hostname=device,
36
+ api_username=username,
37
+ api_password=password,
38
+ )
39
+
40
+
41
+ class CheckExecutionArgs:
42
+ def __init__(self, username, password, hostname, check_configuration, output_file):
43
+ self.check_configuration = check_configuration
44
+ self.output_file = output_file
45
+ self.username = username
46
+ self.password = password
47
+ self.hostname = hostname
48
+
49
+ @property
50
+ def device_str(self):
51
+ return f"{self.hostname}".replace(":", "-")
52
+
53
+
54
+ def setup_logger_for_runners(device_str):
55
+ file_log = logging.getLogger(device_str)
56
+ file_handler = logging.FileHandler(f"{device_str}.log")
57
+ file_handler.setFormatter(
58
+ logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
59
+ )
60
+ file_log.addHandler(file_handler)
61
+ file_log.propagate = False
62
+ return file_log
63
+
64
+
65
+ def setup_for_checks(exec_arguments: CheckExecutionArgs):
66
+ device = get_firewall_proxy_from_args(
67
+ exec_arguments.username,
68
+ exec_arguments.password,
69
+ exec_arguments.hostname,
70
+ )
71
+ file_log = setup_logger_for_runners(exec_arguments.device_str)
72
+ return CheckFirewall(device), file_log
73
+
74
+
75
+ def run_readiness_checks_on_device(exec_arguments: CheckExecutionArgs):
76
+ check_configuration = exec_arguments.check_configuration
77
+ output_file = exec_arguments.output_file
78
+ try:
79
+
80
+ checks, file_log = setup_for_checks(exec_arguments)
81
+ result = checks.run_readiness_checks(check_configuration)
82
+ with open(output_file, "w", encoding=ENCODING) as fh:
83
+ json.dump(result, fh, indent=4)
84
+
85
+ file_log.info(f"{exec_arguments.device_str} - Writing to file {output_file}")
86
+ except Exception as e:
87
+ file_log.critical(f"Readiness checks failed!", exc_info=True)
88
+ result = {
89
+ "device_connectivity": {
90
+ "state": False,
91
+ "status": "ERROR",
92
+ "reason": f"Critical error running readiness checks: {e}",
93
+ }
94
+ }
95
+ with open(output_file, "w", encoding=ENCODING) as fh:
96
+ json.dump(result, fh, indent=4)
97
+
98
+
99
+ def get_snapshots_on_device(exec_arguments: CheckExecutionArgs):
100
+ checks, file_log = setup_for_checks(exec_arguments)
101
+ file_log.info(f"{exec_arguments.device_str} - Taking device snapshot")
102
+ output_file = exec_arguments.output_file
103
+
104
+ try:
105
+ snapshot_configuration = exec_arguments.check_configuration
106
+
107
+ result = checks.run_snapshots(snapshot_configuration)
108
+
109
+ with open(output_file, "w", encoding=ENCODING) as fh:
110
+ json.dump(result, fh, indent=4)
111
+
112
+ file_log.info(f"{exec_arguments.device_str} - Writing to file {output_file}")
113
+ except Exception as e:
114
+ file_log.critical(f"Snapshot failed!", exc_info=True)
115
+
116
+
117
+ def pooled_run_readiness_checks_on_devices(
118
+ exec_args: list[CheckExecutionArgs], parallel: int = 4
119
+ ):
120
+ log.info(f"Running readiness checks using multiprocessing ({parallel})")
121
+ with multiprocessing.Pool(parallel) as pool:
122
+ pool.map(run_readiness_checks_on_device, exec_args)
123
+
124
+ log.info(f"Readiness checks complete")
125
+
126
+
127
+ def pooled_run_snapshot_checks_on_devices(
128
+ exec_args: list[CheckExecutionArgs], parallel: int = 4
129
+ ):
130
+ log.info(f"Running Snapshot checks using multiprocessing ({parallel})")
131
+ with multiprocessing.Pool(parallel) as pool:
132
+ pool.map(get_snapshots_on_device, exec_args)
133
+
134
+ log.info(f"Snapshots complete")
@@ -0,0 +1,90 @@
1
+ import json
2
+ import logging
3
+ import pathlib
4
+
5
+ import yaml
6
+ from pydantic import BaseModel
7
+ from rich.logging import RichHandler
8
+
9
+ FORMAT = "%(message)s"
10
+ logging.basicConfig(
11
+ level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
12
+ )
13
+
14
+ log = logging.getLogger("cli")
15
+
16
+ ENCODING = "utf-8"
17
+
18
+ DEFAULT_SNAPSHOT_CONFIG = [
19
+ "nics",
20
+ "routes",
21
+ "license",
22
+ "arp_table",
23
+ "session_stats",
24
+ "ip_sec_tunnels",
25
+ "bgp_peers",
26
+ ]
27
+
28
+ DEFAULT_SNAPSHOT_COMPARISON_CONFIG = [
29
+ {"arp_table": {"properties": ["!ttl"], "count_change_threshold": 10}},
30
+ {"routes": {"properties": ["!flags"], "count_change_threshold": 10}},
31
+ {"session_stats": {}},
32
+ {"license": {}},
33
+ ]
34
+
35
+ DEFAULT_READINESS_CHECKS = [
36
+ "environmentals",
37
+ "ha",
38
+ "ntp_sync",
39
+ "candidate_config",
40
+ "expired_licenses",
41
+ "active_support",
42
+ "free_disk_space",
43
+ "certificates_requirements",
44
+ "dynamic_updates",
45
+ "jobs",
46
+ "global_jumbo_frame",
47
+ "dp_cpu_utilization",
48
+ "mp_cpu_utilization",
49
+ # "planes_clock_sync" # Currently bugged on some platforms
50
+ ]
51
+
52
+
53
+ class TestConfigs(BaseModel):
54
+ pre_checks: list = DEFAULT_READINESS_CHECKS
55
+ snapshot_config: list = DEFAULT_SNAPSHOT_CONFIG
56
+ snapshot_comparison_config: list | dict = DEFAULT_SNAPSHOT_COMPARISON_CONFIG
57
+
58
+
59
+ def load_config(fp: pathlib.Path):
60
+ if not fp:
61
+ log.warning(
62
+ "No config file provided, using defaults. Use the `show-configuration` subcommand to show all defaults"
63
+ )
64
+ loaded_config = {
65
+ "snapshot_config": DEFAULT_SNAPSHOT_CONFIG,
66
+ "snapshot_comparison_config": DEFAULT_SNAPSHOT_COMPARISON_CONFIG,
67
+ "pre_checks": DEFAULT_READINESS_CHECKS,
68
+ }
69
+
70
+ return TestConfigs(**loaded_config)
71
+ with open(fp) as config:
72
+ try:
73
+ loaded_config = yaml.safe_load(config)
74
+ return TestConfigs(**loaded_config)
75
+
76
+ except yaml.YAMLError:
77
+ log.info("Could not load file as YAML - trying JSON")
78
+
79
+ try:
80
+ loaded_config = json.load(config)
81
+ return TestConfigs(**loaded_config)
82
+
83
+ except json.JSONDecodeError as e:
84
+ log.critical("Could not load check config!")
85
+ raise
86
+
87
+
88
+ def parse_file_to_devices(fp: pathlib.Path):
89
+ with open(fp) as fh:
90
+ return [l.strip() for l in fh.read().splitlines()]
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: upgrade-assurance-cli
3
+ Version: 1.0.1
4
+ Summary: Upgrade Assurance CLI Tool
5
+ License-File: LICENSE
6
+ Author: Adam Baumeister
7
+ Author-email: abaumeister@paloaltonetworks.com
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Dist: panos-upgrade-assurance (>=2.0.1,<3.0.0)
14
+ Requires-Dist: pydantic (>=2.12.5,<3.0.0)
15
+ Requires-Dist: pyyaml (>=6.0.3,<7.0.0)
16
+ Requires-Dist: requests (>=2.33.0,<3.0.0)
17
+ Requires-Dist: setuptools (>=82.0.1,<83.0.0)
18
+ Requires-Dist: typer (>=0.24.1,<0.25.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Upgrade Assurance CLI Tool
22
+
23
+ This project is a simple CLI wrapper around the [PAN-OS Upgrade Assurance](https://github.com/PaloAltoNetworks/pan-os-upgrade-assurance)
24
+ library.
25
+
26
+
27
+ ## Installation
28
+
29
+ It is recommended to install this project with [pipx](https://pipx.pypa.io/stable/).
30
+
31
+ Installing with pipx will automatically make the main script, `assurance-cli` available at the command line.
32
+
33
+ ```shell
34
+ pipx install upgrade-assurance-cli
35
+ ```
36
+
37
+ You can also install directly from this repository if you want to get changes as we develop them, but before they are
38
+ formally released.
39
+
40
+ ```shell
41
+ # Install from the main branch
42
+ pipx install git+https://github.com/PaloAltoNetworks/upgrade-assurance-cli.git
43
+ # Install from <branch_name>, useful for testing.
44
+ pipx install git+https://github.com/PaloAltoNetworks/upgrade-assurance-cli.git@<branch_name>
45
+ ```
46
+
47
+ ## Quickstart
48
+
49
+ Run a readiness check ("pre-checks") against a given device.
50
+
51
+ ```shell
52
+ assurance-cli readiness myfirewall.com
53
+ ```
54
+
55
+ Read the last readiness report for a specific device
56
+
57
+ ```shell
58
+ assurance-cli report --device myfirewall.com
59
+ ```
60
+
61
+ Take an operational snapshot
62
+
63
+ ```shell
64
+ assurance-cli snapshot myfirewall.com
65
+ ```
66
+
67
+ Compare two snapshots
68
+
69
+ ```shell
70
+ assurance-cli compare-snapshots <first-snapshot-path> <second-snapshot-path>
71
+ ```
72
+
73
+ Backup the configuration running-configuration
74
+
75
+ ```shell
76
+ assurance-cli backup myfirewall.com
77
+ ```
78
+
79
+ Backup the configuration device-state
80
+
81
+ ```shell
82
+ assurance-cli backup myfirewall.com --export-type device-state
83
+ ```
84
+
85
+ ## Configuration
86
+
87
+ ### Running Against Multiple Devices
88
+
89
+ This tool allows you to run against multiple devices at once using `multiprocessing`.
90
+
91
+ Multiple devices can be passed to the comand line as arguments to the `readiness` and `snapshot` commands.
92
+
93
+ ```shell
94
+ assurance-cli readiness myfirstfirewall.com mysecondfirewall.com
95
+ ```
96
+
97
+ Or, they can be passed via a text file containing one device per line.
98
+
99
+ ```text
100
+ myfirstfirewall.com
101
+ mysecondfirewall.com
102
+ ```
103
+
104
+ ```shell
105
+ assurance-cli readiness <path_to_devices_file>
106
+ ```
107
+
108
+ ### Connecting Via Panorama
109
+
110
+ Connections can be proxied via Panorama for simplicity. To do so, use the following format for the device string;
111
+ `<panorama_hostname>:<firewall_serial_number>`
112
+
113
+ ```shell
114
+ assurance-cli readiness my_panorama.com:1234567891011
115
+ ```
116
+
117
+ ### Environment Variables
118
+
119
+ envvar | description
120
+ --- | ---
121
+ UA_USERNAME | Username to use for authentication - prompts if not given
122
+ UA_PASSWORD | Username to use for authentication - prompts if not given
123
+
124
+ ### Customizing the Test Suite
125
+
126
+ All commands support passing the `--config-path` flag to pass in a config file. This CLI ships with the most commonly
127
+ used tests but it is expected that most users will need to customize it.
128
+
129
+ The config file is in YAML format and specifies the tests used by the upgrade assurance library.
130
+
131
+ ```yaml
132
+ pre_checks:
133
+ - "ntp_sync"
134
+ snapshot_comparison_config:
135
+ - routes:
136
+ properties:
137
+ - "!flags"
138
+ count_change_threshold: 10
139
+ snapshot_config:
140
+ - routes
141
+ - nics
142
+ ```
143
+
144
+ For a full list of checks and al their configuration options view the
145
+ [Upgrade Assurance Documentation site.](https://pan.dev/panos/docs/panos-upgrade-assurance/configuration-details/)
146
+
@@ -0,0 +1,12 @@
1
+ upgrade_assurance_cli/__init__.py,sha256=MRvq08Iag5qOVCwVdYmrfUIlEQMoUeWpQWplEus--iE,256
2
+ upgrade_assurance_cli/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ upgrade_assurance_cli/cli/exporter.py,sha256=iyVAxVtqqm4Px_xfCDTb0Ta0mjttyKUxN53prAhophQ,3228
4
+ upgrade_assurance_cli/cli/main.py,sha256=B9pKg_9ztKJaA8tvsH04Qgvn5Fl2bz8KkimRJUn4lV0,11381
5
+ upgrade_assurance_cli/cli/report.py,sha256=tLxgI45tKRW-jI2G9TexV832SfeXS2gNU4ufdR5oXvc,10154
6
+ upgrade_assurance_cli/cli/runner.py,sha256=dtgnjzyHwvTIY2M4ArX1apZfeKWwQS_6SghSgTme5zY,4404
7
+ upgrade_assurance_cli/cli/utils.py,sha256=I8tzO12kepC0p8PJPxn1BPlthG3Jub-lKnw9GiVsBi0,2341
8
+ upgrade_assurance_cli-1.0.1.dist-info/METADATA,sha256=p3Eum7NWOU1RXnBGLG5iAD49MYDt96TEKjPhZuIBsT8,3897
9
+ upgrade_assurance_cli-1.0.1.dist-info/WHEEL,sha256=Vz2fHgx6HFtSwhs8KvkHLqH5Ea4w1_rner5uNVGCeIE,88
10
+ upgrade_assurance_cli-1.0.1.dist-info/entry_points.txt,sha256=9W_p23amsslmfUdlg3h7grCRKuu0htqcJ18_Zq2Irac,68
11
+ upgrade_assurance_cli-1.0.1.dist-info/licenses/LICENSE,sha256=hMo1uMYCNg6nvgmG7moDDX9zQ4V0rU_FypzcPP7hDNU,1080
12
+ upgrade_assurance_cli-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.3.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ assurance-cli=upgrade_assurance_cli.cli.main:app
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Palo Alto Networks, inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.