Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / tests / servers.py @ dfcece01

History | View | Annotate | Download (34.3 kB)

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

    
34
import json
35
from copy import deepcopy
36

    
37
from snf_django.utils.testing import (BaseAPITest, mocked_quotaholder,
38
                                      override_settings)
39
from synnefo.db.models import (VirtualMachine, VirtualMachineMetadata,
40
                               FloatingIP)
41
from synnefo.db import models_factory as mfactory
42
from synnefo.logic.utils import get_rsapi_state
43
from synnefo.cyclades_settings import cyclades_services
44
from synnefo.lib.services import get_service_path
45
from synnefo.lib import join_urls
46
from django.conf import settings
47

    
48
from mock import patch, Mock
49

    
50

    
51
class ComputeAPITest(BaseAPITest):
52
    def __init__(self, *args, **kwargs):
53
        super(ComputeAPITest, self).__init__(*args, **kwargs)
54
        self.compute_path = get_service_path(cyclades_services, 'compute',
55
                                             version='v2.0')
56

    
57
    def myget(self, path, *args, **kwargs):
58
        path = join_urls(self.compute_path, path)
59
        return self.get(path, *args, **kwargs)
60

    
61
    def myput(self, path, *args, **kwargs):
62
        path = join_urls(self.compute_path, path)
63
        return self.put(path, *args, **kwargs)
64

    
65
    def mypost(self, path, *args, **kwargs):
66
        path = join_urls(self.compute_path, path)
67
        return self.post(path, *args, **kwargs)
68

    
69
    def mydelete(self, path, *args, **kwargs):
70
        path = join_urls(self.compute_path, path)
71
        return self.delete(path, *args, **kwargs)
72

    
73

    
74
class ServerAPITest(ComputeAPITest):
75
    def setUp(self):
76
        self.user1 = 'user1'
77
        self.user2 = 'user2'
78
        self.vm1 = mfactory.VirtualMachineFactory(userid=self.user1)
79
        self.vm2 = mfactory.VirtualMachineFactory(userid=self.user2)
80
        self.vm3 = mfactory.VirtualMachineFactory(deleted=True,
81
                                                  userid=self.user1)
82
        self.vm4 = mfactory.VirtualMachineFactory(userid=self.user2)
83

    
84
    def test_server_list_1(self):
85
        """Test if the expected list of servers is returned."""
86
        response = self.myget('servers')
87
        self.assertSuccess(response)
88
        servers = json.loads(response.content)['servers']
89
        self.assertEqual(servers, [])
90

    
91
    def test_server_list_2(self):
92
        """Test if the expected list of servers is returned."""
93
        response = self.myget('servers', self.user1)
94
        self.assertSuccess(response)
95
        servers = json.loads(response.content)['servers']
96
        db_server = self.vm1
97
        server = servers[0]
98
        self.assertEqual(server["name"], db_server.name)
99
        self.assertEqual(server["id"], db_server.id)
100

    
101
    def test_server_list_detail(self):
102
        """Test if the servers list details are returned."""
103
        user = self.user2
104
        user_vms = {self.vm2.id: self.vm2,
105
                    self.vm4.id: self.vm4}
106

    
107
        response = self.myget('servers/detail', user)
108
        servers = json.loads(response.content)['servers']
109
        self.assertEqual(len(servers), len(user_vms))
110
        for api_vm in servers:
111
            db_vm = user_vms[api_vm['id']]
112
            self.assertEqual(api_vm['flavor']["id"], db_vm.flavor.id)
113
            self.assertEqual(api_vm['hostId'], db_vm.hostid)
114
            self.assertEqual(api_vm['id'], db_vm.id)
115
            self.assertEqual(api_vm['image']["id"], db_vm.imageid)
116
            self.assertEqual(api_vm['name'], db_vm.name)
117
            self.assertEqual(api_vm['status'], get_rsapi_state(db_vm))
118
            self.assertSuccess(response)
119

    
120
    def test_server_detail(self):
121
        """Test if a server details are returned."""
122
        db_vm = self.vm2
123
        user = self.vm2.userid
124
        net = mfactory.NetworkFactory()
125
        nic = mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net,
126
                                               ipv6="::babe")
127

    
128
        db_vm_meta = mfactory.VirtualMachineMetadataFactory(vm=db_vm)
129

    
130
        response = self.myget('servers/%d' % db_vm.id, user)
