From 9960cf05921c8f121521f80857a0f24d472938d4 Mon Sep 17 00:00:00 2001 From: William Wernert Date: Mon, 9 Nov 2020 12:05:37 -0500 Subject: [PATCH] [feat] Add salt module to check if mysql is accepting db connections --- salt/_modules/mysql.py | 35 +++++++++++++++++++++++++++++++++++ salt/mysql/init.sls | 5 +++++ 2 files changed, 40 insertions(+) create mode 100644 salt/_modules/mysql.py diff --git a/salt/_modules/mysql.py b/salt/_modules/mysql.py new file mode 100644 index 000000000..f4e35ae76 --- /dev/null +++ b/salt/_modules/mysql.py @@ -0,0 +1,35 @@ +#!py + +from MySQLdb import _mysql +import logging +import time + +log = logging.getLogger(__name__) + + +def status(retry): + mainint = __salt__['pillar.get']('sensor:mainint', __salt__['pillar.get']('manager:mainint')) + mainip = __salt__['grains.get']('ip_interfaces').get(mainint)[0] + + mysql_up = False + for i in range(0, retry): + log.debug(f'Connection attempt {i+1}') + try: + _mysql.connect( + host=mainip, + user="root", + passwd=__salt__['pillar.get']('secrets:mysql') + ) + mysql_up = True + break + except _mysql.OperationalError as e: + log.debug(e) + except Exception as e: + log.error(e) + break + time.sleep(1) + + if not mysql_up: + log.error(f'Could not connect to MySQL server on {mainip} after {retry} attempts.') + + return mysql_up diff --git a/salt/mysql/init.sls b/salt/mysql/init.sls index 818b5c303..e1f37f29c 100644 --- a/salt/mysql/init.sls +++ b/salt/mysql/init.sls @@ -97,6 +97,11 @@ so-mysql: - timeout: 900 - onchanges: - docker_container: so-mysql + module.run: + - mysql.status: + - retry: 900 + - onchanges: + - cmd: so-mysql {% endif %} {% else %}