File: registry.py

package info (click to toggle)
python-x2go 0.6.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,660 kB
  • sloc: python: 10,018; makefile: 217
file content (1086 lines) | stat: -rw-r--r-- 59,589 bytes parent folder | download
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# -*- coding: utf-8 -*-

# Copyright (C) 2010-2023 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.

"""\
X2GoSessionRegistry class - the X2GoClient's session registry backend

"""
__NAME__ = 'x2gosessregistry-pylib'

__package__ = 'x2go'
__name__    = 'x2go.registry'

import os
import copy
import types
import time
import threading
import re

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

from .defaults import LOCAL_HOME as _LOCAL_HOME
from .defaults import X2GO_CLIENT_ROOTDIR as _X2GO_CLIENT_ROOTDIR
from .defaults import X2GO_SESSIONS_ROOTDIR as _X2GO_SESSIONS_ROOTDIR
from .defaults import X2GO_SESSIONPROFILE_DEFAULTS as _X2GO_SESSIONPROFILE_DEFAULTS
from .defaults import X2GO_SSH_ROOTDIR as _X2GO_SSH_ROOTDIR

from .defaults import BACKENDS as _BACKENDS


class X2GoSessionRegistry(object):
    """\
    This class is utilized by :class:`x2go.client.X2GoClient` instances to maintain a good overview on
    session status of all associated :class:`x2go.session.X2GoSession` instances.


    """
    def __init__(self, client_instance,
                 logger=None, loglevel=log.loglevel_DEFAULT):
        """\
        :param client_instance: the :class:`x2go.client.X2GoClient` instance that instantiated this :class:`x2go.registry.X2GoSessionRegistry` instance.
        :type client_instance: :class:`x2go.client.X2GoClient` instance
        :param logger: you can pass an :class:`x2go.log.X2GoLogger` object to the :class:`x2go.xserver.X2GoClientXConfig` 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``

        """
        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

        self.registry = {}
        self.control_sessions = {}
        self.master_sessions = {}

        self._last_available_session_registration = None
        self._skip_auto_registration = False
        self._profile_locks = {}

    def keys(self):
        """\
        A list of session registry keys.


        :returns: session registry key list
        :rtype: ``list``

        """
        return list(self.registry.keys())

    def __repr__(self):
        result = 'X2GoSessionRegistry('
        for p in dir(self):
            if '__' in p or not p in self.__dict__: continue
            result += p + '=' + str(self.__dict__[p]) + ','
        result = result.strip(',')
        return result + ')'

    def __call__(self, session_uuid):
        """\
        Returns the :class:`x2go.session.X2GoSession` instance for a given session UUID hash.

        :param session_uuid: the X2Go session's UUID registry hash
        :type session_uuid: ``str``

        :returns: the corresponding :class:`x2go.session.X2GoSession` instance
        :rtype: :class:`x2go.session.X2GoSession` instance

        :raises X2GoSessionRegistryException: if the given session UUID could not be found

        """
        try:
            return self.registry[session_uuid]
        except KeyError:
            raise x2go_exceptions.X2GoSessionRegistryException('No session found for UUID %s' % session_uuid)

    def disable_session_auto_registration(self):
        """\
        This method is used to temporarily skip auto-registration of newly appearing
        X2Go session on the server side. This is necessary during session startups to
        assure that the session registry does not get filled with session UUID
        duplicates.


        """
        self._skip_auto_registration = True

    def enable_session_auto_registration(self):
        """\
        This method is used to temporarily (re-)enable auto-registration of newly appearing
        X2Go session on the server side.


        """
        self._skip_auto_registration = False

    def forget(self, session_uuid):
        """\
        Forget the complete record for session UUID ``session_uuid``.

        :param session_uuid: the X2Go session's UUID registry hash
        :type session_uuid: ``str``

        """
        try:
            del self.registry[session_uuid]
            self.logger('Forgetting session UUID %s' % session_uuid, loglevel=log.loglevel_DEBUG)
        except KeyError:
            pass

    def get_profile_id(self, session_uuid):
        """\
        Retrieve the profile ID of a given session UUID hash.

        :param session_uuid: the X2Go session's UUID registry hash
        :type session_uuid: ``str``
        :returns: profile ID
        :rtype: ``str``

        """
        return self(session_uuid).get_profile_id()

    def get_profile_name(self, session_uuid):
        """\
        Retrieve the profile name of a given session UUID hash.

        :param session_uuid: the X2Go session's UUID registry hash
        :type session_uuid: ``str``
        :returns: profile name
        :rtype: ``str``

        """
        return self(session_uuid).get_profile_name()

    def session_summary(self, session_uuid, status_only=False):
        """\
        Compose a session summary (as Python dictionary).

        :param session_uuid: the X2Go session's UUID registry hash
        :type session_uuid: ``str``
        :param status_only: short summary, include session status only (Default value = False)
        :type status_only: ``bool``
        :returns: session summary dictionary
        :rtype: ``dict``

        """
        _session_summary = {}
        _r = False
        if session_uuid in [ s() for s in self.registered_sessions() ]:
            _r = True

        if not status_only:
            _session_summary['uuid'] = _r and session_uuid or None
            _session_summary['profile_id'] = _r and self.get_profile_id(session_uuid) or ''
            _session_summary['profile_name'] = _r and self.get_profile_name(session_uuid) or ''
            _session_summary['session_name'] = _r and self(session_uuid).get_session_name() or ''
            _session_summary['control_session'] = _r and self(session_uuid).get_control_session() or None
            _session_summary['control_params'] = _r and self(session_uuid).control_params or {}
            _session_summary['terminal_session'] = _r and self(session_uuid).get_terminal_session() or None
            _session_summary['terminal_params'] = _r and self(session_uuid).terminal_params or {}
            _session_summary['active_threads'] = _r and bool(self(session_uuid).get_terminal_session()) and self(session_uuid).get_terminal_session().active_threads or []
            _session_summary['backends'] = {
                'control': _r and self(session_uuid).control_backend or None,
                'terminal': _r and self(session_uuid).terminal_backend or None,
                'info': _r and self(session_uuid).info_backend or None,
                'list': _r and self(session_uuid).list_backend or None,
                'proxy': _r and self(session_uuid).proxy_backend or None,
            }

        if _r:
            _session_summary['virgin'] = self(session_uuid).virgin
            _session_summary['connected'] = self(session_uuid).connected
            _session_summary['running'] = self(session_uuid).running
            _session_summary['suspended'] = self(session_uuid).suspended
            _session_summary['terminated'] = self(session_uuid).terminated
        else:
            _session_summary['virgin'] = None
            _session_summary['connected'] = None
            _session_summary['running'] = None
            _session_summary['suspended'] = None
            _session_summary['terminated'] = None
        return _session_summary

    def update_status(self, session_uuid=None, profile_name=None, profile_id=None, session_list=None, force_update=False, newly_connected=False):
        """\
        Update the session status for :class:`x2go.session.X2GoSession` that is represented by a given session UUID hash,
        profile name or profile ID.

        :param session_uuid: the X2Go session's UUID registry hash (Default value = None)
        :type session_uuid: ``str``
        :param profile_name: alternatively, a profile name can be specified (the stati of all registered sessions for this session
            profile will be updated) (Default value = None)
        :type profile_name: ``str``
        :param profile_id: alternatively, a profile ID can be given (the stati of all registered sessions for this session
            profile will be updated) (Default value = None)
        :type profile_id: ``str``
        :param session_list: an optional ``X2GoServerSessionList*`` instance (as returned by the :func:`X2GoClient.list_sessions() <x2go.client.X2GoClient.list_sessions()>` command can
            be passed to this method. (Default value = None)
        :type session_list: ``X2GoServerSessionList*`` instance
        :param force_update: make sure the session status gets really updated (Default value = False)
        :type force_update: ``bool``
        :param newly_connected: set this to ``True``, if the control session has just been connected (Default value = False)
        :param newly_connected: ``bool`` (Default value = False)
        :returns: ``True`` if this method has been successful
        :rtype: ``bool``
        :raises X2GoSessionRegistryException: if the combination of ``session_uuid``, ``profile_name`` and ``profile_id`` does not match the requirement:
            only one of them

        """
        if session_uuid and profile_name or session_uuid and profile_id or profile_name and profile_id:
            raise x2go_exceptions.X2GoSessionRegistryException('only one of the possible method parameters is allowed (session_uuid, profile_name or profile_id)')
        elif session_uuid is None and profile_name is None and profile_id is None:
            raise x2go_exceptions.X2GoSessionRegistryException('at least one of the method parameters session_uuid, profile_name or profile_id must be given')

        if session_uuid:
            session_uuids = [ session_uuid ]
        elif profile_name:
            session_uuids = [ s() for s in self.registered_sessions_of_profile_name(profile_name, return_objects=True) ]
        elif profile_id:
            session_uuids = [ s() for s in self.registered_sessions_of_profile_name(self.client_instance.to_profile_name(profile_id), return_objects=True) ]

        for _session_uuid in session_uuids:

            # only operate on instantiated X2GoSession objects
            if type(self(_session_uuid)) != session.X2GoSession:
                continue

            if self(_session_uuid).is_locked():
                continue

            if not self(_session_uuid).update_status(session_list=session_list, force_update=force_update):
                # skip this run, as nothing has changed since the last time...
                continue

            _last_status = copy.deepcopy(self(_session_uuid)._last_status)
            _current_status = copy.deepcopy(self(_session_uuid)._current_status)

            # at this point we hook into the X2GoClient instance and call notification methods
            # that can be used to inform an application that something has happened

            _profile_name = self(_session_uuid).get_profile_name()
            _session_name = self(_session_uuid).get_session_name()

            if self(_session_uuid).get_server_hostname() != _current_status['server']:

                # if the server (hostname) has changed due to a configuration change we skip all notifications
                self(_session_uuid).session_cleanup()
                self(_session_uuid).__del__()
                if len(self.virgin_sessions_of_profile_name(profile_name)) > 1:
                    del self.registry[_session_uuid]

            elif not _last_status['running'] and _current_status['running'] and not _current_status['faulty']:
                # session has started
                if newly_connected:
                    # from a suspended state
                    self.client_instance.HOOK_on_found_session_running_after_connect(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)
                else:
                    # explicitly ask for the terminal_session object directly here, so we also get 'PENDING' terminal sessions here...
                    if self(_session_uuid).terminal_session:

                        # declare as master session if appropriate
                        if _profile_name not in list(self.master_sessions.keys()):
                            self.master_sessions[_profile_name] = self(_session_uuid)
                            self(_session_uuid).set_master_session()

                        elif (not self.master_sessions[_profile_name].is_desktop_session() and self(_session_uuid).is_desktop_session()) or \
                             (not self.master_sessions[_profile_name].is_desktop_session() and self(_session_uuid).is_published_applications_provider()):
                                self(self.master_sessions[_profile_name]()).unset_master_session()
                                self.master_sessions[_profile_name] = self(_session_uuid)
                                self(_session_uuid).set_master_session()

                        if _last_status['suspended']:
                            # from a suspended state
                            self.client_instance.HOOK_on_session_has_resumed_by_me(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)
                        elif _last_status['virgin']:
                            # as a new session
                            self.client_instance.HOOK_on_session_has_started_by_me(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)

                    else:
                        if _last_status['suspended']:
                            # from a suspended state
                            self.client_instance.HOOK_on_session_has_resumed_by_other(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)
                        elif _last_status['connected'] and _last_status['virgin']:
                            # as a new session, do not report directly after connect due to many false positives then...
                            self.client_instance.HOOK_on_session_has_started_by_other(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)

            elif _last_status['connected'] and (not _last_status['suspended'] and _current_status['suspended']) and not _current_status['faulty'] and _session_name:

                # unregister as master session
                if _profile_name in list(self.master_sessions.keys()):
                    if self.master_sessions[_profile_name] == self(_session_uuid):

                        self(_session_uuid).unset_master_session()
                        del self.master_sessions[_profile_name]

                # session has been suspended
                self(_session_uuid).session_cleanup()
                self.client_instance.HOOK_on_session_has_been_suspended(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)

            elif _last_status['connected'] and (not _last_status['terminated'] and _current_status['terminated']) and not _current_status['faulty'] and _session_name:

                # unregister as master session
                if _profile_name in list(self.master_sessions.keys()):
                    if self.master_sessions[_profile_name] == self(_session_uuid):

                        self(_session_uuid).unset_master_session()
                        del self.master_sessions[_profile_name]

                # session has terminated
                self.client_instance.HOOK_on_session_has_terminated(session_uuid=_session_uuid, profile_name=_profile_name, session_name=_session_name)
                try: self(_session_uuid).session_cleanup()
                except x2go_exceptions.X2GoSessionException: pass
                try: self(_session_uuid).__del__()
                except x2go_exceptions.X2GoSessionException: pass
                if len(self.virgin_sessions_of_profile_name(profile_name)) > 1:
                    self.forget(_session_uuid)

        # detect master sessions for connected profiles that have lost (suspend/terminate) their master session or never had a master session
        for _profile_name in [ p for p in self.connected_profiles(return_profile_names=True) if p not in list(self.master_sessions.keys()) ]:
            _running_associated_sessions = [ _s for _s in self.running_sessions_of_profile_name(_profile_name, return_objects=True) if _s.is_associated() ]
            if _running_associated_sessions:
                for _r_a_s in _running_associated_sessions:
                    if _r_a_s.is_desktop_session():
                        self.master_sessions[_profile_name] = _r_a_s
                        _r_a_s.set_master_session(wait=1)
                        break
                if _profile_name not in self.master_sessions:
                    _pubapp_associated_sessions = self.pubapp_sessions_of_profile_name(_profile_name, return_objects=True)
                    if _pubapp_associated_sessions:
                        self.master_sessions[_profile_name] = _pubapp_associated_sessions[0]
                        _pubapp_associated_sessions[0].set_master_session(wait=2)
                    else:
                        self.master_sessions[_profile_name] = _running_associated_sessions[0]
                        _running_associated_sessions[0].set_master_session(wait=2)

        return True

    def register_available_server_sessions(self, profile_name, session_list=None, newly_connected=False, re_register=False, skip_pubapp_sessions=False):
        """\
        Register server-side available X2Go sessions with this :class:`x2go.registry.X2GoSessionRegistry` instance for a given profile name.

        :param profile_name: session profile name to register available X2Go sessions for
        :type profile_name: ``str``
        :param session_list: an optional ``X2GoServerSessionList*`` instance (as returned by the :func:`X2GoClient.list_sessions() <x2go.client.X2GoClient.list_sessions()>` command can
            be passed to this method. (Default value = None)
        :type session_list: ``X2GoServerSessionList*`` instance
        :param newly_connected: give a hint that the session profile got newly connected (Default value = False)
        :type newly_connected: ``bool``
        :param re_register: re-register available sessions, needs to be done after changes to the session profile (Default value = False)
        :type re_register: ``bool``
        :param skip_pubapp_sessions: Do not register published applications sessions (Default value = False)
        :type skip_pubapp_sessions: ``bool``

        """
        if self._last_available_session_registration is not None:
            _now = time.time()
            _time_delta = _now - self._last_available_session_registration
            if _time_delta < 2 and not re_register:
                self.logger('registration interval too short (%s), skipping automatic session registration...' % _time_delta, loglevel=log.loglevel_DEBUG)
                return
            self._last_available_session_registration = _now

        _connected_sessions = self.connected_sessions_of_profile_name(profile_name=profile_name, return_objects=False)
        _registered_sessions = self.registered_sessions_of_profile_name(profile_name=profile_name, return_objects=False)
        _session_names = [ self(s_uuid).session_name for s_uuid in _registered_sessions if self(s_uuid).session_name is not None ]

        if _connected_sessions:
            # any of the connected sessions is valuable for accessing the profile's control
            # session commands, so we simply take the first that comes in...
            _ctrl_session = self(_connected_sessions[0])

            if session_list is None:
                session_list = _ctrl_session.list_sessions()

            # make sure the session registry gets updated before registering new session
            # (if the server name has changed, this will kick out obsolete X2GoSessions)
            self.update_status(profile_name=profile_name, session_list=session_list, force_update=True)
            for session_name in list(session_list.keys()):
                if (session_name not in _session_names and not self._skip_auto_registration) or re_register:
                    server = _ctrl_session.get_server_hostname()
                    profile_id = _ctrl_session.get_profile_id()

                    # reconstruct all session options of _ctrl_session to auto-register a suspended session
                    # found on the _ctrl_session's connected server
                    _clone_kwargs = _ctrl_session.__dict__
                    kwargs = {}
                    kwargs.update(self.client_instance.session_profiles.to_session_params(profile_id))
                    kwargs['client_instance'] = self.client_instance
                    kwargs['control_backend'] = _clone_kwargs['control_backend']
                    kwargs['terminal_backend'] = _clone_kwargs['terminal_backend']
                    kwargs['proxy_backend'] = _clone_kwargs['proxy_backend']
                    kwargs['info_backend'] = _clone_kwargs['info_backend']
                    kwargs['list_backend'] = _clone_kwargs['list_backend']
                    kwargs['settings_backend'] = _clone_kwargs['settings_backend']
                    kwargs['printing_backend'] = _clone_kwargs['printing_backend']
                    kwargs['keep_controlsession_alive'] = _clone_kwargs['keep_controlsession_alive']
                    kwargs['client_rootdir'] = _clone_kwargs['client_rootdir']
                    kwargs['sessions_rootdir'] = _clone_kwargs['sessions_rootdir']

                    try: del kwargs['server']
                    except: pass
                    try: del kwargs['profile_name']
                    except: pass
                    try: del kwargs['profile_id']
                    except: pass

                    # this if clause catches problems when x2golistsessions commands give weird results
                    if not self.has_session_of_session_name(session_name) or re_register:
                        if not (skip_pubapp_sessions and re.match('.*_stRPUBLISHED_.*', session_name)):
                            session_uuid = self.register(server, profile_id, profile_name,
                                                         session_name=session_name, virgin=False,
                                                         **kwargs
                                                        )
                            self(session_uuid).connected = True
                            self.update_status(session_uuid=session_uuid, force_update=True, newly_connected=newly_connected)

    def register(self, server, profile_id, profile_name,
                 session_name=None,
                 control_backend=_BACKENDS['X2GoControlSession']['default'],
                 terminal_backend=_BACKENDS['X2GoTerminalSession']['default'],
                 info_backend=_BACKENDS['X2GoServerSessionInfo']['default'],
                 list_backend=_BACKENDS['X2GoServerSessionList']['default'],
                 proxy_backend=_BACKENDS['X2GoProxy']['default'],
                 settings_backend=_BACKENDS['X2GoClientSettings']['default'],
                 printing_backend=_BACKENDS['X2GoClientPrinting']['default'],
                 client_rootdir=os.path.join(_LOCAL_HOME,_X2GO_CLIENT_ROOTDIR),
                 sessions_rootdir=os.path.join(_LOCAL_HOME,_X2GO_SESSIONS_ROOTDIR),
                 ssh_rootdir=os.path.join(_LOCAL_HOME,_X2GO_SSH_ROOTDIR),
                 keep_controlsession_alive=True,
                 add_to_known_hosts=False,
                 known_hosts=None,
                 **kwargs):
        """\
        Register a new :class:`x2go.session.X2GoSession` instance with this :class:`x2go.registry.X2GoSessionRegistry`.

        :param server: hostname of X2Go server
        :type server: ``str``
        :param profile_id: profile ID
        :type profile_id: ``str``
        :param profile_name: profile name
        :type profile_name: ``str``
        :param session_name: session name (if available) (Default value = None)
        :type session_name: ``str``
        :param control_backend: X2Go control session backend to use (Default value = _BACKENDS['X2GoControlSession']['default'])
        :type control_backend: ``str``
        :param terminal_backend: X2Go terminal session backend to use (Default value = _BACKENDS['X2GoTerminalSession']['default'])
        :type terminal_backend: ``str``
        :param info_backend: X2Go session info backend to use (Default value = _BACKENDS['X2GoServerSessionInfo']['default'])
        :type info_backend: ``str``
        :param list_backend: X2Go session list backend to use (Default value = _BACKENDS['X2GoServerSessionList']['default'])
        :type list_backend: ``str``
        :param proxy_backend: X2Go proxy backend to use (Default value = _BACKENDS['X2GoProxy']['default'])
        :type proxy_backend: ``str``
        :param settings_backend: X2Go client settings backend to use (Default value = _BACKENDS['X2GoClientSettings']['default'])
        :type settings_backend: ``str``
        :param printing_backend: X2Go client printing backend to use (Default value = _BACKENDS['X2GoClientPrinting']['default'])
        :type printing_backend: ``str``
        :param client_rootdir: client base dir (default: ~/.x2goclient)
        :type client_rootdir: ``str``
        :param sessions_rootdir: sessions base dir (default: ~/.x2go)
        :type sessions_rootdir: ``str``
        :param ssh_rootdir: ssh base dir (default: ~/.ssh)
        :type ssh_rootdir: ``str``
        :param keep_controlsession_alive: On last :func:`X2GoSession.disconnect() <x2go.session.X2GoSession.disconnect()>` keep the associated ``X2GoControlSession`` instance alive?
        :type keep_controlsession_alive: ``bool``
        :param add_to_known_hosts: Auto-accept server host validity?
        :type add_to_known_hosts: ``bool``
        :param known_hosts: the underlying Paramiko/SSH systems ``known_hosts`` file
        :type known_hosts: ``str``
        :param kwargs: all other options will be passed on to the constructor of the to-be-instantiated :class:`x2go.session.X2GoSession` instance
        :type kwargs: ``dict``
        :param _X2GO_CLIENT_ROOTDIR:
        :returns: the session UUID of the newly registered (or re-registered) session
        :rtype: ``str``

        """
        if profile_id not in list(self._profile_locks.keys()):
            self._profile_locks[profile_id] = threading.Lock()

        self._profile_locks[profile_id].acquire()

        control_session = None
        if profile_id in list(self.control_sessions.keys()):
            control_session = self.control_sessions[profile_id]

        try:
            _params = self.client_instance.session_profiles.to_session_params(profile_id)

        except x2go_exceptions.X2GoProfileException:
            _params = utils._convert_SessionProfileOptions_2_SessionParams(_X2GO_SESSIONPROFILE_DEFAULTS)

        for _k in list(_params.keys()):
            if _k in list(kwargs.keys()):
                _params[_k] = kwargs[_k]

        # allow injection of PKey objects (Paramiko's private SSH keys)
        if 'pkey' in kwargs:
            _params['pkey'] = kwargs['pkey']
        if 'sshproxy_pkey' in kwargs:
            _params['sshproxy_pkey'] = kwargs['sshproxy_pkey']

        # when starting a new session, we will try to use unused registered virgin sessions
        # depending on your application layout, there should either be one or no such virgin session at all
        _virgin_sessions = [ s for s in self.virgin_sessions_of_profile_name(profile_name, return_objects=True) if not s.activated ]
        if _virgin_sessions and not session_name:
            session_uuid = _virgin_sessions[0].get_uuid()
            self(session_uuid).activated = True
            self.logger('using already initially-registered yet-unused session %s' % session_uuid, loglevel=log.loglevel_NOTICE)

        else:
            session_uuid = self.get_session_of_session_name(session_name, match_profile_name=profile_name)
            if session_uuid is not None: self.logger('using already registered-by-session-name session %s' % session_uuid, loglevel=log.loglevel_NOTICE)

        if session_uuid is not None:
            self(session_uuid).activated = True
            self(session_uuid).update_params(_params)
            self(session_uuid).set_server(server)
            self(session_uuid).set_profile_name(profile_name)
            self._profile_locks[profile_id].release()
            return session_uuid

        try: del _params['server']
        except: pass
        try: del _params['profile_name']
        except: pass
        try: del _params['profile_id']
        except: pass

        s = session.X2GoSession(server=server, control_session=control_session,
                                profile_id=profile_id, profile_name=profile_name,
                                session_name=session_name,
                                control_backend=control_backend,
                                terminal_backend=terminal_backend,
                                info_backend=info_backend,
                                list_backend=list_backend,
                                proxy_backend=proxy_backend,
                                settings_backend=settings_backend,
                                printing_backend=printing_backend,
                                client_rootdir=client_rootdir,
                                sessions_rootdir=sessions_rootdir,
                                ssh_rootdir=ssh_rootdir,
                                keep_controlsession_alive=keep_controlsession_alive,
                                add_to_known_hosts=add_to_known_hosts,
                                known_hosts=known_hosts,
                                client_instance=self.client_instance,
                                logger=self.logger, **_params)

        session_uuid = s._X2GoSession__get_uuid()
        self.logger('registering X2Go session %s...' % profile_name, log.loglevel_NOTICE)
        self.logger('registering X2Go session with UUID %s' % session_uuid, log.loglevel_DEBUG)

        self.registry[session_uuid] = s
        if profile_id not in list(self.control_sessions.keys()):
            self.control_sessions[profile_id] = s.get_control_session()

        # make sure a new session is a non-master session unless promoted in update_status method
        self(session_uuid).unset_master_session()
        if control_session is None:
            self(session_uuid).do_auto_connect()

        self._profile_locks[profile_id].release()
        return session_uuid

    def has_session_of_session_name(self, session_name, match_profile_name=None):
        """\
        Detect if we know about an :class:`x2go.session.X2GoSession` of name ``<session_name>``.

        :param session_name: name of session to be searched for
        :type session_name: ``str``
        :param match_profile_name: a session's profile_name must match this profile name (Default value = None)
        :type match_profile_name: ``str``
        :returns: ``True`` if a session of ``<session_name>`` has been found
        :rtype: ``bool``

        """
        return bool(self.get_session_of_session_name(session_name, match_profile_name=match_profile_name))

    def get_session_of_session_name(self, session_name, return_object=False, match_profile_name=None):
        """\
        Retrieve the :class:`x2go.session.X2GoSession` instance with session name ``<session_name>``.

        :param session_name: name of session to be retrieved
        :type session_name: ``str``
        :param return_object: if ``False`` the session UUID hash will be returned, if ``True`` the :class:`x2go.session.X2GoSession` instance will be returned (Default value = False)
        :type return_object: ``bool``
        :param match_profile_name: returned sessions must match this profile name (Default value = None)
        :type match_profile_name: ``str``
        :returns: :class:`x2go.session.X2GoSession` object or its representing session UUID hash
        :rtype: :class:`x2go.session.X2GoSession` instance or ``str``
        :raises X2GoSessionRegistryException: if there is more than one :class:`x2go.session.X2GoSession` registered for ``<session_name>`` within
            the same :class:`x2go.client.X2GoClient` instance. This should never happen!

        """
        if match_profile_name is None:
            reg_sessions = self.registered_sessions()
        else:
            reg_sessions = self.registered_sessions_of_profile_name(match_profile_name)
        found_sessions = [ s for s in reg_sessions if s.session_name == session_name and s.session_name is not None ]
        if len(found_sessions) == 1:
            session = found_sessions[0]
            if return_object:
                return session
            else:
                return session.get_uuid()
        elif len(found_sessions) > 1:
            raise x2go_exceptions.X2GoSessionRegistryException('there should only be one registered session of name ,,%s\'\'' % session_name)
        else:
            return None

    def _sessionsWithState(self, state, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        if state == 'associated':
            sessions = [ ts for ts in list(self.registry.values()) if ts.has_terminal_session() ]
        elif state == 'registered':
            sessions = [ ts for ts in list(self.registry.values()) ]
        else:
            sessions = [ ts for ts in list(self.registry.values()) if eval('ts.%s' % state) ]
        if return_profile_names:
            profile_names = []
            for this_session in sessions:
                if this_session.profile_name and this_session.profile_name not in profile_names:
                    profile_names.append(this_session.profile_name)
            return profile_names
        elif return_profile_ids:
            profile_ids = []
            for this_session in sessions:
                if this_session.profile_id and this_session.profile_id not in profile_ids:
                    profile_ids.append(this_session.profile_id)
            return profile_ids
        elif return_session_names:
            session_names = []
            for this_session in sessions:
                if this_session.session_name and this_session.session_name not in session_names:
                    session_names.append(this_session.session_name)
            return session_names
        elif return_objects:
            return sessions
        else:
            return [s.get_uuid() for s in sessions ]

    def connected_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that the underlying :class:`x2go.client.X2GoClient` instances is currently connected to.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('connected', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def associated_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that are currently associated by an ``X2GoTerminalSession*`` to the underlying :class:`x2go.client.X2GoClient` instance.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('associated', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def virgin_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that are currently still in virgin state (not yet connected, associated etc.).
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('virgin', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def running_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that are currently in running state.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('running', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def suspended_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that are currently in suspended state.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('suspended', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def terminated_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that have terminated recently.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('terminated', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    @property
    def has_running_sessions(self):
        """\
        Equals ``True`` if the underlying :class:`x2go.client.X2GoClient` instance has any running sessions at hand.


        """
        return self.running_sessions() and len(self.running_sessions()) > 0

    @property
    def has_suspended_sessions(self):
        """\
        Equals ``True`` if the underlying :class:`x2go.client.X2GoClient` instance has any suspended sessions at hand.


        """
        return self.suspended_sessions and len(self.suspended_sessions) > 0

    def registered_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of all registered sessions.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return self._sessionsWithState('registered', return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names)

    def non_running_sessions(self, return_objects=True, return_profile_names=False, return_profile_ids=False, return_session_names=False):
        """\
        Retrieve a list of sessions that are currently _NOT_ in running state.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = False)
        :type return_profile_ids: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        return [ s for s in self.registered_sessions(return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names) if s not in self.running_sessions(return_objects=return_objects, return_profile_names=return_profile_names, return_profile_ids=return_profile_ids, return_session_names=return_session_names) ]

    def connected_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are currently connected to the profile's X2Go server.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.connected_sessions() and [ s for s in self.connected_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.connected_sessions() and [ s.session_name for s in self.connected_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.connected_sessions() and [ s.get_uuid() for s in self.connected_sessions() if s.get_profile_name() == profile_name ]

    def associated_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are currently associated by an ``X2GoTerminalSession*`` to this :class:`x2go.client.X2GoClient` instance.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.associated_sessions() and [ s for s in self.associated_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.associated_sessions() and [ s.session_name for s in self.associated_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.associated_sessions() and [ s.get_uuid() for s in self.associated_sessions() if s.get_profile_name() == profile_name ]

    def pubapp_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that can be providers for published application list.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.associated_sessions_of_profile_name(profile_name) and [ s for s in self.associated_sessions_of_profile_name(profile_name) if s.is_published_applications_provider() ]
        elif return_session_names:
            return self.associated_sessions_of_profile_name(profile_name) and [ s.session_name for s in self.associated_sessions_of_profile_name(profile_name) if s.is_published_applications_provider() ]
        else:
            return self.associated_sessions_of_profile_name(profile_name) and [ s.get_uuid() for s in self.associated_sessions_of_profile_name(profile_name) if s.is_published_applications_provider() ]

    def registered_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are currently registered with this :class:`x2go.client.X2GoClient` instance.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.registered_sessions() and [ s for s in self.registered_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.registered_sessions() and [ s.session_name for s in self.registered_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.registered_sessions() and [ s.get_uuid() for s in self.registered_sessions() if s.get_profile_name() == profile_name ]

    def virgin_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are registered with this :class:`x2go.client.X2GoClient` instance but have not
        yet been started (i.e. sessions that are in virgin state). If none of the ``return_*`` options is specified a list of
        session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.virgin_sessions() and [ s for s in self.virgin_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.virgin_sessions() and [ s.session_name for s in self.virgin_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.virgin_sessions() and [ s.get_uuid() for s in self.virgin_sessions() if s.get_profile_name() == profile_name ]

    def running_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are currently running.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.running_sessions() and [ s for s in self.running_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.running_sessions() and [ s.session_name for s in self.running_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.running_sessions() and [ s.get_uuid() for s in self.running_sessions() if s.get_profile_name() == profile_name ]

    def suspended_sessions_of_profile_name(self, profile_name, return_objects=True, return_session_names=False):
        """\
        For a given session profile name retrieve a list of sessions that are currently in suspended state.
        If none of the ``return_*`` options is specified a list of session UUID hashes will be returned.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :param return_objects: return as list of :class:`x2go.session.X2GoSession` instances (Default value = True)
        :type return_objects: ``bool``
        :param return_session_names: return as list of X2Go session names (Default value = False)
        :type return_session_names: ``bool``
        :returns: a session list (as UUID hashes, objects or session names)
        :rtype: ``list``

        """
        if return_objects:
            return self.suspended_sessions() and [ s for s in self.suspended_sessions() if s.get_profile_name() == profile_name ]
        elif return_session_names:
            return self.suspended_sessions() and [ s.session_name for s in self.suspended_sessions() if s.get_profile_name() == profile_name ]
        else:
            return self.suspended_sessions() and [ s.get_uuid() for s in self.suspended_sessions() if s.get_profile_name() == profile_name ]

    def control_session_of_profile_name(self, profile_name):
        """\
        For a given session profile name retrieve a the corresponding ``X2GoControlSession*`` instance.

        :param profile_name: session profile name
        :type profile_name: ``str``
        :returns: contol session instance
        :rtype: ``X2GoControlSession*`` instance

        """
        _sessions = self.registered_sessions_of_profile_name(profile_name, return_objects=True)
        if _sessions:
            session = _sessions[0]
            return session.control_session
        return None

    @property
    def connected_control_sessions(self):
        """\
        Equals a list of all currently connected control sessions.


        """
        return [ c for c in list(self.control_sessions.values()) if c.is_connected() ]

    def connected_profiles(self, use_paramiko=False, return_profile_ids=True, return_profile_names=False):
        """\
        Retrieve a list of all currently connected session profiles.

        :param use_paramiko: send query directly to the Paramiko/SSH layer (Default value = False)
        :type use_paramiko: ``bool``
        :param return_profile_names: return as list of profile names (Default value = False)
        :type return_profile_names: ``bool``
        :param return_profile_ids: return as list of profile IDs (Default value = True)
        :type return_profile_ids: ``bool``
        :returns: list of connected session profiles
        :rtype: ``list``

        """
        if use_paramiko:
            return [ p for p in list(self.control_sessions.keys()) if self.control_sessions[p].is_connected() ]
        else:
            return self.connected_sessions(return_profile_ids=return_profile_ids, return_profile_names=return_profile_names)

    def get_master_session(self, profile_name, return_object=True, return_session_name=False):
        """\
        Retrieve the master session of a specific profile.

        :param profile_name: the profile name that we query the master session of
        :type profile_name: ``str``
        :param return_object: return :class:`x2go.session.X2GoSession` instance (Default value = True)
        :type return_object: ``bool``
        :param return_session_name: return X2Go session name (Default value = False)
        :type return_session_name: ``bool``
        :returns: a session list (as UUID hashes, objects, profile names/IDs or session names)
        :rtype: ``list``

        """
        if profile_name not in self.connected_profiles(return_profile_names=True):
            return None

        if profile_name not in list(self.master_sessions.keys()) or self.master_sessions[profile_name] is None:
            return None

        _session = self.master_sessions[profile_name]

        if not _session.is_master_session():
            del self.master_sessions[profile_name]
            return None

        if return_object:
            return _session
        elif return_session_name:
            return _session.get_session_name()
        else:
            return _session.get_uuid()