diffido.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import re
  5. import io
  6. import json
  7. import shutil
  8. import urllib
  9. import smtplib
  10. from email.mime.text import MIMEText
  11. import logging
  12. import datetime
  13. import requests
  14. import subprocess
  15. import multiprocessing
  16. from lxml import etree
  17. from xml.etree import ElementTree
  18. from tornado.ioloop import IOLoop
  19. from apscheduler.triggers.cron import CronTrigger
  20. from apscheduler.schedulers.tornado import TornadoScheduler
  21. from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
  22. import tornado.httpserver
  23. import tornado.ioloop
  24. import tornado.options
  25. from tornado.options import define, options
  26. import tornado.web
  27. from tornado import gen, escape
  28. JOBS_STORE = 'sqlite:///conf/jobs.db'
  29. API_VERSION = '1.0'
  30. SCHEDULES_FILE = 'conf/schedules.json'
  31. DEFAULT_CONF = 'conf/diffido.conf'
  32. EMAIL_FROM = 'diffido@localhost'
  33. GIT_CMD = 'git'
  34. re_commit = re.compile(r'^(?P<id>[0-9a-f]{40}) (?P<message>.*)\n(?: .* '
  35. '(?P<insertions>\d+) insertion.* (?P<deletions>\d+) deletion.*$)?', re.M)
  36. re_insertion = re.compile(r'(\d+) insertion')
  37. re_deletion = re.compile(r'(\d+) deletion')
  38. logger = logging.getLogger()
  39. logger.setLevel(logging.INFO)
  40. def read_schedules():
  41. if not os.path.isfile(SCHEDULES_FILE):
  42. return {'schedules': {}}
  43. try:
  44. with open(SCHEDULES_FILE, 'r') as fd:
  45. return json.loads(fd.read())
  46. except Exception as e:
  47. logger.error('unable to read %s: %s' % (SCHEDULES_FILE, e))
  48. return {'schedules': {}}
  49. def write_schedules(schedules):
  50. with open(SCHEDULES_FILE, 'w') as fd:
  51. fd.write(json.dumps(schedules, indent=2))
  52. def next_id(schedules):
  53. ids = schedules.get('schedules', {}).keys()
  54. if not ids:
  55. return '1'
  56. return str(max([int(i) for i in ids]) + 1)
  57. def get_schedule(id_, add_id=True):
  58. schedules = read_schedules()
  59. data = schedules.get('schedules', {}).get(id_, {})
  60. if add_id:
  61. data['id'] = str(id_)
  62. return data
  63. def select_xpath(content, xpath):
  64. fd = io.StringIO(content)
  65. tree = etree.parse(fd)
  66. elems = tree.xpath(xpath)
  67. if not elems:
  68. return content
  69. selected_content = []
  70. for elem in elems:
  71. selected_content.append(''.join([elem.text] + [ElementTree.tostring(e).decode('utf-8', 'replace')
  72. for e in elem.getchildren()]))
  73. content = ''.join(selected_content)
  74. return content
  75. def run_job(id_=None, *args, **kwargs):
  76. schedule = get_schedule(id_, add_id=False)
  77. url = schedule.get('url')
  78. if not url:
  79. return
  80. logger.debug('Running job id:%s title:%s url: %s' % (id_, schedule.get('title', ''), url))
  81. req = requests.get(url, allow_redirects=True, timeout=(30.10, 240))
  82. content = req.text
  83. xpath = schedule.get('xpath')
  84. if xpath:
  85. content = select_xpath(content, xpath)
  86. req_path = urllib.parse.urlparse(req.url).path
  87. base_name = os.path.basename(req_path) or 'index.html'
  88. def _commit(id_, filename, content, queue):
  89. os.chdir('storage/%s' % id_)
  90. current_lines = 0
  91. if os.path.isfile(filename):
  92. with open(filename, 'r') as fd:
  93. for line in fd:
  94. current_lines += 1
  95. with open(filename, 'w') as fd:
  96. fd.write(content)
  97. p = subprocess.Popen([GIT_CMD, 'add', filename])
  98. p.communicate()
  99. p = subprocess.Popen([GIT_CMD, 'commit', '-m', '%s' % datetime.datetime.utcnow(), '--allow-empty'],
  100. stdout=subprocess.PIPE)
  101. stdout, _ = p.communicate()
  102. stdout = stdout.decode('utf-8')
  103. insert = re_insertion.findall(stdout)
  104. if insert:
  105. insert = int(insert[0])
  106. else:
  107. insert = 0
  108. delete = re_deletion.findall(stdout)
  109. if delete:
  110. delete = int(delete[0])
  111. else:
  112. delete = 0
  113. queue.put({'insertions': insert, 'deletions': delete, 'previous_lines': current_lines,
  114. 'changes': max(insert, delete)})
  115. queue = multiprocessing.Queue()
  116. p = multiprocessing.Process(target=_commit, args=(id_, base_name, content, queue))
  117. p.start()
  118. res = queue.get()
  119. p.join()
  120. email = schedule.get('email')
  121. if not email:
  122. return
  123. changes = res.get('changes')
  124. if not changes:
  125. return
  126. min_change = schedule.get('minimum_change')
  127. previous_lines = res.get('previous_lines')
  128. if min_change and previous_lines:
  129. min_change = float(min_change)
  130. change_fraction = res.get('changes') / previous_lines
  131. if change_fraction < min_change:
  132. return
  133. # send notification
  134. diff = get_diff(id_).get('diff')
  135. if not diff:
  136. return
  137. send_email(to=email, subject='%s page changed' % schedule.get('title'),
  138. body='changes:\n\n%s' % diff)
  139. def safe_run_job(id_=None, *args, **kwargs):
  140. try:
  141. run_job(id_, *args, **kwargs)
  142. except Exception as e:
  143. send_email('error executing job %s: %s' % (id_, e))
  144. def send_email(to, subject='diffido', body='', from_=None):
  145. msg = MIMEText(body)
  146. msg['Subject'] = subject
  147. msg['From'] = from_ or EMAIL_FROM
  148. msg['To'] = to
  149. s = smtplib.SMTP('localhost')
  150. s.send_message(msg)
  151. s.quit()
  152. def get_history(id_):
  153. def _history(id_, queue):
  154. os.chdir('storage/%s' % id_)
  155. p = subprocess.Popen([GIT_CMD, 'log', '--pretty=oneline', '--shortstat'], stdout=subprocess.PIPE)
  156. stdout, _ = p.communicate()
  157. queue.put(stdout)
  158. queue = multiprocessing.Queue()
  159. p = multiprocessing.Process(target=_history, args=(id_, queue))
  160. p.start()
  161. res = queue.get().decode('utf-8')
  162. p.join()
  163. history = []
  164. for match in re_commit.finditer(res):
  165. info = match.groupdict()
  166. info['insertions'] = int(info['insertions'] or 0)
  167. info['deletions'] = int(info['deletions'] or 0)
  168. info['changes'] = max(info['insertions'], info['deletions'])
  169. history.append(info)
  170. lastid = None
  171. if history and 'id' in history[0]:
  172. lastid = history[0]['id']
  173. for idx, item in enumerate(history):
  174. item['seq'] = idx + 1
  175. schedule = get_schedule(id_)
  176. return {'history': history, 'lastid': lastid, 'schedule': schedule}
  177. def get_diff(id_, commit_id='HEAD', old_commit_id=None):
  178. def _history(id_, commit_id, old_commit_id, queue):
  179. os.chdir('storage/%s' % id_)
  180. p = subprocess.Popen([GIT_CMD, 'diff', old_commit_id or '%s~' % commit_id, commit_id],
  181. stdout=subprocess.PIPE)
  182. stdout, _ = p.communicate()
  183. queue.put(stdout)
  184. queue = multiprocessing.Queue()
  185. p = multiprocessing.Process(target=_history, args=(id_, commit_id, old_commit_id, queue))
  186. p.start()
  187. res = queue.get().decode('utf-8')
  188. p.join()
  189. schedule = get_schedule(id_)
  190. return {'diff': res, 'schedule': schedule}
  191. def scheduler_update(scheduler, id_):
  192. schedule = get_schedule(id_, add_id=False)
  193. if not schedule:
  194. return
  195. trigger = schedule.get('trigger')
  196. if trigger not in ('interval', 'cron'):
  197. return
  198. args = {}
  199. if trigger == 'interval':
  200. args['trigger'] = 'interval'
  201. for unit in 'weeks', 'days', 'hours', 'minutes', 'seconds':
  202. if 'interval_%s' % unit not in schedule:
  203. continue
  204. args[unit] = int(schedule['interval_%s' % unit])
  205. elif trigger == 'cron':
  206. cron_trigger = CronTrigger.from_crontab(schedule.get('cron_crontab'))
  207. args['trigger'] = cron_trigger
  208. git_create_repo(id_)
  209. scheduler.add_job(safe_run_job, id=id_, replace_existing=True, kwargs={'id_': id_}, **args)
  210. def scheduler_delete(scheduler, id_):
  211. scheduler.remove_job(job_id=id_)
  212. git_delete_repo(id_)
  213. def reset_from_schedules(scheduler):
  214. scheduler.remove_all_jobs()
  215. for key in read_schedules().get('schedules', {}).keys():
  216. scheduler_update(scheduler, id_=key)
  217. def git_create_repo(id_):
  218. repo_dir = 'storage/%s' % id_
  219. if os.path.isdir(repo_dir):
  220. return
  221. p = subprocess.Popen([GIT_CMD, 'init', repo_dir])
  222. p.communicate()
  223. def git_delete_repo(id_):
  224. repo_dir = 'storage/%s' % id_
  225. if not os.path.isdir(repo_dir):
  226. return
  227. shutil.rmtree(repo_dir)
  228. class DiffidoBaseException(Exception):
  229. """Base class for diffido custom exceptions.
  230. :param message: text message
  231. :type message: str
  232. :param status: numeric http status code
  233. :type status: int"""
  234. def __init__(self, message, status=400):
  235. super(DiffidoBaseException, self).__init__(message)
  236. self.message = message
  237. self.status = status
  238. class BaseHandler(tornado.web.RequestHandler):
  239. """Base class for request handlers."""
  240. # Cache currently connected users.
  241. _users_cache = {}
  242. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  243. document = None
  244. collection = None
  245. # A property to access the first value of each argument.
  246. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  247. for k, v in self.request.arguments.items()]))
  248. @property
  249. def clean_body(self):
  250. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  251. :returns: a clean copy of the body arguments
  252. :rtype: dict"""
  253. return escape.json_decode(self.request.body or '{}')
  254. def write_error(self, status_code, **kwargs):
  255. """Default error handler."""
  256. if isinstance(kwargs.get('exc_info', (None, None))[1], DiffidoBaseException):
  257. exc = kwargs['exc_info'][1]
  258. status_code = exc.status
  259. message = exc.message
  260. else:
  261. message = 'internal error'
  262. self.build_error(message, status=status_code)
  263. def is_api(self):
  264. """Return True if the path is from an API call."""
  265. return self.request.path.startswith('/v%s' % API_VERSION)
  266. def initialize(self, **kwargs):
  267. """Add every passed (key, value) as attributes of the instance."""
  268. for key, value in kwargs.items():
  269. setattr(self, key, value)
  270. def build_error(self, message='', status=400):
  271. """Build and write an error message.
  272. :param message: textual message
  273. :type message: str
  274. :param status: HTTP status code
  275. :type status: int
  276. """
  277. self.set_status(status)
  278. self.write({'error': True, 'message': message})
  279. def build_success(self, message='', status=200):
  280. """Build and write a success message.
  281. :param message: textual message
  282. :type message: str
  283. :param status: HTTP status code
  284. :type status: int
  285. """
  286. self.set_status(status)
  287. self.write({'error': False, 'message': message})
  288. class SchedulesHandler(BaseHandler):
  289. @gen.coroutine
  290. def get(self, id_=None, *args, **kwargs):
  291. if id_ is not None:
  292. self.write({'schedule': get_schedule(id_)})
  293. return
  294. schedules = read_schedules()
  295. self.write(schedules)
  296. @gen.coroutine
  297. def put(self, id_=None, *args, **kwargs):
  298. if id_ is None:
  299. return self.build_error(message='update action requires an ID')
  300. data = self.clean_body
  301. schedules = read_schedules()
  302. if id_ not in schedules.get('schedules', {}):
  303. return self.build_error(message='schedule %s not found' % id_)
  304. schedules['schedules'][id_] = data
  305. write_schedules(schedules)
  306. scheduler_update(scheduler=self.scheduler, id_=id_)
  307. self.write(get_schedule(id_=id_))
  308. @gen.coroutine
  309. def post(self, *args, **kwargs):
  310. data = self.clean_body
  311. schedules = read_schedules()
  312. id_ = next_id(schedules)
  313. schedules['schedules'][id_] = data
  314. write_schedules(schedules)
  315. scheduler_update(scheduler=self.scheduler, id_=id_)
  316. self.write(get_schedule(id_=id_))
  317. @gen.coroutine
  318. def delete(self, id_=None, *args, **kwargs):
  319. if id_ is None:
  320. return self.build_error(message='an ID must be specified')
  321. schedules = read_schedules()
  322. if id_ in schedules.get('schedules', {}):
  323. del schedules['schedules'][id_]
  324. write_schedules(schedules)
  325. scheduler_delete(scheduler=self.scheduler, id_=id_)
  326. self.build_success(message='removed schedule %s' % id_)
  327. class ResetSchedulesHandler(BaseHandler):
  328. @gen.coroutine
  329. def post(self, *args, **kwargs):
  330. reset_from_schedules(self.scheduler)
  331. class HistoryHandler(BaseHandler):
  332. @gen.coroutine
  333. def get(self, id_, *args, **kwargs):
  334. self.write(get_history(id_))
  335. class DiffHandler(BaseHandler):
  336. @gen.coroutine
  337. def get(self, id_, commit_id, old_commit_id=None, *args, **kwargs):
  338. self.write(get_diff(id_, commit_id, old_commit_id))
  339. class TemplateHandler(BaseHandler):
  340. """Handler for the / path."""
  341. app_path = os.path.join(os.path.dirname(__file__), "dist")
  342. @gen.coroutine
  343. def get(self, *args, **kwargs):
  344. page = 'index.html'
  345. if args and args[0]:
  346. page = args[0].strip('/')
  347. arguments = self.arguments
  348. self.render(page, **arguments)
  349. def serve():
  350. global EMAIL_FROM
  351. jobstores = {'default': SQLAlchemyJobStore(url=JOBS_STORE)}
  352. scheduler = TornadoScheduler(jobstores=jobstores)
  353. scheduler.start()
  354. define('port', default=3210, help='run on the given port', type=int)
  355. define('address', default='', help='bind the server at the given address', type=str)
  356. define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_cert.pem'),
  357. help='specify the SSL certificate to use for secure connections')
  358. define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_key.pem'),
  359. help='specify the SSL private key to use for secure connections')
  360. define('admin-email', default='', help='email address of the site administrator', type=str)
  361. define('debug', default=False, help='run in debug mode')
  362. define('config', help='read configuration file',
  363. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  364. if not options.config and os.path.isfile(DEFAULT_CONF):
  365. tornado.options.parse_config_file(DEFAULT_CONF, final=False)
  366. tornado.options.parse_command_line()
  367. if options.admin_email:
  368. EMAIL_FROM = options.admin_email
  369. if options.debug:
  370. logger.setLevel(logging.DEBUG)
  371. ssl_options = {}
  372. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  373. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  374. init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options,
  375. scheduler=scheduler)
  376. _reset_schedules_path = r'schedules/reset'
  377. _schedules_path = r'schedules/?(?P<id_>\d+)?'
  378. _history_path = r'history/?(?P<id_>\d+)'
  379. _diff_path = r'diff/(?P<id_>\d+)/(?P<commit_id>[0-9a-f]+)/?(?P<old_commit_id>[0-9a-f]+)?/?'
  380. application = tornado.web.Application([
  381. (r'/api/%s' % _reset_schedules_path, ResetSchedulesHandler, init_params),
  382. (r'/api/v%s/%s' % (API_VERSION, _reset_schedules_path), ResetSchedulesHandler, init_params),
  383. (r'/api/%s' % _schedules_path, SchedulesHandler, init_params),
  384. (r'/api/v%s/%s' % (API_VERSION, _schedules_path), SchedulesHandler, init_params),
  385. (r'/api/%s' % _history_path, HistoryHandler, init_params),
  386. (r'/api/v%s/%s' % (API_VERSION, _history_path), HistoryHandler, init_params),
  387. (r'/api/%s' % _diff_path, DiffHandler, init_params),
  388. (r'/api/v%s/%s' % (API_VERSION, _diff_path), DiffHandler, init_params),
  389. (r'/?(.*)', TemplateHandler, init_params),
  390. ],
  391. static_path=os.path.join(os.path.dirname(__file__), 'dist/static'),
  392. template_path=os.path.join(os.path.dirname(__file__), 'dist/'),
  393. debug=options.debug)
  394. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  395. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  396. options.address if options.address else '127.0.0.1',
  397. options.port)
  398. http_server.listen(options.port, options.address)
  399. try:
  400. IOLoop.instance().start()
  401. except (KeyboardInterrupt, SystemExit):
  402. pass
  403. if __name__ == '__main__':
  404. serve()