1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
|
"""
The tool to check the availability or syntax of domain, IP or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗
██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝
██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝
Provides everything related to our status file generation.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Special thanks:
https://pyfunceble.github.io/#/special-thanks
Contributors:
https://pyfunceble.github.io/#/contributors
Project link:
https://github.com/funilrys/PyFunceble
Project documentation:
https://docs.pyfunceble.com
Project homepage:
https://pyfunceble.github.io/
License:
::
Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025 Nissar Chababy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import functools
import os
from typing import Optional, Union
import PyFunceble.cli.storage
import PyFunceble.facility
import PyFunceble.storage
from PyFunceble.checker.availability.status import AvailabilityCheckerStatus
from PyFunceble.checker.reputation.status import ReputationCheckerStatus
from PyFunceble.checker.status_base import CheckerStatusBase
from PyFunceble.checker.syntax.status import SyntaxCheckerStatus
from PyFunceble.cli.filesystem.dir_base import FilesystemDirBase
from PyFunceble.cli.filesystem.dir_structure.restore import (
DirectoryStructureRestoration,
)
from PyFunceble.cli.filesystem.printer.file import FilePrinter
from PyFunceble.utils.platform import PlatformUtility
class StatusFileGenerator(FilesystemDirBase):
"""
Provides an interface for the generation of the status file from
a given status.
"""
# pylint: disable=too-many-public-methods
STD_HOSTS_IP: str = "0.0.0.0" # nosec: B104 # Default to non-routable IP
STD_ALLOW_HOSTS_FILES: bool = True
STD_ALLOW_PLAIN_FILES: bool = True
STD_ALLOW_ANALYTIC_FILES: bool = True
STD_ALLOW_UNIFIED_FILE: bool = False
file_printer: FilePrinter = FilePrinter()
_test_dataset: Optional[dict] = None
_status: Optional[
Union[SyntaxCheckerStatus, AvailabilityCheckerStatus, ReputationCheckerStatus]
] = None
_allow_hosts_files: bool = True
_allow_plain_files: bool = True
_allow_analytic_files: bool = True
_allow_unified_file: bool = False
_hosts_ip: Optional[str] = None
def __init__(
self,
status: Optional[
Union[
SyntaxCheckerStatus, AvailabilityCheckerStatus, ReputationCheckerStatus
]
] = None,
*,
allow_hosts_files: Optional[bool] = None,
allow_plain_files: Optional[bool] = None,
allow_analytic_files: Optional[bool] = None,
hosts_ip: Optional[str] = None,
allow_unified_file: Optional[bool] = None,
parent_dirname: Optional[str] = None,
test_dataset: Optional[dict] = None,
) -> None:
if status is not None:
self.status = status
if allow_hosts_files is not None:
self.allow_hosts_files = allow_hosts_files
else:
self.guess_and_set_allow_hosts_files()
if allow_plain_files is not None:
self.allow_plain_files = allow_plain_files
else:
self.guess_and_set_allow_plain_files()
if allow_analytic_files is not None:
self.allow_analytic_files = allow_analytic_files
else:
self.guess_and_set_allow_analytic_files()
if hosts_ip is not None:
self.hosts_ip = hosts_ip
else:
self.guess_and_set_hosts_ip()
if allow_unified_file is not None:
self.allow_unified_file = allow_unified_file
else:
self.guess_and_set_allow_unified_file()
if test_dataset is not None:
self.test_dataset = test_dataset
super().__init__(parent_dirname=parent_dirname)
def ensure_status_is_given(func): # pylint: disable=no-self-argument
"""
Ensures that the status is given before launching the decorated method.
:raise TypeError:
When :code:`self.status` is not set.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not isinstance(
self.status,
CheckerStatusBase,
):
raise TypeError("<self.status> is not given.")
return func(self, *args, **kwargs) # pylint: disable=not-callable
return wrapper
@property
def status(self) -> CheckerStatusBase:
"""
Provides the current state of the :code:`_status` attribute.
"""
return self._status
@status.setter
def status(self, value: CheckerStatusBase) -> None:
"""
Sets the status to work with.
:param value:
The value to set.
:raise TypeError:
When the given value is not a
:class`~ PyFunceble.checker.syntax.status.SyntaxCheckerStatus`,
:class:`~PyFunceble.checker.availability.status.AvailabilityCheckerStatus`
or :class:`~PyFunceble.checker.reputation.status.ReputationCheckerStatus`
"""
if not isinstance(
value,
CheckerStatusBase,
):
raise TypeError(
f"<value> should be {CheckerStatusBase}, {type(value)} given."
)
self._status = value
def set_status(
self,
value: CheckerStatusBase,
) -> "StatusFileGenerator":
"""
Sets the status to work with.
:param value:
The value to set.
"""
self.status = value
return self
@property
def test_dataset(self) -> Optional[dict]:
"""
Provides the current state of the :code:`_test_dataset` attribute.
"""
return self._test_dataset
@test_dataset.setter
def test_dataset(self, value: dict) -> None:
"""
Sets the test dataset which was given to the tester.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class`dict`.
"""
if not isinstance(value, dict):
raise TypeError(f"<value> should be {dict}, {type(value)} given.")
self._test_dataset = value
def set_test_dataset(self, value: dict) -> "StatusFileGenerator":
"""
Sets the test dataset which was given to the tester.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class`dict`.
"""
self.test_dataset = value
return self
@property
def allow_hosts_files(self) -> bool:
"""
Provides the current state of the :code:`_allow_hosts_files` attribute.
"""
return self._allow_hosts_files
@allow_hosts_files.setter
def allow_hosts_files(self, value: bool) -> None:
"""
Sets the authorization to generation of hosts files.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._allow_hosts_files = value
def set_allow_hosts_files(self, value: bool) -> "StatusFileGenerator":
"""
Sets the authorization to generation of hosts files.
:param value:
The value to set.
"""
self.allow_hosts_files = value
return self
def guess_and_set_allow_hosts_files(self) -> "StatusFileGenerator":
"""
Tries to guess the value of the :code:`allow_hosts_files` from the
configuration file.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
self.allow_hosts_files = (
PyFunceble.storage.CONFIGURATION.cli_testing.file_generation.hosts
)
else:
self.allow_hosts_files = self.STD_ALLOW_HOSTS_FILES
@property
def allow_plain_files(self) -> bool:
"""
Provides the current state of the :code:`_allow_plain_file` attribute.
"""
return self._allow_plain_files
@allow_plain_files.setter
def allow_plain_files(self, value: bool) -> None:
"""
Sets the authorization to generation of plain files.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._allow_plain_files = value
def set_allow_plain_files(self, value: bool) -> "StatusFileGenerator":
"""
Sets the authorization to generation of plain files.
:param value:
The value to set.
"""
self.allow_plain_files = value
return self
def guess_and_set_allow_plain_files(self) -> "StatusFileGenerator":
"""
Tries to guess the value of the :code:`allow_plain_files` from the
configuration file.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
self.allow_plain_files = (
PyFunceble.storage.CONFIGURATION.cli_testing.file_generation.plain
)
else:
self.allow_plain_files = self.STD_ALLOW_PLAIN_FILES
@property
def allow_analytic_files(self) -> bool:
"""
Provides the current state of the :code:`_allow_analytic_files`
attribute.
"""
return self._allow_analytic_files
@allow_analytic_files.setter
def allow_analytic_files(self, value: bool) -> None:
"""
Sets the authorization to generation of analytic files.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._allow_analytic_files = value
def set_allow_analytic_files(self, value: bool) -> "StatusFileGenerator":
"""
Sets the authorization to generation of analytic files.
:param value:
The value to set.
"""
self.allow_analytic_files = value
return self
def guess_and_set_allow_analytic_files(self) -> "StatusFileGenerator":
"""
Tries to guess the value of the :code:`allow_analytic_files` from the
configuration file.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
self.allow_analytic_files = (
PyFunceble.storage.CONFIGURATION.cli_testing.file_generation.analytic
)
else:
self.allow_analytic_files = self.STD_ALLOW_ANALYTIC_FILES
@property
def hosts_ip(self) -> Optional[str]:
"""
Provides the current state of the :code:`_hosts_ip` attribute.
"""
return self._hosts_ip
@hosts_ip.setter
def hosts_ip(self, value: str) -> None:
"""
Sets the hosts IP to use while generating the hosts files.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`value` is empty.
"""
if not isinstance(value, str):
raise TypeError(f"<value> should be {str}, {type(value)} given.")
if not value:
raise ValueError("<value> should not be empty.")
self._hosts_ip = value
def set_hosts_ip(self, value: str) -> "StatusFileGenerator":
"""
Sets the hosts IP to use while generating the hosts files.
:param value:
The value to set.
"""
self.hosts_ip = value
return self
def guess_and_set_hosts_ip(self) -> "StatusFileGenerator":
"""
Tries to guess the value of the :code:`hosts_ip` from the
configuration file.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
self.hosts_ip = PyFunceble.storage.CONFIGURATION.cli_testing.hosts_ip
else:
self.hosts_ip = self.STD_HOSTS_IP
@property
def allow_unified_file(self) -> bool:
"""
Provides the current state of the :code:`allow_unified_file` attribute.
"""
return self._allow_unified_file
@allow_unified_file.setter
def allow_unified_file(self, value: bool) -> None:
"""
Sets the authorization to generation of the unified status file.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`bool`.
"""
if not isinstance(value, bool):
raise TypeError(f"<value> should be {bool}, {type(value)} given.")
self._allow_unified_file = value
def set_allow_unified_file(self, value: bool) -> "StatusFileGenerator":
"""
Sets the authorization to generation of the unified status file.
:param value:
The value to set.
"""
self.allow_unified_file = value
return self
def guess_and_set_allow_unified_file(self) -> "StatusFileGenerator":
"""
Tries to guess the value of the :code:`allow_unified_file` from the
configuration file.
"""
if PyFunceble.facility.ConfigLoader.is_already_loaded():
# pylint: disable=line-too-long
self.allow_unified_file = (
PyFunceble.storage.CONFIGURATION.cli_testing.file_generation.unified_results
)
else:
self.allow_unified_file = self.STD_ALLOW_UNIFIED_FILE
def guess_all_settings(self) -> "StatusFileGenerator":
"""
Try to guess all settings.
"""
to_ignore = ["guess_all_settings"]
for method in dir(self):
if method in to_ignore or not method.startswith("guess_"):
continue
getattr(self, method)()
return self
def get_output_basedir(self) -> str:
"""
Provides the output base directory.
:param create_if_missing:
Authorizes the creation of the directory if it's missing.
"""
result = super().get_output_basedir()
if not self.directory_helper.set_path(result).exists():
DirectoryStructureRestoration(self.parent_dirname).start()
return result
@ensure_status_is_given
def generate_hosts_file(self) -> "StatusFileGenerator":
"""
Generates the hosts file.
"""
our_dataset = self.status.to_dict()
our_dataset["ip"] = self.hosts_ip
if not hasattr(self.status, "ip_syntax") or not self.status.ip_syntax:
location = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.hosts.directory,
self.status.status.upper(),
PyFunceble.cli.storage.OUTPUTS.hosts.filename,
)
else:
location = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.hosts.directory,
self.status.status.upper(),
PyFunceble.cli.storage.OUTPUTS.hosts.ip_filename,
)
self.file_printer.destination = location
self.file_printer.dataset = our_dataset
self.file_printer.template_to_use = "hosts"
self.file_printer.print_interpolated_line()
return self
@ensure_status_is_given
def generate_plain_file(self) -> "StatusFileGenerator":
"""
Generates the plain file.
"""
location = None
if not hasattr(self.status, "ip_syntax") or not self.status.ip_syntax:
location = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.domains.directory,
self.status.status.upper(),
PyFunceble.cli.storage.OUTPUTS.domains.filename,
)
self.file_printer.destination = location
self.file_printer.dataset = self.status.to_dict()
self.file_printer.template_to_use = "plain"
self.file_printer.print_interpolated_line()
if not hasattr(self.status, "ip_syntax") or self.status.subject_kind == "ip":
location = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.ips.directory,
self.status.status.upper(),
PyFunceble.cli.storage.OUTPUTS.ips.filename,
)
self.file_printer.destination = location
self.file_printer.dataset = self.status.to_dict()
self.file_printer.template_to_use = "plain"
self.file_printer.print_interpolated_line()
return self
@ensure_status_is_given
def generate_analytic_file(self) -> "StatusFileGenerator":
"""
Generates the analytic files.
"""
locations_data_and_template = []
# pylint: disable=line-too-long
if hasattr(self.status, "http_status_code") and self.status.http_status_code:
if PyFunceble.facility.ConfigLoader.is_already_loaded():
http_code_dataset = PyFunceble.storage.HTTP_CODES
else:
http_code_dataset = PyFunceble.storage.STD_HTTP_CODES
if (
self.status.http_status_code in http_code_dataset.list.potentially_down
or self.status.status
in (PyFunceble.storage.STATUS.down, PyFunceble.storage.STATUS.invalid)
):
locations_data_and_template.append(
(
os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.analytic.directories.parent,
PyFunceble.cli.storage.OUTPUTS.analytic.directories.potentially_down,
PyFunceble.cli.storage.OUTPUTS.analytic.filenames.potentially_down,
),
"plain",
self.status.to_dict(),
)
)
if self.status.http_status_code in http_code_dataset.list.up:
locations_data_and_template.append(
(
os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.analytic.directories.parent,
PyFunceble.cli.storage.OUTPUTS.analytic.directories.potentially_down,
PyFunceble.cli.storage.OUTPUTS.analytic.filenames.up,
),
"plain",
self.status.to_dict(),
)
)
if (
self.status.http_status_code in http_code_dataset.list.potentially_up
or self.status.status == PyFunceble.storage.STATUS.down
):
locations_data_and_template.append(
(
os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.analytic.directories.parent,
PyFunceble.cli.storage.OUTPUTS.analytic.directories.potentially_down,
PyFunceble.cli.storage.OUTPUTS.analytic.filenames.potentially_up,
),
"plain",
self.status.to_dict(),
)
)
if self.test_dataset and "from_inactive" in self.test_dataset:
# Let's generate the suspicious file :-)
if self.status.status in [
PyFunceble.storage.STATUS.up,
PyFunceble.storage.STATUS.valid,
PyFunceble.storage.STATUS.sane,
]:
locations_data_and_template.append(
(
os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.analytic.directories.parent,
PyFunceble.cli.storage.OUTPUTS.analytic.directories.suspicious,
PyFunceble.cli.storage.OUTPUTS.analytic.filenames.suspicious,
),
"plain",
self.status.to_dict(),
)
)
for file_location, template, our_dataset in locations_data_and_template:
self.file_printer.destination = file_location
self.file_printer.dataset = our_dataset
self.file_printer.template_to_use = template
self.file_printer.print_interpolated_line()
return self
@ensure_status_is_given
def generate_splitted_status_file(self) -> "StatusFileGenerator":
"""
Generates the splitted status file.
"""
self.file_printer.destination = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.OUTPUTS.splitted.directory,
self.status.status.upper(),
)
if not PlatformUtility.is_unix():
self.file_printer.destination += ".txt"
self.file_printer.template_to_use = "all"
self.file_printer.dataset = self.status.to_dict()
self.file_printer.print_interpolated_line()
return self
@ensure_status_is_given
def generate_unified_status_file(self) -> "StatusFileGenerator":
"""
Generates the unified status file.
"""
self.file_printer.destination = os.path.join(
self.get_output_basedir(),
PyFunceble.cli.storage.RESULTS_RAW_FILE,
)
self.file_printer.template_to_use = "all"
self.file_printer.dataset = self.status.to_dict()
self.file_printer.print_interpolated_line()
return self
def start(self) -> "StatusFileGenerator":
"""
Starts the generation of everything possible.
"""
if self.allow_hosts_files:
self.generate_hosts_file()
if self.allow_plain_files:
self.generate_plain_file()
if self.allow_analytic_files:
self.generate_analytic_file()
if self.allow_unified_file:
self.generate_unified_status_file()
else:
self.generate_splitted_status_file()
|