Package Content

cpu_health Main Module

class cpu_health_checks.cpu_health.CPUCheck(config_file='../../config/configuration.yml', config_mode='default', logs_folder=None, min_gb=None, min_percent_disk=None, folders_to_print=None, max_cpu_usage=None, website_to_check=None, max_connection_attempts=None, file_sizes_to_download=None, block_size=None, sleep_time=None, speed_log_filename=None, minimum_previous_tests=None, std_deviations_limit=None, speed_min_mbps=None, minimum_download_time=None, latency_url=None, latency_limit_ms=None, min_percent_battery=None, min_remaining_time_mins=None)

Bases: object

A class for performing CPU-related checks and tests.

Methods:

check_no_pending_reboot(): Returns boolean indicating if the PC has no pending reboots.

check_enough_disk_space(): Returns boolean indicating if there is enough disk space.

check_enough_idle_usage(): Returns boolean indicating if the CPU has enough idle usage.

check_network_available(): Returns boolean indicating if network is available.

check_good_download_speed(): Returns boolean indicating if the download speed is above a threshold and is not a low outlier.

check_fast_latency(): Returns boolean indicating if latency is fast.

check_enough_battery_charge(): Returns boolean indicating if there is enough battery charge left.

CPUCheck object __init__ constructor:

This method creates the CPUCheck object using multiple input parameters that can be defined explicitly when calling the constructor or if not taken from the ‘config_mode’ key of the ‘config_file’ configuration file, but every parameter from the method signature has to be defined in at least one of the two.

The method checks that all the input parameters have the proper type and if it corresponds it also check if the value is within the corresponding min and max limits. It also starts a logger to store the results of the check methods.

Args:

config_file (str): Path to the configuration file. Default: ‘config/configuration.yml’.

config_mode (str): Configuration mode to use. Default: ‘default’.

logs_folder (str): Path to the folder where logs are stored. The general log filename is based on major system properties to facilitate comparison of results across platforms/computers.

min_gb (float): Minimum required free disk space in GB.

min_percent_disk (float): Minimum required free disk space as a percentage.

folders_to_print (int): Number of largest subfolders to print.

max_cpu_usage (float): Maximum allowed CPU usage percentage.

website_to_check (str): Website URL to check network connectivity.

max_connection_attempts (int): Number of times to attempt connection before giving up.

file_sizes_to_download (list): List of file sizes to download for testing. The full list of sizes from which you can choose is: 1MB, 10MB, 100MB, 1GB, 10GB, 50GB, 100GB, and 1000GB. Although very large files are not recommended due to large download times.

block_size (int): Block size for downloading files.

sleep_time (float): Sleep time between download requests used to avoid overloading the server.

speed_log_filename (str): Name of the download speed log file.

minimum_previous_tests (int): Minimum number of previous download tests to perform comparison between current and previous values obtained.

std_deviations_limit (float): Standard deviations limit for comparing download speeds.

check_good_download_speed will not pass if the current download speed is less than the average speed minus ‘std_deviations_limit’ times the standard deviation of the speed.

speed_min_mbps (float): Minimum required download speed in Mbps.

minimum_download_time (float): Minimum required download time in seconds. In check_good_download_speed, files are downloaded from smaller to larger to ensure that a file is large enough for accurate speed measurement but not too large to take too long. If the download time of a file is more than ‘minimum_download_time’, the final file used to measure the download speed will be the next file in terms of size, which is usually 10 times bigger.

latency_url (str): URL to be used for latency check.

latency_limit_ms (float): High limit in milliseconds for the latency check to pass.

min_percent_battery (float): Minimum battery charge as a percentage.

min_remaining_time_mins (float): Minimum remaining battery charge in minutes.

Example configuration file (‘config/configuration.yml’):

