+ use OptionParser in optparse python module instead of getopt
authorStephen Soltesz <soltesz@cs.princeton.edu>
Wed, 8 Aug 2007 13:25:57 +0000 (13:25 +0000)
committerStephen Soltesz <soltesz@cs.princeton.edu>
Wed, 8 Aug 2007 13:25:57 +0000 (13:25 +0000)
config.py

index c9613ff..a3032c0 100644 (file)
--- a/config.py
+++ b/config.py
@@ -4,29 +4,120 @@ import os
 import getopt
 import sys
 import __main__
+from optparse import OptionParser
+
+config_command = False
 
 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
+def parse_bool(option, opt_str, value, parser):
+       if opt_str in ["--debug"]:
+               parser.values.debug = int(int(value))
+       elif opt_str in ["--mail"]:
+               parser.values.mail = int(int(value))
+       elif opt_str in ["--bcc"]:
+               parser.values.bcc = int(int(value))
+       elif opt_str in ["--policysavedb"]:
+               parser.values.policysavedb = int(int(value))
+       elif opt_str in ["--squeeze"]:
+               parser.values.squeeze = int(int(value))
+       else:
+               print "blue"
 
 class config:
-       debug = True
-       mail = False
-       bcc  = True
-       email = "soltesz@cs.utk.edu"
-       userlist = None
-       cachert = True
-       cachenodes = True
-       cachesites = True
-       squeeze = False
-       policysavedb = True
+       debug=0
+       mail=0
+       bcc=0
+       email="soltesz@cs.utk.edu"
+       run=False
+       checkopt=False
+       squeeze=0
+       policysavedb=0
        __file = ".config"
 
-       def __init__(self):
-                if os.path.exists(self.__file): # file exists, read that.
-                       f = open(self.__file, 'r')
+       def __init__(self, parser=None):
+               if os.path.exists(self.__file): # file exists, read that.
+                       f = open(self.__file, 'r')
                        o = pickle.load(f)
                        self.__dict__.update(o)
                        f.close()
 
+               if parser == None:
+                       self.parser = OptionParser()
+               else:
+                       self.parser = parser
+
+               self.parser.set_defaults(debug = self.debug,
+                                                               mail = self.mail,
+                                                               bcc  = self.bcc,
+                                                               email = self.email,
+                                                               run = self.run,
+                                                               checkopt = False,
+                                                               squeeze = self.squeeze,
+                                                               policysavedb = self.policysavedb)
+
+               self.parser.add_option("", "--debug", dest="debug",
+                                                 help="Enable debugging", 
+                                                 type="int",
+                                                 metavar="[0|1]",
+                                                 action="callback", 
+                                                 callback=parse_bool)
+               self.parser.add_option("", "--mail", dest="mail",
+                                                 help="Enable sending email",
+                                                 type="int",
+                                                 metavar="[0|1]",
+                                                 action="callback", 
+                                                 callback=parse_bool)
+               self.parser.add_option("", "--bcc", dest="bcc",
+                                                 help="Include BCC to user",
+                                                 type="int",
+                                                 metavar="[0|1]",
+                                                 action="callback", 
+                                                 callback=parse_bool)
+               self.parser.add_option("", "--squeeze", dest="squeeze",
+                                                 help="Squeeze sites or not",
+                                                 type="int",
+                                                 metavar="[0|1]",
+                                                 action="callback", 
+                                                 callback=parse_bool)
+               self.parser.add_option("", "--policysavedb", dest="policysavedb",
+                                                 help="Save the policy event database after a run",
+                                                 type="int",
+                                                 metavar="[0|1]",
+                                                 action="callback", 
+                                                 callback=parse_bool)
+               self.parser.add_option("", "--checkopt", dest="checkopt", 
+                                                 action="store_true",
+                                                 help="print current options")
+               self.parser.add_option("", "--run", dest="run", 
+                                                 action="store_true",
+                                                 help="Perform monitor or print configs")
+               self.parser.add_option("", "--email", dest="email",
+                                                 help="Specify an email address to use for mail when "+\
+                                                                "debug is enabled or for bcc when it is not")
+               
+               # config_command is needed to keep subsequent loads of config() from
+               # trying to parse the arguments that have already been parsed by
+               # the new main().
+               if parser == None and config_command:
+                       print "calling parse_args"
+                       self.parse_args()
+
+       def parse_args(self):
+               #print "self: %s" % self
+               #import traceback
+               #print traceback.print_stack()
+               #print "Ccalling parse_args"
+               (options, args) = self.parser.parse_args()
+               #for o in options.__dict__:
+               #       print "optin: %s == %s" % (o, options.__dict__[o])
+               self.__dict__.update(options.__dict__)
+               self.__dict__['args'] = args
+               self.save(options)
+               if options.checkopt:
+                       self.usage()
+               #       print "\nAdd --run to actually perform the command"
+                       sys.exit(1)
+
        def getListFromFile(self, file):
                f = open(file, 'r')
                list = []
