diffido.py 16 KB

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