|
| 1 | +import socket |
| 2 | +import encode |
| 3 | + |
| 4 | +# RemoteCollector is a remote collector that operates over a standard, and |
| 5 | +# synchronous, Python socket. |
| 6 | +# |
| 7 | +# rc = RemoteCollector(sock=None, debug=True) |
| 8 | +# |
| 9 | +# try: |
| 10 | +# rc.connect(host="localhost", port=7701) |
| 11 | +# except Exception as e: |
| 12 | +# print "Failed to connect:", e |
| 13 | +# |
| 14 | +# try: |
| 15 | +# rc.collect(spanID, annotationOne, annotationTwo) |
| 16 | +# except Exception as e: |
| 17 | +# print "Failed to collect:", e |
| 18 | +# |
| 19 | +# rc.close() |
| 20 | +# |
| 21 | +# A custom socket for the sock parameter to RemoteCollector's allows one to |
| 22 | +# specify e.g. a TLS socket. |
| 23 | +class RemoteCollector: |
| 24 | + # sock is literally the socket that is used to communicate with the remote |
| 25 | + # collector. |
| 26 | + sock = None |
| 27 | + |
| 28 | + _debug = False |
| 29 | + |
| 30 | + def __init__(self, sock=None, debug=False): |
| 31 | + self.sock = sock |
| 32 | + self._debug = debug |
| 33 | + |
| 34 | + def _log(self, *args): |
| 35 | + if self._debug: |
| 36 | + print "appdash: %s" % (" ".join(args)) |
| 37 | + |
| 38 | + # connect connects the underlying socket to the given address, waiting at |
| 39 | + # max for the given timeout before raising an exception. |
| 40 | + def connect(self, host="localhost", port=7701, timeout=10): |
| 41 | + # Use the given socket, or create a new one. |
| 42 | + if self.sock is None: |
| 43 | + self.sock = socket.create_connection((host, port), timeout=timeout) |
| 44 | + else: |
| 45 | + self.sock.connect() |
| 46 | + |
| 47 | + # collect collects annotations for the given spanID. |
| 48 | + # |
| 49 | + # The annotations are sent to the remote server immediately, and this |
| 50 | + # function does not return until all have been sent out or an exception has |
| 51 | + # occured (e.g. disconnection). |
| 52 | + def collect(self, spanID, *annotations): |
| 53 | + self._log("collecting", str(len(annotations)), "annotations for", str(spanID)) |
| 54 | + packet = encode._collect(spanID, *annotations) |
| 55 | + buf = encode._msg(packet) |
| 56 | + |
| 57 | + totalSent = 0 |
| 58 | + while totalSent < len(buf): |
| 59 | + sent = self.sock.send(buf[totalSent:]) |
| 60 | + if sent == 0: |
| 61 | + raise RuntimeError("socket connection broken") |
| 62 | + totalSent = totalSent + sent |
| 63 | + |
| 64 | + # close closes the underlying socket. |
| 65 | + def close(self): |
| 66 | + self.sock.close() |
| 67 | + self.sock = None |
| 68 | + |
0 commit comments