| 1 |
import os |
| 2 |
import socket |
| 3 |
import logging |
| 4 |
|
| 5 |
from ..exceptions.exceptions import InvalidDaemonAddressException |
| 6 |
|
| 7 |
log = logging.getLogger(__name__) |
| 8 |
|
| 9 |
|
| 10 |
PROTOCOL_HEADER = "{\"format\": \"json\", \"version\": 1}" |
| 11 |
PROTOCOL_DELIMITER = '\n' |
| 12 |
DAEMON_ADDRESS_KEY = "AWS_XRAY_DAEMON_ADDRESS" |
| 13 |
|
| 14 |
|
| 15 |
class UDPEmitter(object): |
| 16 |
""" |
| 17 |
The default emitter the X-Ray recorder uses to send segments/subsegments |
| 18 |
to the X-Ray daemon over UDP using a non-blocking socket. If there is an |
| 19 |
exception on the actual data transfer between the socket and the daemon, |
| 20 |
it logs the exception and continue. |
| 21 |
""" |
| 22 |
def __init__(self, daemon_address='127.0.0.1:2000'): |
| 23 |
|
| 24 |
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 25 |
self._socket.setblocking(0) |
| 26 |
address = os.getenv(DAEMON_ADDRESS_KEY, daemon_address) |
| 27 |
self._ip, self._port = self._parse_address(address) |
| 28 |
|
| 29 |
def send_entity(self, entity): |
| 30 |
""" |
| 31 |
Serializes a segment/subsegment and sends it to the X-Ray daemon |
| 32 |
over UDP. By default it doesn't retry on failures. |
| 33 |
|
| 34 |
:param entity: a trace entity to send to the X-Ray daemon |
| 35 |
""" |
| 36 |
message = "%s%s%s" % (PROTOCOL_HEADER, |
| 37 |
PROTOCOL_DELIMITER, |
| 38 |
entity.serialize()) |
| 39 |
|
| 40 |
log.debug("sending: %s to %s:%s." % (message, self._ip, self._port)) |
| 41 |
self._send_data(message) |
| 42 |
|
| 43 |
def set_daemon_address(self, address): |
| 44 |
""" |
| 45 |
Takes a full address like 127.0.0.1:2000 and parses it into ip address |
| 46 |
and port. Throws an exception if the address has invalid format. |
| 47 |
""" |
| 48 |
if address: |
| 49 |
self._ip, self._port = self._parse_address(address) |
| 50 |
|
| 51 |
def _send_data(self, data): |
| 52 |
|
| 53 |
try: |
| 54 |
self._socket.sendto(data.encode('utf-8'), (self._ip, |
| 55 |
self._port)) |
| 56 |
except Exception: |
| 57 |
log.exception('failed to send data to X-Ray daemon.') |
| 58 |
|
| 59 |
def _parse_address(self, daemon_address): |
| 60 |
try: |
| 61 |
val = daemon_address.split(':') |
| 62 |
return val[0], int(val[1]) |
| 63 |
except Exception: |
| 64 |
raise InvalidDaemonAddressException('Invalid daemon address %s specified.' % daemon_address) |