Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / tools / burnin.py @ 08748d73

History | View | Annotate | Download (48.2 kB)

1
#!/usr/bin/env python
2

    
3
# Copyright 2011 GRNET S.A. All rights reserved.
4
#
5
# Redistribution and use in source and binary forms, with or
6
# without modification, are permitted provided that the following
7
# conditions are met:
8
#
9
#   1. Redistributions of source code must retain the above
10
#      copyright notice, this list of conditions and the following
11
#      disclaimer.
12
#
13
#   2. Redistributions in binary form must reproduce the above
14
#      copyright notice, this list of conditions and the following
15
#      disclaimer in the documentation and/or other materials
16
#      provided with the distribution.
17
#
18
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
# POSSIBILITY OF SUCH DAMAGE.
30
#
31
# The views and conclusions contained in the software and
32
# documentation are those of the authors and should not be
33
# interpreted as representing official policies, either expressed
34
# or implied, of GRNET S.A.
35

    
36
"""Perform integration testing on a running Synnefo deployment"""
37

    
38
import __main__
39
import datetime
40
import inspect
41
import logging
42
import os
43
import paramiko
44
import prctl
45
import subprocess
46
import signal
47
import socket
48
import struct
49
import sys
50
import time
51
import hashlib
52
from base64 import b64encode
53
from pwd import getpwuid
54
from grp import getgrgid
55
from IPy import IP
56
from multiprocessing import Process, Queue
57
from random import choice
58

    
59
from kamaki.clients.compute import ComputeClient
60
from kamaki.clients.cyclades import CycladesClient
61

    
62

    
63
from vncauthproxy.d3des import generate_response as d3des_generate_response
64

    
65
# Use backported unittest functionality if Python < 2.7
66
try:
67
    import unittest2 as unittest
68
except ImportError:
69
    if sys.version_info < (2, 7):
70
        raise Exception("The unittest2 package is required for Python < 2.7")
71
    import unittest
72

    
73

    
74
API = None
75
TOKEN = None
76
DEFAULT_API = "https://cyclades.okeanos.grnet.gr/api/v1.1"
77

    
78
# A unique id identifying this test run
79
TEST_RUN_ID = datetime.datetime.strftime(datetime.datetime.now(),
80
                                         "%Y%m%d%H%M%S")
81
SNF_TEST_PREFIX = "snf-test-"
82

    
83
# Setup logging (FIXME - verigak)
84
logging.basicConfig(format="%(message)s")
85
log = logging.getLogger("burnin")
86
log.setLevel(logging.INFO)
87

    
88
class UnauthorizedTestCase(unittest.TestCase):
89
    def test_unauthorized_access(self):
90
        """Test access without a valid token fails"""
91
        falseToken = '12345'
92
        c=ComputeClient(API, falseToken)
93

    
94
        with self.assertRaises(ClientError) as cm:
95
            c.list_servers()
96
        self.assertEqual(cm.exception.status, 401)
97

    
98

    
99
class ImagesTestCase(unittest.TestCase):
100
    """Test image lists for consistency"""
101
    @classmethod
102
    def setUpClass(cls):
103
        """Initialize kamaki, get (detailed) list of images"""
104
        log.info("Getting simple and detailed list of images")
105

    
106
        cls.client = ComputeClient(API, TOKEN)
107
        cls.images = cls.client.list_images()
108
        cls.dimages = cls.client.list_images(detail=True)
109

    
110
    def test_001_list_images(self):
111
        """Test image list actually returns images"""
112
        self.assertGreater(len(self.images), 0)
113

    
114
    def test_002_list_images_detailed(self):
115
        """Test detailed image list is the same length as list"""
116
        self.assertEqual(len(self.dimages), len(self.images))
117

    
118
    def test_003_same_image_names(self):
119
        """Test detailed and simple image list contain same names"""
120
        names = sorted(map(lambda x: x["name"], self.images))
121
        dnames = sorted(map(lambda x: x["name"], self.dimages))
122
        self.assertEqual(names, dnames)
123

    
124
    def test_004_unique_image_names(self):
125
        """Test images have unique names"""
126
        names = sorted(map(lambda x: x["name"], self.images))
127
        self.assertEqual(sorted(list(set(names))), names)
128

    
129
    def test_005_image_metadata(self):
130
        """Test every image has specific metadata defined"""
131
        keys = frozenset(["os", "description", "size"])
132
        for i in self.dimages:
133
            self.assertTrue(keys.issubset(i["metadata"]["values"].keys()))
134

    
135

    
136
class FlavorsTestCase(unittest.TestCase):
137
    """Test flavor lists for consistency"""
138
    @classmethod
139
    def setUpClass(cls):
140
        """Initialize kamaki, get (detailed) list of flavors"""
141
        log.info("Getting simple and detailed list of flavors")
142

    
143
        cls.client = ComputeClient(API, TOKEN)
144
        cls.flavors = cls.client.list_flavors()
145
        cls.dflavors = cls.client.list_flavors(detail=True)
146

    
147
    def test_001_list_flavors(self):
148
        """Test flavor list actually returns flavors"""
149
        self.assertGreater(len(self.flavors), 0)
150

    
151
    def test_002_list_flavors_detailed(self):
152
        """Test detailed flavor list is the same length as list"""
153
        self.assertEquals(len(self.dflavors), len(self.flavors))
154

    
155
    def test_003_same_flavor_names(self):
156
        """Test detailed and simple flavor list contain same names"""
157
        names = sorted(map(lambda x: x["name"], self.flavors))
158
        dnames = sorted(map(lambda x: x["name"], self.dflavors))
159
        self.assertEqual(names, dnames)
160

    
161
    def test_004_unique_flavor_names(self):
162
        """Test flavors have unique names"""
163
        names = sorted(map(lambda x: x["name"], self.flavors))
164
        self.assertEqual(sorted(list(set(names))), names)
165

    
166
    def test_005_well_formed_flavor_names(self):
167
        """Test flavors have names of the form CxxRyyDzz
168

169
        Where xx is vCPU count, yy is RAM in MiB, zz is Disk in GiB
170

171
        """
172
        for f in self.dflavors:
173
            self.assertEqual("C%dR%dD%d" % (f["cpu"], f["ram"], f["disk"]),
174
                             f["name"],
175
                             "Flavor %s does not match its specs." % f["name"])
176

    
177

    
178
class ServersTestCase(unittest.TestCase):
179
    """Test server lists for consistency"""
180
    @classmethod
181
    def setUpClass(cls):
182
        """Initialize kamaki, get (detailed) list of servers"""
183
        log.info("Getting simple and detailed list of servers")
184

    
185
        cls.client = ComputeClient(API, TOKEN)
186
        cls.servers = cls.client.list_servers()
187
        cls.dservers = cls.client.list_servers(detail=True)
188

    
189
    def test_001_list_servers(self):
190
        """Test server list actually returns servers"""
191
        self.assertGreater(len(self.servers), 0)
192

    
193
    def test_002_list_servers_detailed(self):
194
        """Test detailed server list is the same length as list"""
195
        self.assertEqual(len(self.dservers), len(self.servers))
196

    
197
    def test_003_same_server_names(self):
198
        """Test detailed and simple flavor list contain same names"""
199
        names = sorted(map(lambda x: x["name"], self.servers))
200
        dnames = sorted(map(lambda x: x["name"], self.dservers))
201
        self.assertEqual(names, dnames)
202

    
203

    
204
# This class gets replicated into actual TestCases dynamically
205
class SpawnServerTestCase(unittest.TestCase):
206
    """Test scenario for server of the specified image"""
207

    
208
    @classmethod
209
    def setUpClass(cls):
210
        """Initialize a kamaki instance"""
211
        log.info("Spawning server for image `%s'", cls.imagename)
212

    
213
        cls.client = ComputeClient(API, TOKEN)
214
        cls.cyclades = CycladesClient(API, TOKEN)
215

    
216
    def _get_ipv4(self, server):
217
        """Get the public IPv4 of a server from the detailed server info"""
218

    
219
        public_addrs = filter(lambda x: x["id"] == "public",
220
                              server["addresses"]["values"])
221
        self.assertEqual(len(public_addrs), 1)
222
        ipv4_addrs = filter(lambda x: x["version"] == 4,
223
                            public_addrs[0]["values"])
224
        self.assertEqual(len(ipv4_addrs), 1)
225
        return ipv4_addrs[0]["addr"]
226

    
227
    def _get_ipv6(self, server):
228
        """Get the public IPv6 of a server from the detailed server info"""
229
        public_addrs = filter(lambda x: x["id"] == "public",
230
                              server["addresses"]["values"])
231
        self.assertEqual(len(public_addrs), 1)
232
        ipv6_addrs = filter(lambda x: x["version"] == 6,
233
                            public_addrs[0]["values"])
234
        self.assertEqual(len(ipv6_addrs), 1)
235
        return ipv6_addrs[0]["addr"]
236

    
237
    def _connect_loginname(self, os):
238
        """Return the login name for connections based on the server OS"""
239
        if os in ("Ubuntu", "Kubuntu", "Fedora"):
240
            return "user"
241
        elif os in ("windows", "windows_alpha1"):
242
            return "Administrator"
243
        else:
244
            return "root"
245

    
246
    def _verify_server_status(self, current_status, new_status):
247
        """Verify a server has switched to a specified status"""
248
        server = self.client.get_server_details(self.serverid)
249
        if server["status"] not in (current_status, new_status):
250
            return None  # Do not raise exception, return so the test fails
251
        self.assertEquals(server["status"], new_status)
252

    
253
    def _get_connected_tcp_socket(self, family, host, port):
254
        """Get a connected socket from the specified family to host:port"""
255
        sock = None
256
        for res in \
257
            socket.getaddrinfo(host, port, family, socket.SOCK_STREAM, 0,
258
                               socket.AI_PASSIVE):
259
            af, socktype, proto, canonname, sa = res
260
            try:
261
                sock = socket.socket(af, socktype, proto)
262
            except socket.error as msg:
263
                sock = None
264
                continue
265
            try:
266
                sock.connect(sa)
267
            except socket.error as msg:
268
                sock.close()
269
                sock = None
270
                continue
271
        self.assertIsNotNone(sock)
272
        return sock
273

    
274
    def _ping_once(self, ipv6, ip):
275
        """Test server responds to a single IPv4 or IPv6 ping"""
276
        cmd = "ping%s -c 2 -w 3 %s" % ("6" if ipv6 else "", ip)
277
        ping = subprocess.Popen(cmd, shell=True,
278
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
279
        (stdout, stderr) = ping.communicate()
280
        ret = ping.wait()
281
        self.assertEquals(ret, 0)
282

    
283
    def _get_hostname_over_ssh(self, hostip, username, password):
284
        ssh = paramiko.SSHClient()
285
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
286
        try:
287
            ssh.connect(hostip, username=username, password=password)
288
        except socket.error:
289
            raise AssertionError
290
        stdin, stdout, stderr = ssh.exec_command("hostname")
291
        lines = stdout.readlines()
292
        self.assertEqual(len(lines), 1)
293
        return lines[0]
294

    
295
    def _try_until_timeout_expires(self, warn_timeout, fail_timeout,
296
                                   opmsg, callable, *args, **kwargs):
297
        if warn_timeout == fail_timeout:
298
            warn_timeout = fail_timeout + 1
299
        warn_tmout = time.time() + warn_timeout
300
        fail_tmout = time.time() + fail_timeout
301
        while True:
302
            self.assertLess(time.time(), fail_tmout,
303
                            "operation `%s' timed out" % opmsg)
304
            if time.time() > warn_tmout:
305
                log.warning("Server %d: `%s' operation `%s' not done yet",
306
                            self.serverid, self.servername, opmsg)
307
            try:
308
                log.info("%s... " % opmsg)
309
                return callable(*args, **kwargs)
310
            except AssertionError:
311
                pass
312
            time.sleep(self.query_interval)
313

    
314
    def _insist_on_tcp_connection(self, family, host, port):
315
        familystr = {socket.AF_INET: "IPv4", socket.AF_INET6: "IPv6",
316
                     socket.AF_UNSPEC: "Unspecified-IPv4/6"}
317
        msg = "connect over %s to %s:%s" % \
318
              (familystr.get(family, "Unknown"), host, port)
319
        sock = self._try_until_timeout_expires(
320
                self.action_timeout, self.action_timeout,
321
                msg, self._get_connected_tcp_socket,
322
                family, host, port)
323
        return sock
324

    
325
    def _insist_on_status_transition(self, current_status, new_status,
326
                                    fail_timeout, warn_timeout=None):
327
        msg = "Server %d: `%s', waiting for %s -> %s" % \
328
              (self.serverid, self.servername, current_status, new_status)
329
        if warn_timeout is None:
330
            warn_timeout = fail_timeout
331
        self._try_until_timeout_expires(warn_timeout, fail_timeout,
332
                                        msg, self._verify_server_status,
333
                                        current_status, new_status)
334
        # Ensure the status is actually the expected one
335
        server = self.client.get_server_details(self.serverid)
336
        self.assertEquals(server["status"], new_status)
337

    
338
    def _insist_on_ssh_hostname(self, hostip, username, password):
339
        msg = "SSH to %s, as %s/%s" % (hostip, username, password)
340
        hostname = self._try_until_timeout_expires(
341
                self.action_timeout, self.action_timeout,
342
                msg, self._get_hostname_over_ssh,
343
                hostip, username, password)
344

    
345
        # The hostname must be of the form 'prefix-id'
346
        self.assertTrue(hostname.endswith("-%d\n" % self.serverid))
347

    
348
    def _check_file_through_ssh(self, hostip, username, password, remotepath, content):
349
        msg = "Trying file injection through SSH to %s, as %s/%s" % (hostip, username, password)
350
        log.info(msg)
351
        try:
352
            ssh = paramiko.SSHClient()
353
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
354
            ssh.connect(hostip, username=username, password=password)
355
        except socket.error:
356
            raise AssertionError
357
        
358
        transport = paramiko.Transport((hostip,22))
359
        transport.connect(username = username, password = password)
360

    
361
        localpath = '/tmp/'+SNF_TEST_PREFIX+'injection'
362
        sftp = paramiko.SFTPClient.from_transport(transport)
363
        sftp.get(remotepath, localpath)
364
        
365
        sftp.close()
366
        transport.close()
367

    
368
        f = open(localpath)
369
        remote_content = b64encode(f.read())
370

    
371
        # Check if files are the same
372
        return (remote_content == content)
373

    
374
    def _skipIf(self, condition, msg):
375
        if condition:
376
            self.skipTest(msg)
377

    
378
    def test_001_submit_create_server(self):
379
        """Test submit create server request"""
380
        server = self.client.create_server(self.servername, self.flavorid,
381
                                           self.imageid, self.personality)
382

    
383
        self.assertEqual(server["name"], self.servername)
384
        self.assertEqual(server["flavorRef"], self.flavorid)
385
        self.assertEqual(server["imageRef"], self.imageid)
386
        self.assertEqual(server["status"], "BUILD")
387

    
388
        # Update class attributes to reflect data on building server
389
        cls = type(self)
390
        cls.serverid = server["id"]
391
        cls.username = None
392
        cls.passwd = server["adminPass"]
393

    
394
    def test_002a_server_is_building_in_list(self):
395
        """Test server is in BUILD state, in server list"""
396
        servers = self.client.list_servers(detail=True)
397
        servers = filter(lambda x: x["name"] == self.servername, servers)
398
        self.assertEqual(len(servers), 1)
399
        server = servers[0]
400
        self.assertEqual(server["name"], self.servername)
401
        self.assertEqual(server["flavorRef"], self.flavorid)
402
        self.assertEqual(server["imageRef"], self.imageid)
403
        self.assertEqual(server["status"], "BUILD")
404

    
405
    def test_002b_server_is_building_in_details(self):
406
        """Test server is in BUILD state, in details"""
407
        server = self.client.get_server_details(self.serverid)
408
        self.assertEqual(server["name"], self.servername)
409
        self.assertEqual(server["flavorRef"], self.flavorid)
410
        self.assertEqual(server["imageRef"], self.imageid)
411
        self.assertEqual(server["status"], "BUILD")
412

    
413
    def test_002c_set_server_metadata(self):
414
        image = self.client.get_image_details(self.imageid)
415
        os = image["metadata"]["values"]["os"]
416
        loginname = image["metadata"]["values"].get("users", None)
417
        self.client.update_server_metadata(self.serverid, OS=os)
418

    
419
        # Determine the username to use for future connections
420
        # to this host
421
        cls = type(self)
422
        cls.username = loginname
423
        if not cls.username:
424
            cls.username = self._connect_loginname(os)
425
        self.assertIsNotNone(cls.username)
426

    
427
    def test_002d_verify_server_metadata(self):
428
        """Test server metadata keys are set based on image metadata"""
429
        servermeta = self.client.get_server_metadata(self.serverid)
430
        imagemeta = self.client.get_image_metadata(self.imageid)
431
        self.assertEqual(servermeta["OS"], imagemeta["os"])
432

    
433
    def test_003_server_becomes_active(self):
434
        """Test server becomes ACTIVE"""
435
        self._insist_on_status_transition("BUILD", "ACTIVE",
436
                                         self.build_fail, self.build_warning)
437

    
438
    def test_003a_get_server_oob_console(self):
439
        """Test getting OOB server console over VNC
440

441
        Implementation of RFB protocol follows
442
        http://www.realvnc.com/docs/rfbproto.pdf.
443

444
        """
445
        
446
        console = self.cyclades.get_server_console(self.serverid)
447
        self.assertEquals(console['type'], "vnc")
448
        sock = self._insist_on_tcp_connection(socket.AF_UNSPEC,
449
                                        console["host"], console["port"])
450

    
451
        # Step 1. ProtocolVersion message (par. 6.1.1)
452
        version = sock.recv(1024)
453
        self.assertEquals(version, 'RFB 003.008\n')
454
        sock.send(version)
455

    
456
        # Step 2. Security (par 6.1.2): Only VNC Authentication supported
457
        sec = sock.recv(1024)
458
        self.assertEquals(list(sec), ['\x01', '\x02'])
459

    
460
        # Step 3. Request VNC Authentication (par 6.1.2)
461
        sock.send('\x02')
462

    
463
        # Step 4. Receive Challenge (par 6.2.2)
464
        challenge = sock.recv(1024)
465
        self.assertEquals(len(challenge), 16)
466

    
467
        # Step 5. DES-Encrypt challenge, use password as key (par 6.2.2)
468
        response = d3des_generate_response(
469
            (console["password"] + '\0' * 8)[:8], challenge)
470
        sock.send(response)
471

    
472
        # Step 6. SecurityResult (par 6.1.3)
473
        result = sock.recv(4)
474
        self.assertEquals(list(result), ['\x00', '\x00', '\x00', '\x00'])
475
        sock.close()
476
        
477
    def test_004_server_has_ipv4(self):
478
        """Test active server has a valid IPv4 address"""
479
        server = self.client.get_server_details(self.serverid)
480
        ipv4 = self._get_ipv4(server)
481
        self.assertEquals(IP(ipv4).version(), 4)
482

    
483
    def test_005_server_has_ipv6(self):
484
        """Test active server has a valid IPv6 address"""
485
        server = self.client.get_server_details(self.serverid)
486
        ipv6 = self._get_ipv6(server)
487
        self.assertEquals(IP(ipv6).version(), 6)
488

    
489
    def test_006_server_responds_to_ping_IPv4(self):
490
        """Test server responds to ping on IPv4 address"""
491
        server = self.client.get_server_details(self.serverid)
492
        ip = self._get_ipv4(server)
493
        self._try_until_timeout_expires(self.action_timeout,
494
                                        self.action_timeout,
495
                                        "PING IPv4 to %s" % ip,
496
                                        self._ping_once,
497
                                        False, ip)
498

    
499
    def test_007_server_responds_to_ping_IPv6(self):
500
        """Test server responds to ping on IPv6 address"""
501
        server = self.client.get_server_details(self.serverid)
502
        ip = self._get_ipv6(server)
503
        self._try_until_timeout_expires(self.action_timeout,
504
                                        self.action_timeout,
505
                                        "PING IPv6 to %s" % ip,
506
                                        self._ping_once,
507
                                        True, ip)
508

    
509
    def test_008_submit_shutdown_request(self):
510
        """Test submit request to shutdown server"""
511
        self.cyclades.shutdown_server(self.serverid)
512

    
513
    def test_009_server_becomes_stopped(self):
514
        """Test server becomes STOPPED"""
515
        self._insist_on_status_transition("ACTIVE", "STOPPED",
516
                                         self.action_timeout,
517
                                         self.action_timeout)
518

    
519
    def test_010_submit_start_request(self):
520
        """Test submit start server request"""
521
        self.cyclades.start_server(self.serverid)
522

    
523
    def test_011_server_becomes_active(self):
524
        """Test server becomes ACTIVE again"""
525
        self._insist_on_status_transition("STOPPED", "ACTIVE",
526
                                         self.action_timeout,
527
                                         self.action_timeout)
528

    
529
    def test_011a_server_responds_to_ping_IPv4(self):
530
        """Test server OS is actually up and running again"""
531
        self.test_006_server_responds_to_ping_IPv4()
532

    
533
    def test_012_ssh_to_server_IPv4(self):
534
        """Test SSH to server public IPv4 works, verify hostname"""
535
        self._skipIf(self.is_windows, "only valid for Linux servers")
536
        server = self.client.get_server_details(self.serverid)
537
        self._insist_on_ssh_hostname(self._get_ipv4(server),
538
                                     self.username, self.passwd)
539

    
540
    def test_013_ssh_to_server_IPv6(self):
541
        """Test SSH to server public IPv6 works, verify hostname"""
542
        self._skipIf(self.is_windows, "only valid for Linux servers")
543
        server = self.client.get_server_details(self.serverid)
544
        self._insist_on_ssh_hostname(self._get_ipv6(server),
545
                                     self.username, self.passwd)
546

    
547
    def test_014_rdp_to_server_IPv4(self):
548
        "Test RDP connection to server public IPv4 works"""
549
        self._skipIf(not self.is_windows, "only valid for Windows servers")
550
        server = self.client.get_server_details(self.serverid)
551
        ipv4 = self._get_ipv4(server)
552
        sock = _insist_on_tcp_connection(socket.AF_INET, ipv4, 3389)
553

    
554
        # No actual RDP processing done. We assume the RDP server is there
555
        # if the connection to the RDP port is successful.
556
        # FIXME: Use rdesktop, analyze exit code? see manpage [costasd]
557
        sock.close()
558

    
559
    def test_015_rdp_to_server_IPv6(self):
560
        "Test RDP connection to server public IPv6 works"""
561
        self._skipIf(not self.is_windows, "only valid for Windows servers")
562
        server = self.client.get_server_details(self.serverid)
563
        ipv6 = self._get_ipv6(server)
564
        sock = _get_tcp_connection(socket.AF_INET6, ipv6, 3389)
565

    
566
        # No actual RDP processing done. We assume the RDP server is there
567
        # if the connection to the RDP port is successful.
568
        sock.close()
569

    
570
    def test_016_personality_is_enforced(self):
571
        """Test file injection for personality enforcement"""
572
        self._skipIf(self.is_windows, "only implemented for Linux servers")
573
        self._skipIf(self.personality == None, "No personality file selected")
574

    
575
        server = self.client.get_server_details(self.serverid)
576

    
577
        for inj_file in self.personality:
578
            equal_files = self._check_file_through_ssh(self._get_ipv4(server), inj_file['owner'], 
579
                                                       self.passwd, inj_file['path'], inj_file['contents'])
580
            self.assertTrue(equal_files)
581
        
582

    
583
    def test_017_submit_delete_request(self):
584
        """Test submit request to delete server"""
585
        self.client.delete_server(self.serverid)
586

    
587
    def test_018_server_becomes_deleted(self):
588
        """Test server becomes DELETED"""
589
        self._insist_on_status_transition("ACTIVE", "DELETED",
590
                                         self.action_timeout,
591
                                         self.action_timeout)
592

    
593
    def test_019_server_no_longer_in_server_list(self):
594
        """Test server is no longer in server list"""
595
        servers = self.client.list_servers()
596
        self.assertNotIn(self.serverid, [s["id"] for s in servers])
597

    
598

    
599
class NetworkTestCase(unittest.TestCase):
600
    """ Testing networking in cyclades """
601
  
602
    @classmethod
603
    def setUpClass(cls):
604
        "Initialize kamaki, get list of current networks"
605

    
606
        cls.client = CycladesClient(API, TOKEN)
607
        cls.compute = ComputeClient(API, TOKEN)
608

    
609
        images = cls.compute.list_images(detail = True)
610
        flavors = cls.compute.list_flavors(detail = True)
611

    
612
        cls.imageid = choice([im['id'] for im in images if not im['name'].lower().find("windows") >= 0])
613
        cls.flavorid = choice([f['id'] for f in flavors if f['disk'] >= 20])
614

    
615
        for image in images:
616
            if image['id'] == cls.imageid:
617
                imagename = image['name']
618

    
619
        cls.servername = "%s%s for %s" % (SNF_TEST_PREFIX, TEST_RUN_ID, imagename)
620

    
621
        #Dictionary initialization for the vms credentials
622

    
623
        cls.serverid = dict()
624
        cls.username = dict()
625
        cls.password = dict()
626

    
627
    def _get_ipv4(self, server):
628
    
629
        """Get the public IPv4 of a server from the detailed server info"""
630

    
631
        public_addrs = filter(lambda x: x["id"] == "public",
632
                              server["addresses"]["values"])
633
        self.assertEqual(len(public_addrs), 1)
634
        ipv4_addrs = filter(lambda x: x["version"] == 4,
635
                            public_addrs[0]["values"])
636
        self.assertEqual(len(ipv4_addrs), 1)
637
        return ipv4_addrs[0]["addr"]
638

    
639

    
640
    def _connect_loginname(self, os):
641
        """Return the login name for connections based on the server OS"""
642
        if os in ("Ubuntu", "Kubuntu", "Fedora"):
643
            return "user"
644
        elif os in ("windows", "windows_alpha1"):
645
            return "Administrator"
646
        else:
647
            return "root"
648

    
649

    
650
    def test_00001_submit_create_server_A(self):
651
        """Test submit create server request"""
652
        serverA = self.client.create_server(self.servername, self.flavorid,
653
                                           self.imageid, personality=None)
654

    
655
        self.assertEqual(serverA["name"], self.servername)
656
        self.assertEqual(serverA["flavorRef"], self.flavorid)
657
        self.assertEqual(serverA["imageRef"], self.imageid)
658
        self.assertEqual(serverA["status"], "BUILD")
659

    
660
        # Update class attributes to reflect data on building server
661
        self.serverid['A'] = serverA["id"]
662
        self.username['A'] = None
663
        self.password['A'] = serverA["adminPass"]
664

    
665
    
666
    def test_00001_submit_create_server_B(self):
667
        """Test submit create server request"""
668
        serverB = self.client.create_server(self.servername, self.flavorid,
669
                                           self.imageid, personality=None)
670

    
671
        self.assertEqual(serverB["name"], self.servername)
672
        self.assertEqual(serverB["flavorRef"], self.flavorid)
673
        self.assertEqual(serverB["imageRef"], self.imageid)
674
        self.assertEqual(serverB["status"], "BUILD")
675

    
676
        # Update class attributes to reflect data on building server
677
        self.serverid['B'] = serverB["id"]
678
        self.username['B'] = None
679
        self.password['B'] = serverB["adminPass"]
680

    
681
    def test_0001_serverA_becomes_active(self):
682
        """Test server becomes ACTIVE"""
683

    
684
        fail_tmout = time.time()+self.action_timeout
685
        while True:
686
            d = self.client.get_server_details(self.serverid['A'])
687
            status = d['status']
688
            if status == 'ACTIVE':
689
                active = True
690
                break
691
            elif time.time() > fail_tmout:
692
                self.assertLess(time.time(), fail_tmout)
693
            else:
694
                time.sleep(self.query_interval)
695

    
696
        self.assertTrue(active)
697

    
698
    def test_0001_serverB_becomes_active(self):
699
        """Test server becomes ACTIVE"""
700

    
701
        fail_tmout = time.time()+self.action_timeout
702
        while True:
703
            d = self.client.get_server_details(self.serverid['B'])
704
            status = d['status']
705
            if status == 'ACTIVE':
706
                active = True
707
                break
708
            elif time.time() > fail_tmout:
709
                self.assertLess(time.time(), fail_tmout)
710
            else:
711
                time.sleep(self.query_interval)
712

    
713
        self.assertTrue(active)
714

    
715

    
716
    def test_001_create_network(self):
717
        """Test submit create network request"""
718
        name = SNF_TEST_PREFIX+TEST_RUN_ID
719
        previous_num = len(self.client.list_networks())
720
        network =  self.client.create_network(name)        
721
       
722
        #Test if right name is assigned
723
        self.assertEqual(network['name'], name)
724
        
725
        # Update class attributes
726
        cls = type(self)
727
        cls.networkid = network['id']
728
        networks = self.client.list_networks()
729

    
730
        #Test if new network is created
731
        self.assertTrue(len(networks) > previous_num)
732
        
733
    
734
    def test_002_connect_to_network(self):
735
        """Test connect VM to network"""
736

    
737
        self.client.connect_server(self.serverid['A'], self.networkid)
738
        self.client.connect_server(self.serverid['B'], self.networkid)
739
                
740
        #Insist on connecting until action timeout
741
        fail_tmout = time.time()+self.action_timeout
742

    
743
        while True:
744
            connected = (self.client.get_network_details(self.networkid))
745
            connections = connected['servers']['values']
746
            if (self.serverid['A'] in connections) and (self.serverid['B'] in connections):
747
                conn_exists = True
748
                break
749
            elif time.time() > fail_tmout:
750
                self.assertLess(time.time(), fail_tmout)
751
            else:
752
                time.sleep(self.query_interval)
753

    
754
        self.assertTrue(conn_exists)
755
            
756

    
757
    def test_002a_setup_interface_A(self):
758

    
759
        server = self.client.get_server_details(self.serverid['A'])
760
        image = self.client.get_image_details(self.imageid)
761
        os = image['metadata']['values']['os']
762
        loginname = image["metadata"]["values"].get("users", None)
763
        hostip = self._get_ipv4(server) 
764
        
765
        if not loginname:
766
            loginname = self._connect_loginname(os)
767

    
768
        try:
769
            ssh = paramiko.SSHClient()
770
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
771
            ssh.connect(hostip, username = loginname, password = self.password['A'])
772
        except socket.error:
773
            raise AssertionError
774

    
775
        stdin, stdout, stderr = ssh.exec_command("ifconfig eth1 %s up"%("192.168.0.42"))
776
        lines = stdout.readlines()
777

    
778
        self.assertEqual(len(lines), 0)
779
        
780

    
781
    def test_002b_setup_interface_B(self):
782

    
783
        server = self.client.get_server_details(self.serverid['B'])
784
        image = self.client.get_image_details(self.imageid)
785
        os = image['metadata']['values']['os']
786
        loginname = image["metadata"]["values"].get("users", None)
787
        hostip = self._get_ipv4(server) 
788
        
789
        if not loginname:
790
            loginname = self._connect_loginname(os)
791

    
792
        try:
793
            ssh = paramiko.SSHClient()
794
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
795
            ssh.connect(hostip, username = loginname, password = self.password['B'])
796
        except socket.error:
797
            raise AssertionError
798

    
799
        stdin, stdout, stderr = ssh.exec_command("ifconfig eth1 %s up"%("192.168.0.43"))
800
        lines = stdout.readlines()
801

    
802
        self.assertEqual(len(lines), 0)
803

    
804

    
805

    
806
    def test_002a_test_connection_exists(self):
807
        """Ping serverB from serverA to test if connection exists"""
808

    
809
        server = self.client.get_server_details(self.serverid['A'])
810
        image = self.client.get_image_details(self.imageid)
811
        os = image['metadata']['values']['os']
812
        loginname = image["metadata"]["values"].get("users", None)
813
        
814
        hostip = self._get_ipv4(server)
815
        
816
        if not loginname:
817
            loginname = self._connect_loginname(os)
818

    
819
        try:
820
            ssh = paramiko.SSHClient()
821
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
822
            ssh.connect(hostip, username = loginname, password = self.password['A'])
823
        except socket.error:
824
            raise AssertionError
825

    
826
        cmd = "if ping -c 2 -w 3 %s >/dev/null; then echo \"True\"; fi;" % ("192.168.0.43")
827
        stdin, stdout, stderr = ssh.exec_command(cmd)
828
        lines = stdout.readlines()
829

    
830
        for i in lines:
831
            if i=='True\n':
832
                exists = True
833

    
834
        self.assertTrue(exists)
835

    
836

    
837

    
838
    def test_003_disconnect_from_network(self):
839
        prev_state = self.client.get_network_details(self.networkid)
840
        prev_conn = len(prev_state['servers']['values'])
841

    
842
        self.client.disconnect_server(self.serverid['A'], self.networkid)
843
        self.client.disconnect_server(self.serverid['B'], self.networkid)
844

    
845
        #Insist on deleting until action timeout
846
        fail_tmout = time.time()+self.action_timeout
847

    
848
        while True:
849
            connected = (self.client.get_network_details(self.networkid))
850
            connections = connected['servers']['values']
851
            if (self.serverid['A'] not in connections) and (self.serverid['B'] not in connections):
852
                conn_exists = False
853
                break
854
            elif time.time() > fail_tmout:
855
                self.assertLess(time.time(), fail_tmout)
856
            else:
857
                time.sleep(self.query_interval)
858

    
859
        self.assertFalse(conn_exists)
860

    
861
    def test_004_destroy_network(self):
862
        """Test submit delete network request"""
863
        self.client.delete_network(self.networkid)        
864
        networks = self.client.list_networks()
865

    
866
        curr_net = []
867
        for net in networks:
868
            curr_net.append(net['id'])
869

    
870
        self.assertTrue(self.networkid not in curr_net)
871
        
872
    def test_005_cleanup_servers(self):
873
        """Cleanup servers created for this test"""
874
        self.compute.delete_server(self.serverid['A'])
875
        self.compute.delete_server(self.serverid['B'])
876

    
877
        fail_tmout = time.time()+self.action_timeout
878

    
879
        #Ensure server gets deleted
880
        status = dict() 
881

    
882
        while True:
883
            details = self.compute.get_server_details(self.serverid['A'])
884
            status['A'] = details['status']
885
            details = self.compute.get_server_details(self.serverid['B'])
886
            status['B'] = details['status']
887
            if (status['A'] == 'DELETED') and (status['B'] == 'DELETED'):
888
                deleted = True
889
                break
890
            elif time.time() > fail_tmout: 
891
                self.assertLess(time.time(), fail_tmout)
892
            else:
893
                time.sleep(self.query_interval)
894

    
895
        self.assertTrue(deleted)
896

    
897
class TestRunnerProcess(Process):
898
    """A distinct process used to execute part of the tests in parallel"""
899
    def __init__(self, **kw):
900
        Process.__init__(self, **kw)
901
        kwargs = kw["kwargs"]
902
        self.testq = kwargs["testq"]
903
        self.runner = kwargs["runner"]
904

    
905
    def run(self):
906
        # Make sure this test runner process dies with the parent
907
        # and is not left behind.
908
        #
909
        # WARNING: This uses the prctl(2) call and is
910
        # Linux-specific.
911
        prctl.set_pdeathsig(signal.SIGHUP)
912

    
913
        while True:
914
            log.debug("I am process %d, GETting from queue is %s",
915
                     os.getpid(), self.testq)
916
            msg = self.testq.get()
917
            log.debug("Dequeued msg: %s", msg)
918

    
919
            if msg == "TEST_RUNNER_TERMINATE":
920
                raise SystemExit
921
            elif issubclass(msg, unittest.TestCase):
922
                # Assemble a TestSuite, and run it
923
                suite = unittest.TestLoader().loadTestsFromTestCase(msg)
924
                self.runner.run(suite)
925
            else:
926
                raise Exception("Cannot handle msg: %s" % msg)
927

    
928

    
929

    
930
def _run_cases_in_parallel(cases, fanout=1, runner=None):
931
    """Run instances of TestCase in parallel, in a number of distinct processes
932

933
    The cases iterable specifies the TestCases to be executed in parallel,
934
    by test runners running in distinct processes.
935
    The fanout parameter specifies the number of processes to spawn,
936
    and defaults to 1.
937
    The runner argument specifies the test runner class to use inside each
938
    runner process.
939

940
    """
941
    if runner is None:
942
        runner = unittest.TextTestRunner(verbosity=2, failfast=True)
943

    
944
    # testq: The master process enqueues TestCase objects into this queue,
945
    #        test runner processes pick them up for execution, in parallel.
946
    testq = Queue()
947
    runners = []
948
    for i in xrange(0, fanout):
949
        kwargs = dict(testq=testq, runner=runner)
950
        runners.append(TestRunnerProcess(kwargs=kwargs))
951

    
952
    log.info("Spawning %d test runner processes", len(runners))
953
    for p in runners:
954
        p.start()
955
    log.debug("Spawned %d test runners, PIDs are %s",
956
              len(runners), [p.pid for p in runners])
957

    
958
    # Enqueue test cases
959
    map(testq.put, cases)
960
    map(testq.put, ["TEST_RUNNER_TERMINATE"] * len(runners))
961

    
962
    log.debug("Joining %d processes", len(runners))
963
    for p in runners:
964
        p.join()
965
    log.debug("Done joining %d processes", len(runners))
966

    
967

    
968
def _spawn_server_test_case(**kwargs):
969
    """Construct a new unit test case class from SpawnServerTestCase"""
970

    
971
    name = "SpawnServerTestCase_%s" % kwargs["imageid"]
972
    cls = type(name, (SpawnServerTestCase,), kwargs)
973

    
974
    # Patch extra parameters into test names by manipulating method docstrings
975
    for (mname, m) in \
976
        inspect.getmembers(cls, lambda x: inspect.ismethod(x)):
977
            if hasattr(m, __doc__):
978
                m.__func__.__doc__ = "[%s] %s" % (imagename, m.__doc__)
979

    
980
    # Make sure the class can be pickled, by listing it among
981
    # the attributes of __main__. A PicklingError is raised otherwise.
982
    setattr(__main__, name, cls)
983
    return cls 
984

    
985
def _spawn_network_test_case(**kwargs):
986
    """Construct a new unit test case class from NetworkTestCase"""
987

    
988
    name = "NetworkTestCase"+TEST_RUN_ID
989
    cls = type(name, (NetworkTestCase,), kwargs)
990

    
991
    # Make sure the class can be pickled, by listing it among
992
    # the attributes of __main__. A PicklingError is raised otherwise.
993
    setattr(__main__, name, cls)
994
    return cls 
995

    
996

    
997
def cleanup_servers(delete_stale=False):
998

    
999
    c = ComputeClient(API, TOKEN)
1000

    
1001
    servers = c.list_servers()
1002
    stale = [s for s in servers if s["name"].startswith(SNF_TEST_PREFIX)]
1003

    
1004
    if len(stale) == 0:
1005
        return
1006

    
1007
    print >> sys.stderr, "Found these stale servers from previous runs:"
1008
    print "    " + \
1009
          "\n    ".join(["%d: %s" % (s["id"], s["name"]) for s in stale])
1010

    
1011
    if delete_stale:
1012
        print >> sys.stderr, "Deleting %d stale servers:" % len(stale)
1013
        for server in stale:
1014
            c.delete_server(server["id"])
1015
        print >> sys.stderr, "    ...done"
1016
    else:
1017
        print >> sys.stderr, "Use --delete-stale to delete them."
1018

    
1019

    
1020
def parse_arguments(args):
1021
    from optparse import OptionParser
1022

    
1023
    kw = {}
1024
    kw["usage"] = "%prog [options]"
1025
    kw["description"] = \
1026
        "%prog runs a number of test scenarios on a " \
1027
        "Synnefo deployment."
1028

    
1029
    parser = OptionParser(**kw)
1030
    parser.disable_interspersed_args()
1031
    parser.add_option("--api",
1032
                      action="store", type="string", dest="api",
1033
                      help="The API URI to use to reach the Synnefo API",
1034
                      default=DEFAULT_API)
1035
    parser.add_option("--token",
1036
                      action="store", type="string", dest="token",
1037
                      help="The token to use for authentication to the API")
1038
    parser.add_option("--nofailfast",
1039
                      action="store_true", dest="nofailfast",
1040
                      help="Do not fail immediately if one of the tests " \
1041
                           "fails (EXPERIMENTAL)",
1042
                      default=False)
1043
    parser.add_option("--action-timeout",
1044
                      action="store", type="int", dest="action_timeout",
1045
                      metavar="TIMEOUT",
1046
                      help="Wait SECONDS seconds for a server action to " \
1047
                           "complete, then the test is considered failed",
1048
                      default=100)
1049
    parser.add_option("--build-warning",
1050
                      action="store", type="int", dest="build_warning",
1051
                      metavar="TIMEOUT",
1052
                      help="Warn if TIMEOUT seconds have passed and a " \
1053
                           "build operation is still pending",
1054
                      default=600)
1055
    parser.add_option("--build-fail",
1056
                      action="store", type="int", dest="build_fail",
1057
                      metavar="BUILD_TIMEOUT",
1058
                      help="Fail the test if TIMEOUT seconds have passed " \
1059
                           "and a build operation is still incomplete",
1060
                      default=900)
1061
    parser.add_option("--query-interval",
1062
                      action="store", type="int", dest="query_interval",
1063
                      metavar="INTERVAL",
1064
                      help="Query server status when requests are pending " \
1065
                           "every INTERVAL seconds",
1066
                      default=3)
1067
    parser.add_option("--fanout",
1068
                      action="store", type="int", dest="fanout",
1069
                      metavar="COUNT",
1070
                      help="Spawn up to COUNT child processes to execute " \
1071
                           "in parallel, essentially have up to COUNT " \
1072
                           "server build requests outstanding (EXPERIMENTAL)",
1073
                      default=1)
1074
    parser.add_option("--force-flavor",
1075
                      action="store", type="int", dest="force_flavorid",
1076
                      metavar="FLAVOR ID",
1077
                      help="Force all server creations to use the specified "\
1078
                           "FLAVOR ID instead of a randomly chosen one, " \
1079
                           "useful if disk space is scarce",
1080
                      default=None)
1081
    parser.add_option("--image-id",
1082
                      action="store", type="string", dest="force_imageid",
1083
                      metavar="IMAGE ID",
1084
                      help="Test the specified image id, use 'all' to test " \
1085
                           "all available images (mandatory argument)",
1086
                      default=None)
1087
    parser.add_option("--show-stale",
1088
                      action="store_true", dest="show_stale",
1089
                      help="Show stale servers from previous runs, whose "\
1090
                           "name starts with `%s'" % SNF_TEST_PREFIX,
1091
                      default=False)
1092
    parser.add_option("--delete-stale",
1093
                      action="store_true", dest="delete_stale",
1094
                      help="Delete stale servers from previous runs, whose "\
1095
                           "name starts with `%s'" % SNF_TEST_PREFIX,
1096
                      default=False)
1097
    parser.add_option("--force-personality",
1098
                      action="store", type="string", dest="personality_path",
1099
                      help="Force a personality file injection. File path required. ",
1100
                      default=None)
1101
    
1102

    
1103
    # FIXME: Change the default for build-fanout to 10
1104
    # FIXME: Allow the user to specify a specific set of Images to test
1105

    
1106
    (opts, args) = parser.parse_args(args)
1107

    
1108
    # Verify arguments
1109
    if opts.delete_stale:
1110
        opts.show_stale = True
1111

    
1112
    if not opts.show_stale:
1113
        if not opts.force_imageid:
1114
            print >>sys.stderr, "The --image-id argument is mandatory."
1115
            parser.print_help()
1116
            sys.exit(1)
1117

    
1118
        if opts.force_imageid != 'all':
1119
            try:
1120
                opts.force_imageid = str(opts.force_imageid)
1121
            except ValueError:
1122
                print >>sys.stderr, "Invalid value specified for --image-id." \
1123
                                    "Use a valid id, or `all'."
1124
                sys.exit(1)
1125

    
1126
    return (opts, args)
1127

    
1128

    
1129
def main():
1130
    """Assemble test cases into a test suite, and run it
1131

1132
    IMPORTANT: Tests have dependencies and have to be run in the specified
1133
    order inside a single test case. They communicate through attributes of the
1134
    corresponding TestCase class (shared fixtures). Distinct subclasses of
1135
    TestCase MAY SHARE NO DATA, since they are run in parallel, in distinct
1136
    test runner processes.
1137

1138
    """
1139
    (opts, args) = parse_arguments(sys.argv[1:])
1140

    
1141
    global API, TOKEN
1142
    API = opts.api
1143
    TOKEN = opts.token
1144

    
1145
    # Cleanup stale servers from previous runs
1146
    if opts.show_stale:
1147
        cleanup_servers(delete_stale=opts.delete_stale)
1148
        return 0
1149

    
1150
    # Initialize a kamaki instance, get flavors, images
1151

    
1152
    c = ComputeClient(API, TOKEN)
1153

    
1154
    DIMAGES = c.list_images(detail=True)
1155
    DFLAVORS = c.list_flavors(detail=True)
1156

    
1157
    # FIXME: logging, log, LOG PID, TEST_RUN_ID, arguments
1158
    # Run them: FIXME: In parallel, FAILEARLY, catchbreak?
1159
    #unittest.main(verbosity=2, catchbreak=True)
1160

    
1161
    if opts.force_imageid == 'all':
1162
        test_images = DIMAGES
1163
    else:
1164
        test_images = filter(lambda x: x["id"] == opts.force_imageid, DIMAGES)
1165

    
1166
    for image in test_images:
1167
        imageid = str(image["id"])
1168
        flavorid = choice([f["id"] for f in DFLAVORS if f["disk"] >= 20])
1169
        imagename = image["name"]
1170
        
1171
        #Personality dictionary for file injection test
1172
        if opts.personality_path != None:
1173
            f = open(opts.personality_path)
1174
            content = b64encode(f.read())
1175
            personality = []
1176
            st = os.stat(opts.personality_path)
1177
            personality.append({
1178
                    'path': '/root/test_inj_file',
1179
                    'owner': 'root',
1180
                    'group': 'root',
1181
                    'mode': 0x7777 & st.st_mode,
1182
                    'contents': content
1183
                    })
1184
        else:
1185
            personality = None
1186

    
1187
        servername = "%s%s for %s" % (SNF_TEST_PREFIX, TEST_RUN_ID, imagename)
1188
        is_windows = imagename.lower().find("windows") >= 0
1189
        
1190
    ServerTestCase = _spawn_server_test_case(imageid=imageid, flavorid=flavorid,
1191
                                             imagename=imagename,
1192
                                             personality=personality,
1193
                                             servername=servername,
1194
                                             is_windows=is_windows,
1195
                                             action_timeout=opts.action_timeout,
1196
                                             build_warning=opts.build_warning,
1197
                                             build_fail=opts.build_fail,
1198
                                             query_interval=opts.query_interval,
1199
                                             )
1200

    
1201

    
1202
    #Running all the testcases sequentially
1203
    
1204
    #To run all cases
1205
    #seq_cases = [UnauthorizedTestCase, FlavorsTestCase, ImagesTestCase, ServerTestCase, NetworkTestCase]
1206
    
1207
    newNetworkTestCase = _spawn_network_test_case(action_timeout = opts.action_timeout,
1208
                                                  query_interval = opts.query_interval)    
1209
    seq_cases = [newNetworkTestCase]
1210

    
1211
    for case in seq_cases:
1212
        suite = unittest.TestLoader().loadTestsFromTestCase(case)
1213
        unittest.TextTestRunner(verbosity=2).run(suite)
1214
        
1215
    
1216

    
1217
    # # The Following cases run sequentially
1218
    # seq_cases = [UnauthorizedTestCase, FlavorsTestCase, ImagesTestCase]
1219
    # _run_cases_in_parallel(seq_cases, fanout=3, runner=runner)
1220

    
1221
    # # The following cases run in parallel
1222
    # par_cases = []
1223

    
1224
    # if opts.force_imageid == 'all':
1225
    #     test_images = DIMAGES
1226
    # else:
1227
    #     test_images = filter(lambda x: x["id"] == opts.force_imageid, DIMAGES)
1228

    
1229
    # for image in test_images:
1230
    #     imageid = image["id"]
1231
    #     imagename = image["name"]
1232
    #     if opts.force_flavorid:
1233
    #         flavorid = opts.force_flavorid
1234
    #     else:
1235
    #         flavorid = choice([f["id"] for f in DFLAVORS if f["disk"] >= 20])
1236
    #     personality = None   # FIXME
1237
    #     servername = "%s%s for %s" % (SNF_TEST_PREFIX, TEST_RUN_ID, imagename)
1238
    #     is_windows = imagename.lower().find("windows") >= 0
1239
    #     case = _spawn_server_test_case(imageid=str(imageid), flavorid=flavorid,
1240
    #                                    imagename=imagename,
1241
    #                                    personality=personality,
1242
    #                                    servername=servername,
1243
    #                                    is_windows=is_windows,
1244
    #                                    action_timeout=opts.action_timeout,
1245
    #                                    build_warning=opts.build_warning,
1246
    #                                    build_fail=opts.build_fail,
1247
    #                                    query_interval=opts.query_interval)
1248
    #     par_cases.append(case)
1249

    
1250
    # _run_cases_in_parallel(par_cases, fanout=opts.fanout, runner=runner)
1251

    
1252
if __name__ == "__main__":
1253
    sys.exit(main())