controller 39.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

Matthieu Lamalle's avatar
Matthieu Lamalle committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    def get_profil_for_servers_list(self, cursor, uri, message_arguments):
        serveridList = message_arguments['serveridlist'].split(',')
        if '_session_user' not in message_arguments or message_arguments['_session_user']['profil'] == 'root':
            return 'root'
        else:
            role=None
            for server_id in serveridList :
                profils = self._get_serverselection_user_server_role(cursor, server_id, message_arguments['_session_user']['username'])
                if profils == []:
                    return None
                for profil in profils:
                    if 'role' in profil:
                        role = profil['role']
                        if not self.policy.enforce(role, uri, 'allowed'):
                            return None
                    else:
                        return None
            return role

111
    @register_wamp('v1.server.list', notification_uri=None, database=True)
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
112
    async def list_servers(self, cursor, _session_user):
113
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
114 115 116 117 118 119 120
            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
121 122 123 124 125 126 127 128 129
        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
130 131 132 133 134
    @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):
135
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
136
            server = self.server.describe_server(cursor, serverid, environment)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            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
159
    #FIXME a supprimer, cf server.describe avec configuration=True
Matthieu Lamalle's avatar
Matthieu Lamalle committed
160 161 162 163 164 165 166 167 168 169 170
    @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
171
    #FIXME END
Matthieu Lamalle's avatar
Matthieu Lamalle committed
172

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

176 177 178 179 180 181
        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})
182
            if return_code:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
183
                defaultserverselection = self._default_user_serverselection(cursor, _session_user)
184
                self.serverselection.add_server_to_selection(cursor, result['serverid'], defaultserverselection['serverselectionid'])
185 186
                return result
            else:
187
                raise ServerError('put passphrase return code status not available')
188 189 190 191 192 193 194 195 196 197 198 199 200 201

        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
202 203
    @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):
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
        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
220 221
    @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):
222
        try:
223
            self.serverselection.remove_server_from_all_selections(cursor, serverid)
224
            return self.server.delete_server(cursor, serverid)
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
225

226 227 228 229 230 231 232 233 234 235 236
        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
237 238
    @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):
239 240 241
        try:
            secret = await self.call('v1.vault.secret.get', secretkey="{}_peeringconf".format(serverid))
            return secret['secret']
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
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
        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
268
    @register_wamp('v1.server.exec.command', notification_uri='v1.server.executed', database=True, profil_adapter='get_profil_for_server')
