Created
July 6, 2023 06:35
-
-
Save adrianlzt/818df9a12e82e8f5663f39c72015798b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Script to handle keepalived notifications. | |
This script will be called by keepalived with three arguments: | |
- "GROUP" or "INSTANCE" | |
- name of the group or instance | |
- target state of the transition: "MASTER", "BACKUP", "FAULT" | |
The script should return 1 if the number of parameters is not 3, if the | |
target state is not "MASTER", "BACKUP" or "FAULT", or if the first parameter | |
is not "GROUP" or "INSTANCE". Otherwise it should return 0. | |
It should log its actions to syslog. | |
If the transition is to "MASTER", the script should start the service "zabbix-proxy". | |
It should also call a GCP cloud function to change the route to point to the new master. | |
This call will done to the URL defined in the variable FUNCTION_URL. | |
It should be called with a parameter "target" passing the hostname of the new master. | |
Is should also pass an Authorization header with a token. | |
To generate the token, the script should call the GCP metadata server. | |
If the transition is to "BACKUP" or "FAULT", the script should stop the service "zabbix-proxy". | |
""" | |
import logging | |
import os | |
import subprocess | |
import sys | |
import urllib.request | |
import urllib.error | |
from systemd.journal import JournalHandler | |
# URL of the cloud function to call | |
# We use the "zone" and "project" hostvars to get the region and project of the cloud function. | |
FUNCTION_URL = "https://{{ (zone | split('-'))[:-1] | join('-') }}-{{ project }}.cloudfunctions.net/switch-route" | |
def main(): | |
"""Main function""" | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') | |
logger = logging.getLogger(__name__) | |
logger.addHandler(JournalHandler()) | |
logger.info("Starting keepalived notification script") | |
logger.debug("Arguments: %s", sys.argv) | |
# https://github.com/acassen/keepalived/blob/ab91d7fe9430918371993dc6234be077915c879d/keepalived/vrrp/vrrp_notify.c#L166 | |
# script {GROUP|INSTANCE} NAME {MASTER|BACKUP|FAULT|STOP|DELETED} PRIO | |
if len(sys.argv) != 5: | |
logger.error("Wrong number of arguments") | |
return 1 | |
if sys.argv[1] not in ["GROUP", "INSTANCE"]: | |
logger.error("First argument must be GROUP or INSTANCE") | |
return 1 | |
# https://github.com/acassen/keepalived/blob/ab91d7fe9430918371993dc6234be077915c879d/keepalived/vrrp/vrrp_notify.c#L174 | |
if sys.argv[3] not in ["MASTER", "BACKUP", "FAULT", "STOP", "DELETED"]: | |
logger.error("Third argument must be MASTER, BACKUP, FAULT, STOP or DELETED") | |
return 1 | |
if sys.argv[3] == "MASTER": | |
logger.info("Starting zabbix-proxy") | |
r = subprocess.run(["/usr/bin/sudo", "systemctl", "start", "zabbix-proxy"]) | |
if r.returncode != 0: | |
logger.error("Error starting zabbix-proxy") | |
logger.info("Calling cloud function") | |
# Get the token. The request should add the header "Metadata-Flavor: Google". | |
# The token should be passed as a bearer token in the Authorization header. | |
# The audience should be the URL of the cloud function. | |
req = urllib.request.Request("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=" + FUNCTION_URL) | |
req.add_header("Metadata-Flavor", "Google") | |
# Capture if the request fails and return, logging the error and returning 1 | |
try: | |
token = urllib.request.urlopen(req).read().decode("utf-8") | |
except urllib.error.HTTPError as err: | |
logger.error("Error getting token: %s", err) | |
return 1 | |
logger.debug("Token: %s", token) | |
# Set the target variable with the hostname of the current server | |
target = os.uname()[1] | |
req = urllib.request.Request(FUNCTION_URL + "?target=" + target) | |
req.add_header("Authorization", "bearer " + token) | |
try: | |
urllib.request.urlopen(req) | |
except urllib.error.HTTPError as err: | |
logger.error("Error calling cloud function: %s", err) | |
return 1 | |
else: | |
logger.info("Stopping zabbix-proxy") | |
r = subprocess.run(["/usr/bin/sudo", "systemctl", "stop", "zabbix-proxy"]) | |
if r.returncode != 0: | |
logger.error("Error stopping zabbix-proxy") | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment