1
0

minionswarm.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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.helpers
  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.helpers.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. self.raet_port = 4550
  157. # If given a temp_dir, use it for temporary files
  158. if opts['temp_dir']:
  159. self.swarm_root = opts['temp_dir']
  160. else:
  161. # If given a root_dir, keep the tmp files there as well
  162. if opts['root_dir']:
  163. tmpdir = os.path.join(opts['root_dir'], 'tmp')
  164. else:
  165. tmpdir = opts['root_dir']
  166. self.swarm_root = tempfile.mkdtemp(
  167. prefix='mswarm-root', suffix='.d',
  168. dir=tmpdir)
  169. if self.opts['transport'] == 'zeromq':
  170. self.pki = self._pki_dir()
  171. self.zfill = len(str(self.opts['minions']))
  172. self.confs = set()
  173. random.seed(0)
  174. def _pki_dir(self):
  175. '''
  176. Create the shared pki directory
  177. '''
  178. path = os.path.join(self.swarm_root, 'pki')
  179. if not os.path.exists(path):
  180. os.makedirs(path)
  181. print('Creating shared pki keys for the swarm on: {0}'.format(path))
  182. subprocess.call(
  183. 'salt-key -c {0} --gen-keys minion --gen-keys-dir {0} '
  184. '--log-file {1} --user {2}'.format(
  185. path, os.path.join(path, 'keys.log'), self.opts['user'],
  186. ), shell=True
  187. )
  188. print('Keys generated')
  189. return path
  190. def start(self):
  191. '''
  192. Start the magic!!
  193. '''
  194. if self.opts['master_too']:
  195. master_swarm = MasterSwarm(self.opts)
  196. master_swarm.start()
  197. minions = MinionSwarm(self.opts)
  198. minions.start_minions()
  199. print('Starting minions...')
  200. #self.start_minions()
  201. print('All {0} minions have started.'.format(self.opts['minions']))
  202. print('Waiting for CTRL-C to properly shutdown minions...')
  203. while True:
  204. try:
  205. time.sleep(5)
  206. except KeyboardInterrupt:
  207. print('\nShutting down minions')
  208. self.clean_configs()
  209. break
  210. def shutdown(self):
  211. '''
  212. Tear it all down
  213. '''
  214. print('Killing any remaining running minions')
  215. subprocess.call(
  216. 'pkill -KILL -f "python.*salt-minion"',
  217. shell=True
  218. )
  219. if self.opts['master_too']:
  220. print('Killing any remaining masters')
  221. subprocess.call(
  222. 'pkill -KILL -f "python.*salt-master"',
  223. shell=True
  224. )
  225. if not self.opts['no_clean']:
  226. print('Remove ALL related temp files/directories')
  227. shutil.rmtree(self.swarm_root)
  228. print('Done')
  229. def clean_configs(self):
  230. '''
  231. Clean up the config files
  232. '''
  233. for path in self.confs:
  234. pidfile = '{0}.pid'.format(path)
  235. try:
  236. try:
  237. with salt.utils.files.fopen(pidfile) as fp_:
  238. pid = int(fp_.read().strip())
  239. os.kill(pid, signal.SIGTERM)
  240. except ValueError:
  241. pass
  242. if os.path.exists(pidfile):
  243. os.remove(pidfile)
  244. if not self.opts['no_clean']:
  245. shutil.rmtree(path)
  246. except (OSError, IOError):
  247. pass
  248. class MinionSwarm(Swarm):
  249. '''
  250. Create minions
  251. '''
  252. def __init__(self, opts):
  253. super(MinionSwarm, self).__init__(opts)
  254. def start_minions(self):
  255. '''
  256. Iterate over the config files and start up the minions
  257. '''
  258. self.prep_configs()
  259. for path in self.confs:
  260. cmd = 'salt-minion -c {0} --pid-file {1}'.format(
  261. path,
  262. '{0}.pid'.format(path)
  263. )
  264. if self.opts['foreground']:
  265. cmd += ' -l debug &'
  266. else:
  267. cmd += ' -d &'
  268. subprocess.call(cmd, shell=True)
  269. time.sleep(self.opts['start_delay'])
  270. def mkconf(self, idx):
  271. '''
  272. Create a config file for a single minion
  273. '''
  274. data = {}
  275. if self.opts['config_dir']:
  276. spath = os.path.join(self.opts['config_dir'], 'minion')
  277. with salt.utils.files.fopen(spath) as conf:
  278. data = salt.utils.yaml.safe_load(conf) or {}
  279. minion_id = '{0}-{1}'.format(
  280. self.opts['name'],
  281. str(idx).zfill(self.zfill)
  282. )
  283. dpath = os.path.join(self.swarm_root, minion_id)
  284. if not os.path.exists(dpath):
  285. os.makedirs(dpath)
  286. data.update({
  287. 'id': minion_id,
  288. 'user': self.opts['user'],
  289. 'cachedir': os.path.join(dpath, 'cache'),
  290. 'master': self.opts['master'],
  291. 'log_file': os.path.join(dpath, 'minion.log'),
  292. 'grains': {},
  293. })
  294. if self.opts['transport'] == 'zeromq':
  295. minion_pkidir = os.path.join(dpath, 'pki')
  296. if not os.path.exists(minion_pkidir):
  297. os.makedirs(minion_pkidir)
  298. minion_pem = os.path.join(self.pki, 'minion.pem')
  299. minion_pub = os.path.join(self.pki, 'minion.pub')
  300. shutil.copy(minion_pem, minion_pkidir)
  301. shutil.copy(minion_pub, minion_pkidir)
  302. data['pki_dir'] = minion_pkidir
  303. elif self.opts['transport'] == 'raet':
  304. data['transport'] = 'raet'
  305. data['sock_dir'] = os.path.join(dpath, 'sock')
  306. data['raet_port'] = self.raet_port
  307. data['pki_dir'] = os.path.join(dpath, 'pki')
  308. self.raet_port += 1
  309. elif self.opts['transport'] == 'tcp':
  310. data['transport'] = 'tcp'
  311. if self.opts['root_dir']:
  312. data['root_dir'] = self.opts['root_dir']
  313. path = os.path.join(dpath, 'minion')
  314. if self.opts['keep']:
  315. keep = self.opts['keep'].split(',')
  316. modpath = os.path.join(os.path.dirname(salt.__file__), 'modules')
  317. fn_prefixes = (fn_.partition('.')[0] for fn_ in os.listdir(modpath))
  318. ignore = [fn_prefix for fn_prefix in fn_prefixes if fn_prefix not in keep]
  319. data['disable_modules'] = ignore
  320. if self.opts['rand_os']:
  321. data['grains']['os'] = random.choice(OSES)
  322. if self.opts['rand_ver']:
  323. data['grains']['saltversion'] = random.choice(VERS)
  324. if self.opts['rand_machine_id']:
  325. data['grains']['machine_id'] = hashlib.md5(minion_id).hexdigest()
  326. if self.opts['rand_uuid']:
  327. data['grains']['uuid'] = str(uuid.uuid4())
  328. with salt.utils.files.fopen(path, 'w+') as fp_:
  329. salt.utils.yaml.safe_dump(data, fp_)
  330. self.confs.add(dpath)
  331. def prep_configs(self):
  332. '''
  333. Prepare the confs set
  334. '''
  335. for idx in range(self.opts['minions']):
  336. self.mkconf(idx)
  337. class MasterSwarm(Swarm):
  338. '''
  339. Create one or more masters
  340. '''
  341. def __init__(self, opts):
  342. super(MasterSwarm, self).__init__(opts)
  343. self.conf = os.path.join(self.swarm_root, 'master')
  344. def start(self):
  345. '''
  346. Prep the master start and fire it off
  347. '''
  348. # sys.stdout for no newline
  349. sys.stdout.write('Generating master config...')
  350. self.mkconf()
  351. print('done')
  352. sys.stdout.write('Starting master...')
  353. self.start_master()
  354. print('done')
  355. def start_master(self):
  356. '''
  357. Do the master start
  358. '''
  359. cmd = 'salt-master -c {0} --pid-file {1}'.format(
  360. self.conf,
  361. '{0}.pid'.format(self.conf)
  362. )
  363. if self.opts['foreground']:
  364. cmd += ' -l debug &'
  365. else:
  366. cmd += ' -d &'
  367. subprocess.call(cmd, shell=True)
  368. def mkconf(self): # pylint: disable=W0221
  369. '''
  370. Make a master config and write it'
  371. '''
  372. data = {}
  373. if self.opts['config_dir']:
  374. spath = os.path.join(self.opts['config_dir'], 'master')
  375. with salt.utils.files.fopen(spath) as conf:
  376. data = salt.utils.yaml.safe_load(conf)
  377. data.update({
  378. 'log_file': os.path.join(self.conf, 'master.log'),
  379. 'open_mode': True # TODO Pre-seed keys
  380. })
  381. os.makedirs(self.conf)
  382. path = os.path.join(self.conf, 'master')
  383. with salt.utils.files.fopen(path, 'w+') as fp_:
  384. salt.utils.yaml.safe_dump(data, fp_)
  385. def shutdown(self):
  386. print('Killing master')
  387. subprocess.call(
  388. 'pkill -KILL -f "python.*salt-master"',
  389. shell=True
  390. )
  391. print('Master killed')
  392. # pylint: disable=C0103
  393. if __name__ == '__main__':
  394. swarm = Swarm(parse())
  395. try:
  396. swarm.start()
  397. finally:
  398. swarm.shutdown()