269 270 271 272
    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):
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
        """
        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']:
304 305 306 307
            if 'success' in result :
                dico['success'] = result['success']
                dico['retcode'] = result['retcode']
                dico['return'] = result['return']
308 309
        return dico

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
310
    @register_wamp('v1.server.exec.list', notification_uri=None, database=True, profil_adapter='get_profil_for_server')
Lionel Morin's avatar
Lionel Morin committed
311
    async def exec_job_on_server(self, cursor, _session_user, server_id):
312 313 314 315 316 317 318 319 320 321 322 323
        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
324 325
    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
326

Lionel Morin's avatar
Lionel Morin committed
327
    async def _exec_deploy_on_server(self, cursor, _session_user, server_id):
328 329 330
        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
331
                                     _session_user=_session_user,
332 333 334 335 336 337 338 339 340 341 342 343 344 345
                                     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
346
                                      jid=str(job_id))
347

348 349 350 351 352 353 354
        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
355
    @register_wamp('v1.config.configuration.server.updated', None, database=True)
356
    async def update_configuration(self, cursor, server_id):
357 358 359 360 361
        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
362 363
        self.server.update_configuration(cursor, server_id, configuration['configuration'])

364

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    @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
384
    def _list_user_servers(self, cursor, _session_user):
385
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
386 387
            username = _session_user['username']
            return self.serverselection.list_user_servers(cursor, username)
388 389 390 391 392 393 394 395

        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
396 397
    @register_wamp('v1.serverselection.list', notification_uri=None, database=True)
    async def list_serverselections(self, cursor, _session_user):
398
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
399 400 401 402
            if _session_user['profil'] == 'root':
                return self.serverselection.list_serverselections(cursor)
            else:
                return self._list_user_serverselections(cursor, _session_user)
403 404 405 406 407 408 409

        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
410

411 412
    @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
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        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):
432
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
433 434
            return self.serverselection.describe_serverselection(cursor, serverselectionid)

435 436 437 438
        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
439 440 441 442
        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))
443 444
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
445

446 447
    @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
448 449 450
        return self._default_user_serverselection(cursor, _session_user)

    def _default_user_serverselection(self, cursor, _session_user):
451
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
452 453
            username = _session_user['username']
            return self.serverselection.default_user_serverselection(cursor, username)
454 455

        except ServerSelectionEmptyRecordDatabaseError as err:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
456 457 458 459
            serverselectionname = username + "_DEFAULT"
            serverselectiondescription = username + " server selection"
            self._create_default_user_serverselection(cursor, serverselectionname, serverselectiondescription, username)
            return self.serverselection.default_user_serverselection(cursor, username)
460 461 462 463 464 465 466 467

        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
468
    def _create_default_user_serverselection(self, cursor, serverselectionname, serverselectiondescription, username):
469
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
470
            return self.serverselection.create_serverselection(cursor, serverselectionname, serverselectiondescription, username)
471 472

        except ServerSelectionErrorDatabaseNotAvailable as err:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
473
            raise ApplicationError('serverselection.error.database-not-available', reason=str(err))
474 475
        except ServerSelectionErrorDbConnection as err:
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
476 477
        except ServerSelectionErrorDuplicateServerSelectionName as err:
            raise ApplicationError('serverselection.static.create.error.duplicate_serverselection', reason=str(err))
478 479 480 481 482 483 484
        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
485 486 487 488 489
            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'))
490 491 492 493

        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
494
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
495
        except ServerSelectionErrorDuplicateServerSelectionName as err:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
496
            raise ApplicationError('serverselection.static.create.error.duplicate_serverselection', reason=str(err))
497 498 499
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
500 501 502 503 504 505 506
    @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'))
507 508 509 510 511 512 513 514 515 516 517 518

        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
519 520
    @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):
521 522
        try:
            return self.serverselection.delete_serverselection(cursor, serverselectionid)
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
523

524 525 526 527 528 529 530 531 532 533 534
        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
535 536
    @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):
537
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
538
            return self.serverselection.add_server_to_selection(cursor, serverid, serverselectionid)
539 540 541 542

        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
543
            raise ApplicationError('serverselection.error.db-connection', reason=str(err))
544 545
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
546 547 548

    @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):
549
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
550 551
            return self.serverselection.remove_server_from_selection(cursor, serverid, serverselectionid)

552 553 554 555 556 557 558
        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
559
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
560 561
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
562

Matthieu Lamalle's avatar
Matthieu Lamalle committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    @register_wamp('v1.serverselection.server.set', notification_uri=None, database=True, profil_adapter='get_profil_for_servers_list')
    async def set_serverselection_server_list(self, cursor,_session_user, serverselectionid, serveridlist):
        try:
            return self.serverselection.set_serverselection_server_list(cursor, serverselectionid, serveridlist)

        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
579 580
    @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):
581
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
582 583
            return self.serverselection.add_user_to_serverselection(cursor, serverselectionid, username, role)

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 594
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
595 596
    @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):
597
        try:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
598
            if self._get_serverselection_user_role(cursor, serverselectionid, username)['role'] != 'owner':
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
599 600 601 602
                return self.serverselection.remove_user_from_serverselection(cursor, serverselectionid, username)
            else:
                raise Exception(_('Can not remove user with role owner from serverseleciton'))

603 604 605 606 607 608 609
        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
610
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
611 612
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
613 614 615

    @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):
616
        try:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
617
            return self.serverselection.update_user_to_serverselection(cursor, serverselectionid, username, role)
618 619 620 621 622 623 624 625

        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
626
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
627 628
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
629

630
    @register_wamp('v1.serverselection.user.role.get', notification_uri=None, database=True)
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
631 632 633 634
    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):
635
        try:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
636
            return self.serverselection.get_serverselection_user_role(cursor, serverselectionid, username)
637

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
638 639
        except ServerSelectionEmptyRecordDatabaseError as err:
            return {}
640 641 642 643 644 645 646
        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
647
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
648 649 650 651
        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
652 653 654 655
    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):
656
        try:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
657
            return self.serverselection.get_serverselection_user_server_role(cursor, serverid, username)
658 659 660 661 662 663 664 665

        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
666
            raise ApplicationError('serverselection.error.unknown_serverselection_id', reason=str(err))
667 668
        except ServerSelectionError as err:
            raise ApplicationError('serverselection.error', reason=str(err))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
669

670 671 672 673 674 675 676
    @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
677

678
        for server_id in servers:
Matthieu Lamalle's avatar
Matthieu Lamalle committed
679 680 681 682 683 684 685 686 687 688 689
            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)})
690 691
        return ret

Matthieu Lamalle's avatar
Matthieu Lamalle committed
692 693 694 695 696 697 698
    @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
699

Matthieu Lamalle's avatar
Matthieu Lamalle committed
700 701 702 703 704 705 706 707 708 709
        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
710

711 712
if __name__ == '__main__':
    run(ServerRunner)
713