1
0

minionswarm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. The minionswarm script will start a group of salt minions with different ids
  5. on a single system to test scale capabilities
  6. """
  7. # pylint: disable=resource-leakage
  8. # Import Python Libs
  9. from __future__ import absolute_import, print_function
  10. import hashlib
  11. import optparse
  12. import os
  13. import random
  14. import shutil
  15. import signal
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import time
  20. import uuid
  21. # Import salt libs
  22. import salt
  23. import salt.utils.files
  24. import salt.utils.yaml
  25. import tests.support.runtests
  26. # Import third party libs
  27. from salt.ext import six
  28. from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
  29. OSES = [
  30. "Arch",
  31. "Ubuntu",
  32. "Debian",
  33. "CentOS",
  34. "Fedora",
  35. "Gentoo",
  36. "AIX",
  37. "Solaris",
  38. ]
  39. VERS = [
  40. "2014.1.6",
  41. "2014.7.4",
  42. "2015.5.5",
  43. "2015.8.0",
  44. ]
  45. def parse():
  46. """
  47. Parse the cli options
  48. """
  49. parser = optparse.OptionParser()
  50. parser.add_option(
  51. "-m",
  52. "--minions",
  53. dest="minions",
  54. default=5,
  55. type="int",
  56. help="The number of minions to make",
  57. )
  58. parser.add_option(
  59. "-M",
  60. action="store_true",
  61. dest="master_too",
  62. default=False,
  63. help="Run a local master and tell the minions to connect to it",
  64. )
  65. parser.add_option(
  66. "--master",
  67. dest="master",
  68. default="salt",
  69. help="The location of the salt master that this swarm will serve",
  70. )
  71. parser.add_option(
  72. "--name",
  73. "-n",
  74. dest="name",
  75. default="ms",
  76. help=(
  77. "Give the minions an alternative id prefix, this is used "
  78. "when minions from many systems are being aggregated onto "
  79. "a single master"
  80. ),
  81. )
  82. parser.add_option(
  83. "--rand-os",
  84. dest="rand_os",
  85. default=False,
  86. action="store_true",
  87. help="Each Minion claims a different os grain",
  88. )
  89. parser.add_option(
  90. "--rand-ver",
  91. dest="rand_ver",
  92. default=False,
  93. action="store_true",
  94. help="Each Minion claims a different version grain",
  95. )
  96. parser.add_option(
  97. "--rand-machine-id",
  98. dest="rand_machine_id",
  99. default=False,
  100. action="store_true",
  101. help="Each Minion claims a different machine id grain",
  102. )
  103. parser.add_option(
  104. "--rand-uuid",
  105. dest="rand_uuid",
  106. default=False,
  107. action="store_true",
  108. help="Each Minion claims a different UUID grain",
  109. )
  110. parser.add_option(
  111. "-k",
  112. "--keep-modules",
  113. dest="keep",
  114. default="",
  115. help="A comma delimited list of modules to enable",
  116. )
  117. parser.add_option(
  118. "-f",
  119. "--foreground",
  120. dest="foreground",
  121. default=False,
  122. action="store_true",
  123. help=(
  124. "Run the minions with debug output of the swarm going to " "the terminal"
  125. ),
  126. )
  127. parser.add_option(
  128. "--temp-dir",
  129. dest="temp_dir",
  130. default=None,
  131. help="Place temporary files/directories here",
  132. )
  133. parser.add_option(
  134. "--no-clean",
  135. action="store_true",
  136. default=False,
  137. help="Don't cleanup temporary files/directories",
  138. )
  139. parser.add_option(
  140. "--root-dir",
  141. dest="root_dir",
  142. default=None,
  143. help="Override the minion root_dir config",
  144. )
  145. parser.add_option(
  146. "--transport",
  147. dest="transport",
  148. default="zeromq",
  149. help="Declare which transport to use, default is zeromq",
  150. )
  151. parser.add_option(
  152. "--start-delay",
  153. dest="start_delay",
  154. default=0.0,
  155. type="float",
  156. help="Seconds to wait between minion starts",
  157. )
  158. parser.add_option(
  159. "-c",
  160. "--config-dir",
  161. default="",
  162. help=("Pass in a configuration directory containing base configuration."),
  163. )
  164. parser.add_option("-u", "--user", default=tests.support.runtests.this_user())
  165. options, _args = parser.parse_args()
  166. opts = {}
  167. for key, val in six.iteritems(options.__dict__):
  168. opts[key] = val
  169. return opts
  170. class Swarm(object):
  171. """
  172. Create a swarm of minions
  173. """
  174. def __init__(self, opts):
  175. self.opts = opts
  176. # If given a temp_dir, use it for temporary files
  177. if opts["temp_dir"]:
  178. self.swarm_root = opts["temp_dir"]
  179. else:
  180. # If given a root_dir, keep the tmp files there as well
  181. if opts["root_dir"]:
  182. tmpdir = os.path.join(opts["root_dir"], "tmp")
  183. else:
  184. tmpdir = opts["root_dir"]
  185. self.swarm_root = tempfile.mkdtemp(
  186. prefix="mswarm-root", suffix=".d", dir=tmpdir
  187. )
  188. if self.opts["transport"] == "zeromq":
  189. self.pki = self._pki_dir()
  190. self.zfill = len(str(self.opts["minions"]))
  191. self.confs = set()
  192. random.seed(0)
  193. def _pki_dir(self):
  194. """
  195. Create the shared pki directory
  196. """
  197. path = os.path.join(self.swarm_root, "pki")
  198. if not os.path.exists(path):
  199. os.makedirs(path)
  200. print("Creating shared pki keys for the swarm on: {0}".format(path))
  201. subprocess.call(
  202. "salt-key -c {0} --gen-keys minion --gen-keys-dir {0} "
  203. "--log-file {1} --user {2}".format(
  204. path, os.path.join(path, "keys.log"), self.opts["user"],
  205. ),
  206. shell=True,
  207. )
  208. print("Keys generated")
  209. return path
  210. def start(self):
  211. """
  212. Start the magic!!
  213. """
  214. if self.opts["master_too"]:
  215. master_swarm = MasterSwarm(self.opts)
  216. master_swarm.start()
  217. minions = MinionSwarm(self.opts)
  218. minions.start_minions()
  219. print("Starting minions...")
  220. # self.start_minions()
  221. print("All {0} minions have started.".format(self.opts["minions"]))
  222. print("Waiting for CTRL-C to properly shutdown minions...")
  223. while True:
  224. try:
  225. time.sleep(5)
  226. except KeyboardInterrupt:
  227. print("\nShutting down minions")
  228. self.clean_configs()
  229. break
  230. def shutdown(self):
  231. """
  232. Tear it all down
  233. """
  234. print("Killing any remaining running minions")
  235. subprocess.call('pkill -KILL -f "python.*salt-minion"', shell=True)
  236. if self.opts["master_too"]:
  237. print("Killing any remaining masters")
  238. subprocess.call('pkill -KILL -f "python.*salt-master"', shell=True)
  239. if not self.opts["no_clean"]:
  240. print("Remove ALL related temp files/directories")
  241. shutil.rmtree(self.swarm_root)
  242. print("Done")
  243. def clean_configs(self):
  244. """
  245. Clean up the config files
  246. """
  247. for path in self.confs:
  248. pidfile = "{0}.pid".format(path)
  249. try:
  250. try:
  251. with salt.utils.files.fopen(pidfile) as fp_:
  252. pid = int(fp_.read().strip())
  253. os.kill(pid, signal.SIGTERM)
  254. except ValueError:
  255. pass
  256. if os.path.exists(pidfile):
  257. os.remove(pidfile)
  258. if not self.opts["no_clean"]:
  259. shutil.rmtree(path)
  260. except (OSError, IOError):
  261. pass
  262. class MinionSwarm(Swarm):
  263. """
  264. Create minions
  265. """
  266. def start_minions(self):
  267. """
  268. Iterate over the config files and start up the minions
  269. """
  270. self.prep_configs()
  271. for path in self.confs:
  272. cmd = "salt-minion -c {0} --pid-file {1}".format(
  273. path, "{0}.pid".format(path)
  274. )
  275. if self.opts["foreground"]:
  276. cmd += " -l debug &"
  277. else:
  278. cmd += " -d &"
  279. subprocess.call(cmd, shell=True)
  280. time.sleep(self.opts["start_delay"])
  281. def mkconf(self, idx):
  282. """
  283. Create a config file for a single minion
  284. """
  285. data = {}
  286. if self.opts["config_dir"]:
  287. spath = os.path.join(self.opts["config_dir"], "minion")
  288. with salt.utils.files.fopen(spath) as conf:
  289. data = salt.utils.yaml.safe_load(conf) or {}
  290. minion_id = "{0}-{1}".format(self.opts["name"], str(idx).zfill(self.zfill))
  291. dpath = os.path.join(self.swarm_root, minion_id)
  292. if not os.path.exists(dpath):
  293. os.makedirs(dpath)
  294. data.update(
  295. {
  296. "id": minion_id,
  297. "user": self.opts["user"],
  298. "cachedir": os.path.join(dpath, "cache"),
  299. "master": self.opts["master"],
  300. "log_file": os.path.join(dpath, "minion.log"),
  301. "grains": {},
  302. }
  303. )
  304. if self.opts["transport"] == "zeromq":
  305. minion_pkidir = os.path.join(dpath, "pki")
  306. if not os.path.exists(minion_pkidir):
  307. os.makedirs(minion_pkidir)
  308. minion_pem = os.path.join(self.pki, "minion.pem")
  309. minion_pub = os.path.join(self.pki, "minion.pub")
  310. shutil.copy(minion_pem, minion_pkidir)
  311. shutil.copy(minion_pub, minion_pkidir)
  312. data["pki_dir"] = minion_pkidir
  313. elif self.opts["transport"] == "tcp":
  314. data["transport"] = "tcp"
  315. if self.opts["root_dir"]:
  316. data["root_dir"] = self.opts["root_dir"]
  317. path = os.path.join(dpath, "minion")
  318. if self.opts["keep"]:
  319. keep = self.opts["keep"].split(",")
  320. modpath = os.path.join(os.path.dirname(salt.__file__), "modules")
  321. fn_prefixes = (fn_.partition(".")[0] for fn_ in os.listdir(modpath))
  322. ignore = [fn_prefix for fn_prefix in fn_prefixes if fn_prefix not in keep]
  323. data["disable_modules"] = ignore
  324. if self.opts["rand_os"]:
  325. data["grains"]["os"] = random.choice(OSES)
  326. if self.opts["rand_ver"]:
  327. data["grains"]["saltversion"] = random.choice(VERS)
  328. if self.opts["rand_machine_id"]:
  329. data["grains"]["machine_id"] = hashlib.md5(minion_id).hexdigest()
  330. if self.opts["rand_uuid"]:
  331. data["grains"]["uuid"] = str(uuid.uuid4())
  332. with salt.utils.files.fopen(path, "w+") as fp_:
  333. salt.utils.yaml.safe_dump(data, fp_)
  334. self.confs.add(dpath)
  335. def prep_configs(self):
  336. """
  337. Prepare the confs set
  338. """
  339. for idx in range(self.opts["minions"]):
  340. self.mkconf(idx)
  341. class MasterSwarm(Swarm):
  342. """
  343. Create one or more masters
  344. """
  345. def __init__(self, opts):
  346. super(MasterSwarm, self).__init__(opts)
  347. self.conf = os.path.join(self.swarm_root, "master")
  348. def start(self):
  349. """
  350. Prep the master start and fire it off
  351. """
  352. # sys.stdout for no newline
  353. sys.stdout.write("Generating master config...")
  354. self.mkconf()
  355. print("done")
  356. sys.stdout.write("Starting master...")
  357. self.start_master()
  358. print("done")
  359. def start_master(self):
  360. """
  361. Do the master start
  362. """
  363. cmd = "salt-master -c {0} --pid-file {1}".format(
  364. self.conf, "{0}.pid".format(self.conf)
  365. )
  366. if self.opts["foreground"]:
  367. cmd += " -l debug &"
  368. else:
  369. cmd += " -d &"
  370. subprocess.call(cmd, shell=True)
  371. def mkconf(self): # pylint: disable=W0221
  372. """
  373. Make a master config and write it'
  374. """
  375. data = {}
  376. if self.opts["config_dir"]:
  377. spath = os.path.join(self.opts["config_dir"], "master")
  378. with salt.utils.files.fopen(spath) as conf:
  379. data = salt.utils.yaml.safe_load(conf)
  380. data.update(
  381. {
  382. "log_file": os.path.join(self.conf, "master.log"),
  383. "open_mode": True, # TODO Pre-seed keys
  384. }
  385. )
  386. os.makedirs(self.conf)
  387. path = os.path.join(self.conf, "master")
  388. with salt.utils.files.fopen(path, "w+") as fp_:
  389. salt.utils.yaml.safe_dump(data, fp_)
  390. def shutdown(self):
  391. print("Killing master")
  392. subprocess.call('pkill -KILL -f "python.*salt-master"', shell=True)
  393. print("Master killed")
  394. # pylint: disable=C0103
  395. if __name__ == "__main__":
  396. swarm = Swarm(parse())
  397. try:
  398. swarm.start()
  399. finally:
  400. swarm.shutdown()