Ingen beskrivning
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 21KB

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