Skip to content
cli.py 23.8 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
import logging
from collections import defaultdict

from sjrpc.core import RpcError

from ccserver.orderedset import OrderedSet
from ccserver.conf import CCConf
from ccserver.exceptions import (AlreadyRegistered, AuthenticationError,
                                 RightError, ReservedTagError, BadObjectError,
                                 BadRoleError, NotConnectedAccountError,
                                 CloneError)
from ccserver.election import Elector

from ccserver.handlers import listed, Reporter
from ccserver.clients import Client, RegisteredCCHandler
from cloudcontrol.common.tql.db.tag import StaticTag

MIGRATION_TYPES = {'cold': 'cold_migrate',
                   'hot': 'hot_migrate',}


class CliHandler(RegisteredCCHandler):
    """ Handler binded to 'cli' role.

    Summary of methods:

    ================ ================================ =============
    Method name      Description                      Right(s)
    ================ ================================ =============
    list             list objects                     list
    start            start a vm                       start
    stop             stop a vm                        stop
    destroy          destroy a vm                     destroy
    pause            suspend a vm                     pause
    resume           resume a paused vm               resume
    passwd           change password of accounts      passwd
    addaccount       add a new account                addaccount
    copyaccount      copy an account                  addaccount
    addtag           add a tag to accounts            addtag
    deltag           remove a tag from accounts       deltag
    tags             show tags of accounts            tags
    delaccount       delete an account                delaccount
    close            close an account                 close
    declose          declose an account               declose
    kill             kill a connected account         kill
    rights           show rights of accounts          rights
    addright         add right rules to accounts      addright
    delright         remove right rules from accounts delright
    execute          execute remote command on hosts  execute
    shutdown         shutdown a connected client      shutdown
    jobs             show jobs                        jobs
    cancel           cancel a running job             cancel
    jobspurge        remove done jobs from jobs list  jobspurge
    ================ ================================ =============
    """

    @listed
    def list(self, query):
        """ List all objects registered on this instance.

        :param query: the query to select objects to show
        """

        self.check('list', query)
        logging.debug('Executed list function with query %s', query)
        objects = self.server.list(query)
        order = OrderedSet(['id'])
        #if tags is not None:
        #    order |= OrderedSet(tags)
        return {'objects': objects, 'order': list(order)}

    def _vm_action(self, query, method, *args, **kwargs):
        """ Do an action on a virtual machine.
        """
        errs = Reporter()
        # Search all hypervisors of selected vms:
        for vm in self.server.list(query, show=('r', 'h', 'p')):
            if vm['r'] != 'vm':
                errs.error(vm['id'], 'not a vm')
            else:
                hvclient = self.server.get_client(vm['p'])
                if hvclient is None:
                    errs.error(vm['id'], 'offline hypervisor')
                else:
                    try:
                        hvclient.vm_action(method, vm['h'])
                    except Exception as err:
                        errs.error(vm['id'], str(err))
                    else:
                        errs.success(vm['id'], 'ok')
        return errs.get_dict()

    @listed
    def start(self, query):
        """ Start a virtual machine.
        """
        self.check('start', query)
        return self._vm_action(query, 'vm_start')

    @listed
    def stop(self, query):
        """ Stop a virtual machine.
        """
        self.check('stop', query)
        return self._vm_action(query, 'vm_stop')

    @listed
    def destroy(self, query):
        """ Destroy (hard shutdown) a virtual machine.
        """
        self.check('destroy', query)
        return self._vm_action(query, 'vm_destroy')

    @listed
    def pause(self, query):
        """ Pause a virtual machine.
        """
        self.check('pause', query)
        return self._vm_action(query, 'vm_suspend')

    @listed
    def resume(self, query):
        """ Resume a virtual machine.
        """
        self.check('resume', query)
        return self._vm_action(query, 'vm_resume')

    @listed
    def undefine(self, query, delete_storage=True):
        """ Undefine selected virtual machines.

        :param query: the tql query to select objects.
        :param delete_storage: delete storage of vm.
        :return: a dict where key is the id of a selected object, and the value
            a tuple (errcode, message) where errcode is (success|error|warn) and
            message an error message or the output of the command in case of
            success.
        """

        self.check('undefine', query)

        #FIXME: When tag globbing will be implemented, the list of tags to
        #       show will be: r, p, h, disk*
        #       I ask "all tags" pending implementation.
        objects = self.server.list(query, show=('*',))
        errs = Reporter()
        for obj in objects:
            if obj['r'] != 'vm':
                errs.error(obj['id'], 'bad role')
                continue
            try:
                hvcon = self.server.get_connection(obj['p'])
            except KeyError:
                errs.error(obj['id'], 'hypervisor not connected')
            else:
                if delete_storage:
                    for disk in obj.get('disk', '').split():
                        pool = obj.get('disk%s_pool' % disk)
                        name = obj.get('disk%s_vol' % disk)
                        hvcon.proxy.vol_delete(pool, name)
                hvcon.proxy.vm_undefine(obj['h'])
                errs.success(obj['id'], 'vm undefined')

        return errs.get_dict()

    @listed
    def passwd(self, query, password, method='ssha'):
        """ Define a new password for selected users.

        :param query: the query to select the objects to change
        :param password: the password to set (None to remove password)
        :param method: the hash method (sha, ssha, md5, smd5 or plain)
        :return: a standard report output
        """

        self.check('passwd', query)
        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue

                self.conf.set_password(obj['a'], password, method)
                errs.success(obj['id'], 'password updated')

        return errs.get_dict()

    @listed
    def addaccount(self, login, role, password=None):
        """ Create a new account with specified login.

        :param login: the login of the new account
        :param role: the role of the new account
        :param password: the password of the new account (None = not set)
        """

        self.check('addaccount')

        if role in Client.roles:
            self.conf.create_account(login, role, password)
        else:
            raise BadRoleError('%r is not a legal role.' % role)

    @listed
    def copyaccount(self, copy_login, login, password=None):
        """ Create a new account with specified login.

        :param copy_login: the login of the account to copy
        :param login: the login of the new account
        :param password: the password of the new account (default None)
        """

        self.check('addaccount')
        self.conf.copy_account(copy_login, login, password)

    @listed
    def addtag(self, query, tag_name, tag_value):
        """ Add a tag to the accounts which match the specified query.

        :param query: the query to select objects
        :param tag_name: the name of the tag to add
        :param tag_value: the value of the tag
        """

        self.check('addtag', query)

        if tag_name in self.server.RESERVED_TAGS:
            raise ReservedTagError('Tag %r is read-only' % tag_name)

        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.conf:
            for obj in objects:
                print obj
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue

                # Update the configuration for this account:
                tags = self.conf.show(obj['a'])['tags']
                if tag_name in tags:
                    errs.warn(obj['id'], 'tag already exists, changed from %s'
                                         ' to %s' % (tags[tag_name], tag_value))
                    # Update the object db (update the tag value):
                    dbobj = self.server.db.get(obj['id'])
                    dbobj[tag_name].set_value(tag_value)
                else:
                    errs.success(obj['id'], 'tag created')
                    # Update the object db (create the tag):
                    dbobj = self.server.db.get(obj['id'])
                    dbobj.register(StaticTag(tag_name, tag_value), override=True)
                self.conf.add_tag(obj['a'], tag_name, tag_value)

        return errs.get_dict()

    @listed
    def deltag(self, query, tag_name):
        """ Remove a tag of the selected accounts.

        :param query: the query to select objects
        :param tag_name: the name of the tag to remove
        """

        self.check('deltag', query)

        if tag_name in self.server.RESERVED_TAGS:
            raise ReservedTagError('Tag %r is read-only' % tag_name)

        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                tags = self.conf.show(obj['a'])['tags']
                if tag_name in tags:
                    errs.success(obj['id'], 'tag deleted')
                    dbobj = self.server.db.get(obj['id'])
                    dbobj.unregister(tag_name, override=True)
                else:
                    errs.warn(obj['id'], 'unknown tag')
                self.server.conf.remove_tag(obj['a'], tag_name)

        return errs.get_dict()

    @listed
    def tags(self, query):
        """ Return all static tags attached to the selected accounts.

        :param query: the query to select objects
        """

        self.check('tags', query)
        objects = self.server.list(query, show=('a',))
        tags = []
        for obj in objects:
            o = {'id': obj['id']}
            if 'a' in obj:
                otags = self.server.conf.show(obj['a'])['tags']
                otags.update({'id': obj['id']})
                o.update(otags)
            tags.append(o)
        return {'objects': tags, 'order': ['id']}

    @listed
    def delaccount(self, query):
        """ Delete the accounts selected by query.

        :param query: the query to select objects
        """

        self.check('delaccount', query)
        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                try:
                    self.server.conf.remove_account(obj['a'])
                except CCConf.UnknownAccount:
                    errs.error(obj['id'], 'unknown account')
                else:
                    errs.success(obj['id'], 'account deleted')

                self.server.jobs.create('kill', author=self.client.login,
                                         account=obj['a'], gracetime=1)

        return errs.get_dict()

    @listed
    def close(self, query):
        """ Close selected account an account without deleting them.

        :param query: the query to select objects
        """

        self.check('close', query)
        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                tags = self.server.conf.show(obj['a'])['tags']
                if 'close' in tags:
                    errs.warn(obj['id'], 'account already closed')
                    continue

                errs.success(obj['id'], 'closed')
                self.server.conf.add_tag(obj['a'], 'close', 'yes')

                self.server.jobs.create('kill', author=self.client.login,
                                         account=obj['a'], gracetime=1)

        return errs.get_dict()

    @listed
    def declose(self, query):
        """ Re-open selected closed accounts.

        :param query: the query to select objects
        """

        self.check('declose', query)
        objects = self.server.list(query, show=('a',))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                tags = self.conf.show(obj['a'])['tags']
                if 'close' in tags:
                    errs.success(obj['id'], 'account declosed')
                else:
                    errs.warn(obj['id'], 'account not closed')
                self.conf.remove_tag(obj['a'], 'close')

        return errs.get_dict()

    @listed
    def kill(self, query):
        """ Disconnect all connected accounts selected by query.

        :param query: the query to select objects
        """

        self.check('kill', query)
        objects = self.server.list(query, show=set(('a',)))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                try:
                    self.server.kill(obj['a'])
                except NotConnectedAccountError:
                    errs.error(obj['id'], 'account is not connected')
                else:
                    errs.success(obj['id'], 'account killed')

        return errs.get_dict()

    @listed
    def rights(self, query):
        """ Get the rights of selected accounts.

        :param query: the query to select objects
        """

        self.check('rights', query)
        objects = self.server.list(query, show=set(('a',)))
        rules = {}
        for obj in objects:
            if 'a' in obj:
                rules[obj['a']] = self.server.conf.show(obj['a'])['rights']
            else:
                raise BadObjectError('All objects must have the "a" tag.')

        return rules

    @listed
    def addright(self, query, tql, method=None, allow=True, index=None):
        """ Add a right rule to the selected accounts.

        :param query: the query to select objects
        :param tql: the TQL of the right rule
        :param method: the method of the right rule
        :param allow: target = allow if True, else False
        :param index: the index of the rule in list (can be negative to index
            from the end, if the index is out of range, the rule is added to
            the end.
        """

        self.check('addright', query)
        objects = self.server.list(query, show=set(('a',)))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                try:
                    self.server.conf.add_right(obj['a'], tql, method,
                                                allow, index)
                except self.server.conf.UnknownAccount:
                    errs.error(obj['id'], 'unknown account')
                else:
                    errs.success(obj['id'], 'right rule added')

        return errs.get_dict()

    @listed
    def delright(self, query, index):
        """ Remove a right rule from the selected objects.

        :param query: the query to select objects
        :param index: the index of the right rule to remove
        """

        self.check('delright', query)
        objects = self.server.list(query, show=set(('a',)))
        errs = Reporter()
        with self.server.conf:
            for obj in objects:
                if 'a' not in obj:
                    errs.error(obj['id'], 'not an account')
                    continue
                try:
                    self.server.conf.remove_right(obj['a'], index)
                except self.server.conf.UnknownAccount:
                    errs.error(obj['id'], 'unknown account')
                except self.server.conf.OutOfRangeIndexError:
                    errs.error(obj['id'], 'index out of range')
                else:
                    errs.success(obj['id'], 'right rule deleted')

        return errs.get_dict()

    @listed
    def execute(self, query, command):
        """ Execute command on matched objects (must be roles hv or host).

        :param query: the tql query to select objects.
        :param command: the command to execute on each object
        :return: a dict where key is the id of a selected object, and the value
            a tuple (errcode, message) where errcode is (success|error|warn) and
            message an error message or the output of the command in case of
            success.
        """

        self.check('execute', query)
        objects = self.server.list(query, show=('r',))
        errs = Reporter()
        for obj in objects:
            if obj['r'] not in ('hv', 'host'):
                errs.error(obj['id'], 'bad role')
                continue
            try:
                objcon = self.server.get_connection(obj['id'])
            except KeyError:
                errs.error(obj['id'], 'node not connected')
            else:
                returned = objcon.connection.call('execute_command', command)
                errs.success(obj['id'], 'command executed', output=returned)

        return errs.get_dict()

    @listed
    def shutdown(self, query, reboot=True, gracefull=True):
        """ Execute a shutdown on selected objects (must be roles hv or host).

        :param query: the tql query to select objects.
        :param reboot: reboot the host instead of just shut it off
        :param gracefull: properly shutdown the host
        :return: a dict where key is the id of a selected object, and the value
            a tuple (errcode, message) where errcode is (success|error|warn) and
            message an error message.
        """

        self.check('execute', query)
        objects = self.server.list(query, show=set(('r',)))
        errs = Reporter()
        for obj in objects:
            if obj['r'] not in ('hv', 'host'):
                errs.error(obj['id'], 'bad role')
                continue
            try:
                objcon = self.server.get_connection(obj['id'])
            except KeyError:
                errs.error(obj['id'], 'node not connected')
            else:
                try:
                    objcon.connection.call('node_shutdown',
                                                      reboot, gracefull)
                except RpcError as err:
                    errs.error(obj['id'], '%s (exc: %s)' % (err.message,
                                                            err.exception))
                else:
                    errs.success(obj['id'], 'ok')

        return errs.get_dict()

    @listed
    def jobs(self, query, show_done=True, show_running=True):
        """ Return all jobs.

        :param show_done: show done jobs
        :param show_running: show running jobs
        """

        if query:
            raise NotImplementedError('Tql in jobs is not yet supported.')
        props = ('id', 'author', 'created', 'ended',
                 'duration', 'done', 'title', 'status')
        jobs = []
        for job in self.server.jobs.iterjobs(show_done, show_running):

            jobs.append(job.export(props))

        return {'objects': jobs, 'order': props}

    @listed
    def cancel(self, jobid):
        """ Cancel a job.

        :param jobid: the id of the job to cancel.
        """

        self.server.jobs.cancel(jobid)

    @listed
    def jobspurge(self):
        """ Purge all done jobs from the job list.
        """
        self.server.jobs.purge()

    @listed
    def electiontypes(self):
        return Elector.ALGO_BY_TYPES

    @listed
    def election(self, query_vm, query_dest, mtype='cold', algo='fair', **kwargs):
        """ Consult the server for the migration of specified vm on
            an hypervisor pool.

        :param query_vm: the tql query to select VMs to migrate
        :param query_dest: the tql query to select destination hypervisors
            candidates
        :param mtype: type of migration
        :param algo: algo used for distribution
        """
        elector = Elector(self.server, query_vm, query_dest, self.client.login)
        return elector.election(mtype, algo, **kwargs)

    @listed
    def migrate(self, migration_plan):
        """ Launch the provided migration plan.

        :param migration_plan: the plan of the migration.
        :return: a standard error report
        """
        errs = Reporter()
        for migration in migration_plan:
            # Check if the migration type is know:
            if migration['type'] in MIGRATION_TYPES:
                mtype = MIGRATION_TYPES[migration['type']]
            else:
                errmsg = '%r unknown migration type' % migration['type']
                errs.error(migration['sid'], errmsg)
                continue

            self.server.objects.update(ids=(migration['sid'],))
            vm = self.server.objects.get_by_id(migration['sid'])

            # Construct the migration properties:
            migration_properties = {
                'author': self.client.login,
                'vm_name': vm['h'],
                'hv_source': vm['p'],
                'hv_dest': migration['did']
            }

            # Create the job:
            self.server.jobs.create(mtype, **migration_properties)
            errs.success(migration['sid'], 'migration launched')

        return errs.get_dict()

    @listed
    def clone(self, tql_vm, tql_dest, name):
        """ Create and launch a clone job.

        :param tql_vm: a tql matching one vm object (the cloned vm)
        :param tql_dest: a tql matching one hypervisor object (the destination
                         hypervisor)
        :param name: the new name of the VM
        """

        vm = self.server.list(tql_vm, show=('r', 'h', 'p'))

        if len(vm) != 1:
            raise CloneError('VM Tql must select ONE vm')
        elif vm[0]['r'] != 'vm':
            raise CloneError('Destination Tql must select a vm')
        else:
            vm = vm[0]

        dest = self.server.list(tql_dest, show=('r',))
        if len(dest) != 1:
            raise CloneError('Destination Tql must select ONE hypervisor')
        elif dest[0]['r'] != 'hv':
            raise CloneError('Destination Tql must select an hypervisor')
        else:
            dest = dest[0]

        self.server.jobs.create('clone', **{'vm_name': vm['h'],
                                           'new_vm_name': name,
                                           'hv_source': vm['p'],
                                           'hv_dest': dest['id'],
                                           'author': self.client.login})


class CliClient(Client):

    """ A cli client connected to the cc-server.
    """

    ROLE = 'cli'
    RPC_HANDLER = CliHandler


Client.register_client_class(CliClient)