No Description
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.

slim.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. import os, os.path
  4. import sys
  5. import shutil
  6. import argparse
  7. import logging
  8. import re
  9. import json
  10. import configparser
  11. import signal
  12. import subprocess
  13. logging.basicConfig(level=logging.INFO)
  14. INSTANCES_ABSPATH="/tmp/lodel2_instances"
  15. CONFFILE='conf.d/lodel2.ini'
  16. try:
  17. STORE_FILE = os.path.join("[@]SLIM_VAR_DIR[@]", 'slim_instances.json')
  18. PID_FILE = os.path.join("[@]SLIM_VAR_DIR[@]", 'slim_instances_pid.json')
  19. CREATION_SCRIPT = os.path.join("[@]LODEL2_PROGSDIR[@]", 'create_instance')
  20. INSTALL_TPL = "[@]SLIM_INSTALLMODEL_DIR[@]"
  21. EMFILE = os.path.join("[@]SLIM_DATADIR[@]", 'emfile.pickle')
  22. except SyntaxError:
  23. STORE_FILE='./instances.json'
  24. PID_FILE = './slim_instances_pid.json'
  25. CREATION_SCRIPT='../scripts/create_instance.sh'
  26. INSTALL_TPL = './slim_ressources/slim_install_model'
  27. EMFILE = './slim_ressources/emfile.pickle'
  28. CREATION_SCRIPT=os.path.join(os.path.dirname(__file__), CREATION_SCRIPT)
  29. STORE_FILE=os.path.join(os.path.dirname(__file__), STORE_FILE)
  30. INSTALL_TPL=os.path.join(os.path.dirname(__file__), INSTALL_TPL)
  31. EMFILE=os.path.join(os.path.dirname(__file__), EMFILE)
  32. #STORE_FILE syntax :
  33. #
  34. #First level keys are instances names, their values are dict with following
  35. #informations :
  36. # - path
  37. #
  38. ##@brief Run 'make %target%' for each instances given in names
  39. #@param target str : make target
  40. #@param names list : list of instance name
  41. def run_make(target, names):
  42. validate_names(names)
  43. store_datas = get_store_datas()
  44. cwd = os.getcwd()
  45. for name in [n for n in store_datas if n in names]:
  46. datas = store_datas[name]
  47. logging.info("Running 'make %s' for '%s' in %s" % (
  48. target, name, datas['path']))
  49. os.chdir(datas['path'])
  50. os.system('make %s' % target)
  51. os.chdir(cwd)
  52. ##@brief Set configuration given args
  53. #@param args as returned by argparse
  54. def set_conf(name, args):
  55. validate_names([name])
  56. conffile = get_conffile(name)
  57. config = configparser.ConfigParser(interpolation=None)
  58. config.read(conffile)
  59. if args.interface is not None:
  60. iarg = args.interface
  61. if iarg not in ('web', 'python'):
  62. raise TypeError("Interface can only be on of : 'web', 'python'")
  63. if iarg.lower() == 'web':
  64. iarg = 'webui'
  65. else:
  66. iarg = ''
  67. config['lodel2']['interface'] = iarg
  68. interface = config['lodel2']['interface']
  69. if interface == 'webui':
  70. if 'lodel2.webui' not in config:
  71. config['lodel2.webui'] = dict()
  72. config['lodel2.webui']['standalone'] = 'uwsgi'
  73. if args.listen_port is not None:
  74. config['lodel2.webui']['listen_port'] = str(args.listen_port)
  75. if args.listen_address is not None:
  76. config['lodel2.webui']['listen_address'] = str(args.listen_address)
  77. else: #interface is python
  78. if args.listen_port is not None or args.listen_address is not None:
  79. logging.error("Listen port and listen address will not being set. \
  80. Selected interface is not the web iterface")
  81. if 'lodel.webui' in config:
  82. del(config['lodel2.webui'])
  83. #Now config should be OK to be written again in conffile
  84. with open(conffile, 'w+') as cfp:
  85. config.write(cfp)
  86. ##@brief If the name is not valid raise
  87. def name_is_valid(name):
  88. allowed_chars = [chr(i) for i in range(ord('a'), ord('z')+1)]
  89. allowed_chars += [chr(i) for i in range(ord('A'), ord('Z')+1)]
  90. allowed_chars += [chr(i) for i in range(ord('0'), ord('9')+1)]
  91. allowed_chars += ['_']
  92. for c in name:
  93. if c not in allowed_chars:
  94. raise RuntimeError("Allowed characters for instance name are \
  95. lower&upper alphanum and '_'. Name '%s' is invalid" % name)
  96. ##@brief Create a new instance
  97. #@param name str : the instance name
  98. def new_instance(name):
  99. name_is_valid(name)
  100. store_datas = get_store_datas()
  101. if name in store_datas:
  102. logging.error("An instance named '%s' already exists" % name)
  103. exit(1)
  104. if not os.path.isdir(INSTANCES_ABSPATH):
  105. logging.info("Instances directory '%s' don't exists, creating it")
  106. os.mkdir(INSTANCES_ABSPATH)
  107. instance_path = os.path.join(INSTANCES_ABSPATH, name)
  108. creation_cmd = '{script} "{name}" "{path}" "{install_tpl}" \
  109. "{emfile}"'.format(
  110. script = CREATION_SCRIPT,
  111. name = name,
  112. path = instance_path,
  113. install_tpl = INSTALL_TPL,
  114. emfile = EMFILE)
  115. res = os.system(creation_cmd)
  116. if res != 0:
  117. logging.error("Creation script fails")
  118. exit(res)
  119. #storing new instance
  120. store_datas[name] = {'path': instance_path}
  121. save_datas(store_datas)
  122. ##@brief Delete an instance
  123. #@param name str : the instance name
  124. def delete_instance(name):
  125. pids = get_pids()
  126. if name in pids:
  127. logging.error("The instance '%s' is started. Stop it before deleting \
  128. it" % name)
  129. return
  130. store_datas = get_store_datas()
  131. logging.warning("Deleting instance %s" % name)
  132. logging.info("Deleting instance folder %s" % store_datas[name]['path'])
  133. shutil.rmtree(store_datas[name]['path'])
  134. logging.debug("Deleting instance from json store file")
  135. del(store_datas[name])
  136. save_datas(store_datas)
  137. ##@brief returns stored datas
  138. def get_store_datas():
  139. if not os.path.isfile(STORE_FILE) or os.stat(STORE_FILE).st_size == 0:
  140. return dict()
  141. else:
  142. with open(STORE_FILE, 'r') as sfp:
  143. datas = json.load(sfp)
  144. return datas
  145. ##@brief Checks names validity and exit if fails
  146. def validate_names(names):
  147. store_datas = get_store_datas()
  148. invalid = [ n for n in names if n not in store_datas]
  149. if len(invalid) > 0:
  150. print("Following names are not existing instance :", file=sys.stderr)
  151. for name in invalid:
  152. print("\t%s" % name, file=sys.stderr)
  153. exit(1)
  154. ##@brief Returns the PID dict
  155. #@return a dict with instance name as key an PID as value
  156. def get_pids():
  157. if not os.path.isfile(PID_FILE) or os.stat(PID_FILE).st_size == 0:
  158. return dict()
  159. with open(PID_FILE, 'r') as pfd:
  160. return json.load(pfd)
  161. ##@brief Save a dict of pid
  162. #@param pid_dict dict : key is instance name values are pid
  163. def save_pids(pid_dict):
  164. with open(PID_FILE, 'w+') as pfd:
  165. json.dump(pid_dict, pfd)
  166. ##@brief Given an instance name returns its PID
  167. #@return False or an int
  168. def get_pid(name):
  169. pid_datas = get_pids()
  170. if name not in pid_datas:
  171. return False
  172. else:
  173. pid = pid_datas[name]
  174. if not is_running(name, pid):
  175. return False
  176. return pid
  177. ##@brief Start an instance
  178. #@param names list : instance name list
  179. def start_instances(names, foreground):
  180. pids = get_pids()
  181. store_datas = get_store_datas()
  182. for name in names:
  183. if name in pids:
  184. logging.warning("The instance %s is allready running" % name)
  185. continue
  186. os.chdir(store_datas[name]['path'])
  187. args = [sys.executable, 'loader.py']
  188. if foreground:
  189. logging.info("Calling execl with : ", args)
  190. os.execl(args[0], *args)
  191. return #only usefull if execl call fails (not usefull)
  192. else:
  193. curexec = subprocess.Popen(args,
  194. stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
  195. stderr=subprocess.DEVNULL, preexec_fn=os.setsid,
  196. cwd = store_datas[name]['path'])
  197. pids[name] = curexec.pid
  198. logging.info("Instance '%s' started. PID %d" % (name, curexec.pid))
  199. save_pids(pids)
  200. ##@brief Stop an instance given its name
  201. #@param names list : names list
  202. def stop_instances(names):
  203. pids = get_pids()
  204. store_datas = get_store_datas()
  205. for name in names:
  206. if name not in pids:
  207. logging.warning("The instance %s is not running" % name)
  208. continue
  209. pid = pids[name]
  210. try:
  211. os.kill(pid, signal.SIGINT)
  212. except ProcessLookupError:
  213. logging.warning("The instance %s seems to be in error, no process \
  214. with pid %d found" % (pids[name], name))
  215. del(pids[name])
  216. save_pids(pids)
  217. ##@brief Checks that a process is running
  218. #
  219. #If not running clean the pid list
  220. #@return bool
  221. def is_running(name, pid):
  222. try:
  223. os.kill(pid, 0)
  224. return True
  225. except (OSError,ProcessLookupError):
  226. pid_datas = get_pids()
  227. logging.warning("Instance '%s' was marked as running, but not \
  228. process with pid %d found. Cleaning pid list" % (name, pid))
  229. del(pid_datas[name])
  230. save_pids(pid_datas)
  231. return False
  232. ##@brief Check if instance are specified
  233. def get_specified(args):
  234. if args.all:
  235. names = list(get_store_datas().keys())
  236. elif args.name is not None:
  237. names = args.name
  238. else:
  239. names = None
  240. return names
  241. ##@brief Saves store datas
  242. def save_datas(datas):
  243. with open(STORE_FILE, 'w+') as sfp:
  244. json.dump(datas, sfp)
  245. ##@return conffile path
  246. def get_conffile(name):
  247. validate_names([name])
  248. store_datas = get_store_datas()
  249. return os.path.join(store_datas[name]['path'], CONFFILE)
  250. ##@brief Print the list of instances and exit
  251. #@param verbosity int
  252. #@param batch bool : if true make simple output
  253. def list_instances(verbosity, batch):
  254. verbosity = 0 if verbosity is None else verbosity
  255. if not os.path.isfile(STORE_FILE):
  256. print("No store file, no instances are existing. Exiting...",
  257. file=sys.stderr)
  258. exit(0)
  259. store_datas = get_store_datas()
  260. if not batch:
  261. print('Instances list :')
  262. for name in store_datas:
  263. details_instance(name, verbosity, batch)
  264. exit(0)
  265. ##@brief Print instance informations and return (None)
  266. #@param name str : instance name
  267. #@param verbosity int
  268. #@param batch bool : if true make simple output
  269. def details_instance(name, verbosity, batch):
  270. validate_names([name])
  271. store_datas = get_store_datas()
  272. pids = get_pids()
  273. if not batch:
  274. msg = "\t- '%s'" % name
  275. if name in pids and is_running(name, pids[name]):
  276. msg += ' [Run PID %d] ' % pids[name]
  277. if verbosity > 0:
  278. msg += ' path = "%s"' % store_datas[name]['path']
  279. if verbosity > 1:
  280. ruler = (''.join(['=' for _ in range(20)])) + "\n"
  281. msg += "\n\t\t====conf.d/lodel2.ini====\n"
  282. with open(get_conffile(name)) as cfp:
  283. for line in cfp:
  284. msg += "\t\t"+line
  285. msg += "\t\t=========================\n"
  286. print(msg)
  287. else:
  288. msg = name
  289. if name in pids and is_running(name, pids[name]):
  290. msg += ' %d ' % pids[name]
  291. else:
  292. msg += ' stopped '
  293. if verbosity > 0:
  294. msg += "\t"+'"%s"' % store_datas[name]['path']
  295. if verbosity > 1:
  296. conffile = get_conffile(name)
  297. msg += "\n\t#####"+conffile+"#####\n"
  298. with open(conffile, 'r') as cfp:
  299. for line in cfp:
  300. msg += "\t"+line
  301. msg += "\n\t###########"
  302. print(msg)
  303. ##@brief Returns instanciated parser
  304. def get_parser():
  305. parser = argparse.ArgumentParser(
  306. description='SLIM (Simple Lodel Instance Manager.)')
  307. selector = parser.add_argument_group('Instances selectors')
  308. actions = parser.add_argument_group('Instances actions')
  309. confs = parser.add_argument_group('Options (use with -c or -s)')
  310. startstop = parser.add_argument_group('Start/stop options')
  311. parser.add_argument('-l', '--list',
  312. help='list existing instances and exit', action='store_const',
  313. const=True, default=False)
  314. parser.add_argument('-v', '--verbose', action='count')
  315. parser.add_argument('-b', '--batch', action='store_const',
  316. default=False, const=True,
  317. help="Format output (when possible) making it usable by POSIX scripts \
  318. (only implemented for -l for the moment)")
  319. selector.add_argument('-a', '--all', action='store_const',
  320. default=False, const=True,
  321. help='Select all instances')
  322. selector.add_argument('-n', '--name', metavar='NAME', type=str, nargs='*',
  323. help="Specify an instance name")
  324. actions.add_argument('-c', '--create', action='store_const',
  325. default=False, const=True,
  326. help="Create a new instance with given name (see -n --name)")
  327. actions.add_argument('-d', '--delete', action='store_const',
  328. default=False, const=True,
  329. help="Delete an instance with given name (see -n --name)")
  330. actions.add_argument('-p', '--purge', action='store_const',
  331. default=False, const=True,
  332. help="Delete ALL instances")
  333. actions.add_argument('-s', '--set-option', action='store_const',
  334. default=False, const=True,
  335. help="Use this flag to set options on instance")
  336. actions.add_argument('-e', '--edit-config', action='store_const',
  337. default=False, const=True,
  338. help='Edit configuration of specified instance')
  339. actions.add_argument('-i', '--interactive', action='store_const',
  340. default=False, const=True,
  341. help='Run a loader.py from ONE instance in foreground')
  342. actions.add_argument('-m', '--make', metavar='TARGET', type=str,
  343. nargs="?", default='not',
  344. help='Run make for selected instances')
  345. startstop.add_argument('--stop', action='store_const',
  346. default=False, const=True, help="Stop instances")
  347. startstop.add_argument('--start', action='store_const',
  348. default=False, const=True, help="Start instances")
  349. startstop.add_argument('-f', '--foreground', action='store_const',
  350. default=False, const=True, help="Start in foreground (limited \
  351. to 1 instance")
  352. confs.add_argument('--interface', type=str,
  353. help="Select wich interface to run. Possible values are \
  354. 'python' and 'web'")
  355. confs.add_argument('--listen-port', type=int,
  356. help="Select the port on wich the web interface will listen to")
  357. confs.add_argument('--listen-address', type=str,
  358. help="Select the address on wich the web interface will bind to")
  359. return parser
  360. if __name__ == '__main__':
  361. parser = get_parser()
  362. args = parser.parse_args()
  363. if args.verbose is None:
  364. args.verbose = 0
  365. if args.list:
  366. # Instances list
  367. if args.name is not None:
  368. validate_names(args.name)
  369. for name in args.name:
  370. details_instance(name, args.verbose, args.batch)
  371. else:
  372. list_instances(args.verbose, args.batch)
  373. elif args.create:
  374. #Instance creation
  375. if args.name is None:
  376. parser.print_help()
  377. print("\nAn instance name expected when creating an instance !",
  378. file=sys.stderr)
  379. exit(1)
  380. for name in args.name:
  381. new_instance(name)
  382. elif args.purge:
  383. # SLIM Purge (stop & delete all)
  384. print("Do you really want to delete all the instances ? Yes/no ",)
  385. rep = sys.stdin.readline()
  386. if rep == "Yes\n":
  387. store = get_store_datas()
  388. stop_instances(store.keys())
  389. for name in store:
  390. delete_instance(name)
  391. elif rep.lower() != 'no':
  392. print("Expect exactly 'Yes' to confirm...")
  393. exit()
  394. elif args.delete:
  395. #Instance deletion
  396. if args.all:
  397. parser.print_help()
  398. print("\n use -p --purge instead of --delete --all",
  399. file=sys.stderr)
  400. exit(1)
  401. if args.name is None:
  402. parser.print_help()
  403. print("\nAn instance name expected when creating an instance !",
  404. file=sys.stderr)
  405. exit(1)
  406. validate_names(args.name)
  407. for name in args.name:
  408. delete_instance(name)
  409. elif args.make != 'not':
  410. #Running make in instances
  411. if args.make is None:
  412. target = 'all'
  413. else:
  414. target = args.make
  415. names = get_specified(args)
  416. if names is None:
  417. parser.print_help()
  418. print("\nWhen using -m --make options you have to select \
  419. instances, either by name using -n or all using -a")
  420. exit(1)
  421. run_make(target, names)
  422. elif args.edit_config:
  423. #Edit configuration
  424. names = get_specified(args)
  425. if len(names) > 1:
  426. print("\n-e --edit-config option works only when 1 instance is \
  427. specified")
  428. validate_names(names)
  429. name = names[0]
  430. store_datas = get_store_datas()
  431. conffile = get_conffile(name)
  432. os.system('editor "%s"' % conffile)
  433. exit(0)
  434. elif args.interactive:
  435. #Run loader.py in foreground
  436. if args.name is None or len(args.name) != 1:
  437. print("\n-i option only allowed with ONE instance name")
  438. parser.print_help()
  439. exit(1)
  440. validate_names(args.name)
  441. name = args.name[0]
  442. store_datas = get_store_datas()
  443. os.chdir(store_datas[name]['path'])
  444. os.execl('/usr/bin/env', '/usr/bin/env', 'python3', 'loader.py')
  445. elif args.set_option:
  446. names = None
  447. if args.all:
  448. names = list(get_store_datas().values())
  449. elif args.name is not None:
  450. names = args.name
  451. if names is None:
  452. parser.print_help()
  453. print("\n-s option only allowed with instance specified (by name \
  454. or with -a)")
  455. exit(1)
  456. for name in names:
  457. set_conf(name, args)
  458. elif args.start:
  459. names = get_specified(args)
  460. if names is None:
  461. parser.print_help()
  462. print("\nPlease specify at least 1 instance with the --start \
  463. option", file=sys.stderr)
  464. elif args.foreground and len(names) > 1:
  465. parser.prin_help()
  466. print("\nOnly 1 instance allowed with the use of the --forground \
  467. argument")
  468. start_instances(names, args.foreground)
  469. elif args.stop:
  470. names = get_specified(args)
  471. stop_instances(names)