helpers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # Copyright 2009-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Bits and pieces used by the driver that don't really fit elsewhere."""
  15. import sys
  16. import traceback
  17. from bson.py3compat import abc, iteritems, itervalues, string_type
  18. from bson.son import SON
  19. from pymongo import ASCENDING
  20. from pymongo.errors import (CursorNotFound,
  21. DuplicateKeyError,
  22. ExecutionTimeout,
  23. NotPrimaryError,
  24. OperationFailure,
  25. WriteError,
  26. WriteConcernError,
  27. WTimeoutError)
  28. from pymongo.hello_compat import HelloCompat
  29. # From the SDAM spec, the "node is shutting down" codes.
  30. _SHUTDOWN_CODES = frozenset([
  31. 11600, # InterruptedAtShutdown
  32. 91, # ShutdownInProgress
  33. ])
  34. # From the SDAM spec, the "not primary" error codes are combined with the
  35. # "node is recovering" error codes (of which the "node is shutting down"
  36. # errors are a subset).
  37. _NOT_MASTER_CODES = frozenset([
  38. 10058, # LegacyNotPrimary <=3.2 "not primary" error code
  39. 10107, # NotWritablePrimary
  40. 13435, # NotPrimaryNoSecondaryOk
  41. 11602, # InterruptedDueToReplStateChange
  42. 13436, # NotPrimaryOrSecondary
  43. 189, # PrimarySteppedDown
  44. ]) | _SHUTDOWN_CODES
  45. # From the retryable writes spec.
  46. _RETRYABLE_ERROR_CODES = _NOT_MASTER_CODES | frozenset([
  47. 7, # HostNotFound
  48. 6, # HostUnreachable
  49. 89, # NetworkTimeout
  50. 9001, # SocketException
  51. 262, # ExceededTimeLimit
  52. ])
  53. _UUNDER = u"_"
  54. def _gen_index_name(keys):
  55. """Generate an index name from the set of fields it is over."""
  56. return _UUNDER.join(["%s_%s" % item for item in keys])
  57. def _index_list(key_or_list, direction=None):
  58. """Helper to generate a list of (key, direction) pairs.
  59. Takes such a list, or a single key, or a single key and direction.
  60. """
  61. if direction is not None:
  62. return [(key_or_list, direction)]
  63. else:
  64. if isinstance(key_or_list, string_type):
  65. return [(key_or_list, ASCENDING)]
  66. elif not isinstance(key_or_list, (list, tuple)):
  67. raise TypeError("if no direction is specified, "
  68. "key_or_list must be an instance of list")
  69. return key_or_list
  70. def _index_document(index_list):
  71. """Helper to generate an index specifying document.
  72. Takes a list of (key, direction) pairs.
  73. """
  74. if isinstance(index_list, abc.Mapping):
  75. raise TypeError("passing a dict to sort/create_index/hint is not "
  76. "allowed - use a list of tuples instead. did you "
  77. "mean %r?" % list(iteritems(index_list)))
  78. elif not isinstance(index_list, (list, tuple)):
  79. raise TypeError("must use a list of (key, direction) pairs, "
  80. "not: " + repr(index_list))
  81. if not len(index_list):
  82. raise ValueError("key_or_list must not be the empty list")
  83. index = SON()
  84. for (key, value) in index_list:
  85. if not isinstance(key, string_type):
  86. raise TypeError("first item in each key pair must be a string")
  87. if not isinstance(value, (string_type, int, abc.Mapping)):
  88. raise TypeError("second item in each key pair must be 1, -1, "
  89. "'2d', or another valid MongoDB index specifier.")
  90. index[key] = value
  91. return index
  92. def _check_command_response(response, max_wire_version,
  93. allowable_errors=None,
  94. parse_write_concern_error=False):
  95. """Check the response to a command for errors.
  96. """
  97. if "ok" not in response:
  98. # Server didn't recognize our message as a command.
  99. raise OperationFailure(response.get("$err"),
  100. response.get("code"),
  101. response,
  102. max_wire_version)
  103. if parse_write_concern_error and 'writeConcernError' in response:
  104. _error = response["writeConcernError"]
  105. _labels = response.get("errorLabels")
  106. if _labels:
  107. _error.update({'errorLabels': _labels})
  108. _raise_write_concern_error(_error)
  109. if response["ok"]:
  110. return
  111. details = response
  112. # Mongos returns the error details in a 'raw' object
  113. # for some errors.
  114. if "raw" in response:
  115. for shard in itervalues(response["raw"]):
  116. # Grab the first non-empty raw error from a shard.
  117. if shard.get("errmsg") and not shard.get("ok"):
  118. details = shard
  119. break
  120. errmsg = details["errmsg"]
  121. code = details.get("code")
  122. # For allowable errors, only check for error messages when the code is not
  123. # included.
  124. if allowable_errors:
  125. if code is not None:
  126. if code in allowable_errors:
  127. return
  128. elif errmsg in allowable_errors:
  129. return
  130. # Server is "not primary" or "recovering"
  131. if code is not None:
  132. if code in _NOT_MASTER_CODES:
  133. raise NotPrimaryError(errmsg, response)
  134. elif HelloCompat.LEGACY_ERROR in errmsg or "node is recovering" in errmsg:
  135. raise NotPrimaryError(errmsg, response)
  136. # Other errors
  137. # findAndModify with upsert can raise duplicate key error
  138. if code in (11000, 11001, 12582):
  139. raise DuplicateKeyError(errmsg, code, response, max_wire_version)
  140. elif code == 50:
  141. raise ExecutionTimeout(errmsg, code, response, max_wire_version)
  142. elif code == 43:
  143. raise CursorNotFound(errmsg, code, response, max_wire_version)
  144. raise OperationFailure(errmsg, code, response, max_wire_version)
  145. def _check_gle_response(result, max_wire_version):
  146. """Return getlasterror response as a dict, or raise OperationFailure."""
  147. # Did getlasterror itself fail?
  148. _check_command_response(result, max_wire_version)
  149. if result.get("wtimeout", False):
  150. # MongoDB versions before 1.8.0 return the error message in an "errmsg"
  151. # field. If "errmsg" exists "err" will also exist set to None, so we
  152. # have to check for "errmsg" first.
  153. raise WTimeoutError(result.get("errmsg", result.get("err")),
  154. result.get("code"),
  155. result)
  156. error_msg = result.get("err", "")
  157. if error_msg is None:
  158. return result
  159. if error_msg.startswith(HelloCompat.LEGACY_ERROR):
  160. raise NotPrimaryError(error_msg, result)
  161. details = result
  162. # mongos returns the error code in an error object for some errors.
  163. if "errObjects" in result:
  164. for errobj in result["errObjects"]:
  165. if errobj.get("err") == error_msg:
  166. details = errobj
  167. break
  168. code = details.get("code")
  169. if code in (11000, 11001, 12582):
  170. raise DuplicateKeyError(details["err"], code, result)
  171. raise OperationFailure(details["err"], code, result)
  172. def _raise_last_write_error(write_errors):
  173. # If the last batch had multiple errors only report
  174. # the last error to emulate continue_on_error.
  175. error = write_errors[-1]
  176. if error.get("code") == 11000:
  177. raise DuplicateKeyError(error.get("errmsg"), 11000, error)
  178. raise WriteError(error.get("errmsg"), error.get("code"), error)
  179. def _raise_write_concern_error(error):
  180. if "errInfo" in error and error["errInfo"].get('wtimeout'):
  181. # Make sure we raise WTimeoutError
  182. raise WTimeoutError(
  183. error.get("errmsg"), error.get("code"), error)
  184. raise WriteConcernError(
  185. error.get("errmsg"), error.get("code"), error)
  186. def _check_write_command_response(result):
  187. """Backward compatibility helper for write command error handling.
  188. """
  189. # Prefer write errors over write concern errors
  190. write_errors = result.get("writeErrors")
  191. if write_errors:
  192. _raise_last_write_error(write_errors)
  193. error = result.get("writeConcernError")
  194. if error:
  195. error_labels = result.get("errorLabels")
  196. if error_labels:
  197. error.update({'errorLabels': error_labels})
  198. _raise_write_concern_error(error)
  199. def _raise_last_error(bulk_write_result):
  200. """Backward compatibility helper for insert error handling.
  201. """
  202. # Prefer write errors over write concern errors
  203. write_errors = bulk_write_result.get("writeErrors")
  204. if write_errors:
  205. _raise_last_write_error(write_errors)
  206. _raise_write_concern_error(bulk_write_result["writeConcernErrors"][-1])
  207. def _fields_list_to_dict(fields, option_name):
  208. """Takes a sequence of field names and returns a matching dictionary.
  209. ["a", "b"] becomes {"a": 1, "b": 1}
  210. and
  211. ["a.b.c", "d", "a.c"] becomes {"a.b.c": 1, "d": 1, "a.c": 1}
  212. """
  213. if isinstance(fields, abc.Mapping):
  214. return fields
  215. if isinstance(fields, (abc.Sequence, abc.Set)):
  216. if not all(isinstance(field, string_type) for field in fields):
  217. raise TypeError("%s must be a list of key names, each an "
  218. "instance of %s" % (option_name,
  219. string_type.__name__))
  220. return dict.fromkeys(fields, 1)
  221. raise TypeError("%s must be a mapping or "
  222. "list of key names" % (option_name,))
  223. def _handle_exception():
  224. """Print exceptions raised by subscribers to stderr."""
  225. # Heavily influenced by logging.Handler.handleError.
  226. # See note here:
  227. # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
  228. if sys.stderr:
  229. einfo = sys.exc_info()
  230. try:
  231. traceback.print_exception(einfo[0], einfo[1], einfo[2],
  232. None, sys.stderr)
  233. except IOError:
  234. pass
  235. finally:
  236. del einfo