@@ -34,109 +125,50 @@ class config:
                        line = line.strip()
                        list += [line]
                return list
+
+       def print_values(self):
+               exclude = ['parser']
+               for key in self.__dict__.keys():
+                       if key not in exclude:
+                               print "%20s == %s" % (key, self.__dict__[key])
                
-       def save(self):
+       def save(self, options=None):
                f = open(self.__file, 'w')
-               o = {'debug': self.debug, 
-                        'mail': self.mail
-                        'bcc': self.bcc
-                        'email':self.email,
-                        'userlist': self.userlist,
-                        'cachert': self.cachert, 
-                        'cachenodes' : self.cachenodes, 
-                        'cachesites': self.cachesites,
-                        'squeeze':self.squeeze,
-                        'policysavedb':self.policysavedb}
+               if options == None:
+                       o = {'debug': self.debug
+                                'mail': self.mail
+                                'bcc': self.bcc, 
+                                'email':self.email,
+                                'squeeze':self.squeeze,
+                                'policysavedb':self.policysavedb}
+               else:
+                       o = options.__dict__
+
                pickle.dump(o, f)
                f.close()
 
+       def usage(self):
+               self.print_values()
+               self.parser.print_help()
 
-def usage():
-       config = __main__.config()
-     #   --cachesites=[0|1]      Cache Sites from PLC (current: %s)
-     #  --status                Print memory usage statistics and exit
-       print """
-Settings:
-        --debug=[0|1]           Set debugging        (current: %s)
-        --mail=[0|1]            Send mail or not     (current: %s)
-        --bcc=[0|1]             Include bcc of user  (current: %s)
-        --email=[email]         Email to use above   (current: %s)
-        --userlist=[filename]   Use a list of nodes  (current: %s)
-        --cachert=[0|1]        Cache the RT db      (current: %s)
-        --cachenodes=[0|1]      Cache Nodes from PLC (current: %s)
-        --squeeze=[0|1]         Squeeze sites or not (current: %s)
-        --policysavedb=[0|1]    Save policy DBs      (current: %s)
-        -h, --help              This message
-""".lstrip() % (config.debug, 
-                           config.mail, 
-                               config.bcc, 
-                           config.email, 
-                               config.userlist, 
-                               config.cachert, 
-                               config.cachenodes, 
-                               config.squeeze, 
-                               config.policysavedb)
 
 def main():
        """ Start threads, do some housekeeping, then daemonize. """
        # Defaults
+       global config_command
+       config_command = True
        config = __main__.config()
 
        try:
-               longopts = [ "debug=", 
-                                       "mail=", 
-                                       "email=", 
-                                       "bcc=", 
-                                       "userlist=",
-                                       "cachert=", 
-                                       "cachesites=", 
-                                       "cachenodes=", 
-                                       "squeeze=", 
-                                       "policysavedb=", 
-                                       "status", 
-                                       "help"]
-               (opts, argv) = getopt.getopt(sys.argv[1:], "h", longopts)
-       except getopt.GetoptError, err:
-               print "Error: " + err.msg
-               usage()
+               print "acalling parse_args"
+               config.parse_args()
+               
+       except Exception, err:
+               print "Error: %s " %  err
+               config.usage()
                sys.exit(1)
 
-       for (opt, optval) in opts:
-               if opt in ["--debug"]:
-                       config.debug = bool(int(optval))
-                       print "Running in DEBUG mode. Copying DB & "
-                       print "caching correspondences. NO SQUEEZING."
-               elif opt in ["--mail"]:
-                       config.mail = bool(int(optval))
-                       print "NO EMAILS SENT."
-               elif opt in ["--email"]:
-                       config.email = optval
-               elif opt in ["--bcc"]:
-                       config.bcc = bool(int(optval))
-               elif opt in ["--userlist"]:
-                       if len(optval) == 0:
-                               config.userlist = None
-                       else:
-                               config.userlist = optval
-               elif opt in ["--cachert"]:
-                       config.cachert = bool(int(optval))
-               elif opt in ["--cachesites"]:
-                       config.cachesites = bool(int(optval))
-               elif opt in ["--cachenodes"]:
-                       config.cachenodes = bool(int(optval))
-               elif opt in ["--policysavedb"]:
-                       config.policysavedb = bool(int(optval))
-               elif opt in ["--squeeze"]:
-                       config.squeeze = bool(int(optval))
-               elif opt in ["--status"]:
-                       #print summary(names)
-                       sys.exit(0)
-               else:
-                       usage()
-                       sys.exit(0)
-
-       config.save()
-       usage()
+       config.usage()
 
 
 if __name__ == '__main__':