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 23KB

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