Debian Codegraph @

lib/plugins/stonith/external/riloe

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 #
3 # Stonith module for RILOE Stonith device
4 #
5 # Copyright (c) 2004 Alain St-Denis <[email protected]>
6 #
7 # Modified by Alan Robertson <[email protected]> for STONITH external compatibility.
8 #
9 # Extended and merged by Tijl Van den broeck <[email protected]>
10 # with ilo-v2 script from Guy Coates
11 #
12 # Cleanup by Andrew Beekhof <[email protected]>
13 #
14 # Rewritten by Dejan Muhamedagic <[email protected]>
15 # Now, the plugin actually reads replies from iLO.
16 #
17 # Extended by Jochen Roeder <[email protected]>
18 # to enable access via proxies
19 #
20 # This library is free software; you can redistribute it and/or
21 # modify it under the terms of the GNU Lesser General Public
22 # License as published by the Free Software Foundation; either
23 # version 2.1 of the License, or (at your option) any later version.
24 #
25 # This library is distributed in the hope that it will be useful,
26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 # Lesser General Public License for more details.
29 #
30 # You should have received a copy of the GNU Lesser General Public
31 # License along with this library; if not, write to the Free Software
32 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #
34 import sys
35 import os
36 import socket
37 import subprocess
38 import xml.dom.minidom
39 import httplib
40 import time
41 import re
42
43 def log_msg(level,msg):
44 subprocess.call("ha_log.sh %s '%s'" % (level,msg), shell=True)
45 def my_err(msg):
46 log_msg("err", msg)
47 def my_warn(msg):
48 log_msg("warn", msg)
49 def my_debug(msg):
50 log_msg("debug", msg)
51 def fatal(msg):
52 my_err(msg)
53 sys.exit(1)
54
55 argv = sys.argv
56
57 try:
58 cmd = argv[1]
59 except IndexError:
60 my_err("Not enough arguments")
61 sys.exit(1)
62
63 legacy_RI_HOST = os.environ.get('RI_HOST', '')
64 legacy_RI_HOSTRI = os.environ.get('RI_HOSTRI', '')
65 legacy_RI_LOGIN = os.environ.get('RI_LOGIN', 'Administrator')
66 legacy_RI_PASSWORD = os.environ.get('RI_PASSWORD', '')
67
68 reset_ok = os.environ.get('ilo_can_reset', '0')
69 ilo_protocol = os.environ.get('ilo_protocol', '1.2')
70 power_method = os.environ.get('ilo_powerdown_method', 'power')
71
72 realhost = os.environ.get('hostlist', legacy_RI_HOST)
73 rihost = os.environ.get('ilo_hostname', legacy_RI_HOSTRI)
74 ilouser = os.environ.get('ilo_user', legacy_RI_LOGIN)
75 ilopass = os.environ.get('ilo_password', legacy_RI_PASSWORD)
76 iloproxyhost = os.environ.get('ilo_proxyhost', '')
77 try:
78 iloproxyport = int(os.environ.get('ilo_proxyport', 3128))
79 except ValueError:
80 my_err("ilo_proxyport is not a number")
81 sys.exit(1)
82
83 xmlinfo = '''<parameters>
84 <parameter name="hostlist" unique="1" required="1">
85 <content type="string"/>
86 <shortdesc lang="en">ilo target hostname</shortdesc>
87 <longdesc lang="en">
88 Contains the hostname that the ilo controls
89 </longdesc>
90 </parameter>
91 <parameter name="ilo_hostname" unique="1" required="1">
92 <content type="string"/>
93 <shortdesc lang="en">ilo device hostname</shortdesc>
94 <longdesc lang="en">
95 The hostname of the ilo device
96 </longdesc>
97 </parameter>
98 <parameter name="ilo_user" unique="0" required="1">
99 <content type="string" default="Administrator"/>
100 <shortdesc lang="en">ilo user</shortdesc>
101 <longdesc lang="en">
102 The user for connecting to the ilo device
103 </longdesc>
104 </parameter>
105 <parameter name="ilo_password" unique="0" required="1">
106 <content type="string" default=""/>
107 <shortdesc lang="en">password</shortdesc>
108 <longdesc lang="en">
109 The password for the ilo device user
110 </longdesc>
111 </parameter>
112 <parameter name="ilo_can_reset" unique="0" required="0">
113 <content type="string" default="0"/>
114 <shortdesc lang="en">Device can reset</shortdesc>
115 <longdesc lang="en">
116 Does the ILO device support RESET commands (hint: older ones cannot)
117 </longdesc>
118 </parameter>
119 <parameter name="ilo_protocol" unique="0" required="0">
120 <content type="string" default="1.2"/>
121 <shortdesc lang="en">ILO Protocol</shortdesc>
122 <longdesc lang="en">
123 Protocol version supported by the ILO device.
124 Known supported versions: 1.2, 2.0
125 </longdesc>
126 </parameter>
127 <parameter name="ilo_powerdown_method" unique="0" required="0">
128 <content type="string" default="power"/>
129 <shortdesc lang="en">Power down method</shortdesc>
130 <longdesc lang="en">
131 The method to powerdown the host in question.
132 * button - Emulate holding down the power button
133 * power - Emulate turning off the machines power
134
135 NB: A button request takes around 20 seconds. The power method
136 about half a minute.
137 </longdesc>
138 </parameter>
139 <parameter name="ilo_proxyhost" unique="0" required="0">
140 <content type="string" default=""/>
141 <shortdesc lang="en">Proxy hostname</shortdesc>
142 <longdesc lang="en">
143 proxy hostname if required to access ILO board
144 </longdesc>
145 </parameter>
146 <parameter name="ilo_proxyport" unique="0" required="0">
147 <content type="string" default="3128"/>
148 <shortdesc lang="en">Proxy port</shortdesc>
149 <longdesc lang="en">
150 proxy port if required to access ILO board
151 parameter will be ignored if proxy hostname is not set
152 </longdesc>
153 </parameter>
154
155 </parameters>'''
156
157 info = {
158 'getinfo-devid': 'iLO2',
159 'getinfo-devname': 'ilo2 ' + rihost,
160 'getinfo-devdescr': 'HP/COMPAQ iLO2 STONITH device',
161 'getinfo-devurl': 'http://www.hp.com/',
162 'gethosts': realhost,
163 'getinfo-xml': xmlinfo
164 }
165
166 if cmd in info:
167 print info[cmd]
168 sys.exit(0)
169
170 if cmd == 'getconfignames':
171 for arg in [ "hostlist", "ilo_hostname", "ilo_user", "ilo_password", "ilo_can_reset", "ilo_protocol", "ilo_powerdown_method", "ilo_proxyhost", "ilo_proxyport"]:
172 print arg
173 sys.exit(0)
174
175 if not rihost:
176 fatal("ILO device hostname not specified")
177
178 if not realhost:
179 fatal("Host controlled by this ILO device not specified")
180
181 if not power_method in ("power","button"):
182 my_err('unknown power method %s, setting to "power"')
183 power_method = "power"
184
185 # XML elements
186 E_RIBCL = "RIBCL"
187 E_LOGIN = "LOGIN"
188 E_SERVER_INFO = "SERVER_INFO"
189
190 # power mgmt methods
191 E_RESET = "RESET_SERVER" # error if powered off
192 E_COLD_BOOT = "COLD_BOOT_SERVER" # error if powered off
193 E_WARM_BOOT = "WARM_BOOT_SERVER" # error if powered off
194 E_PRESS_BUTTON = "PRESS_PWR_BTN"
195 E_HOLD_BUTTON = "HOLD_PWR_BTN"
196
197 # get/set status elements
198 E_SET_POWER = "SET_HOST_POWER"
199 E_GET_PSTATUS = "GET_HOST_POWER_STATUS"
200
201 # whatever this means, but we have to use it to get good XML
202 E_LOCFG = "LOCFG"
203 LOCFG_VER = '2.21'
204
205 # attributes
206 A_VERSION = "VERSION" # ilo_protocol
207 A_USER = "USER_LOGIN"
208 A_PWD = "PASSWORD"
209 A_MODE = "MODE" # info mode (read or write)
210 A_POWER_SW = "HOST_POWER" # "Y" or "N"
211 A_POWER_STATE = "HOST_POWER" # "ON" or "OFF"
212
213 def new_power_req(tag, name = None, value = None):
214 '''
215 Create a new RIBCL request (as XML).
216 '''
217 my_debug("creating power request: %s,%s,%s"%(tag,name,value))
218 doc = xml.dom.minidom.Document()
219 locfg = doc.createElement(E_LOCFG)
220 locfg.setAttribute(A_VERSION,LOCFG_VER)
221 ribcl = doc.createElement(E_RIBCL)
222 ribcl.setAttribute(A_VERSION,ilo_protocol)
223 login = doc.createElement(E_LOGIN)
224 login.setAttribute(A_USER,ilouser)
225 login.setAttribute(A_PWD,ilopass)
226 serv_info = doc.createElement(E_SERVER_INFO)
227 # read or write, it doesn't really matter, i.e. even if we
228 # say "write" that doesn't mean we can't read
229 serv_info.setAttribute(A_MODE,"write")
230 doc.appendChild(locfg)
231 locfg.appendChild(ribcl)
232 ribcl.appendChild(login)
233 login.appendChild(serv_info)
234 el_node = doc.createElement(tag)
235 if name:
236 el_node.setAttribute(name,value)
237 serv_info.appendChild(el_node)
238 s = doc.toprettyxml()
239 doc.unlink()
240 # work around an iLO bug: last line containing "</LOCFG>"
241 # produces a syntax error
242 lines = s.split('\n')
243 return '\n'.join(lines[:-2])
244
245 E_RESPONSE = "RESPONSE"
246 E_HOST_POWER = "GET_HOST_POWER"
247 A_STATUS = "STATUS"
248 # documentation mentions both; better safe than sorry
249 A_MSG = "MSG"
250 A_MSG2 = "MESSAGE"
251
252 def is_element(xmlnode):
253 return xmlnode.nodeType == xmlnode.ELEMENT_NODE
254
255 def read_resp(node):
256 '''
257 Check if the RESPONSE XML is OK.
258 '''
259 msg = ""
260 str_status = ""
261 for attr in node.attributes.keys():
262 if attr == A_STATUS:
263 str_status = node.getAttribute(attr)
264 elif attr == A_MSG:
265 msg = node.getAttribute(attr)
266 elif attr == A_MSG2:
267 msg = node.getAttribute(attr)
268 else:
269 my_warn("unexpected attribute %s in %s" % (attr,E_RESPONSE))
270 if not str_status:
271 my_err("no status in response")
272 return -1
273 try:
274 status = int(str_status,16)
275 except ValueError:
276 my_err("unexpected status %s in response" % str_status)
277 return -1
278 if status != 0:
279 my_err("%s (rc: %s)"%(msg,str_status))
280 return -1
281 return 0
282
283 def read_power(node):
284 '''
285 Read the power from the XML node. Set the global power
286 variable correspondingly.
287 '''
288 global power
289 for attr in node.attributes.keys():
290 if attr == A_POWER_STATE:
291 power_state = node.getAttribute(attr).upper()
292 else:
293 my_warn("unexpected attribute %s in %s" % (attr,node.tagName))
294 if not power_state:
295 my_err("no %s attribute in %s" % (A_POWER_STATE,node.tagName))
296 return -1
297 if power_state not in ("ON","OFF"):
298 my_err("unexpected value for %s: %s" % (A_POWER_STATE,power_state))
299 return -1
300 power = (power_state == "ON")
301 my_debug("Host has power: %s"%power)
302 return 0
303
304 el_parsers = {
305 E_RESPONSE:read_resp,
306 E_HOST_POWER:read_power
307 }
308 def proc_resp(doc):
309 '''
310 Process one iLO reply. Real work is done in el_parsers.
311 '''
312 ribcl = doc.childNodes[0]
313 if not is_element(ribcl) or ribcl.tagName != E_RIBCL:
314 my_err("unexpected top element in response")
315 return -1
316 for child in ribcl.childNodes:
317 if not is_element(child):
318 continue
319 if child.tagName in el_parsers:
320 rc = el_parsers[child.tagName](child)
321 if rc != 0:
322 return -1
323 else:
324 my_warn("unexpected element in response: %s" % child.toxml())
325 return 0
326
327 def open_ilo(host):
328 # open https connection
329 try:
330 if iloproxyhost != "" and iloproxyport != 0:
331 proxy=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
332 proxy.connect((iloproxyhost, iloproxyport))
333 proxy_connect='CONNECT %s:%s HTTP/1.1\r\n'%(host,443)
334 user_agent='User-Agent: python\r\n'
335 proxy_pieces=proxy_connect+user_agent+'\r\n'
336 proxy.sendall(proxy_pieces)
337 response=proxy.recv(8192)
338 status=response.split()[1]
339 if status!=str(200):
340 fatal("Error status=: %s" %(response))
341 import ssl
342 sock = ssl.wrap_socket(proxy)
343 h=httplib.HTTPConnection('localhost')
344 h.sock=sock
345 return h
346 else:
347 return httplib.HTTPSConnection(host)
348 except socket.gaierror, msg:
349 fatal("%s: %s" %(msg,host))
350 except socket.sslerror, msg:
351 fatal("%s for %s" %(msg,host))
352 except socket.error, msg:
353 fatal("%s while talking to %s" %(msg,host))
354 except ImportError, msg:
355 fatal("ssl support missing (%s)" %msg)
356
357 def send_request(req,proc_f):
358 '''
359 1. After every request, the iLO closes the connection.
360 2. For every request, there are multiple replies. Each reply
361 is an XML document. Most of replies are just a kind of
362 (verbose) XML "OK".
363 '''
364 t_begin = time.time()
365 c = open_ilo(rihost)
366 try:
367 c.send(req+'\r\n')
368 except socket.error, msg:
369 fatal("%s, while talking to %s" %(msg,rihost))
370 t_end = time.time()
371 my_debug("request sent in %0.2f s" % ((t_end-t_begin)))
372
373 t_begin = time.time()
374 result = []
375 while True:
376 try:
377 reply = c.sock.recv(1024)
378 if not reply:
379 break
380 result.append(reply)
381 except socket.error, msg:
382 if msg[0] == 6: # connection closed
383 break
384 my_err("%s, while talking to %s" %(msg,rihost))
385 return -1
386 c.close()
387 t_end = time.time()
388
389 if not result:
390 fatal("no response from %s within %0.2f s"%(rihost,(t_end-t_begin)))
391 for reply in result:
392 # work around the iLO bug, i.e. element RIBCL closed twice
393 if re.search("</RIBCL", reply) and re.search("<RIBCL.*/>", reply):
394 reply = re.sub("<(RIBCL.*)/>", r"<\1>", reply)
395 try:
396 doc = xml.dom.minidom.parseString(reply)
397 except xml.parsers.expat.ExpatError,msg:
398 fatal("malformed response: %s\n%s"%(msg,reply))
399 rc = proc_f(doc)
400 doc.unlink()
401 if rc != 0:
402 break
403 my_debug("iLO processed request (rc=%d) in %0.2f s" % (rc,(t_end-t_begin)))
404 return rc
405
406 def manage_power(cmd):
407 '''
408 Before trying to send a request we have to check the power
409 state.
410 '''
411 rc = 0
412 req = ''
413 # it won't do to turn it on if it's already on!
414 if cmd == "on" and not power:
415 req = new_power_req(E_SET_POWER,A_POWER_SW,"Y")
416 # also to turn it off if it's already off
417 elif cmd == "off" and power:
418 req = new_power_req(E_SET_POWER,A_POWER_SW,"N")
419 elif cmd == "cold_boot" and power:
420 req = new_power_req(E_COLD_BOOT)
421 elif cmd == "warm_boot" and power:
422 req = new_power_req(E_WARM_BOOT)
423 elif cmd == "reset":
424 if power:
425 req = new_power_req(E_RESET)
426 # reset doesn't work if the host's off
427 else:
428 req = new_power_req(E_SET_POWER,A_POWER_SW,"Y")
429 if req:
430 rc = send_request(req,proc_resp)
431 return rc
432 def power_on():
433 '''
434 Update the power variable without checking the power state.
435 The iLO is slow at times to report the actual power state, so
436 we assume that it changed if the request succeeded.
437 '''
438 rc = manage_power("on")
439 if rc == 0:
440 global power
441 power = True
442 return rc
443 def power_off():
444 rc = manage_power("off")
445 if rc == 0:
446 global power
447 power = False
448 return rc
449 def cold_boot():
450 rc = manage_power("cold_boot")
451 return rc
452 def warm_boot():
453 rc = manage_power("warm_boot")
454 return rc
455 def reset():
456 rc = manage_power("reset")
457 if rc == 0:
458 global power
459 power = True
460 return rc
461 def hold_button():
462 '''
463 Hold the power button. Got this error message when tried
464 without the TOGGLE attribute:
465 Command without TOGGLE="Yes" attribute is ignored
466 when host power is off. (rc: 0x0054)
467 Didn't find any documentation about TOGGLE.
468 '''
469 if power:
470 req = new_power_req(E_HOLD_BUTTON)
471 else:
472 req = new_power_req(E_HOLD_BUTTON,"TOGGLE","Yes")
473 rc = send_request(req,proc_resp)
474 return rc
475 def read_power_state():
476 req = new_power_req(E_GET_PSTATUS)
477 rc = send_request(req,proc_resp)
478 return rc
479
480 def reset_power():
481 '''
482 Three methods to reset:
483 - hold power button
484 - reset (only if host has power and user said that reset is ok)
485 - power off/on
486 '''
487 do_power_on = False
488 if power_method == 'button':
489 rc = hold_button()
490 elif reset_ok != '0':
491 if power:
492 return reset()
493 else:
494 return power_on()
495 else:
496 do_power_on = True
497 rc = power_off()
498 if rc == 0:
499 rc = read_power_state()
500 if do_power_on:
501 while rc == 0 and power: # wait for the power state to go off
502 time.sleep(5)
503 rc = read_power_state()
504 if rc == 0 and do_power_on and not power:
505 rc = power_on()
506 return rc
507
508 # track state of host power
509 power = -1
510
511 todo = {
512 'reset':reset_power,
513 'on':power_on,
514 'off':power_off,
515 'cold':cold_boot,
516 'warm':warm_boot,
517 'status':lambda: 0 # just return 0, we already read the state
518 }
519
520 rc = read_power_state()
521 if rc == 0:
522 if cmd in todo:
523 rc = todo[cmd]()
524 else:
525 fatal('Invalid command: %s' % cmd)
526 if rc != 0:
527 fatal("request failed")
528 sys.exit(rc)
529
530 # vi:ts=4:sw=4:et: