Debian Codegraph @

lib/plugins/stonith/external/riloe

raw ◀ ▶
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 http.client
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 list(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 list(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.encode("utf-8"))
337 response=proxy.recv(8192).decode("utf-8")
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=http.client.HTTPConnection('localhost')
344 h.sock=sock
345 return h
346 else:
•347 return http.client.HTTPSConnection(host)
348 except socket.gaierror as msg:
349 fatal("%s: %s" %(msg,host))
•350 except socket.error as msg:
351 fatal("%s while talking to %s" %(msg,host))
•352 except ImportError as msg:
353 fatal("ssl support missing (%s)" %msg)
354
355 def send_request(req,proc_f):
356 '''
357 1. After every request, the iLO closes the connection.
358 2. For every request, there are multiple replies. Each reply
359 is an XML document. Most of replies are just a kind of
360 (verbose) XML "OK".
361 '''
362 t_begin = time.time()
363 c = open_ilo(rihost)
364 try:
•365 c.send(req.encode("utf-8") + b'\r\n')
366 except socket.error as msg:
367 fatal("%s, while talking to %s" %(msg,rihost))
368 t_end = time.time()
369 my_debug("request sent in %0.2f s" % ((t_end-t_begin)))
370
371 t_begin = time.time()
372 result = []
373 while True:
374 try:
375 reply = c.sock.recv(1024)
376 if not reply:
377 break
378 result.append(reply)
•379 except socket.error as msg:
380 if msg[0] == 6: # connection closed
381 break
382 my_err("%s, while talking to %s" %(msg,rihost))
383 return -1
384 c.close()
385 t_end = time.time()
386
387 if not result:
388 fatal("no response from %s within %0.2f s"%(rihost,(t_end-t_begin)))
389 for reply in result:
•390 reply = reply.decode("utf-8")
391 # work around the iLO bug, i.e. element RIBCL closed twice
392 if re.search("</RIBCL", reply) and re.search("<RIBCL.*/>", reply):
393 reply = re.sub("<(RIBCL.*)/>", r"<\1>", reply)
394 try:
395 doc = xml.dom.minidom.parseString(reply)
•396 except xml.parsers.expat.ExpatError as msg:
397 fatal("malformed response: %s\n%s"%(msg,reply))
398 rc = proc_f(doc)
399 doc.unlink()
400 if rc != 0:
401 break
402 my_debug("iLO processed request (rc=%d) in %0.2f s" % (rc,(t_end-t_begin)))
403 return rc
404
405 def manage_power(cmd):
406 '''
407 Before trying to send a request we have to check the power
408 state.
409 '''
410 rc = 0
411 req = ''
412 # it won't do to turn it on if it's already on!
413 if cmd == "on" and not power:
414 req = new_power_req(E_SET_POWER,A_POWER_SW,"Y")
415 # also to turn it off if it's already off
416 elif cmd == "off" and power:
417 req = new_power_req(E_SET_POWER,A_POWER_SW,"N")
418 elif cmd == "cold_boot" and power:
419 req = new_power_req(E_COLD_BOOT)
420 elif cmd == "warm_boot" and power:
421 req = new_power_req(E_WARM_BOOT)
422 elif cmd == "reset":
423 if power:
424 req = new_power_req(E_RESET)
425 # reset doesn't work if the host's off
426 else:
427 req = new_power_req(E_SET_POWER,A_POWER_SW,"Y")
428 if req:
429 rc = send_request(req,proc_resp)
430 return rc
431 def power_on():
432 '''
433 Update the power variable without checking the power state.
434 The iLO is slow at times to report the actual power state, so
435 we assume that it changed if the request succeeded.
436 '''
437 rc = manage_power("on")
438 if rc == 0:
439 global power
440 power = True
441 return rc
442 def power_off():
443 rc = manage_power("off")
444 if rc == 0:
445 global power
446 power = False
447 return rc
448 def cold_boot():
449 rc = manage_power("cold_boot")
450 return rc
451 def warm_boot():
452 rc = manage_power("warm_boot")
453 return rc
454 def reset():
455 rc = manage_power("reset")
456 if rc == 0:
457 global power
458 power = True
459 return rc
460 def hold_button():
461 '''
462 Hold the power button. Got this error message when tried
463 without the TOGGLE attribute:
464 Command without TOGGLE="Yes" attribute is ignored
465 when host power is off. (rc: 0x0054)
466 Didn't find any documentation about TOGGLE.
467 '''
468 if power:
469 req = new_power_req(E_HOLD_BUTTON)
470 else:
471 req = new_power_req(E_HOLD_BUTTON,"TOGGLE","Yes")
472 rc = send_request(req,proc_resp)
473 return rc
474 def read_power_state():
475 req = new_power_req(E_GET_PSTATUS)
476 rc = send_request(req,proc_resp)
477 return rc
478
479 def reset_power():
480 '''
481 Three methods to reset:
482 - hold power button
483 - reset (only if host has power and user said that reset is ok)
484 - power off/on
485 '''
486 do_power_on = False
487 if power_method == 'button':
488 rc = hold_button()
489 elif reset_ok != '0':
490 if power:
491 return reset()
492 else:
493 return power_on()
494 else:
495 do_power_on = True
496 rc = power_off()
497 if rc == 0:
498 rc = read_power_state()
499 if do_power_on:
500 while rc == 0 and power: # wait for the power state to go off
501 time.sleep(5)
502 rc = read_power_state()
503 if rc == 0 and do_power_on and not power:
504 rc = power_on()
505 return rc
506
507 # track state of host power
508 power = -1
509
510 todo = {
511 'reset':reset_power,
512 'on':power_on,
513 'off':power_off,
514 'cold':cold_boot,
515 'warm':warm_boot,
516 'status':lambda: 0 # just return 0, we already read the state
517 }
518
519 rc = read_power_state()
520 if rc == 0:
521 if cmd in todo:
522 rc = todo[cmd]()
523 else:
524 fatal('Invalid command: %s' % cmd)
525 if rc != 0:
526 fatal("request failed")
527 sys.exit(rc)
528
529 # vi:ts=4:sw=4:et: