Files
ProxLB/proxlb
2024-07-21 11:41:13 +02:00

793 lines
40 KiB
Python
Executable File

#!/usr/bin/env python3
# ProxLB
# ProxLB (re)balances VM workloads across nodes in Proxmox clusters.
# ProxLB obtains current metrics from all nodes within the cluster for
# further auto balancing by memory, disk or cpu and rebalances the VMs
# over all available nodes in a cluster by having an equal resource usage.
# Copyright (C) 2024 Florian Paul Azim Hoberg @gyptazy <gyptazy@gyptazy.ch>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import configparser
import json
import logging
import os
try:
import proxmoxer
_imports = True
except ImportError:
_imports = False
import random
import re
import requests
import sys
import time
import urllib3
# Constants
__appname__ = "ProxLB"
__version__ = "0.9.9"
__author__ = "Florian Paul Azim Hoberg <gyptazy@gyptazy.ch> @gyptazy"
__errors__ = False
# Classes
## Logging class
class SystemdHandler(logging.Handler):
""" Class to handle logging options. """
PREFIX = {
logging.CRITICAL: "<2> " + __appname__ + ": ",
logging.ERROR: "<3> " + __appname__ + ": ",
logging.WARNING: "<4> " + __appname__ + ": ",
logging.INFO: "<6> " + __appname__ + ": ",
logging.DEBUG: "<7> " + __appname__ + ": ",
logging.NOTSET: "<7 " + __appname__ + ": ",
}
def __init__(self, stream=sys.stdout):
self.stream = stream
logging.Handler.__init__(self)
def emit(self, record):
try:
msg = self.PREFIX[record.levelno] + self.format(record) + "\n"
self.stream.write(msg)
self.stream.flush()
except Exception:
self.handleError(record)
# Functions
def initialize_logger(log_level, update_log_verbosity=False):
""" Initialize ProxLB logging handler. """
info_prefix = 'Info: [logger]:'
root_logger = logging.getLogger()
root_logger.setLevel(log_level)
if not update_log_verbosity:
root_logger.addHandler(SystemdHandler())
logging.info(f'{info_prefix} Logger got initialized.')
else:
logging.info(f'{info_prefix} Logger verbosity got updated to: {log_level}.')
def pre_validations(config_path):
""" Run pre-validations as sanity checks. """
info_prefix = 'Info: [pre-validations]:'
__validate_imports()
__validate_config_file(config_path)
logging.info(f'{info_prefix} All pre-validations done.')
def post_validations():
""" Run post-validations as sanity checks. """
error_prefix = 'Error: [post-validations]:'
info_prefix = 'Info: [post-validations]:'
if __errors__:
logging.critical(f'{error_prefix} Not all post-validations succeeded. Please validate!')
else:
logging.info(f'{info_prefix} All post-validations succeeded.')
def validate_daemon(daemon, schedule):
""" Validate if ProxLB runs as a daemon. """
info_prefix = 'Info: [daemon]:'
if bool(int(daemon)):
logging.info(f'{info_prefix} Running in daemon mode. Next run in {schedule} hours.')
time.sleep(int(schedule) * 60)
else:
logging.info(f'{info_prefix} Not running in daemon mode. Quitting.')
sys.exit(0)
def __validate_imports():
""" Validate if all Python imports succeeded. """
error_prefix = 'Error: [python-imports]:'
info_prefix = 'Info: [python-imports]:'
if not _imports:
logging.critical(f'{error_prefix} Could not import all dependencies. Please install "proxmoxer".')
sys.exit(2)
else:
logging.info(f'{info_prefix} All required dependencies were imported.')
def __validate_config_file(config_path):
""" Validate if all Python imports succeeded. """
error_prefix = 'Error: [config]:'
info_prefix = 'Info: [config]:'
if not os.path.isfile(config_path):
logging.critical(f'{error_prefix} Could not find config file in: {config_path}.')
sys.exit(2)
else:
logging.info(f'{info_prefix} Configuration file loaded from: {config_path}.')
def initialize_args():
""" Initialize given arguments for ProxLB. """
argparser = argparse.ArgumentParser(description='ProxLB')
argparser.add_argument('-c', '--config', type=str, help='Path to config file.', required=True)
argparser.add_argument('-d', '--dry-run', help='Perform a dry-run without doing any actions.', action='store_true', required=False)
argparser.add_argument('-j', '--json', help='Return a JSON of the VM movement.', action='store_true', required=False)
return argparser.parse_args()
def initialize_config_path(app_args):
""" Initialize path to ProxLB config file. """
info_prefix = 'Info: [config]:'
config_path = app_args.config
if app_args.config is None:
config_path = '/etc/proxlb/proxlb.conf'
logging.info(f'{info_prefix} No config file provided. Falling back to: {config_path}.')
else:
logging.info(f'{info_prefix} Using config file: {config_path}.')
return config_path
def initialize_config_options(config_path):
""" Read configuration from given config file for ProxLB. """
error_prefix = 'Error: [config]:'
info_prefix = 'Info: [config]:'
try:
config = configparser.ConfigParser()
config.read(config_path)
# Proxmox config
proxmox_api_host = config['proxmox']['api_host']
proxmox_api_user = config['proxmox']['api_user']
proxmox_api_pass = config['proxmox']['api_pass']
proxmox_api_ssl_v = config['proxmox']['verify_ssl']
# Balancing
balancing_method = config['balancing'].get('method', 'memory')
balancing_mode = config['balancing'].get('mode', 'used')
balancing_type = config['balancing'].get('type', 'vm')
balanciness = config['balancing'].get('balanciness', 10)
ignore_nodes = config['balancing'].get('ignore_nodes', None)
ignore_vms = config['balancing'].get('ignore_vms', None)
# Service
daemon = config['service'].get('daemon', 1)
schedule = config['service'].get('schedule', 24)
log_verbosity = config['service'].get('log_verbosity', 'CRITICAL')
except configparser.NoSectionError:
logging.critical(f'{error_prefix} Could not find the required section.')
sys.exit(2)
except configparser.ParsingError:
logging.critical(f'{error_prefix} Unable to parse the config file.')
sys.exit(2)
except KeyError:
logging.critical(f'{error_prefix} Could not find the required options in config file.')
sys.exit(2)
logging.info(f'{info_prefix} Configuration file loaded.')
return proxmox_api_host, proxmox_api_user, proxmox_api_pass, proxmox_api_ssl_v, balancing_method, \
balancing_mode, balancing_type, balanciness, ignore_nodes, ignore_vms, daemon, schedule, log_verbosity
def api_connect(proxmox_api_host, proxmox_api_user, proxmox_api_pass, proxmox_api_ssl_v):
""" Connect and authenticate to the Proxmox remote API. """
error_prefix = 'Error: [api-connection]:'
warn_prefix = 'Warning: [api-connection]:'
info_prefix = 'Info: [api-connection]:'
proxmox_api_ssl_v = bool(int(proxmox_api_ssl_v))
if not proxmox_api_ssl_v:
requests.packages.urllib3.disable_warnings()
logging.warning(f'{warn_prefix} API connection does not verify SSL certificate.')
try:
api_object = proxmoxer.ProxmoxAPI(proxmox_api_host, user=proxmox_api_user, password=proxmox_api_pass, verify_ssl=proxmox_api_ssl_v)
except urllib3.exceptions.NameResolutionError:
logging.critical(f'{error_prefix} Could not resolve the given host: {proxmox_api_host}.')
sys.exit(2)
except requests.exceptions.ConnectTimeout:
logging.critical(f'{error_prefix} Connection time out to host: {proxmox_api_host}.')
sys.exit(2)
except requests.exceptions.SSLError:
logging.critical(f'{error_prefix} SSL certificate verification failed for host: {proxmox_api_host}.')
sys.exit(2)
logging.info(f'{info_prefix} API connection succeeded to host: {proxmox_api_host}.')
return api_object
def get_node_statistics(api_object, ignore_nodes):
""" Get statistics of cpu, memory and disk for each node in the cluster. """
info_prefix = 'Info: [node-statistics]:'
node_statistics = {}
ignore_nodes_list = ignore_nodes.split(',')
for node in api_object.nodes.get():
if node['status'] == 'online' and node['node'] not in ignore_nodes_list:
node_statistics[node['node']] = {}
node_statistics[node['node']]['cpu_total'] = node['maxcpu']
node_statistics[node['node']]['cpu_assigned'] = node['cpu']
node_statistics[node['node']]['cpu_assigned_percent'] = int((node_statistics[node['node']]['cpu_assigned']) / int(node_statistics[node['node']]['cpu_total']) * 100)
node_statistics[node['node']]['cpu_assigned_percent_last_run'] = 0
node_statistics[node['node']]['cpu_used'] = 0
node_statistics[node['node']]['cpu_free'] = int(node['maxcpu']) - int(node['cpu'])
node_statistics[node['node']]['cpu_free_percent'] = int((node_statistics[node['node']]['cpu_free']) / int(node['maxcpu']) * 100)
node_statistics[node['node']]['cpu_free_percent_last_run'] = 0
node_statistics[node['node']]['memory_total'] = node['maxmem']
node_statistics[node['node']]['memory_assigned'] = 0
node_statistics[node['node']]['memory_assigned_percent'] = int((node_statistics[node['node']]['memory_assigned']) / int(node_statistics[node['node']]['memory_total']) * 100)
node_statistics[node['node']]['memory_assigned_percent_last_run'] = 0
node_statistics[node['node']]['memory_used'] = node['mem']
node_statistics[node['node']]['memory_free'] = int(node['maxmem']) - int(node['mem'])
node_statistics[node['node']]['memory_free_percent'] = int((node_statistics[node['node']]['memory_free']) / int(node['maxmem']) * 100)
node_statistics[node['node']]['memory_free_percent_last_run'] = 0
node_statistics[node['node']]['disk_total'] = node['maxdisk']
node_statistics[node['node']]['disk_assigned'] = 0
node_statistics[node['node']]['disk_assigned_percent'] = int((node_statistics[node['node']]['disk_assigned']) / int(node_statistics[node['node']]['disk_total']) * 100)
node_statistics[node['node']]['disk_assigned_percent_last_run'] = 0
node_statistics[node['node']]['disk_used'] = node['disk']
node_statistics[node['node']]['disk_free'] = int(node['maxdisk']) - int(node['disk'])
node_statistics[node['node']]['disk_free_percent'] = int((node_statistics[node['node']]['disk_free']) / int(node['maxdisk']) * 100)
node_statistics[node['node']]['disk_free_percent_last_run'] = 0
logging.info(f'{info_prefix} Added node {node["node"]}.')
logging.info(f'{info_prefix} Created node statistics.')
return node_statistics
def get_vm_statistics(api_object, ignore_vms, balancing_type):
""" Get statistics of cpu, memory and disk for each vm in the cluster. """
info_prefix = 'Info: [vm-statistics]:'
warn_prefix = 'Warn: [vm-statistics]:'
vm_statistics = {}
ignore_vms_list = ignore_vms.split(',')
group_include = None
group_exclude = None
vm_ignore = None
vm_ignore_wildcard = False
# Wildcard support: Initially validate if we need to honour
# any wildcards within the vm_ignore list.
vm_ignore_wildcard = __validate_ignore_vm_wildcard(ignore_vms)
for node in api_object.nodes.get():
# Add all virtual machines if type is vm or all.
if balancing_type == 'vm' or balancing_type == 'all':
for vm in api_object.nodes(node['node']).qemu.get():
# Get the VM tags from API.
vm_tags = __get_vm_tags(api_object, node, vm['vmid'], 'vm')
if vm_tags is not None:
group_include, group_exclude, vm_ignore = __get_proxlb_groups(vm_tags)
# Get wildcard match for VMs to ignore if a wildcard pattern was
# previously found. Wildcards may slow down the task when using
# many patterns in the ignore list. Therefore, run this only if
# a wildcard pattern was found. We also do not need to validate
# this if the VM is already being ignored by a defined tag.
if vm_ignore_wildcard and not vm_ignore:
vm_ignore = __check_vm_name_wildcard_pattern(vm['name'], ignore_vms_list)
if vm['status'] == 'running' and vm['name'] not in ignore_vms_list and not vm_ignore:
vm_statistics[vm['name']] = {}
vm_statistics[vm['name']]['group_include'] = group_include
vm_statistics[vm['name']]['group_exclude'] = group_exclude
vm_statistics[vm['name']]['cpu_total'] = vm['cpus']
vm_statistics[vm['name']]['cpu_used'] = vm['cpu']
vm_statistics[vm['name']]['memory_total'] = vm['maxmem']
vm_statistics[vm['name']]['memory_used'] = vm['mem']
vm_statistics[vm['name']]['disk_total'] = vm['maxdisk']
vm_statistics[vm['name']]['disk_used'] = vm['disk']
vm_statistics[vm['name']]['vmid'] = vm['vmid']
vm_statistics[vm['name']]['node_parent'] = node['node']
vm_statistics[vm['name']]['type'] = 'vm'
# Rebalancing node will be overwritten after calculations.
# If the vm stays on the node, it will be removed at a
# later time.
vm_statistics[vm['name']]['node_rebalance'] = node['node']
logging.info(f'{info_prefix} Added vm {vm["name"]}.')
# Add all containers if type is ct or all.
if balancing_type == 'ct' or balancing_type == 'all':
for vm in api_object.nodes(node['node']).lxc.get():
logging.warning(f'{warn_prefix} Rebalancing on LXC containers (CT) always requires them to shut down.')
logging.warning(f'{warn_prefix} {vm["name"]} is from type CT and cannot be live migrated!')
# Get the VM tags from API.
vm_tags = __get_vm_tags(api_object, node, vm['vmid'], 'ct')
if vm_tags is not None:
group_include, group_exclude, vm_ignore = __get_proxlb_groups(vm_tags)
# Get wildcard match for VMs to ignore if a wildcard pattern was
# previously found. Wildcards may slow down the task when using
# many patterns in the ignore list. Therefore, run this only if
# a wildcard pattern was found. We also do not need to validate
# this if the VM is already being ignored by a defined tag.
if vm_ignore_wildcard and not vm_ignore:
vm_ignore = __check_vm_name_wildcard_pattern(vm['name'], ignore_vms_list)
if vm['status'] == 'running' and vm['name'] not in ignore_vms_list and not vm_ignore:
vm_statistics[vm['name']] = {}
vm_statistics[vm['name']]['group_include'] = group_include
vm_statistics[vm['name']]['group_exclude'] = group_exclude
vm_statistics[vm['name']]['cpu_total'] = vm['cpus']
vm_statistics[vm['name']]['cpu_used'] = vm['cpu']
vm_statistics[vm['name']]['memory_total'] = vm['maxmem']
vm_statistics[vm['name']]['memory_used'] = vm['mem']
vm_statistics[vm['name']]['disk_total'] = vm['maxdisk']
vm_statistics[vm['name']]['disk_used'] = vm['disk']
vm_statistics[vm['name']]['vmid'] = vm['vmid']
vm_statistics[vm['name']]['node_parent'] = node['node']
vm_statistics[vm['name']]['type'] = 'ct'
# Rebalancing node will be overwritten after calculations.
# If the vm stays on the node, it will be removed at a
# later time.
vm_statistics[vm['name']]['node_rebalance'] = node['node']
logging.info(f'{info_prefix} Added vm {vm["name"]}.')
logging.info(f'{info_prefix} Created VM statistics.')
return vm_statistics
def update_node_statistics(node_statistics, vm_statistics):
""" Update node statistics by VMs statistics. """
info_prefix = 'Info: [node-update-statistics]:'
warn_prefix = 'Warning: [node-update-statistics]:'
for vm, vm_value in vm_statistics.items():
node_statistics[vm_value['node_parent']]['cpu_assigned'] = node_statistics[vm_value['node_parent']]['cpu_assigned'] + int(vm_value['cpu_total'])
node_statistics[vm_value['node_parent']]['cpu_assigned_percent'] = (node_statistics[vm_value['node_parent']]['cpu_assigned'] / node_statistics[vm_value['node_parent']]['cpu_total']) * 100
node_statistics[vm_value['node_parent']]['memory_assigned'] = node_statistics[vm_value['node_parent']]['memory_assigned'] + int(vm_value['memory_total'])
node_statistics[vm_value['node_parent']]['memory_assigned_percent'] = (node_statistics[vm_value['node_parent']]['memory_assigned'] / node_statistics[vm_value['node_parent']]['memory_total']) * 100
node_statistics[vm_value['node_parent']]['disk_assigned'] = node_statistics[vm_value['node_parent']]['disk_assigned'] + int(vm_value['disk_total'])
node_statistics[vm_value['node_parent']]['disk_assigned_percent'] = (node_statistics[vm_value['node_parent']]['disk_assigned'] / node_statistics[vm_value['node_parent']]['disk_total']) * 100
if node_statistics[vm_value['node_parent']]['cpu_assigned_percent'] > 99:
logging.warning(f'{warn_prefix} Node {vm_value["node_parent"]} is overprovisioned for CPU by {int(node_statistics[vm_value["node_parent"]]["cpu_assigned_percent"])}%.')
if node_statistics[vm_value['node_parent']]['memory_assigned_percent'] > 99:
logging.warning(f'{warn_prefix} Node {vm_value["node_parent"]} is overprovisioned for memory by {int(node_statistics[vm_value["node_parent"]]["memory_assigned_percent"])}%.')
if node_statistics[vm_value['node_parent']]['disk_assigned_percent'] > 99:
logging.warning(f'{warn_prefix} Node {vm_value["node_parent"]} is overprovisioned for disk by {int(node_statistics[vm_value["node_parent"]]["disk_assigned_percent"])}%.')
logging.info(f'{info_prefix} Updated node resource assignments by all VMs.')
logging.debug('node_statistics')
return node_statistics
def __validate_ignore_vm_wildcard(ignore_vms):
""" Validate if a wildcard is used for ignored VMs. """
if '*' in ignore_vms:
return True
def __check_vm_name_wildcard_pattern(vm_name, ignore_vms_list):
""" Validate if the VM name is in the ignore list pattern included. """
for ignore_vm in ignore_vms_list:
if '*' in ignore_vm:
if ignore_vm[:-1] in vm_name:
return True
def __get_vm_tags(api_object, node, vmid, balancing_type):
""" Get tags for a VM/CT for a given VMID. """
info_prefix = 'Info: [api-get-vm-tags]:'
if balancing_type == 'vm':
vm_config = api_object.nodes(node['node']).qemu(vmid).config.get()
if balancing_type == 'ct':
vm_config = api_object.nodes(node['node']).lxc(vmid).config.get()
logging.info(f'{info_prefix} Got VM/CT tag from API.')
return vm_config.get('tags', None)
def __get_proxlb_groups(vm_tags):
""" Get ProxLB related include and exclude groups. """
info_prefix = 'Info: [api-get-vm-include-exclude-tags]:'
group_include = None
group_exclude = None
vm_ignore = None
group_list = re.split(";", vm_tags)
for group in group_list:
if group.startswith('plb_include_'):
logging.info(f'{info_prefix} Got PLB include group.')
group_include = group
if group.startswith('plb_exclude_'):
logging.info(f'{info_prefix} Got PLB include group.')
group_exclude = group
if group.startswith('plb_ignore_vm'):
logging.info(f'{info_prefix} Got PLB ignore group.')
vm_ignore = True
return group_include, group_exclude, vm_ignore
def balancing_calculations(balancing_method, balancing_mode, node_statistics, vm_statistics, balanciness, rebalance, processed_vms):
""" Calculate re-balancing of VMs on present nodes across the cluster. """
info_prefix = 'Info: [rebalancing-calculator]:'
# Validate for a supported balancing method, mode and if rebalancing is required.
__validate_balancing_method(balancing_method)
__validate_balancing_mode(balancing_mode)
rebalance = __validate_balanciness(balanciness, balancing_method, balancing_mode, node_statistics)
if rebalance:
# Get most used/assigned resources of the VM and the most free or less allocated node.
resources_vm_most_used, processed_vms = __get_most_used_resources_vm(balancing_method, balancing_mode, vm_statistics, processed_vms)
resources_node_most_free = __get_most_free_resources_node(balancing_method, balancing_mode, node_statistics)
# Update resource statistics for VMs and nodes.
node_statistics, vm_statistics = __update_resource_statistics(resources_vm_most_used, resources_node_most_free,
vm_statistics, node_statistics, balancing_method, balancing_mode)
# Start recursion until we do not have any needs to rebalance anymore.
balancing_calculations(balancing_method, balancing_mode, node_statistics, vm_statistics, balanciness, rebalance, processed_vms)
# Honour groupings for include and exclude groups for rebalancing VMs.
node_statistics, vm_statistics = __get_vm_tags_include_groups(vm_statistics, node_statistics, balancing_method, balancing_mode)
node_statistics, vm_statistics = __get_vm_tags_exclude_groups(vm_statistics, node_statistics, balancing_method, balancing_mode)
# Remove VMs that are not being relocated.
vms_to_remove = [vm_name for vm_name, vm_info in vm_statistics.items() if 'node_rebalance' in vm_info and vm_info['node_rebalance'] == vm_info.get('node_parent')]
for vm_name in vms_to_remove:
del vm_statistics[vm_name]
logging.info(f'{info_prefix} Balancing calculations done.')
return node_statistics, vm_statistics
def __validate_balancing_method(balancing_method):
""" Validate for valid and supported balancing method. """
error_prefix = 'Error: [balancing-method-validation]:'
info_prefix = 'Info: [balancing-method-validation]]:'
if balancing_method not in ['memory', 'disk', 'cpu']:
logging.error(f'{error_prefix} Invalid balancing method: {balancing_method}')
sys.exit(2)
else:
logging.info(f'{info_prefix} Valid balancing method: {balancing_method}')
def __validate_balancing_mode(balancing_mode):
""" Validate for valid and supported balancing mode. """
error_prefix = 'Error: [balancing-mode-validation]:'
info_prefix = 'Info: [balancing-mode-validation]]:'
if balancing_mode not in ['used', 'assigned']:
logging.error(f'{error_prefix} Invalid balancing method: {balancing_mode}')
sys.exit(2)
else:
logging.info(f'{info_prefix} Valid balancing method: {balancing_mode}')
def __validate_balanciness(balanciness, balancing_method, balancing_mode, node_statistics):
""" Validate for balanciness to ensure further rebalancing is needed. """
info_prefix = 'Info: [balanciness-validation]:'
node_resource_percent_list = []
node_assigned_percent_match = []
# Remap balancing mode to get the related values from nodes dict.
if balancing_mode == 'used':
node_resource_selector = 'free'
if balancing_mode == 'assigned':
node_resource_selector = 'assigned'
for node_name, node_info in node_statistics.items():
# Save information of nodes from current run to compare them in the next recursion.
if node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent_last_run'] == node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent']:
node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent_match'] = True
else:
node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent_match'] = False
# Update value to the current value of the recursion run.
node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent_last_run'] = node_statistics[node_name][f'{balancing_method}_{node_resource_selector}_percent']
# If all node resources are unchanged, the recursion can be left.
for key, value in node_statistics.items():
node_assigned_percent_match.append(value.get(f'{balancing_method}_{node_resource_selector}_percent_match', False))
if False not in node_assigned_percent_match:
return False
# Add node information to resource list.
node_resource_percent_list.append(int(node_info[f'{balancing_method}_{node_resource_selector}_percent']))
logging.debug(f'{info_prefix} Node: {node_name} with values: {node_info}')
# Create a sorted list of the delta + balanciness between the node resources.
node_resource_percent_list_sorted = sorted(node_resource_percent_list)
node_lowest_percent = node_resource_percent_list_sorted[0]
node_highest_percent = node_resource_percent_list_sorted[-1]
# Validate if the recursion should be proceeded for further rebalancing.
if (int(node_lowest_percent) + int(balanciness)) < int(node_highest_percent):
logging.info(f'{info_prefix} Rebalancing for {balancing_method} is needed. Highest usage: {int(node_highest_percent)}% | Lowest usage: {int(node_lowest_percent)}%.')
return True
else:
logging.info(f'{info_prefix} Rebalancing for {balancing_method} is not needed. Highest usage: {int(node_highest_percent)}% | Lowest usage: {int(node_lowest_percent)}%.')
return False
def __get_most_used_resources_vm(balancing_method, balancing_mode, vm_statistics, processed_vms):
""" Get and return the most used resources of a VM by the defined balancing method. """
info_prefix = 'Info: [get-most-used-resources-vm]:'
# Remap balancing mode to get the related values from nodes dict.
if balancing_mode == 'used':
vm_resource_selector = 'used'
if balancing_mode == 'assigned':
vm_resource_selector = 'total'
vm = max(vm_statistics.items(), key=lambda item: item[1][f'{balancing_method}_{vm_resource_selector}'] if item[0] not in processed_vms else -float('inf'))
processed_vms.append(vm[0])
logging.info(f'{info_prefix} {vm}')
return vm, processed_vms
def __get_most_free_resources_node(balancing_method, balancing_mode, node_statistics):
""" Get and return the most free resources of a node by the defined balancing method. """
info_prefix = 'Info: [get-most-free-resources-nodes]:'
# Return the node information based on the balancing mode.
if balancing_mode == 'used':
node = max(node_statistics.items(), key=lambda item: item[1][f'{balancing_method}_free'])
if balancing_mode == 'assigned':
node = min(node_statistics.items(), key=lambda item: item[1][f'{balancing_method}_assigned'] if item[1][f'{balancing_method}_assigned_percent'] > 0 or item[1][f'{balancing_method}_assigned_percent'] < 100 else -float('inf'))
logging.info(f'{info_prefix} {node}')
return node
def __update_resource_statistics(resource_highest_used_resources_vm, resource_highest_free_resources_node, vm_statistics, node_statistics, balancing_method, balancing_mode):
""" Update VM and node resource statistics. """
info_prefix = 'Info: [rebalancing-resource-statistics-update]:'
if resource_highest_used_resources_vm[1]['node_parent'] != resource_highest_free_resources_node[0]:
vm_name = resource_highest_used_resources_vm[0]
vm_node_parent = resource_highest_used_resources_vm[1]['node_parent']
vm_node_rebalance = resource_highest_free_resources_node[0]
vm_resource_used = vm_statistics[resource_highest_used_resources_vm[0]][f'{balancing_method}_used']
vm_resource_total = vm_statistics[resource_highest_used_resources_vm[0]][f'{balancing_method}_total']
# Update dictionaries for new values
# Assign new rebalance node to vm
vm_statistics[vm_name]['node_rebalance'] = vm_node_rebalance
logging.info(f'Moving {vm_name} from {vm_node_parent} to {vm_node_rebalance}')
# Recalculate values for nodes
## Add freed resources to old parent node
node_statistics[vm_node_parent][f'{balancing_method}_used'] = int(node_statistics[vm_node_parent][f'{balancing_method}_used']) - int(vm_resource_used)
node_statistics[vm_node_parent][f'{balancing_method}_free'] = int(node_statistics[vm_node_parent][f'{balancing_method}_free']) + int(vm_resource_used)
node_statistics[vm_node_parent][f'{balancing_method}_free_percent'] = int(int(node_statistics[vm_node_parent][f'{balancing_method}_free']) / int(node_statistics[vm_node_parent][f'{balancing_method}_total']) * 100)
node_statistics[vm_node_parent][f'{balancing_method}_assigned'] = int(node_statistics[vm_node_parent][f'{balancing_method}_assigned']) - int(vm_resource_total)
node_statistics[vm_node_parent][f'{balancing_method}_assigned_percent'] = int(int(node_statistics[vm_node_parent][f'{balancing_method}_assigned']) / int(node_statistics[vm_node_parent][f'{balancing_method}_total']) * 100)
## Removed newly allocated resources to new rebalanced node
node_statistics[vm_node_rebalance][f'{balancing_method}_used'] = int(node_statistics[vm_node_rebalance][f'{balancing_method}_used']) + int(vm_resource_used)
node_statistics[vm_node_rebalance][f'{balancing_method}_free'] = int(node_statistics[vm_node_rebalance][f'{balancing_method}_free']) - int(vm_resource_used)
node_statistics[vm_node_rebalance][f'{balancing_method}_free_percent'] = int(int(node_statistics[vm_node_rebalance][f'{balancing_method}_free']) / int(node_statistics[vm_node_rebalance][f'{balancing_method}_total']) * 100)
node_statistics[vm_node_rebalance][f'{balancing_method}_assigned'] = int(node_statistics[vm_node_rebalance][f'{balancing_method}_assigned']) + int(vm_resource_total)
node_statistics[vm_node_rebalance][f'{balancing_method}_assigned_percent'] = int(int(node_statistics[vm_node_rebalance][f'{balancing_method}_assigned']) / int(node_statistics[vm_node_rebalance][f'{balancing_method}_total']) * 100)
logging.info(f'{info_prefix} Updated VM and node statistics.')
return node_statistics, vm_statistics
def __get_vm_tags_include_groups(vm_statistics, node_statistics, balancing_method, balancing_mode):
""" Get VMs tags for include groups. """
info_prefix = 'Info: [rebalancing-tags-group-include]:'
tags_include_vms = {}
processed_vm = []
# Create groups of tags with belongings hosts.
for vm_name, vm_values in vm_statistics.items():
if vm_values.get('group_include', None):
if not tags_include_vms.get(vm_values['group_include'], None):
tags_include_vms[vm_values['group_include']] = [vm_name]
else:
tags_include_vms[vm_values['group_include']] = tags_include_vms[vm_values['group_include']] + [vm_name]
# Update the VMs to the corresponding node to their group assignments.
for group, vm_names in tags_include_vms.items():
# Do not take care of tags that have only a single host included.
if len(vm_names) < 2:
logging.info(f'{info_prefix} Only one host in group assignment.')
return node_statistics, vm_statistics
vm_node_rebalance = False
logging.info(f'{info_prefix} Create include groups of VM hosts.')
for vm_name in vm_names:
if vm_name not in processed_vm:
if not vm_node_rebalance:
vm_node_rebalance = vm_statistics[vm_name]['node_rebalance']
else:
_mocked_vm_object = (vm_name, vm_statistics[vm_name])
node_statistics, vm_statistics = __update_resource_statistics(_mocked_vm_object, [vm_node_rebalance], vm_statistics, node_statistics, balancing_method, balancing_mode)
processed_vm.append(vm_name)
return node_statistics, vm_statistics
def __get_vm_tags_exclude_groups(vm_statistics, node_statistics, balancing_method, balancing_mode):
""" Get VMs tags for exclude groups. """
info_prefix = 'Info: [rebalancing-tags-group-exclude]:'
tags_exclude_vms = {}
processed_vm = []
# Create groups of tags with belongings hosts.
for vm_name, vm_values in vm_statistics.items():
if vm_values.get('group_include', None):
if not tags_exclude_vms.get(vm_values['group_include'], None):
tags_exclude_vms[vm_values['group_include']] = [vm_name]
else:
tags_exclude_vms[vm_values['group_include']] = tags_exclude_vms[vm_values['group_include']] + [vm_name]
# Update the VMs to the corresponding node to their group assignments.
for group, vm_names in tags_exclude_vms.items():
# Do not take care of tags that have only a single host included.
if len(vm_names) < 2:
logging.info(f'{info_prefix} Only one host in group assignment.')
return node_statistics, vm_statistics
vm_node_rebalance = False
logging.info(f'{info_prefix} Create exclude groups of VM hosts.')
for vm_name in vm_names:
if vm_name not in processed_vm:
if not vm_node_rebalance:
random_node = vm_statistics[vm_name]['node_parent']
# Get a random node and make sure that it is not by accident the
# currently assigned one.
while random_node == vm_statistics[vm_name]['node_parent']:
random_node = random.choice(list(node_statistics.keys()))
else:
_mocked_vm_object = (vm_name, vm_statistics[vm_name])
node_statistics, vm_statistics = __update_resource_statistics(_mocked_vm_object, [random_node], vm_statistics, node_statistics, balancing_method, balancing_mode)
processed_vm.append(vm_name)
return node_statistics, vm_statistics
def __run_vm_rebalancing(api_object, vm_statistics_rebalanced, app_args):
""" Run & execute the VM rebalancing via API. """
error_prefix = 'Error: [rebalancing-executor]:'
info_prefix = 'Info: [rebalancing-executor]:'
if len(vm_statistics_rebalanced) > 0 and not app_args.dry_run:
for vm, value in vm_statistics_rebalanced.items():
try:
logging.info(f'{info_prefix} Rebalancing vm {vm} from node {value["node_parent"]} to node {value["node_rebalance"]}.')
api_object.nodes(value['node_parent']).qemu(value['vmid']).migrate().post(target=value['node_rebalance'],online=1)
except proxmoxer.core.ResourceException as error_resource:
logging.critical(f'{error_prefix} {error_resource}')
else:
logging.info(f'{info_prefix} No rebalancing needed.')
def __create_json_output(vm_statistics_rebalanced, app_args):
""" Create a machine parsable json output of VM rebalance statitics. """
info_prefix = 'Info: [json-output-generator]:'
if app_args.json:
logging.info(f'{info_prefix} Printing json output of VM statistics.')
print(json.dumps(vm_statistics_rebalanced))
def __create_dry_run_output(vm_statistics_rebalanced, app_args):
""" Create output for CLI when running in dry-run mode. """
info_prefix = 'Info: [dry-run-output-generator]:'
vm_to_node_list = []
logging.info(f'{info_prefix} Starting dry-run to rebalance vms to their new nodes.')
vm_to_node_list.append(['VM', 'Current Node', 'Rebalanced Node', 'VM Type'])
for vm_name, vm_values in vm_statistics_rebalanced.items():
vm_to_node_list.append([vm_name, vm_values['node_parent'], vm_values['node_rebalance'], vm_values['type']])
if len(vm_statistics_rebalanced) > 0:
logging.info(f'{info_prefix} Printing cli output of VM rebalancing.')
__print_table_cli(vm_to_node_list)
else:
logging.info(f'{info_prefix} No rebalancing needed.')
def __print_table_cli(table):
""" Pretty print a given table to the cli. """
longest_cols = [
(max([len(str(row[i])) for row in table]) + 3)
for i in range(len(table[0]))
]
row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
for row in table:
print(row_format.format(*row))
def run_vm_rebalancing(api_object, vm_statistics_rebalanced, app_args):
""" Run rebalancing of vms to new nodes in cluster. """
__run_vm_rebalancing(api_object, vm_statistics_rebalanced, app_args)
__create_json_output(vm_statistics_rebalanced, app_args)
__create_dry_run_output(vm_statistics_rebalanced, app_args)
def main():
""" Run ProxLB for balancing VM workloads across a Proxmox cluster. """
# Initialize PAS.
initialize_logger('CRITICAL')
app_args = initialize_args()
config_path = initialize_config_path(app_args)
pre_validations(config_path)
# Parse global config.
proxmox_api_host, proxmox_api_user, proxmox_api_pass, proxmox_api_ssl_v, balancing_method, balancing_mode, balancing_type, \
balanciness, ignore_nodes, ignore_vms, daemon, schedule, log_verbosity = initialize_config_options(config_path)
# Overwrite logging handler with user defined log verbosity.
initialize_logger(log_verbosity, update_log_verbosity=True)
while True:
# API Authentication.
api_object = api_connect(proxmox_api_host, proxmox_api_user, proxmox_api_pass, proxmox_api_ssl_v)
# Get metric & statistics for vms and nodes.
node_statistics = get_node_statistics(api_object, ignore_nodes)
vm_statistics = get_vm_statistics(api_object, ignore_vms, balancing_type)
node_statistics = update_node_statistics(node_statistics, vm_statistics)
# Calculate rebalancing of vms.
node_statistics_rebalanced, vm_statistics_rebalanced = balancing_calculations(balancing_method, balancing_mode, node_statistics, vm_statistics, balanciness, rebalance=False, processed_vms=[])
# Rebalance vms to new nodes within the cluster.
run_vm_rebalancing(api_object, vm_statistics_rebalanced, app_args)
# Validate for any errors.
post_validations()
# Validate daemon service.
validate_daemon(daemon, schedule)
if __name__ == '__main__':
main()