customhandlers.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. #!/usr/bin/env python
  2. # Copyright 2010 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Handle special HTTP requests.
  16. /web-page-replay-generate-[RESPONSE_CODE]
  17. - Return the given RESPONSE_CODE.
  18. /web-page-replay-post-image-[FILENAME]
  19. - Save the posted image to local disk.
  20. /web-page-replay-command-[record|replay|status]
  21. - Optional. Enable by calling custom_handlers.add_server_manager_handler(...).
  22. - Change the server mode to either record or replay.
  23. + When switching to record, the http_archive is cleared.
  24. + When switching to replay, the http_archive is maintained.
  25. """
  26. import base64
  27. import httparchive
  28. import json
  29. import logging
  30. import os
  31. COMMON_URL_PREFIX = '/web-page-replay-'
  32. COMMAND_URL_PREFIX = COMMON_URL_PREFIX + 'command-'
  33. GENERATOR_URL_PREFIX = COMMON_URL_PREFIX + 'generate-'
  34. POST_IMAGE_URL_PREFIX = COMMON_URL_PREFIX + 'post-image-'
  35. IMAGE_DATA_PREFIX = 'data:image/png;base64,'
  36. def SimpleResponse(status):
  37. """Return a ArchivedHttpResponse with |status| code and a simple text body."""
  38. return httparchive.create_response(status)
  39. def JsonResponse(data):
  40. """Return a ArchivedHttpResponse with |data| encoded as json in the body."""
  41. status = 200
  42. reason = 'OK'
  43. headers = [('content-type', 'application/json')]
  44. body = json.dumps(data)
  45. return httparchive.create_response(status, reason, headers, body)
  46. class CustomHandlers(object):
  47. def __init__(self, options, http_archive):
  48. """Initialize CustomHandlers.
  49. Args:
  50. options: original options passed to the server.
  51. http_archive: reference to the HttpArchive object.
  52. """
  53. self.server_manager = None
  54. self.options = options
  55. self.http_archive = http_archive
  56. self.handlers = [
  57. (GENERATOR_URL_PREFIX, self.get_generator_url_response_code)]
  58. # screenshot_dir is a path to which screenshots are saved.
  59. if options.screenshot_dir:
  60. if not os.path.exists(options.screenshot_dir):
  61. try:
  62. os.makedirs(options.screenshot_dir)
  63. except IOError:
  64. logging.error('Unable to create screenshot dir: %s',
  65. options.screenshot_dir)
  66. options.screenshot_dir = None
  67. if options.screenshot_dir:
  68. self.screenshot_dir = options.screenshot_dir
  69. self.handlers.append(
  70. (POST_IMAGE_URL_PREFIX, self.handle_possible_post_image))
  71. def handle(self, request):
  72. """Dispatches requests to matching handlers.
  73. Args:
  74. request: an http request
  75. Returns:
  76. ArchivedHttpResponse or None.
  77. """
  78. for prefix, handler in self.handlers:
  79. if request.full_path.startswith(prefix):
  80. return handler(request, request.full_path[len(prefix):])
  81. return None
  82. def get_generator_url_response_code(self, request, url_suffix):
  83. """Parse special generator URLs for the embedded response code.
  84. Args:
  85. request: an ArchivedHttpRequest instance
  86. url_suffix: string that is after the handler prefix (e.g. 304)
  87. Returns:
  88. On a match, an ArchivedHttpResponse.
  89. Otherwise, None.
  90. """
  91. del request
  92. try:
  93. response_code = int(url_suffix)
  94. return SimpleResponse(response_code)
  95. except ValueError:
  96. return None
  97. def handle_possible_post_image(self, request, url_suffix):
  98. """If sent, saves embedded image to local directory.
  99. Expects a special url containing the filename. If sent, saves the base64
  100. encoded request body as a PNG image locally. This feature is enabled by
  101. passing in screenshot_dir to the initializer for this class.
  102. Args:
  103. request: an ArchivedHttpRequest instance
  104. url_suffix: string that is after the handler prefix (e.g. 'foo.png')
  105. Returns:
  106. On a match, an ArchivedHttpResponse.
  107. Otherwise, None.
  108. """
  109. basename = url_suffix
  110. if not basename:
  111. return None
  112. data = request.request_body
  113. if not data.startswith(IMAGE_DATA_PREFIX):
  114. logging.error('Unexpected image format for: %s', basename)
  115. return SimpleResponse(400)
  116. data = data[len(IMAGE_DATA_PREFIX):]
  117. png = base64.b64decode(data)
  118. filename = os.path.join(self.screenshot_dir,
  119. '%s-%s.png' % (request.host, basename))
  120. if not os.access(self.screenshot_dir, os.W_OK):
  121. logging.error('Unable to write to: %s', filename)
  122. return SimpleResponse(400)
  123. with file(filename, 'w') as f:
  124. f.write(png)
  125. return SimpleResponse(200)
  126. def add_server_manager_handler(self, server_manager):
  127. """Add the ability to change the server mode (e.g. to record mode).
  128. Args:
  129. server_manager: a servermanager.ServerManager instance.
  130. """
  131. self.server_manager = server_manager
  132. self.handlers.append(
  133. (COMMAND_URL_PREFIX, self.handle_server_manager_command))
  134. def handle_server_manager_command(self, request, url_suffix):
  135. """Parse special URLs for the embedded server manager command.
  136. Clients like webpagetest.org can use URLs of this form to change
  137. the replay server from record mode to replay mode.
  138. This handler is not in the default list of handlers. Call
  139. add_server_manager_handler to add it.
  140. In the future, this could be expanded to save or serve archive files.
  141. Args:
  142. request: an ArchivedHttpRequest instance
  143. url_suffix: string that is after the handler prefix (e.g. 'record')
  144. Returns:
  145. On a match, an ArchivedHttpResponse.
  146. Otherwise, None.
  147. """
  148. command = url_suffix
  149. if command == 'record':
  150. self.server_manager.SetRecordMode()
  151. return SimpleResponse(200)
  152. elif command == 'replay':
  153. self.server_manager.SetReplayMode()
  154. return SimpleResponse(200)
  155. elif command == 'status':
  156. status = {}
  157. is_record_mode = self.server_manager.IsRecordMode()
  158. status['is_record_mode'] = is_record_mode
  159. status['options'] = json.loads(str(self.options))
  160. archive_stats = self.http_archive.stats()
  161. if archive_stats:
  162. status['archive_stats'] = json.loads(archive_stats)
  163. return JsonResponse(status)
  164. elif command == 'exit':
  165. self.server_manager.should_exit = True
  166. return SimpleResponse(200)
  167. elif command == 'log':
  168. logging.info('log command: %s', str(request.request_body)[:1000000])
  169. return SimpleResponse(200)
  170. return None