This shows you the differences between two versions of the page.
check_service_and_restart_if_failed [2020/07/27 03:33] k2patel |
check_service_and_restart_if_failed [2020/08/10 02:35] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ==== Check service and restart if failed ==== | ||
- | Check the service if nginx is running and if not start | ||
- | <code bash> | ||
- | #!/usr/bin/env bash | ||
- | |||
- | # Enable System level logging | ||
- | # Redirect log to logger | ||
- | exec 1> >(logger -t $(basename $0)) 2>&1 | ||
- | |||
- | STATUS="$(systemctl is-active nginx.service)" | ||
- | |||
- | if [ "${STATUS}" != "active" ]; then | ||
- | echo "Not running starting Service : Nginx" | ||
- | systemctl start nginx.service | ||
- | fi | ||
- | </code> | ||
- | |||
- | for python | ||
- | |||
- | <code python> | ||
- | #!/usr/bin/env python3 | ||
- | import os | ||
- | import logging | ||
- | from systemd import journal | ||
- | |||
- | def main(serviceName): | ||
- | status = os.system('systemctl is-active --quiet ' + serviceName) | ||
- | finisher(status) | ||
- | |||
- | def finisher(status): | ||
- | if status is not 0: | ||
- | status = os.system('systemctl start --quiet ' + serviceName) | ||
- | print(status) | ||
- | if status is not 0: | ||
- | log.error('Failed to start: ' + serviceName) | ||
- | else: | ||
- | log.info('Started service: ' + serviceName) | ||
- | |||
- | if __name__ == "__main__": | ||
- | |||
- | # Initialize and handle options | ||
- | log = logging.getLogger(__file__) | ||
- | log.addHandler(journal.JournaldLogHandler()) | ||
- | log.setLevel(logging.INFO) | ||
- | |||
- | # Define service array | ||
- | serviceName = 'nginx' | ||
- | |||
- | main(serviceName) | ||
- | </code> |