changeset 25:7571c101a4ee

Read options properly so it's usable by others
author Daniel O'Connor <darius@dons.net.au>
date Mon, 19 Jun 2017 10:02:30 +0930
parents 806b1ed7f1b5
children 04874587fb6e
files adslstats.py
diffstat 1 files changed, 63 insertions(+), 47 deletions(-) [+]
line wrap: on
line diff
--- a/adslstats.py	Sat Jun 17 16:52:20 2017 +0930
+++ b/adslstats.py	Mon Jun 19 10:02:30 2017 +0930
@@ -37,7 +37,7 @@
 import json
 import mechanize
 import mysrp as srp
-import optparse
+import argparse
 import os
 import os.path
 import re
@@ -49,39 +49,55 @@
 
 conf = ConfigParser.ConfigParser()
 conf.add_section('global')
-conf.set('global', 'username', 'admin')
-conf.set('global', 'password', 'admin')
-conf.set('global', 'name', '10.0.2.14')
-conf.set('global', 'cookiejar', os.path.expanduser('~/.adslstats.cj'))
 
-conflist = ['adslstats.ini']
+conflist = []
 if ('HOME' in os.environ):
     conflist.append(os.path.expanduser('~/.adslstats.ini'))
 conf.read(conflist)
 
 usage = '''%prog [options]'''
-opts = optparse.OptionParser(usage)
-opts.add_option('-v', '--verbose', action="store_true", default=False,
-                    help="Enable debug output")
-opts.add_option('-g', '--graph', action="store_true", default=False,
-                    help="Generate a graph")
-opts.add_option('-u', '--update', action="store_true", default=False,
-                    help="Update RRD (implies -d)")
-opts.add_option('-m', '--munin', action="store", default=None,
-                    help="Output munin data for ARG")
-opts.add_option('-a', '--authname', action="store", default=conf.get('global', 'username'),
-                    help="Username to login to modem")
-opts.add_option('-p', '--password', action="store", default=conf.get('global', 'password'),
-                    help="Password to login to modem")
-opts.add_option('-n', '--name', action="store", default=conf.get('global', 'name'),
-                    help="Hostname of modem")
-opts.add_option('-b', '--base', action="store", default="/home/darius/projects/adslstats/adslstats",
-                    help="Base directory for RRD & PNGs")
+parser = argparse.ArgumentParser(usage)
+parser.add_argument('-v', '--verbose', action='store_true', default=False,
+                    help='Enable debug output')
+parser.add_argument('-g', '--graph', action='store_true', default=False,
+                    help='Generate a graph')
+parser.add_argument('-u', '--update', action='store_true', default=False,
+                    help='Update RRD (implies -d)')
+parser.add_argument('-m', '--munin', action='store', default=None,
+                    help='Output munin data for ARG')
+parser.add_argument('-a', '--username', action='store',
+                    help='Username to login to modem')
+parser.add_argument('-p', '--password', action='store',
+                    help='Password to login to modem')
+parser.add_argument('-n', '--name', action='store',
+                    help='Hostname of modem')
+parser.add_argument('-b', '--base', action='store',
+                    help='Base directory for RRD & PNGs')
+parser.add_argument('-c', '--cookiejar', action='store',
+                    help='Location of cookiejar')
 
-(options, args) = opts.parse_args()
+args = parser.parse_args()
+
+# Handle options from conf and override with ini
+def opthelper(args, conf, optname):
+    if args.__getattribute__(optname) == None:
+        if not conf.has_option('global', optname):
+            parser.error(optname + ' must be specified in config file or via commandline')
+        else:
+            args.__setattr__(optname, conf.get('global', optname))
 
-rrdname = "%s.rrd" % (options.base)
-graphbasename = options.base
+opthelper(args, conf, 'username')
+opthelper(args, conf, 'password')
+opthelper(args, conf, 'name')
+opthelper(args, conf, 'base')
+opthelper(args, conf, 'cookiejar')
+
+# Expand path names
+args.cookiejar = os.path.expanduser(args.cookiejar)
+args.base = os.path.expanduser(args.base)
+
+rrdname = "%s.rrd" % (args.base)
+graphbasename = args.base
 
 class DSLStats(object):
     def __str__(self):
@@ -101,23 +117,23 @@
 def getstats():
     stats = DSLStats()
     parser = ConfigParser.ConfigParser()
-    base = 'http://%s' % (conf.get('global', 'name'))
+    base = 'http://%s' % (args.name)
     br = mechanize.Browser()
     #br.set_debug_http(True)
     #br.set_debug_responses(True)
     #br.set_debug_redirects(True)
     cj = mechanize.LWPCookieJar()
-    if os.path.exists(conf.get('global', 'cookiejar')):
-        cj.load(conf.get('global', 'cookiejar'), ignore_discard = True)
+    if os.path.exists(args.cookiejar):
+        cj.load(args.cookiejar, ignore_discard = True)
     br.set_cookiejar(cj)
     if not fillstats(br, base, stats):
-        if not authenticate(br, base, conf.get('global', 'username'), conf.get('global', 'password')):
+        if not authenticate(br, base, args.username, args.password):
             print('login failed')
             return None
-        print('login succeeded, getting stats')
+        #print('login succeeded, getting stats')
         fillstats(br, base, stats)
 
-    cj.save(conf.get('global', 'cookiejar'), ignore_discard = True)
+    cj.save(args.cookiejar, ignore_discard = True)
     return stats
 
 def authenticate(br, base, username, password):
@@ -372,17 +388,17 @@
 
 if __name__ == "__main__":
     names = ['Noise Margin (up)', 'Noise Margin (down)', 'Attenuation (up)', 'Attenuation (down)']
-    if options.munin != None:
+    if args.munin != None:
         # Handle the wrapper passing us its $0 as our $1
-        tmp = options.munin.split('_')
+        tmp = args.munin.split('_')
         if len(tmp) > 1:
-            options.munin = tmp[-1]
-        if options.munin not in ['signal', 'sync']:
-            print "Unknown data type ", options.munin
+            args.munin = tmp[-1]
+        if args.munin not in ['signal', 'sync']:
+            print "Unknown data type ", args.munin
             sys.exit(1)
         if len(args) > 0:
             if args[0] == 'config':
-                if options.munin == 'signal':
+                if args.munin == 'signal':
                     print '''graph_category adsl
 graph_title DSL Signal Quality
 graph_args --base 1000 -l 0
@@ -393,7 +409,7 @@
 %s.type GAUGE
 %s.max 100
 %s.min 0''' % (name, n, name, name, name)
-                elif options.munin == 'sync':
+                elif args.munin == 'sync':
                     print '''graph_category adsl
 graph_title DSL Sync Speed
 graph_args --base 1024 -l 0
@@ -415,15 +431,15 @@
 downmax.max 150000
 downmax.min 0'''
             sys.exit(0)
-    if options.update or options.munin:
+    if args.update or args.munin:
         stats = getdata()
-        if options.verbose:
+        if args.verbose:
             if stats == None:
                 print "Modem is offline"
             else:
                 print stats
-    if (options.update or options.munin != None) and stats != None:
-        if options.update:
+    if (args.update or args.munin != None) and stats != None:
+        if args.update:
             try:
                 os.stat(rrdname)
             except OSError, e:
@@ -431,19 +447,19 @@
                     print "rrd not found, creating.."
                     makerrd(rrdname)
             updaterrd(rrdname, int(time.time()), stats)
-        if options.munin != None:
-            if options.munin == 'signal':
+        if args.munin != None:
+            if args.munin == 'signal':
                 print '''noisemarginup.value %.1f
 noisemargindown.value %.1f
 attenuationup.value %.1f
 attenuationdown.value %.1f''' % (stats.nmup, stats.nmdown, stats.attenup, stats.attendown)
-            elif options.munin == 'sync':
+            elif args.munin == 'sync':
                 s = '''up.value %.1f
 down.value %.1f\n''' % (stats.upstream, stats.downstream)
                 if hasattr(stats, 'upstreammax'):
                     s += '''upmax.value %.1f
 downmax.value %.1f''' % (stats.upstreammax, stats.downstreammax)
                 print s
-    if options.graph:
+    if args.graph:
         gengraph()