computer-playbook/roles/system-maintenance-service-freezer/files/system-maintenance-service-freezer.py

186 lines
6.8 KiB
Python
Raw Normal View History

import argparse
import subprocess
import time
2023-12-14 00:15:01 +01:00
import os
from datetime import datetime
# Global variable definition
BREAK_TIME_SECONDS = 5
FREEZER_SERVICES_PREFIX="system-maintenance-service-"
class AttemptException(Exception):
"""A custom exception for maximum number of attempts."""
pass
2023-12-14 16:29:11 +01:00
def parse_time_to_seconds(time_str):
2023-12-14 18:19:44 +01:00
"""
Convert a time string (e.g., '1h', '30min', '45s') to seconds.
"""
2023-12-14 16:29:11 +01:00
units = {"s": 1, "min": 60, "h": 3600}
if time_str[-3:] in units:
number, unit = time_str[:-3], time_str[-3:]
elif time_str[-2:] in units:
number, unit = time_str[:-2], time_str[-2:]
elif time_str[-1:] in units:
number, unit = time_str[:-1], time_str[-1:]
else:
2023-12-14 16:29:11 +01:00
raise ValueError("Invalid time unit")
return int(number) * units[unit]
2023-12-14 00:15:01 +01:00
def service_file_exists(service_name, service_type="service"):
2023-12-14 18:19:44 +01:00
"""
Check if a systemd service file of a given type exists for a service.
"""
2023-12-14 00:15:01 +01:00
path = "/etc/systemd/system/"
2023-12-14 18:19:44 +01:00
service_file_name = f"{service_name}.{service_type}"
2023-12-14 00:15:01 +01:00
full_path = os.path.join(path, service_file_name)
2023-12-14 18:19:44 +01:00
# Debug output for checking the service file existence
print(f"Checking {full_path}")
return os.path.isfile(full_path)
def check_service_active(service_name):
2023-12-14 18:19:44 +01:00
"""
Check if a systemd service is currently active or activating.
"""
result = subprocess.run(['systemctl', 'is-active', service_name], stdout=subprocess.PIPE)
2023-12-14 00:15:01 +01:00
service_status = result.stdout.decode('utf-8').strip()
2023-12-14 18:19:44 +01:00
is_active = service_status in ['active', 'activating']
print(f"Service {service_name} is {'active' if is_active else 'not active'}.")
return is_active
def check_any_service_active(services):
2023-12-14 18:19:44 +01:00
"""
Check if any service in a given list is active or activating.
"""
return any(check_service_active(service) for service in services)
2023-12-15 08:27:41 +01:00
def manage_timer(service, action):
"""
Manage a systemd timer for a service.
action can be 'start' or 'stop'.
"""
if action not in ['start', 'stop']:
raise ValueError("Invalid action specified for manage_timer")
timer_name = f"{service}.timer"
subprocess.run(['systemctl', action, timer_name])
if action == 'start':
subprocess.run(['systemctl', 'enable', timer_name])
elif action == 'stop':
subprocess.run(['systemctl', 'disable', timer_name])
print(f"{timer_name} {action}ed and {'enabled' if action == 'start' else 'disabled'}.")
def stop_timer(service):
2023-12-14 18:19:44 +01:00
"""
Stop and disable a systemd timer for a service if it exists.
"""
if service == f"{FREEZER_SERVICES_PREFIX}defrost":
print(f"Ignoring {service}. It's the initializer of freezer.")
2023-12-14 21:12:25 +01:00
if service_file_exists(service, "timer"):
2023-12-15 08:27:41 +01:00
manage_timer(service, 'stop')
else:
2023-12-15 08:27:41 +01:00
print(f"Timer {service}.timer does not exist.")
def filter_services(services, ignored_services):
"""
2023-12-14 18:19:44 +01:00
Filter out services that are in the ignored_services list from services list.
"""
return [service for service in services if service not in ignored_services]
def stop_all_timers(services):
2023-12-14 18:19:44 +01:00
"""
Stop and disable timers for all services in a given list.
"""
for service in services:
stop_timer(service)
def wait_for_all_services_to_stop(filtered_services, max_attempts, attempt):
2023-12-14 18:19:44 +01:00
"""
Wait until all services in the list have stopped, with a maximum number of attempts.
"""
for service in filtered_services:
while check_service_active(service):
attempt += 1
if attempt > max_attempts:
raise AttemptException(f"Maximum attempts ({max_attempts}) reached. Exiting.")
print(f"{datetime.now().isoformat()}#{attempt}/{max_attempts}: Waiting for {BREAK_TIME_SECONDS} seconds for {service} to stop...")
time.sleep(BREAK_TIME_SECONDS)
return attempt
2023-12-14 18:19:44 +01:00
def freeze(filtered_services, timeout_sec):
"""
Freeze services by stopping them and their timers, waiting up to a timeout.
"""
attempt = 0
max_attempts = get_max_attempts(timeout_sec)
while check_any_service_active(filtered_services):
stop_all_timers(filtered_services)
attempt = wait_for_all_services_to_stop(filtered_services, max_attempts, attempt)
2023-12-14 18:19:44 +01:00
print("All required services have stopped.")
def get_max_attempts(timeout_sec):
return timeout_sec // BREAK_TIME_SECONDS
2023-12-15 01:04:14 +01:00
def defrost(filtered_services,timeout_sec):
2023-12-14 18:19:44 +01:00
"""
Defrost services by starting and enabling their timers.
"""
2023-12-15 08:27:41 +01:00
running_service = f"{FREEZER_SERVICES_PREFIX}defrost"
attempt = 0
max_attempts = get_max_attempts(timeout_sec)
try:
wait_for_all_services_to_stop(filtered_services, max_attempts, attempt)
except AttemptException as e:
print(e)
print("Defrosting was not possible. The execution of other services took to long.")
2023-12-15 08:27:41 +01:00
manage_timer(running_service, "stop")
exit(0)
for service in filtered_services + [running_service]:
2023-12-14 18:19:44 +01:00
print(f"Unfreezing: {service}")
if service_file_exists(service, "timer"):
2023-12-15 08:27:41 +01:00
manage_timer(service, "start")
2023-12-14 00:15:01 +01:00
else:
2023-12-14 18:19:44 +01:00
print("No timer to activate for service.")
print("All required services are started.")
def main(services, ignored_services, action, timeout_sec):
2023-12-14 18:19:44 +01:00
"""
Main function to process the command-line arguments and perform actions.
"""
2023-12-14 21:12:25 +01:00
# Ignoring the current running service
running_service=f"{FREEZER_SERVICES_PREFIX}{action}"
2023-12-14 21:12:25 +01:00
if running_service not in ignored_services:
ignored_services.append(running_service)
2023-12-14 18:19:44 +01:00
filtered_services = filter_services(services, ignored_services)
print(f"Services to handle: {services}")
print(f"Services to ignore: {ignored_services}")
print(f"Services filtered: {filtered_services}")
if action == 'freeze':
2023-12-14 18:19:44 +01:00
print("Freezing services.")
freeze(filtered_services, timeout_sec)
elif action == 'defrost':
2023-12-14 18:19:44 +01:00
print("Unfreezing services.")
defrost(filtered_services, timeout_sec)
2023-12-14 18:19:44 +01:00
print("Overview:")
2023-12-14 00:15:01 +01:00
subprocess.run(['systemctl', 'list-timers'])
if __name__ == "__main__":
2023-12-14 18:19:44 +01:00
parser = argparse.ArgumentParser(description='Freezes and defrosts systemd services and timers.')
parser.add_argument('action', choices=['freeze', 'defrost'], help='Action to perform: freeze or defrost services.')
2023-12-14 18:19:44 +01:00
parser.add_argument('services', nargs='+', help='List of services to apply the action to.')
parser.add_argument('--ignore', nargs='*', help='List of services to ignore in the action.', default=[])
parser.add_argument('--timeout', help='Timeout for freezing services (e.g., 1h, 30min, 45s).', default='1h')
args = parser.parse_args()
services = args.services
2023-12-14 16:29:11 +01:00
ignored_services = args.ignore if args.ignore else []
timeout_seconds = parse_time_to_seconds(args.timeout)
main(services, ignored_services, args.action, timeout_seconds)