corosync.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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.CTSscenarios import ScenarioComponent
  44. from cts.CTS import RemoteExec
  45. from cts.CTSvars import CTSvars
  46. from cts.CTSaudits import ClusterAudit
  47. from cts.CTSaudits import LogAudit
  48. ###################################################################
  49. class CoroConfig(object):
  50. def __init__(self, corobase=None):
  51. self.base = "/files/etc/corosync/corosync.conf/"
  52. self.new_root = "/tmp/aug-root/"
  53. if corobase == None:
  54. self.corobase = os.getcwd() + "/.."
  55. else:
  56. self.corobase = corobase
  57. example = self.corobase + "/conf/corosync.conf.example"
  58. if os.path.isdir(self.new_root):
  59. shutil.rmtree (self.new_root)
  60. os.makedirs (self.new_root + "/etc/corosync")
  61. shutil.copy (example, self.new_root + "/etc/corosync/corosync.conf")
  62. self.aug = augeas.Augeas (root=self.new_root,
  63. loadpath=self.corobase + "/conf/lenses")
  64. self.original = {}
  65. # store the original values (of totem), so we can restore them in
  66. # apply_default_config()
  67. totem = self.aug.match('/files/etc/corosync/corosync.conf/totem/*')
  68. for c in totem:
  69. # /files/etc/corosync/corosync.conf/
  70. short_name = c[len(self.base):]
  71. self.original[short_name] = self.aug.get(c)
  72. interface = self.aug.match('/files/etc/corosync/corosync.conf/totem/interface/*')
  73. for c in interface:
  74. short_name = c[len(self.base):]
  75. self.original[short_name] = self.aug.get(c)
  76. def get (self, name):
  77. return self.aug.get (self.base + name)
  78. def set (self, name, value):
  79. token = self.aug.set (self.base + name, str(value))
  80. def save (self):
  81. self.aug.save()
  82. def get_filename(self):
  83. return self.new_root + "/etc/corosync/corosync.conf"
  84. ###################################################################
  85. class corosync_needle(ClusterManager):
  86. '''
  87. bla
  88. '''
  89. def __init__(self, Environment, randseed=None):
  90. ClusterManager.__init__(self, Environment, randseed)
  91. self.update({
  92. "Name" : "corosync(needle)",
  93. "StartCmd" : "service corosync start",
  94. "StopCmd" : "service corosync stop",
  95. "RereadCmd" : "service corosync reload",
  96. "StatusCmd" : "service corosync status",
  97. "DeadTime" : 30,
  98. "StartTime" : 15, # Max time to start up
  99. "StableTime" : 10,
  100. "BreakCommCmd" : "/usr/share/corosync/tests/net_breaker.sh BreakCommCmd %s",
  101. "FixCommCmd" : "/usr/share/corosync/tests/net_breaker.sh FixCommCmd %s",
  102. "QuorumCmd" : "corosync-quorumtool -s",
  103. "Pat:We_stopped" : "%s.*Corosync Cluster Engine exiting.*",
  104. "Pat:They_stopped" : "%s.*Member left:.*%s.*",
  105. "Pat:They_dead" : "corosync:.*Node %s is now: lost",
  106. "Pat:Local_starting" : "%s.*started and ready to provide service.",
  107. "Pat:Local_started" : "%s.*started and ready to provide service.",
  108. "Pat:Master_started" : "%s.*Completed service synchronization, ready to provide service.",
  109. "Pat:Slave_started" : "%s.*Completed service synchronization, ready to provide service.",
  110. "Pat:ChildKilled" : "%s corosync.*Child process %s terminated with signal 9",
  111. "Pat:ChildRespawn" : "%s corosync.*Respawning failed child process: %s",
  112. "Pat:ChildExit" : "Child process .* exited",
  113. "Pat:DC_IDLE" : ".*A processor joined or left the membership and a new membership was formed.",
  114. # Bad news Regexes. Should never occur.
  115. "BadRegexes" : (
  116. r"ERROR:",
  117. r"CRIT:",
  118. r"Shutting down\.",
  119. r"Forcing shutdown\.",
  120. r"core dump",
  121. r"Could not bind AF_UNIX",
  122. r"Too many open files",
  123. r"Address already in use",
  124. ),
  125. "LogFileName" : Environment["LogFileName"],
  126. })
  127. self.start_cpg = True
  128. self.cpg_agent = {}
  129. self.sam_agent = {}
  130. self.votequorum_agent = {}
  131. self.config = CoroConfig ()
  132. self.node_to_ip = {}
  133. self.new_config = {}
  134. self.applied_config = {}
  135. for n in self.Env["nodes"]:
  136. ip = socket.gethostbyname(n)
  137. ips = ip.split('.')
  138. ips[3] = '0'
  139. ip_mask = '.'.join(ips)
  140. self.new_config['totem/interface/bindnetaddr'] = str(ip_mask)
  141. return
  142. def apply_default_config(self):
  143. for c in self.applied_config:
  144. if 'bindnetaddr' in c:
  145. continue
  146. elif not self.config.original.has_key(c):
  147. # new config option (non default)
  148. pass
  149. elif self.applied_config[c] is not self.config.original[c]:
  150. # reset to the original
  151. self.new_config[c] = self.config.original[c]
  152. if len(self.new_config) > 0:
  153. self.debug('applying default config')
  154. self.stopall()
  155. def apply_new_config(self):
  156. if len(self.new_config) > 0:
  157. self.debug('applying new config')
  158. self.stopall()
  159. self.startall()
  160. def install_all_config(self):
  161. tmp1 = {}
  162. sorted_keys = sorted(self.new_config.keys())
  163. for c in sorted_keys:
  164. self.log('configuring: ' + c + ' = '+ str(self.new_config[c]))
  165. self.config.set (c, self.new_config[c])
  166. self.applied_config[c] = self.new_config[c]
  167. tmp1[c] = self.new_config[c]
  168. for c in tmp1:
  169. del self.new_config[c]
  170. self.config.save()
  171. src_file = self.config.get_filename()
  172. for node in self.Env["nodes"]:
  173. self.rsh.cp(src_file, "%s:%s" % (node, "/etc/corosync/"))
  174. def install_config(self, node):
  175. # install gets new_config and installs it, then moves the
  176. # config to applied_config
  177. if len(self.new_config) > 0:
  178. self.install_all_config()
  179. def key_for_node(self, node):
  180. if not self.node_to_ip.has_key(node):
  181. self.node_to_ip[node] = socket.gethostbyname (node)
  182. return self.node_to_ip[node]
  183. def StartaCM(self, node, verbose=False):
  184. if not self.ShouldBeStatus.has_key(node):
  185. self.ShouldBeStatus[node] = "down"
  186. if self.ShouldBeStatus[node] != "down":
  187. return 1
  188. self.debug('starting corosync on : ' + node)
  189. ret = ClusterManager.StartaCM(self, node)
  190. if self.start_cpg:
  191. if self.cpg_agent.has_key(node):
  192. self.cpg_agent[node].restart()
  193. else:
  194. self.cpg_agent[node] = CpgTestAgent(node, self.Env)
  195. self.cpg_agent[node].start()
  196. if self.sam_agent.has_key(node):
  197. self.sam_agent[node].restart()
  198. # votequorum agent started as needed.
  199. if self.applied_config.has_key('quorum/provider'):
  200. if self.applied_config['quorum/provider'] is 'corosync_votequorum':
  201. if self.votequorum_agent.has_key(node):
  202. self.votequorum_agent[node].restart()
  203. else:
  204. self.votequorum_agent[node] = VoteQuorumTestAgent(node, self.Env)
  205. self.votequorum_agent[node].start()
  206. return ret
  207. def StopaCM(self, node, verbose=False):
  208. if self.ShouldBeStatus[node] != "up":
  209. return 1
  210. self.debug('stoping corosync on : ' + node)
  211. if self.cpg_agent.has_key(node):
  212. self.cpg_agent[node].stop()
  213. if self.sam_agent.has_key(node):
  214. self.sam_agent[node].stop()
  215. if self.votequorum_agent.has_key(node):
  216. self.votequorum_agent[node].stop()
  217. return ClusterManager.StopaCM(self, node)
  218. def test_node_CM(self, node):
  219. # 2 - up and stable
  220. # 1 - unstable
  221. # 0 - down
  222. (rc, lines) = self.rsh(node, self["StatusCmd"], stdout=2)
  223. out = str(lines)
  224. if 'systemctl' in out:
  225. is_running = ('active (running)' in out)
  226. ret = (rc is 0 and is_running is 0)
  227. else:
  228. is_stopped = string.find(out, 'stopped')
  229. is_dead = string.find(out, 'dead')
  230. ret = (is_dead is -1 and is_stopped is -1)
  231. try:
  232. if ret:
  233. ret = 2
  234. if self.ShouldBeStatus[node] == "down":
  235. self.log(
  236. "Node status for %s is %s but we think it should be %s"
  237. % (node, "up", self.ShouldBeStatus[node]))
  238. else:
  239. if self.ShouldBeStatus[node] == "up":
  240. self.log(
  241. "Node status for %s is %s but we think it should be %s"
  242. % (node, "down", self.ShouldBeStatus[node]))
  243. except KeyError: pass
  244. if ret: self.ShouldBeStatus[node] = "up"
  245. else: self.ShouldBeStatus[node] = "down"
  246. return ret
  247. def StataCM(self, node):
  248. '''Report the status of corosync on a given node'''
  249. if self.test_node_CM(node) > 0:
  250. return 1
  251. else:
  252. return None
  253. def RereadCM(self, node):
  254. self.log('reloading corosync on : ' + node)
  255. return ClusterManager.RereadCM(self, node)
  256. def find_partitions(self):
  257. ccm_partitions = []
  258. return ccm_partitions
  259. def prepare(self):
  260. '''Finish the Initialization process. Prepare to test...'''
  261. self.partitions_expected = 1
  262. for node in self.Env["nodes"]:
  263. self.ShouldBeStatus[node] = ""
  264. self.unisolate_node(node)
  265. self.StataCM(node)
  266. def HasQuorum(self, node_list):
  267. # If we are auditing a partition, then one side will
  268. # have quorum and the other not.
  269. # So the caller needs to tell us which we are checking
  270. # If no value for node_list is specified... assume all nodes
  271. if not node_list:
  272. node_list = self.Env["nodes"]
  273. for node in node_list:
  274. if self.ShouldBeStatus[node] == "up":
  275. (quorum, qout) = self.rsh(node, self["QuorumCmd"], stdout=2)
  276. if quorum == 1:
  277. return 1
  278. elif quorum == 0:
  279. return 0
  280. else:
  281. self.log("WARN: Unexpected quorum test result from %s : %d" % (node, quorum))
  282. return 0
  283. def Components(self):
  284. return None
  285. class ShmLeakAudit(ClusterAudit):
  286. def __init__(self, cm):
  287. self.CM = cm
  288. def name(self):
  289. return "ShmLeakAudit"
  290. def is_applicable(self):
  291. return 1
  292. def __call__(self):
  293. rc = 1
  294. for node in self.CM.Env["nodes"]:
  295. (res, lines) = self.CM.rsh(node, "/usr/share/corosync/tests/shm_leak_audit.sh", None)
  296. for line in lines:
  297. self.CM.log("%s leaked %s" % (node, line))
  298. rc = 0
  299. return rc
  300. ###################################################################
  301. class TestAgentComponent(ScenarioComponent):
  302. def __init__(self, Env):
  303. self.Env = Env
  304. def IsApplicable(self):
  305. '''Return TRUE if the current ScenarioComponent is applicable
  306. in the given LabEnvironment given to the constructor.
  307. '''
  308. return True
  309. def SetUp(self, CM):
  310. '''Set up the given ScenarioComponent'''
  311. self.CM = CM
  312. for node in self.Env["nodes"]:
  313. if not CM.StataCM(node):
  314. raise RuntimeError ("corosync not up")
  315. if self.CM.start_cpg:
  316. if self.CM.cpg_agent.has_key(node):
  317. self.CM.cpg_agent[node].clean_start()
  318. else:
  319. self.CM.cpg_agent[node] = CpgTestAgent(node, CM.Env)
  320. self.CM.cpg_agent[node].start()
  321. if self.CM.sam_agent.has_key(node):
  322. self.CM.sam_agent[node].clean_start()
  323. else:
  324. self.CM.sam_agent[node] = SamTestAgent(node, CM.Env)
  325. self.CM.sam_agent[node].start()
  326. # votequorum agent started as needed.
  327. if self.CM.applied_config.has_key('quorum/provider'):
  328. if CM.applied_config['quorum/provider'] is 'corosync_votequorum':
  329. self.CM.votequorum_agent[node] = VoteQuorumTestAgent(node, CM.Env)
  330. self.CM.votequorum_agent[node].start()
  331. return 1
  332. def TearDown(self, CM):
  333. '''Tear down (undo) the given ScenarioComponent'''
  334. self.CM = CM
  335. for node in self.Env["nodes"]:
  336. if self.CM.cpg_agent.has_key(node):
  337. self.CM.cpg_agent[node].stop()
  338. self.CM.sam_agent[node].stop()
  339. if self.CM.votequorum_agent.has_key(node):
  340. self.CM.votequorum_agent[node].stop()
  341. ###################################################################
  342. class TestAgent(object):
  343. def __init__(self, binary, node, port, env=None):
  344. self.node = node
  345. self.node_address = None
  346. self.port = port
  347. self.sock = None
  348. self.binary = binary
  349. self.started = False
  350. self.rsh = RemoteExec(Env=env)
  351. self.func_name = None
  352. self.used = False
  353. self.env = env
  354. self.send_recv = False
  355. def restart(self):
  356. self.env.debug('%s:%s restarting' % (self.node, self.binary))
  357. self.stop()
  358. self.start()
  359. def clean_start(self):
  360. if self.used or not self.status():
  361. self.env.debug('%s:%s cleaning' % (self.node, self.binary))
  362. self.stop()
  363. self.start()
  364. def status(self):
  365. if not self.started:
  366. return False
  367. try:
  368. self.send_internal(["are_you_ok_dude"])
  369. self.read()
  370. self.started = True
  371. return True
  372. except RuntimeError, msg:
  373. self.started = False
  374. return False
  375. def start(self):
  376. '''Set up the given ScenarioComponent'''
  377. if self.status():
  378. return
  379. self.env.debug('%s:%s starting ' % (self.node, self.binary))
  380. self.rsh(self.node, self.binary, synchronous=False)
  381. self.sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
  382. ip = socket.gethostbyname(self.node)
  383. is_connected = False
  384. retries = 0
  385. while not is_connected:
  386. try:
  387. retries = retries + 1
  388. self.sock.connect ((ip, self.port))
  389. is_connected = True
  390. except socket.error, msg:
  391. if retries > 10:
  392. self.env.log("%s:%s Tried connecting %d times. %s" % (self.node, self.binary, retries, str(msg)))
  393. if retries > 30:
  394. raise RuntimeError("%s:%s can't connect" % (self.node, self.binary))
  395. time.sleep(1)
  396. self.started = True
  397. self.used = False
  398. def stop(self):
  399. '''Tear down (undo) the given ScenarioComponent'''
  400. self.env.debug('%s:%s stopping' % (self.binary, self.node))
  401. self.rsh(self.node, "killall " + self.binary + " 2>/dev/null")
  402. if self.sock:
  403. self.sock.close ()
  404. del self.sock
  405. self.sock = None
  406. while self.getpid() != '':
  407. time.sleep(1)
  408. self.started = False
  409. def kill(self):
  410. '''Tear down (undo) the given ScenarioComponent'''
  411. self.env.log('%s:%s killing' % (self.node, self.binary))
  412. self.rsh(self.node, "killall -9 " + self.binary + " 2>/dev/null")
  413. self.started = False
  414. def getpid(self):
  415. return self.rsh(self.node, 'pidof ' + self.binary, 1)
  416. def send_internal(self, args):
  417. real_msg = str (len (args))
  418. for a in args:
  419. a_str = str(a)
  420. real_msg += ":" + str (len (a_str)) + ":" + a_str
  421. real_msg += ";"
  422. try:
  423. return self.sock.send (real_msg)
  424. except socket.error, msg:
  425. self.env.log("send(%s): %s; error: %s" % (self.node, real_msg, msg))
  426. return 0
  427. def send (self, args):
  428. if not self.started:
  429. self.start()
  430. sent = self.send_internal(args)
  431. if sent == 0:
  432. raise RuntimeError ("socket connection broken")
  433. self.used = True
  434. def __getattribute__(self,name):
  435. try:
  436. return object.__getattribute__(self, name)
  437. except:
  438. self.func_name = name
  439. if self.send_recv:
  440. return self.send_recv_dynamic
  441. else:
  442. return self.send_dynamic
  443. def send_recv_dynamic (self, *args):
  444. self.send_dynamic (args)
  445. try:
  446. res = self.read ()
  447. except RuntimeError, msg:
  448. res = None
  449. self.env.log("send_recv_dynamic: %s(); error: %s" % (self.func_name, msg))
  450. return res
  451. def send_dynamic (self, *args):
  452. if not self.started:
  453. raise RuntimeError ("agent not started")
  454. # number of args+func
  455. real_msg = str (len (args) + 1) + ":" + str(len(self.func_name)) + ":" + self.func_name
  456. for a in args:
  457. a_str = str(a)
  458. real_msg += ":" + str (len (a_str)) + ":" + a_str
  459. real_msg += ";"
  460. sent = 0
  461. try:
  462. sent = self.sock.send (real_msg)
  463. except socket.error, msg:
  464. self.env.log("send_dynamic(%s): %s; error: %s" % (self.node, real_msg, msg))
  465. if sent == 0:
  466. raise RuntimeError ("socket connection broken")
  467. self.used = True
  468. def read (self):
  469. try:
  470. msg = self.sock.recv (4096)
  471. except socket.error, msg:
  472. raise RuntimeError(msg)
  473. if msg == '':
  474. raise RuntimeError("socket connection broken")
  475. return msg
  476. class CpgConfigEvent:
  477. def __init__(self, msg):
  478. info = msg.split(',')
  479. self.group_name = info[0]
  480. self.node_id = info[1]
  481. self.node = None
  482. self.pid = info[2]
  483. if "left" in info[3]:
  484. self.is_member = False
  485. else:
  486. self.is_member = True
  487. def __str__ (self):
  488. str = self.group_name + "," + self.node_id + "," + self.pid + ","
  489. if self.is_member:
  490. return str + "joined"
  491. else:
  492. return str + "left"
  493. ###################################################################
  494. class CpgTestAgent(TestAgent):
  495. def __init__(self, node, Env=None):
  496. TestAgent.__init__(self, "cpg_test_agent", node, 9034, env=Env)
  497. self.nodeid = None
  498. def start(self):
  499. if not self.status():
  500. TestAgent.start(self)
  501. self.cpg_initialize()
  502. self.used = False
  503. def cpg_local_get(self):
  504. if self.nodeid == None:
  505. self.send (["cpg_local_get"])
  506. self.nodeid = self.read ()
  507. return self.nodeid
  508. def record_config_events(self, truncate=True):
  509. if truncate:
  510. self.send (["record_config_events", "truncate"])
  511. else:
  512. self.send (["record_config_events", "append"])
  513. return self.read ()
  514. def read_config_event(self):
  515. self.send (["read_config_event"])
  516. msg = self.read ()
  517. if "None" in msg:
  518. return None
  519. else:
  520. return CpgConfigEvent(msg)
  521. def read_messages(self, atmost):
  522. self.send (["read_messages", atmost])
  523. msg = self.read ()
  524. if "None" in msg:
  525. return None
  526. else:
  527. return msg
  528. def context_test(self):
  529. self.send (["context_test"])
  530. return self.read ()
  531. ###################################################################
  532. class SamTestAgent(TestAgent):
  533. def __init__(self, node, Env=None):
  534. TestAgent.__init__(self, "sam_test_agent", node, 9036, env=Env)
  535. self.nodeid = None
  536. self.send_recv = True
  537. ###################################################################
  538. class VoteQuorumTestAgent(TestAgent):
  539. def __init__(self, node, Env=None):
  540. TestAgent.__init__(self, "votequorum_test_agent", node, 9037, env=Env)
  541. self.nodeid = None
  542. self.send_recv = True
  543. AllAuditClasses = []
  544. AllAuditClasses.append(LogAudit)
  545. AllAuditClasses.append(ShmLeakAudit)
  546. def CoroAuditList(cm):
  547. result = []
  548. for auditclass in AllAuditClasses:
  549. a = auditclass(cm)
  550. if a.is_applicable():
  551. result.append(a)
  552. return result