cyclades_common.py 29.4 KB
Newer Older
Vangelis Koukis's avatar
Vangelis Koukis committed
1
# Copyright (C) 2010-2014 GRNET S.A.
2
#
Vangelis Koukis's avatar
Vangelis Koukis committed
3 4 5 6
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
7
#
Vangelis Koukis's avatar
Vangelis Koukis committed
8 9 10 11
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
12
#
Vangelis Koukis's avatar
Vangelis Koukis committed
13 14
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15 16 17 18 19 20 21 22 23

"""
Utility functions for Cyclades Tests
Cyclades require a lot helper functions and `common'
had grown too much.

"""

import time
24
import IPy
25
import base64
26 27
import socket
import random
28 29
import paramiko
import tempfile
30 31
import subprocess

32 33
from kamaki.clients import ClientError

34 35
from synnefo_tools.burnin.common import BurninTests, MB, GB, QADD, QREMOVE, \
    QDISK, QVM, QRAM, QIP, QCPU, QNET
36 37


38
# pylint: disable=too-many-public-methods
39 40
class CycladesTests(BurninTests):
    """Extends the BurninTests class for Cyclades"""
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
    def _parse_images(self):
        """Find images given to command line"""
        if self.images is None:
            self.info("No --images given. Will use the default %s",
                      "^Debian Base$")
            filters = ["name:^Debian Base$"]
        else:
            filters = self.images
        avail_images = self._find_images(filters)
        self.info("Found %s images to choose from", len(avail_images))
        return avail_images

    def _parse_flavors(self):
        """Find flavors given to command line"""
        flavors = self._get_list_of_flavors(detail=True)

        if self.flavors is None:
            self.info("No --flavors given. Will use all of them")
            avail_flavors = flavors
        else:
            avail_flavors = self._find_flavors(self.flavors, flavors=flavors)

        self.info("Found %s flavors to choose from", len(avail_flavors))
        return avail_flavors

66
    def _try_until_timeout_expires(self, opmsg, check_fun):
67 68 69 70 71 72 73 74
        """Try to perform an action until timeout expires"""
        assert callable(check_fun), "Not a function"

        action_timeout = self.action_timeout
        action_warning = self.action_warning
        if action_warning > action_timeout:
            action_warning = action_timeout

75 76 77
        start_time = int(time.time())
        end_time = start_time + action_warning
        while end_time > time.time():
78
            try:
79 80 81 82
                ret_value = check_fun()
                self.info("Operation `%s' finished in %s seconds",
                          opmsg, int(time.time()) - start_time)
                return ret_value
83 84
            except Retry:
                time.sleep(self.query_interval)
85 86 87 88 89
        self.warning("Operation `%s' is taking too long after %s seconds",
                     opmsg, int(time.time()) - start_time)

        end_time = start_time + action_timeout
        while end_time > time.time():
90
            try:
91 92 93 94
                ret_value = check_fun()
                self.info("Operation `%s' finished in %s seconds",
                          opmsg, int(time.time()) - start_time)
                return ret_value
95 96
            except Retry:
                time.sleep(self.query_interval)
97 98
        self.error("Operation `%s' timed out after %s seconds",
                   opmsg, int(time.time()) - start_time)
99 100
        self.fail("time out")

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    def _try_once(self, opmsg, check_fun, should_fail=False):
        """Try to perform an action once"""
        assert callable(check_fun), "Not a function"
        ret_value = None
        failed = False
        try:
            ret_value = check_fun()
        except Retry:
            failed = True

        if failed and not should_fail:
            self.error("Operation `%s' failed", opmsg)
        elif not failed and should_fail:
            self.error("Operation `%s' should have failed", opmsg)
        else:
            return ret_value

118 119 120 121 122 123 124 125
    def _get_list_of_servers(self, detail=False):
        """Get (detailed) list of servers"""
        if detail:
            self.info("Getting detailed list of servers")
        else:
            self.info("Getting simple list of servers")
        return self.clients.cyclades.list_servers(detail=detail)

