Exemple #1
0
    def run(self, args):
        if not os.path.exists(args.file):
            self.ctx.die(670, "No such file: %s" % args.file)
        else:
            client = self.ctx.conn(args)
            store = SessionsStore()
            srv, usr, uuid = store.get_current()
            props = store.get(srv, usr, uuid)

            from omero.scripts import parse_file
            from omero.util.temp_files import create_path
            path = create_path()
            text = """
omero.host=%(omero.host)s
omero.user=%(omero.sess)s
omero.pass=%(omero.sess)s
            """
            path.write_text(text % props)

            params = parse_file(args.file)
            m = self._parse_inputs(args, params)
            for k, v in m.items():
                if v is not None:
                    client.setInput(k, v)

            p = self.ctx.popen([sys.executable, args.file], stdout=sys.stdout,
                               stderr=sys.stderr, ICE_CONFIG=str(path))
            p.wait()
            if p.poll() != 0:
                self.ctx.die(p.poll(), "Execution failed.")
Exemple #2
0
    def run(self, args):
        if not os.path.exists(args.file):
            self.ctx.die(670, "No such file: %s" % args.file)
        else:
            client = self.ctx.conn(args)
            store = SessionsStore()
            srv, usr, uuid, port = store.get_current()
            props = store.get(srv, usr, uuid)

            from omero.scripts import parse_file
            from omero.util.temp_files import create_path
            path = create_path()
            text = """
omero.host=%(omero.host)s
omero.user=%(omero.sess)s
omero.pass=%(omero.sess)s
            """
            path.write_text(text % props)

            params = parse_file(args.file)
            m = self._parse_inputs(args, params)
            for k, v in list(m.items()):
                if v is not None:
                    client.setInput(k, v)

            p = self.ctx.popen([sys.executable, args.file],
                               stdout=sys.stdout,
                               stderr=sys.stderr,
                               ICE_CONFIG=str(path))
            p.wait()
            if p.poll() != 0:
                self.ctx.die(p.poll(), "Execution failed.")
Exemple #3
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.store = SessionsStore()
     self.destroyed.connect(self.close)
     atexit.register(self.close)
     self.worker: Optional[WorkerBase] = None
     self._next_worker: Optional[WorkerBase] = None
Exemple #4
0
def get_params_from_session():
    store = SessionsStore()
    session_props = store.get_current()
    host, username, suuid, port = session_props

    # If there is no suuid, there is no session
    if suuid is None:
        return None

    return {'host': host, 'username': username, 'suuid': suuid, 'port': port}
Exemple #5
0
    def __init__(self, config_file=None):

        # Set the connection as not established
        self.conn = None

        self.SUUID = None
        self.HOST = None
        self.PORT = None
        self.USERNAME = None
        self.PASSWORD = None

        # If config_file not specified, first see if there's an active OMERO
        # CLI session.
        if config_file is None:
            store = SessionsStore()
            session_props = store.get_current()
            self.HOST, self.USERNAME, self.SUUID, self.PORT = session_props

        # config_file specified, or no active session. Continue with reading
        # connection params from the config file.
        if config_file is not None or self.SUUID is None:

            # Normalize file path.
            if config_file is None:
                config_file = '~/.omero/config'
            config_file = os.path.expanduser(config_file)

            # Check config file exists.
            if not (os.path.exists(config_file)
                    and os.path.isfile(config_file)):
                sys.stderr.write('No active OMERO CLI session and '
                                 'configuration file {} does not '
                                 'exist\n'.format(config_file))
                sys.exit(1)

            # Check permisisons on config file.
            if os.stat(config_file).st_mode & 0077:
                sys.stderr.write('Configuration file contains private '
                                 'credentials and must not be accessible by '
                                 'other users. Please run:\n\n'
                                 '    chmod 600 {}\n\n'.format(config_file))
                sys.exit(1)

            # Read the credentials file.
            config = ConfigParser.RawConfigParser()
            config.read(config_file)
            self.HOST = config.get('OMEROCredentials', 'host')
            self.PORT = config.getint('OMEROCredentials', 'port')
            self.USERNAME = config.get('OMEROCredentials', 'username')
            self.PASSWORD = config.get('OMEROCredentials', 'password')
 def __init__(self, *args, **kwargs):
     SessionsStore.__init__(self, *args, **kwargs)
     self.clients = []
     self.exceptions = []
Exemple #7
0
 def __init__(self, *args, **kwargs):
     SessionsStore.__init__(self, *args, **kwargs)
     self.clients = []
     self.exceptions = []
