controller 37.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import datetime
from autobahn.wamp.exception import ApplicationError

from zephir.i18n import _
from zephir.controller import ZephirCommonController, run
from zephir.http import register as register_http
from zephir.wamp import register as register_wamp
from server.server.lib import Server
from server.server.error import (ServerError,
                                 ServerErrorDatabaseNotAvailable,
                                 ServerErrorPeeringConfNotAvailable,
                                 ServerErrorDbConnection,
                                 ServerErrorInvalidServerId,
                                 ServerErrorInvalidServerModelId,
                                 ServerErrorServerNameNotProvided,
                                 ServerErrorUnknownServerId,
                                 ServerErrorUnknownServerModelId)
21
22
23
24
from server.serverselection.lib import ServerSelection
from server.serverselection.error import (ServerSelectionError,
                                 ServerSelectionErrorDatabaseNotAvailable,
                                 ServerSelectionErrorDbConnection,
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
25
                                 ServerSelectionErrorInvalidServerSelectionId,
26
27
28
29
                                 ServerSelectionErrorServerSelectionNameNotProvided,
                                 ServerSelectionErrorUnknownServerSelectionId,
                                 ServerSelectionErrorDuplicateServerSelectionName,
                                 ServerSelectionEmptyRecordDatabaseError)
30

31
32
33
34
35
36
37
38
39
40
41
42

from zephir.config import ServiceConfig


class ServerRunner(ZephirCommonController):
    """Server controller

    """
    def __init__(self, *args, **kwargs):
        # Create instance of working code
        super().__init__(*args, **kwargs)
        self.server = Server()
43
        self.serverselection = ServerSelection()
44
45
        self.conn = None

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
46
47
48
49
50
51
52
     # GET ROLE
    def get_profil_for_server(self, cursor, uri, message_arguments):
        if 'serverid' in message_arguments:
            server_id = message_arguments['serverid']
        if 'server_id' in message_arguments:
            server_id = message_arguments['server_id']

Matthieu Lamalle's avatar
Matthieu Lamalle committed
53
        if '_session_user' not in message_arguments or message_arguments['_session_user']['profil'] == 'root':
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
54
55
56
57
58
59
60
61
62
63
64
65
66
            return 'root'
        else:
            profils = self._get_serverselection_user_server_role(cursor, server_id, message_arguments['_session_user']['username'])
            for profil in profils:
                if 'role' in profil:
                    role = profil['role']
                    if self.policy.enforce(role, uri, 'allowed'):
                        return role
            return None


    def get_profil_for_serverselection(self, cursor, uri, message_arguments):
        serverselection_id = message_arguments['serverselectionid']
Matthieu Lamalle's avatar
Matthieu Lamalle committed
67
        if '_session_user' not in message_arguments or message_arguments['_session_user']['profil'] == 'root':
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
            return 'root'
        else:
            if message_arguments['_session_user']['profil'] == 'root':
                role = message_arguments['_session_user']['profil']
            else:
                profil = self._get_serverselection_user_role(cursor, serverselection_id, message_arguments['_session_user']['username'])
                if not 'role' in profil:
                    return None
                role = profil['role']
            if self.policy.enforce(role, uri, 'allowed'):
                return role
            return None

    def get_profil_for_all(self, cursor, uri, message_arguments):
        serverselection_role = self.get_profil_for_serverselection(cursor, uri, message_arguments)
        if serverselection_role is None :
            return None

86
87
88
89
90
        server_role = self.get_profil_for_server(cursor, uri, message_arguments)
        if server_role is None :
            return None
        else:
            return server_role
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
91

92
    @register_wamp('v1.server.list', notification_uri=None, database=True)
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
93
    async def list_servers(self, cursor, _session_user):
94
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
95
96
97
98
99
100
101
            if _session_user['profil'] == 'root':
                return self.server.list_servers(cursor)
            else:
                ret = []
                for server_id in self._list_user_servers(cursor, _session_user).get('serverselectionserversid', []):
                    ret.append(self._describe_server(cursor, server_id, False, False))
                return ret
102
103
104
105
106
107
108
109
110
        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))

        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))

        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
111
112
113
114
115
    @register_wamp('v1.server.describe', notification_uri=None, database=True, profil_adapter='get_profil_for_server')
    async def describe_server(self, cursor,_session_user, serverid, configuration):
        return self._describe_server(cursor, serverid, configuration, True)

    def _describe_server(self, cursor, serverid, configuration, environment):
116
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
117
            server = self.server.describe_server(cursor, serverid, environment)
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            if configuration:
                server['configuration'] = serverid
            return server
        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))
        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))
        except ServerErrorInvalidServerId as err:
            raise ApplicationError('server.error.invalid-server-id', reason=str(err))
        except ServerErrorUnknownServerId as err:
            raise ApplicationError('server.error.unknown-server-id', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

    @register_http('v1.server.describe', param='configuration', database=True)
    async def describe_configuration(self, cursor, secret):
        values = self.server.fetch_configuration(cursor, secret)
        if values:
            return json.dumps(values).encode()
        else:
            return b'{}'

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
140
    #FIXME a supprimer, cf server.describe avec configuration=True
Matthieu Lamalle's avatar
Matthieu Lamalle committed
141
142
143
144
145
146
147
148
149
150
151
    @register_wamp('v1.server.config.get', notification_uri=None, database=True)
    async def get_config(self, cursor, serverid):
        return {'configuration': serverid}

    @register_http('v1.server.config.get', param='configuration', database=True)
    async def get_config_file(self, cursor, secret):
        values = self.server.fetch_configuration(cursor, secret)
        if values:
            return json.dumps(values).encode()
        else:
            return b'{}'
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
152
    #FIXME END
Matthieu Lamalle's avatar
Matthieu Lamalle committed
153

154
    @register_wamp('v1.server.create', notification_uri='v1.server.created', database=True)
155
    async def create_server(self, cursor, _session_user, servername, serverdescription, servermodelid, serverpassphrase):
156

157
158
159
160
161
162
        try:
            result = self.server.create_server(cursor, servername, serverdescription, servermodelid)

            return_code = await self.call('v1.vault.secret.set',
                                          secretkey="{}_passphrase".format(result['serverid']),
                                          secret={"passphrase" : serverpassphrase})
163
            if return_code:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
164
                defaultserverselection = self._default_user_serverselection(cursor, _session_user)
165
                self.serverselection.add_server_to_selection(cursor, result['serverid'], defaultserverselection['serverselectionid'])
166
167
                return result
            else:
168
                raise ServerError('put passphrase return code status not available')
169
170
171
172
173
174
175
176
177
178
179
180
181
182

        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))
        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))
        except ServerErrorInvalidServerModelId as err:
            raise ApplicationError('server.error.invalid-servermodel-id', reason=str(err))
        except ServerErrorUnknownServerModelId as err:
            raise ApplicationError('server.error.unknown-servermodel-id', reason=str(err))
        except ServerErrorServerNameNotProvided as err:
            raise ApplicationError('server.error.servername-not-provided', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
183
184
    @register_wamp('v1.server.update', notification_uri='v1.server.updated', database=True, profil_adapter='get_profil_for_server')
    async def update_server(self, cursor, _session_user, serverid, servername, serverdescription):
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        try:
            return self.server.update_server(cursor, serverid, servername, serverdescription)

        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))
        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))
        except ServerErrorInvalidServerId as err:
            raise ApplicationError('server.error.invalid-server-id', reason=str(err))
        except ServerErrorUnknownServerId as err:
            raise ApplicationError('server.error.unknown-server-id', reason=str(err))
        except ServerErrorServerNameNotProvided as err:
            raise ApplicationError('server.error.servername-not-provided', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
201
202
    @register_wamp('v1.server.delete', notification_uri='v1.server.deleted', database=True, profil_adapter='get_profil_for_server')
    async def delete_server(self, cursor,_session_user, serverid):
203
        try:
204
            self.serverselection.remove_server_from_all_selections(cursor, serverid)
205
            return self.server.delete_server(cursor, serverid)
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
206

207
208
209
210
211
212
213
214
215
216
217
        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))
        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))
        except ServerErrorInvalidServerId as err:
            raise ApplicationError('server.error.invalid-server-id', reason=str(err))
        except ServerErrorUnknownServerId as err:
            raise ApplicationError('server.error.unknown-server-id', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
218
219
    @register_wamp('v1.server.peering-conf.get', notification_uri='v1.server.peering-conf.sent', database=True, profil_adapter='get_profil_for_server')
    async def get_peering_conf(self, cursor, _session_user, serverid):
220
221
222
        try:
            secret = await self.call('v1.vault.secret.get', secretkey="{}_peeringconf".format(serverid))
            return secret['secret']
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
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
        except ServerErrorPeeringConfNotAvailable as err:
            raise ApplicationError('server.error.peering-conf-not-available', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

    @register_wamp('v1.execution.salt.master.event.ready', notification_uri='v1.server.environment.updated', database=True)
    async def minion_ready(self,
                           cursor,
                           server_id):
        environ = await self.call('v1.execution.salt.environment.get',
                                  server_id=server_id)
        self.server.update_environment(cursor,
                                       server_id,
                                       json.dumps(environ))
        return {'server_id': server_id}

    @register_wamp('v1.execution.salt.peer.registered', notification_uri='v1.server.salt.registered', database=True)
    async def salt_register(self, cursor, serverid, automation):
        try:
            self.server.register_server_for_automation(cursor, serverid, automation)
            return {'serverid': serverid}
        except Exception as err:
            raise ApplicationError('server.registering.error',
                                   reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
249
    @register_wamp('v1.server.exec.command', notification_uri='v1.server.executed', database=True, profil_adapter='get_profil_for_server')
250
251
252
253
    async def exec_cmd_on_server(self, cursor, _session_user, server_id, command):
        return await self._exec_cmd_on_server(cursor, server_id, command)

    async def _exec_cmd_on_server(self, cursor, server_id, command):
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
        """
        Transfer command transmitted to automation (salt, ...)
        """
        automation, automation_command = self.server.get_automation_command(cursor, server_id)
        if automation == 'salt':
            result = await self.call('v1.execution.salt.exec',
                                     minion_pattern=str(server_id),
                                     command=automation_command,
                                     arg=command,
                                     client_mode='local_async')
        else:
            raise Exception(_('Automation engine not supported: {}').format(automation))
        if result['minions'] != [str(server_id)]:
            raise Exception(_('Job ({}) not executed only in selected server, all client affected : {}').format(result['jid'],
                                                                                                                result['minions']))
        return {'job_id': result['jid'],
                'server_id': server_id,
                'command': command,
                'automation': automation,
                'executed': False}

    def result_to_dict(self, result, automation):
        dico = {'job_id': result['jid'],
                'server_id': int(result['minion']),
                'automation': automation,
                'executed': result['executed']}
        if result['command'] == 'deploy':
            dico['command'] = 'v1.server.exec.deploy'
        else:
            dico['command'] = result['arg']
        if dico['executed']:
285
286
287
288
            if 'success' in result :
                dico['success'] = result['success']
                dico['retcode'] = result['retcode']
                dico['return'] = result['return']
289
290
        return dico

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
291
    @register_wamp('v1.server.exec.list', notification_uri=None, database=True, profil_adapter='get_profil_for_server')
Lionel Morin's avatar
Lionel Morin committed
292
    async def exec_job_on_server(self, cursor, _session_user, server_id):
293
294
295
296
297
298
299
300
301
302
303
304
        automation, automation_command = self.server.get_automation_command(cursor, server_id)
        if automation == 'salt':
            results = await self.call('v1.execution.salt.job.list',
                                      minion_pattern=str(server_id))
        else:
            raise Exception(_('Automation engine not supported: {}').format(automation))
        ret = []
        for result in results:
            ret.append(self.result_to_dict(result, automation))
        return ret

    @register_wamp('v1.server.exec.deploy', notification_uri=None, database=True)
Lionel Morin's avatar
Lionel Morin committed
305
306
    async def exec_deploy(self, cursor, _session_user, server_id):
        return await self._exec_deploy_on_server(cursor, _session_user, server_id)
Matthieu Lamalle's avatar
Matthieu Lamalle committed
307

Lionel Morin's avatar
Lionel Morin committed
308
    async def _exec_deploy_on_server(self, cursor, _session_user, server_id):
309
310
311
        automation, automation_command = self.server.get_automation_command(cursor, server_id)
        if automation == 'salt':
            result = await self.call('v1.execution.salt.configuration.deploy',
Lionel Morin's avatar
Lionel Morin committed
312
                                     _session_user=_session_user,
313
314
315
316
317
318
319
320
321
322
323
324
325
326
                                     minion_pattern=str(server_id))
        else:
            raise Exception(_('Automation engine not supported: {}').format(automation))
        dico = {'job_id': result['jid'],
                'command': 'v1.server.exec.deploy',
                'automation': automation,
                'server_id': server_id,
                'executed': False}
        return dico

    @register_wamp('v1.server.exec.describe', notification_uri=None)
    async def exec_describe(self, job_id, automation):
        if automation == 'salt':
            results = await self.call('v1.execution.salt.job.describe',
Matthieu Lamalle's avatar
Matthieu Lamalle committed
327
                                      jid=str(job_id))
328

329
330
331
332
333
334
335
        else:
            raise Exception(_('Automation engine not supported: {}').format(automation))
        ret = []
        for result in results:
            ret.append(self.result_to_dict(result, automation))
        return ret

Matthieu Lamalle's avatar
Matthieu Lamalle committed
336
    @register_wamp('v1.config.configuration.server.updated', None, database=True)
337
    async def update_configuration(self, cursor, server_id):
338
339
340
341
342
        try:
            configuration = await self.call('v1.config.configuration.server.get', server_id=server_id)
        except:
            print(f'No configuration available for server {server_id}')
            return
343
344
        self.server.update_configuration(cursor, server_id, configuration['configuration'])

345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    @register_wamp('v1.server.peer-connection.update', notification_uri=None, database=True)
    async def update_peerconnection(self, cursor, serverid):
        try:
            lastpeerconnection = datetime.datetime.now()
            return self.server.update_peerconnection(cursor, serverid, lastpeerconnection)

        except ServerErrorDatabaseNotAvailable as err:
            raise ApplicationError('server.error.database-not-available', reason=str(err))
        except ServerErrorDbConnection as err:
            raise ApplicationError('server.error.db-connection', reason=str(err))
        except ServerErrorInvalidServerId as err:
            raise ApplicationError('server.error.invalid-server-id', reason=str(err))
        except ServerErrorUnknownServerId as err:
            raise ApplicationError('server.error.unknown-server-id', reason=str(err))
        except ServerErrorServerNameNotProvided as err:
            raise ApplicationError('server.error.servername-not-provided', reason=str(err))
        except ServerError as err:
            raise ApplicationError('server.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
365
    def _list_user_servers(self, cursor, _session_user):
366
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
367
368
            username = _session_user['username']
            return self.serverselection.list_user_servers(cursor, username)
369
370
371
372
373
374
375
376

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
377
378
    @register_wamp('v1.serverselection.list', notification_uri=None, database=True)
    async def list_serverselections(self, cursor, _session_user):
379
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
380
381
382
383
            if _session_user['profil'] == 'root':
                return self.serverselection.list_serverselections(cursor)
            else:
                return self._list_user_serverselections(cursor, _session_user)
384
385
386
387
388
389
390

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
391

392
393
    @register_wamp('v1.serverselection.user.list', notification_uri=None, database=True)
    async def list_user_serverselections(self, cursor, _session_user):
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
        return self._list_user_serverselections(cursor, _session_user)

    def _list_user_serverselections(self, cursor, _session_user):
        try:
            username = _session_user['username']
            return self.serverselection.list_user_serverselections(cursor, username)

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

    @register_wamp('v1.serverselection.describe', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def describe_serverselection(self, cursor, _session_user, serverselectionid):
        return self._describe_serverselection(cursor, _session_user, serverselectionid)

    def _describe_serverselection(self, cursor, _session_user, serverselectionid):
413
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
414
415
            return self.serverselection.describe_serverselection(cursor, serverselectionid)

416
417
418
419
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
420
421
422
423
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_server_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
            raise ApplicationError('serverselection.error.unknown_server_id', reason=str(err))
424
425
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
426

427
428
    @register_wamp('v1.serverselection.user.default', notification_uri=None, database=True)
    async def default_user_serverselection(self, cursor, _session_user):
Matthieu Lamalle's avatar
Matthieu Lamalle committed
429
430
431
        return self._default_user_serverselection(cursor, _session_user)

    def _default_user_serverselection(self, cursor, _session_user):
432
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
433
434
            username = _session_user['username']
            return self.serverselection.default_user_serverselection(cursor, username)
435
436

        except ServerSelectionEmptyRecordDatabaseError as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
437
438
439
440
            serverselectionname = username + "_DEFAULT"
            serverselectiondescription = username + " server selection"
            self._create_default_user_serverselection(cursor, serverselectionname, serverselectiondescription, username)
            return self.serverselection.default_user_serverselection(cursor, username)
441
442
443
444
445
446
447
448

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
449
    def _create_default_user_serverselection(self, cursor, serverselectionname, serverselectiondescription, username):
450
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
451
            return self.serverselection.create_serverselection(cursor, serverselectionname, serverselectiondescription, username)
452
453

        except ServerSelectionErrorDatabaseNotAvailable as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
454
            raise ApplicationError('serverselection.error.database-not-available', reason=str(err))
455
456
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
457
458
        except ServerSelectionErrorDuplicateServerSelectionName as err:
            raise ApplicationError('serverselection.static.create.error.duplicate_serverselection', reason=str(err))
459
460
461
462
463
464
465
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))


    @register_wamp('v1.serverselection.create', notification_uri=None, database=True)
    async def create_serverselection(self, cursor, serverselectionname, serverselectiondescription, _session_user):
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
466
467
468
469
470
            if _session_user['profil'] in ['root', 'admin'] or ('_DEFAULT' not in serverselectionname and _session_user['profil'] not in ['root', 'admin']):
                username = _session_user['username']
                return self.serverselection.create_serverselection(cursor, serverselectionname, serverselectiondescription, username)
            else:
                raise Exception(_('Unable to create _DEFAULT serverselection'))
471
472
473
474

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database-not-available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
475
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
476
        except ServerSelectionErrorDuplicateServerSelectionName as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
477
            raise ApplicationError('serverselection.static.create.error.duplicate_serverselection', reason=str(err))
478
479
480
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
481
482
483
484
485
486
487
    @register_wamp('v1.serverselection.update', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def update_serverselection(self, cursor,_session_user, serverselectionid, serverselectionname, serverselectiondescription, dynamique, requete):
        try:
            if '_DEFAULT' not in serverselectionname:
                return self.serverselection.update_serverselection(cursor, serverselectionid, serverselectionname, serverselectiondescription, dynamique, requete)
            else:
                raise Exception(_('Unable to update _DEFAULT serverselection'))
488
489
490
491
492
493
494
495
496
497
498
499

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database-not-available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
500
501
    @register_wamp('v1.serverselection.delete', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def delete_serverselection(self, cursor,_session_user, serverselectionid):
502
503
        try:
            return self.serverselection.delete_serverselection(cursor, serverselectionid)
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
504

505
506
507
508
509
510
511
512
513
514
515
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
516
517
    @register_wamp('v1.serverselection.server.add', notification_uri=None, database=True, profil_adapter='get_profil_for_all')
    async def add_server_to_selection(self, cursor, _session_user, serverid, serverselectionid):
518
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
519
            return self.serverselection.add_server_to_selection(cursor, serverid, serverselectionid)
520
521
522
523

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database-not-available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
524
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
525
526
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
527
528
529

    @register_wamp('v1.serverselection.server.remove', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def remove_server_from_selection(self, cursor,_session_user, serverid, serverselectionid):
530
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
531
532
            return self.serverselection.remove_server_from_selection(cursor, serverid, serverselectionid)

533
534
535
536
537
538
539
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
540
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
541
542
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
543
544
545

    @register_wamp('v1.serverselection.user.add', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def add_user_to_serverselection(self, cursor,_session_user, serverselectionid, username, role):
546
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
547
548
            return self.serverselection.add_user_to_serverselection(cursor, serverselectionid, username, role)

549
550
551
552
553
554
555
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
556
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
557
558
559
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
560
561
    @register_wamp('v1.serverselection.user.remove', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def remove_user_from_serverselection(self, cursor, _session_user, serverselectionid, username):
562
        try:
563
            if self._get_serverselection_user_role(cursor, serverselectionid, username)['role'] != 'owner':            
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
564
565
566
567
                return self.serverselection.remove_user_from_serverselection(cursor, serverselectionid, username)
            else:
                raise Exception(_('Can not remove user with role owner from serverseleciton'))

568
569
570
571
572
573
574
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
575
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
576
577
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
578
579
580

    @register_wamp('v1.serverselection.user.update', notification_uri=None, database=True, profil_adapter='get_profil_for_serverselection')
    async def update_user_to_serverselection(self, cursor,_session_user, serverselectionid, username, role):
581
        try:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
582
            return self.serverselection.update_user_to_serverselection(cursor, serverselectionid, username, role)
583
584
585
586
587
588
589
590

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
591
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
592
593
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
594

595
    @register_wamp('v1.serverselection.user.role.get', notification_uri=None, database=True)
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
596
597
598
599
    async def get_serverselection_user_role(self, cursor, _session_user, serverselectionid, username):
        return self._get_serverselection_user_role(cursor, serverselectionid, _session_user['username'])

    def _get_serverselection_user_role(self, cursor, serverselectionid, username):
600
        try:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
601
            return self.serverselection.get_serverselection_user_role(cursor, serverselectionid, username)
602

Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
603
604
        except ServerSelectionEmptyRecordDatabaseError as err:
            return {}
605
606
607
608
609
610
611
        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
612
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
613
614
615
616
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

    @register_wamp('v1.serverselection.user.role.server.get', notification_uri=None, database=True)
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
617
618
619
620
    async def get_serverselection_user_server_role(self, cursor, _session_user, serverid, username):
        return self._get_serverselection_user_server_role(cursor, serverid, _session_user['username'])

    def _get_serverselection_user_server_role(self, cursor, serverid, username):
621
        try:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
622
            return self.serverselection.get_serverselection_user_server_role(cursor, serverid, username)
623
624
625
626
627
628
629
630

        except ServerSelectionErrorDatabaseNotAvailable as err:
            raise ApplicationError('serverselection.error.database_not_available', reason=str(err))
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
        except ServerSelectionErrorInvalidServerSelectionId as err:
            raise ApplicationError('serverselection.error.invalid_serverselection_id', reason=str(err))
        except ServerSelectionErrorUnknownServerSelectionId as err:
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
631
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
632
633
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
634

635
636
637
638
639
640
641
    @register_wamp('v1.serverselection.exec.command', notification_uri=None, database=True) #FIXME notification
    async def exec_cmd_on_serverserverselection(self, cursor, serverselection_id, command):
        """
        Transfer command transmitted to automation (salt, ...)
        """
        servers = self.serverselection.describe_serverselection(cursor, serverselection_id)['serverselectionserversid']
        ret = []
Matthieu Lamalle's avatar
Acl    
Matthieu Lamalle committed
642

643
        for server_id in servers:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
644
645
646
647
648
649
650
651
652
653
654
            try:
                ret.append(await self._exec_cmd_on_server(cursor, server_id, command))
            except ServerErrorUnknownServerId as err:
                ret.append({'job_id': '',
                            'server_id': server_id,
                            'command': command,
                            'automation': 'salt',
                            'executed': True,
                            'success': False,
                            'retcode': 1,
                            'return': str(err)})
655
656
        return ret

Matthieu Lamalle's avatar
Matthieu Lamalle committed
657
658
659
660
661
662
663
    @register_wamp('v1.serverselection.exec.deploy', notification_uri=None, database=True) #FIXME notification
    async def exec_deploy_on_serverserverselection(self, cursor, serverselection_id):
        """
        Transfer command transmitted to automation (salt, ...)
        """
        servers = self.serverselection.describe_serverselection(cursor, serverselection_id)['serverselectionserversid']
        ret = []
Lionel Morin's avatar
Lionel Morin committed
664

Matthieu Lamalle's avatar
Matthieu Lamalle committed
665
666
667
668
669
670
671
672
673
674
        for server_id in servers:
            try:
                ret.append(await self._exec_deploy_on_server(cursor, server_id))
            except ServerErrorUnknownServerId as err:
                ret.append({'job_id': '',
                            'server_id': server_id,
                            'command': 'deploy',
                            'automation': 'salt',
                            'executed': False})
        return ret
675

676
677
if __name__ == '__main__':
    run(ServerRunner)
678