~x2go/x2go/python-x2go_master

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# -*- coding: utf-8 -*-

# Copyright (C) 2010-2020 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# Python X2Go is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Python X2Go is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

"""\
X2GoListSessionCache class - caching X2Go session information.

"""
__NAME__ = 'x2gocache-pylib'

__package__ = 'x2go'
__name__    = 'x2go.cache'

# modules
import copy
import gevent

# Python X2Go modules
from . import log
from . import x2go_exceptions

class X2GoListSessionsCache(object):
    """\
    For non-blocking operations in client applications using Python X2Go, it is
    recommended to enable the :class:`x2go.cache.X2GoListSessionsCache`. This can be done by calling
    the constructor of the :class:`x2go.client.X2GoClient` class.

    The session list and desktop cache gets updated in regular intervals by a threaded
    :class:`x2go.guardian.X2GoSessionGuardian` instance. For the session list and desktop list update, the
    X2Go server commands ``x2golistsessions`` and ``x2godesktopsessions`` are called and
    the command's stdout is cached in the session list cache.

    Whenever your client application needs access to either the server's session list
    or the server's desktop list the session cache is queried instead. This assures that
    the server's session/desktop list is available without delay, even on slow internet
    connections.


    """
    x2go_listsessions_cache = {}

    def __init__(self, client_instance, logger=None, loglevel=log.loglevel_DEFAULT):
        """\
        :param client_instance: the :class:`x2go.client.X2GoClient` instance that uses this :class:`x2go.cache.X2GoListSessionsCache`
        :type client_instance: ``obj``
        :param logger: you can pass an :class:`x2go.log.X2GoLogger` object to the :class:`x2go.cache.X2GoListSessionsCache` constructor
        :type logger: ``obj``
        :param loglevel: if no :class:`x2go.log.X2GoLogger` object has been supplied a new one will be
            constructed with the given loglevel
        :type loglevel: ``int``

        """
        self.x2go_listsessions_cache = {}
        self.last_listsessions_cache = {}
        self.protected = False

        if logger is None:
            self.logger = log.X2GoLogger(loglevel=loglevel)
        else:
            self.logger = copy.deepcopy(logger)
        self.logger.tag = __NAME__

        self.client_instance = client_instance

    def delete(self, profile_name):
        """\
        Remove session list from cache for a given profile.

        :param profile_name: name of profile to operate on
        :type profile_name: ``str``

        """
        while self.protected:
            gevent.sleep(.1)
        try: del self.x2go_listsessions_cache[profile_name]
        except KeyError: pass

    def check_cache(self):
        """\
        Check if session list cache elements are still valid (i.e. if all corresponding
        session profiles are still connected). If not so, remove invalid cache entries from
        the session list cache.


        """
        for profile_name in list(self.x2go_listsessions_cache.keys()):
            if profile_name not in self.client_instance.client_connected_profiles(return_profile_names=True):
                del self.x2go_listsessions_cache[profile_name]

    def update_all(self, update_sessions=True, update_desktops=False):
        """\
        Update :class:`x2go.cache.X2GoListSessionsCache` for all connected session profiles.

        :param update_sessions: cache recent session lists from all connected servers (Default value = True)
        :type update_sessions: ``bool``
        :param update_desktops: cache recent desktop lists from all connected servers (Default value = False)
        :type update_desktops: ``bool``

        """
        for profile_name in self.client_instance.client_connected_profiles(return_profile_names=True):
            self.update(profile_name, update_sessions=update_sessions, update_desktops=update_desktops)

        self.check_cache()

    def update(self, profile_name, update_sessions=True, update_desktops=False, update_mounts=False):
        """\
        Update :class:`x2go.cache.X2GoListSessionsCache` (i.e. session/desktops) for session profile ``profile_name``.

        :param profile_name: name of profile to update
        :type profile_name: ``str``
        :param update_sessions: cache recent session list from server (Default value = True)
        :type update_sessions: ``bool``
        :param update_desktops: cache recent desktop list from server (Default value = False)
        :type update_desktops: ``bool``
        :param update_mounts: cache list of client-side mounts on server (Default value = False)
        :type update_mounts: ``bool``

        """
        self.protected = True
        self.last_listsessions_cache = copy.deepcopy(self.x2go_listsessions_cache)
        control_session = self.client_instance.client_control_session_of_profile_name(profile_name)
        if profile_name not in self.x2go_listsessions_cache:
            self.x2go_listsessions_cache[profile_name] = {'sessions': None, 'desktops': None, 'mounts': {}, }
        if update_sessions:
            self._update_sessions(profile_name, control_session)
        if update_desktops:
            self._update_desktops(profile_name, control_session)
        if update_mounts:
            self._update_mounts(profile_name, control_session)
        self.protected = False

    def _update_mounts(self, profile_name, control_session):
        """\
        Update mounts list of :class:`x2go.cache.X2GoListSessionsCache` for session profile ``profile_name``.

        :param profile_name: name of profile to update
        :type profile_name: ``str``
        :param control_session: X2Go control session instance
        :raises X2GoControlSessionException: if the control session's ``list_mounts`` method fails

        """
        try:
            self.x2go_listsessions_cache[profile_name]['mounts'] = {}
            if self.x2go_listsessions_cache[profile_name]['sessions']:
                for session_name in self.x2go_listsessions_cache[profile_name]['sessions']:
                    session = self.client_instance.get_session_of_session_name(session_name, return_object=True, match_profile_name=profile_name)
                    if session is not None and session.is_running():
                        if control_session is not None and not control_session.has_session_died():
                            self.x2go_listsessions_cache[profile_name]['mounts'].update(control_session.list_mounts(session_name))
        except (x2go_exceptions.X2GoControlSessionException, AttributeError) as e:
            if profile_name in list(self.x2go_listsessions_cache.keys()):
                del self.x2go_listsessions_cache[profile_name]
            self.protected = False
            raise x2go_exceptions.X2GoControlSessionException(str(e))
        except x2go_exceptions.X2GoTimeOutException:
            pass
        except KeyError:
            pass

    def _update_desktops(self, profile_name, control_session):
        """\
        Update session lists of :class:`x2go.cache.X2GoListSessionsCache` for session profile ``profile_name``.

        :param profile_name: name of profile to update
        :type profile_name: ``str``
        :param control_session: X2Go control session instance
        :type control_session: ``obj``
        :raises X2GoControlSessionException: if the control session's ``list_desktop`` method fails

        """
        try:
            if control_session is not None and not control_session.has_session_died():
                self.x2go_listsessions_cache[profile_name]['desktops'] = control_session.list_desktops()
        except (x2go_exceptions.X2GoControlSessionException, AttributeError) as e:
            if profile_name in list(self.x2go_listsessions_cache.keys()):
                del self.x2go_listsessions_cache[profile_name]
            self.protected = False
            raise x2go_exceptions.X2GoControlSessionException(str(e))
        except x2go_exceptions.X2GoTimeOutException:
            pass
        except KeyError:
            pass

    def _update_sessions(self, profile_name, control_session):
        """\
        Update desktop list of :class:`x2go.cache.X2GoListSessionsCache` for session profile ``profile_name``.

        :param profile_name: name of profile to update
        :type profile_name: ``str``
        :param control_session: X2Go control session instance
        :type control_session: ``obj``
        :raises X2GoControlSessionException: if the control session's ``list_sessions`` method fails

        """
        try:
            if control_session is not None and not control_session.has_session_died():
                self.x2go_listsessions_cache[profile_name]['sessions'] = control_session.list_sessions()
        except (x2go_exceptions.X2GoControlSessionException, AttributeError) as e:
            if profile_name in list(self.x2go_listsessions_cache.keys()):
                del self.x2go_listsessions_cache[profile_name]
            self.protected = False
            raise x2go_exceptions.X2GoControlSessionException(str(e))
        except KeyError:
            pass

    def list_sessions(self, session_uuid):
        """\
        Retrieve a session list from the current cache content of :class:`x2go.cache.X2GoListSessionsCache`
        for a given :class:`x2go.session.X2GoSession` instance (specified by its unique session UUID).

        :param session_uuid: unique identifier of session to query cache for
        :type session_uuid: ``str``
        :returns: a data object containing available session information
        :rtype: ``X2GoServerSessionList*`` instance (or ``None``)

        """
        profile_name = self.client_instance.get_session_profile_name(session_uuid)
        if self.is_cached(session_uuid=session_uuid):
            return self.x2go_listsessions_cache[profile_name]['sessions']
        else:
            return None

    def list_desktops(self, session_uuid):
        """\
        Retrieve a list of available desktop sessions from the current cache content of
        :class:`x2go.cache.X2GoListSessionsCache` for a given :class:`x2go.session.X2GoSession` instance (specified by its
        unique session UUID).

        :param session_uuid: unique identifier of session to query cache for
        :type session_uuid: ``str``
        :returns: a list of strings representing X2Go desktop sessions available for sharing
        :rtype: ``list`` (or ``None``)

        """
        profile_name = self.client_instance.get_session_profile_name(session_uuid)
        if self.is_cached(session_uuid=session_uuid):
            return self.x2go_listsessions_cache[profile_name]['desktops']
        else:
            return None

    def list_mounts(self, session_uuid):
        """\
        Retrieve a list of mounted client shares from the current cache content of
        :class:`x2go.cache.X2GoListSessionsCache` for a given :class:`x2go.session.X2GoSession` instance (specified by its
        unique session UUID).

        :param session_uuid: unique identifier of session to query cache for
        :type session_uuid: ``str``
        :returns: a list of strings representing mounted client shares
        :rtype: ``list`` (or ``None``)

        """
        profile_name = self.client_instance.get_session_profile_name(session_uuid)
        if self.is_cached(session_uuid=session_uuid):
            return self.x2go_listsessions_cache[profile_name]['mounts']
        else:
            return None

    def is_cached(self, profile_name=None, session_uuid=None, cache_type=None):
        """\
        Check if session information is cached.

        :param profile_name: name of profile to update (Default value = None)
        :type profile_name: ``str``
        :param session_uuid: unique identifier of session to query cache for (Default value = None)
        :type session_uuid: ``str``
        :param cache_type: cache type (e.g. 'mounts', 'desktops', 'sessions') (Default value = None)
        :type cache_type: ``str``
        :returns: ``True`` if session information is cached
        :rtype: ``bool``

        """
        if profile_name is None and session_uuid and self.client_instance:
            try:
                profile_name = self.client_instance.get_session_profile_name(session_uuid)
            except x2go_exceptions.X2GoSessionRegistryException:
                raise x2go_exceptions.X2GoSessionCacheException("requested session UUID is not valid anymore")
        _is_profile_cached = profile_name in self.x2go_listsessions_cache
        _is_cache_type_cached = _is_profile_cached and cache_type in self.x2go_listsessions_cache[profile_name]
        if cache_type is None:
            return _is_profile_cached
        else:
            return _is_cache_type_cached