Exemple #8
0
class QGateWay(QObject):
    status = Signal(str)
    connected = Signal(BlitzGateway)
    disconnected = Signal()
    error = Signal(object)

    # singletons
    _conn: Optional[BlitzGateway] = None
    _host: Optional[str] = None
    _port: Optional[str] = None
    _user: Optional[str] = None

    def __init__(self, parent=None):
        super().__init__(parent)
        self.store = SessionsStore()
        self.destroyed.connect(self.close)
        atexit.register(self.close)
        self.worker: Optional[WorkerBase] = None
        self._next_worker: Optional[WorkerBase] = None

    @property
    def conn(self):
        return QGateWay._conn

    @conn.setter
    def conn(self, val):
        QGateWay._conn = val

    @property
    def host(self):
        return QGateWay._host

    @host.setter
    def host(self, val):
        QGateWay._host = val

    @property
    def port(self):
        return QGateWay._port

    @port.setter
    def port(self, val):
        QGateWay._port = val

    @property
    def user(self):
        return QGateWay._user

    @user.setter
    def user(self, val):
        QGateWay._user = val

    def isConnected(self):
        return self.conn and self.conn.isConnected()

    def close(self, hard=False):
        if self.isConnected():
            self.conn.close(hard=hard)
            try:
                self.disconnected.emit()
            except RuntimeError:
                # if called during atexit the C/C++ object may be deleted
                pass

    def connect(self):
        if not self.conn:
            raise ValueError("No gateway to connect")
        if not self.conn.isConnected():
            if not self.conn.c:
                self.conn._resetOmeroClient()
            if self.conn.connect():
                self.connected.emit(self.conn)

    def get_current(self) -> Tuple[str, str, str, str]:
        return self.store.get_current()

    def _start_next_worker(self):
        if self._next_worker is not None:
            self.worker = self._next_worker
            self._next_worker = None
            self.worker.start()
        else:
            self.worker = None

    def _submit(self,
                func: Callable,
                *args,
                _wait=True,
                **kwargs) -> WorkerBase:
        new_worker = create_worker(func, *args, _start_thread=False, **kwargs)
        new_worker.finished.connect(self._start_next_worker)

        if self.worker and self.worker.is_running:
            self._next_worker = new_worker
            if not _wait:
                self.worker.quit()
        else:
            self.worker = new_worker
            self.worker.start()
        return new_worker

    def try_restore_session(self):
        return self._submit(self._try_restore_session)

    def _try_restore_session(self) -> Optional[SessionStats]:
        host, username, uuid, port = self.get_current()
        host = self.host or host
        username = self.user or username
        port = self.port or port
        if uuid and self.store.exists(host, username, uuid):
            try:
                self.status.emit("connecting...")
                session = self.store.attach(host, username, uuid)
                return self._on_new_session(session)
            except Exception as e:
                self.status.emit("Error")
                self.error.emit(e)
        return None

    def create_session(self, host: str, port: str, username: str,
                       password: str):
        return self._submit(self._create_session, host, port, username,
                            password)

    def _create_session(self, host: str, port: str, username: str,
                        password: str):
        self.status.emit("connecting...")
        try:
            props = {
                "omero.host": host,
                "omero.user": username,
            }
            if port:
                props['omero.port'] = port
            session = self.store.create(username, password, props)
            return self._on_new_session(session)
        except Exception as e:
            self.status.emit("Error")
            self.error.emit(e)

    def _on_new_session(self, session: SessionStats):
        client = session[0]
        if not client:
            return
        self.conn = BlitzGateway(client_obj=client)
        self.host = client.getProperty("omero.host")
        self.port = client.getProperty("omero.port")
        self.user = client.getProperty("omero.user")

        self.connected.emit(self.conn)
        self.status.emit("")
        return self.conn

    def getObjects(self, name: str,
                   **kwargs) -> Generator[BlitzObjectWrapper, None, None]:
        if not self.isConnected():
            raise RuntimeError("No connection!")
        yield from self.conn.getObjects(name, **kwargs)
Exemple #9
0
def timer(func):
    """Print the runtime of the decorated function"""
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):
        start_time = time.perf_counter()  # 1
        value = func(*args, **kwargs)
        end_time = time.perf_counter()  # 2
        run_time = end_time - start_time  # 3
        logger.debug(f"Finished {func.__name__!r} in {run_time:.4f} secs")
        return value

    return wrapper_timer


STORE = SessionsStore()


def parse_omero_url(url):
    m = re.search(
        r"https?://(?P<host>[^/]+).*/webclient/\?show=(?P<type>[a-z]+)-(?P<id>[0-9]+)",
        url,
    )
    if m:
        return m.groupdict()


@timer
def get_gateway(path, host=None):
    gateway = QGateWay()
    if host: