diffido.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. logger.warn('MEHHHH %s %s %s' % (id_, commit_id, old_commit_id))
  191. def _history(id_, commit_id, old_commit_id, queue):
  192. os.chdir('storage/%s' % id_)
  193. p = subprocess.Popen([GIT_CMD, 'diff', old_commit_id or '%s~' % commit_id, commit_id],
  194. stdout=subprocess.PIPE)
  195. stdout, _ = p.communicate()
  196. queue.put(stdout)
  197. queue = multiprocessing.Queue()
  198. p = multiprocessing.Process(target=_history, args=(id_, commit_id, old_commit_id, queue))
  199. p.start()
  200. res = queue.get().decode('utf-8')
  201. p.join()
  202. return {'diff': res}
  203. def scheduler_update(scheduler, id_):
  204. schedule = get_schedule(id_, add_id=False)
  205. if not schedule:
  206. return
  207. trigger = schedule.get('trigger')
  208. if trigger not in ('interval', 'cron'):
  209. return
  210. args = {}
  211. if trigger == 'interval':
  212. args['trigger'] = 'interval'
  213. for unit in 'weeks', 'days', 'hours', 'minutes', 'seconds':
  214. if 'interval_%s' % unit not in schedule:
  215. continue
  216. args[unit] = int(schedule['interval_%s' % unit])
  217. elif trigger == 'cron':
  218. cron_trigger = CronTrigger.from_crontab(schedule.get('cron_crontab'))
  219. args['trigger'] = cron_trigger
  220. git_create_repo(id_)
  221. scheduler.add_job(safe_run_job, id=id_, replace_existing=True, kwargs={'id_': id_}, **args)
  222. def scheduler_delete(scheduler, id_):
  223. scheduler.remove_job(job_id=id_)
  224. git_delete_repo(id_)
  225. def reset_from_schedules(scheduler):
  226. scheduler.remove_all_jobs()
  227. for key in read_schedules().get('schedules', {}).keys():
  228. scheduler_update(scheduler, id_=key)
  229. def git_create_repo(id_):
  230. repo_dir = 'storage/%s' % id_
  231. if os.path.isdir(repo_dir):
  232. return
  233. p = subprocess.Popen([GIT_CMD, 'init', repo_dir])
  234. p.communicate()
  235. def git_delete_repo(id_):
  236. repo_dir = 'storage/%s' % id_
  237. if not os.path.isdir(repo_dir):
  238. return
  239. shutil.rmtree(repo_dir)
  240. class DiffidoBaseException(Exception):
  241. """Base class for diffido custom exceptions.
  242. :param message: text message
  243. :type message: str
  244. :param status: numeric http status code
  245. :type status: int"""
  246. def __init__(self, message, status=400):
  247. super(DiffidoBaseException, self).__init__(message)
  248. self.message = message
  249. self.status = status
  250. class BaseHandler(tornado.web.RequestHandler):
  251. """Base class for request handlers."""
  252. # Cache currently connected users.
  253. _users_cache = {}
  254. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  255. document = None
  256. collection = None
  257. # A property to access the first value of each argument.
  258. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  259. for k, v in self.request.arguments.items()]))
  260. @property
  261. def clean_body(self):
  262. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  263. :returns: a clean copy of the body arguments
  264. :rtype: dict"""
  265. return escape.json_decode(self.request.body or '{}')
  266. def write_error(self, status_code, **kwargs):
  267. """Default error handler."""
  268. if isinstance(kwargs.get('exc_info', (None, None))[1], DiffidoBaseException):
  269. exc = kwargs['exc_info'][1]
  270. status_code = exc.status
  271. message = exc.message
  272. else:
  273. message = 'internal error'
  274. self.build_error(message, status=status_code)
  275. def is_api(self):
  276. """Return True if the path is from an API call."""
  277. return self.request.path.startswith('/v%s' % API_VERSION)
  278. def initialize(self, **kwargs):
  279. """Add every passed (key, value) as attributes of the instance."""
  280. for key, value in kwargs.items():
  281. setattr(self, key, value)
  282. def build_error(self, message='', status=400):
  283. """Build and write an error message.
  284. :param message: textual message
  285. :type message: str
  286. :param status: HTTP status code
  287. :type status: int
  288. """
  289. self.set_status(status)
  290. self.write({'error': True, 'message': message})
  291. def build_success(self, message='', status=200):
  292. """Build and write a success message.
  293. :param message: textual message
  294. :type message: str
  295. :param status: HTTP status code
  296. :type status: int
  297. """
  298. self.set_status(status)
  299. self.write({'error': False, 'message': message})
  300. class SchedulesHandler(BaseHandler):
  301. @gen.coroutine
  302. def get(self, id_=None, *args, **kwargs):
  303. if id_ is not None:
  304. self.write({'schedule': get_schedule(id_)})
  305. return
  306. schedules = read_schedules()
  307. self.write(schedules)
  308. @gen.coroutine
  309. def put(self, id_=None, *args, **kwargs):
  310. if id_ is None:
  311. return self.build_error(message='update action requires an ID')
  312. data = self.clean_body
  313. schedules = read_schedules()
  314. if id_ not in schedules.get('schedules', {}):
  315. return self.build_error(message='schedule %s not found' % id_)
  316. schedules['schedules'][id_] = data
  317. write_schedules(schedules)
  318. scheduler_update(scheduler=self.scheduler, id_=id_)
  319. self.write(get_schedule(id_=id_))
  320. @gen.coroutine
  321. def post(self, *args, **kwargs):
  322. data = self.clean_body
  323. schedules = read_schedules()
  324. id_ = next_id(schedules)
  325. schedules['schedules'][id_] = data
  326. write_schedules(schedules)
  327. scheduler_update(scheduler=self.scheduler, id_=id_)
  328. self.write(get_schedule(id_=id_))
  329. @gen.coroutine
  330. def delete(self, id_=None, *args, **kwargs):
  331. if id_ is None:
  332. return self.build_error(message='an ID must be specified')
  333. schedules = read_schedules()
  334. if id_ in schedules.get('schedules', {}):
  335. del schedules['schedules'][id_]
  336. write_schedules(schedules)
  337. scheduler_delete(scheduler=self.scheduler, id_=id_)
  338. self.build_success(message='removed schedule %s' % id_)
  339. class ResetSchedulesHandler(BaseHandler):
  340. @gen.coroutine
  341. def post(self, *args, **kwargs):
  342. reset_from_schedules(self.scheduler)
  343. class HistoryHandler(BaseHandler):
  344. @gen.coroutine
  345. def get(self, id_, *args, **kwargs):
  346. self.write(get_history(id_))
  347. class DiffHandler(BaseHandler):
  348. @gen.coroutine
  349. def get(self, id_, commit_id, old_commit_id=None, *args, **kwargs):
  350. self.write(get_diff(id_, commit_id, old_commit_id))
  351. class TemplateHandler(BaseHandler):
  352. """Handler for the / path."""
  353. app_path = os.path.join(os.path.dirname(__file__), "dist")
  354. @gen.coroutine
  355. def get(self, *args, **kwargs):
  356. page = 'index.html'
  357. if args and args[0]:
  358. page = args[0].strip('/')
  359. arguments = self.arguments
  360. self.render(page, **arguments)
  361. def serve():
  362. global EMAIL_FROM
  363. jobstores = {'default': SQLAlchemyJobStore(url=JOBS_STORE)}
  364. scheduler = TornadoScheduler(jobstores=jobstores)
  365. scheduler.start()
  366. define('port', default=3210, help='run on the given port', type=int)
  367. define('address', default='', help='bind the server at the given address', type=str)
  368. define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_cert.pem'),
  369. help='specify the SSL certificate to use for secure connections')
  370. define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_key.pem'),
  371. help='specify the SSL private key to use for secure connections')
  372. define('admin-email', default='', help='email address of the site administrator', type=str)
  373. define('debug', default=False, help='run in debug mode')
  374. define('config', help='read configuration file',
  375. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  376. if not options.config and os.path.isfile(DEFAULT_CONF):
  377. tornado.options.parse_config_file(DEFAULT_CONF, final=False)
  378. tornado.options.parse_command_line()
  379. if options.admin_email:
  380. EMAIL_FROM = options.admin_email
  381. if options.debug:
  382. logger.setLevel(logging.DEBUG)
  383. ssl_options = {}
  384. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  385. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  386. init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options,
  387. scheduler=scheduler)
  388. _reset_schedules_path = r'schedules/reset'
  389. _schedules_path = r'schedules/?(?P<id_>\d+)?'
  390. _history_path = r'history/?(?P<id_>\d+)'
  391. _diff_path = r'diff/(?P<id_>\d+)/(?P<commit_id>[0-9a-f]+)/?(?P<old_commit_id>[0-9a-f]+)?/?'
  392. application = tornado.web.Application([
  393. (r'/api/%s' % _reset_schedules_path, ResetSchedulesHandler, init_params),
  394. (r'/api/v%s/%s' % (API_VERSION, _reset_schedules_path), ResetSchedulesHandler, init_params),
  395. (r'/api/%s' % _schedules_path, SchedulesHandler, init_params),
  396. (r'/api/v%s/%s' % (API_VERSION, _schedules_path), SchedulesHandler, init_params),
  397. (r'/api/%s' % _history_path, HistoryHandler, init_params),
  398. (r'/api/v%s/%s' % (API_VERSION, _history_path), HistoryHandler, init_params),
  399. (r'/api/%s' % _diff_path, DiffHandler, init_params),
  400. (r'/api/v%s/%s' % (API_VERSION, _diff_path), DiffHandler, init_params),
  401. (r'/?(.*)', TemplateHandler, init_params),
  402. ],
  403. static_path=os.path.join(os.path.dirname(__file__), 'dist/static'),
  404. template_path=os.path.join(os.path.dirname(__file__), 'dist/'),
  405. debug=options.debug)
  406. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  407. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  408. options.address if options.address else '127.0.0.1',
  409. options.port)
  410. http_server.listen(options.port, options.address)
  411. try:
  412. IOLoop.instance().start()
  413. except (KeyboardInterrupt, SystemExit):
  414. pass
  415. if __name__ == '__main__':
  416. serve()