minionswarm.py 13 KB

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