'default':
  # General
  logs_folder: 'logs/'

  # check_enough_disk_space
  min_gb: 2
  min_percent_disk: 10
  folders_to_print: 3

  # check_enough_idle_usage
  max_cpu_usage: 75

  # check_network_available
  website_to_check: 'www.google.com'

  # check_good_download_speed
  max_connection_attempts: 5
  file_sizes_to_download: ['1MB', '10MB', '100MB', '1GB', '10GB']
  block_size: 8192
  sleep_time: 1
  speed_log_filename: 'download_speed_register.txt'
  minimum_previous_tests: 3
  std_deviations_limit: 2
  speed_min_mbps: 1
  minimum_download_time: 3

  # check_fast_latency
  latency_url: 'www.google.com'
  latency_limit_ms: 100

  # check_enough_battery_charge
  min_percent_battery: 10
  min_remaining_time_mins: 15
check_enough_battery_charge()

Checks battery level, plugging, and time remaining.

Returns True if the battery has enough charge and the remaining time is not too low. If not, returns False and checks if the battery is plugged, if it is it recommends to check battery health, if it is not, it recommends to plug it.

check_enough_disk_space()

Checks if there is enough disk space available.

Checks the disk space available, and if the disk space is above the minimum limit and the fraction of free space is above the minimum required then it returns True

If there is no enough space it gives you a hint on how to free space indicating the largest home subfolders.

check_enough_idle_usage()

Returns True if the CPU has enough idle usage.

check_fast_latency()

Checks if the latency is fast measuring the average value to the given host.

It also prints a quality flag associated to the latency value according to genelrally acceted benchmarks

check_good_download_speed()

Perform download speed tests and return the result.

The download speed test is performed by downloading files of different sizes from a predefined URL. The download speed is calculated and compared against specified thresholds to determine if the test passes or fails. If the file is sucessfuly downloaded, the download speed is above the minimum limit, and the speed is not a low outlier compared to previous results, the method returns True, if not it results False.

Returns:

bool: True if the download speed test suceeds, False otherwise.

Raises:

AssertionError: If the logs folder is not a directory.

check_network_available()

Return True if it suceeds to resolve the given URL, and False otherwise.

check_no_pending_reboot()

Returns True if the computer has no pending reboots and False if it has

cpu_health_checks.cpu_health.main(**kwargs)

The main function to execute the cpu checks based on the provided configuration.

It starts by instantiating a CPUCheck object which by default (no kwargs provided at call time) is done taking all the input parameters from the ‘default’ main key of the configuration file config/configuration.yml. Then, if any kwarg is provided when calling the function, that parameter overrides the value in the configuration file.

Then it runs a series of cpu health checks, which return True if the test pass and False otherwise. Finally it prints and logs the results indicating how many checks passed/failed.

The list of checks to run is: [check_no_pending_reboot, check_enough_disk_space, check_enough_idle_usage, check_network_available, check_good_download_speed, and check_enough_battery_charge]. But if check_network_available fails (returns False), check_good_download_speed and check_fast_latency are not run and it is set automatically to failed. Also the test check_enough_battery_charge is automatically skipped if there is no battery information available (which probably means the code is beign run on a desktop).

Args:
kwargs: Series of optional kwargs to be used for instantiating the CPUCheck object.

These parameters have to be part of the CPUCheck.__init__ signature (see help CPUCheck.__init__ for more information), and they override the value present in the configuration file.

Returns:
dict: Dictionary whose keys are the name of the checks performed and the values

correspond to the result of each test

Raises:
TypeError: If any kwargs are not part of the parameters used

to instantiate the CPUCheck object.

Examples:

# Example 1: Running main without any kwargs

>>> results = main()
>>> result
{'check_no_pending_reboot': True, 'check_enough_disk_space': True, ...}

# Example 2: Running main with specific (and extreme) kwargs

>>> results = main(min_percent_disk=100, max_cpu_usage=100)
>>> result
{..., 'check_enough_disk_space': False, 'check_enough_idle_usage': True, ...}

utilities Complementary Module

cpu_health_checks.utilities.check_arguments_validity(arguments)

Check the validity of input arguments based on their types and specified boundaries.

Args:

