__init__.py 3.91 KB
Newer Older
1
2
3
4
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
5
# Copyright (c) 2015-2019 Beamline Control Unit, ESRF
6
7
# Distributed under the GNU LGPLv3. See LICENSE for more info.

8
"""Shell (:term:`CLI` and Web based)"""
9

10
11
import os
import sys
12
import logging
13
import platform
14
15
16
17
18
19
20
21
22
23
24
25


if sys.platform not in ["win32", "cygwin"]:
    from blessings import Terminal
else:

    class Terminal:
        def __getattr__(self, prop):
            if prop.startswith("__"):
                raise AttributeError(prop)
            return ""

26

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
27
from gevent import socket
28
import functools
29
from bliss import release, current_session
30
from bliss.config import static
31
from bliss.common import session
32
from bliss.common.session import DefaultSession
33
34
from bliss.config.conductor.client import get_default_connection
from bliss.shell.bliss_banners import print_rainbow_banner
35
import __main__
36

37
_log = logging.getLogger("bliss.shell")
38

39

40
41
42
43
44
session.set_current_session = functools.partial(
    session.set_current_session, force=False
)


45
def initialize(session_name=None):
46
    # Add config to the user namespace
47
    config = static.get_config()
48
    error_flag = False
49

50
    """ BLISS CLI welcome messages """
51

52
53
54
    t = Terminal()

    # Version
55
    _version = "version %s" % release.short_version
56
57
58
59
60
61
62
63
64
65
66
67
68
69

    # Hostname
    _hostname = platform.node()

    # Beacon host/port
    try:
        _host = get_default_connection()._host
        _port = str(get_default_connection()._port)
    except:
        _host = "UNKNOWN"
        _port = "UNKNOWN"

    # Conda environment
    try:
70
71
72
73
        _conda_env = (
            "(in {t.blue}%s{t.normal} Conda environment)".format(t=t)
            % os.environ["CONDA_DEFAULT_ENV"]
        )
74
    except KeyError:
75
        _conda_env = ""
76
77

    print_rainbow_banner()
Geoffrey Mant's avatar
Geoffrey Mant committed
78
79
    print("")
    print(
80
81
82
        "Welcome to BLISS %s running on {t.blue}%s{t.normal} %s".format(t=t)
        % (_version, _hostname, _conda_env)
    )
83
    print("Copyright (c) 2015-2019 Beamline Control Unit, ESRF")
Geoffrey Mant's avatar
Geoffrey Mant committed
84
85
    print("-")
    print(
86
87
88
        "Connected to Beacon server on {t.blue}%s{t.normal} (port %s)".format(t=t)
        % (_host, _port)
    )
89
90

    """ Setup(s) """
91
92
93
    if session_name is None:
        session = DefaultSession()
    else:
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        # we will lock the session name
        # this will prevent to start serveral bliss shell
        # with the same session name
        # lock will only be released at the end of process
        default_cnx = get_default_connection()
        try:
            default_cnx.lock(session_name, timeout=1.)
        except RuntimeError:
            try:
                lock_dict = default_cnx.who_locked(session_name)
            except RuntimeError:  # Beacon is to old to answer
                raise RuntimeError(f"{session_name} is already started")
            else:
                raise RuntimeError(
                    f"{session_name} is already running on %s"
                    % lock_dict.get(session_name)
                )
        # set the client name to somethings useful
        try:
            default_cnx.set_client_name(
                f"host:{socket.gethostname()},pid:{os.getpid()} cmd: **bliss -s {session_name}**"
            )
        except RuntimeError:  # Beacon is too old
            pass
118
        session = config.get(session_name)
119
        print("%s: Loading config..." % session.name)
120

121
    env_dict = __main__.__dict__
122

Piergiorgio Pancino's avatar
Piergiorgio Pancino committed
123
    exec("from bliss.shell.standard import *", env_dict)
124
    from bliss.scanning.scan import ScanDisplay
125
126
127
128
129

    env_dict["SCAN_DISPLAY"] = ScanDisplay(session.name)

    env_dict["history"] = lambda: print("Please press F3-key to view history!")

130
    try:
131
        session.setup(env_dict, verbose=True)
132
133
134
    except Exception:
        error_flag = True
        sys.excepthook(*sys.exc_info())
135

136
    if error_flag:
Vincent Michel's avatar
Vincent Michel committed
137
        print("Warning: error(s) happened during setup, setup may not be complete.")
138
    else:
Geoffrey Mant's avatar
Geoffrey Mant committed
139
140
        print("Done.")
        print("")
141

142
143
    env_dict["SCANS"] = current_session.scans

144
    return session.env_dict, session