Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.82 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Check if all processes matching a name were started after a config
  4. file's mtime.
  5.  
  6. --snip--
  7.  
  8. Tested under Python 2.7 and 3.4
  9. """
  10.  
  11. from __future__ import (absolute_import, division, print_function,
  12. with_statement, unicode_literals)
  13.  
  14. __author__ = "Stephan Sokolow (deitarion/SSokolow)"
  15. __appname__ = "restarted_since.py"
  16. __version__ = "0.1"
  17. __license__ = "MIT"
  18.  
  19. import logging, os, subprocess, sys
  20. log = logging.getLogger(__name__)
  21.  
  22. # Ticks per second
  23. tick_rate = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
  24.  
  25. def getpids(procname):
  26. """Simple abstraction for a couple of ways to get PIDs from names"""
  27. try:
  28. pidstr = subprocess.check_output(['pidof', procname])
  29. except subprocess.CalledProcessError:
  30. pidstr = subprocess.check_output(['pgrep', procname])
  31. return [int(x.strip()) for x in pidstr.strip().split()]
  32.  
  33. def get_start_time(pid):
  34. """Given a PID, look up the start time in seconds since the epoch
  35.  
  36. See `man 5 proc` for references used to implement.
  37.  
  38. Passes through IOError with errno=ENOENT if the process went away.
  39. """
  40. # Read process start time as clock ticks since system boot
  41. with open("/proc/{}/stat".format(pid), 'rb') as fobj:
  42. proc_start_ticks_since_boot = int(fobj.read().strip().split()[21])
  43.  
  44. # Read system boot time as seconds since the epoch
  45. sys_boot_time = None
  46. with open("/proc/stat", 'rb') as fobj:
  47. for line in fobj:
  48. key, val = line.split(None, 1)
  49. if key == b'btime':
  50. sys_boot_time = int(val)
  51. assert sys_boot_time
  52.  
  53. # Translate process start time from ticks to seconds
  54. proc_start_secs_since_boot = proc_start_ticks_since_boot / tick_rate
  55. # Translate process start time from since-boot to since-epoch
  56. proc_start_secs_since_epoch = proc_start_secs_since_boot + sys_boot_time
  57.  
  58. return proc_start_secs_since_epoch
  59.  
  60. def get_mtime(path):
  61. """Thin wrapper for grabbing a file's mtime"""
  62. assert os.path.exists(path), "Path does not exist: {}".format(path)
  63. return os.stat(path).st_mtime
  64.  
  65. def main():
  66. """The main entry point, compatible with setuptools entry points."""
  67. # If we're running on Python 2, take responsibility for preventing
  68. # output from causing UnicodeEncodeErrors. (Done here so it should only
  69. # happen when not being imported by some other program.)
  70. if sys.version_info.major < 3:
  71. reload(sys)
  72. sys.setdefaultencoding('utf-8') # pylint: disable=no-member
  73.  
  74. from argparse import ArgumentParser
  75. parser = ArgumentParser(
  76. description=__doc__.replace('\r\n', '\n').split('\n--snip--\n')[0])
  77. parser.add_argument('--version', action='version',
  78. version="%%(prog)s v%s" % __version__)
  79. parser.add_argument('-v', '--verbose', action="count",
  80. default=2, help="Increase the verbosity. Use twice for extra effect")
  81. parser.add_argument('-q', '--quiet', action="count",
  82. default=0, help="Decrease the verbosity. Use twice for extra effect")
  83. parser.add_argument('process_name', help="Process name to be checked")
  84. parser.add_argument('config_file', help="UNIX timestamp to compare")
  85.  
  86. args = parser.parse_args()
  87.  
  88. # Set up clean logging to stderr
  89. log_levels = [logging.CRITICAL, logging.ERROR, logging.WARNING,
  90. logging.INFO, logging.DEBUG]
  91. args.verbose = min(args.verbose - args.quiet, len(log_levels) - 1)
  92. args.verbose = max(args.verbose, 0)
  93. logging.basicConfig(level=log_levels[args.verbose],
  94. format='%(levelname)s: %(message)s')
  95.  
  96. earliest_started = min(get_start_time(i)
  97. for i in getpids(args.process_name))
  98. if earliest_started > get_mtime(args.config_file):
  99. sys.exit(0)
  100. else:
  101. sys.exit(1)
  102.  
  103. if __name__ == '__main__':
  104. main()
  105.  
  106. # vim: set sw=4 sts=4 expandtab :
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement