图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

552 lines
18 KiB

  1. #
  2. # Copyright (C) 2010-2011, 2011 Canonical Ltd. All Rights Reserved
  3. #
  4. # This file was originally taken from txzookeeper and modified later.
  5. #
  6. # Authors:
  7. # Kapil Thangavelu and the Kazoo team
  8. #
  9. # txzookeeper is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU Lesser General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # txzookeeper is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License
  20. # along with txzookeeper. If not, see <http://www.gnu.org/licenses/>.
  21. import code
  22. from collections import namedtuple
  23. from glob import glob
  24. from itertools import chain
  25. import logging
  26. import os
  27. import os.path
  28. import pathlib
  29. import shutil
  30. import signal
  31. import subprocess
  32. import tempfile
  33. import traceback
  34. import OpenSSL
  35. import jks
  36. log = logging.getLogger(__name__)
  37. def debug(sig, frame):
  38. """Interrupt running process, and provide a python prompt for
  39. interactive debugging."""
  40. d = {"_frame": frame} # Allow access to frame object.
  41. d.update(frame.f_globals) # Unless shadowed by global
  42. d.update(frame.f_locals)
  43. i = code.InteractiveConsole(d)
  44. message = "Signal recieved : entering python shell.\nTraceback:\n"
  45. message += "".join(traceback.format_stack(frame))
  46. i.interact(message)
  47. def listen():
  48. if os.name != "nt": # SIGUSR1 is not supported on Windows
  49. signal.signal(signal.SIGUSR1, debug) # Register handler
  50. listen()
  51. def to_java_compatible_path(path):
  52. if os.name == "nt":
  53. path = path.replace("\\", "/")
  54. return path
  55. ServerInfo = namedtuple(
  56. "ServerInfo",
  57. "server_id client_port secure_client_port "
  58. "election_port leader_port admin_port peer_type",
  59. )
  60. class ManagedZooKeeper(object):
  61. """Class to manage the running of a ZooKeeper instance for testing.
  62. Note: no attempt is made to probe the ZooKeeper instance is
  63. actually available, or that the selected port is free. In the
  64. future, we may want to do that, especially when run in a
  65. Hudson/Buildbot context, to ensure more test robustness."""
  66. def __init__(
  67. self,
  68. software_path,
  69. server_info,
  70. peers=(),
  71. classpath=None,
  72. configuration_entries=(),
  73. java_system_properties=(),
  74. jaas_config=None,
  75. ssl_configuration=None,
  76. ):
  77. """Define the ZooKeeper test instance.
  78. @param install_path: The path to the install for ZK
  79. @param port: The port to run the managed ZK instance
  80. """
  81. self.install_path = software_path
  82. self._classpath = classpath
  83. self.server_info = server_info
  84. self.host = "127.0.0.1"
  85. self.peers = peers
  86. self.working_path = tempfile.mkdtemp()
  87. self._running = False
  88. self.configuration_entries = configuration_entries
  89. self.java_system_properties = java_system_properties
  90. self.jaas_config = jaas_config
  91. self.ssl_configuration = (
  92. ssl_configuration if ssl_configuration is not None else {}
  93. )
  94. def run(self):
  95. """Run the ZooKeeper instance under a temporary directory.
  96. Writes ZK log messages to zookeeper.log in the current directory.
  97. """
  98. if self.running:
  99. return
  100. config_path = os.path.join(self.working_path, "zoo.cfg")
  101. jaas_config_path = os.path.join(self.working_path, "jaas.conf")
  102. log_path = os.path.join(self.working_path, "log")
  103. log4j_path = os.path.join(self.working_path, "log4j.properties")
  104. data_path = os.path.join(self.working_path, "data")
  105. truststore_path = os.path.join(self.working_path, "truststore.jks")
  106. keystore_path = os.path.join(self.working_path, "keystore.jks")
  107. # various setup steps
  108. if not os.path.exists(self.working_path):
  109. os.mkdir(self.working_path)
  110. if not os.path.exists(log_path):
  111. os.mkdir(log_path)
  112. if not os.path.exists(data_path):
  113. os.mkdir(data_path)
  114. try:
  115. self.ssl_configuration["truststore"].save(
  116. truststore_path, "apassword"
  117. )
  118. self.ssl_configuration["keystore"].save(keystore_path, "apassword")
  119. except Exception:
  120. log.exception("Unable to perform SSL configuration: ")
  121. raise
  122. with open(config_path, "w") as config:
  123. config.write(
  124. """
  125. tickTime=2000
  126. dataDir=%s
  127. clientPort=%s
  128. secureClientPort=%s
  129. maxClientCnxns=0
  130. admin.serverPort=%s
  131. serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
  132. authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
  133. ssl.keyStore.location=%s
  134. ssl.keyStore.password=apassword
  135. ssl.trustStore.location=%s
  136. ssl.trustStore.password=apassword
  137. %s
  138. """
  139. % (
  140. to_java_compatible_path(data_path),
  141. self.server_info.client_port,
  142. self.server_info.secure_client_port,
  143. self.server_info.admin_port,
  144. to_java_compatible_path(keystore_path),
  145. to_java_compatible_path(truststore_path),
  146. "\n".join(self.configuration_entries),
  147. )
  148. ) # NOQA
  149. # setup a replicated setup if peers are specified
  150. if self.peers:
  151. servers_cfg = []
  152. for p in chain((self.server_info,), self.peers):
  153. servers_cfg.append(
  154. "server.%s=localhost:%s:%s:%s"
  155. % (
  156. p.server_id,
  157. p.leader_port,
  158. p.election_port,
  159. p.peer_type,
  160. )
  161. )
  162. with open(config_path, "a") as config:
  163. config.write(
  164. """
  165. initLimit=4
  166. syncLimit=2
  167. %s
  168. peerType=%s
  169. """
  170. % ("\n".join(servers_cfg), self.server_info.peer_type)
  171. )
  172. # Write server ids into datadir
  173. with open(os.path.join(data_path, "myid"), "w") as myid_file:
  174. myid_file.write(str(self.server_info.server_id))
  175. # Write JAAS configuration
  176. with open(jaas_config_path, "w") as jaas_file:
  177. jaas_file.write(self.jaas_config or "")
  178. with open(log4j_path, "w") as log4j:
  179. log4j.write(
  180. """
  181. # DEFAULT: console appender only
  182. log4j.rootLogger=INFO, ROLLINGFILE
  183. log4j.appender.ROLLINGFILE.layout=org.apache.log4j.PatternLayout
  184. log4j.appender.ROLLINGFILE.layout.ConversionPattern=%d{ISO8601} \
  185. [myid:%X{myid}] - %-5p [%t:%C{1}@%L] - %m%n
  186. log4j.appender.ROLLINGFILE=org.apache.log4j.RollingFileAppender
  187. log4j.appender.ROLLINGFILE.Threshold=DEBUG
  188. log4j.appender.ROLLINGFILE.File="""
  189. + to_java_compatible_path( # NOQA
  190. self.working_path + os.sep + "zookeeper.log\n"
  191. )
  192. )
  193. args = (
  194. [
  195. "java",
  196. "-cp",
  197. self.classpath,
  198. # make_digest_acl_credential assumes UTF-8, but ZK decodes
  199. # digest auth packets using the JVM's default "charset"--which
  200. # depends on the environment. Force it to use UTF-8 to avoid
  201. # test failures.
  202. "-Dfile.encoding=UTF-8",
  203. # "-Dlog4j.debug",
  204. "-Dreadonlymode.enabled=true",
  205. "-Dzookeeper.log.dir=%s" % log_path,
  206. "-Dzookeeper.root.logger=INFO,CONSOLE",
  207. "-Dlog4j.configuration=file:%s" % log4j_path,
  208. # OS X: Prevent java from appearing in menu bar, process dock
  209. # and from activation of the main workspace on run.
  210. "-Djava.awt.headless=true",
  211. # JAAS configuration for SASL authentication
  212. "-Djava.security.auth.login.config=%s" % jaas_config_path,
  213. ]
  214. + list(self.java_system_properties)
  215. + [
  216. "org.apache.zookeeper.server.quorum.QuorumPeerMain",
  217. config_path,
  218. ]
  219. )
  220. self.process = subprocess.Popen(args=args)
  221. log.info(
  222. "Started zookeeper process %s on port %s using args %s",
  223. self.process.pid,
  224. self.server_info.client_port,
  225. args,
  226. )
  227. self._running = True
  228. @property
  229. def classpath(self):
  230. """Get the classpath necessary to run ZooKeeper."""
  231. if self._classpath:
  232. return self._classpath
  233. # Two possibilities, as seen in zkEnv.sh:
  234. # Check for a release - top-level zookeeper-*.jar?
  235. jars = glob((os.path.join(self.install_path, "zookeeper-*.jar")))
  236. if jars:
  237. # Release build (`ant package`)
  238. jars.extend(glob(os.path.join(self.install_path, "lib", "*.jar")))
  239. jars.extend(glob(os.path.join(self.install_path, "*.jar")))
  240. # support for different file locations on Debian/Ubuntu
  241. jars.extend(glob(os.path.join(self.install_path, "log4j-*.jar")))
  242. jars.extend(
  243. glob(os.path.join(self.install_path, "slf4j-api-*.jar"))
  244. )
  245. jars.extend(
  246. glob(os.path.join(self.install_path, "slf4j-log4j*.jar"))
  247. )
  248. else:
  249. # Development build (plain `ant`)
  250. jars = glob(
  251. (os.path.join(self.install_path, "build", "zookeeper-*.jar"))
  252. )
  253. jars.extend(
  254. glob(os.path.join(self.install_path, "build", "lib", "*.jar"))
  255. )
  256. return os.pathsep.join(jars)
  257. @property
  258. def address(self):
  259. """Get the address of the ZooKeeper instance."""
  260. return "%s:%s" % (self.host, self.client_port)
  261. @property
  262. def secure_address(self):
  263. """Get the address of the SSL ZooKeeper instance."""
  264. return "%s:%s" % (self.host, self.secure_client_port)
  265. @property
  266. def running(self):
  267. return self._running
  268. @property
  269. def client_port(self):
  270. return self.server_info.client_port
  271. @property
  272. def secure_client_port(self):
  273. return self.server_info.secure_client_port
  274. def reset(self):
  275. """Stop the zookeeper instance, cleaning out its on disk-data."""
  276. self.stop()
  277. shutil.rmtree(os.path.join(self.working_path, "data"), True)
  278. os.mkdir(os.path.join(self.working_path, "data"))
  279. with open(os.path.join(self.working_path, "data", "myid"), "w") as fh:
  280. fh.write(str(self.server_info.server_id))
  281. def stop(self):
  282. """Stop the Zookeeper instance, retaining on disk state."""
  283. if not self.running:
  284. return
  285. self.process.terminate()
  286. self.process.wait()
  287. if self.process.returncode != 0:
  288. log.warn(
  289. "Zookeeper process %s failed to terminate with"
  290. " non-zero return code (it terminated with %s return"
  291. " code instead)",
  292. self.process.pid,
  293. self.process.returncode,
  294. )
  295. self._running = False
  296. def destroy(self):
  297. """Stop the ZooKeeper instance and destroy its on disk-state"""
  298. # called by at exit handler, reimport to avoid cleanup race.
  299. self.stop()
  300. shutil.rmtree(self.working_path, True)
  301. def get_logs(self, num_lines=100):
  302. log_path = pathlib.Path(self.working_path, "zookeeper.log")
  303. if log_path.exists():
  304. log_file = log_path.open("r")
  305. lines = log_file.readlines()
  306. return lines[-num_lines:]
  307. return []
  308. class ZookeeperCluster(object):
  309. def __init__(
  310. self,
  311. install_path=None,
  312. classpath=None,
  313. size=3,
  314. port_offset=20000,
  315. observer_start_id=-1,
  316. configuration_entries=(),
  317. java_system_properties=(),
  318. jaas_config=None,
  319. ):
  320. self._install_path = install_path
  321. self._classpath = classpath
  322. self._servers = []
  323. self._ssl_configuration = {}
  324. self.perform_ssl_certs_generation()
  325. # Calculate ports and peer group
  326. port = port_offset
  327. peers = []
  328. for i in range(size):
  329. server_id = i + 1
  330. if observer_start_id != -1 and server_id >= observer_start_id:
  331. peer_type = "observer"
  332. else:
  333. peer_type = "participant"
  334. info = ServerInfo(
  335. server_id,
  336. port,
  337. port + 4,
  338. port + 1,
  339. port + 2,
  340. port + 3,
  341. peer_type,
  342. )
  343. peers.append(info)
  344. port += 10
  345. # Instantiate Managed ZK Servers
  346. for i in range(size):
  347. server_peers = list(peers)
  348. server_info = server_peers.pop(i)
  349. self._servers.append(
  350. ManagedZooKeeper(
  351. self._install_path,
  352. server_info,
  353. server_peers,
  354. classpath=self._classpath,
  355. configuration_entries=configuration_entries,
  356. java_system_properties=java_system_properties,
  357. jaas_config=jaas_config,
  358. ssl_configuration=dict(self._ssl_configuration),
  359. )
  360. )
  361. def __getitem__(self, k):
  362. return self._servers[k]
  363. def __iter__(self):
  364. return iter(self._servers)
  365. def start(self):
  366. # Zookeeper client expresses a preference for either lower ports or
  367. # lexicographical ordering of hosts, to ensure that all servers have a
  368. # chance to startup, start them in reverse order.
  369. for server in reversed(list(self)):
  370. server.run()
  371. # Giving the servers a moment to start, decreases the overall time
  372. # required for a client to successfully connect (2s vs. 4s without
  373. # the sleep).
  374. import time
  375. time.sleep(2)
  376. def stop(self):
  377. for server in self:
  378. server.stop()
  379. self._servers = []
  380. def terminate(self):
  381. for server in self:
  382. server.destroy()
  383. def reset(self):
  384. for server in self:
  385. server.reset()
  386. def get_logs(self):
  387. logs = []
  388. for server in self:
  389. logs += server.get_logs()
  390. return logs
  391. def perform_ssl_certs_generation(self):
  392. if self._ssl_configuration:
  393. return
  394. # generate CA key
  395. ca_key = OpenSSL.crypto.PKey()
  396. ca_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
  397. # generate CA
  398. ca_cert = OpenSSL.crypto.X509()
  399. ca_cert.set_version(2)
  400. ca_cert.set_serial_number(1)
  401. ca_cert.get_subject().CN = "ca.kazoo.org"
  402. ca_cert.gmtime_adj_notBefore(0)
  403. ca_cert.gmtime_adj_notAfter(24 * 60 * 60)
  404. ca_cert.set_issuer(ca_cert.get_subject())
  405. ca_cert.set_pubkey(ca_key)
  406. ca_cert.add_extensions(
  407. [
  408. OpenSSL.crypto.X509Extension(
  409. b"basicConstraints", True, b"CA:TRUE, pathlen:0"
  410. ),
  411. OpenSSL.crypto.X509Extension(
  412. b"keyUsage", True, b"keyCertSign, cRLSign"
  413. ),
  414. OpenSSL.crypto.X509Extension(
  415. b"subjectKeyIdentifier", False, b"hash", subject=ca_cert
  416. ),
  417. ]
  418. )
  419. ca_cert.sign(ca_key, "sha256")
  420. # generate server cert
  421. server_key = OpenSSL.crypto.PKey()
  422. server_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
  423. server_cert = OpenSSL.crypto.X509()
  424. server_cert.get_subject().CN = "localhost"
  425. server_cert.set_serial_number(2)
  426. server_cert.gmtime_adj_notBefore(0)
  427. server_cert.gmtime_adj_notAfter(24 * 60 * 60)
  428. server_cert.set_issuer(ca_cert.get_subject())
  429. server_cert.set_pubkey(server_key)
  430. server_cert.sign(ca_key, "sha256")
  431. # generate client cert
  432. client_key = OpenSSL.crypto.PKey()
  433. client_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
  434. client_cert = OpenSSL.crypto.X509()
  435. client_cert.get_subject().CN = "client"
  436. client_cert.set_serial_number(3)
  437. client_cert.gmtime_adj_notBefore(0)
  438. client_cert.gmtime_adj_notAfter(24 * 60 * 60)
  439. client_cert.set_issuer(ca_cert.get_subject())
  440. client_cert.set_pubkey(client_key)
  441. client_cert.sign(ca_key, "sha256")
  442. dumped_ca_cert = OpenSSL.crypto.dump_certificate(
  443. OpenSSL.crypto.FILETYPE_ASN1, ca_cert
  444. )
  445. tce = jks.TrustedCertEntry.new("kazoo ca", dumped_ca_cert)
  446. truststore = jks.KeyStore.new("jks", [tce])
  447. dumped_server_cert = OpenSSL.crypto.dump_certificate(
  448. OpenSSL.crypto.FILETYPE_ASN1, server_cert
  449. )
  450. dumped_server_key = OpenSSL.crypto.dump_privatekey(
  451. OpenSSL.crypto.FILETYPE_ASN1, server_key
  452. )
  453. server_pke = jks.PrivateKeyEntry.new(
  454. "server cert", [dumped_server_cert], dumped_server_key, "rsa_raw"
  455. )
  456. keystore = jks.KeyStore.new("jks", [server_pke])
  457. self._ssl_configuration = {
  458. "ca_cert": ca_cert,
  459. "ca_key": ca_key,
  460. "ca_cert_pem": OpenSSL.crypto.dump_certificate(
  461. OpenSSL.crypto.FILETYPE_PEM, ca_cert
  462. ),
  463. "server_cert": server_cert,
  464. "server_key": server_key,
  465. "client_cert": client_cert,
  466. "client_key": client_key,
  467. "client_cert_pem": OpenSSL.crypto.dump_certificate(
  468. OpenSSL.crypto.FILETYPE_PEM, client_cert
  469. ),
  470. "client_key_pem": OpenSSL.crypto.dump_privatekey(
  471. OpenSSL.crypto.FILETYPE_PEM, client_key
  472. ),
  473. "truststore": truststore,
  474. "keystore": keystore,
  475. }
  476. def get_ssl_client_configuration(self):
  477. if not self._ssl_configuration:
  478. raise RuntimeError("SSL not configured yet.")
  479. return {
  480. "client_key": self._ssl_configuration["client_key_pem"],
  481. "client_cert": self._ssl_configuration["client_cert_pem"],
  482. "ca_cert": self._ssl_configuration["ca_cert_pem"],
  483. }