diffido.py 28 KB

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