__init__.py 5.6 KB

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