2
0

tunasync.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env python2
  2. # -*- coding:utf-8 -*-
  3. import os
  4. import argparse
  5. import json
  6. from datetime import datetime
  7. from tunasync import TUNASync
  8. from tunasync.hook import JobHook
  9. class IndexPageHook(JobHook):
  10. def __init__(self, parent, dbfile):
  11. self.parent = parent
  12. self.dbfile = dbfile
  13. @property
  14. def mirrors(self):
  15. mirrors = {}
  16. try:
  17. with open(self.dbfile) as f:
  18. _mirrors = json.load(f)
  19. for m in _mirrors:
  20. mirrors[m["name"]] = m
  21. except:
  22. for name, _ in self.parent.mirrors.iteritems():
  23. mirrors[name] = {
  24. 'name': name,
  25. 'last_update': '-',
  26. 'status': 'unknown',
  27. }
  28. return mirrors
  29. def before_job(self, name=None, *args, **kwargs):
  30. if name is None:
  31. return
  32. mirrors = self.mirrors
  33. _m = mirrors.get(name, {
  34. 'name': name,
  35. 'last_update': '-',
  36. 'status': '-',
  37. })
  38. mirrors[name] = {
  39. 'name': name,
  40. 'last_update': _m['last_update'],
  41. 'status': 'syncing'
  42. }
  43. with open(self.dbfile, 'wb') as f:
  44. _mirrors = sorted(
  45. [m for _, m in mirrors.items()],
  46. key=lambda x: x['name']
  47. )
  48. json.dump(_mirrors, f)
  49. def after_job(self, name=None, status="unknown", *args, **kwargs):
  50. if name is None:
  51. return
  52. print("Updating tunasync.json")
  53. now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  54. mirrors = self.mirrors
  55. mirrors[name] = {
  56. 'name': name,
  57. 'last_update': now,
  58. 'status': status
  59. }
  60. with open(self.dbfile, 'wb') as f:
  61. _mirrors = sorted(
  62. [m for _, m in mirrors.items()],
  63. key=lambda x: x['name']
  64. )
  65. json.dump(_mirrors, f)
  66. if __name__ == "__main__":
  67. here = os.path.abspath(os.path.dirname(__file__))
  68. parser = argparse.ArgumentParser(prog="tunasync")
  69. parser.add_argument("-c", "--config",
  70. default="tunasync.ini", help="config file")
  71. parser.add_argument("--dbfile",
  72. default="tunasync.json",
  73. help="mirror status db file")
  74. parser.add_argument("--pidfile", default="/var/run/tunasync.pid",
  75. help="pidfile")
  76. args = parser.parse_args()
  77. with open(args.pidfile, 'w') as f:
  78. f.write("{}".format(os.getpid()))
  79. tunaSync = TUNASync()
  80. tunaSync.read_config(args.config)
  81. index_hook = IndexPageHook(tunaSync, args.dbfile)
  82. tunaSync.add_hook(index_hook)
  83. tunaSync.run_jobs()
  84. # vim: ts=4 sw=4 sts=4 expandtab