omero.util package

Submodules

Module contents

class util.Dependency(key)[source]

Bases: object

Centralized logic for declaring and logging a service dependency on a non-shipped library. This is called lazily from the run method of the application to give logging time to be initialized.

See #4566

check(logger)[source]
get_version(target)[source]

Get version method which returns a string representing. Should be overwritten by subclasses for packages/modules with no __version__ field.

class util.Environment(*args)[source]

Bases: object

Simple class for creating an executable environment

append(key, addition)[source]

Manually adds a value to the environment string

set(key, value)[source]

Manually sets a value in the target environment.

class util.Resources(sleeptime=60, stop_event=None)[source]

Bases: object

Container class for storing resources which should be cleaned up on close and periodically checked. Use stop_event.set() to stop the internal thread.

add(object, cleanupMethod='cleanup', checkMethod='check')
checkAll(copy)[source]

While stop_event is unset, go through the copy of stuff and call the check method on each entry. Any that throws an exception or returns a False value will be returned in the remove list.

cleanup()
copyStuff()

Within a lock, copy the “stuff” list and reverse it. The list is reversed so that entries added later, which may depend on earlier added entries get a chance to be cleaned up first.

removeAll(remove)

Finally, within another lock, call the “cleanup” method on all the entries in remove, and remove them from the official stuff list. (If stop_event is set during execution, we return with the assumption that Resources.cleanup() will take care of them)

safeClean(m)[source]
class util.Servant(ctx, needs_session=False)[source]

Bases: SimpleServant

Abstract servant which can be used along with a slice2py generated dispatch class as the base type of high-level servants. These provide resource cleanup as per the omero.util.Server class.

By passing “needs_session = True” to this constructor, an internal session will be created and stored in ServerContext as well as registered with self.resources

cleanup()[source]

Cleanups all resoures created by this servant. Calling cleanup multiple times should be safe.

class util.Server(*args: Any, **kwargs: Any)[source]

Bases: Application

Basic server implementation which can be used for implementing a standalone python server which can be started from icegridnode.

The servant implementation MUST have a constructor which takes a single ServerContext argument AND have a cleanup() method

Logging is configured relative to the current directory to be in var/log by default.

Usage:

if __name__ == "__main__":
    app=Server(
        ServicesI, "ServicesAdapter", Ice.Identity("Services",""))
    sys.exit(app.main(sys.argv))

app.impl now points to an instance of ServicesI

cleanup()[source]

Cleans up all resources that were created by this server. Primarily the one servant instance.

run(args)[source]
waitOnStartup()[source]
class util.ServerContext(server_id, communicator, stop_event, on_newsession=None)[source]

Bases: object

Context passed to all servants.

server_id, communicator, and stop_event will be constructed by the top-level Server instance.

A context instance may also be configured to hold on to an internal session (ServiceFactoryPrx) and keep it alive.

This instance obeys the Resources API and calls sf.keepAlive(None) on every check call, but does nothing on cleanup. The sf instance must be manually cleaned as the final operation of a servant.

(Note: cleanup of the server context indicates server shutdown, so should be infrequent)

add_servant(adapter_or_current, servant, ice_identity=None)
check()[source]

Calls getSession() but always returns True. This keeps the context available in the resources for later uses, and tries to re-establish a connection in case Blitz goes down.

cleanup()[source]

Does nothing. Context clean up must happen manually since later activities may want to reuse it. Servants using a server connection should cleanup the instance after Resources is cleaned up

getSession(recreate=True)

Returns the ServiceFactoryPrx configured for the context if available. If the context was not configured for sessions, an ApiUsageException will be thrown: servants should know whether or not they were configured for sessions. See Servant(…, needs_session = True)

Otherwise, if there is no ServiceFactoryPrx, an attempt will be made to create one if recreate == True. If the value is None or non can be recreated, an InternalException will be thrown.

TODO : currently no arguments are provided for re-creating these, but also not in Servant.__init__

hasSession()[source]
newSession()[source]
class util.SimpleServant(ctx)[source]

Bases: object

Base servant initialization. Doesn’t create or try to cleanup a top-level Resources thread. This is useful for large numbers of servants. For servers and other singleton-like servants, see “Servant”

setProxy(prx)[source]

Should be overwritten for post-initialization activities. The reason this method exists is that the implementation must be complete before registering it with the adapter.

class util.StreamRedirect(logger)[source]

Bases: object

Since all server components should exclusively using the logging module any output to stdout or stderr is caught and logged at “WARN”. This is useful, especially in the case of Windows, where stdout/stderr is eaten.

flush()[source]
write(msg)[source]
util.add_grid_object(communicator, obj)[source]
util.configure_logging(logdir=None, logfile=None, loglevel=20, format='%(asctime)s %(levelname)-5.5s [%(name)40s] (%(threadName)-10s) %(message)s', filemode='a', maxBytes=500000000, backupCount=9, time_rollover=False)[source]
util.configure_server_logging(props)[source]

Takes an Ice.Properties instance and configures logging

util.create_admin_session(communicator)[source]
util.edit_path(path_or_obj, start_text)[source]
util.get_omero_user_cache_dir()[source]

Returns the OMERO user cache directory

util.get_omero_userdir()[source]

Returns the OMERO user directory

In 6.0.0 the default will change to use appdirs.user_data_dir. You can enable this behaviour now by setting OMERO_USERDIR=”” (empty string) instead of unset.

Note that files in the old user directory will not be migrated.

util.get_user(default=None)[source]

Returns the username. For most purposes, this value will be the same as getpass.getuser on Unix and win32api.GetUserName on Windows, but in some situations (when running without a terminal, etc) getuser may throw a KeyError. In which case, or if the username resolves to False, the default value be returned.

Any unexpected exceptions will be thrown.

See ticket:6307

util.get_user_dir()[source]
util.internal_service_factory(communicator, user='root', group=None, retries=6, interval=10, client_uuid=None, stop_event=None)[source]

Try to return a ServiceFactory from the grid.

Try a number of times then give up and raise the last exception returned. This method will only work internally to the grid, i.e. behind the Glacier2 firewall. It is intended for internal servers to be able to create sessions for accessing the database.

communicator := Ice.Communicator used to find the registry
user         := Username which should have a session created
group        := Group into which the session should be logged
retries      := Number of session creation retries before throwing
interval     := Seconds between retries
client_uuid  := Uuid of the client which should be used
util.load_dotted_class(dotted_class)[source]

Load a Python class of the form “pkg.mod.Class” via __import__ and return it. No ctor or similar is called.

util.long_to_path(id, root='')[source]

Converts a long to a path such that for all directiories only a 1000 files and a 1000 subdirectories will be returned.

This method duplicates the logic in ome.io.nio.AbstractFileSystemService.java:getPath()

util.make_logname(self)[source]

Generates a logname from the given instance using the module and name from its class

util.tail_lines(filename, linesback=10, returnlist=0)[source]

Does what “tail -10 filename” would have done Parameters:

filename file to read linesback Number of lines to read from end of file returnlist Return a list containing the lines instead of a string