Advertisement
Guest User

pm

a guest
Dec 18th, 2013
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.81 KB | None | 0 0
  1. #!/usr/local/bin/python
  2.  
  3. import sys
  4. from optparse import OptionParser
  5. import re
  6. import time
  7. import subprocess
  8. import syslog
  9. import os
  10. import stat
  11.  
  12.  
  13. INTERVAL    = 40
  14. NUM         = 30
  15. SYSLOG      = False
  16.  
  17.  
  18. def log (message):
  19.     global SYSLOG
  20.  
  21.     if SYSLOG:
  22.         os.system ("logger " + message)
  23.     else:
  24.         print message
  25.  
  26.  
  27. def daemonize ():
  28.     log ("Daemonizing ...")
  29.     try:
  30.         pid = os.fork()
  31.         if pid > 0:
  32.             sys.exit(0)
  33.  
  34.     except OSError, e:
  35.         sys.exit(1)
  36.  
  37.         os.chdir("/")
  38.         os.setsid()
  39.         os.umask(0)
  40.  
  41.     try:
  42.         pid = os.fork()
  43.         if pid > 0:
  44.             sys.exit(0)
  45.  
  46.     except OSError, e:
  47.         sys.exit(1)
  48.  
  49.  
  50. def check_devices (devices_map):
  51.     for device in sorted (devices_map.iterkeys ()):
  52.         info = os.stat ("/dev/" + device)
  53.         if not stat.S_ISCHR (info.st_mode):
  54.             log ("/dev/%s is not a device" % device)
  55.             sys.exit (1)
  56.  
  57.  
  58. def get_gstat_output (device_map):
  59.     command = "gstat -b -f "
  60.  
  61.     for device in sorted (devices_map.iterkeys ()):
  62.         command += "^" + device + "$|"
  63.  
  64.     command = command.rstrip ('|')
  65.  
  66.     proc = subprocess.Popen(command.split (), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  67.     proc.wait ()
  68.  
  69.     if proc.returncode != 0:
  70.         error = proc.stderr.read ()
  71.         log ("Cannot execute '%s', error: %s" % (command, error))
  72.         sys.exit (1)
  73.  
  74.     output = proc.stdout.read ()
  75.  
  76.     return output
  77.  
  78.  
  79. def get_device_ops (device, status):
  80.     for line in status.splitlines ():
  81.         found = re.search (device, line)
  82.  
  83.         if (found):
  84.             line = ' '.join (line.split ())
  85.             ops = line.split (' ')[1]
  86.  
  87.     return int (ops)
  88.  
  89.  
  90. def print_status (devices_map):
  91.     str = ""
  92.  
  93.     for device in sorted (devices_map.iterkeys ()):
  94.         (time_left, status) = devices_map[device]
  95.         str += "!%s,%d,%s" % (device, time_left, "Spinning" if status else "Stopped")
  96.  
  97.     str += "!"
  98.     log (str)
  99.  
  100.  
  101. def stop_device (device, sync, test):
  102.     log ("Stopping device: %s" % device)
  103.  
  104.     if test:
  105.         command = "sleep 2"
  106.     else:
  107.         command = "camcontrol stop %s" % device
  108.  
  109.     proc = subprocess.Popen(command.split (), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  110.  
  111.     if sync:
  112.         proc.wait ()
  113.  
  114.         if proc.returncode != 0:
  115.             error = proc.stderr.read ()
  116.             log ("Cannot execute '%s', error: %s" % (command, error))
  117.             sys.exit (1)
  118.  
  119.  
  120. def run (options, devices_map):
  121.     check_devices (devices_map)
  122.  
  123.     while (1):
  124.         print_status (devices_map)
  125.  
  126.         time.sleep (options.interval)
  127.  
  128.         output = get_gstat_output (devices_map)
  129.  
  130.         for device in sorted (devices_map.iterkeys()):
  131.             ops = get_device_ops (device, output)
  132.  
  133.             (time_left, status) = devices_map[device]
  134.  
  135.             if ops == 0:
  136.                 if time_left > 0:
  137.                     time_left = time_left - options.interval
  138.        
  139.                     if time_left == 0:
  140.                         status = False
  141.                         stop_device (device, options.sync, options.test)
  142.  
  143.             else:
  144.                 time_left = options.interval * options.num
  145.                 status = True
  146.  
  147.             devices_map[device] = (time_left, status)
  148.    
  149.     return 0
  150.  
  151.  
  152. if __name__ == "__main__":
  153.     parser = OptionParser ()
  154.     parser.add_option ("-i", "--interval",  type = "int",           dest = "interval",      default = INTERVAL, help = "interval between checks in seconds (default 40)",   metavar = "SECONDS")
  155.     parser.add_option ("-n", "--num",       type = "int",           dest = "num",           default = NUM,      help = "number of intervals (default 30)",                  metavar = "NUMBER")
  156.     parser.add_option ("-d", "--devices",   type = "string",        dest = "devices",                           help = "comma separated list of devices (without /dev/)",   metavar = "LIST")
  157.     parser.add_option ("-s", "--syslog",    action = "store_true",  dest = "syslog",        default = False,    help = "log to syslog")
  158.     parser.add_option ("-y", "--sync",      action = "store_true",  dest = "sync",          default = False,    help = "stop devices synchronously")
  159.     parser.add_option ("-t", "--test",      action = "store_true",  dest = "test",          default = False,    help = "test only (devices are not stopped)")
  160.     parser.add_option ("-x", "--daemonize", action = "store_true",  dest = "daemonize",     default = False,    help = "run as daemon")
  161.  
  162.     (options, args) = parser.parse_args ()
  163.  
  164.     if not options.devices or options.devices == "":
  165.         print "error: -d argument is required\n"
  166.  
  167.         parser.print_help ()
  168.         sys.exit(1)
  169.  
  170.     SYSLOG = options.syslog
  171.  
  172.     #
  173.     # devices_map['device'] = (time left, status)
  174.     # status : [False = Stopped, True = Spinning]
  175.     #
  176.     devices_map = dict ((d.strip (), (options.interval * options.num, True)) for d in options.devices.split (','))
  177.  
  178.     log ("=" * 31)
  179.     log ("= interval: %s" % options.interval)
  180.     log ("= num: %d" % options.num)
  181.     log ("= total time: %d seconds" % (options.interval * options.num))
  182.     log ("= devices: %s" % options.devices)
  183.     log ("= syslog: %s" % ('on' if options.syslog else 'off'))
  184.     log ("= sync: %s" % ('on' if options.sync else 'off'))
  185.     log ("= test: %s" % ('on' if options.test else 'off'))
  186.     log ("= daemonize: %s" % ('on' if options.daemonize else 'off'))
  187.     log ("=" * 31)
  188.  
  189.     if options.daemonize:
  190.         daemonize ()
  191.  
  192.     run (options, devices_map)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement