Guest User

HDHR Delay tool

a guest
Dec 27th, 2022
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.13 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. """ See if the HD Homerun box is accessible and running
  5.  
  6. Can be called with a optional IP address(s) for users that
  7. have multiple HDHRs that have STATIC addresses.
  8.  
  9. Expects a writable log file in /tmp named hdhr_discovery.log.
  10. Owner:group = mythtv:mythtv and mode = 664. If your user is a
  11. member of the mythtv group, then this can be run by you from
  12. the command line assuming the permissions are 0664.
  13.  
  14. Exit codes are:
  15.  
  16.    5 times the number of failing HDHRs
  17.    4 if the user running the program isn't what systemd is using
  18.    3 if the logfile isn't writable
  19.    2 for a keyboard interrupt
  20.    0 if all HDHR(s) are found (success case)
  21. """
  22.  
  23. __version__ = '1.13'
  24.  
  25. import argparse
  26. import getpass
  27. import subprocess
  28. import sys
  29. import logging
  30. from time import sleep
  31. from datetime import datetime
  32.  
  33. ATTEMPTS = 21
  34. DELAY = 2
  35.  
  36.  
  37. def get_program_arguments():
  38.     ''' Process the command line. '''
  39.  
  40.     parser = argparse.ArgumentParser(description='HDHR Access Test',
  41.                                      epilog='*  Default values are in ()s.')
  42.  
  43.     parser.add_argument('IP_ADDRESSES', type=str, metavar='<IP>', default=' ',
  44.                         nargs='*', help='Optional IP address(s) (%(default)s)')
  45.  
  46.     parser.add_argument('--logfile', default='/tmp/hdhr_discovery.log',
  47.                         type=str, metavar='<lf>',
  48.                         help='Location of log file (%(default)s)')
  49.  
  50.     parser.add_argument('--version', action='version',
  51.                         version='%(prog)s ' + __version__)
  52.  
  53.     return vars(parser.parse_args())
  54.  
  55.  
  56. def get_elapsed_time(start):
  57.     ''' Calculate the time spent waiting for the HDHR to come up '''
  58.  
  59.     delta = datetime.utcnow() - start
  60.     rounded_delta = '{:.3f}'.format(delta.seconds +
  61.                                     (delta.microseconds / 1000000))
  62.     return rounded_delta
  63.  
  64.  
  65. def main(ip_address, logfile):
  66.     ''' Try to discover the HDHR(s) '''
  67.  
  68.     attempt = 0  # Shut up pylint.
  69.     command = ['systemctl', 'show', '--property=User', '--value',
  70.                'mythtv-backend.service']
  71.  
  72.     systemd_user = subprocess.check_output(command, stderr=subprocess.STDOUT).\
  73.                                            strip().decode()
  74.     if not systemd_user:
  75.         systemd_user = 'root'
  76.  
  77.     if getpass.getuser() != systemd_user:
  78.         print('BE running as user %s, not your user, aborting' % systemd_user)
  79.         sys.exit(4)
  80.  
  81.     command = 'hdhomerun_config discover ' + ip_address
  82.     logger = logging.getLogger(command)
  83.  
  84.     try:
  85.         logging.basicConfig(filename=logfile, filemode='a',
  86.                             format='%(asctime)s %(levelname)s\t%(message)s',
  87.                             datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
  88.     except PermissionError:
  89.         print('%s is not writable, aborting!' % logfile)
  90.         sys.exit(3)
  91.  
  92.     logger.info('Starting HD Homerun discovery')
  93.  
  94.     start = datetime.utcnow()
  95.  
  96.     for attempt in range(1, ATTEMPTS):
  97.         try:
  98.             sproc = subprocess.Popen(command, stdout=subprocess.PIPE,
  99.                                      shell=True)
  100.             sproc.communicate()
  101.         except KeyboardInterrupt:
  102.             sys.exit(2)
  103.  
  104.         if sproc.returncode != 0:
  105.             logger.warning('%s failed, return code = %d.', command,
  106.                            sproc.returncode)
  107.             sleep(DELAY)
  108.         else:
  109.             logger.info('Found HD Homerun%s. Seconds=%s, attempts=%d.',
  110.                         '' if ip_address == ' ' else (' for ' + ip_address),
  111.                         get_elapsed_time(start), attempt)
  112.             return 0
  113.  
  114.     logger.error('Couldn\'t find HD Homerun%s. Seconds=%s, attempts=%d.',
  115.                  '' if ip_address == ' ' else (' for ' + ip_address),
  116.                  get_elapsed_time(start), attempt)
  117.  
  118.     return 5
  119.  
  120.  
  121. if __name__ == '__main__':
  122.  
  123.     ARGS = get_program_arguments()
  124.     RETURN_VALUE = 0
  125.  
  126.     for address in ARGS['IP_ADDRESSES']:
  127.         RETURN_VALUE += main(address, ARGS['logfile'])
  128.  
  129.     sys.exit(RETURN_VALUE)
  130.  
  131. # vim: set expandtab tabstop=4 shiftwidth=4 smartindent colorcolumn=80:
Advertisement
Add Comment
Please, Sign In to add comment