|
| 1 | +from typing import Dict |
| 2 | + |
| 3 | +import time |
| 4 | +import uuid |
| 5 | + |
| 6 | +from lumigo_tracer.lumigo_utils import lumigo_safe_execute, get_logger, lumigo_dumps |
| 7 | +from lumigo_tracer.spans_container import SpansContainer |
| 8 | + |
| 9 | +try: |
| 10 | + from pymongo import monitoring |
| 11 | +except Exception: |
| 12 | + monitoring = None |
| 13 | + |
| 14 | +if not monitoring: |
| 15 | + LumigoMongoMonitoring = None |
| 16 | +else: |
| 17 | + |
| 18 | + class LumigoMongoMonitoring(monitoring.CommandListener): # type: ignore |
| 19 | + request_to_span_id: Dict[str, str] = {} |
| 20 | + MONGO_SPAN = "mongoDb" |
| 21 | + |
| 22 | + def started(self, event): |
| 23 | + with lumigo_safe_execute("pymongo started"): |
| 24 | + span_id = str(uuid.uuid4()) |
| 25 | + LumigoMongoMonitoring.request_to_span_id[event.request_id] = span_id |
| 26 | + SpansContainer.get_span().add_span( |
| 27 | + { |
| 28 | + "id": span_id, |
| 29 | + "type": self.MONGO_SPAN, |
| 30 | + "started": int(time.time() * 1000), |
| 31 | + "databaseName": event.database_name, |
| 32 | + "commandName": event.command_name, |
| 33 | + "request": lumigo_dumps(event.command), |
| 34 | + "mongoRequestId": event.request_id, |
| 35 | + "mongoOperationId": event.operation_id, |
| 36 | + "mongoConnectionId": event.connection_id, |
| 37 | + } |
| 38 | + ) |
| 39 | + |
| 40 | + def succeeded(self, event): |
| 41 | + with lumigo_safe_execute("pymongo succeed"): |
| 42 | + if event.request_id not in LumigoMongoMonitoring.request_to_span_id: |
| 43 | + get_logger().warning("Mongo span ended without a record on its start") |
| 44 | + return |
| 45 | + span_id = LumigoMongoMonitoring.request_to_span_id.pop(event.request_id) |
| 46 | + span = SpansContainer.get_span().get_span_by_id(span_id) |
| 47 | + span.update( |
| 48 | + { |
| 49 | + "ended": span["started"] + (event.duration_micros / 1000), |
| 50 | + "response": lumigo_dumps(event.reply), |
| 51 | + } |
| 52 | + ) |
| 53 | + |
| 54 | + def failed(self, event): |
| 55 | + with lumigo_safe_execute("pymongo failed"): |
| 56 | + if event.request_id not in LumigoMongoMonitoring.request_to_span_id: |
| 57 | + get_logger().warning("Mongo span ended without a record on its start") |
| 58 | + return |
| 59 | + span_id = LumigoMongoMonitoring.request_to_span_id.pop(event.request_id) |
| 60 | + span = SpansContainer.get_span().get_span_by_id(span_id) |
| 61 | + span.update( |
| 62 | + { |
| 63 | + "ended": span["started"] + (event.duration_micros / 1000), |
| 64 | + "error": lumigo_dumps(event.failure), |
| 65 | + } |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +def wrap_pymongo(): |
| 70 | + with lumigo_safe_execute("wrap pymogno"): |
| 71 | + if monitoring: |
| 72 | + get_logger().debug("wrapping pymongo") |
| 73 | + monitoring.register(LumigoMongoMonitoring()) |
0 commit comments