Debian Codegraph @

lib/plugins/stonith/external/dracmc-telnet

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # vim: set filetype=python
3 #######################################################################
4 #
5 # dracmc-telnet - External stonith plugin for HAv2 (http://linux-ha.org/wiki)
6 # Connects to Dell Drac/MC Blade Enclosure via a Cyclades
7 # terminal server with telnet and switches power of named
8 # blade servers appropriatelly.
9 #
10 # Required parameters:
11 # nodename: The name of the server you want to touch on your network
12 # cyclades_ip: The IP address of the cyclades terminal server
13 # cyclades_port: The port for telnet to access on the cyclades (i.e. 7032)
14 # servername: The DRAC/MC server name of the blade (i.e. Server-7)
15 # username: The login user name for the DRAC/MC
16 # password: The login password for the DRAC/MC
17 #
18 # Author: Alex Tsariounov <[email protected]>
19 #
20 # Based on ibmrsa-telnet external stonith plugin by Andreas Mock
21 # ([email protected]), Copyright by Adreas Mock and released as part
22 # of HAv2.
23 #
24 # History:
25 # 2009-10-12 First release.
26 #
27 # Copyright (c) 2009 Novell, Inc.
28 # All Rights Reserved.
29 #
30 # This program is free software; you can redistribute it and/or modify
31 # it under the terms of version 2 or later of the GNU General Public
32 # License as published by the Free Software Foundation.
33 #
34 # This program is distributed in the hope that it would be useful, but
35 # WITHOUT ANY WARRANTY; without even the implied warranty of
36 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
37 #
38 # Further, this software is distributed without any warranty that it is
39 # free of the rightful claim of any third person regarding infringement
40 # or the like. Any license provided herein, whether implied or
41 # otherwise, applies only to this software file. Patent licenses, if
42 # any, provided herein do not apply to combinations of this program with
43 # other software, or any other product whatsoever.
44 #
45 # You should have received a copy of the GNU General Public License
46 # along with this program; if not, write the Free Software Foundation,
47 # Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
48 #
49 #######################################################################
50 import sys
51 import os
52 import time
53 import telnetlib
54 import random
55 import subprocess
56
57 LOGINRETRIES = 10
58
59 class TimeoutException(Exception):
60 def __init__(self, value=None):
61 Exception.__init__(self)
62 self.value = value
63
64 def __str__(self):
65 return repr(self.value)
66
67 class DracMC(telnetlib.Telnet):
68 def __init__(self, *args, **kwargs):
69 telnetlib.Telnet.__init__(self)
70 self._timeout = 4
71 self._loggedin = 0
72 self._history = []
73 self._appl = os.path.basename(sys.argv[0])
74 self._server = args[0]
75
76 def _get_timestamp(self):
77 ct = time.time()
•78 msecs = (ct - int(ct)) * 1000
79 return "%s,%03d" % (time.strftime("%Y-%m-%d %H:%M:%S",
80 time.localtime(ct)), msecs)
81
82 def write(self, buffer):
83 self._history.append(self._get_timestamp() + ': WRITE: ' + repr(buffer))
84 telnetlib.Telnet.write(self, buffer)
85
86 def read_until(self, what, timeout=2):
87 line = telnetlib.Telnet.read_until(self, what, timeout)
88 self._history.append(self._get_timestamp() + ': READ : ' + repr(line))
89 if not line.endswith(what):
90 raise TimeoutException("Timeout while waiting for '%s'." % (what, ))
91 return line
92
93 def login(self, user, passwd):
94 time.sleep(0.3)
95 try:
•96 line = self.read_until(b'Login: ', self._timeout)
97 self.write(user.encode("utf-8"))
98 self.write(b'\r')
99 line = self.read_until(b'Password: ', self._timeout)
100 self.write(passwd.encode("utf-8"))
101 self.write(b'\r')
102 except:
•103 self.write(b"\r")
104 line = self.read_until(b'Login: ', self._timeout)
105 self.write(user.encode("utf-8"))
106 self.write(b'\r')
107 line = self.read_until(b'Password: ', self._timeout)
108 self.write(passwd.encode("utf-8"))
109 self.write('b\r')
110 try:
•111 line = self.read_until(b'DRAC/MC:', self._timeout)
112 except:
•113 self.write(b"\r")
114 line = self.read_until(b'DRAC/MC:', self._timeout)
115
116 def hardreset(self):
•117 self.write(b'serveraction -s %b hardreset\r' % self._server.encode("utf-8"))
118 line = self.read_until(b'OK', 10)
119 line = self.read_until(b'DRAC/MC:', self._timeout)
120
121 def powercycle(self):
•122 self.write(b'serveraction -s %b powercycle\r' % self._server.encode("utf-8"))
123 line = self.read_until(b'OK', 10)
124 line = self.read_until(b'DRAC/MC:', self._timeout)
125
126 def on(self):
•127 self.write(b'serveraction -s %b powerup\r' % self._server.encode("utf-8"))
128 line = self.read_until(b'OK', 10)
129 line = self.read_until(b'DRAC/MC:', self._timeout)
130
131 def off(self):
•132 self.write(b'serveraction -s %b powerdown\r' % self._server.encode("utf-8"))
133 line = self.read_until(b'OK', 10)
134 line = self.read_until(b'DRAC/MC:', self._timeout)
135
136 def exit(self):
•137 self.write(b'exit\r')
138
139 def get_history(self):
140 return "\n".join(self._history)
141
142
143 class DracMCStonithPlugin:
144 def __init__(self):
145 # define the external stonith plugin api
146 self._required_cmds = \
147 'reset gethosts status getconfignames getinfo-devid ' \
148 'getinfo-devname getinfo-devdescr getinfo-devurl ' \
149 'getinfo-xml'
150 self._optional_cmds = 'on off'
151 self._required_cmds_list = self._required_cmds.split()
152 self._optional_cmds_list = self._optional_cmds.split()
153
154 # who am i
155 self._appl = os.path.basename(sys.argv[0])
156
157 # telnet connection object
158 self._connection = None
159
160 # the list of configuration names
161 self._confignames = ['nodename', 'cyclades_ip', 'cyclades_port',
162 'servername', 'username', 'password']
163
164 # catch the parameters provided by environment
165 self._parameters = {}
166 for name in self._confignames:
167 try:
168 self._parameters[name] = os.environ.get(name, '').split()[0]
169 except IndexError:
170 self._parameters[name] = ''
171
172 def _get_timestamp(self):
173 ct = time.time()
•174 msecs = (ct - int(ct)) * 1000
175 return "%s,%03d" % (time.strftime("%Y-%m-%d %H:%M:%S",
176 time.localtime(ct)), msecs)
177
178 def _echo_debug(self, *args):
179 subprocess.call("ha_log.sh debug '%s'" % ' '.join(args), shell=True)
180
181 def echo(self, *args):
182 what = ''.join([str(x) for x in args])
183 sys.stdout.write(what)
184 sys.stdout.write('\n')
185 sys.stdout.flush()
186 self._echo_debug("STDOUT:", what)
187
188 def echo_log(self, level, *args):
189 subprocess.call("ha_log.sh %s '%s'" % (level,' '.join(args)), shell=True)
190
191 def _get_connection(self):
192 if not self._connection:
193 c = DracMC(self._parameters['servername'])
194 self._echo_debug("Connecting to '%s:%s'" %
195 (self._parameters['cyclades_ip'],
196 self._parameters['cyclades_port']))
197 tries = 0
198 while tries < LOGINRETRIES:
199 try:
200 c.open(self._parameters['cyclades_ip'],
201 self._parameters['cyclades_port'])
202 c.login(self._parameters['username'],
203 self._parameters['password'])
•204 except Exception as args:
205 if "Connection reset by peer" in str(args):
206 self._echo_debug("Someone is already logged in... retry=%s" % tries)
207 c.close()
208 time.sleep(random.uniform(1.0, 5.0))
209 else:
210 raise
211 else:
212 break
213 tries += 1
214
215 if tries == LOGINRETRIES:
216 c.close()
217 raise Exception("Could not log in to %s:%s" %
218 (self._parameters['cyclades_ip'],
219 self._parameters['cyclades_port']))
220 self._connection = c
221
222 def _end_connection(self):
223 if self._connection:
224 self._connection.exit()
225 self._connection.close()
226
227 def reset(self):
228 self._get_connection()
229 # self._connection.hardreset()
230 self._connection.powercycle()
231 self._end_connection()
232 self._echo_debug(self._connection.get_history())
233 self.echo_log("info", "Reset of node '%s' done" %
234 (self._parameters['nodename'],))
235 return(0)
236
237 def on(self):
238 self._get_connection()
239 self._connection.on()
240 self._end_connection()
241 self._echo_debug(self._connection.get_history())
242 self.echo_log("info", "Switched node '%s' ON" %
243 (self._parameters['nodename'],))
244 return(0)
245
246 def off(self):
247 self._get_connection()
248 self._connection.off()
249 self._end_connection()
250 self._echo_debug(self._connection.get_history())
251 self.echo_log("info", "Switched node '%s' OFF" %
252 (self._parameters['nodename'],))
253 return(0)
254
255 def gethosts(self):
256 self.echo(self._parameters['nodename'])
257 return(0)
258
259 def status(self):
260 self._get_connection()
261 self._end_connection()
262 self._echo_debug(self._connection.get_history())
263 return(0)
264
265 def getconfignames(self):
266 for name in ['nodename', 'cyclades_ip', 'cyclades_port', 'servername',
267 'username', 'password']:
268 self.echo(name)
269 return(0)
270
271 def getinfo_devid(self):
272 self.echo("External Stonith Plugin for Dell DRAC/MC via Cyclades")
273 return(0)
274
275 def getinfo_devname(self):
276 self.echo("External Stonith Plugin for Dell Drac/MC connecting "
277 "via Telnet to a Cyclades port")
278 return(0)
279
280 def getinfo_devdescr(self):
281 self.echo("External stonith plugin for HAv2 which connects to "
282 "a Dell DRAC/MC connected via a Cyclades port with telnet. "
283 "Commands to turn on/off power and to reset server are sent "
284 "appropriately. "
285 "(c) 2009 by Novell, Inc. ([email protected])")
286 return(0)
287
288 def getinfo_devurl(self):
289 self.echo("http://support.dell.com/support/edocs/software/smdrac3/dracmc/1.3/en/index.htm")
290
291 def getinfo_xml(self):
292 info = """<parameters>
293 <parameter name="nodename" unique="1" required="1">
294 <content type="string" />
295 <shortdesc lang="en">nodename to shoot</shortdesc>
296 <longdesc lang="en">
297 Name of the node to be stonithed.
298 </longdesc>
299 </parameter>
300 <parameter name="cyclades_ip" unique="1" required="1">
301 <content type="string" />
302 <shortdesc lang="en">hostname or ip address of cyclades</shortdesc>
303 <longdesc lang="en">
304 Hostname or IP address of Cyclades connected to DRAC/MC.
305 </longdesc>
306 </parameter>
307 <parameter name="cyclades_port" unique="1" required="1">
308 <content type="string" />
309 <shortdesc lang="en">telnet port to use on cyclades</shortdesc>
310 <longdesc lang="en">
311 Port used with the Cyclades telnet interface which is connected to the DRAC/MC.
312 </longdesc>
313 </parameter>
314 <parameter name="servername" unique="1" required="1">
315 <content type="string" />
316 <shortdesc lang="en">DRAC/MC name of blade to be stonithed</shortdesc>
317 <longdesc lang="en">
318 Name of server blade to be stonithed on the DRAC/MC (example: Server-7)
319 </longdesc>
320 </parameter>
321 <parameter name="username" unique="1" required="1">
322 <content type="string" />
323 <shortdesc lang="en">username to login on the DRAC/MC</shortdesc>
324 <longdesc lang="en">
325 Username to login to the DRAC/MC once connected via the Cyclades port.
326 </longdesc>
327 </parameter>
328 <parameter name="password" unique="1" required="1">
329 <content type="string" />
330 <shortdesc lang="en">password to login on the DRAC/MC</shortdesc>
331 <longdesc lang="en">
332 Password to login to the DRAC/MC once connected via the Cyclades port.
333 </longdesc>
334 </parameter>
335 </parameters>
336 """
337 self.echo(info)
338 return(0)
339
340 def not_implemented(self, cmd):
341 self.echo_log("err", "Command '%s' not implemented." % (cmd,))
342 return(1)
343
344 def usage(self):
345 usage = "Call me with one of the allowed commands: %s, %s" % (
346 ', '.join(self._required_cmds_list),
347 ', '.join(self._optional_cmds_list))
348 return usage
349
350 def process(self, argv):
351 self._echo_debug("========== Start =============")
352 if len(argv) < 1:
353 self.echo_log("err", 'At least one commandline argument required.')
354 return(1)
355 cmd = argv[0]
356 self._echo_debug("cmd:", cmd)
357 if cmd not in self._required_cmds_list and \
358 cmd not in self._optional_cmds_list:
359 self.echo_log("err", "Command '%s' not supported." % (cmd,))
360 return(1)
361 try:
362 cmd = cmd.lower().replace('-', '_')
363 func = getattr(self, cmd, self.not_implemented)
364 rc = func()
365 return(rc)
•366 except Exception as args:
367 self.echo_log("err", 'Exception raised:', str(args))
368 if self._connection:
369 self.echo_log("err", self._connection.get_history())
370 self._connection.close()
371 return(1)
372
373
374 if __name__ == '__main__':
375 stonith = DracMCStonithPlugin()
376 rc = stonith.process(sys.argv[1:])
377 sys.exit(rc)