__init__.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # Copyright (C) 2018 Garmin Ltd.
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License version 2 as
  5. # published by the Free Software Foundation.
  6. #
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License along
  13. # with this program; if not, write to the Free Software Foundation, Inc.,
  14. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. from http.server import BaseHTTPRequestHandler, HTTPServer
  16. import contextlib
  17. import urllib.parse
  18. import sqlite3
  19. import json
  20. import traceback
  21. import logging
  22. from datetime import datetime
  23. logger = logging.getLogger('hashserv')
  24. class HashEquivalenceServer(BaseHTTPRequestHandler):
  25. def log_message(self, f, *args):
  26. logger.debug(f, *args)
  27. def do_GET(self):
  28. try:
  29. p = urllib.parse.urlparse(self.path)
  30. if p.path != self.prefix + '/v1/equivalent':
  31. self.send_error(404)
  32. return
  33. query = urllib.parse.parse_qs(p.query, strict_parsing=True)
  34. method = query['method'][0]
  35. taskhash = query['taskhash'][0]
  36. d = None
  37. with contextlib.closing(self.db.cursor()) as cursor:
  38. cursor.execute('SELECT taskhash, method, unihash FROM tasks_v1 WHERE method=:method AND taskhash=:taskhash ORDER BY created ASC LIMIT 1',
  39. {'method': method, 'taskhash': taskhash})
  40. row = cursor.fetchone()
  41. if row is not None:
  42. logger.debug('Found equivalent task %s', row['taskhash'])
  43. d = {k: row[k] for k in ('taskhash', 'method', 'unihash')}
  44. self.send_response(200)
  45. self.send_header('Content-Type', 'application/json; charset=utf-8')
  46. self.end_headers()
  47. self.wfile.write(json.dumps(d).encode('utf-8'))
  48. except:
  49. logger.exception('Error in GET')
  50. self.send_error(400, explain=traceback.format_exc())
  51. return
  52. def do_POST(self):
  53. try:
  54. p = urllib.parse.urlparse(self.path)
  55. if p.path != self.prefix + '/v1/equivalent':
  56. self.send_error(404)
  57. return
  58. length = int(self.headers['content-length'])
  59. data = json.loads(self.rfile.read(length).decode('utf-8'))
  60. with contextlib.closing(self.db.cursor()) as cursor:
  61. cursor.execute('''
  62. SELECT taskhash, method, unihash FROM tasks_v1 WHERE method=:method AND outhash=:outhash
  63. ORDER BY CASE WHEN taskhash=:taskhash THEN 1 ELSE 2 END,
  64. created ASC
  65. LIMIT 1
  66. ''', {k: data[k] for k in ('method', 'outhash', 'taskhash')})
  67. row = cursor.fetchone()
  68. if row is None or row['taskhash'] != data['taskhash']:
  69. unihash = data['unihash']
  70. if row is not None:
  71. unihash = row['unihash']
  72. insert_data = {
  73. 'method': data['method'],
  74. 'outhash': data['outhash'],
  75. 'taskhash': data['taskhash'],
  76. 'unihash': unihash,
  77. 'created': datetime.now()
  78. }
  79. for k in ('owner', 'PN', 'PV', 'PR', 'task', 'outhash_siginfo'):
  80. if k in data:
  81. insert_data[k] = data[k]
  82. cursor.execute('''INSERT INTO tasks_v1 (%s) VALUES (%s)''' % (
  83. ', '.join(sorted(insert_data.keys())),
  84. ', '.join(':' + k for k in sorted(insert_data.keys()))),
  85. insert_data)
  86. logger.info('Adding taskhash %s with unihash %s', data['taskhash'], unihash)
  87. cursor.execute('SELECT taskhash, method, unihash FROM tasks_v1 WHERE id=:id', {'id': cursor.lastrowid})
  88. row = cursor.fetchone()
  89. self.db.commit()
  90. d = {k: row[k] for k in ('taskhash', 'method', 'unihash')}
  91. self.send_response(200)
  92. self.send_header('Content-Type', 'application/json; charset=utf-8')
  93. self.end_headers()
  94. self.wfile.write(json.dumps(d).encode('utf-8'))
  95. except:
  96. logger.exception('Error in POST')
  97. self.send_error(400, explain=traceback.format_exc())
  98. return
  99. def create_server(addr, db, prefix=''):
  100. class Handler(HashEquivalenceServer):
  101. pass
  102. Handler.prefix = prefix
  103. Handler.db = db
  104. db.row_factory = sqlite3.Row
  105. with contextlib.closing(db.cursor()) as cursor:
  106. cursor.execute('''
  107. CREATE TABLE IF NOT EXISTS tasks_v1 (
  108. id INTEGER PRIMARY KEY AUTOINCREMENT,
  109. method TEXT NOT NULL,
  110. outhash TEXT NOT NULL,
  111. taskhash TEXT NOT NULL,
  112. unihash TEXT NOT NULL,
  113. created DATETIME,
  114. -- Optional fields
  115. owner TEXT,
  116. PN TEXT,
  117. PV TEXT,
  118. PR TEXT,
  119. task TEXT,
  120. outhash_siginfo TEXT
  121. )
  122. ''')
  123. logger.info('Starting server on %s', addr)
  124. return HTTPServer(addr, Handler)