Skip to content

Instantly share code, notes, and snippets.

@valferon
Created September 14, 2017 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valferon/3b188fb22c53631a2b4dbf0904cb4990 to your computer and use it in GitHub Desktop.
Save valferon/3b188fb22c53631a2b4dbf0904cb4990 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import logging
import os
import os.path
import socket
import simplejson as json
import subprocess
#
##
### parameters - to do: include from external config file
aws_upstream = '[UPSTREAM_URL]'
json_dns_file = '/tmp/dns_check.json'
logfile = '/var/log/lb_dns_check.log'
#
##
### log config
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.FileHandler(logfile)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def resolve(host_to_res):
dns_res = socket.gethostbyname_ex(host_to_res)
return dns_res
def write_json(json_file, data):
with open(json_file, 'w+') as outfile:
json.dump(data, outfile)
def read_json(json_file):
with open(json_file, 'r') as infile:
data = json.load(infile)
return data
def check_exist(file_variable):
if os.path.isfile(file_variable):
print 'OK'
else:
logger.warn('creating file {}'.format(file_variable))
current = resolve(aws_upstream)
write_json(file_variable, current)
def restart_service(name):
command = ['service', name, 'restart']
# shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
def comp(list1, list2):
a = list1[2]
b = list2[2]
a.sort()
b.sort()
return a == b
def main():
check_exist(json_dns_file)
current = resolve(aws_upstream)
old = read_json(json_dns_file)
if comp(old, current):
logger.info('Dns has not changed : {}'.format(current[2]))
else:
logger.warn('Nginx is cactus - restarting')
restart_service('nginx')
write_json(json_dns_file,current)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment