code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self._running.isSet(): raise RuntimeError('Server already started') self._stopped.clear() # Make sure we have an ioloop self.ioloop = self._ioloop_manager.get_ioloop() self._ioloop_manager.start() # Set max_buffer_size to ensure streams are closed # if too-large messages are received self._tcp_server = tornado.tcpserver.TCPServer( self.ioloop, max_buffer_size=self.MAX_MSG_SIZE) self._tcp_server.handle_stream = self._handle_stream self._server_sock = self._bind_socket(self._bindaddr) self._bindaddr = self._server_sock.getsockname() self.ioloop.add_callback(self._install) if timeout: return self._running.wait(timeout)
def start(self, timeout=None)
Install the server on its IOLoop, optionally starting the IOLoop. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start.
4.004569
3.938884
1.016676
if timeout: self._running.wait(timeout) return self._ioloop_manager.stop(callback=self._uninstall)
def stop(self, timeout=1.0)
Stop a running server (from another thread). Parameters ---------- timeout : float or None, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when the server is stopped
13.940943
19.264957
0.723643
t0 = time.time() self._ioloop_manager.join(timeout=timeout) if timeout: self._stopped.wait(timeout - (time.time() - t0))
def join(self, timeout=None)
Rejoin the server thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for the thread to finish. Notes ----- If the ioloop is not managed, this function will block until the server port is closed, meaning a new server can be started on the same port.
4.808753
4.343122
1.107211
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: sock.bind(bindaddr) except Exception: self._logger.exception("Unable to bind to %s" % str(bindaddr)) raise sock.listen(self.BACKLOG) return sock
def _bind_socket(self, bindaddr)
Create a listening server socket.
1.839201
1.777684
1.034605
try: assert get_thread_ident() == self.ioloop_thread_id stream.set_close_callback(partial(self._stream_closed_callback, stream)) # Our message packets are small, don't delay sending them. stream.set_nodelay(True) stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE # Abuse IOStream object slightly by adding 'address' and 'closing' # attributes. Use nasty prefix to prevent naming collisions. stream.KATCPServer_address = address # Flag to indicate that no more write should be accepted so that # we can flush the write buffer when closing a connection stream.KATCPServer_closing = False client_conn = self.client_connection_factory(self, stream) self._connections[stream] = client_conn try: yield gen.maybe_future(self._device.on_client_connect(client_conn)) except Exception: # If on_client_connect fails there is no reason to continue # trying to handle this connection. Try and send exception info # to the client and disconnect e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, e_value, trace, self._tb_limit)) log_msg = 'Device error initialising connection {0}'.format(reason) self._logger.error(log_msg) stream.write(str(Message.inform('log', log_msg))) stream.close(exc_info=True) else: self._line_read_loop(stream, client_conn) except Exception: self._logger.error('Unhandled exception trying ' 'to handle new connection', exc_info=True)
def _handle_stream(self, stream, address)
Handle a new connection as a tornado.iostream.IOStream instance.
5.46162
5.18365
1.053624
try: addr = ":".join(str(part) for part in stream.KATCPServer_address) except AttributeError: # Something weird happened, but keep trucking addr = '<error>' self._logger.warn('Could not determine address of stream', exc_info=True) return addr
def get_address(self, stream)
Text representation of the network address of a connection stream. Notes ----- This method is thread-safe
7.804595
8.702982
0.896773
assert get_thread_ident() == self.ioloop_thread_id try: if stream.KATCPServer_closing: raise RuntimeError('Stream is closing so we cannot ' 'accept any more writes') return stream.write(str(msg) + '\n') except Exception: addr = self.get_address(stream) self._logger.warn('Could not send message {0!r} to {1}' .format(str(msg), addr), exc_info=True) stream.close(exc_info=True)
def send_message(self, stream, msg)
Send an arbitrary message to a particular client. Parameters ---------- stream : :class:`tornado.iostream.IOStream` object The stream to send the message to. msg : Message object The message to send. Notes ----- This method can only be called in the IOLoop thread. Failed sends disconnect the client connection and calls the device on_client_disconnect() method. They do not raise exceptions, but they are logged. Sends also fail if more than self.MAX_WRITE_BUFFER_SIZE bytes are queued for sending, implying that client is falling behind.
5.173233
4.968102
1.04129
assert get_thread_ident() == self.ioloop_thread_id # Prevent futher writes stream.KATCPServer_closing = True # Write empty message to get future that resolves when buffer is flushed return stream.write('\n')
def flush_on_close(self, stream)
Flush tornado iostream write buffer and prevent further writes. Returns a future that resolves when the stream is flushed.
17.895041
14.171791
1.262723
if self.in_ioloop_thread(): f = tornado_Future() try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception('Error executing callback ' 'in ioloop thread') finally: return f else: f = Future() try: f.set_running_or_notify_cancel() def send_message_callback(): try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception( 'Error executing wrapped async callback') self.ioloop.add_callback(send_message_callback) finally: return f
def call_from_thread(self, fn)
Allow thread-safe calls to ioloop functions. Uses add_callback if not in the IOLoop thread, otherwise calls directly. Returns an already resolved `tornado.concurrent.Future` if in ioloop, otherwise a `concurrent.Future`. Logs unhandled exceptions. Resolves with an exception if one occurred.
2.977577
2.752476
1.081781
return self.call_from_thread(partial(self.send_message, stream, msg))
def send_message_from_thread(self, stream, msg)
Thread-safe version of send_message() returning a Future instance. Returns ------- A Future that will resolve without raising an exception as soon as the call to send_message() completes. This does not guarantee that the message has been delivered yet. If the call to send_message() failed, the exception will be logged, and the future will resolve with the exception raised. Since a failed call to send_message() will result in the connection being closed, no real error handling apart from logging will be possible. Notes ----- This method is thread-safe. If called from within the ioloop, send_message is called directly and a resolved tornado.concurrent.Future is returned, otherwise a callback is submitted to the ioloop that will resolve a thread-safe concurrent.futures.Future instance.
6.147115
6.356363
0.967081
for stream in self._connections.keys(): if not stream.closed(): # Don't cause noise by trying to write to already closed streams self.send_message(stream, msg)
def mass_send_message(self, msg)
Send a message to all connected clients. Notes ----- This method can only be called in the IOLoop thread.
10.004985
11.041759
0.906104
self._post_reply() return self.client_connection.reply(rep_msg, self.msg)
def reply_with_message(self, rep_msg)
Send a pre-created reply message to the client connection. Will check that rep_msg.name matches the bound request.
10.697809
11.006649
0.971941
MAX_QUEUE_SIZE = 30 if len(self._msg_queue) >= MAX_QUEUE_SIZE: # This should never happen if callers to handle_message wait # for its futures to resolve before sending another message. # NM 2014-10-06: Except when there are multiple clients. Oops. raise RuntimeError('MessageHandlerThread unhandled ' 'message queue full, not handling message') ready_future = Future() self._msg_queue.append((ready_future, client_conn, msg)) self._wake.set() return ready_future
def on_message(self, client_conn, msg)
Handle message. Returns ------- ready : Future A future that will resolve once we're ready, else None. Notes ----- *on_message* should not be called again until *ready* has resolved.
7.743297
6.85083
1.130271
if timeout: self._running.wait(timeout) self._running.clear() # Make sure to wake the run thread. self._wake.set()
def stop(self, timeout=1.0)
Stop the handler thread (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*.
6.947333
8.494022
0.817908
if timestamp is None: timestamp = time.time() katcp_version = self.PROTOCOL_INFO.major timestamp_msg = ('%.6f' % timestamp if katcp_version >= SEC_TS_KATCP_MAJOR else str(int(timestamp*1000))) return Message.inform("log", level_name, timestamp_msg, name, msg)
def create_log_inform(self, level_name, msg, name, timestamp=None)
Create a katcp logging inform message. Usually this will be called from inside a DeviceLogger object, but it is also used by the methods in this class when errors need to be reported to the client.
6.000714
5.134584
1.168685
# log messages received so that no one else has to self._logger.debug('received: {0!s}'.format(msg)) if msg.mtype == msg.REQUEST: return self.handle_request(client_conn, msg) elif msg.mtype == msg.INFORM: return self.handle_inform(client_conn, msg) elif msg.mtype == msg.REPLY: return self.handle_reply(client_conn, msg) else: reason = "Unexpected message type received by server ['%s']." \ % (msg,) client_conn.inform(self.create_log_inform("error", reason, "root"))
def handle_message(self, client_conn, msg)
Handle messages of all types from clients. Parameters ---------- client_conn : ClientConnection object The client connection the message was from. msg : Message object The message to process.
4.33124
4.481918
0.966381
send_reply = True # TODO Should check presence of Message-ids against protocol flags and # raise an error as needed. if msg.name in self._request_handlers: req_conn = ClientRequestConnection(connection, msg) handler = self._request_handlers[msg.name] try: reply = handler(self, req_conn, msg) # If we get a future, assume this is an async message handler # that will resolve the future with the reply message when it # is complete. Attach a message-sending callback to the future, # and return the future. if gen.is_future(reply): concurrent = getattr(handler, '_concurrent_reply', False) concurrent_str = ' CONCURRENT' if concurrent else '' done_future = Future() def async_reply(f): try: connection.reply(f.result(), msg) self._logger.debug("%s FUTURE%s replied", msg.name, concurrent_str) except FailReply, e: reason = str(e) self._logger.error("Request %s FUTURE%s FAIL: %s", msg.name, concurrent_str, reason) reply = Message.reply(msg.name, "fail", reason) connection.reply(reply, msg) except AsyncReply: self._logger.debug("%s FUTURE ASYNC OK" % (msg.name,)) except Exception: error_reply = self.create_exception_reply_and_log( msg, sys.exc_info()) connection.reply(error_reply, msg) finally: done_future.set_result(None) # TODO When using the return_reply() decorator the future # returned is not currently threadsafe, must either deal # with it here, or in kattypes.py. Would be nice if we don't # have to always fall back to adding a callback, or wrapping # a thread-safe future. Supporting sync-with-thread and # async futures is turning out to be a pain in the ass ;) self.ioloop.add_callback(reply.add_done_callback, async_reply) # reply.add_done_callback(async_reply) if concurrent: # Return immediately if this is a concurrent handler self._logger.debug("%s FUTURE CONCURRENT OK", msg.name) return else: self._logger.debug("%s FUTURE OK", msg.name) return done_future else: assert (reply.mtype == Message.REPLY) assert (reply.name == msg.name) self._logger.debug("%s OK" % (msg.name,)) except AsyncReply, e: self._logger.debug("%s ASYNC OK" % (msg.name,)) send_reply = False except FailReply, e: reason = str(e) self._logger.error("Request %s FAIL: %s" % (msg.name, reason)) reply = Message.reply(msg.name, "fail", reason) except Exception: reply = self.create_exception_reply_and_log(msg, sys.exc_info()) else: self._logger.error("%s INVALID: Unknown request." % (msg.name,)) reply = Message.reply(msg.name, "invalid", "Unknown request.") if send_reply: connection.reply(reply, msg)
def handle_request(self, connection, msg)
Dispatch a request message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The request message to process. Returns ------- done_future : Future or None Returns Future for async request handlers that will resolve when done, or None for sync request handlers once they have completed.
3.824829
3.819279
1.001453
if msg.name in self._inform_handlers: try: self._inform_handlers[msg.name](self, connection, msg) except Exception: e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, e_value, trace, self._tb_limit)) self._logger.error("Inform %s FAIL: %s" % (msg.name, reason)) else: self._logger.warn("%s INVALID: Unknown inform." % (msg.name,))
def handle_inform(self, connection, msg)
Dispatch an inform message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The inform message to process.
3.004303
3.157322
0.951535
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.inform() ' 'within a reply handler context -- use req.inform()\n' 'Traceback:\n %s', "".join(traceback.format_stack())) # Get the underlying ClientConnection instance connection = connection.client_connection connection.inform(msg)
def inform(self, connection, msg)
Send an inform message to a particular client. Should only be used for asynchronous informs. Informs that are part of the response to a request should use :meth:`reply_inform` so that the message identifier from the original request can be attached to the inform. Parameters ---------- connection : ClientConnection object The client to send the message to. msg : Message object The inform message to send.
9.044866
10.469774
0.863903
assert (msg.mtype == Message.INFORM) self._server.mass_send_message_from_thread(msg)
def mass_inform(self, msg)
Send an inform message to all clients. Parameters ---------- msg : Message object The inform message to send.
12.171134
11.50798
1.057626
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.reply() ' 'within a reply handler context -- use req.reply(*msg_args)\n' 'or req.reply_with_message(msg) Traceback:\n %s', "".join(traceback.format_stack())) # Get the underlying ClientConnection instance connection = connection.client_connection connection.reply(reply, orig_req)
def reply(self, connection, reply, orig_req)
Send an asynchronous reply to an earlier request. Parameters ---------- connection : ClientConnection object The client to send the reply to. reply : Message object The reply message to send. orig_req : Message object The request message being replied to. The reply message's id is overridden with the id from orig_req before the reply is sent.
8.896186
9.318684
0.954661
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.reply_inform() ' 'within a reply handler context -- ' 'use req.inform(*inform_arguments)\n' 'Traceback:\n %s', "".join(traceback.format_stack())) # Get the underlying ClientConnection instance connection = connection.client_connection connection.reply_inform(inform, orig_req)
def reply_inform(self, connection, inform, orig_req)
Send an inform as part of the reply to an earlier request. Parameters ---------- connection : ClientConnection object The client to send the inform to. inform : Message object The inform message to send. orig_req : Message object The request message being replied to. The inform message's id is overridden with the id from orig_req before the inform is sent.
7.922741
8.879687
0.892232
self._server.set_ioloop(ioloop) self.ioloop = self._server.ioloop
def set_ioloop(self, ioloop=None)
Set the tornado IOLoop to use. Sets the tornado.ioloop.IOLoop instance to use, defaulting to IOLoop.current(). If set_ioloop() is never called the IOLoop is started in a new thread, and will be stopped if self.stop() is called. Notes ----- Must be called before start() is called.
3.669021
5.464564
0.671421
if handler_thread: assert thread_safe, "handler_thread=True requires thread_safe=True" self._server.client_connection_factory = ( ThreadsafeClientConnection if thread_safe else ClientConnection) if handler_thread: self._handler_thread = MessageHandlerThread( self.handle_message, self.create_log_inform, self._logger) self.on_message = self._handler_thread.on_message else: self.on_message = return_future(self.handle_message) self._handler_thread = None self._concurrency_options = ObjectDict( thread_safe=thread_safe, handler_thread=handler_thread)
def set_concurrency_options(self, thread_safe=True, handler_thread=True)
Set concurrency options for this device server. Must be called before :meth:`start`. Parameters ========== thread_safe : bool If True, make the server public methods thread safe. Incurs performance overhead. handler_thread : bool Can only be set if `thread_safe` is True. Handle all requests (even from different clients) in a separate, single, request-handling thread. Blocking request handlers will prevent the server from handling new requests from any client, but sensor strategies should still function. This more or less mimics the behaviour of a server in library versions before 0.6.0.
3.829481
3.843066
0.996465
if self._handler_thread and self._handler_thread.isAlive(): raise RuntimeError('Message handler thread already started') self._server.start(timeout) self.ioloop = self._server.ioloop if self._handler_thread: self._handler_thread.set_ioloop(self.ioloop) self._handler_thread.start(timeout)
def start(self, timeout=None)
Start the server in a new thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start.
3.427036
3.619171
0.946912
self._server.join(timeout) if self._handler_thread: self._handler_thread.join(timeout)
def join(self, timeout=None)
Rejoin the server thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for the thread to finish.
4.28218
5.527572
0.774695
stopped = self._server.stop(timeout) if self._handler_thread: self._handler_thread.stop(timeout) return stopped
def stop(self, timeout=1.0)
Stop a running server (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when the server is stopped
5.397964
8.034067
0.671884
in_ioloop = self._server.in_ioloop_thread() if in_ioloop: f = tornado_Future() else: f = Future() def cb(): f.set_result(None) self.ioloop.add_callback(cb) if in_ioloop: return f else: f.result(timeout)
def sync_with_ioloop(self, timeout=None)
Block for ioloop to complete a loop if called from another thread. Returns a future if called from inside the ioloop. Raises concurrent.futures.TimeoutError if timed out while blocking.
3.495775
3.160616
1.106042
assert get_thread_ident() == self._server.ioloop_thread_id self._client_conns.add(client_conn) self._strategies[client_conn] = {} # map sensors -> sampling strategies katcp_version = self.PROTOCOL_INFO.major if katcp_version >= VERSION_CONNECT_KATCP_MAJOR: client_conn.inform(Message.inform( "version-connect", "katcp-protocol", self.PROTOCOL_INFO)) client_conn.inform(Message.inform( "version-connect", "katcp-library", "katcp-python-%s" % katcp.__version__)) client_conn.inform(Message.inform( "version-connect", "katcp-device", self.version(), self.build_state())) else: client_conn.inform(Message.inform("version", self.version())) client_conn.inform(Message.inform("build-state", self.build_state()))
def on_client_connect(self, client_conn)
Inform client of build state and version on connect. Parameters ---------- client_conn : ClientConnection object The client connection that has been successfully established. Returns ------- Future that resolves when the device is ready to accept messages.
4.137208
4.056453
1.019908
assert get_thread_ident() == self._server.ioloop_thread_id getter = (self._strategies.pop if remove_client else self._strategies.get) strategies = getter(client_conn, None) if strategies is not None: for sensor, strategy in list(strategies.items()): strategy.cancel() del strategies[sensor]
def clear_strategies(self, client_conn, remove_client=False)
Clear the sensor strategies of a client connection. Parameters ---------- client_connection : ClientConnection instance The connection that should have its sampling strategies cleared remove_client : bool, optional Remove the client connection from the strategies datastructure. Useful for clients that disconnect.
4.778389
5.288047
0.903621
f = tornado_Future() @gen.coroutine def remove_strategies(): self.clear_strategies(client_conn, remove_client=True) if connection_valid: client_conn.inform(Message.inform("disconnect", msg)) yield client_conn.flush_on_close() try: self._client_conns.remove(client_conn) self.ioloop.add_callback(lambda: chain_future(remove_strategies(), f)) except Exception: f.set_exc_info(sys.exc_info()) return f
def on_client_disconnect(self, client_conn, msg, connection_valid)
Inform client it is about to be disconnected. Parameters ---------- client_conn : ClientConnection object The client connection being disconnected. msg : str Reason client is being disconnected. connection_valid : bool True if connection is still open for sending, False otherwise. Returns ------- Future that resolves when the client connection can be closed.
5.106388
5.387456
0.947829
if isinstance(sensor, basestring): sensor_name = sensor else: sensor_name = sensor.name sensor = self._sensors.pop(sensor_name) def cancel_sensor_strategies(): for conn_strategies in self._strategies.values(): strategy = conn_strategies.pop(sensor, None) if strategy: strategy.cancel() self.ioloop.add_callback(cancel_sensor_strategies)
def remove_sensor(self, sensor)
Remove a sensor from the device. Also deregisters all clients observing the sensor. Parameters ---------- sensor : Sensor object or name string The sensor to remove from the device server.
3.191213
3.204421
0.995878
sensor = self._sensors.get(sensor_name, None) if not sensor: raise ValueError("Unknown sensor '%s'." % (sensor_name,)) return sensor
def get_sensor(self, sensor_name)
Fetch the sensor with the given name. Parameters ---------- sensor_name : str Name of the sensor to retrieve. Returns ------- sensor : Sensor object The sensor with the given name.
2.873545
3.568744
0.805198
f = Future() @gen.coroutine def _halt(): req.reply("ok") yield gen.moment self.stop(timeout=None) raise AsyncReply self.ioloop.add_callback(lambda: chain_future(_halt(), f)) return f
def request_halt(self, req, msg)
Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok
6.434451
10.1601
0.633306
if not msg.arguments: for name, method in sorted(self._request_handlers.items()): doc = method.__doc__ req.inform(name, doc) num_methods = len(self._request_handlers) return req.make_reply("ok", str(num_methods)) else: name = msg.arguments[0] if name in self._request_handlers: method = self._request_handlers[name] doc = method.__doc__.strip() req.inform(name, doc) return req.make_reply("ok", "1") return req.make_reply("fail", "Unknown request method.")
def request_help(self, req, msg)
Return help on the available requests. Return a description of the available requests using a sequence of #help informs. Parameters ---------- request : str, optional The name of the request to return help for (the default is to return help for all requests). Informs ------- request : str The name of a request. description : str Documentation for the named request. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #help inform messages sent. Examples -------- :: ?help #help halt ...description... #help help ...description... ... !help ok 5 ?help halt #help halt ...description... !help ok 1
2.786138
2.934538
0.94943
timeout_hints = {} if request: if request not in self._request_handlers: raise FailReply('Unknown request method') timeout_hint = getattr( self._request_handlers[request], 'request_timeout_hint', None) timeout_hint = timeout_hint or 0 timeout_hints[request] = timeout_hint else: for request_, handler in self._request_handlers.items(): timeout_hint = getattr(handler, 'request_timeout_hint', None) if timeout_hint: timeout_hints[request_] = timeout_hint cnt = len(timeout_hints) for request_name, timeout_hint in sorted(timeout_hints.items()): req.inform(request_name, float(timeout_hint)) return ('ok', cnt)
def request_request_timeout_hint(self, req, request)
Return timeout hints for requests KATCP requests should generally take less than 5s to complete, but some requests are unavoidably slow. This results in spurious client timeout errors. This request provides timeout hints that clients can use to select suitable request timeouts. Parameters ---------- request : str, optional The name of the request to return a timeout hint for (the default is to return hints for all requests that have timeout hints). Returns one inform per request. Must be an existing request if specified. Informs ------- request : str The name of the request. suggested_timeout : float Suggested request timeout in seconds for the request. If `suggested_timeout` is zero (0), no timeout hint is available. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #request-timeout-hint inform messages sent. Examples -------- :: ?request-timeout-hint #request-timeout-hint halt 5 #request-timeout-hint very-slow-request 500 ... !request-timeout-hint ok 5 ?request-timeout-hint moderately-slow-request #request-timeout-hint moderately-slow-request 20 !request-timeout-hint ok 1 Notes ----- ?request-timeout-hint without a parameter will only return informs for requests that have specific timeout hints, so it will most probably be a subset of all the requests, or even no informs at all.
2.94232
2.779836
1.058451
if msg.arguments: try: self.log.set_log_level_by_name(msg.arguments[0]) except ValueError, e: raise FailReply(str(e)) return req.make_reply("ok", self.log.level_name())
def request_log_level(self, req, msg)
Query or set the current logging level. Parameters ---------- level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'}, optional Name of the logging level to set the device server to (the default is to leave the log level unchanged). Returns ------- success : {'ok', 'fail'} Whether the request succeeded. level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'} The log level after processing the request. Examples -------- :: ?log-level !log-level ok warn ?log-level info !log-level ok info
4.178781
6.536681
0.639282
if self._restart_queue is None: raise FailReply("No restart queue registered -- cannot restart.") f = tornado_Future() @gen.coroutine def _restart(): # .put should never block because queue should have no size limit self._restart_queue.put_nowait(self) req.reply('ok') raise AsyncReply self.ioloop.add_callback(lambda: chain_future(_restart(), f)) return f
def request_restart(self, req, msg)
Restart the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the restart succeeded. Examples -------- :: ?restart !restart ok
8.193758
9.433309
0.868599
# TODO Get list of ClientConnection* instances and implement a standard # 'address-print' method in the ClientConnection class clients = self._client_conns num_clients = len(clients) for conn in clients: addr = conn.address req.inform(addr) return req.make_reply('ok', str(num_clients))
def request_client_list(self, req, msg)
Request the list of connected clients. The list of clients is sent as a sequence of #client-list informs. Informs ------- addr : str The address of the client as host:port with host in dotted quad notation. If the address of the client could not be determined (because, for example, the client disconnected suddenly) then a unique string representing the client is sent instead. Returns ------- success : {'ok', 'fail'} Whether sending the client list succeeded. informs : int Number of #client-list inform messages sent. Examples -------- :: ?client-list #client-list 127.0.0.1:53600 !client-list ok 1
11.138019
11.032243
1.009588
versions = [ ("katcp-protocol", (self.PROTOCOL_INFO, None)), ("katcp-library", ("katcp-python-%s" % katcp.__version__, katcp.__version__)), ("katcp-device", (self.version(), self.build_state())), ] extra_versions = sorted(self.extra_versions.items()) for name, (version, build_state) in versions + extra_versions: if build_state is None: inform_args = (name, version) else: inform_args = (name, version, build_state) req.inform(*inform_args) num_versions = len(versions) + len(extra_versions) return req.make_reply("ok", str(num_versions))
def request_version_list(self, req, msg)
Request the list of versions of roles and subcomponents. Informs ------- name : str Name of the role or component. version : str A string identifying the version of the component. Individual components may define the structure of this argument as they choose. In the absence of other information clients should treat it as an opaque string. build_state_or_serial_number : str A unique identifier for a particular instance of a component. This should change whenever the component is replaced or updated. Returns ------- success : {'ok', 'fail'} Whether sending the version list succeeded. informs : int Number of #version-list inform messages sent. Examples -------- :: ?version-list #version-list katcp-protocol 5.0-MI #version-list katcp-library katcp-python-0.4 katcp-python-0.4.1-py2 #version-list katcp-device foodevice-1.0 foodevice-1.0.0rc1 !version-list ok 3
3.77189
3.244578
1.162521
exact, name_filter = construct_name_filter(msg.arguments[0] if msg.arguments else None) sensors = [(name, sensor) for name, sensor in sorted(self._sensors.iteritems()) if name_filter(name)] if exact and not sensors: return req.make_reply("fail", "Unknown sensor name.") self._send_sensor_value_informs(req, sensors) return req.make_reply("ok", str(len(sensors)))
def request_sensor_list(self, req, msg)
Request the list of sensors. The list of sensors is sent as a sequence of #sensor-list informs. Parameters ---------- name : str, optional Name of the sensor to list (the default is to list all sensors). If name starts and ends with '/' it is treated as a regular expression and all sensors whose names contain the regular expression are returned. Informs ------- name : str The name of the sensor being described. description : str Description of the named sensor. units : str Units for the value of the named sensor. type : str Type of the named sensor. params : list of str, optional Additional sensor parameters (type dependent). For integer and float sensors the additional parameters are the minimum and maximum sensor value. For discrete sensors the additional parameters are the allowed values. For all other types no additional parameters are sent. Returns ------- success : {'ok', 'fail'} Whether sending the sensor list succeeded. informs : int Number of #sensor-list inform messages sent. Examples -------- :: ?sensor-list #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.status CPU\_status. \@ discrete on off error ... !sensor-list ok 5 ?sensor-list cpu.power.on #sensor-list cpu.power.on Whether\_CPU\_hase\_power. \@ boolean !sensor-list ok 1 ?sensor-list /voltage/ #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.voltage CPU\_voltage. V float 0.0 3.0 !sensor-list ok 2
5.142578
5.981907
0.859689
exact, name_filter = construct_name_filter(msg.arguments[0] if msg.arguments else None) sensors = [(name, sensor) for name, sensor in sorted(self._sensors.iteritems()) if name_filter(name)] if exact and not sensors: return req.make_reply("fail", "Unknown sensor name.") katcp_version = self.PROTOCOL_INFO.major for name, sensor in sensors: timestamp, status, value = sensor.read_formatted(katcp_version) req.inform(timestamp, "1", name, status, value) return req.make_reply("ok", str(len(sensors)))
def request_sensor_value(self, req, msg)
Request the value of a sensor or sensors. A list of sensor values as a sequence of #sensor-value informs. Parameters ---------- name : str, optional Name of the sensor to poll (the default is to send values for all sensors). If name starts and ends with '/' it is treated as a regular expression and all sensors whose names contain the regular expression are returned. Informs ------- timestamp : float Timestamp of the sensor reading in seconds since the Unix epoch, or milliseconds for katcp versions <= 4. count : {1} Number of sensors described in this #sensor-value inform. Will always be one. It exists to keep this inform compatible with #sensor-status. name : str Name of the sensor whose value is being reported. value : object Value of the named sensor. Type depends on the type of the sensor. Returns ------- success : {'ok', 'fail'} Whether sending the list of values succeeded. informs : int Number of #sensor-value inform messages sent. Examples -------- :: ?sensor-value #sensor-value 1244631611.415231 1 psu.voltage 4.5 #sensor-value 1244631611.415200 1 cpu.status off ... !sensor-value ok 5 ?sensor-value cpu.power.on #sensor-value 1244631611.415231 1 cpu.power.on 0 !sensor-value ok 1
5.796928
5.443717
1.064884
f = Future() self.ioloop.add_callback(lambda: chain_future( self._handle_sensor_sampling(req, msg), f)) return f
def request_sensor_sampling(self, req, msg)
Configure or query the way a sensor is sampled. Sampled values are reported asynchronously using the #sensor-status message. Parameters ---------- name : str Name of the sensor whose sampling strategy to query or configure. strategy : {'none', 'auto', 'event', 'differential', \ 'period', 'event-rate'}, optional Type of strategy to use to report the sensor value. The differential strategy type may only be used with integer or float sensors. If this parameter is supplied, it sets the new strategy. params : list of str, optional Additional strategy parameters (dependent on the strategy type). For the differential strategy, the parameter is an integer or float giving the amount by which the sensor value may change before an updated value is sent. For the period strategy, the parameter is the sampling period in float seconds. The event strategy has no parameters. Note that this has changed from KATCPv4. For the event-rate strategy, a minimum period between updates and a maximum period between updates (both in float seconds) must be given. If the event occurs more than once within the minimum period, only one update will occur. Whether or not the event occurs, the sensor value will be updated at least once per maximum period. The differential-rate strategy is not supported in this release. Returns ------- success : {'ok', 'fail'} Whether the sensor-sampling request succeeded. name : str Name of the sensor queried or configured. strategy : {'none', 'auto', 'event', 'differential', 'period'} Name of the new or current sampling strategy for the sensor. params : list of str Additional strategy parameters (see description under Parameters). Examples -------- :: ?sensor-sampling cpu.power.on !sensor-sampling ok cpu.power.on none ?sensor-sampling cpu.power.on period 500 !sensor-sampling ok cpu.power.on period 500
5.960324
9.098228
0.655108
f = Future() @gen.coroutine def _clear_strategies(): self.clear_strategies(req.client_connection) raise gen.Return(('ok',)) self.ioloop.add_callback(lambda: chain_future(_clear_strategies(), f)) return f
def request_sensor_sampling_clear(self, req)
Set all sampling strategies for this client to none. Returns ------- success : {'ok', 'fail'} Whether sending the list of devices succeeded. Examples -------- ?sensor-sampling-clear !sensor-sampling-clear ok
6.427301
6.943955
0.925597
if level is None: level = self._log_level return self.LEVELS[level]
def level_name(self, level=None)
Return the name of the given level value. If level is None, return the name of the current level. Parameters ---------- level : logging level constant The logging level constant whose name to retrieve. Returns ------- level_name : str The name of the logging level.
4.987421
7.12368
0.700119
try: return self.LEVELS.index(level_name) except ValueError: raise ValueError("Unknown logging level name '%s'" % (level_name,))
def level_from_name(self, level_name)
Return the level constant for a given name. If the *level_name* is not known, raise a ValueError. Parameters ---------- level_name : str The logging level name whose logging level constant to retrieve. Returns ------- level : logging level constant The logging level constant associated with the name.
3.259042
3.264159
0.998432
self._log_level = level if self._python_logger: try: level = self.PYTHON_LEVEL.get(level) except ValueError as err: raise FailReply("Unknown logging level '%s'" % (level)) self._python_logger.setLevel(level)
def set_log_level(self, level)
Set the logging level. Parameters ---------- level : logging level constant The value to set the logging level to.
4.312311
5.045228
0.854731
timestamp = kwargs.get("timestamp") python_msg = msg if self._python_logger is not None: if timestamp is not None: python_msg = ' '.join(( 'katcp timestamp: %r' % timestamp, python_msg)) self._python_logger.log(self.PYTHON_LEVEL[level], python_msg, *args) if level >= self._log_level: name = kwargs.get("name") if name is None: name = self._root_logger_name try: inform_msg = msg % args except TypeError: # Catch the "not enough arguments for format string" exception. inform_msg = "{} {}".format( msg, args if args else '').strip() self._device_server.mass_inform( self._device_server.create_log_inform( self.level_name(level), inform_msg, name, timestamp=timestamp))
def log(self, level, msg, *args, **kwargs)
Log a message and inform all clients. Parameters ---------- level : logging level constant The level to log the message at. msg : str The text format for the log message. args : list of objects Arguments to pass to log format string. Final message text is created using: msg % args. kwargs : additional keyword parameters Allowed keywords are 'name' and 'timestamp'. The name is the name of the logger to log the message to. If not given the name defaults to the root logger. The timestamp is a float in seconds. If not given the timestamp defaults to the current time.
4.394011
4.318128
1.017573
self.log(self.WARN, msg, *args, **kwargs)
def warn(self, msg, *args, **kwargs)
Log an warning message.
4.275635
3.425704
1.248104
(level, timestamp, name, message) = tuple(msg.arguments) log_string = "%s %s: %s" % (timestamp, name, message) logger.log({"trace": 0, "debug": logging.DEBUG, "info": logging.INFO, "warn": logging.WARN, "error": logging.ERROR, "fatal": logging.FATAL}[level], log_string)
def log_to_python(cls, logger, msg)
Log a KATCP logging message to a Python logger. Parameters ---------- logger : logging.Logger object The Python logger to log the given message to. msg : Message object The #log message to create a log entry from.
3.263774
3.405979
0.958248
return katcp.Message.reply(msg.name, "ok", *msg.arguments)
def request_echo(self, sock, msg)
Echo the arguments of the message sent.
13.254381
11.35734
1.167032
def log_cb(self, f): try: f.result() except Exception: self._logger.exception('Unhandled exception calling coroutine {0!r}' .format(coro)) @wraps(coro) def wrapped_coro(self, *args, **kwargs): try: f = coro(self, *args, **kwargs) except Exception: f = tornado_Future() f.set_exc_info(sys.exc_info()) f.add_done_callback(partial(log_cb, self)) return f return wrapped_coro
def log_coroutine_exceptions(coro)
Coroutine (or any method that returns a future) decorator to log exceptions Example ------- :: import logging class A(object): _logger = logging.getLogger(__name__) @log_coroutine_exceptions @tornado.gen.coroutine def raiser(self, arg): yield tornado.gen.moment raise Exception(arg) Assuming that your object (self) has a `_logger` attribute containing a logger instance
2.520434
2.774678
0.90837
def log_cb(f): try: f.result() except ignore: pass except Exception: logger.exception('Unhandled exception returned by future') f.add_done_callback(log_cb)
def log_future_exceptions(logger, f, ignore=())
Log any exceptions set to a future Parameters ---------- logger : logging.Logger instance logger.exception(...) is called if the future resolves with an exception f : Future object Future to be monitored for exceptions ignore : Exception or tuple of Exception Exptected exception(s) to ignore, i.e. they will not be logged. Notes ----- This is useful when an async task is started for its side effects without waiting for the result. The problem is that if the future's resolution is not checked for exceptions, unhandled exceptions in the async task will be silently ignored.
3.480247
4.622572
0.752881
def deco(fn): docs = [obj.__doc__] if fn.__doc__: docs.append(fn.__doc__) fn.__doc__ = '\n\n'.join(docs) return fn return deco
def steal_docstring_from(obj)
Decorator that lets you steal a docstring from another object Example ------- :: @steal_docstring_from(superclass.meth) def meth(self, arg): "Extra subclass documentation" pass In this case the docstring of the new 'meth' will be copied from superclass.meth, and if an additional dosctring was defined for meth it will be appended to the superclass docstring with a two newlines inbetween.
3.068873
3.981827
0.77072
if hasattr(obj, '__func__'): return (id(obj.__func__), id(obj.__self__)) elif hasattr(obj, 'im_func'): return (id(obj.im_func), id(obj.im_self)) elif isinstance(obj, (basestring, unicode)): return obj else: return id(obj)
def hashable_identity(obj)
Generate a hashable ID that is stable for methods etc Approach borrowed from blinker. Why it matters: see e.g. http://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object
2.107383
1.919684
1.097776
timeout = kwargs.get('timeout', None) ioloop = kwargs.get('ioloop', None) or tornado.ioloop.IOLoop.current() any_future = tornado_Future() def handle_done(done_future): if not any_future.done(): try: any_future.set_result(done_future.result()) except Exception: any_future.set_exc_info(done_future.exc_info()) # (NM) Nasty hack to remove handle_done from the callback list to prevent a # memory leak where one of the futures resolves quickly, particularly when # used together with AsyncState.until_state(). Also addresses Jira issue # CM-593 for f in futures: if f._callbacks: try: f._callbacks.remove(handle_done) except ValueError: pass for f in futures: f.add_done_callback(handle_done) if any_future.done(): break if timeout: return with_timeout(ioloop.time() + timeout, any_future, ioloop) else: return any_future
def until_any(*futures, **kwargs)
Return a future that resolves when any of the passed futures resolves. Resolves with the value yielded by the first future to resolve. Note, this will only work with tornado futures.
4.196856
4.203612
0.998393
ioloop = ioloop or tornado.ioloop.IOLoop.current() t0 = ioloop.time() def _remaining(): return timeout - (ioloop.time() - t0) if timeout else None def maybe_timeout(f): if not timeout: return f else: remaining = _remaining() deadline = ioloop.time() + remaining return with_timeout(deadline, f, ioloop) maybe_timeout.remaining = _remaining return maybe_timeout
def future_timeout_manager(timeout=None, ioloop=None)
Create Helper function for yielding with a cumulative timeout if required Keeps track of time over multiple timeout calls so that a single timeout can be placed over multiple operations. Parameters ---------- timeout : int or None Timeout, or None for no timeout ioloop : IOLoop instance or None tornado IOloop instance to use, or None for IOLoop.current() Return value ------------ maybe_timeout : func Accepts a future, and wraps it in :func:tornado.gen.with_timeout. maybe_timeout raises :class:`tornado.gen.TimeoutError` if the timeout expires Has a function attribute `remaining()` that returns the remaining timeout or None if timeout == None Example ------- :: @tornado.gen.coroutine def multi_op(timeout): maybe_timeout = future_timeout_manager(timeout) result1 = yield maybe_timeout(op1()) result2 = yield maybe_timeout(op2()) # If the cumulative time of op1 and op2 exceeds timeout, # :class:`tornado.gen.TimeoutError` is raised
3.148532
3.718982
0.846611
done_at_least = kwargs.pop('done_at_least', None) timeout = kwargs.pop('timeout', None) # At this point args and kwargs are either empty or contain futures only if done_at_least is None: done_at_least = len(args) + len(kwargs) wait_iterator = tornado.gen.WaitIterator(*args, **kwargs) maybe_timeout = future_timeout_manager(timeout) results = [] while not wait_iterator.done(): result = yield maybe_timeout(wait_iterator.next()) results.append((wait_iterator.current_index, result)) if len(results) >= done_at_least: break raise tornado.gen.Return(results)
def until_some(*args, **kwargs)
Return a future that resolves when some of the passed futures resolve. The futures can be passed as either a sequence of *args* or a dict of *kwargs* (but not both). Some additional keyword arguments are supported, as described below. Once a specified number of underlying futures have resolved, the returned future resolves as well, or a timeout could be raised if specified. Parameters ---------- done_at_least : None or int Number of futures that need to resolve before this resolves or None to wait for all (default None) timeout : None or float Timeout in seconds, or None for no timeout (the default) Returns ------- This command returns a tornado Future that resolves with a list of (index, value) tuples containing the results of all futures that resolved, with corresponding indices (numbers for *args* futures or keys for *kwargs* futures). Raises ------ :class:`tornado.gen.TimeoutError` If operation times out before the requisite number of futures resolve
3.157699
2.817256
1.120842
if isinstance(arg, float): return repr(arg) elif isinstance(arg, bool): return str(int(arg)) else: try: return str(arg) except UnicodeEncodeError: # unicode characters will break the str cast, so # try to encode to ascii and replace the offending characters # with a '?' character logger.error("Error casting message argument to str! " "Trying to encode argument to ascii.") if not isinstance(arg, unicode): arg = arg.decode('utf-8') return arg.encode('ascii', 'replace')
def format_argument(self, arg)
Format a Message argument to a string
4.398006
4.244457
1.036176
return (self.mtype == self.REPLY and self.arguments and self.arguments[0] == self.OK)
def reply_ok(self)
Return True if this is a reply and its first argument is 'ok'.
7.232831
4.194318
1.724435
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.REQUEST, name, args, mid)
def request(cls, name, *args, **kwargs)
Helper method for creating request messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments. Keyword arguments ----------------- mid : str or None Message ID to use or None (default) for no Message ID
4.30457
3.902897
1.102917
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.REPLY, name, args, mid)
def reply(cls, name, *args, **kwargs)
Helper method for creating reply messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments. Keyword Arguments ----------------- mid : str or None Message ID to use or None (default) for no Message ID
4.103299
4.19136
0.97899
return cls(cls.REPLY, req_msg.name, args, req_msg.mid)
def reply_to_request(cls, req_msg, *args)
Helper method for creating reply messages to a specific request. Copies the message name and message identifier from request message. Parameters ---------- req_msg : katcp.core.Message instance The request message that this inform if in reply to args : list of strings The message arguments.
9.140654
9.994531
0.914566
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.INFORM, name, args, mid)
def inform(cls, name, *args, **kwargs)
Helper method for creating inform messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments.
4.18005
4.549521
0.918789
return cls(cls.INFORM, req_msg.name, args, req_msg.mid)
def reply_inform(cls, req_msg, *args)
Helper method for creating inform messages in reply to a request. Copies the message name and message identifier from request message. Parameters ---------- req_msg : katcp.core.Message instance The request message that this inform if in reply to args : list of strings The message arguments except name
8.107583
8.727034
0.929019
char = match.group(1) if char in self.ESCAPE_LOOKUP: return self.ESCAPE_LOOKUP[char] elif not char: raise KatcpSyntaxError("Escape slash at end of argument.") else: raise KatcpSyntaxError("Invalid escape character %r." % (char,))
def _unescape_match(self, match)
Given an re.Match, unescape the escape code it represents.
4.642481
4.263947
1.088775
match = self.SPECIAL_RE.search(arg) if match: raise KatcpSyntaxError("Unescaped special %r." % (match.group(),)) return self.UNESCAPE_RE.sub(self._unescape_match, arg)
def _parse_arg(self, arg)
Parse an argument.
6.331923
6.123485
1.034039
# find command type and check validity if not line: raise KatcpSyntaxError("Empty message received.") type_char = line[0] if type_char not in self.TYPE_SYMBOL_LOOKUP: raise KatcpSyntaxError("Bad type character %r." % (type_char,)) mtype = self.TYPE_SYMBOL_LOOKUP[type_char] # find command and arguments name # (removing possible empty argument resulting from whitespace at end # of command) parts = self.WHITESPACE_RE.split(line) if not parts[-1]: del parts[-1] name = parts[0][1:] arguments = [self._parse_arg(x) for x in parts[1:]] # split out message id match = self.NAME_RE.match(name) if match: name = match.group('name') mid = match.group('id') else: raise KatcpSyntaxError("Bad message name (and possibly id) %r." % (name,)) return Message(mtype, name, arguments, mid)
def parse(self, line)
Parse a line, return a Message. Parameters ---------- line : str The line to parse (should not contain the terminating newline or carriage return). Returns ------- msg : Message object The resulting Message.
4.029642
4.126479
0.976533
match = cls.VERSION_RE.match(version_str) if match: major = int(match.group('major')) minor = int(match.group('minor')) flags = set(match.group('flags') or '') else: major, minor, flags = None, None, set() return cls(major, minor, flags)
def parse_version(cls, version_str)
Create a :class:`ProtocolFlags` object from a version string. Parameters ---------- version_str : str The version string from a #version-connect katcp-protocol message.
2.143335
2.31047
0.927662
protocol_info = mcs.PROTOCOL_INFO protocol_version = (protocol_info.major, protocol_info.minor) protocol_flags = protocol_info.flags # Check if minimum protocol version requirement is met min_protocol_version = getattr(handler, '_minimum_katcp_version', None) protocol_version_ok = (min_protocol_version is None or protocol_version >= min_protocol_version) # Check if required optional protocol flags are present required_katcp_protocol_flags = getattr( handler, '_has_katcp_protocol_flags', None) protocol_flags_ok = ( required_katcp_protocol_flags is None or all(flag in protocol_flags for flag in required_katcp_protocol_flags)) return protocol_version_ok and protocol_flags_ok
def check_protocol(mcs, handler)
True if the current server's protocol flags satisfy handler requirements
2.763416
2.676646
1.032417
return cls(cls.INTEGER, name, description, unit, params, default, initial_status)
def integer(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new integer sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. params : list [min, max] -- miniumum and maximum values of the sensor default : int An initial value for the sensor. Defaults to 0. initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
3.348635
6.369812
0.525704
return cls(cls.FLOAT, name, description, unit, params, default, initial_status)
def float(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new float sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. params : list [min, max] -- miniumum and maximum values of the sensor default : float An initial value for the sensor. Defaults to 0.0. initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
3.368768
6.334713
0.531795
return cls(cls.BOOLEAN, name, description, unit, None, default, initial_status)
def boolean(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new boolean sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. default : bool An initial value for the sensor. Defaults to False. initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
4.544687
8.847078
0.513694
return cls(cls.LRU, name, description, unit, None, default, initial_status)
def lru(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new lru sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. default : enum, Sensor.LRU_* An initial value for the sensor. Defaults to self.LRU_NOMINAL initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
4.621086
7.085918
0.652151
return cls(cls.STRING, name, description, unit, None, default, initial_status)
def string(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new string sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. default : string An initial value for the sensor. Defaults to the empty string. initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
4.542243
8.513287
0.533547
return cls(cls.DISCRETE, name, description, unit, params, default, initial_status)
def discrete(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new discrete sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. params : [str] Sequence of all allowable discrete sensor states default : str An initial value for the sensor. Defaults to the first item of params initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
3.190287
5.413779
0.58929
return cls(cls.TIMESTAMP, name, description, unit, None, default, initial_status)
def timestamp(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new timestamp sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. For timestamp sensor may only be the empty string. default : string An initial value for the sensor in seconds since the Unix Epoch. Defaults to 0. initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
4.377312
8.333978
0.525237
return cls(cls.ADDRESS, name, description, unit, None, default, initial_status)
def address(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new IP address sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no applicable units. default : (string, int) An initial value for the sensor. Tuple contaning (host, port). default is ("0.0.0.0", None) initial_status : int enum or None An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. `initial_status` must be one of the keys in Sensor.STATUSES
4.485355
9.084799
0.493721
# copy list before iterating in case new observers arrive for o in list(self._observers): o.update(self, reading)
def notify(self, reading)
Notify all observers of changes to this sensor.
9.82318
7.932592
1.238332
reading = self._current_reading = Reading(timestamp, status, value) self.notify(reading)
def set(self, timestamp, status, value)
Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error condition or not. value : object The value of the sensor (the type should be appropriate to the sensor's type).
7.32711
11.093998
0.660457
timestamp = self.TIMESTAMP_TYPE.decode(raw_timestamp, major) status = self.STATUS_NAMES[raw_status] value = self.parse_value(raw_value, major) self.set(timestamp, status, value)
def set_formatted(self, raw_timestamp, raw_status, raw_value, major=DEFAULT_KATCP_MAJOR)
Set the current value of the sensor. Parameters ---------- timestamp : str KATCP formatted timestamp string status : str KATCP formatted sensor status string value : str KATCP formatted sensor value major : int, default = 5 KATCP major version to use for interpreting the raw values
3.288848
4.514065
0.728578
timestamp, status, value = reading return (self.TIMESTAMP_TYPE.encode(timestamp, major), self.STATUSES[status], self._formatter(value, True, major))
def format_reading(self, reading, major=DEFAULT_KATCP_MAJOR)
Format sensor reading as (timestamp, status, value) tuple of strings. All values are strings formatted as specified in the Sensor Type Formats in the katcp specification. Parameters ---------- reading : :class:`Reading` object Sensor reading as returned by :meth:`read` major : int Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- timestamp : str KATCP formatted timestamp string status : str KATCP formatted sensor status string value : str KATCP formatted sensor value Note ---- Should only be used for a reading obtained from the same sensor.
9.621573
9.613754
1.000813
self._kattype.check(value, major) if timestamp is None: timestamp = time.time() self.set(timestamp, status, value)
def set_value(self, value, status=NOMINAL, timestamp=None, major=DEFAULT_KATCP_MAJOR)
Check and then set the value of the sensor. Parameters ---------- value : object Value of the appropriate type for the sensor. status : Sensor status constant Whether the value represents an error condition or not. timestamp : float in seconds or None The time at which the sensor value was determined. Uses current time if None. major : int Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.
6.041063
5.48213
1.101955
if type_string in cls.SENSOR_TYPE_LOOKUP: return cls.SENSOR_TYPE_LOOKUP[type_string] else: raise KatcpSyntaxError("Invalid sensor type string %s" % type_string)
def parse_type(cls, type_string)
Parse KATCP formatted type code into Sensor type constant. Parameters ---------- type_string : str KATCP formatted type code. Returns ------- sensor_type : Sensor type constant The corresponding Sensor type constant.
3.833783
3.28629
1.166599
typeclass, _value = cls.SENSOR_TYPES[sensor_type] if sensor_type == cls.DISCRETE: kattype = typeclass([]) else: kattype = typeclass() return [kattype.decode(x, major) for x in formatted_params]
def parse_params(cls, sensor_type, formatted_params, major=DEFAULT_KATCP_MAJOR)
Parse KATCP formatted parameters into Python values. Parameters ---------- sensor_type : Sensor type constant The type of sensor the parameters are for. formatted_params : list of strings The formatted parameters that should be parsed. major : int Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- params : list of objects The parsed parameters.
6.098396
6.585481
0.926037
self._flag = True old_future = self._waiting_future # Replace _waiting_future with a fresh one incase someone woken up by set_result() # sets this AsyncEvent to False before waiting on it to be set again. self._waiting_future = tornado_Future() old_future.set_result(True)
def set(self)
Set event flag to true and resolve future(s) returned by until_set() Notes ----- A call to set() may result in control being transferred to done_callbacks attached to the future returned by until_set().
12.476902
10.966577
1.137721
f = Future() def cb(): return gen.chain_future(self.until_set(), f) ioloop.add_callback(cb) try: f.result(timeout) return True except TimeoutError: return self._flag
def wait_with_ioloop(self, ioloop, timeout=None)
Do blocking wait until condition is event is set. Parameters ---------- ioloop : tornadio.ioloop.IOLoop instance MUST be the same ioloop that set() / clear() is called from timeout : float, int or None If not None, only wait up to `timeout` seconds for event to be set. Return Value ------------ flag : True if event was set within timeout, otherwise False. Notes ----- This will deadlock if called in the ioloop!
5.764138
6.932121
0.831511
if state not in self._valid_states: raise ValueError('State must be one of {0}, not {1}' .format(self._valid_states, state)) if state != self._state: if timeout: return with_timeout(self._ioloop.time() + timeout, self._waiting_futures[state], self._ioloop) else: return self._waiting_futures[state] else: f = tornado_Future() f.set_result(True) return f
def until_state(self, state, timeout=None)
Return a tornado Future that will resolve when the requested state is set
3.317687
2.843195
1.166887
timeout = kwargs.get('timeout', None) state_futures = (self.until_state(s, timeout=timeout) for s in states) return until_any(*state_futures)
def until_state_in(self, *states, **kwargs)
Return a tornado Future, resolves when any of the requested states is set
4.623773
3.781077
1.222872
done = self.done = fut.done() if done and not self.prev_done: self.done_since = self.ioloop.time() self.prev_done = done
def check_future(self, fut)
Call with each future that is to be yielded on
5.362131
5.857724
0.915395
delta = self.ioloop.time() - self.done_since if self.done and delta > self.max_loop_latency: return True return False
def time_to_yield(self)
Call after check_future(). If True, it is time to yield tornado.gen.moment
8.824964
7.121769
1.239153
timeout = kwargs.get('timeout', None) req_msg = Message.request(*msg_parms) if timeout is not None: reply, informs = client.blocking_request(req_msg, timeout=timeout) else: reply, informs = client.blocking_request(req_msg) if not reply.reply_ok(): raise exception('Unexpected failure reply "{2}"\n' ' with device at {0}, request \n"{1}"' .format(client.bind_address_string, req_msg, reply)) return reply, informs
def request_check(client, exception, *msg_parms, **kwargs)
Make blocking request to client and raise exception if reply is not ok. Parameters ---------- client : DeviceClient instance exception: Exception class to raise *msg_parms : Message parameters sent to the Message.request() call **kwargs : Keyword arguments Forwards kwargs['timeout'] to client.blocking_request(). Forwards kwargs['mid'] to Message.request(). Returns ------- reply, informs : as returned by client.blocking_request Raises ------ *exception* passed as parameter is raised if reply.reply_ok() is False Notes ----- A typical use-case for this function is to use functools.partial() to bind a particular client and exception. The resulting function can then be used instead of direct client.blocking_request() calls to automate error handling.
4.597778
3.535013
1.30064
if self.protocol_flags.major >= SEC_TS_KATCP_MAJOR: return time_seconds else: device_time = time_seconds * SEC_TO_MS_FAC if self.protocol_flags.major < FLOAT_TS_KATCP_MAJOR: device_time = int(device_time) return device_time
def convert_seconds(self, time_seconds)
Convert a time in seconds to the device timestamp units. KATCP v4 and earlier, specified all timestamps in milliseconds. Since KATCP v5, all timestamps are in seconds. If the device KATCP version has been detected, this method converts a value in seconds to the appropriate (seconds or milliseconds) quantity. For version smaller than V4, the time value will be truncated to the nearest millisecond.
5.672462
4.205548
1.348804
assert get_thread_ident() == self.ioloop_thread_id self._last_msg_id += 1 return str(self._last_msg_id)
def _next_id(self)
Return the next available message id.
6.007663
4.884875
1.22985
if len(msg.arguments) < 2: return # Store version information. name = msg.arguments[0] self.versions[name] = tuple(msg.arguments[1:]) if msg.arguments[0] == "katcp-protocol": protocol_flags = ProtocolFlags.parse_version(msg.arguments[1]) self._set_protocol_from_inform(protocol_flags, msg)
def inform_version_connect(self, msg)
Process a #version-connect message.
4.855143
4.581652
1.059693
if use_mid is None: use_mid = self._server_supports_ids if msg.mid is None: mid = self._next_id() if use_mid: msg.mid = mid # An internal mid may be needed for the request/inform/response # machinery to work, so we return it return mid else: return msg.mid
def _get_mid_and_update_msg(self, msg, use_mid)
Get message ID for current request and assign to msg.mid if needed. Parameters ---------- msg : katcp.Message ?request message use_mid : bool or None If msg.mid is None, a new message ID will be created. msg.mid will be filled with this ID if use_mid is True or if use_mid is None and the server supports message ids. If msg.mid is already assigned, it will not be touched, and will be used as the active message ID. Return value ------------ The active message ID
5.838087
5.681411
1.027577
mid = self._get_mid_and_update_msg(msg, use_mid) self.send_request(msg) return mid
def request(self, msg, use_mid=None)
Send a request message, with automatic message ID assignment. Parameters ---------- msg : katcp.Message request message use_mid : bool or None, default=None Returns ------- mid : string or None The message id, or None if no msg id is used If use_mid is None and the server supports msg ids, or if use_mid is True a message ID will automatically be assigned msg.mid is None. if msg.mid has a value, and the server supports msg ids, that value will be used. If the server does not support msg ids, KatcpVersionError will be raised.
5.055585
5.382317
0.939295
assert(msg.mtype == Message.REQUEST) if msg.mid and not self._server_supports_ids: raise KatcpVersionError('Message IDs not supported by server') self.send_message(msg)
def send_request(self, msg)
Send a request messsage. Parameters ---------- msg : Message object The request Message to send.
8.214293
8.458208
0.971162
assert get_thread_ident() == self.ioloop_thread_id data = str(msg) + "\n" # Log all sent messages here so no one else has to. if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug("Sending to {}: {}" .format(self.bind_address_string, repr(data))) if not self._connected.isSet(): raise KatcpClientDisconnected('Not connected to device {0}'.format( self.bind_address_string)) try: return self._stream.write(data) except Exception: self._logger.warn('Could not send message {0!r} to {1!r}' .format(str(msg), self._bindaddr), exc_info=True) self._disconnect(exc_info=True)
def send_message(self, msg)
Send any kind of message. Parameters ---------- msg : Message object The message to send.
4.442645
4.764866
0.932376
assert get_thread_ident() == self.ioloop_thread_id if self._stream: self._logger.warn('Disconnecting existing connection to {0!r} ' 'to create a new connection') self._disconnect() yield self._disconnected.until_set() stream = None try: host, port = self._bindaddr stream = self._stream = yield self._tcp_client.connect( host, port, max_buffer_size=self.MAX_MSG_SIZE) stream.set_close_callback(partial(self._stream_closed_callback, stream)) # our message packets are small, don't delay sending them. stream.set_nodelay(True) stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE self._logger.debug('Connected to {0} with client addr {1}' .format(self.bind_address_string, address_to_string(stream.socket.getsockname()))) if self._connect_failures >= 5: self._logger.warn("Reconnected to {0}" .format(self.bind_address_string)) self._connect_failures = 0 except Exception, e: if self._connect_failures % 5 == 0: # warn on every fifth failure # TODO (NM 2015-03-04) This can get a bit verbose, and typically we have # other mechanisms for tracking failed connections. Consider doing some # kind of exponential backoff starting at 5 times the reconnect time up to # once per 5 minutes self._logger.debug("Failed to connect to {0!r}: {1}" .format(self._bindaddr, e)) self._connect_failures += 1 stream = None yield gen.moment # TODO some kind of error rate limiting? if self._stream: # Can't use _disconnect() and wait on self._disconnected, since # exception may have been raised before _stream_closed_callback # was attached to the iostream. self._logger.debug('stream was set even though connecting failed') self._stream.close() self._disconnected.set() if stream: self._disconnected.clear() self._connected.set() self.last_connect_time = self.ioloop.time() try: self.notify_connected(True) except Exception: self._logger.exception("Notify connect failed. Disconnecting.") self._disconnect()
def _connect(self)
Connect to the server.
5.01789
4.94896
1.013928