diffido.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """Diffido - because the F5 key is a terrible thing to waste.
  4. Copyright 2018 Davide Alberani <da@erlug.linux.it>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import os
  15. import re
  16. import io
  17. import json
  18. import shutil
  19. import urllib
  20. import smtplib
  21. from email.mime.text import MIMEText
  22. import logging
  23. import datetime
  24. import requests
  25. import subprocess
  26. import multiprocessing
  27. from lxml import etree
  28. from xml.etree import ElementTree
  29. from tornado.ioloop import IOLoop
  30. from apscheduler.triggers.cron import CronTrigger
  31. from apscheduler.schedulers.tornado import TornadoScheduler
  32. from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
  33. import tornado.httpserver
  34. import tornado.ioloop
  35. import tornado.options
  36. from tornado.options import define, options
  37. import tornado.web
  38. from tornado import gen, escape
  39. JOBS_STORE = 'sqlite:///conf/jobs.db'
  40. API_VERSION = '1.0'
  41. SCHEDULES_FILE = 'conf/schedules.json'
  42. DEFAULT_CONF = 'conf/diffido.conf'
  43. EMAIL_FROM = 'diffido@localhost'
  44. SMTP_SETTINGS = {}
  45. GIT_CMD = 'git'
  46. re_commit = re.compile(r'^(?P<id>[0-9a-f]{40}) (?P<message>.*)\n(?: .* '
  47. '(?P<insertions>\d+) insertion.* (?P<deletions>\d+) deletion.*$)?', re.M)
  48. re_insertion = re.compile(r'(\d+) insertion')
  49. re_deletion = re.compile(r'(\d+) deletion')
  50. logger = logging.getLogger()
  51. logger.setLevel(logging.INFO)
  52. def read_schedules():
  53. """Return the schedules configuration.
  54. :returns: dictionary from the JSON object in conf/schedules.json
  55. :rtype: dict"""
  56. if not os.path.isfile(SCHEDULES_FILE):
  57. return {'schedules': {}}
  58. try:
  59. with open(SCHEDULES_FILE, 'r') as fd:
  60. schedules = json.loads(fd.read())
  61. for id_ in schedules.get('schedules', {}).keys():
  62. schedule = schedules['schedules'][id_]
  63. try:
  64. schedule['last_history'] = get_last_history(id_)
  65. except:
  66. schedule['last_history'] = {}
  67. continue
  68. return schedules
  69. except Exception as e:
  70. logger.error('unable to read %s: %s' % (SCHEDULES_FILE, e))
  71. return {'schedules': {}}
  72. def write_schedules(schedules):
  73. """Write the schedules configuration.
  74. :param schedules: the schedules to save
  75. :type schedules: dict
  76. :returns: True in case of success
  77. :rtype: bool"""
  78. try:
  79. with open(SCHEDULES_FILE, 'w') as fd:
  80. fd.write(json.dumps(schedules, indent=2))
  81. except Exception as e:
  82. logger.error('unable to write %s: %s' % (SCHEDULES_FILE, e))
  83. return False
  84. return True
  85. def next_id(schedules):
  86. """Return the next available integer (as a string) in the list of schedules keys (do not fills holes)
  87. :param schedules: the schedules
  88. :type schedules: dict
  89. :returns: the ID of the next schedule
  90. :rtype: str"""
  91. ids = schedules.get('schedules', {}).keys()
  92. if not ids:
  93. return '1'
  94. return str(max([int(i) for i in ids]) + 1)
  95. def get_schedule(id_, add_id=True, add_history=False):
  96. """Return information about a single schedule
  97. :param id_: ID of the schedule
  98. :type id_: str
  99. :param add_id: if True, add the ID in the dictionary
  100. :type add_id: bool
  101. :returns: the schedule
  102. :rtype: dict"""
  103. try:
  104. schedules = read_schedules()
  105. except Exception:
  106. return {}
  107. data = schedules.get('schedules', {}).get(id_, {})
  108. if add_history and data:
  109. data['last_history'] = get_last_history(id_)
  110. if add_id:
  111. data['id'] = str(id_)
  112. return data
  113. def select_xpath(content, xpath):
  114. """Select a portion of a HTML document
  115. :param content: the content of the document
  116. :type content: str
  117. :param xpath: the XPath selector
  118. :type xpath: str
  119. :returns: the selected document
  120. :rtype: str"""
  121. fd = io.StringIO(content)
  122. tree = etree.parse(fd)
  123. elems = tree.xpath(xpath)
  124. if not elems:
  125. return content
  126. selected_content = []
  127. for elem in elems:
  128. selected_content.append(''.join([elem.text] + [ElementTree.tostring(e).decode('utf-8', 'replace')
  129. for e in elem.getchildren()]))
  130. content = ''.join(selected_content)
  131. return content
  132. def run_job(id_=None, force=False, *args, **kwargs):
  133. """Run a job
  134. :param id_: ID of the schedule to run
  135. :type id_: str
  136. :param force: run even if disabled
  137. :type force: bool
  138. :param args: positional arguments
  139. :type args: tuple
  140. :param kwargs: named arguments
  141. :type kwargs: dict
  142. :returns: True in case of success
  143. :rtype: bool"""
  144. schedule = get_schedule(id_, add_id=False)
  145. url = schedule.get('url')
  146. if not url:
  147. return False
  148. logger.debug('running job id:%s title:%s url: %s' % (id_, schedule.get('title', ''), url))
  149. if not schedule.get('enabled') and not force:
  150. logger.info('not running job %s: disabled' % id_)
  151. return True
  152. req = requests.get(url, allow_redirects=True, timeout=(30.10, 240))
  153. content = req.text
  154. xpath = schedule.get('xpath')
  155. if xpath:
  156. try:
  157. content = select_xpath(content, xpath)
  158. except Exception as e:
  159. logger.warn('unable to extract XPath %s: %s' % (xpath, e))
  160. req_path = urllib.parse.urlparse(req.url).path
  161. base_name = os.path.basename(req_path) or 'index.html'
  162. def _commit(id_, filename, content, queue):
  163. os.chdir('storage/%s' % id_)
  164. current_lines = 0
  165. if os.path.isfile(filename):
  166. with open(filename, 'r') as fd:
  167. for line in fd:
  168. current_lines += 1
  169. with open(filename, 'w') as fd:
  170. fd.write(content)
  171. p = subprocess.Popen([GIT_CMD, 'add', filename])
  172. p.communicate()
  173. p = subprocess.Popen([GIT_CMD, 'commit', '-m', '%s' % datetime.datetime.utcnow(), '--allow-empty'],
  174. stdout=subprocess.PIPE)
  175. stdout, _ = p.communicate()
  176. stdout = stdout.decode('utf-8')
  177. insert = re_insertion.findall(stdout)
  178. if insert:
  179. insert = int(insert[0])
  180. else:
  181. insert = 0
  182. delete = re_deletion.findall(stdout)
  183. if delete:
  184. delete = int(delete[0])
  185. else:
  186. delete = 0
  187. queue.put({'insertions': insert, 'deletions': delete, 'previous_lines': current_lines,
  188. 'changes': max(insert, delete)})
  189. queue = multiprocessing.Queue()
  190. p = multiprocessing.Process(target=_commit, args=(id_, base_name, content, queue))
  191. p.start()
  192. res = queue.get()
  193. p.join()
  194. email = schedule.get('email')
  195. if not email:
  196. return True
  197. changes = res.get('changes')
  198. if not changes:
  199. return True
  200. min_change = schedule.get('minimum_change')
  201. previous_lines = res.get('previous_lines')
  202. if min_change and previous_lines:
  203. min_change = float(min_change)
  204. change_fraction = res.get('changes') / previous_lines
  205. if change_fraction < min_change:
  206. return True
  207. # send notification
  208. diff = get_diff(id_).get('diff')
  209. if not diff:
  210. return True
  211. send_email(to=email, subject='%s page changed' % schedule.get('title'),
  212. body='changes:\n\n%s' % diff)
  213. return True
  214. def safe_run_job(id_=None, *args, **kwargs):
  215. """Safely run a job, catching all the exceptions
  216. :param id_: ID of the schedule to run
  217. :type id_: str
  218. :param args: positional arguments
  219. :type args: tuple
  220. :param kwargs: named arguments
  221. :type kwargs: dict
  222. :returns: True in case of success
  223. :rtype: bool"""
  224. try:
  225. run_job(id_, *args, **kwargs)
  226. except Exception as e:
  227. send_email('error executing job %s: %s' % (id_, e))
  228. def send_email(to, subject='diffido', body='', from_=None):
  229. """Send an email
  230. :param to: destination address
  231. :type to: str
  232. :param subject: email subject
  233. :type subject: str
  234. :param body: body of the email
  235. :type body: str
  236. :param from_: sender address
  237. :type from_: str
  238. :returns: True in case of success
  239. :rtype: bool"""
  240. msg = MIMEText(body)
  241. msg['Subject'] = subject
  242. msg['From'] = from_ or EMAIL_FROM
  243. msg['To'] = to
  244. starttls = SMTP_SETTINGS.get('smtp-starttls')
  245. use_ssl = SMTP_SETTINGS.get('smtp-use-ssl')
  246. args = {}
  247. for key, value in SMTP_SETTINGS.items():
  248. if key in ('smtp-starttls', 'smtp-use-ssl'):
  249. continue
  250. if key in ('smtp-port'):
  251. value = int(value)
  252. key = key.replace('smtp-', '', 1).replace('-', '_')
  253. args[key] = value
  254. try:
  255. if use_ssl:
  256. with smtplib.SMTP_SSL(**args) as s:
  257. s.send_message(msg)
  258. else:
  259. tls_args = {}
  260. for key in ('ssl_keyfile', 'ssl_certfile', 'ssl_context'):
  261. if key in args:
  262. tls_args = args[key]
  263. del args[key]
  264. with smtplib.SMTP(**args) as s:
  265. if starttls:
  266. s.starttls(**tls_args)
  267. s.ehlo_or_helo_if_needed()
  268. s.send_message(msg)
  269. except Exception as e:
  270. logger.error('unable to send email to %s: %s' % (to, e))
  271. return False
  272. return True
  273. def get_history(id_, limit=None, add_info=False):
  274. """Read the history of a schedule
  275. :param id_: ID of the schedule
  276. :type id_: str
  277. :param limit: number of entries to fetch
  278. :type limit: int
  279. :param add_info: add information about the schedule itself
  280. :type add_info: int
  281. :returns: information about the schedule and its history
  282. :rtype: dict"""
  283. def _history(id_, limit, queue):
  284. os.chdir('storage/%s' % id_)
  285. cmd = [GIT_CMD, 'log', '--pretty=oneline', '--shortstat']
  286. if limit is not None:
  287. cmd.append('-%s' % limit)
  288. p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  289. stdout, _ = p.communicate()
  290. queue.put(stdout)
  291. queue = multiprocessing.Queue()
  292. p = multiprocessing.Process(target=_history, args=(id_, limit, queue))
  293. p.start()
  294. res = queue.get().decode('utf-8')
  295. p.join()
  296. history = []
  297. for match in re_commit.finditer(res):
  298. info = match.groupdict()
  299. info['insertions'] = int(info['insertions'] or 0)
  300. info['deletions'] = int(info['deletions'] or 0)
  301. info['changes'] = max(info['insertions'], info['deletions'])
  302. history.append(info)
  303. last_id = None
  304. if history and 'id' in history[0]:
  305. last_id = history[0]['id']
  306. for idx, item in enumerate(history):
  307. item['seq'] = idx + 1
  308. data = {'history': history, 'last_id': last_id}
  309. if add_info:
  310. data['schedule'] = get_schedule(id_)
  311. return data
  312. def get_last_history(id_):
  313. """Read the last history entry of a schedule
  314. :param id_: ID of the schedule
  315. :type id_: str
  316. :returns: information about the schedule and its history
  317. :rtype: dict"""
  318. history = get_history(id_, limit=1)
  319. return history.get('history', [{}])[0]
  320. def get_diff(id_, commit_id='HEAD', old_commit_id=None):
  321. """Return the diff between commits of a schedule
  322. :param id_: ID of the schedule
  323. :type id_: str
  324. :param commit_id: the most recent commit ID; HEAD by default
  325. :type commit_id: str
  326. :param old_commit_id: the older commit ID; if None, the previous commit is used
  327. :type old_commit_id: str
  328. :returns: information about the schedule and the diff between commits
  329. :rtype: dict"""
  330. def _history(id_, commit_id, old_commit_id, queue):
  331. os.chdir('storage/%s' % id_)
  332. p = subprocess.Popen([GIT_CMD, 'diff', old_commit_id or '%s~' % commit_id, commit_id],
  333. stdout=subprocess.PIPE)
  334. stdout, _ = p.communicate()
  335. queue.put(stdout)
  336. queue = multiprocessing.Queue()
  337. p = multiprocessing.Process(target=_history, args=(id_, commit_id, old_commit_id, queue))
  338. p.start()
  339. res = queue.get().decode('utf-8')
  340. p.join()
  341. schedule = get_schedule(id_)
  342. return {'diff': res, 'schedule': schedule}
  343. def scheduler_update(scheduler, id_):
  344. """Update a scheduler job, using information from the JSON object
  345. :param scheduler: the TornadoScheduler instance to modify
  346. :type scheduler: TornadoScheduler
  347. :param id_: ID of the schedule that must be updated
  348. :type id_: str
  349. :returns: True in case of success
  350. :rtype: bool"""
  351. schedule = get_schedule(id_, add_id=False)
  352. if not schedule:
  353. logger.warn('unable to update empty schedule %s' % id_)
  354. return False
  355. trigger = schedule.get('trigger')
  356. if trigger not in ('interval', 'cron'):
  357. logger.warn('unable to update empty schedule %s: trigger not in ("cron", "interval")' % id_)
  358. return False
  359. args = {}
  360. if trigger == 'interval':
  361. args['trigger'] = 'interval'
  362. for unit in 'weeks', 'days', 'hours', 'minutes', 'seconds':
  363. if 'interval_%s' % unit not in schedule:
  364. continue
  365. try:
  366. args[unit] = int(schedule['interval_%s' % unit])
  367. except Exception:
  368. logger.warn('invalid argument on schedule %s: %s parameter %s is not an integer' %
  369. (id_, 'interval_%s' % unit, schedule['interval_%s' % unit]))
  370. elif trigger == 'cron':
  371. try:
  372. cron_trigger = CronTrigger.from_crontab(schedule['cron_crontab'])
  373. args['trigger'] = cron_trigger
  374. except Exception:
  375. logger.warn('invalid argument on schedule %s: cron_tab parameter %s is not a valid crontab' %
  376. (id_, schedule.get('cron_crontab')))
  377. git_create_repo(id_)
  378. try:
  379. scheduler.add_job(safe_run_job, id=id_, replace_existing=True, kwargs={'id_': id_}, **args)
  380. except Exception as e:
  381. logger.warn('unable to update job %s: %s' % (id_, e))
  382. return False
  383. return True
  384. def scheduler_delete(scheduler, id_):
  385. """Update a scheduler job, using information from the JSON object
  386. :param scheduler: the TornadoScheduler instance to modify
  387. :type scheduler: TornadoScheduler
  388. :param id_: ID of the schedule
  389. :type id_: str
  390. :returns: True in case of success
  391. :rtype: bool"""
  392. try:
  393. scheduler.remove_job(job_id=id_)
  394. except Exception as e:
  395. logger.warn('unable to delete job %s: %s' % (id_, e))
  396. return False
  397. return git_delete_repo(id_)
  398. def reset_from_schedules(scheduler):
  399. """"Reset all scheduler jobs, using information from the JSON object
  400. :param scheduler: the TornadoScheduler instance to modify
  401. :type scheduler: TornadoScheduler
  402. :returns: True in case of success
  403. :rtype: bool"""
  404. ret = False
  405. try:
  406. scheduler.remove_all_jobs()
  407. for key in read_schedules().get('schedules', {}).keys():
  408. ret |= scheduler_update(scheduler, id_=key)
  409. except Exception as e:
  410. logger.warn('unable to reset all jobs: %s' % e)
  411. return False
  412. return ret
  413. def git_init():
  414. """Initialize Git global settings"""
  415. p = subprocess.Popen([GIT_CMD, 'config', '--global', 'user.email', '"%s"' % EMAIL_FROM])
  416. p.communicate()
  417. p = subprocess.Popen([GIT_CMD, 'config', '--global', 'user.name', '"Diffido"'])
  418. p.communicate()
  419. def git_create_repo(id_):
  420. """Create a Git repository
  421. :param id_: ID of the schedule
  422. :type id_: str
  423. :returns: True in case of success
  424. :rtype: bool"""
  425. repo_dir = 'storage/%s' % id_
  426. if os.path.isdir(repo_dir):
  427. return True
  428. p = subprocess.Popen([GIT_CMD, 'init', repo_dir])
  429. p.communicate()
  430. return p.returncode == 0
  431. def git_delete_repo(id_):
  432. """Delete a Git repository
  433. :param id_: ID of the schedule
  434. :type id_: str
  435. :returns: True in case of success
  436. :rtype: bool"""
  437. repo_dir = 'storage/%s' % id_
  438. if not os.path.isdir(repo_dir):
  439. return False
  440. try:
  441. shutil.rmtree(repo_dir)
  442. except Exception as e:
  443. logger.warn('unable to delete Git repository %s: %s' % (id_, e))
  444. return False
  445. return True
  446. class DiffidoBaseException(Exception):
  447. """Base class for diffido custom exceptions.
  448. :param message: text message
  449. :type message: str
  450. :param status: numeric http status code
  451. :type status: int"""
  452. def __init__(self, message, status=400):
  453. super(DiffidoBaseException, self).__init__(message)
  454. self.message = message
  455. self.status = status
  456. class BaseHandler(tornado.web.RequestHandler):
  457. """Base class for request handlers."""
  458. # A property to access the first value of each argument.
  459. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  460. for k, v in self.request.arguments.items()]))
  461. @property
  462. def clean_body(self):
  463. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  464. :returns: a clean copy of the body arguments
  465. :rtype: dict"""
  466. return escape.json_decode(self.request.body or '{}')
  467. def write_error(self, status_code, **kwargs):
  468. """Default error handler."""
  469. if isinstance(kwargs.get('exc_info', (None, None))[1], DiffidoBaseException):
  470. exc = kwargs['exc_info'][1]
  471. status_code = exc.status
  472. message = exc.message
  473. else:
  474. message = 'internal error'
  475. self.build_error(message, status=status_code)
  476. def initialize(self, **kwargs):
  477. """Add every passed (key, value) as attributes of the instance."""
  478. for key, value in kwargs.items():
  479. setattr(self, key, value)
  480. def build_error(self, message='', status=400):
  481. """Build and write an error message.
  482. :param message: textual message
  483. :type message: str
  484. :param status: HTTP status code
  485. :type status: int
  486. """
  487. self.set_status(status)
  488. self.write({'error': True, 'message': message})
  489. def build_success(self, message='', status=200):
  490. """Build and write a success message.
  491. :param message: textual message
  492. :type message: str
  493. :param status: HTTP status code
  494. :type status: int
  495. """
  496. self.set_status(status)
  497. self.write({'error': False, 'message': message})
  498. class SchedulesHandler(BaseHandler):
  499. """Schedules handler."""
  500. @gen.coroutine
  501. def get(self, id_=None, *args, **kwargs):
  502. """Get a schedule."""
  503. if id_ is not None:
  504. return self.write({'schedule': get_schedule(id_, add_history=True)})
  505. schedules = read_schedules()
  506. self.write(schedules)
  507. @gen.coroutine
  508. def put(self, id_=None, *args, **kwargs):
  509. """Update a schedule."""
  510. if id_ is None:
  511. return self.build_error(message='update action requires an ID')
  512. data = self.clean_body
  513. schedules = read_schedules()
  514. if id_ not in schedules.get('schedules', {}):
  515. return self.build_error(message='schedule %s not found' % id_)
  516. schedules['schedules'][id_] = data
  517. write_schedules(schedules)
  518. scheduler_update(scheduler=self.scheduler, id_=id_)
  519. self.write(get_schedule(id_=id_))
  520. @gen.coroutine
  521. def post(self, *args, **kwargs):
  522. """Add a schedule."""
  523. data = self.clean_body
  524. schedules = read_schedules()
  525. id_ = next_id(schedules)
  526. schedules['schedules'][id_] = data
  527. write_schedules(schedules)
  528. scheduler_update(scheduler=self.scheduler, id_=id_)
  529. self.write(get_schedule(id_=id_))
  530. @gen.coroutine
  531. def delete(self, id_=None, *args, **kwargs):
  532. """Delete a schedule."""
  533. if id_ is None:
  534. return self.build_error(message='an ID must be specified')
  535. schedules = read_schedules()
  536. if id_ in schedules.get('schedules', {}):
  537. del schedules['schedules'][id_]
  538. write_schedules(schedules)
  539. scheduler_delete(scheduler=self.scheduler, id_=id_)
  540. self.build_success(message='removed schedule %s' % id_)
  541. class RunScheduleHandler(BaseHandler):
  542. """Reset schedules handler."""
  543. @gen.coroutine
  544. def post(self, id_, *args, **kwargs):
  545. if run_job(id_, force=True):
  546. return self.build_success('job run')
  547. self.build_error('job not run')
  548. class ResetSchedulesHandler(BaseHandler):
  549. """Reset schedules handler."""
  550. @gen.coroutine
  551. def post(self, *args, **kwargs):
  552. reset_from_schedules(self.scheduler)
  553. class HistoryHandler(BaseHandler):
  554. """History handler."""
  555. @gen.coroutine
  556. def get(self, id_, *args, **kwargs):
  557. self.write(get_history(id_, add_info=True))
  558. class DiffHandler(BaseHandler):
  559. """Diff handler."""
  560. @gen.coroutine
  561. def get(self, id_, commit_id, old_commit_id=None, *args, **kwargs):
  562. self.write(get_diff(id_, commit_id, old_commit_id))
  563. class TemplateHandler(BaseHandler):
  564. """Handler for the template files in the / path."""
  565. @gen.coroutine
  566. def get(self, *args, **kwargs):
  567. """Get a template file."""
  568. page = 'index.html'
  569. if args and args[0]:
  570. page = args[0].strip('/')
  571. arguments = self.arguments
  572. self.render(page, **arguments)
  573. def serve():
  574. """Read configuration and start the server."""
  575. global EMAIL_FROM, SMTP_SETTINGS
  576. jobstores = {'default': SQLAlchemyJobStore(url=JOBS_STORE)}
  577. scheduler = TornadoScheduler(jobstores=jobstores)
  578. scheduler.start()
  579. define('port', default=3210, help='run on the given port', type=int)
  580. define('address', default='', help='bind the server at the given address', type=str)
  581. define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_cert.pem'),
  582. help='specify the SSL certificate to use for secure connections')
  583. define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_key.pem'),
  584. help='specify the SSL private key to use for secure connections')
  585. define('admin-email', default='', help='email address of the site administrator', type=str)
  586. define('smtp-host', default='localhost', help='SMTP server address', type=str)
  587. define('smtp-port', default=0, help='SMTP server port', type=int)
  588. define('smtp-local-hostname', default=None, help='SMTP local hostname', type=str)
  589. define('smtp-use-ssl', default=False, help='Use SSL to connect to the SMTP server', type=bool)
  590. define('smtp-starttls', default=False, help='Use STARTTLS to connect to the SMTP server', type=bool)
  591. define('smtp-ssl-keyfile', default=None, help='SSL key file', type=str)
  592. define('smtp-ssl-certfile', default=None, help='SSL cert file', type=str)
  593. define('smtp-ssl-context', default=None, help='SSL context', type=str)
  594. define('debug', default=False, help='run in debug mode', type=bool)
  595. define('config', help='read configuration file',
  596. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  597. if not options.config and os.path.isfile(DEFAULT_CONF):
  598. tornado.options.parse_config_file(DEFAULT_CONF, final=False)
  599. tornado.options.parse_command_line()
  600. if options.admin_email:
  601. EMAIL_FROM = options.admin_email
  602. for key, value in options.as_dict().items():
  603. if key.startswith('smtp-'):
  604. SMTP_SETTINGS[key] = value
  605. if options.debug:
  606. logger.setLevel(logging.DEBUG)
  607. ssl_options = {}
  608. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  609. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  610. init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options,
  611. scheduler=scheduler)
  612. git_init()
  613. _reset_schedules_path = r'schedules/reset'
  614. _schedule_run_path = r'schedules/(?P<id_>\d+)/run'
  615. _schedules_path = r'schedules/?(?P<id_>\d+)?'
  616. _history_path = r'schedules/?(?P<id_>\d+)/history'
  617. _diff_path = r'schedules/(?P<id_>\d+)/diff/(?P<commit_id>[0-9a-f]+)/?(?P<old_commit_id>[0-9a-f]+)?/?'
  618. application = tornado.web.Application([
  619. (r'/api/%s' % _reset_schedules_path, ResetSchedulesHandler, init_params),
  620. (r'/api/v%s/%s' % (API_VERSION, _reset_schedules_path), ResetSchedulesHandler, init_params),
  621. (r'/api/%s' % _schedule_run_path, RunScheduleHandler, init_params),
  622. (r'/api/v%s/%s' % (API_VERSION, _schedule_run_path), RunScheduleHandler, init_params),
  623. (r'/api/%s' % _history_path, HistoryHandler, init_params),
  624. (r'/api/v%s/%s' % (API_VERSION, _history_path), HistoryHandler, init_params),
  625. (r'/api/%s' % _diff_path, DiffHandler, init_params),
  626. (r'/api/v%s/%s' % (API_VERSION, _diff_path), DiffHandler, init_params),
  627. (r'/api/%s' % _schedules_path, SchedulesHandler, init_params),
  628. (r'/api/v%s/%s' % (API_VERSION, _schedules_path), SchedulesHandler, init_params),
  629. (r'/?(.*)', TemplateHandler, init_params),
  630. ],
  631. static_path=os.path.join(os.path.dirname(__file__), 'dist/static'),
  632. template_path=os.path.join(os.path.dirname(__file__), 'dist/'),
  633. debug=options.debug)
  634. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  635. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  636. options.address if options.address else '127.0.0.1',
  637. options.port)
  638. http_server.listen(options.port, options.address)
  639. try:
  640. IOLoop.instance().start()
  641. except (KeyboardInterrupt, SystemExit):
  642. pass
  643. if __name__ == '__main__':
  644. serve()