daemon Package

daemon Package

NICOS daemon package.

class nicos.daemon.NicosDaemon(name, **config)

Bases: nicos.core.device.Device

Bases: Device

This class abstracts the main daemon process.

Parameters

authmethod (one of 'none', 'list', 'pam')

Authentication method. Default value: 'none'.

maxlogins (int)

Maximum number of logins. Default value: 10.

passwd (a list of a tuple of (str, str, int))

User/password list for authmethod “list”. Default value: [].

reuseaddress (bool)

Whether to set SO_REUSEADDR. Default value: True.

server (str, mandatory in setup)

Address to bind to (host or host:port).

trustedhosts (a list of str)

Trusted hosts allowed to log in. Default value: [].

updateinterval (float)

Update interval for watch expressions. Default value: 0.20000000000000001. Unit: s.

Parameters inherited from the base classes: description, loglevel, lowlevel

class nicos.daemon.Server(daemon, address, handler)

Bases: SocketServer.TCPServer

Bases: TCPServer

handle_error(request, client_address)

Last chance exception handling.

process_request(request, client_address)

Process a “request”, that is, a client connection.

process_request_thread(request, client_address)

Thread to process the client connection, calls the Handler.

register_handler(handler, host)

Give each handler a unique ID.

serve_forever()
server_close()

Close the server and its socket.

shutdown()
unregister_handler(ident)

Remove a handler from the handlers dictionary.

verify_request(request, client_address)

Called on a new connection. If we have a connection from that host that lacks an event connection, use this.

client Module

The base class for communication with the NICOS server.

class nicos.daemon.client.ErrorResponse

Bases: exceptions.Exception

Bases: Exception

class nicos.daemon.client.NicosClient

Bases: object

ask(*command, **kwds)
connect(conndata, password=None, eventmask=None)
disconnect()
eval(expr, default)
event_handler()
handle_error(err)
read()
signal(name, *args)
tell(*command)
class nicos.daemon.client.ProtocolError

Bases: exceptions.Exception

Bases: Exception

handler Module

The connection handler for the execution daemon, handling the protocol commands.

class nicos.daemon.handler.CloseConnection

Bases: exceptions.Exception

Bases: Exception

Raised to unconditionally close the connection.

class nicos.daemon.handler.ConnectionHandler(request, client_address, server)

Bases: SocketServer.BaseRequestHandler

Bases: BaseRequestHandler

This class is the SocketServer “request handler” implementation for the licos server. One instance of this class is created for every control connection (not event connections) from a client. When the event connection is opened, the event_sender method of the existing instance is spawned as a new thread.

The handle method reads commands from the client, dispatches them to methods of the same name, and writes the responses back.

Command methods must be decorated with the @command decorator; it registers the command for dispatching and avoids boilerplate: if the needcontrol argument is True, the command will need to be called in the controlling session. If the needscript argument is True or False, the command can only be called if a script is running or not running, respectively.

Note that the SocketServer interface is such that the request handling is done while the constructor runs, i.e. the __init__ method calls handle.

break_(args)
check_control()

Check if the current thread is the session’s controlling thread.

check_host()

Match the connecting host against the daemon’s trusted hosts list.

complete(args)
continue_(args)
emergency(args)
eval(args)
event_sender(sock)

Take events from the handler instance’s event queue and send them to the client using the event connection.

eventmask(args)
exec_(args)
getdataset(args)
gethistory(args)
getscript(args)
getstatus(args)
getversion(args)
handle()

Handle a single connection.

queue(args)
quit(args)
read()

Read a command and arguments from the client.

simulate(args)
start(args)
stop(args)
transfer(args)
unlock(args)
unqueue(args)
unwatch(args)
update(args)
watch(args)
write(prefix, msg=None)

Write a message to the client.

nicos.daemon.handler.command(needcontrol=False, needscript=None, name=None)

Decorates a nicosd protocol command. The needcontrol and needscript parameters can be set to avoid boilerplate in the handler functions.

pyctl Module

Python interface to the _pyctl module, to control the execution of Python code via a C trace function.

class nicos.daemon.pyctl.Controller(break_only_in_toplevel=False, break_only_in_filename=None, lineno_behavior=None)

Bases: _pyctl.Controller

Bases: Controller

The Controller object allows to execute Python code in a controlled environment using the Python tracing mechanism (using a C trace function instead of a Python one for speed).

The running code can therefore be halted and stopped from another thread. Additionally, the currently executed line and Python frame can be observed.

Halting works by calling a custom function (“break function”) from the trace function – until this function returns the execution is halted.

Stopping works by throwing an exception from the trace function into the frame executing code, where it should be allowed to propagate to the toplevel and exit excecution. The exception (ControlStop) inherits from BaseException. This works nicely together with “finally:” clauses, but requires that bare “except:” clauses are replaced by “except Exception:”.

There are various options to control breaking behavior. By default, a break can occur everywhere. “break_only_in_toplevel” limits breaking so that a break can only occur between two lines of code in the toplevel code. “break_only_in_filename” works similar, but if it is set, breaks can occur in all frames whose code has the given filename. Using this, breakpoints in non-toplevel code are implemented.

Using an “observer” callable, changes in the line number and execution need not be polled: each time the status or line number changes, the observer is called as observer(status, lineno).

The external interface is usually used like this:

In the executing thread: * instantiate the Controller object * call set_observer() to add an observer * call start()/start_exec()

In the controlling thread: * when halting is wanted, call set_break() * when continuing is wanted, call set_continue() * when stopping is wanted, call set_stop()

Signature of the C class:

