tweaks
[monitor.git] / grouprins.py
index 99af752..92a745c 100755 (executable)
 # 
 
 import plc
-import auth
-api = plc.PLC(auth.auth, auth.plc)
+api = plc.getAuthAPI()
 
 import policy
-
+import traceback
 from config import config as cfg
+import util.file
 from optparse import OptionParser
 
 from nodecommon import *
 from nodequery import verify,query_to_dict,node_select
-import soltesz
+import database
 from unified_model import *
+import os
 
 import time
+import parser as parsermodule
 
 from model import *
 import bootman                 # debug nodes
 import monitor         # down nodes with pcu
 import reboot          # down nodes without pcu
-reboot.verbose = 0
+from emailTxt import mailtxt
+#reboot.verbose = 0
 import sys
 
 class Reboot(object):
@@ -50,7 +53,7 @@ class Reboot(object):
                m = PersistMessage(host, mailtxt.pcudown_one[0] % args,
                                                                 mailtxt.pcudown_one[1] % args, True, db='pcu_persistmessages')
 
-               loginbase = plc.siteId(hostname)
+               loginbase = plc.siteId(host)
                m.send([policy.TECHEMAIL % loginbase])
 
        def pcu(self, host):
@@ -59,8 +62,8 @@ class Reboot(object):
                if self.fbnode['pcu'] == "PCU": 
                        self.action = "reboot.reboot('%s')" % host
 
-                       pflags = PersistFlags(host, 1*60*60*24, db='pcu_persistflags')
-                       if not pflags.getRecentFlag('pcutried'): # or not pflags.getFlag('pcufailed'):
+                       pflags = PersistFlags(host, 2*60*60*24, db='pcu_persistflags')
+                       if not pflags.getRecentFlag('pcutried'):
                                pflags.setRecentFlag('pcutried')
                                try:
                                        ret = reboot.reboot(host)
@@ -69,7 +72,7 @@ class Reboot(object):
                                        return ret
 
                                except Exception,e:
-                                       import traceback; print traceback.print_exc(); print e
+                                       print traceback.print_exc(); print e
 
                                        # NOTE: this failure could be an implementation issue on
                                        #               our end.  So, extra notices are confusing...
@@ -87,10 +90,11 @@ class Reboot(object):
 
                                        pflags.setRecentFlag('pcumessagesent')
                                        pflags.save()
+                                       # NOTE: this will result in just one message sent at a time.
+                                       return True
 
                                else:
-                                       pass # just skip it?
-
+                                       return False
                else:
                        self.action = "None"
                        return False
@@ -109,7 +113,7 @@ class Reboot(object):
                try:
                        return monitor.reboot(host)
                except Exception, e:
-                       import traceback; print traceback.print_exc(); print e
+                       print traceback.print_exc(); print e
                        return False
 
 class RebootDebug(Reboot):
@@ -130,18 +134,34 @@ class RebootDown(Reboot):
                self.action = "None"
                return False    # this always fails, since the node will be down.
 
+def set_node_to_rins(host, fb):
+
+       node = api.GetNodes(host, ['boot_state', 'last_contact', 'last_updated', 'date_created'])
+       record = {'observation' : node[0], 
+                         'model' : 'USER_REQUEST', 
+                         'action' : 'api.UpdateNode(%s, {"boot_state" : "rins"})' % host, 
+                         'time' : time.time()}
+       l = Log(host, record)
+
+       ret = api.UpdateNode(host, {'boot_state' : 'rins'})
+       if ret:
+               # it's nice to see the current status rather than the previous status on the console
+               node = api.GetNodes(host)[0]
+               print l
+               print "%-2d" % (i-1), nodegroup_display(node, fb)
+               return l
+       else:
+               print "FAILED TO UPDATE NODE BOOT STATE : %s" % host
+               return None
+
 
 try:
-       rebootlog = soltesz.dbLoad("rebootlog")
+       rebootlog = database.dbLoad("rebootlog")
 except:
        rebootlog = LogRoll()
 
-parser = OptionParser()
-parser.set_defaults(nodegroup=None,
-                                       node=None,
-                                       nodelist=None,
-                                       nodeselect=None,
-                                       timewait=30,
+parser = parsermodule.getParser(['nodesets'])
+parser.set_defaults( timewait=0,
                                        skip=0,
                                        rins=False,
                                        reboot=False,
@@ -153,33 +173,9 @@ parser.set_defaults(nodegroup=None,
                                        stopvalue=None,
                                        quiet=False,
                                        )
-parser.add_option("", "--node", dest="node", metavar="nodename.edu", 
-                                       help="A single node name to add to the nodegroup")
-parser.add_option("", "--nodelist", dest="nodelist", metavar="list.txt", 
-                                       help="Use all nodes in the given file for operation.")
-parser.add_option("", "--nodegroup", dest="nodegroup", metavar="NodegroupName",
-                                       help="Specify a nodegroup to perform actions on")
-parser.add_option("", "--nodeselect", dest="nodeselect", metavar="querystring",
-                                       help="Specify a query to perform on findbad db")
-
-parser.add_option("", "--verbose", dest="verbose", action="store_true", 
-                                       help="Extra debug output messages.")
-parser.add_option("", "--nosetup", dest="nosetup", action="store_true", 
-                                       help="Do not perform the orginary setup phase.")
-
-parser.add_option("", "--skip", dest="skip", 
-                                       help="Number of machines to skip on the input queue.")
-parser.add_option("", "--timewait", dest="timewait", 
-                                       help="Minutes to wait between iterations of 10 nodes.")
 
 parser.add_option("", "--stopselect", dest="stopselect", metavar="", 
                                        help="The select string that must evaluate to true for the node to be considered 'done'")
-
-parser.add_option("", "--stopkey", dest="stopkey", metavar="", 
-                                       help="")
-parser.add_option("", "--stopvalue", dest="stopvalue", metavar="", 
-                                       help="")
-
 parser.add_option("", "--findbad", dest="findbad", action="store_true", 
                                        help="Re-run findbad on the nodes we're going to check before acting.")
 parser.add_option("", "--force", dest="force", action="store_true", 
@@ -188,9 +184,18 @@ parser.add_option("", "--rins", dest="rins", action="store_true",
                                        help="Set the boot_state to 'rins' for all nodes.")
 parser.add_option("", "--reboot", dest="reboot", action="store_true", 
                                        help="Actively try to reboot the nodes, keeping a log of actions.")
-#config = config(parser)
-config = cfg(parser)
-config.parse_args()
+
+parser.add_option("", "--verbose", dest="verbose", action="store_true", 
+                                       help="Extra debug output messages.")
+parser.add_option("", "--nosetup", dest="nosetup", action="store_true", 
+                                       help="Do not perform the orginary setup phase.")
+parser.add_option("", "--skip", dest="skip", 
+                                       help="Number of machines to skip on the input queue.")
+parser.add_option("", "--timewait", dest="timewait", 
+                                       help="Minutes to wait between iterations of 10 nodes.")
+
+parser = parsermodule.getParser(['defaults'], parser)
+config = parsermodule.parse_args(parser)
 
 # COLLECT nodegroups, nodes and node lists
 if config.nodegroup:
@@ -207,24 +212,22 @@ if config.nodeselect:
 
 if config.findbad:
        # rerun findbad with the nodes in the given nodes.
-       import os
        file = "findbad.txt"
-       config.setFileFromList(file, hostnames)
+       util.file.setFileFromList(file, hostnames)
        os.system("./findbad.py --cachenodes --debug=0 --dbname=findbad --increment --nodelist %s" % file)
 
-fb = soltesz.dbLoad("findbad")
+fb = database.dbLoad("findbad")
 # commands:
 i = 1
 count = 1
 for host in hostnames:
 
        #if 'echo' in host or 'hptest-1' in host: continue
-
        try:
                try:
                        node = api.GetNodes(host)[0]
                except:
-                       import traceback; print traceback.print_exc(); 
+                       print traceback.print_exc(); 
                        print "FAILED GETNODES for host: %s" % host
                        continue
                        
@@ -259,26 +262,6 @@ for host in hostnames:
                        print "recently rebooted %s.  skipping... " % host
                        continue
 
-               if config.rins:
-                       # reset the boot_state to 'rins'
-                       node = api.GetNodes(host, ['boot_state', 'last_contact', 'last_updated', 'date_created'])
-                       record = {'observation' : node[0], 
-                                         'model' : 'USER_REQUEST', 
-                                         'action' : 'api.UpdateNode(%s, {"boot_state" : "rins"})' % host, 
-                                         'time' : time.time()}
-                       l = Log(host, record)
-
-                       ret = api.UpdateNode(host, {'boot_state' : 'rins'})
-                       if ret:
-                               # it's nice to see the current status rather than the previous status on the console
-                               node = api.GetNodes(host)[0]
-                               print l
-                               print "%-2d" % (i-1), nodegroup_display(node, fb)
-                               rebootlog.add(l)
-                       else:
-                               print "FAILED TO UPDATE NODE BOOT STATE : %s" % host
-
-
                if config.reboot:
 
                        fbnode = fb['nodes'][host]['values']
@@ -288,9 +271,17 @@ for host in hostnames:
                                o = RebootDebug(fbnode)
 
                        elif observed_state == "boot" :
+                               if config.rins:
+                                       l = set_node_to_rins(host, fb)
+                                       if l: rebootlog.add(l)
+
                                o = RebootBoot(fbnode)
 
                        elif observed_state == "down":
+                               if config.rins:
+                                       l = set_node_to_rins(host, fb)
+                                       if l: rebootlog.add(l)
+
                                o = RebootDown(fbnode)
 
 
@@ -316,6 +307,12 @@ for host in hostnames:
                                                  'time' : time.time()}
 
                                print "ALL METHODS OF RESTARTING %s FAILED" % host
+                               args = {}
+                               args['hostname'] = host
+                               m = PersistMessage(host, "ALL METHODS FAILED for %(hostname)s" % args,
+                                                                                        "CANNOT CONTACT", False, db='suspect_persistmessages')
+                               m.reset()
+                               m.send(['monitor-list@lists.planet-lab.org'])
 
                        l = Log(host, record)
                        print l
@@ -324,13 +321,13 @@ for host in hostnames:
                print "Killed by interrupt"
                sys.exit(0)
        except:
-               import traceback; print traceback.print_exc();
+               print traceback.print_exc();
                print "Continuing..."
 
        time.sleep(1)
        if count % 10 == 0:
                print "Saving rebootlog"
-               soltesz.dbDump("rebootlog", rebootlog)
+               database.dbDump("rebootlog", rebootlog)
                wait_time = int(config.timewait)
                print "Sleeping %d minutes" % wait_time
                ti = 0
@@ -345,4 +342,4 @@ for host in hostnames:
        count = count + 1
 
 print "Saving rebootlog"
-soltesz.dbDump("rebootlog", rebootlog)
+database.dbDump("rebootlog", rebootlog)