1
0

minionswarm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 start_minions(self):
  252. '''
  253. Iterate over the config files and start up the minions
  254. '''
  255. self.prep_configs()
  256. for path in self.confs:
  257. cmd = 'salt-minion -c {0} --pid-file {1}'.format(
  258. path,
  259. '{0}.pid'.format(path)
  260. )
  261. if self.opts['foreground']:
  262. cmd += ' -l debug &'
  263. else:
  264. cmd += ' -d &'
  265. subprocess.call(cmd, shell=True)
  266. time.sleep(self.opts['start_delay'])
  267. def mkconf(self, idx):
  268. '''
  269. Create a config file for a single minion
  270. '''
  271. data = {}
  272. if self.opts['config_dir']:
  273. spath = os.path.join(self.opts['config_dir'], 'minion')
  274. with salt.utils.files.fopen(spath) as conf:
  275. data = salt.utils.yaml.safe_load(conf) or {}
  276. minion_id = '{0}-{1}'.format(
  277. self.opts['name'],
  278. str(idx).zfill(self.zfill)
  279. )
  280. dpath = os.path.join(self.swarm_root, minion_id)
  281. if not os.path.exists(dpath):
  282. os.makedirs(dpath)
  283. data.update({
  284. 'id': minion_id,
  285. 'user': self.opts['user'],
  286. 'cachedir': os.path.join(dpath, 'cache'),
  287. 'master': self.opts['master'],
  288. 'log_file': os.path.join(dpath, 'minion.log'),
  289. 'grains': {},
  290. })
  291. if self.opts['transport'] == 'zeromq':
  292. minion_pkidir = os.path.join(dpath, 'pki')
  293. if not os.path.exists(minion_pkidir):
  294. os.makedirs(minion_pkidir)
  295. minion_pem = os.path.join(self.pki, 'minion.pem')
  296. minion_pub = os.path.join(self.pki, 'minion.pub')
  297. shutil.copy(minion_pem, minion_pkidir)
  298. shutil.copy(minion_pub, minion_pkidir)
  299. data['pki_dir'] = minion_pkidir
  300. elif self.opts['transport'] == 'tcp':
  301. data['transport'] = 'tcp'
  302. if self.opts['root_dir']:
  303. data['root_dir'] = self.opts['root_dir']
  304. path = os.path.join(dpath, 'minion')
  305. if self.opts['keep']:
  306. keep = self.opts['keep'].split(',')
  307. modpath = os.path.join(os.path.dirname(salt.__file__), 'modules')
  308. fn_prefixes = (fn_.partition('.')[0] for fn_ in os.listdir(modpath))
  309. ignore = [fn_prefix for fn_prefix in fn_prefixes if fn_prefix not in keep]
  310. data['disable_modules'] = ignore
  311. if self.opts['rand_os']:
  312. data['grains']['os'] = random.choice(OSES)
  313. if self.opts['rand_ver']:
  314. data['grains']['saltversion'] = random.choice(VERS)
  315. if self.opts['rand_machine_id']:
  316. data['grains']['machine_id'] = hashlib.md5(minion_id).hexdigest()
  317. if self.opts['rand_uuid']:
  318. data['grains']['uuid'] = str(uuid.uuid4())
  319. with salt.utils.files.fopen(path, 'w+') as fp_:
  320. salt.utils.yaml.safe_dump(data, fp_)
  321. self.confs.add(dpath)
  322. def prep_configs(self):
  323. '''
  324. Prepare the confs set
  325. '''
  326. for idx in range(self.opts['minions']):
  327. self.mkconf(idx)
  328. class MasterSwarm(Swarm):
  329. '''
  330. Create one or more masters
  331. '''
  332. def __init__(self, opts):
  333. super(MasterSwarm, self).__init__(opts)
  334. self.conf = os.path.join(self.swarm_root, 'master')
  335. def start(self):
  336. '''
  337. Prep the master start and fire it off
  338. '''
  339. # sys.stdout for no newline
  340. sys.stdout.write('Generating master config...')
  341. self.mkconf()
  342. print('done')
  343. sys.stdout.write('Starting master...')
  344. self.start_master()
  345. print('done')
  346. def start_master(self):
  347. '''
  348. Do the master start
  349. '''
  350. cmd = 'salt-master -c {0} --pid-file {1}'.format(
  351. self.conf,
  352. '{0}.pid'.format(self.conf)
  353. )
  354. if self.opts['foreground']:
  355. cmd += ' -l debug &'
  356. else:
  357. cmd += ' -d &'
  358. subprocess.call(cmd, shell=True)
  359. def mkconf(self): # pylint: disable=W0221
  360. '''
  361. Make a master config and write it'
  362. '''
  363. data = {}
  364. if self.opts['config_dir']:
  365. spath = os.path.join(self.opts['config_dir'], 'master')
  366. with salt.utils.files.fopen(spath) as conf:
  367. data = salt.utils.yaml.safe_load(conf)
  368. data.update({
  369. 'log_file': os.path.join(self.conf, 'master.log'),
  370. 'open_mode': True # TODO Pre-seed keys
  371. })
  372. os.makedirs(self.conf)
  373. path = os.path.join(self.conf, 'master')
  374. with salt.utils.files.fopen(path, 'w+') as fp_:
  375. salt.utils.yaml.safe_dump(data, fp_)
  376. def shutdown(self):
  377. print('Killing master')
  378. subprocess.call(
  379. 'pkill -KILL -f "python.*salt-master"',
  380. shell=True
  381. )
  382. print('Master killed')
  383. # pylint: disable=C0103
  384. if __name__ == '__main__':
  385. swarm = Swarm(parse())
  386. try:
  387. swarm.start()
  388. finally:
  389. swarm.shutdown()