Controller(breakfunc, # break function
break_only_in_toplevel=False, # see above break_only_in_filename=None, # see above lineno_behavior) # which line numbers to trace

Methods of the C class:

  • start(callable): start execution, calling the given callable as toplevel
  • start_exec(code, globals[, locals]): start execution of the given code object with the global and local scopes
  • set_break(arg): request a break, the breakfunc will be called at the next trace function run, the arg is given to the breakfunc; a not-None arg is supposed to mean “stop”
  • set_stop(arg): request a stop, the arg will be used as an intializer argument to the ControlStop exception
  • set_observer(observer): attach an observer to the instance

Attributes of the C class:

  • status: execution status
  • currentframe: current execution frame
  • toplevelframe: first and topmost execution frame
  • lineno: current line number (in which frame, see lineno_behavior)
get_stacktrace(limit=None)

Return a stacktrace of the currently executed code.

set_continue(arg)

Allow continuation of a halted execution.

stop(arg)

Called from outside: stop execution.

wait_for_continue()

Called from the break func: wait for set_continue() to be called.

script Module

Thread that executes user scripts.

class nicos.daemon.script.EmergencyStopRequest(user=None)

Bases: nicos.daemon.script.Request

Bases: Request

An emergency stop request (while no script is running).

class nicos.daemon.script.ExecutionController(log, eventfunc, startupsetup)

Bases: nicos.daemon.pyctl.Controller

Bases: Controller

The Controller object has two functions: it holds the state of the script thread, and it controls execution of scripts via a C trace function.

The script_thread_entry method is called in a separate thread, which then processes the requests put into self.queue by the server thread.

When set_break is called, execution is suspended and _breakfunc is called which waits until somebody calls set_continue or set_stop. Since break_only_in_filename is given at creation time, a break request will only break when the execution frame is one from the toplevel script.

The attributes currentframe and lineno correspond to the current execution frame and the current line number in the toplevel script.

See the docstring of pyctl.Controller for more details on the inner working of the Controller object and the trace function.

add_estop_function(func, args)
add_watch_expression(val)
block_requests(requests)
current_location(verbose=False)
eval_expression(expr)
eval_watch_expressions()
exec_estop_functions()
exec_script(code)
new_request(request)
remove_all_watch_expressions(group)
remove_watch_expression(val)
script_thread_entry()

The script execution thread entry point. This thread executes setup code, then waits for scripts on self.queue. The script is then executed in the context of self.namespace, using the controller (self) to watch execution.

simulate_script(code, name)
start_script_thread(*args)
stop_script_thread()
class nicos.daemon.script.Request(user=None)

Bases: object

Abstract Request class.

The server communicates with the script thread via Requests. Each request is put onto a queue, which the script thread processes sequentially. A request can be for script execution, but also for termination of the script thread. Each request has a number, by which pending requests can be identified and ignored.

serialize()
class nicos.daemon.script.RequestError

Bases: exceptions.Exception

Bases: Exception

Exception raised if a request cannot be queued.

class nicos.daemon.script.ScriptError

Bases: exceptions.Exception

Bases: Exception

Exception raised if a script operation cannot be executed.

class nicos.daemon.script.ScriptRequest(text, name=None, user=None)

Bases: nicos.daemon.script.Request

Bases: Request

A request to execute a Python script.

This class holds the script to execute as well, and has all operations that can be done with the script: execute it, and update it.

execute(controller)

Execute the script in the given namespace, using “controller” to execute individual blocks.

parse()
serialize()
update(text, controller)

Update the code with a new script.

This method is called from a different thread than execute(), so we must unset the _run flag before doing anything to self.curblock, self.code or self.blocks.

class nicos.daemon.script.TerminateRequest(user=None)

Bases: nicos.daemon.script.Request

Bases: Request

A script thread termination request.

user Module

NICOS daemon user abstraction.

class nicos.daemon.user.AuthenticationError

Bases: exceptions.Exception

Bases: Exception

class nicos.daemon.user.Authenticator(daemon)

Bases: object

authenticate(username, password)
needs_plain_pw()
class nicos.daemon.user.User(username, accesslevel)

Bases: object

utils Module

Utilities for the NICOS daemon.

class nicos.daemon.utils.DaemonLogHandler(daemon)

Bases: logging.Handler

Bases: Handler

Log handler for transmitting NICOS log messages to the client.

emit(record, entries=('name', 'created', 'levelno', 'message', 'exc_text', 'filename'))
class nicos.daemon.utils.LoggerWrapper(logger, prepend)

Bases: object

Adds more information to logging records. Similar to LoggerAdapter, which is new in Python 2.5.

class nicos.daemon.utils.SimLogReceiver(fileno, daemon)

Bases: threading.Thread

Bases: Thread

Thread for receiving messages from a pipe and sending them to the client.

class nicos.daemon.utils.SimLogSender(fileno, session)

Bases: logging.Handler

Bases: Handler

Log handler sending messages to the original daemon via a pipe.

begin()
emit(record, entries=('name', 'created', 'levelno', 'message', 'exc_text', 'filename'))
finish()
nicos.daemon.utils.fixup_script(script)

Perform some fixup operations on the script.

nicos.daemon.utils.format_exception_cut_frames(cut=0)

Format an exception with traceback, but leave out the first cut number of frames.

nicos.daemon.utils.format_script(script, prompt='>>>')

Format a script with timestamp.

nicos.daemon.utils.format_timestamp(prompt='<<<')

Print a timestamp to stdout.

nicos.daemon.utils.serialize(data)

Serialize an object.

nicos.daemon.utils.update_linecache(name, script)

Set the linecache for a pseudo-module so that the traceback module can extract the source code when creating tracebacks.

Table Of Contents

Previous topic

core Package

Next topic

elog Package