126 127 128 129 130 131
    def _get_list_of_networks(self, detail=False):
        """Get (detailed) list of networks"""
        if detail:
            self.info("Getting detailed list of networks")
        else:
            self.info("Getting simple list of networks")
132
        return self.clients.network.list_networks(detail=detail)
133 134

    def _get_server_details(self, server, quiet=False):
135
        """Get details for a server"""
136 137 138
        if not quiet:
            self.info("Getting details for server %s with id %s",
                      server['name'], server['id'])
139 140
        return self.clients.cyclades.get_server_details(server['id'])

141 142 143
    # pylint: disable=too-many-arguments
    def _create_server(self, image, flavor, personality=None,
                       network=False, project_id=None):
144
        """Create a new server"""
145
        if network:
146
            fip = self._create_floating_ip(project_id=project_id)
147 148 149 150 151 152
            port = self._create_port(fip['floating_network_id'],
                                     floating_ip=fip)
            networks = [{'port': port['id']}]
        else:
            networks = None

153 154
        name = image.get('name', image.get('display_name', ''))
        servername = "%s for %s" % (self.run_id, name)
155
        self.info("Creating a server with name %s", servername)
156
        self.info("Using image %s with id %s", name, image['id'])
157 158
        self.info("Using flavor %s with id %s", flavor['name'], flavor['id'])
        server = self.clients.cyclades.create_server(
159
            servername, flavor['id'], image['id'],
160
            personality=personality, networks=networks,
161
            project_id=project_id)
162 163 164 165

        self.info("Server id: %s", server['id'])
        self.info("Server password: %s", server['adminPass'])

166
        self.assertEqual(server['name'], servername)
167 168 169
        self.assertEqual(server['flavor']['id'], flavor['id'])
        self.assertEqual(server['image']['id'], image['id'])
        self.assertEqual(server['status'], "BUILD")
170 171 172
        if project_id is None:
            project_id = self._get_uuid()
        self.assertEqual(server['tenant_id'], project_id)
173

Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
174
        # Verify quotas
175 176 177 178 179 180 181
        changes = \
            {project_id:
                [(QDISK, QADD, flavor['disk'], GB),
                 (QVM, QADD, 1, None),
                 (QRAM, QADD, flavor['ram'], MB),
                 (QCPU, QADD, flavor['vcpus'], None)]}
        self._check_quotas(changes)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
182

183 184
        return server

185 186 187
    def _delete_servers(self, servers, error=False):
        """Deleting a number of servers in parallel"""
        # Disconnect floating IPs
188 189 190 191 192 193 194 195
        if not error:
            # If there is the possibility for the machine to be in
            # ERROR state we cannot delete its ports.
            for srv in servers:
                self.info(
                    "Disconnecting all floating IPs from server with id %s",
                    srv['id'])
                self._disconnect_from_network(srv)
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

        # Delete servers
        for srv in servers:
            self.info("Sending the delete request for server with id %s",
                      srv['id'])
            self.clients.cyclades.delete_server(srv['id'])

        if error:
            curr_states = ["ACTIVE", "ERROR", "STOPPED", "BUILD"]
        else:
            curr_states = ["ACTIVE"]
        for srv in servers:
            self._insist_on_server_transition(srv, curr_states, "DELETED")

        # Servers no longer in server list
        new_servers = [s['id'] for s in self._get_list_of_servers()]
        for srv in servers:
            self.info("Verifying that server with id %s is no longer in "
                      "server list", srv['id'])
            self.assertNotIn(srv['id'], new_servers)

        # Verify quotas
218
        self._verify_quotas_deleted(servers)
219

220
    def _verify_quotas_deleted(self, servers):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
221
        """Verify quotas for a number of deleted servers"""
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        changes = dict()
        for server in servers:
            project = server['tenant_id']
            if project not in changes:
                changes[project] = []
            flavor = \
                self.clients.compute.get_flavor_details(server['flavor']['id'])
            new_changes = [
                (QDISK, QREMOVE, flavor['disk'], GB),
                (QVM, QREMOVE, 1, None),
                (QRAM, QREMOVE, flavor['ram'], MB),
                (QCPU, QREMOVE, flavor['vcpus'], None)]
            changes[project].extend(new_changes)

        self._check_quotas(changes)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
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
    def _get_connection_username(self, server):
        """Determine the username to use to connect to the server"""
        users = server['metadata'].get("users", None)
        ret_user = None
        if users is not None:
            user_list = users.split()
            if "root" in user_list:
                ret_user = "root"
            else:
                ret_user = random.choice(user_list)
        else:
            # Return the login name for connections based on the server OS
            self.info("Could not find `users' metadata in server. Let's guess")
            os_value = server['metadata'].get("os")
            if os_value in ("Ubuntu", "Kubuntu", "Fedora"):
                ret_user = "user"
            elif os_value in ("windows", "windows_alpha1"):
                ret_user = "Administrator"
            else:
                ret_user = "root"

        self.assertIsNotNone(ret_user)
        self.info("User's login name: %s", ret_user)
        return ret_user

263 264
    def _insist_on_server_transition(self, server, curr_statuses, new_status):
        """Insist on server transiting from curr_statuses to new_status"""
265 266
        def check_fun():
            """Check server status"""
267 268
            srv = self._get_server_details(server, quiet=True)
            if srv['status'] in curr_statuses:
269 270 271 272
                raise Retry()
            elif srv['status'] == new_status:
                return
            else:
273 274 275
                msg = "Server \"%s\" with id %s went to unexpected status %s"
                self.error(msg, server['name'], server['id'], srv['status'])
                self.fail(msg % (server['name'], server['id'], srv['status']))
276 277 278
        opmsg = "Waiting for server \"%s\" with id %s to become %s"
        self.info(opmsg, server['name'], server['id'], new_status)
        opmsg = opmsg % (server['name'], server['id'], new_status)
279 280
        self._try_until_timeout_expires(opmsg, check_fun)

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
    def _insist_on_snapshot_transition(self, snapshot,
                                       curr_statuses, new_status):
        """Insist on snapshot transiting from curr_statuses to new_status"""
        def check_fun():
            """Check snapstho status"""
            snap = \
                self.clients.block_storage.get_snapshot_details(snapshot['id'])
            if snap['status'] in curr_statuses:
                raise Retry()
            elif snap['status'] == new_status:
                return
            else:
                msg = "Snapshot \"%s\" with id %s went to unexpected status %s"
                self.error(msg, snapshot['display_name'],
                           snapshot['id'], snap['status'])
        opmsg = "Waiting for snapshot \"%s\" with id %s to become %s"
        self.info(opmsg, snapshot['display_name'], snapshot['id'], new_status)
        opmsg = opmsg % (snapshot['display_name'], snapshot['id'], new_status)
        self._try_until_timeout_expires(opmsg, check_fun)

    def _insist_on_snapshot_deletion(self, snapshot_id):
        """Insist on snapshot deletion"""
        def check_fun():
            """Check snapshot details"""
            try:
                self.clients.block_storage.get_snapshot_details(snapshot_id)
            except ClientError as err:
                if err.status != 404:
                    raise
            else:
                raise Retry()
        opmsg = "Waiting for snapshot %s to be deleted"
        self.info(opmsg, snapshot_id)
        opmsg = opmsg % snapshot_id
        self._try_until_timeout_expires(opmsg, check_fun)

317 318 319 320 321
    def _insist_on_network_transition(self, network,
                                      curr_statuses, new_status):
        """Insist on network transiting from curr_statuses to new_status"""
        def check_fun():
            """Check network status"""
322
            ntw = self.clients.network.get_network_details(network['id'])
323 324 325 326 327 328 329 330 331
            if ntw['status'] in curr_statuses:
                raise Retry()
            elif ntw['status'] == new_status:
                return
            else:
                msg = "Network %s with id %s went to unexpected status %s"
                self.error(msg, network['name'], network['id'], ntw['status'])
                self.fail(msg %
                          (network['name'], network['id'], ntw['status']))
332 333 334
        opmsg = "Waiting for network \"%s\" with id %s to become %s"
        self.info(opmsg, network['name'], network['id'], new_status)
        opmsg = opmsg % (network['name'], network['id'], new_status)
335 336
        self._try_until_timeout_expires(opmsg, check_fun)

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
    def _insist_on_tcp_connection(self, family, host, port):
        """Insist on tcp connection"""
        def check_fun():
            """Get a connected socket from the specified family to host:port"""
            sock = None
            for res in socket.getaddrinfo(host, port, family,
                                          socket.SOCK_STREAM, 0,
                                          socket.AI_PASSIVE):
                fam, socktype, proto, _, saddr = res
                try:
                    sock = socket.socket(fam, socktype, proto)
                except socket.error:
                    sock = None
                    continue
                try:
                    sock.connect(saddr)
                except socket.error:
                    sock.close()
                    sock = None
                    continue
            if sock is None:
                raise Retry
            return sock
        familystr = {socket.AF_INET: "IPv4", socket.AF_INET6: "IPv6",
                     socket.AF_UNSPEC: "Unspecified-IPv4/6"}
        opmsg = "Connecting over %s to %s:%s"
        self.info(opmsg, familystr.get(family, "Unknown"), host, port)
        opmsg = opmsg % (familystr.get(family, "Unknown"), host, port)
        return self._try_until_timeout_expires(opmsg, check_fun)

367 368
    def _get_ips(self, server, version=4, network=None):
        """Get the IPs of a server from the detailed server info
369

370
        If network not given then get the public IPs. Else the IPs
371 372 373
        attached to that network

        """
374 375 376
        assert version in (4, 6)

        nics = server['attachments']
377
        addrs = []
378 379
        for nic in nics:
            net_id = nic['network_id']
380
            if network is None:
381
                if self.clients.network.get_network_details(net_id)['public']:
382
                    if nic['ipv' + str(version)]:
383
                        addrs.append(nic['ipv' + str(version)])
384 385
            else:
                if net_id == network['id']:
386
                    if nic['ipv' + str(version)]:
387 388 389 390 391 392
                        addrs.append(nic['ipv' + str(version)])

        self.assertGreater(len(addrs), 0,
                           "Can not get IPs from server attachments")

        for addr in addrs:
393
            self.assertEqual(IPy.IP(addr).version(), version)
394

395 396
        if network is None:
            msg = "Server's public IPv%s is %s"
397 398
            for addr in addrs:
                self.info(msg, version, addr)
399 400
        else:
            msg = "Server's IPv%s attached to network \"%s\" is %s"
401 402
            for addr in addrs:
                self.info(msg, version, network['id'], addr)
403
        return addrs
404

405
    def _insist_on_ping(self, ip_addr, version=4, should_fail=False):
406 407 408 409 410 411 412 413 414 415 416 417
        """Test server responds to a single IPv4 of IPv6 ping"""
        def check_fun():
            """Ping to server"""
            cmd = ("ping%s -c 3 -w 20 %s" %
                   ("6" if version == 6 else "", ip_addr))
            ping = subprocess.Popen(
                cmd, shell=True, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            ping.communicate()
            ret = ping.wait()
            if ret != 0:
                raise Retry
418
        assert version in (4, 6)
419 420 421
        opmsg = "Sent IPv%s ping requests to %s"
        self.info(opmsg, version, ip_addr)
        opmsg = opmsg % (version, ip_addr)
422 423 424 425
        if should_fail:
            self._try_once(opmsg, check_fun, should_fail=True)
        else:
            self._try_until_timeout_expires(opmsg, check_fun)
426

427 428 429 430 431
    def _image_is(self, image, osfamily):
        """Return true if the image is of `osfamily'"""
        d_image = self.clients.cyclades.get_image_details(image['id'])
        return d_image['metadata']['osfamily'].lower().find(osfamily) >= 0

432
    # pylint: disable=no-self-use
433 434 435 436 437 438
    def _ssh_execute(self, hostip, username, password, command):
        """Execute a command via ssh"""
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(hostip, username=username, password=password)
439
        except paramiko.SSHException as err:
440 441
            self.warning("%s", err.message)
            raise Retry()
442
        _, stdout, _ = ssh.exec_command(command)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        status = stdout.channel.recv_exit_status()
        output = stdout.readlines()
        ssh.close()
        return output, status

    def _insist_get_hostname_over_ssh(self, hostip, username, password):
        """Connect to server using ssh and get it's hostname"""
        def check_fun():
            """Get hostname"""
            try:
                lines, status = self._ssh_execute(
                    hostip, username, password, "hostname")
                self.assertEqual(status, 0)
                self.assertEqual(len(lines), 1)
                # Remove new line
                return lines[0].strip('\n')
            except AssertionError:
                raise Retry()
        opmsg = "Connecting to server using ssh and get it's hostname"
        self.info(opmsg)
        hostname = self._try_until_timeout_expires(opmsg, check_fun)
        self.info("Server's hostname is %s", hostname)
        return hostname

467
    # pylint: disable=too-many-arguments
468 469 470
    def _check_file_through_ssh(self, hostip, username, password,
                                remotepath, content):
        """Fetch file from server and compare contents"""
471 472 473 474 475 476 477 478 479 480 481 482 483
        def check_fun():
            """Fetch file"""
            try:
                transport = paramiko.Transport((hostip, 22))
                transport.connect(username=username, password=password)
                with tempfile.NamedTemporaryFile() as ftmp:
                    sftp = paramiko.SFTPClient.from_transport(transport)
                    sftp.get(remotepath, ftmp.name)
                    sftp.close()
                    transport.close()
                    self.info("Comparing file contents")
                    remote_content = base64.b64encode(ftmp.read())
                    self.assertEqual(content, remote_content)
484 485 486
            except paramiko.SSHException as err:
                self.warning("%s", err.message)
                raise Retry()
487 488 489
        opmsg = "Fetching file %s from remote server" % remotepath
        self.info(opmsg)
        self._try_until_timeout_expires(opmsg, check_fun)
490

491 492
    # ----------------------------------
    # Networks
493 494
    def _create_network(self, cidr="10.0.1.0/28", dhcp=True,
                        project_id=None):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
495
        """Create a new private network"""
496 497
        name = self.run_id
        network = self.clients.network.create_network(
498
            "MAC_FILTERED", name=name, shared=False,
499
            project_id=project_id)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
500
        self.info("Network with id %s created", network['id'])
501 502 503
        subnet = self.clients.network.create_subnet(
            network['id'], cidr=cidr, enable_dhcp=dhcp)
        self.info("Subnet with id %s created", subnet['id'])
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
504 505

        # Verify quotas
506 507 508 509 510
        if project_id is None:
            project_id = self._get_uuid()
        changes = \
            {project_id: [(QNET, QADD, 1, None)]}
        self._check_quotas(changes)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
511

512
        # Test if the right name is assigned
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
513
        self.assertEqual(network['name'], name)
514
        self.assertEqual(network['tenant_id'], project_id)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
515 516 517

        return network

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    def _delete_networks(self, networks, error=False):
        """Delete a network"""
        for net in networks:
            self.info("Deleting network with id %s", net['id'])
            self.clients.network.delete_network(net['id'])

        if error:
            curr_states = ["ACTIVE", "SNF:DRAINED", "ERROR"]
        else:
            curr_states = ["ACTIVE", "SNF:DRAINED"]
        for net in networks:
            self._insist_on_network_transition(net, curr_states, "DELETED")

        # Networks no longer in network list
        new_networks = [n['id'] for n in self._get_list_of_networks()]
        for net in networks:
            self.info("Verifying that network with id %s is no longer in "
                      "network list", net['id'])
            self.assertNotIn(net['id'], new_networks)

        # Verify quotas
539 540 541
        changes = \
            {self._get_uuid(): [(QNET, QREMOVE, len(networks), None)]}
        self._check_quotas(changes)
542

543 544
    def _get_public_networks(self, networks=None):
        """Get the public networks"""
545 546
        if networks is None:
            networks = self._get_list_of_networks(detail=True)
547 548
        self.info("Getting the public networks")
        public_networks = []
549 550
        for net in networks:
            if net['SNF:floating_ip_pool'] and net['public']:
551 552 553 554 555
                public_networks.append(net)

        self.assertNotEqual(public_networks, [],
                            "Could not find a public network to use")
        return public_networks
556

557
    def _create_floating_ip(self, project_id=None):
558
        """Create a new floating ip"""
559 560 561 562 563
        pub_nets = self._get_public_networks()
        for pub_net in pub_nets:
            self.info("Creating a new floating ip for network with id %s",
                      pub_net['id'])
            try:
564
                fip = self.clients.network.create_floatingip(
565
                    pub_net['id'], project_id=project_id)
566 567 568 569 570 571 572
            except ClientError as err:
                self.warning("%s: %s", err.message, err.details)
                continue
            # Verify that floating ip has been created
            fips = self.clients.network.list_floatingips()
            fips = [f['id'] for f in fips]
            self.assertIn(fip['id'], fips)
573

574
            # Verify quotas
575 576 577 578 579
            if project_id is None:
                project_id = self._get_uuid()
            changes = \
                {project_id: [(QIP, QADD, 1, None)]}
            self._check_quotas(changes)
580 581 582 583 584 585
            # Check that IP is IPv4
            self.assertEquals(IPy.IP(fip['floating_ip_address']).version(), 4)

            self.info("Floating IP %s with id %s created",
                      fip['floating_ip_address'], fip['id'])
            return fip
586

587
        self.fail("No more IP addresses available")
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

    def _create_port(self, network_id, device_id=None, floating_ip=None):
        """Create a new port attached to the a specific network"""
        self.info("Creating a new port to network with id %s", network_id)
        if floating_ip is not None:
            fixed_ips = [{'ip_address': floating_ip['floating_ip_address']}]
        else:
            fixed_ips = None
        port = self.clients.network.create_port(network_id,
                                                device_id=device_id,
                                                fixed_ips=fixed_ips)
        # Verify that port created
        ports = self.clients.network.list_ports()
        ports = [p['id'] for p in ports]
        self.assertIn(port['id'], ports)
        # Insist on creation
        if device_id is None:
            self._insist_on_port_transition(port, ["BUILD"], "DOWN")
        else:
            self._insist_on_port_transition(port, ["BUILD", "DOWN"], "ACTIVE")

        self.info("Port with id %s created", port['id'])
        return port

    def _insist_on_port_transition(self, port, curr_statuses, new_status):
        """Insist on port transiting from curr_statuses to new_status"""
        def check_fun():
            """Check port status"""
            portd = self.clients.network.get_port_details(port['id'])
            if portd['status'] in curr_statuses:
                raise Retry()
            elif portd['status'] == new_status:
                return
            else:
                msg = "Port %s went to unexpected status %s"
                self.fail(msg % (portd['id'], portd['status']))
        opmsg = "Waiting for port %s to become %s"
        self.info(opmsg, port['id'], new_status)
        opmsg = opmsg % (port['id'], new_status)
        self._try_until_timeout_expires(opmsg, check_fun)

    def _insist_on_port_deletion(self, portid):
        """Insist on port deletion"""
        def check_fun():
            """Check port details"""
            try:
                self.clients.network.get_port_details(portid)
            except ClientError as err:
                if err.status != 404:
                    raise
            else:
                raise Retry()
        opmsg = "Waiting for port %s to be deleted"
        self.info(opmsg, portid)
        opmsg = opmsg % portid
        self._try_until_timeout_expires(opmsg, check_fun)

    def _disconnect_from_network(self, server, network=None):
        """Disconnnect server from network"""
        if network is None:
648 649 650 651
            # Disconnect from all public networks
            for net in self._get_public_networks():
                self._disconnect_from_network(server, network=net)
            return
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

        lports = self.clients.network.list_ports()
        ports = []
        for port in lports:
            dport = self.clients.network.get_port_details(port['id'])
            if str(dport['network_id']) == str(network['id']) \
                    and str(dport['device_id']) == str(server['id']):
                ports.append(dport)

        # Find floating IPs attached to these ports
        ports_id = [p['id'] for p in ports]
        fips = [f for f in self.clients.network.list_floatingips()
                if str(f['port_id']) in ports_id]

        # First destroy the ports
        for port in ports:
            self.info("Destroying port with id %s", port['id'])
            self.clients.network.delete_port(port['id'])
            self._insist_on_port_deletion(port['id'])

        # Then delete the floating IPs
673 674 675 676
        self._delete_floating_ips(fips)

    def _delete_floating_ips(self, fips):
        """Delete floating ips"""
677 678
        # Renew the list of floating IP objects
        # (It may have been changed, i.e. a port may have been deleted).
679 680
        if not fips:
            return
681 682 683 684 685
        fip_ids = [f['id'] for f in fips]
        new_fips = [f for f in self.clients.network.list_floatingips()
                    if f['id'] in fip_ids]

        for fip in new_fips:
686 687 688 689 690 691
            port_id = fip['port_id']
            if port_id:
                self.info("Destroying port with id %s", port_id)
                self.clients.network.delete_port(port_id)
                self._insist_on_port_deletion(port_id)

692 693 694 695 696 697 698 699
            self.info("Destroying floating IP %s with id %s",
                      fip['floating_ip_address'], fip['id'])
            self.clients.network.delete_floatingip(fip['id'])

        # Check that floating IPs have been deleted
        list_ips = [f['id'] for f in self.clients.network.list_floatingips()]
        for fip in fips:
            self.assertNotIn(fip['id'], list_ips)
700

701
        # Verify quotas
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
        changes = dict()
        for fip in fips:
            project = fip['tenant_id']
            if project not in changes:
                changes[project] = []
            changes[project].append((QIP, QREMOVE, 1, None))
        self._check_quotas(changes)

    def _find_project(self, flavors, projects=None):
        """Return a pair of flavor, project that we can use"""
        if projects is None:
            projects = self.quotas.keys()

        # XXX: Well there seems to be no easy way to find how many resources
        # we have left in a project (we have to substract usage from limit,
        # check both per_user and project quotas, blah, blah). For now
        # just return the first flavor with the first project and lets hope
        # that it fits.
        return (flavors[0], projects[0])

        # # Get only the quotas for the given 'projects'
        # quotas = dict()
        # for prj, qts in self.quotas.items():
        #     if prj in projects:
        #         quotas[prj] = qts
        #
        # results = []
        # for flv in flavors:
        #     for prj, qts in quotas.items():
        #         self.debug("Testing flavor %s, project %s", flv['name'], prj)
        #         condition = \
        #             (flv['ram'] <= qts['cyclades.ram']['usage'] and
        #              flv['vcpus'] <= qts['cyclades.cpu']['usage'] and
        #              flv['disk'] <= qts['cyclades.disk']['usage'] and
        #              qts['cyclades.vm']['usage'] >= 1)
        #         if condition:
        #             results.append((flv, prj))
        #
        # if not results:
        #     msg = "Couldn't find a suitable flavor to use for current qutoas"
        #     self.error(msg)
        #
        # return random.choice(results)
745

746 747 748 749 750 751 752

class Retry(Exception):
    """Retry the action

    This is used by _try_unit_timeout_expires method.

    """