PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/client/common_lib/base_barrier.py

https://gitlab.com/libvirt/autotest
Python | 542 lines | 513 code | 6 blank | 23 comment | 5 complexity | 9301cc7b3e53e1eb56fd6fa45910a126 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0
  1. import sys, socket, errno, logging
  2. from time import time, sleep
  3. from autotest_lib.client.common_lib import error
  4. # default barrier port
  5. _DEFAULT_PORT = 11922
  6. def get_host_from_id(hostid):
  7. # Remove any trailing local identifier following a #.
  8. # This allows multiple members per host which is particularly
  9. # helpful in testing.
  10. if not hostid.startswith('#'):
  11. return hostid.split('#')[0]
  12. else:
  13. raise error.BarrierError(
  14. "Invalid Host id: Host Address should be specified")
  15. class BarrierAbortError(error.BarrierError):
  16. """Special BarrierError raised when an explicit abort is requested."""
  17. class listen_server(object):
  18. """
  19. Manages a listening socket for barrier.
  20. Can be used to run multiple barrier instances with the same listening
  21. socket (if they were going to listen on the same port).
  22. Attributes:
  23. @attr address: Address to bind to (string).
  24. @attr port: Port to bind to.
  25. @attr socket: Listening socket object.
  26. """
  27. def __init__(self, address='', port=_DEFAULT_PORT):
  28. """
  29. Create a listen_server instance for the given address/port.
  30. @param address: The address to listen on.
  31. @param port: The port to listen on.
  32. """
  33. self.address = address
  34. self.port = port
  35. self.socket = self._setup()
  36. def _setup(self):
  37. """Create, bind and listen on the listening socket."""
  38. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  39. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  40. sock.bind((self.address, self.port))
  41. sock.listen(10)
  42. return sock
  43. def close(self):
  44. """Close the listening socket."""
  45. self.socket.close()
  46. class barrier(object):
  47. """Multi-machine barrier support.
  48. Provides multi-machine barrier mechanism.
  49. Execution stops until all members arrive at the barrier.
  50. Implementation Details:
  51. .......................
  52. When a barrier is forming the master node (first in sort order) in the
  53. set accepts connections from each member of the set. As they arrive
  54. they indicate the barrier they are joining and their identifier (their
  55. hostname or IP address and optional tag). They are then asked to wait.
  56. When all members are present the master node then checks that each
  57. member is still responding via a ping/pong exchange. If this is
  58. successful then everyone has checked in at the barrier. We then tell
  59. everyone they may continue via a rlse message.
  60. Where the master is not the first to reach the barrier the client
  61. connects will fail. Client will retry until they either succeed in
  62. connecting to master or the overall timeout is exceeded.
  63. As an example here is the exchange for a three node barrier called
  64. 'TAG'
  65. MASTER CLIENT1 CLIENT2
  66. <-------------TAG C1-------------
  67. --------------wait-------------->
  68. [...]
  69. <-------------TAG C2-----------------------------
  70. --------------wait------------------------------>
  71. [...]
  72. --------------ping-------------->
  73. <-------------pong---------------
  74. --------------ping------------------------------>
  75. <-------------pong-------------------------------
  76. ----- BARRIER conditions MET -----
  77. --------------rlse-------------->
  78. --------------rlse------------------------------>
  79. Note that once the last client has responded to pong the barrier is
  80. implicitly deemed satisifed, they have all acknowledged their presence.
  81. If we fail to send any of the rlse messages the barrier is still a
  82. success, the failed host has effectively broken 'right at the beginning'
  83. of the post barrier execution window.
  84. In addition, there is another rendezvous, that makes each slave a server
  85. and the master a client. The connection process and usage is still the
  86. same but allows barriers from machines that only have a one-way
  87. connection initiation. This is called rendezvous_servers.
  88. For example:
  89. if ME == SERVER:
  90. server start
  91. b = job.barrier(ME, 'server-up', 120)
  92. b.rendezvous(CLIENT, SERVER)
  93. if ME == CLIENT:
  94. client run
  95. b = job.barrier(ME, 'test-complete', 3600)
  96. b.rendezvous(CLIENT, SERVER)
  97. if ME == SERVER:
  98. server stop
  99. Any client can also request an abort of the job by setting
  100. abort=True in the rendezvous arguments.
  101. """
  102. def __init__(self, hostid, tag, timeout=None, port=None,
  103. listen_server=None):
  104. """
  105. @param hostid: My hostname/IP address + optional tag.
  106. @param tag: Symbolic name of the barrier in progress.
  107. @param timeout: Maximum seconds to wait for a the barrier to meet.
  108. @param port: Port number to listen on.
  109. @param listen_server: External listen_server instance to use instead
  110. of creating our own. Create a listen_server instance and
  111. reuse it across multiple barrier instances so that the
  112. barrier code doesn't try to quickly re-bind on the same port
  113. (packets still in transit for the previous barrier they may
  114. reset new connections).
  115. """
  116. self._hostid = hostid
  117. self._tag = tag
  118. if listen_server:
  119. if port:
  120. raise error.BarrierError(
  121. '"port" and "listen_server" are mutually exclusive.')
  122. self._port = listen_server.port
  123. else:
  124. self._port = port or _DEFAULT_PORT
  125. self._server = listen_server # A listen_server instance or None.
  126. self._members = [] # List of hosts we expect to find at the barrier.
  127. self._timeout_secs = timeout
  128. self._start_time = None # Timestamp of when we started waiting.
  129. self._masterid = None # Host/IP + optional tag of selected master.
  130. logging.info("tag=%s port=%d timeout=%r",
  131. self._tag, self._port, self._timeout_secs)
  132. # Number of clients seen (should be the length of self._waiting).
  133. self._seen = 0
  134. # Clients who have checked in and are waiting (if we are a master).
  135. self._waiting = {} # Maps from hostname -> (client, addr) tuples.
  136. def _update_timeout(self, timeout):
  137. if timeout is not None and self._start_time is not None:
  138. self._timeout_secs = (time() - self._start_time) + timeout
  139. else:
  140. self._timeout_secs = timeout
  141. def _remaining(self):
  142. if self._timeout_secs is not None and self._start_time is not None:
  143. timeout = self._timeout_secs - (time() - self._start_time)
  144. if timeout <= 0:
  145. errmsg = "timeout waiting for barrier: %s" % self._tag
  146. logging.error(error)
  147. raise error.BarrierError(errmsg)
  148. else:
  149. timeout = self._timeout_secs
  150. if self._timeout_secs is not None:
  151. logging.info("seconds remaining: %d", timeout)
  152. return timeout
  153. def _master_welcome(self, connection):
  154. client, addr = connection
  155. name = None
  156. client.settimeout(5)
  157. try:
  158. # Get the clients name.
  159. intro = client.recv(1024)
  160. intro = intro.strip("\r\n")
  161. intro_parts = intro.split(' ', 2)
  162. if len(intro_parts) != 2:
  163. logging.warn("Ignoring invalid data from %s: %r",
  164. client.getpeername(), intro)
  165. client.close()
  166. return
  167. tag, name = intro_parts
  168. logging.info("new client tag=%s, name=%s", tag, name)
  169. # Ok, we know who is trying to attach. Confirm that
  170. # they are coming to the same meeting. Also, everyone
  171. # should be using a unique handle (their IP address).
  172. # If we see a duplicate, something _bad_ has happened
  173. # so drop them now.
  174. if self._tag != tag:
  175. logging.warn("client arriving for the wrong barrier: %s != %s",
  176. self._tag, tag)
  177. client.settimeout(5)
  178. client.send("!tag")
  179. client.close()
  180. return
  181. elif name in self._waiting:
  182. logging.warn("duplicate client")
  183. client.settimeout(5)
  184. client.send("!dup")
  185. client.close()
  186. return
  187. # Acknowledge the client
  188. client.send("wait")
  189. except socket.timeout:
  190. # This is nominally an error, but as we do not know
  191. # who that was we cannot do anything sane other
  192. # than report it and let the normal timeout kill
  193. # us when thats appropriate.
  194. logging.warn("client handshake timeout: (%s:%d)",
  195. addr[0], addr[1])
  196. client.close()
  197. return
  198. logging.info("client now waiting: %s (%s:%d)",
  199. name, addr[0], addr[1])
  200. # They seem to be valid record them.
  201. self._waiting[name] = connection
  202. self._seen += 1
  203. def _slave_hello(self, connection):
  204. (client, addr) = connection
  205. name = None
  206. client.settimeout(5)
  207. try:
  208. client.send(self._tag + " " + self._hostid)
  209. reply = client.recv(4)
  210. reply = reply.strip("\r\n")
  211. logging.info("master said: %s", reply)
  212. # Confirm the master accepted the connection.
  213. if reply != "wait":
  214. logging.warn("Bad connection request to master")
  215. client.close()
  216. return
  217. except socket.timeout:
  218. # This is nominally an error, but as we do not know
  219. # who that was we cannot do anything sane other
  220. # than report it and let the normal timeout kill
  221. # us when thats appropriate.
  222. logging.error("master handshake timeout: (%s:%d)",
  223. addr[0], addr[1])
  224. client.close()
  225. return
  226. logging.info("slave now waiting: (%s:%d)", addr[0], addr[1])
  227. # They seem to be valid record them.
  228. self._waiting[self._hostid] = connection
  229. self._seen = 1
  230. def _master_release(self):
  231. # Check everyone is still there, that they have not
  232. # crashed or disconnected in the meantime.
  233. allpresent = True
  234. abort = self._abort
  235. for name in self._waiting:
  236. (client, addr) = self._waiting[name]
  237. logging.info("checking client present: %s", name)
  238. client.settimeout(5)
  239. reply = 'none'
  240. try:
  241. client.send("ping")
  242. reply = client.recv(1024)
  243. except socket.timeout:
  244. logging.warn("ping/pong timeout: %s", name)
  245. pass
  246. if reply == 'abrt':
  247. logging.warn("Client %s requested abort", name)
  248. abort = True
  249. elif reply != "pong":
  250. allpresent = False
  251. if not allpresent:
  252. raise error.BarrierError("master lost client")
  253. if abort:
  254. logging.info("Aborting the clients")
  255. msg = 'abrt'
  256. else:
  257. logging.info("Releasing clients")
  258. msg = 'rlse'
  259. # If every ones checks in then commit the release.
  260. for name in self._waiting:
  261. (client, addr) = self._waiting[name]
  262. client.settimeout(5)
  263. try:
  264. client.send(msg)
  265. except socket.timeout:
  266. logging.warn("release timeout: %s", name)
  267. pass
  268. if abort:
  269. raise BarrierAbortError("Client requested abort")
  270. def _waiting_close(self):
  271. # Either way, close out all the clients. If we have
  272. # not released them then they know to abort.
  273. for name in self._waiting:
  274. (client, addr) = self._waiting[name]
  275. logging.info("closing client: %s", name)
  276. try:
  277. client.close()
  278. except Exception:
  279. pass
  280. def _run_server(self, is_master):
  281. server = self._server or listen_server(port=self._port)
  282. failed = 0
  283. try:
  284. while True:
  285. try:
  286. # Wait for callers welcoming each.
  287. server.socket.settimeout(self._remaining())
  288. connection = server.socket.accept()
  289. if is_master:
  290. self._master_welcome(connection)
  291. else:
  292. self._slave_hello(connection)
  293. except socket.timeout:
  294. logging.warn("timeout waiting for remaining clients")
  295. pass
  296. if is_master:
  297. # Check if everyone is here.
  298. logging.info("master seen %d of %d",
  299. self._seen, len(self._members))
  300. if self._seen == len(self._members):
  301. self._master_release()
  302. break
  303. else:
  304. # Check if master connected.
  305. if self._seen:
  306. logging.info("slave connected to master")
  307. self._slave_wait()
  308. break
  309. finally:
  310. self._waiting_close()
  311. # if we created the listening_server in the beginning of this
  312. # function then close the listening socket here
  313. if not self._server:
  314. server.close()
  315. def _run_client(self, is_master):
  316. while self._remaining() is None or self._remaining() > 0:
  317. try:
  318. remote = socket.socket(socket.AF_INET,
  319. socket.SOCK_STREAM)
  320. remote.settimeout(30)
  321. if is_master:
  322. # Connect to all slaves.
  323. host = get_host_from_id(self._members[self._seen])
  324. logging.info("calling slave: %s", host)
  325. connection = (remote, (host, self._port))
  326. remote.connect(connection[1])
  327. self._master_welcome(connection)
  328. else:
  329. # Just connect to the master.
  330. host = get_host_from_id(self._masterid)
  331. logging.info("calling master")
  332. connection = (remote, (host, self._port))
  333. remote.connect(connection[1])
  334. self._slave_hello(connection)
  335. except socket.timeout:
  336. logging.warn("timeout calling host, retry")
  337. sleep(10)
  338. pass
  339. except socket.error, err:
  340. (code, str) = err
  341. if (code != errno.ECONNREFUSED):
  342. raise
  343. sleep(10)
  344. if is_master:
  345. # Check if everyone is here.
  346. logging.info("master seen %d of %d",
  347. self._seen, len(self._members))
  348. if self._seen == len(self._members):
  349. self._master_release()
  350. break
  351. else:
  352. # Check if master connected.
  353. if self._seen:
  354. logging.info("slave connected to master")
  355. self._slave_wait()
  356. break
  357. self._waiting_close()
  358. def _slave_wait(self):
  359. remote = self._waiting[self._hostid][0]
  360. mode = "wait"
  361. while True:
  362. # All control messages are the same size to allow
  363. # us to split individual messages easily.
  364. remote.settimeout(self._remaining())
  365. reply = remote.recv(4)
  366. if not reply:
  367. break
  368. reply = reply.strip("\r\n")
  369. logging.info("master said: %s", reply)
  370. mode = reply
  371. if reply == "ping":
  372. # Ensure we have sufficient time for the
  373. # ping/pong/rlse cyle to complete normally.
  374. self._update_timeout(10 + 10 * len(self._members))
  375. if self._abort:
  376. msg = "abrt"
  377. else:
  378. msg = "pong"
  379. logging.info(msg)
  380. remote.settimeout(self._remaining())
  381. remote.send(msg)
  382. elif reply == "rlse" or reply == "abrt":
  383. # Ensure we have sufficient time for the
  384. # ping/pong/rlse cyle to complete normally.
  385. self._update_timeout(10 + 10 * len(self._members))
  386. logging.info("was released, waiting for close")
  387. if mode == "rlse":
  388. pass
  389. elif mode == "wait":
  390. raise error.BarrierError("master abort -- barrier timeout")
  391. elif mode == "ping":
  392. raise error.BarrierError("master abort -- client lost")
  393. elif mode == "!tag":
  394. raise error.BarrierError("master abort -- incorrect tag")
  395. elif mode == "!dup":
  396. raise error.BarrierError("master abort -- duplicate client")
  397. elif mode == "abrt":
  398. raise BarrierAbortError("Client requested abort")
  399. else:
  400. raise error.BarrierError("master handshake failure: " + mode)
  401. def rendezvous(self, *hosts, **dargs):
  402. # if called with abort=True, this will raise an exception
  403. # on all the clients.
  404. self._start_time = time()
  405. self._members = list(hosts)
  406. self._members.sort()
  407. self._masterid = self._members.pop(0)
  408. self._abort = dargs.get('abort', False)
  409. logging.info("masterid: %s", self._masterid)
  410. if self._abort:
  411. logging.debug("%s is aborting", self._hostid)
  412. if not len(self._members):
  413. logging.info("No other members listed.")
  414. return
  415. logging.info("members: %s", ",".join(self._members))
  416. self._seen = 0
  417. self._waiting = {}
  418. # Figure out who is the master in this barrier.
  419. if self._hostid == self._masterid:
  420. logging.info("selected as master")
  421. self._run_server(is_master=True)
  422. else:
  423. logging.info("selected as slave")
  424. self._run_client(is_master=False)
  425. def rendezvous_servers(self, masterid, *hosts, **dargs):
  426. # if called with abort=True, this will raise an exception
  427. # on all the clients.
  428. self._start_time = time()
  429. self._members = list(hosts)
  430. self._members.sort()
  431. self._masterid = masterid
  432. self._abort = dargs.get('abort', False)
  433. logging.info("masterid: %s", self._masterid)
  434. if not len(self._members):
  435. logging.info("No other members listed.")
  436. return
  437. logging.info("members: %s", ",".join(self._members))
  438. self._seen = 0
  439. self._waiting = {}
  440. # Figure out who is the master in this barrier.
  441. if self._hostid == self._masterid:
  442. logging.info("selected as master")
  443. self._run_client(is_master=True)
  444. else:
  445. logging.info("selected as slave")
  446. self._run_server(is_master=False)