Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- ######################
- checkswap.py
- Author: Sheldon Alman
- Date : Nov. 21 2013
- ######################
- This script was specifically written as a workaround for the Samba memory leak issue. The script checks the amount of swap space available and restarts the Samba process if the amount of swap available is less than the specified value.
- ######################
- Revision History:
- v0.1 - Nov 21 2013 - Initial Release
- ######################
- '''
- import subprocess
- import re
- import syslog
- def write_syslog(level,message):
- '''This function writes the message passed to it at the corresponding log level to syslog'''
- try:
- syslog.syslog(level, message)
- return True
- except Exception, e:
- print "Cannot write to syslog ",e
- return False
- def main():
- service = 'smb'
- total = subprocess.Popen(['/bin/grep','SwapTotal','/proc/meminfo'],stdout=subprocess.PIPE) #Total amount of swap space
- free = subprocess.Popen(['/bin/grep','SwapFree','/proc/meminfo'],stdout=subprocess.PIPE) #Amount of free swap space
- ps_aux = subprocess.Popen(['ps','aux'],stdout=subprocess.PIPE) #Executes the 'ps aux ' command and stores it's results
- grep_service = subprocess.Popen(['grep',service],stdin=ps_aux.stdout, stdout=subprocess.PIPE) #Executes the 'grep smb' command and takes stdout of 'ps aux' as it's input
- wc_service = subprocess.Popen(['wc','-l'],stdin=grep_service.stdout, stdout=subprocess.PIPE)
- wc_service_string = str(eval(str(wc_service.communicate()[0])) - 1)
- ps_aux.stdout.close()
- #Removes all other characters except for digits and converts the results to floating point numbers
- free_swap = float(re.findall(r'\d+', str(free.communicate()))[0])
- total_swap = float(re.findall(r'\d+', str(total.communicate()))[0])
- max_swap_usage = 75.0 #Max swap usage before service restart
- '''If the amount of free swap space is less than the specified number, write to syslog and restart the smb process.'''
- if (free_swap / total_swap * 100) < max_swap_usage:
- write_syslog(syslog.LOG_WARNING, "Swap usage is above %s%%. Restarting %s service" % (max_swap_usage, service))
- write_syslog(syslog.LOG_WARNING, "Number of %s processes running : %s" % (service,wc_service_string))
- try:
- subprocess.check_call('/etc/init.d/%s restart' % (service), shell=True)
- except Exception, e:
- print "Could not execute ", e
- write_syslog(syslog.LOG_WARNING, "Could not restart %s service. Error: %s" % (service, e))
- else:
- write_syslog(syslog.LOG_INFO, "Swap usage is less than %s%%. Restart of %s not required." % (max_swap_usage,service))
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement