3 # This script is used to manipulate the operational state of nodes in
4 # different node groups. These are basically set operations on nodes via the
7 # Take the ng name as an argument....
9 # * get a list of nodes in the given nodegroup.
10 # * set some or all in the set to rins.
12 # * do something else to them all.
19 from optparse import OptionParser
21 from monitor import config
22 from monitor import parser as parsermodule
23 from monitor.common import *
24 from monitor.const import MINUP
25 from monitor.model import *
26 from monitor.wrapper import plc
27 from monitor.wrapper import plccache
28 from monitor.database.info.model import *
29 from monitor.database.info.interface import *
31 from monitor.query import verify,query_to_dict,node_select
33 api = plc.getAuthAPI()
37 plc.nodeBootState(host, 'reinstall')
40 def check_node_and_pcu_status_for(loginbase):
42 this function checks whether all the nodes and associated pcus for a
43 given site are considered 'good'.
45 If so, the function returns True.
46 Otherwise, the function returns False.
50 for node in plccache.plcdb_lb2hn[loginbase]:
52 noderec = FindbadNodeRecord.findby_or_create(hostname=node['hostname'])
53 nodehist = HistoryNodeRecord.findby_or_create(hostname=node['hostname'])
54 nodebl = BlacklistRecord.get_by(hostname=node['hostname'])
55 pcuhist = HistoryPCURecord.get_by(plc_pcuid=noderec.plc_pcuid)
57 if (nodehist is not None and nodehist.status == 'good' and \
58 ((pcuhist is not None and pcuhist.status == 'good') or (pcuhist is None)) ):
59 if nodebl is None: # no entry in blacklist table
61 elif nodebl is not None and nodebl.expired(): # expired entry in blacklist table
64 results.append(False) # entry that is not expired.
69 print "test: %s" % results
70 # NOTE: incase results is empty, reduce does not work on an empty set.
71 return reduce(lambda x,y: x&y, results) and len(results) > MINUP
75 def main(hostnames, sitenames):
80 #print "hosts: %s" % hostnames
82 for i,host in enumerate(hostnames):
84 lb = plccache.plcdb_hn2lb[host]
86 print "unknown host in plcdb_hn2lb %s" % host
87 email_exception("%s %s" % (i,host))
90 nodeblack = BlacklistRecord.get_by(hostname=host)
92 if nodeblack and not nodeblack.expired():
93 print "skipping %s due to blacklist. will expire %s" % (host, nodeblack.willExpire() )
96 sitehist = SiteInterface.get_or_make(loginbase=lb)
98 recent_actions = sitehist.getRecentActions(hostname=host)
100 nodehist = HistoryNodeRecord.findby_or_create(hostname=host)
102 print "%s %s %s" % (i, nodehist.hostname, nodehist.status)
103 if nodehist.status == 'good' and \
104 changed_lessthan(nodehist.last_changed, 1.0) and \
105 found_within(recent_actions, 'down_notice', 7.0) and \
106 not found_within(recent_actions, 'online_notice', 0.5):
107 # NOTE: chronicly flapping nodes will not get 'online' notices
108 # since, they are never up long enough to be 'good'.
109 # NOTE: searching for down_notice proves that the node has
110 # gone through a 'down' state first, rather than just
111 # flapping through: good, offline, online, ...
113 # NOTE: there is a narrow window in which this command must be
114 # evaluated, otherwise the notice will not go out.
116 sitehist.sendMessage('online_notice', hostname=host, viart=False, saveact=True)
117 print "send message for host %s online" % host
120 # if a node is offline and doesn't have a PCU, remind the user that they should have one.
121 #if not nodehist.haspcu and nodehist.status in ['offline', 'down'] and \
122 # changed_greaterthan(nodehist.last_changed,1.0) and \
123 # not found_within(recent_actions, 'pcumissing_notice', 7.0):
125 # sitehist.sendMessage('pcumissing_notice', hostname=host)
126 # print "send message for host %s pcumissing_notice" % host
128 # if it is offline and HAS a PCU, then try to use it.
129 if nodehist.haspcu and nodehist.status in ['offline', 'down'] and \
130 changed_greaterthan(nodehist.last_changed,1.0) and \
131 not nodehist.firewall and \
132 not found_between(recent_actions, 'try_reboot', 3.5, 1):
134 # TODO: there MUST be a better way to do this...
135 # get fb node record for pcuid
137 fbnode = FindbadNodeRecord.get_latest_by(hostname=host)
139 fbpcu = FindbadPCURecord.get_latest_by(plc_pcuid=fbnode.plc_pcuid)
141 sitehist.attemptReboot(host)
142 print "send message for host %s try_reboot" % host
143 if False and not fbpcu.test_is_ok() and \
144 not found_within(recent_actions, 'pcuerror_notice', 3.0):
148 args['pcu_name'] = fbpcu.pcu_name()
149 args['pcu_errors'] = fbpcu.pcu_errors()
150 args['plc_pcuid'] = fbpcu.plc_pcuid
152 args['pcu_name'] = "error looking up pcu name"
153 args['pcu_errors'] = ""
154 args['plc_pcuid'] = 0
156 args['hostname'] = host
157 sitehist.sendMessage('pcuerror_notice', **args)
158 print "send message for host %s PCU Failure" % host
161 # NOTE: non-intuitive is that found_between(try_reboot, 3.5, 1)
162 # will be false for a day after the above condition is satisfied
163 if False and nodehist.haspcu and nodehist.status in ['offline', 'down'] and \
164 changed_greaterthan(nodehist.last_changed,1.5) and \
165 not nodehist.firewall and \
166 found_between(recent_actions, 'try_reboot', 3.5, 1) and \
167 not found_within(recent_actions, 'pcufailed_notice', 3.5):
169 # TODO: there MUST be a better way to do this...
170 # get fb node record for pcuid
172 fbnode = FindbadNodeRecord.get_latest_by(hostname=host)
174 fbpcu = FindbadPCURecord.get_latest_by(plc_pcuid=fbnode.plc_pcuid)
176 pcu_name = fbpcu.pcu_name()
178 pcu_name = "error looking up pcu name"
180 # get fb pcu record for pcuid
181 # send pcu failure message
182 sitehist.sendMessage('pcufailed_notice', hostname=host, pcu_name=pcu_name)
183 print "send message for host %s PCU Failure" % host
185 if nodehist.status == 'down' and \
186 changed_greaterthan(nodehist.last_changed, 2):
187 if not nodehist.firewall and not found_within(recent_actions, 'down_notice', 3.5):
188 # send down node notice
189 sitehist.sendMessage('down_notice', hostname=host)
190 print "send message for host %s down" % host
192 #if nodehist.firewall and not found_within(recent_actions, 'firewall_notice', 3.5):
193 # send down node notice
194 #email_exception(host, "firewall_notice")
195 # sitehist.sendMessage('firewall_notice', hostname=host)
196 # print "send message for host %s down" % host
198 node_count = node_count + 1
199 print "time: ", time.strftime('%Y-%m-%d %H:%M:%S')
203 for i,site in enumerate(sitenames):
204 sitehist = SiteInterface.get_or_make(loginbase=site)
205 siteblack = BlacklistRecord.get_by(loginbase=site)
206 skip_due_to_blacklist=False
209 site_exempt = plc.isSiteExempt(site)
213 if siteblack and not siteblack.expired() or site_exempt:
215 print "skipping %s due to blacklist. will expire %s" % (site, siteblack.willExpire() )
217 print "skipping %s due to blacklist." % (site)
218 skip_due_to_blacklist=True
219 sitehist.clearPenalty()
220 sitehist.applyPenalty()
223 # TODO: make query only return records within a certin time range,
224 # i.e. greater than 0.5 days ago. or 5 days, etc.
225 recent_actions = sitehist.getRecentActions(loginbase=site)
227 print "%s %s %s" % (i, sitehist.db.loginbase, sitehist.db.status)
229 if sitehist.db.status == 'down':
230 if sitehist.db.penalty_pause and \
231 changed_greaterthan(sitehist.db.penalty_pause_time, 30):
233 email_exception("", "clear pause penalty for site: %s" % sitehist.db.loginbase)
234 sitehist.closeTicket()
235 # NOTE: but preserve the penalty status.
236 sitehist.clearPenaltyPause()
238 if sitehist.db.message_id != 0 and \
239 sitehist.db.message_status == 'open' and \
240 not sitehist.db.penalty_pause:
242 email_exception("", "pause penalty for site: %s" % sitehist.db.loginbase)
243 sitehist.setPenaltyPause()
245 if not sitehist.db.penalty_pause and \
246 not found_within(recent_actions, 'increase_penalty', 7) and \
247 changed_greaterthan(sitehist.db.last_changed, 7):
250 sitehist.increasePenalty()
251 sitehist.applyPenalty()
252 sitehist.sendMessage('increase_penalty')
254 print "send message for site %s penalty increase" % site
256 if sitehist.db.status == 'good':
258 # NOTE: because 'all clear' should have an indefinite status, we
259 # have a boolean value rather than a 'recent action'
260 if sitehist.db.penalty_applied or sitehist.db.penalty_pause:
261 # send message that penalties are cleared.
263 sitehist.clearPenalty()
264 sitehist.applyPenalty()
265 sitehist.sendMessage('clear_penalty')
266 sitehist.closeTicket()
268 print "send message for site %s penalty cleared" % site
270 # check all nodes and pcus for this site; if they're all ok,
271 # close the ticket, else leave it open.
272 # NOTE: in the case where a PCU reboots and fails, a message is
273 # sent, but the PCU may appear to be ok according to tests.
274 # NOTE: Also, bootmanager sends messages regarding disks,
275 # configuration, etc. So, the conditions here are 'good'
276 # rather than 'not down' as it is in sitebad.
277 close_ticket = check_node_and_pcu_status_for(site)
279 sitehist.closeTicket()
281 site_count = site_count + 1
283 print "time: ", time.strftime('%Y-%m-%d %H:%M:%S')
291 if __name__ == "__main__":
292 parser = parsermodule.getParser(['nodesets'])
293 parser.set_defaults( timewait=0,
303 parser.add_option("", "--stopselect", dest="stopselect", metavar="",
304 help="The select string that must evaluate to true for the node to be considered 'done'")
305 parser.add_option("", "--findbad", dest="findbad", action="store_true",
306 help="Re-run findbad on the nodes we're going to check before acting.")
307 parser.add_option("", "--force", dest="force", action="store_true",
308 help="Force action regardless of previous actions/logs.")
309 parser.add_option("", "--rins", dest="rins", action="store_true",
310 help="Set the boot_state to 'rins' for all nodes.")
311 parser.add_option("", "--reboot", dest="reboot", action="store_true",
312 help="Actively try to reboot the nodes, keeping a log of actions.")
314 parser.add_option("", "--verbose", dest="verbose", action="store_true",
315 help="Extra debug output messages.")
316 parser.add_option("", "--nosetup", dest="nosetup", action="store_true",
317 help="Do not perform the orginary setup phase.")
318 parser.add_option("", "--skip", dest="skip",
319 help="Number of machines to skip on the input queue.")
320 parser.add_option("", "--timewait", dest="timewait",
321 help="Minutes to wait between iterations of 10 nodes.")
323 parser = parsermodule.getParser(['defaults'], parser)
324 config = parsermodule.parse_args(parser)
326 fbquery = HistoryNodeRecord.query.all()
327 hostnames = [ n.hostname for n in fbquery ]
329 fbquery = HistorySiteRecord.query.all()
330 sitenames = [ s.loginbase for s in fbquery ]
333 # TODO: replace with calls to local db. the api fails so often that
334 # these calls should be regarded as unreliable.
335 l_nodes = plccache.GetNodesBySite(config.site)
336 filter_hostnames = [ n['hostname'] for n in l_nodes ]
338 hostnames = filter(lambda x: x in filter_hostnames, hostnames)
339 sitenames = [config.site]
342 hostnames = [ config.node ]
343 sitenames = [ plccache.plcdb_hn2lb[config.node] ]
346 main(hostnames, sitenames)
348 except KeyboardInterrupt:
349 print "Killed by interrupt"
354 print traceback.print_exc();