corosync.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. '''CTS: Cluster Testing System: corosync...
  2. '''
  3. __copyright__='''
  4. Copyright (c) 2010 Red Hat, Inc.
  5. '''
  6. # All rights reserved.
  7. #
  8. # Author: Angus Salkeld <asalkeld@redhat.com>
  9. #
  10. # This software licensed under BSD license, the text of which follows:
  11. #
  12. # Redistribution and use in source and binary forms, with or without
  13. # modification, are permitted provided that the following conditions are met:
  14. #
  15. # - Redistributions of source code must retain the above copyright notice,
  16. # this list of conditions and the following disclaimer.
  17. # - Redistributions in binary form must reproduce the above copyright notice,
  18. # this list of conditions and the following disclaimer in the documentation
  19. # and/or other materials provided with the distribution.
  20. # - Neither the name of the MontaVista Software, Inc. nor the names of its
  21. # contributors may be used to endorse or promote products derived from this
  22. # software without specific prior written permission.
  23. #
  24. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  25. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  28. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  29. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  30. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  31. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  32. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  33. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  34. # THE POSSIBILITY OF SUCH DAMAGE.
  35. import os
  36. import sys
  37. import time
  38. import socket
  39. import shutil
  40. import string
  41. import augeas
  42. from cts.CTS import ClusterManager
  43. from cts.CTS import ScenarioComponent
  44. from cts.CTS import RemoteExec
  45. from cts.CTSvars import CTSvars
  46. ###################################################################
  47. class CoroConfig(object):
  48. def __init__(self, corobase=None):
  49. self.base = "/files/etc/corosync/corosync.conf/"
  50. self.new_root = "/tmp/aug-root/"
  51. if corobase == None:
  52. self.corobase = os.getcwd() + "/.."
  53. else:
  54. self.corobase = corobase
  55. example = self.corobase + "/conf/corosync.conf.example"
  56. shutil.rmtree (self.new_root)
  57. os.makedirs (self.new_root + "/etc/corosync")
  58. shutil.copy (example, self.new_root + "/etc/corosync/corosync.conf")
  59. self.aug = augeas.Augeas (root=self.new_root,
  60. loadpath=self.corobase + "/conf/lenses")
  61. self.original = {}
  62. # store the original values (of totem), so we can restore them in
  63. # apply_default_config()
  64. totem = self.aug.match('/files/etc/corosync/corosync.conf/totem/*')
  65. for c in totem:
  66. # /files/etc/corosync/corosync.conf/
  67. short_name = c[len(self.base):]
  68. self.original[short_name] = self.aug.get(c)
  69. interface = self.aug.match('/files/etc/corosync/corosync.conf/totem/interface/*')
  70. for c in interface:
  71. short_name = c[len(self.base):]
  72. self.original[short_name] = self.aug.get(c)
  73. def get (self, name):
  74. return self.aug.get (self.base + name)
  75. def set (self, name, value):
  76. token = self.aug.set (self.base + name, str(value))
  77. def save (self):
  78. self.aug.save()
  79. def get_filename(self):
  80. return self.new_root + "/etc/corosync/corosync.conf"
  81. ###################################################################
  82. class corosync_flatiron(ClusterManager):
  83. '''
  84. bla
  85. '''
  86. def __init__(self, Environment, randseed=None):
  87. ClusterManager.__init__(self, Environment, randseed)
  88. self.update({
  89. "Name" : "corosync(flatiron)",
  90. "StartCmd" : CTSvars.INITDIR+"/corosync start",
  91. "StopCmd" : CTSvars.INITDIR+"/corosync stop",
  92. "RereadCmd" : CTSvars.INITDIR+"/corosync reload",
  93. "StatusCmd" : CTSvars.INITDIR+"/corosync status %s",
  94. "DeadTime" : 30,
  95. "StartTime" : 15, # Max time to start up
  96. "StableTime" : 10,
  97. "BreakCommCmd" : "/usr/share/corosync/tests/net_breaker.sh BreakCommCmd %s",
  98. "FixCommCmd" : "/usr/share/corosync/tests/net_breaker.sh FixCommCmd %s",
  99. "Pat:We_stopped" : "%s.*Corosync Cluster Engine exiting with status.*",
  100. "Pat:They_stopped" : "%s.*Member left:.*%s.*",
  101. "Pat:They_dead" : "corosync:.*Node %s is now: lost",
  102. "Pat:Local_starting" : "%s.*started and ready to provide service.",
  103. "Pat:Local_started" : "%s.*started and ready to provide service.",
  104. "Pat:Master_started" : "%s.*Completed service synchronization, ready to provide service.",
  105. "Pat:Slave_started" : "%s.*Completed service synchronization, ready to provide service.",
  106. "Pat:ChildKilled" : "%s corosync.*Child process %s terminated with signal 9",
  107. "Pat:ChildRespawn" : "%s corosync.*Respawning failed child process: %s",
  108. "Pat:ChildExit" : "Child process .* exited",
  109. "Pat:DC_IDLE" : ".*A processor joined or left the membership and a new membership was formed.",
  110. # Bad news Regexes. Should never occur.
  111. "BadRegexes" : (
  112. r"ERROR:",
  113. r"CRIT:",
  114. r"Shutting down\.",
  115. r"Forcing shutdown\.",
  116. r"core dump",
  117. ),
  118. "LogFileName" : Environment["LogFileName"],
  119. })
  120. self.agent={}
  121. self.config = CoroConfig ()
  122. self.node_to_ip = {}
  123. self.new_config = {}
  124. self.applied_config = {}
  125. for n in self.Env["nodes"]:
  126. ip = socket.gethostbyname(n)
  127. ips = ip.split('.')
  128. ips[3] = '0'
  129. ip_mask = '.'.join(ips)
  130. self.new_config['totem/interface/bindnetaddr'] = str(ip_mask)
  131. return
  132. def apply_default_config(self):
  133. for c in self.applied_config:
  134. if 'bindnetaddr' in c:
  135. continue
  136. elif not self.config.original.has_key(c):
  137. # new config option (non default)
  138. pass
  139. elif self.applied_config[c] is not self.config.original[c]:
  140. # reset to the original
  141. self.new_config[c] = self.config.original[c]
  142. if len(self.new_config) > 0:
  143. self.debug('applying default config')
  144. self.stopall()
  145. def apply_new_config(self):
  146. if len(self.new_config) > 0:
  147. self.debug('applying new config')
  148. self.stopall()
  149. self.startall()
  150. def install_all_config(self):
  151. tmp1 = {}
  152. for c in self.new_config:
  153. self.log('configuring: ' + c + ' = '+ str(self.new_config[c]))
  154. self.config.set (c, self.new_config[c])
  155. self.applied_config[c] = self.new_config[c]
  156. tmp1[c] = self.new_config[c]
  157. for c in tmp1:
  158. del self.new_config[c]
  159. self.config.save()
  160. src_file = self.config.get_filename()
  161. for node in self.Env["nodes"]:
  162. self.rsh.cp(src_file, "%s:%s" % (node, "/etc/corosync/"))
  163. def install_config(self, node):
  164. # install gets new_config and installs it, then moves the
  165. # config to applied_config
  166. if len(self.new_config) > 0:
  167. self.install_all_config()
  168. def key_for_node(self, node):
  169. if not self.node_to_ip.has_key(node):
  170. self.node_to_ip[node] = socket.gethostbyname (node)
  171. return self.node_to_ip[node]
  172. def StartaCM(self, node):
  173. if not self.ShouldBeStatus.has_key(node):
  174. self.ShouldBeStatus[node] = "down"
  175. if self.ShouldBeStatus[node] != "down":
  176. return 1
  177. self.debug('starting corosync on : ' + node)
  178. ret = ClusterManager.StartaCM(self, node)
  179. if self.agent.has_key(node):
  180. self.agent[node].restart()
  181. return ret
  182. def StopaCM(self, node):
  183. if self.ShouldBeStatus[node] != "up":
  184. return 1
  185. self.debug('stoping corosync on : ' + node)
  186. if self.agent.has_key(node):
  187. self.agent[node].stop()
  188. return ClusterManager.StopaCM(self, node)
  189. def StataCM(self, node):
  190. '''Report the status of corosync on a given node'''
  191. out=self.rsh(node, self["StatusCmd"], 1)
  192. is_stopped = string.find(out, 'stopped')
  193. is_dead = string.find(out, 'dead')
  194. ret = (is_dead is -1 and is_stopped is -1)
  195. try:
  196. if ret:
  197. if self.ShouldBeStatus[node] == "down":
  198. self.log(
  199. "Node status for %s is %s but we think it should be %s"
  200. % (node, "up", self.ShouldBeStatus[node]))
  201. else:
  202. if self.ShouldBeStatus[node] == "up":
  203. self.log(
  204. "Node status for %s is %s but we think it should be %s"
  205. % (node, "down", self.ShouldBeStatus[node]))
  206. except KeyError: pass
  207. if ret: self.ShouldBeStatus[node]="up"
  208. else: self.ShouldBeStatus[node]="down"
  209. return ret
  210. def RereadCM(self, node):
  211. self.log('reloading corosync on : ' + node)
  212. return ClusterManager.RereadCM(self, node)
  213. def prepare(self):
  214. '''Finish the Initialization process. Prepare to test...'''
  215. self.partitions_expected = 1
  216. for node in self.Env["nodes"]:
  217. self.ShouldBeStatus[node] = ""
  218. self.unisolate_node(node)
  219. self.rsh(node, 'service abrtd stop', 1)
  220. self.StataCM(node)
  221. def HasQuorum(self, node_list):
  222. # If we are auditing a partition, then one side will
  223. # have quorum and the other not.
  224. # So the caller needs to tell us which we are checking
  225. # If no value for node_list is specified... assume all nodes
  226. if not node_list:
  227. node_list = self.Env["nodes"]
  228. for node in node_list:
  229. if self.ShouldBeStatus[node] == "up":
  230. quorum = self.rsh(node, self["QuorumCmd"], 1)
  231. if string.find(quorum, "1") != -1:
  232. return 1
  233. elif string.find(quorum, "0") != -1:
  234. return 0
  235. else:
  236. self.log("WARN: Unexpected quorum test result from "+ node +":"+ quorum)
  237. return 0
  238. def Components(self):
  239. return None
  240. ###################################################################
  241. class TestAgentComponent(ScenarioComponent):
  242. def __init__(self, Env):
  243. self.Env = Env
  244. def IsApplicable(self):
  245. '''Return TRUE if the current ScenarioComponent is applicable
  246. in the given LabEnvironment given to the constructor.
  247. '''
  248. return True
  249. def SetUp(self, CM):
  250. '''Set up the given ScenarioComponent'''
  251. self.CM = CM
  252. for node in self.Env["nodes"]:
  253. if not CM.StataCM(node):
  254. raise RuntimeError ("corosync not up")
  255. self.CM.agent[node] = CpgTestAgent(node, CM.Env)
  256. self.CM.agent[node].start()
  257. return 1
  258. def TearDown(self, CM):
  259. '''Tear down (undo) the given ScenarioComponent'''
  260. self.CM = CM
  261. for node in self.Env["nodes"]:
  262. self.CM.agent[node].stop()
  263. ###################################################################
  264. class TestAgent(object):
  265. def __init__(self, binary, node, port, env=None):
  266. self.node = node
  267. self.node_address = None
  268. self.port = port
  269. self.sock = None
  270. self.binary = binary
  271. self.started = False
  272. self.rsh = RemoteExec(Env=env)
  273. self.func_name = None
  274. self.used = False
  275. self.env = env
  276. def restart(self):
  277. self.stop()
  278. self.start()
  279. def clean_start(self):
  280. if self.used or not self.status():
  281. self.env.debug('test agent: clean_start (' + self.node + ')')
  282. self.stop()
  283. self.start()
  284. def status(self):
  285. if not self.started:
  286. return False
  287. try:
  288. self.send (["cpg_local_get"])
  289. self.nodeid = self.read ()
  290. return True
  291. except RuntimeError, msg:
  292. return False
  293. def start(self):
  294. '''Set up the given ScenarioComponent'''
  295. self.env.debug('test agent: start (' + self.node + ')')
  296. self.sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
  297. ip = socket.gethostbyname(self.node)
  298. self.rsh(self.node, self.binary, blocking=0)
  299. is_connected = False
  300. retries = 0
  301. while not is_connected:
  302. try:
  303. retries = retries + 1
  304. self.sock.connect ((ip, self.port))
  305. is_connected = True
  306. except socket.error, msg:
  307. if retries > 5:
  308. self.env.debug( "Retried " + str(retries) + " times. Error: " + msg )
  309. time.sleep(1)
  310. self.started = True
  311. self.used = False
  312. def stop(self):
  313. '''Tear down (undo) the given ScenarioComponent'''
  314. self.env.debug('test agent: stop (' + self.node + ')')
  315. self.sock.close ()
  316. self.rsh(self.node, "killall " + self.binary + " 2>/dev/null")
  317. self.started = False
  318. def send (self, args):
  319. if not self.started:
  320. self.start()
  321. real_msg = str (len (args))
  322. for a in args:
  323. a_str = str(a)
  324. real_msg += ":" + str (len (a_str)) + ":" + a_str
  325. real_msg += ";"
  326. sent = 0
  327. try:
  328. sent = self.sock.send (real_msg)
  329. except socket.error, msg:
  330. print msg
  331. if sent == 0:
  332. raise RuntimeError ("socket connection broken")
  333. self.used = True
  334. def __getattribute__(self,name):
  335. try:
  336. return object.__getattribute__(self, name)
  337. except:
  338. self.func_name = name
  339. return self.send_dynamic
  340. def send_dynamic (self, *args):
  341. if not self.started:
  342. self.start()
  343. # number of args+func
  344. real_msg = str (len (args) + 1) + ":" + str(len(self.func_name)) + ":" + self.func_name
  345. for a in args:
  346. a_str = str(a)
  347. real_msg += ":" + str (len (a_str)) + ":" + a_str
  348. real_msg += ";"
  349. #print "CLIENT:" + real_msg
  350. sent = 0
  351. try:
  352. sent = self.sock.send (real_msg)
  353. except socket.error, msg:
  354. print msg
  355. if sent == 0:
  356. raise RuntimeError ("socket connection broken")
  357. self.used = True
  358. def read (self):
  359. msg = self.sock.recv (4096)
  360. if msg == '':
  361. raise RuntimeError("socket connection broken")
  362. return msg
  363. class CpgConfigEvent:
  364. def __init__(self, msg):
  365. info = msg.split(',')
  366. self.group_name = info[0]
  367. self.node_id = info[1]
  368. self.node = None
  369. self.pid = info[2]
  370. if "left" in info[3]:
  371. self.is_member = False
  372. else:
  373. self.is_member = True
  374. def __str__ (self):
  375. str = self.group_name + "," + self.node_id + "," + self.pid + ","
  376. if self.is_member:
  377. return str + "joined"
  378. else:
  379. return str + "left"
  380. ###################################################################
  381. class CpgTestAgent(TestAgent):
  382. def __init__(self, node, Env=None):
  383. TestAgent.__init__(self, "cpg_test_agent", node, 9034, env=Env)
  384. self.initialized = False
  385. self.nodeid = None
  386. def start(self):
  387. TestAgent.start(self)
  388. self.send(["cpg_initialize"])
  389. self.used = False
  390. def stop(self):
  391. try:
  392. self.send(["cpg_finalize"])
  393. except RuntimeError, msg:
  394. # if agent is down, we are not going to stress
  395. print msg
  396. TestAgent.stop(self)
  397. def cpg_local_get(self):
  398. if self.nodeid == None:
  399. self.send (["cpg_local_get"])
  400. self.nodeid = self.read ()
  401. return self.nodeid
  402. def record_config_events(self, truncate=True):
  403. if truncate:
  404. self.send (["record_config_events", "truncate"])
  405. else:
  406. self.send (["record_config_events", "append"])
  407. def read_config_event(self):
  408. self.send (["read_config_event"])
  409. msg = self.read ()
  410. if "None" in msg:
  411. return None
  412. else:
  413. return CpgConfigEvent(msg)
  414. def read_messages(self, atmost):
  415. self.send (["read_messages", atmost])
  416. msg = self.read ()
  417. if "None" in msg:
  418. return None
  419. else:
  420. return msg