Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / tools / burnin.py @ 96da37c8

History | View | Annotate | Download (44.7 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
        cls.serverid = dict()
623
        cls.username = dict()
624
        cls.password = dict()
625

    
626
    def test_0001_submit_create_server_A(self):
627
        """Test submit create server request"""
628
        serverA = self.client.create_server(self.servername, self.flavorid,
629
                                           self.imageid, personality=None)
630

    
631
        self.assertEqual(server["name"], self.servername)
632
        self.assertEqual(server["flavorRef"], self.flavorid)
633
        self.assertEqual(server["imageRef"], self.imageid)
634
        self.assertEqual(server["status"], "BUILD")
635

    
636
        # Update class attributes to reflect data on building server
637
        cls = type(self)
638
        cls.serverid['A'] = serverA["id"]
639
        cls.username['A'] = None
640
        cls.password['A'] = serverA["adminPass"]
641

    
642
    
643
    def test_0001_submit_create_server_B(self):
644
        """Test submit create server request"""
645
        serverB = self.client.create_server(self.servername, self.flavorid,
646
                                           self.imageid, personality=None)
647

    
648
        self.assertEqual(server["name"], self.servername)
649
        self.assertEqual(server["flavorRef"], self.flavorid)
650
        self.assertEqual(server["imageRef"], self.imageid)
651
        self.assertEqual(server["status"], "BUILD")
652

    
653
        # Update class attributes to reflect data on building server
654
        cls = type(self)
655
        cls.serverid['B'] = serverB["id"]
656
        cls.username['B'] = None
657
        cls.password['B'] = serverB["adminPass"]
658

    
659
    def test_0001_serverA_becomes_active(self):
660
        """Test server becomes ACTIVE"""
661

    
662
        fail_tmout = time.time()+self.action_timeout
663
        while True:
664
            d = self.client.get_server_details(self.serverid['A'])
665
            status = d['status']
666
            if status == 'ACTIVE':
667
                active = True
668
                break
669
            elif time.time() > fail_tmout:
670
                self.assertLess(time.time(), fail_tmout)
671
            else:
672
                time.sleep(self.query_interval)
673

    
674
        self.assertTrue(active)
675

    
676
    def test_0001_serverB_becomes_active(self):
677
        """Test server becomes ACTIVE"""
678

    
679
        fail_tmout = time.time()+self.action_timeout
680
        while True:
681
            d = self.client.get_server_details(self.serverid['B'])
682
            status = d['status']
683
            if status == 'ACTIVE':
684
                active = True
685
                break
686
            elif time.time() > fail_tmout:
687
                self.assertLess(time.time(), fail_tmout)
688
            else:
689
                time.sleep(self.query_interval)
690

    
691
        self.assertTrue(active)
692

    
693

    
694
    def test_001_create_network(self):
695
        """Test submit create network request"""
696
        name = SNF_TEST_PREFIX+TEST_RUN_ID
697
        previous_num = len(self.client.list_networks())
698
        network =  self.client.create_network(name)        
699
       
700
        #Test if right name is assigned
701
        self.assertEqual(network['name'], name)
702
        
703
        # Update class attributes
704
        cls = type(self)
705
        cls.networkid = network['id']
706
        networks = self.client.list_networks()
707

    
708
        #Test if new network is created
709
        self.assertTrue(len(networks) > previous_num)
710
        
711
    
712
    def test_002_connect_to_network(self):
713
        """Test connect VM to network"""
714

    
715
        self.client.connect_server(self.serverid['A'], self.networkid)
716
        self.client.connect_server(self.serverid['B'], self.networkid)
717
                
718
        #Insist on connecting until action timeout
719
        fail_tmout = time.time()+self.action_timeout
720

    
721
        while True:
722
            connected = (self.client.get_network_details(self.networkid))
723
            connections = connected['servers']['values']
724
            if (self.serverid['A'] in connections) and (self.serverid['B'] in connections):
725
                conn_exists = True
726
                break
727
            elif time.time() > fail_tmout:
728
                self.assertLess(time.time(), fail_tmout)
729
            else:
730
                time.sleep(self.query_interval)
731

    
732
        self.assertTrue(conn_exists)
733
            
734

    
735
    def test_003_disconnect_from_network(self):
736
        prev_state = self.client.get_network_details(self.networkid)
737
        prev_conn = len(prev_state['servers']['values'])
738

    
739
        self.client.disconnect_server(self.serverid['A'], self.networkid)
740
        self.client.disconnect_server(self.serverid['B'], self.networkid)
741

    
742
        #Insist on deleting until action timeout
743
        fail_tmout = time.time()+self.action_timeout
744

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

    
756
        self.assertFalse(conn_exists)
757

    
758
    def test_004_destroy_network(self):
759
        """Test submit delete network request"""
760
        self.client.delete_network(self.networkid)        
761
        networks = self.client.list_networks()
762

    
763
        curr_net = []
764
        for net in networks:
765
            curr_net.append(net['id'])
766

    
767
        self.assertTrue(self.networkid not in curr_net)
768
        
769
    def test_005_cleanup_servers(self):
770
        """Cleanup servers created for this test"""
771
        self.compute.delete_server(self.serverid['A'])
772
        self.compute.delete_server(self.serverid['B'])
773

    
774
        fail_tmout = time.time()+self.action_timeout
775

    
776
        #Ensure server gets deleted
777
        status = dict() 
778

    
779
        while True:
780
            details = self.compute.get_server_details(self.serverid['A'])
781
            status['A'] = details['status']
782
            details = self.compute.get_server_details(self.serverid['B'])
783
            status['B'] = details['status']
784
            if (status['A'] == 'DELETED') and (status['B'] == 'DELETED'):
785
                deleted = True
786
                break
787
            elif time.time() > fail_tmout: 
788
                self.assertLess(time.time(), fail_tmout)
789
            else:
790
                time.sleep(self.query_interval)
791

    
792
        self.assertTrue(deleted)
793

    
794
class TestRunnerProcess(Process):
795
    """A distinct process used to execute part of the tests in parallel"""
796
    def __init__(self, **kw):
797
        Process.__init__(self, **kw)
798
        kwargs = kw["kwargs"]
799
        self.testq = kwargs["testq"]
800
        self.runner = kwargs["runner"]
801

    
802
    def run(self):
803
        # Make sure this test runner process dies with the parent
804
        # and is not left behind.
805
        #
806
        # WARNING: This uses the prctl(2) call and is
807
        # Linux-specific.
808
        prctl.set_pdeathsig(signal.SIGHUP)
809

    
810
        while True:
811
            log.debug("I am process %d, GETting from queue is %s",
812
                     os.getpid(), self.testq)
813
            msg = self.testq.get()
814
            log.debug("Dequeued msg: %s", msg)
815

    
816
            if msg == "TEST_RUNNER_TERMINATE":
817
                raise SystemExit
818
            elif issubclass(msg, unittest.TestCase):
819
                # Assemble a TestSuite, and run it
820
                suite = unittest.TestLoader().loadTestsFromTestCase(msg)
821
                self.runner.run(suite)
822
            else:
823
                raise Exception("Cannot handle msg: %s" % msg)
824

    
825

    
826

    
827
def _run_cases_in_parallel(cases, fanout=1, runner=None):
828
    """Run instances of TestCase in parallel, in a number of distinct processes
829

830
    The cases iterable specifies the TestCases to be executed in parallel,
831
    by test runners running in distinct processes.
832
    The fanout parameter specifies the number of processes to spawn,
833
    and defaults to 1.
834
    The runner argument specifies the test runner class to use inside each
835
    runner process.
836

837
    """
838
    if runner is None:
839
        runner = unittest.TextTestRunner(verbosity=2, failfast=True)
840

    
841
    # testq: The master process enqueues TestCase objects into this queue,
842
    #        test runner processes pick them up for execution, in parallel.
843
    testq = Queue()
844
    runners = []
845
    for i in xrange(0, fanout):
846
        kwargs = dict(testq=testq, runner=runner)
847
        runners.append(TestRunnerProcess(kwargs=kwargs))
848

    
849
    log.info("Spawning %d test runner processes", len(runners))
850
    for p in runners:
851
        p.start()
852
    log.debug("Spawned %d test runners, PIDs are %s",
853
              len(runners), [p.pid for p in runners])
854

    
855
    # Enqueue test cases
856
    map(testq.put, cases)
857
    map(testq.put, ["TEST_RUNNER_TERMINATE"] * len(runners))
858

    
859
    log.debug("Joining %d processes", len(runners))
860
    for p in runners:
861
        p.join()
862
    log.debug("Done joining %d processes", len(runners))
863

    
864

    
865
def _spawn_server_test_case(**kwargs):
866
    """Construct a new unit test case class from SpawnServerTestCase"""
867

    
868
    name = "SpawnServerTestCase_%s" % kwargs["imageid"]
869
    cls = type(name, (SpawnServerTestCase,), kwargs)
870

    
871
    # Patch extra parameters into test names by manipulating method docstrings
872
    for (mname, m) in \
873
        inspect.getmembers(cls, lambda x: inspect.ismethod(x)):
874
            if hasattr(m, __doc__):
875
                m.__func__.__doc__ = "[%s] %s" % (imagename, m.__doc__)
876

    
877
    # Make sure the class can be pickled, by listing it among
878
    # the attributes of __main__. A PicklingError is raised otherwise.
879
    setattr(__main__, name, cls)
880
    return cls 
881

    
882
def _spawn_network_test_case(**kwargs):
883
    """Construct a new unit test case class from NetworkTestCase"""
884

    
885
    name = "NetworkTestCase"+TEST_RUN_ID
886
    cls = type(name, (NetworkTestCase,), kwargs)
887

    
888
    # Make sure the class can be pickled, by listing it among
889
    # the attributes of __main__. A PicklingError is raised otherwise.
890
    setattr(__main__, name, cls)
891
    return cls 
892

    
893

    
894
def cleanup_servers(delete_stale=False):
895

    
896
    c = ComputeClient(API, TOKEN)
897

    
898
    servers = c.list_servers()
899
    stale = [s for s in servers if s["name"].startswith(SNF_TEST_PREFIX)]
900

    
901
    if len(stale) == 0:
902
        return
903

    
904
    print >> sys.stderr, "Found these stale servers from previous runs:"
905
    print "    " + \
906
          "\n    ".join(["%d: %s" % (s["id"], s["name"]) for s in stale])
907

    
908
    if delete_stale:
909
        print >> sys.stderr, "Deleting %d stale servers:" % len(stale)
910
        for server in stale:
911
            c.delete_server(server["id"])
912
        print >> sys.stderr, "    ...done"
913
    else:
914
        print >> sys.stderr, "Use --delete-stale to delete them."
915

    
916

    
917
def parse_arguments(args):
918
    from optparse import OptionParser
919

    
920
    kw = {}
921
    kw["usage"] = "%prog [options]"
922
    kw["description"] = \
923
        "%prog runs a number of test scenarios on a " \
924
        "Synnefo deployment."
925

    
926
    parser = OptionParser(**kw)
927
    parser.disable_interspersed_args()
928
    parser.add_option("--api",
929
                      action="store", type="string", dest="api",
930
                      help="The API URI to use to reach the Synnefo API",
931
                      default=DEFAULT_API)
932
    parser.add_option("--token",
933
                      action="store", type="string", dest="token",
934
                      help="The token to use for authentication to the API")
935
    parser.add_option("--nofailfast",
936
                      action="store_true", dest="nofailfast",
937
                      help="Do not fail immediately if one of the tests " \
938
                           "fails (EXPERIMENTAL)",
939
                      default=False)
940
    parser.add_option("--action-timeout",
941
                      action="store", type="int", dest="action_timeout",
942
                      metavar="TIMEOUT",
943
                      help="Wait SECONDS seconds for a server action to " \
944
                           "complete, then the test is considered failed",
945
                      default=100)
946
    parser.add_option("--build-warning",
947
                      action="store", type="int", dest="build_warning",
948
                      metavar="TIMEOUT",
949
                      help="Warn if TIMEOUT seconds have passed and a " \
950
                           "build operation is still pending",
951
                      default=600)
952
    parser.add_option("--build-fail",
953
                      action="store", type="int", dest="build_fail",
954
                      metavar="BUILD_TIMEOUT",
955
                      help="Fail the test if TIMEOUT seconds have passed " \
956
                           "and a build operation is still incomplete",
957
                      default=900)
958
    parser.add_option("--query-interval",
959
                      action="store", type="int", dest="query_interval",
960
                      metavar="INTERVAL",
961
                      help="Query server status when requests are pending " \
962
                           "every INTERVAL seconds",
963
                      default=3)
964
    parser.add_option("--fanout",
965
                      action="store", type="int", dest="fanout",
966
                      metavar="COUNT",
967
                      help="Spawn up to COUNT child processes to execute " \
968
                           "in parallel, essentially have up to COUNT " \
969
                           "server build requests outstanding (EXPERIMENTAL)",
970
                      default=1)
971
    parser.add_option("--force-flavor",
972
                      action="store", type="int", dest="force_flavorid",
973
                      metavar="FLAVOR ID",
974
                      help="Force all server creations to use the specified "\
975
                           "FLAVOR ID instead of a randomly chosen one, " \
976
                           "useful if disk space is scarce",
977
                      default=None)
978
    parser.add_option("--image-id",
979
                      action="store", type="string", dest="force_imageid",
980
                      metavar="IMAGE ID",
981
                      help="Test the specified image id, use 'all' to test " \
982
                           "all available images (mandatory argument)",
983
                      default=None)
984
    parser.add_option("--show-stale",
985
                      action="store_true", dest="show_stale",
986
                      help="Show stale servers from previous runs, whose "\
987
                           "name starts with `%s'" % SNF_TEST_PREFIX,
988
                      default=False)
989
    parser.add_option("--delete-stale",
990
                      action="store_true", dest="delete_stale",
991
                      help="Delete stale servers from previous runs, whose "\
992
                           "name starts with `%s'" % SNF_TEST_PREFIX,
993
                      default=False)
994
    parser.add_option("--force-personality",
995
                      action="store", type="string", dest="personality_path",
996
                      help="Force a personality file injection. File path required. ",
997
                      default=None)
998
    
999

    
1000
    # FIXME: Change the default for build-fanout to 10
1001
    # FIXME: Allow the user to specify a specific set of Images to test
1002

    
1003
    (opts, args) = parser.parse_args(args)
1004

    
1005
    # Verify arguments
1006
    if opts.delete_stale:
1007
        opts.show_stale = True
1008

    
1009
    if not opts.show_stale:
1010
        if not opts.force_imageid:
1011
            print >>sys.stderr, "The --image-id argument is mandatory."
1012
            parser.print_help()
1013
            sys.exit(1)
1014

    
1015
        if opts.force_imageid != 'all':
1016
            try:
1017
                opts.force_imageid = str(opts.force_imageid)
1018
            except ValueError:
1019
                print >>sys.stderr, "Invalid value specified for --image-id." \
1020
                                    "Use a valid id, or `all'."
1021
                sys.exit(1)
1022

    
1023
    return (opts, args)
1024

    
1025

    
1026
def main():
1027
    """Assemble test cases into a test suite, and run it
1028

1029
    IMPORTANT: Tests have dependencies and have to be run in the specified
1030
    order inside a single test case. They communicate through attributes of the
1031
    corresponding TestCase class (shared fixtures). Distinct subclasses of
1032
    TestCase MAY SHARE NO DATA, since they are run in parallel, in distinct
1033
    test runner processes.
1034

1035
    """
1036
    (opts, args) = parse_arguments(sys.argv[1:])
1037

    
1038
    global API, TOKEN
1039
    API = opts.api
1040
    TOKEN = opts.token
1041

    
1042
    # Cleanup stale servers from previous runs
1043
    if opts.show_stale:
1044
        cleanup_servers(delete_stale=opts.delete_stale)
1045
        return 0
1046

    
1047
    # Initialize a kamaki instance, get flavors, images
1048

    
1049
    c = ComputeClient(API, TOKEN)
1050

    
1051
    DIMAGES = c.list_images(detail=True)
1052
    DFLAVORS = c.list_flavors(detail=True)
1053

    
1054
    # FIXME: logging, log, LOG PID, TEST_RUN_ID, arguments
1055
    # Run them: FIXME: In parallel, FAILEARLY, catchbreak?
1056
    #unittest.main(verbosity=2, catchbreak=True)
1057

    
1058
    if opts.force_imageid == 'all':
1059
        test_images = DIMAGES
1060
    else:
1061
        test_images = filter(lambda x: x["id"] == opts.force_imageid, DIMAGES)
1062

    
1063
    for image in test_images:
1064
        imageid = str(image["id"])
1065
        flavorid = choice([f["id"] for f in DFLAVORS if f["disk"] >= 20])
1066
        imagename = image["name"]
1067
        
1068
        #Personality dictionary for file injection test
1069
        if opts.personality_path != None:
1070
            f = open(opts.personality_path)
1071
            content = b64encode(f.read())
1072
            personality = []
1073
            st = os.stat(opts.personality_path)
1074
            personality.append({
1075
                    'path': '/root/test_inj_file',
1076
                    'owner': 'root',
1077
                    'group': 'root',
1078
                    'mode': 0x7777 & st.st_mode,
1079
                    'contents': content
1080
                    })
1081
        else:
1082
            personality = None
1083

    
1084
        servername = "%s%s for %s" % (SNF_TEST_PREFIX, TEST_RUN_ID, imagename)
1085
        is_windows = imagename.lower().find("windows") >= 0
1086
        
1087
    ServerTestCase = _spawn_server_test_case(imageid=imageid, flavorid=flavorid,
1088
                                             imagename=imagename,
1089
                                             personality=personality,
1090
                                             servername=servername,
1091
                                             is_windows=is_windows,
1092
                                             action_timeout=opts.action_timeout,
1093
                                             build_warning=opts.build_warning,
1094
                                             build_fail=opts.build_fail,
1095
                                             query_interval=opts.query_interval,
1096
                                             )
1097

    
1098

    
1099
    #Running all the testcases sequentially
1100
    
1101
    #To run all cases
1102
    #seq_cases = [UnauthorizedTestCase, FlavorsTestCase, ImagesTestCase, ServerTestCase, NetworkTestCase]
1103
    
1104
    newNetworkTestCase = _spawn_network_test_case(action_timeout = opts.action_timeout,
1105
                                                  query_interval = opts.query_interval)    
1106
    seq_cases = [newNetworkTestCase]
1107

    
1108
    for case in seq_cases:
1109
        suite = unittest.TestLoader().loadTestsFromTestCase(case)
1110
        unittest.TextTestRunner(verbosity=2).run(suite)
1111
        
1112
    
1113

    
1114
    # # The Following cases run sequentially
1115
    # seq_cases = [UnauthorizedTestCase, FlavorsTestCase, ImagesTestCase]
1116
    # _run_cases_in_parallel(seq_cases, fanout=3, runner=runner)
1117

    
1118
    # # The following cases run in parallel
1119
    # par_cases = []
1120

    
1121
    # if opts.force_imageid == 'all':
1122
    #     test_images = DIMAGES
1123
    # else:
1124
    #     test_images = filter(lambda x: x["id"] == opts.force_imageid, DIMAGES)
1125

    
1126
    # for image in test_images:
1127
    #     imageid = image["id"]
1128
    #     imagename = image["name"]
1129
    #     if opts.force_flavorid:
1130
    #         flavorid = opts.force_flavorid
1131
    #     else:
1132
    #         flavorid = choice([f["id"] for f in DFLAVORS if f["disk"] >= 20])
1133
    #     personality = None   # FIXME
1134
    #     servername = "%s%s for %s" % (SNF_TEST_PREFIX, TEST_RUN_ID, imagename)
1135
    #     is_windows = imagename.lower().find("windows") >= 0
1136
    #     case = _spawn_server_test_case(imageid=str(imageid), flavorid=flavorid,
1137
    #                                    imagename=imagename,
1138
    #                                    personality=personality,
1139
    #                                    servername=servername,
1140
    #                                    is_windows=is_windows,
1141
    #                                    action_timeout=opts.action_timeout,
1142
    #                                    build_warning=opts.build_warning,
1143
    #                                    build_fail=opts.build_fail,
1144
    #                                    query_interval=opts.query_interval)
1145
    #     par_cases.append(case)
1146

    
1147
    # _run_cases_in_parallel(par_cases, fanout=opts.fanout, runner=runner)
1148

    
1149
if __name__ == "__main__":
1150
    sys.exit(main())