131
        server = json.loads(response.content)['server']
132

    
133
        self.assertEqual(server['flavor']["id"], db_vm.flavor.id)
134
        self.assertEqual(server['hostId'], db_vm.hostid)
135
        self.assertEqual(server['id'], db_vm.id)
136
        self.assertEqual(server['image']["id"], db_vm.imageid)
137
        self.assertEqual(server['name'], db_vm.name)
138
        self.assertEqual(server['status'], get_rsapi_state(db_vm))
139
        api_nic = server['attachments'][0]
140
        self.assertEqual(api_nic['network_id'], str(net.id))
141
        self.assertEqual(api_nic['mac_address'], nic.mac)
142
        self.assertEqual(api_nic['firewallProfile'], nic.firewall_profile)
143
        self.assertEqual(api_nic['ipv4'], nic.ipv4)
144
        self.assertEqual(api_nic['ipv6'], nic.ipv6)
145
        self.assertEqual(api_nic['OS-EXT-IPS:type'], "fixed")
146
        self.assertEqual(api_nic['id'], 'nic-%s-%s' % (db_vm.id, nic.index))
147
        api_address = server["addresses"]
148
        self.assertEqual(api_address[str(net.id)], [
149
            {"version": 4, "addr": nic.ipv4, "OS-EXT-IPS:type": "fixed"},
150
            {"version": 6, "addr": nic.ipv6, "OS-EXT-IPS:type": "fixed"}
151
        ])
152

    
153
        metadata = server['metadata']
154
        self.assertEqual(len(metadata), 1)
155
        self.assertEqual(metadata[db_vm_meta.meta_key], db_vm_meta.meta_value)
156
        self.assertSuccess(response)
157

    
158
    def test_server_fqdn(self):
159
        vm = mfactory.VirtualMachineFactory()
160
        with override_settings(settings,
161
                               CYCLADES_SERVERS_FQDN="vm.example.org"):
162
            response = self.myget("servers/%d" % vm.id, vm.userid)
163
            server = json.loads(response.content)['server']
164
            self.assertEqual(server["SNF:fqdn"], "vm.example.org")
165
        with override_settings(settings, CYCLADES_SERVERS_FQDN=
166
                               "snf-%(id)s.vm.example.org"):
167
            response = self.myget("servers/%d" % vm.id, vm.userid)
168
            server = json.loads(response.content)['server']
169
            self.assertEqual(server["SNF:fqdn"],
170
                             "snf-%d.vm.example.org" % vm.id)
171
        with override_settings(settings,
172
                               CYCLADES_SERVERS_FQDN=
173
                               "snf-%(id)s.vm-%(id)s.example.org"):
174
            response = self.myget("servers/%d" % vm.id, vm.userid)
175
            server = json.loads(response.content)['server']
176
            self.assertEqual(server["SNF:fqdn"], "snf-%d.vm-%d.example.org" %
177
                             (vm.id, vm.id))
178
        # No setting, no NICs
179
        with override_settings(settings,
180
                               CYCLADES_SERVERS_FQDN=None):
181
            response = self.myget("servers/%d" % vm.id, vm.userid)
182
            server = json.loads(response.content)['server']
183
            self.assertEqual(server["SNF:fqdn"], "")
184

    
185
        # IPv6 NIC
186
        nic = mfactory.NetworkInterfaceFactory(machine=vm, ipv4=None,
187
                                               ipv6="babe::", state="ACTIVE",
188
                                               network__public=True)
189
        with override_settings(settings,
190
                               CYCLADES_SERVERS_FQDN=None):
191
            response = self.myget("servers/%d" % vm.id, vm.userid)
192
            server = json.loads(response.content)['server']
193
            self.assertEqual(server["SNF:fqdn"], nic.ipv6)
194

    
195
        # IPv4 NIC
196
        nic = mfactory.NetworkInterfaceFactory(machine=vm,
197
                                               network__public=True,
198
                                               state="ACTIVE")
199
        with override_settings(settings,
200
                               CYCLADES_SERVERS_FQDN=None):
201
            response = self.myget("servers/%d" % vm.id, vm.userid)
202
            server = json.loads(response.content)['server']
203
            self.assertEqual(server["SNF:fqdn"], nic.ipv4)
204

    
205
    def test_server_port_forwarding(self):
206
        vm = mfactory.VirtualMachineFactory()
207
        ports = {
208
            22: ("foo", 61000),
209
            80: lambda ip, id, fqdn, user: ("bar", 61001)}
210
        with override_settings(settings,
211
                               CYCLADES_PORT_FORWARDING=ports):
212
            response = self.myget("servers/%d" % vm.id, vm.userid)
213
            server = json.loads(response.content)['server']
214
            self.assertEqual(server["SNF:port_forwarding"],
215
                             {"22": {"host": "foo", "port": "61000"},
216
                              "80": {"host": "bar", "port": "61001"}})
217

    
218
        def _port_from_ip(ip, base):
219
            fields = ip.split('.', 4)
220
            return (base + 256*int(fields[2]) + int(fields[3]))
221

    
222
        ports = {
223
            22: lambda ip, id, fqdn, user:
224
            ip and ("gate", _port_from_ip(ip, 10000)) or None}
225
        with override_settings(settings,
226
                               CYCLADES_PORT_FORWARDING=ports):
227
            response = self.myget("servers/%d" % vm.id, vm.userid)
228
            server = json.loads(response.content)['server']
229
            self.assertEqual(server["SNF:port_forwarding"], {})
230

    
231
        mfactory.NetworkInterfaceFactory(machine=vm, ipv4="192.168.2.2",
232
                                         network__public=True)
233
        with override_settings(settings,
234
                               CYCLADES_PORT_FORWARDING=ports):
235
            response = self.myget("servers/%d" % vm.id, vm.userid)
236
            server = json.loads(response.content)['server']
237
            self.assertEqual(server["SNF:port_forwarding"],
238
                             {"22": {"host": "gate", "port": "10514"}})
239

    
240
    def test_server_building_nics(self):
241
        db_vm = self.vm2
242
        user = self.vm2.userid
243
        net1 = mfactory.NetworkFactory()
244
        net2 = mfactory.NetworkFactory()
245
        net3 = mfactory.NetworkFactory()
246
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net1,
247
                                         state="BUILDING")
248
        nic2 = mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net2,
249
                                                state="ACTIVE")
250
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net3,
251
                                         state="BUILDING")
252

    
253
        response = self.myget('servers/%d' % db_vm.id, user)
254
        server = json.loads(response.content)['server']
255
        nics = server["attachments"]
256
        self.assertEqual(len(nics), 1)
257
        self.assertEqual(nics[0]["network_id"], str(nic2.network_id))
258

    
259
    def test_noauthorized(self):
260
        """Test 404 for detail of other user vm"""
261
        db_vm = self.vm2
262

    
263
        response = self.myget('servers/%d' % db_vm.id, 'wrong_user')
264
        self.assertItemNotFound(response)
265

    
266
    def test_wrong_server(self):
267
        """Test 404 response if server does not exist."""
268
        response = self.myget('servers/%d' % 5000)
269
        self.assertItemNotFound(response)
270

    
271
    def test_create_server_empty(self):
272
        """Test if the create server call returns a 400 badRequest if
273
           no attributes are specified."""
274

    
275
        response = self.mypost('servers', params={})
276
        self.assertBadRequest(response)
277

    
278
    def test_rename_server(self):
279
        vm = self.vm2
280
        request = {'server': {'name': 'new_name'}}
281
        response = self.myput('servers/%d' % vm.id, vm.userid,
282
                              json.dumps(request), 'json')
283
        self.assertSuccess(response)
284
        self.assertEqual(VirtualMachine.objects.get(id=vm.id).name, "new_name")
285

    
286
    def test_catch_wrong_api_paths(self):
287
        response = self.myget('nonexistent')
288
        self.assertEqual(response.status_code, 400)
289
        try:
290
            json.loads(response.content)
291
        except ValueError:
292
            self.assertTrue(False)
293

    
294
    def test_method_not_allowed(self, *args):
295
        # /servers/ allows only POST, GET
296
        response = self.myput('servers', '', '')
297
        self.assertMethodNotAllowed(response)
298
        response = self.mydelete('servers')
299
        self.assertMethodNotAllowed(response)
300

    
301
        # /servers/<srvid>/ allows only GET, PUT, DELETE
302
        response = self.mypost("servers/42")
303
        self.assertMethodNotAllowed(response)
304

    
305
        # /imags/<srvid>/metadata/ allows only POST, GET
306
        response = self.myput('servers/42/metadata', '', '')
307
        self.assertMethodNotAllowed(response)
308
        response = self.mydelete('servers/42/metadata')
309
        self.assertMethodNotAllowed(response)
310

    
311
        # /imags/<srvid>/metadata/ allows only POST, GET
312
        response = self.myput('servers/42/metadata', '', '')
313
        self.assertMethodNotAllowed(response)
314
        response = self.mydelete('servers/42/metadata')
315
        self.assertMethodNotAllowed(response)
316

    
317
        # /imags/<srvid>/metadata/<key> allows only PUT, GET, DELETE
318
        response = self.mypost('servers/42/metadata/foo')
319
        self.assertMethodNotAllowed(response)
320

    
321

    
322
fixed_image = Mock()
323
fixed_image.return_value = {'location': 'pithos://foo',
324
                            'checksum': '1234',
325
                            "id": 1,
326
                            "name": "test_image",
327
                            "size": "41242",
328
                            'disk_format': 'diskdump'}
329

    
330

    
331
@patch('synnefo.api.util.get_image', fixed_image)
332
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
333
class ServerCreateAPITest(ComputeAPITest):
334
    def setUp(self):
335
        self.flavor = mfactory.FlavorFactory()
336
        # Create public network and backend
337
        self.network = mfactory.NetworkFactory(public=True)
338
        self.backend = mfactory.BackendFactory()
339
        mfactory.BackendNetworkFactory(network=self.network,
340
                                       backend=self.backend,
341
                                       operstate="ACTIVE")
342
        self.request = {
343
            "server": {
344
                "name": "new-server-test",
345
                "userid": "test_user",
346
                "imageRef": 1,
347
                "flavorRef": self.flavor.id,
348
                "metadata": {
349
                    "My Server Name": "Apache1"
350
                },
351
                "personality": []
352
            }
353
        }
354

    
355
    def test_create_server(self, mrapi):
356
        """Test if the create server call returns the expected response
357
           if a valid request has been speficied."""
358

    
359
        mrapi().CreateInstance.return_value = 12
360
        with override_settings(settings, DEFAULT_INSTANCE_NETWORKS=[]):
361
            with mocked_quotaholder():
362
                response = self.mypost('servers', 'test_user',
363
                                       json.dumps(self.request), 'json')
364
        self.assertEqual(response.status_code, 202)
365
        mrapi().CreateInstance.assert_called_once()
366

    
367
        api_server = json.loads(response.content)['server']
368
        self.assertEqual(api_server['status'], "BUILD")
369
        self.assertEqual(api_server['progress'], 0)
370
        self.assertEqual(api_server['metadata'],
371
                         {"My Server Name":  "Apache1"})
372
        self.assertTrue('adminPass' in api_server)
373

    
374
        db_vm = VirtualMachine.objects.get(userid='test_user')
375
        self.assertEqual(api_server['name'], db_vm.name)
376
        self.assertEqual(api_server['status'], db_vm.operstate)
377

    
378
        # Test drained flag in Network:
379
        self.network.drained = True
380
        self.network.save()
381
        with mocked_quotaholder():
382
            response = self.mypost('servers', 'test_user',
383
                                   json.dumps(self.request), 'json')
384
        self.assertEqual(response.status_code, 503, "serviceUnavailable")
385

    
386
    def test_create_network_settings(self, mrapi):
387
        mrapi().CreateInstance.return_value = 12
388
        bnet1 = mfactory.BackendNetworkFactory(operstate="ACTIVE",
389
                                               backend=self.backend)
390
        bnet2 = mfactory.BackendNetworkFactory(operstate="ACTIVE",
391
                                               backend=self.backend)
392
        bnet3 = mfactory.BackendNetworkFactory(network__userid="test_user",
393
                                               operstate="ACTIVE",
394
                                               backend=self.backend)
395
        bnet4 = mfactory.BackendNetworkFactory(network__userid="test_user",
396
                                               operstate="ACTIVE",
397
                                               backend=self.backend)
398
        # User requested private networks
399
        request = deepcopy(self.request)
400
        request["server"]["networks"] = [bnet3.network.id, bnet4.network.id]
401
        with override_settings(settings,
402
                               DEFAULT_INSTANCE_NETWORKS=[
403
                                   "SNF:ANY_PUBLIC",
404
                                   bnet1.network.id,
405
                                   bnet2.network.id]):
406
            with mocked_quotaholder():
407
                response = self.mypost('servers', 'test_user',
408
                                       json.dumps(request), 'json')
409
        self.assertEqual(response.status_code, 202)
410
        name, args, kwargs = mrapi().CreateInstance.mock_calls[0]
411
        self.assertEqual(len(kwargs["nics"]), 5)
412
        self.assertEqual(kwargs["nics"][0]["network"],
413
                         self.network.backend_id)
414
        self.assertEqual(kwargs["nics"][1]["network"],
415
                         bnet1.network.backend_id)
416
        self.assertEqual(kwargs["nics"][2]["network"],
417
                         bnet2.network.backend_id)
418
        self.assertEqual(kwargs["nics"][3]["network"],
419
                         bnet3.network.backend_id)
420
        self.assertEqual(kwargs["nics"][4]["network"],
421
                         bnet4.network.backend_id)
422

    
423
        request["server"]["floating_ips"] = []
424
        with override_settings(settings,
425
                               DEFAULT_INSTANCE_NETWORKS=[bnet2.network.id]):
426
            with mocked_quotaholder():
427
                response = self.mypost('servers', 'test_user',
428
                                       json.dumps(request), 'json')
429
        self.assertEqual(response.status_code, 202)
430
        name, args, kwargs = mrapi().CreateInstance.mock_calls[1]
431
        self.assertEqual(len(kwargs["nics"]), 3)
432
        self.assertEqual(kwargs["nics"][0]["network"],
433
                         bnet2.network.backend_id)
434
        self.assertEqual(kwargs["nics"][1]["network"],
435
                         bnet3.network.backend_id)
436
        self.assertEqual(kwargs["nics"][2]["network"],
437
                         bnet4.network.backend_id)
438

    
439
        # test invalid network in DEFAULT_INSTANCE_NETWORKS
440
        with override_settings(settings, DEFAULT_INSTANCE_NETWORKS=[42]):
441
            response = self.mypost('servers', 'test_user',
442
                                   json.dumps(request), 'json')
443
        self.assertFault(response, 500, "internalServerError")
444

    
445
        # test connect to public netwok
446
        request = deepcopy(self.request)
447
        request["server"]["networks"] = [self.network.id]
448
        with override_settings(settings,
449
                               DEFAULT_INSTANCE_NETWORKS=["SNF:ANY_PUBLIC"]):
450
            response = self.mypost('servers', 'test_user',
451
                                   json.dumps(request), 'json')
452
        self.assertFault(response, 403, "forbidden")
453
        # test wrong user
454
        request = deepcopy(self.request)
455
        request["server"]["networks"] = [bnet3.network.id]
456
        with override_settings(settings,
457
                               DEFAULT_INSTANCE_NETWORKS=["SNF:ANY_PUBLIC"]):
458
            with mocked_quotaholder():
459
                response = self.mypost('servers', 'dummy_user',
460
                                       json.dumps(request), 'json')
461
        self.assertItemNotFound(response)
462

    
463
        # Test floating IPs
464
        request = deepcopy(self.request)
465
        request["server"]["networks"] = [bnet4.network.id]
466
        network = mfactory.NetworkFactory(subnet="10.0.0.0/24")
467
        mfactory.BackendNetworkFactory(network=network,
468
                                       backend=self.backend,
469
                                       operstate="ACTIVE")
470
        fp1 = mfactory.FloatingIPFactory(ipv4="10.0.0.2",
471
                                         userid="test_user",
472
                                         network=network, machine=None)
473
        fp2 = mfactory.FloatingIPFactory(ipv4="10.0.0.3", network=network,
474
                                         userid="test_user",
475
                                         machine=None)
476
        request["server"]["floating_ips"] = [fp1.ipv4, fp2.ipv4]
477
        with override_settings(settings,
478
                               DEFAULT_INSTANCE_NETWORKS=[bnet3.network.id]):
479
            with mocked_quotaholder():
480
                response = self.mypost('servers', 'test_user',
481
                                       json.dumps(request), 'json')
482
        self.assertEqual(response.status_code, 202)
483
        api_server = json.loads(response.content)['server']
484
        vm = VirtualMachine.objects.get(id=api_server["id"])
485
        fp1 = FloatingIP.objects.get(id=fp1.id)
486
        fp2 = FloatingIP.objects.get(id=fp2.id)
487
        self.assertEqual(fp1.machine, vm)
488
        self.assertEqual(fp2.machine, vm)
489
        name, args, kwargs = mrapi().CreateInstance.mock_calls[2]
490
        self.assertEqual(len(kwargs["nics"]), 4)
491
        self.assertEqual(kwargs["nics"][0]["network"],
492
                         bnet3.network.backend_id)
493
        self.assertEqual(kwargs["nics"][1]["network"], network.backend_id)
494
        self.assertEqual(kwargs["nics"][1]["ip"], fp1.ipv4)
495
        self.assertEqual(kwargs["nics"][2]["network"], network.backend_id)
496
        self.assertEqual(kwargs["nics"][2]["ip"], fp2.ipv4)
497
        self.assertEqual(kwargs["nics"][3]["network"],
498
                         bnet4.network.backend_id)
499

    
500
    def test_create_server_no_flavor(self, mrapi):
501
        request = deepcopy(self.request)
502
        request["server"]["flavorRef"] = 42
503
        with mocked_quotaholder():
504
            response = self.mypost('servers', 'test_user',
505
                                   json.dumps(request), 'json')
506
        self.assertItemNotFound(response)
507

    
508

    
509
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
510
class ServerDestroyAPITest(ComputeAPITest):
511
    def test_delete_server(self, mrapi):
512
        vm = mfactory.VirtualMachineFactory()
513
        mrapi().DeleteInstance.return_value = 12
514
        response = self.mydelete('servers/%d' % vm.id, vm.userid)
515
        self.assertEqual(response.status_code, 204)
516
        mrapi().DeleteInstance.assert_called_once()
517

    
518
    def test_non_existing_delete_server(self, mrapi):
519
        vm = mfactory.VirtualMachineFactory()
520
        response = self.mydelete('servers/%d' % 42, vm.userid)
521
        self.assertItemNotFound(response)
522
        self.assertFalse(mrapi.mock_calls)
523

    
524

    
525
class ServerMetadataAPITest(ComputeAPITest):
526
    def setUp(self):
527
        self.vm = mfactory.VirtualMachineFactory()
528
        self.metadata = mfactory.VirtualMachineMetadataFactory(vm=self.vm)
529
        super(ServerMetadataAPITest, self).setUp()
530

    
531
    def test_get_metadata(self):
532
        vm = self.vm
533
        create_meta = lambda: mfactory.VirtualMachineMetadataFactory(vm=vm)
534
        metadata = [create_meta(), create_meta(), create_meta()]
535
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
536
        self.assertTrue(response.status_code in [200, 203])
537
        api_metadata = json.loads(response.content)['metadata']
538
        self.assertEqual(len(api_metadata), len(metadata) + 1)
539
        for db_m in metadata:
540
            self.assertEqual(api_metadata[db_m.meta_key], db_m.meta_value)
541

    
542
        request = {
543
            'metadata': {
544
                'foo': 'bar'
545
            },
546
            metadata[0].meta_key: 'bar2'
547
        }
548
        response = self.mypost('servers/%d/metadata' % vm.id,
549
                               vm.userid, json.dumps(request), 'json')
550
        metadata2 = VirtualMachineMetadata.objects.filter(vm=vm)
551
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
552
        self.assertTrue(response.status_code in [200, 203])
553
        api_metadata2 = json.loads(response.content)['metadata']
554
        self.assertTrue('foo' in api_metadata2.keys())
555
        self.assertTrue(api_metadata2[metadata[0].meta_key], 'bar2')
556
        self.assertEqual(len(api_metadata2), len(metadata2))
557
        for db_m in metadata2:
558
            self.assertEqual(api_metadata2[db_m.meta_key], db_m.meta_value)
559

    
560
        # Create new meta
561
        request = {'meta': {'foo2': 'bar2'}}
562
        response = self.myput('servers/%d/metadata/foo2' % vm.id,
563
                              vm.userid, json.dumps(request), 'json')
564

    
565
        # Get the new meta
566
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
567
        meta = json.loads(response.content)['meta']
568
        self.assertEqual(meta['foo2'], 'bar2')
569

    
570
        # Delete the new meta
571
        response = self.mydelete('servers/%d/metadata/foo2' % vm.id, vm.userid)
572
        self.assertEqual(response.status_code, 204)
573

    
574
        # Try to get the deleted meta: should raise 404
575
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
576
        self.assertEqual(response.status_code, 404)
577

    
578
    def test_invalid_metadata(self):
579
        vm = self.vm
580
        response = self.mypost('servers/%d/metadata' % vm.id, vm.userid)
581
        self.assertBadRequest(response)
582
        self.assertEqual(len(vm.metadata.all()), 1)
583

    
584
    def test_invalid_metadata_server(self):
585
        response = self.mypost('servers/42/metadata', 'user')
586
        self.assertItemNotFound(response)
587

    
588
    def test_get_meta_invalid_key(self):
589
        vm = self.vm
590
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
591
        self.assertItemNotFound(response)
592

    
593

    
594
@patch('synnefo.api.util.get_image')
595
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
596
class ServerActionAPITest(ComputeAPITest):
597
    def test_actions(self, mrapi, mimage):
598
        actions = ['start', 'shutdown', 'reboot']
599
        vm = mfactory.VirtualMachineFactory()
600
        vm.operstate = "STOPPED"
601
        vm.save()
602
        mrapi().StartupInstance.return_value = 0
603
        mrapi().ShutdownInstance.return_value = 1
604
        mrapi().RebootInstance.return_value = 2
605
        for jobId, action in enumerate(actions):
606
            if action in ["shutdown", "reboot"]:
607
                vm.operstate = "STARTED"
608
            else:
609
                vm.operstate = "STOPPED"
610
            vm.task = None
611
            vm.task_job_id = None
612
            vm.save()
613
            val = {'type': 'HARD'} if action == 'reboot' else {}
614
            request = {action: val}
615
            response = self.mypost('servers/%d/action' % vm.id,
616
                                   vm.userid, json.dumps(request), 'json')
617
            self.assertEqual(response.status_code, 202)
618
            if action == 'shutdown':
619
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
620
                                 "STOP")
621
            else:
622
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
623
                                 action.upper())
624
            self.assertEqual(VirtualMachine.objects.get(id=vm.id).task_job_id,
625
                             jobId)
626

    
627
    def test_action_in_building_vm(self, mrapi, mimage):
628
        """Test building in progress"""
629
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
630
        request = {'start': {}}
631
        with mocked_quotaholder():
632
            response = self.mypost('servers/%d/action' % vm.id,
633
                                   vm.userid, json.dumps(request), 'json')
634
        self.assertEqual(response.status_code, 409)
635
        self.assertFalse(mrapi.mock_calls)
636

    
637
    def test_destroy_build_vm(self, mrapi, mimage):
638
        """Test building in progress"""
639
        vm = mfactory.VirtualMachineFactory()
640
        mrapi().DeleteInstance.return_value = 2
641
        response = self.mydelete('servers/%d' % vm.id,
642
                                 vm.userid)
643
        self.assertSuccess(response)
644
        mrapi().RemoveInstance.assert_called_once()
645

    
646
    def test_firewall(self, mrapi, mimage):
647
        vm = mfactory.VirtualMachineFactory()
648
        vm.operstate = "STOPPED"
649
        vm.save()
650
        request = {'firewallProfile': {'profile': 'PROTECTED'}}
651
        response = self.mypost('servers/%d/action' % vm.id,
652
                               vm.userid, json.dumps(request), 'json')
653
        self.assertEqual(response.status_code, 202)
654
        mrapi().ModifyInstance.assert_called_once()
655

    
656
    def test_unsupported_firewall(self, mrapi, mimage):
657
        vm = mfactory.VirtualMachineFactory()
658
        vm.operstate = "STOPPED"
659
        vm.save()
660
        request = {'firewallProfile': {'profile': 'FOO'}}
661
        response = self.mypost('servers/%d/action' % vm.id,
662
                               vm.userid, json.dumps(request), 'json')
663
        self.assertBadRequest(response)
664
        self.assertFalse(mrapi.mock_calls)
665

    
666
    def test_resize_vm(self, mrapi, mimage):
667
        flavor = mfactory.FlavorFactory(cpu=1, ram=1024)
668
        # Check building VM
669
        vm = self.get_vm(flavor=flavor, operstate="BUILD")
670
        request = {'resize': {'flavorRef': flavor.id}}
671
        response = self.mypost('servers/%d/action' % vm.id,
672
                               vm.userid, json.dumps(request), 'json')
673
        self.assertFault(response, 409, "buildInProgress")
674
        # Check same Flavor
675
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
676
        request = {'resize': {'flavorRef': flavor.id}}
677
        response = self.mypost('servers/%d/action' % vm.id,
678
                               vm.userid, json.dumps(request), 'json')
679
        self.assertBadRequest(response)
680
        # Check flavor with different disk
681
        flavor2 = mfactory.FlavorFactory(disk=1024)
682
        flavor3 = mfactory.FlavorFactory(disk=2048)
683
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
684
        request = {'resize': {'flavorRef': flavor3.id}}
685
        response = self.mypost('servers/%d/action' % vm.id,
686
                               vm.userid, json.dumps(request), 'json')
687
        self.assertBadRequest(response)
688
        flavor2 = mfactory.FlavorFactory(disk_template="foo")
689
        flavor3 = mfactory.FlavorFactory(disk_template="baz")
690
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
691
        request = {'resize': {'flavorRef': flavor3.id}}
692
        response = self.mypost('servers/%d/action' % vm.id,
693
                               vm.userid, json.dumps(request), 'json')
694
        self.assertBadRequest(response)
695
        # Check success
696
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
697
        flavor4 = mfactory.FlavorFactory(disk_template=flavor.disk_template,
698
                                         disk=flavor.disk,
699
                                         cpu=4, ram=2048)
700
        request = {'resize': {'flavorRef': flavor4.id}}
701
        mrapi().ModifyInstance.return_value = 42
702
        response = self.mypost('servers/%d/action' % vm.id,
703
                               vm.userid, json.dumps(request), 'json')
704
        self.assertEqual(response.status_code, 202)
705
        vm = VirtualMachine.objects.get(id=vm.id)
706
        self.assertEqual(vm.task_job_id, 42)
707
        name, args, kwargs = mrapi().ModifyInstance.mock_calls[0]
708
        self.assertEqual(kwargs["beparams"]["vcpus"], 4)
709
        self.assertEqual(kwargs["beparams"]["minmem"], 2048)
710
        self.assertEqual(kwargs["beparams"]["maxmem"], 2048)
711

    
712
    def test_action_on_resizing_vm(self, mrapi, mimage):
713
        vm = mfactory.VirtualMachineFactory()
714
        vm.operstate = "RESIZE"
715
        vm.save()
716
        for action in VirtualMachine.ACTIONS:
717
            request = {action[0]: ""}
718
            response = self.mypost('servers/%d/action' % vm.id,
719
                                   vm.userid, json.dumps(request), 'json')
720
            self.assertBadRequest(response)
721
        # however you can destroy
722
        mrapi().DeleteInstance.return_value = 42
723
        response = self.mydelete('servers/%d' % vm.id,
724
                                 vm.userid)
725
        self.assertSuccess(response)
726

    
727
    def get_vm(self, flavor, operstate):
728
        vm = mfactory.VirtualMachineFactory(flavor=flavor)
729
        vm.operstate = operstate
730
        vm.backendjobstatus = "success"
731
        vm.save()
732
        return vm
733

    
734

    
735
class ServerVNCConsole(ComputeAPITest):
736
    def test_not_active_server(self):
737
        """Test console req for not ACTIVE server returns badRequest"""
738
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
739
        data = json.dumps({'console': {'type': 'vnc'}})
740
        response = self.mypost('servers/%d/action' % vm.id,
741
                               vm.userid, data, 'json')
742
        self.assertBadRequest(response)
743

    
744
    def test_active_server(self):
745
        """Test console req for ACTIVE server"""
746
        vm = mfactory.VirtualMachineFactory()
747
        vm.operstate = 'STARTED'
748
        vm.save()
749

    
750
        data = json.dumps({'console': {'type': 'vnc'}})
751
        with override_settings(settings, TEST=True):
752
            response = self.mypost('servers/%d/action' % vm.id,
753
                                   vm.userid, data, 'json')
754
        self.assertEqual(response.status_code, 200)
755
        reply = json.loads(response.content)
756
        self.assertEqual(reply.keys(), ['console'])
757
        console = reply['console']
758
        self.assertEqual(console['type'], 'vnc')
759
        self.assertEqual(set(console.keys()),
760
                         set(['type', 'host', 'port', 'password']))
761

    
762
    def test_wrong_console_type(self):
763
        """Test console req for ACTIVE server"""
764
        vm = mfactory.VirtualMachineFactory()
765
        vm.operstate = 'STARTED'
766
        vm.save()
767

    
768
        data = json.dumps({'console': {'type': 'foo'}})
769
        response = self.mypost('servers/%d/action' % vm.id,
770
                               vm.userid, data, 'json')
771
        self.assertBadRequest(response)