"""Watch current connections of haproxy server backends.Fire an event when over a specified threshold... versionadded:: 2016.11.0"""importloggingimportsalt.utils.beaconslog=logging.getLogger(__name__)__virtualname__="haproxy"
[docs]def__virtual__():""" Only load the module if haproxyctl module is installed """if"haproxy.get_sessions"in__salt__:return__virtualname__else:err_msg="haproxy.get_sessions is missing."log.error("Unable to load %s beacon: %s",__virtualname__,err_msg)returnFalse,err_msg
[docs]defvalidate(config):""" Validate the beacon configuration """ifnotisinstance(config,list):returnFalse,"Configuration for haproxy beacon must be a list."else:config=salt.utils.beacons.list_to_dict(config)if"backends"notinconfig:returnFalse,"Configuration for haproxy beacon requires backends."else:ifnotisinstance(config["backends"],dict):returnFalse,"Backends for haproxy beacon must be a dictionary."else:forbackendinconfig["backends"]:log.debug("config %s",config["backends"][backend])if"servers"notinconfig["backends"][backend]:return(False,"Backends for haproxy beacon require servers.",)else:_servers=config["backends"][backend]["servers"]ifnotisinstance(_servers,list):return(False,"Servers for haproxy beacon must be a list.",)returnTrue,"Valid beacon configuration"
[docs]defbeacon(config):""" Check if current number of sessions of a server for a specific haproxy backend is over a defined threshold. .. code-block:: yaml beacons: haproxy: - backends: www-backend: threshold: 45 servers: - web1 - web2 - interval: 120 """ret=[]config=salt.utils.beacons.list_to_dict(config)forbackendinconfig.get("backends",()):backend_config=config["backends"][backend]threshold=backend_config["threshold"]forserverinbackend_config["servers"]:scur=__salt__["haproxy.get_sessions"](server,backend)ifscur:ifint(scur)>int(threshold):_server={"server":server,"scur":scur,"threshold":threshold,}log.debug("Emit because %s > %s for %s in %s",scur,threshold,server,backend,)ret.append(_server)returnret