arguments (dict): A dictionary containing the input arguments and their values.

Raises:

TypeError: If an argument’s value does not match the allowed types. ValueError: If an argument’s value is outside the specified minimum or maximum bounds.

Returns:

None

cpu_health_checks.utilities.determines_log_filename()

Determines the log filename based on major system properties.

This way we can facilitate the comparison between the performance of the different test across different machines.

cpu_health_checks.utilities.downloads_file(url, block_size, max_attempts, logger, track_progress)

Performs a null download of the file in the url.

File is downloaded by splitting it into blocks, trying (max_attempts) of times to establish connection. If it doesn’t work it returns False and logs an error. If it succeeds returns True If track_progress is True then it displays a progress bar while downloading.

cpu_health_checks.utilities.get_configured_logger(log_object_name, log_file_name)

Configures a logger with RotatingFileHandler and retrieves it.

cpu_health_checks.utilities.get_folder_size(folder)

Get the size of a folder in bytes.

Args:

folder (str): Path to the folder.

Returns:

int: Size of the folder in bytes.

cpu_health_checks.utilities.get_home_subfolder_info()

Get information about the home subfolders.

Returns:

dict: A dict containing the home subfolders names and sizes.

cpu_health_checks.utilities.get_input_params(function_params, function_values, config_file, config_mode)

Gets the input parameters to be used for a given function.

It used the parameters explicitly defined when calling the function and if not it uses the ones present in a configuration file, but all the parameters of the function signature have to be present in one of those two.

cpu_health_checks.utilities.get_largest_subfolders(folders_to_print, subfolders_sizes)

Get the largest subfolders based on their sizes.

Args:

folders_to_print (int): The number of folders to print. subfolders_sizes (dict): A dictionary containing subfolder sizes.

Returns:

list: A list of tuples containing the largest subfolders and their sizes.

cpu_health_checks.utilities.get_megas(size)

Convert a string with bytes info into the number of corresponding mega bytes

cpu_health_checks.utilities.handle_final_download_test(logs_folder, speed_log_filename, size, download_time, download_speed_mbps, minimum_previous_tests, std_deviations_limit, speed_min_mbps)

Handles the result of the download used to measure speed.

This function stores the value in the speed logs, and checks if the speed is below the absolute minimum threshold or if it is too slow compared to usual values obtained if there are enough previous tests to make a significant comparison.

Args:

logs_folder (str): The folder to store the log files.

speed_log_filename (str): The name of the speed log file.

size (str): The size of the file downloaded to measure speed.

download_time (float): The download time in seconds.

download_speed_mbps (float): The download speed in Mbps.

minimum_previous_tests (int): The minimum number of previous tests required to compare current results with results usually obtained.

std_deviations_limit (int): The number of standard deviations used for comparison. If the current download speed is less than the average speed minus ‘std_deviations_limit’ times the standard deviation of the speed, this function returns False which implied that check_download_speed will not pass.

speed_min_mbps (float): The minimum download speed threshold in Mbps.

Returns:

bool: True if there is an error, False otherwise.

cpu_health_checks.utilities.load_configuration(config_file, config_mode)

Load configuration from a YAML file based on the specified mode.

Args:

config_file (str): The path to the configuration file. config_mode (str): The mode to select from the configuration file.

Returns:

dict or None: The configuration dictionary for the given mode, or None if an error occurs.

cpu_health_checks.utilities.print_and_log_result(result, message_passed, message_failed, logger)

Performs the common practice that based on the result of a check we print a message if result is True, or an error if result is False, and then log the corresponding message as info.

cpu_health_checks.utilities.print_error(message, new_line=True)

Print an error message in red color.

cpu_health_checks.utilities.print_message(message, new_line=True)

Print a message in green color.

cpu_health_checks.utilities.print_warning(message)

Print a warning message in yellow color.

cpu_health_checks.utilities.run_command(command)

Run a command in the shell and capture the output.

Args:

command (str): The command to run.

Returns:

CompletedProcess: The result of running the command.