connection.py 8.83 KB
Newer Older
1
2
3
4
5
import os
from pybis import Openbis
from notebook.base.handlers import IPythonHandler

openbis_connections = {}
vermeul's avatar
vermeul committed
6
fake_password = "******"
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

def register_connection(connection_info):

    conn = OpenBISConnection(
        name                = connection_info.get('name'),
        url                 = connection_info.get('url'),
        verify_certificates = connection_info.get('verify_certificates', False),
        username            = connection_info.get('username'),
        password            = connection_info.get('password'),
        http_only           = connection_info.get('http_only', False),
        status              = 'not connected',
    )
    openbis_connections[conn.name] = conn
    return conn


class OpenBISConnection:
    """register an openBIS connection
    """

    def __init__(self, **kwargs):
        for needed_key in ['name', 'url']:
            if needed_key not in kwargs:
                raise KeyError("{} is missing".format(needed_key))

        for key in kwargs:
            setattr(self, key, kwargs[key])

        openbis = Openbis(
            url = self.url,
            verify_certificates = self.verify_certificates,
            allow_http_but_do_not_use_this_in_production_and_only_within_safe_networks = self.http_only
        )
        self.openbis = openbis
        self.status = "not connected"

    def is_session_active(self):
        return self.openbis.is_session_active()

    def check_status(self):
        if self.openbis.is_session_active():
            self.status = "connected"
        else:
            self.status = "not connected"

    def login(self, username=None, password=None):
        if username is None:
            username=self.username
vermeul's avatar
vermeul committed
55
        if password is None or password == fake_password:
56
57
58
            password=self.password
        self.openbis.login(
            username = username,
vermeul's avatar
vermeul committed
59
            password = password,
60
61
62
63
64
65
        )
        # store username and password in memory
        self.username = username
        self.password = password
        self.status  = 'connected'

vermeul's avatar
vermeul committed
66
67
68
69
    def logout(self):
        self.openbis.logout()
        self.status = "not connected"

vermeul's avatar
vermeul committed
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
    def mount(self, username=None, password=None, hostname=None):
        if username is None:
            username=self.username
        if password is None or password == fake_password:
            password=self.password
        if hostname is None:
            hostname=self.openbis.hostname

        self.openbis.mount(
            username = username,
            password = password,
            hostname = hostname,
        )
        self.mount_status = 'mounted'

    def unmount(self):
        
        mountpoint = getattr(self.openbis, 'mountpoint', None)

        if mountpoint is None:
            try:
                mountpoint = self.openbis.get_mountpoint(search_mountpoint=True)
            except Exception:
                pass
        self.openbis.unmount(mountpoint=mountpoint)


97
    def get_info(self):
98
99
100
101
        is_mounted = self.openbis.is_mounted()
        mountpoint = ''
        if is_mounted:
            mountpoint = self.openbis.get_mountpoint()
102
103
104
105
106
107
        
        return {
            'name'      : self.name,
            'url'       : self.url,
            'status'    : self.status,
            'username'  : self.username,
vermeul's avatar
vermeul committed
108
            'password'  : fake_password,
109
            'isMounted' : is_mounted,
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
            'mountpoint': mountpoint,
        }

class OpenBISConnections(IPythonHandler):

    def _notebook_dir(self):
        notebook_dir = os.getcwd()
        if 'SingleUserNotebookApp' in self.config and 'notebook_dir' in self.config.SingleUserNotebookApp:
            notebook_dir = self.config.SingleUserNotebookApp.notebook_dir
        elif 'notebook_dir' in self.config.NotebookApp:
            notebook_dir = self.config.NotebookApp.notebook_dir
        return notebook_dir

    def post(self):
        """create a new connection

        :return: a new connection object
        """
        data = self.get_json_body()
        conn = register_connection(data)
        if conn.username and conn.password:
            try:
                conn.login()
            except Exception:
                pass
        self.get()
        return

    def get(self):
        """returns all available openBIS connections
        """

        connections= []
        for conn in openbis_connections.values():
            conn.check_status()
            connections.append(conn.get_info())

        self.write({
            'status'       : 200,
            'connections'  : connections,
            'notebook_dir' : self._notebook_dir()
        })
        return


class OpenBISConnectionHandler(IPythonHandler):
    """Handle the requests to /openbis/conn
    """

    def _notebook_dir(self):
        notebook_dir = os.getcwd()
        if 'SingleUserNotebookApp' in self.config and 'notebook_dir' in self.config.SingleUserNotebookApp:
            notebook_dir = self.config.SingleUserNotebookApp.notebook_dir
        elif 'notebook_dir' in self.config.NotebookApp:
            notebook_dir = self.config.NotebookApp.notebook_dir
        return notebook_dir

vermeul's avatar
vermeul committed
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
    def delete(self, connection_name):
        """logout and unmount a connection, remove from connection list
        """
        try:
            conn = openbis_connections[connection_name]
        except KeyError:
            self.set_status(404)
            self.write({
                "reason" : 'No such connection: {}'.format(data)
            })
            return

        try:
            conn.unmount()
        except Exception:
            pass

        try:
            conn.logout()
        except Exception:
            pass

        del openbis_connections[connection_name]


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    def put(self, connection_name):
        """reconnect to a current connection
        :return: an updated connection object
        """
        data = self.get_json_body()

        try:
            conn = openbis_connections[connection_name]
        except KeyError:
            self.set_status(404)
            self.write({
                "reason" : 'No such connection: {}'.format(data)
            })
            return

vermeul's avatar
vermeul committed
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
        if data.get('action','') == 'mount':
            try:
                conn.mount(
                    username=data.get('username'),
                    password=data.get('password'),
                )
                self.write({
                    'status'     : 200,
                    'connection' : conn.get_info(),
                })
            except Exception as err:
                self.set_status(500)
                self.write({
                    "reason": "Mounting failed: {}".format(err)
                })
            return

        if data.get('action','') == 'unmount':
            try:
                conn.unmount()
                self.write({
                    'status'     : 200,
                    'connection' : conn.get_info(),
                })
            except Exception as err:
                self.set_status(500)
                self.write({
                    "reason": "Unmounting failed: {}".format(err)
                })
            return

vermeul's avatar
vermeul committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        if data.get('action','') == 'logout':
            try:
                conn.logout()
                self.write({
                    'status'     : 200,
                    'connection' : conn.get_info(),
                })
            except Exception as err:
                self.set_status(500)
                self.write({
                    "reason": "logout failed: {}".format(err)
                })
            return

vermeul's avatar
vermeul committed
252
253
        # no action given, try to connect instead

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        try:
            conn.login(data.get('username'), data.get('password'))
        except ConnectionError:
            self.set_status(500)
            self.write({
                "reason": "Could not establish connection to {}".format(connection_name)
            })
            return
        except ValueError:
            self.set_status(401)
            self.write({
                "reason": "Incorrect username or password for {}".format(connection_name)
            })
            return
        except Exception:
            self.set_status(500)
            self.write({
                "reason": "General Network Error"
            })

        self.write({
vermeul's avatar
vermeul committed
275
276
277
            'status'       : 200,
            'connection'   : conn.get_info(),
            'notebook_dir' : self._notebook_dir()
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        })

    def get(self, connection_name):
        """returns  information about a connection name
        """

        try:
            conn = openbis_connections[connection_name]
        except KeyError:
            self.set_status(404)
            self.write({
                "reason" : 'No such connection: {}'.format(connection_name)
            })
            return

        conn.check_status()

        self.write({
            'status'        : 200,
            'connection'    : conn.get_info(),
            'noteboook_dir' : self._notebook_dir()
        })
        return