Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (35.8 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
from synnefo.logic.rapi import GanetiApiError
48

    
49
from mock import patch, Mock
50

    
51

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

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

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

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

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

    
74

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
322

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

    
331

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

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

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

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

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

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

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

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

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

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

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

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

    
509
    def test_create_server_error(self, mrapi):
510
        """Test if the create server call returns the expected response
511
           if a valid request has been speficied."""
512
        mrapi().CreateInstance.side_effect = GanetiApiError("..ganeti is down")
513
        # Create public network and backend
514
        network = mfactory.NetworkFactory(public=True)
515
        backend = mfactory.BackendFactory()
516
        mfactory.BackendNetworkFactory(network=network, backend=backend)
517

    
518
        request = self.request
519
        with mocked_quotaholder():
520
            response = self.mypost('servers', 'test_user',
521
                                   json.dumps(request), 'json')
522
        self.assertEqual(response.status_code, 202)
523
        mrapi().CreateInstance.assert_called_once()
524
        vm = VirtualMachine.objects.get()
525
        # The VM has not been deleted
526
        self.assertFalse(vm.deleted)
527
        # but is in "ERROR" operstate
528
        self.assertEqual(vm.operstate, "ERROR")
529

    
530

    
531
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
532
class ServerDestroyAPITest(ComputeAPITest):
533
    def test_delete_server(self, mrapi):
534
        vm = mfactory.VirtualMachineFactory()
535
        mrapi().DeleteInstance.return_value = 12
536
        response = self.mydelete('servers/%d' % vm.id, vm.userid)
537
        self.assertEqual(response.status_code, 204)
538
        mrapi().DeleteInstance.assert_called_once()
539

    
540
    def test_non_existing_delete_server(self, mrapi):
541
        vm = mfactory.VirtualMachineFactory()
542
        response = self.mydelete('servers/%d' % 42, vm.userid)
543
        self.assertItemNotFound(response)
544
        self.assertFalse(mrapi.mock_calls)
545

    
546

    
547
class ServerMetadataAPITest(ComputeAPITest):
548
    def setUp(self):
549
        self.vm = mfactory.VirtualMachineFactory()
550
        self.metadata = mfactory.VirtualMachineMetadataFactory(vm=self.vm)
551
        super(ServerMetadataAPITest, self).setUp()
552

    
553
    def test_get_metadata(self):
554
        vm = self.vm
555
        create_meta = lambda: mfactory.VirtualMachineMetadataFactory(vm=vm)
556
        metadata = [create_meta(), create_meta(), create_meta()]
557
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
558
        self.assertTrue(response.status_code in [200, 203])
559
        api_metadata = json.loads(response.content)['metadata']
560
        self.assertEqual(len(api_metadata), len(metadata) + 1)
561
        for db_m in metadata:
562
            self.assertEqual(api_metadata[db_m.meta_key], db_m.meta_value)
563

    
564
        request = {
565
            'metadata': {
566
                'foo': 'bar'
567
            },
568
            metadata[0].meta_key: 'bar2'
569
        }
570
        response = self.mypost('servers/%d/metadata' % vm.id,
571
                               vm.userid, json.dumps(request), 'json')
572
        metadata2 = VirtualMachineMetadata.objects.filter(vm=vm)
573
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
574
        self.assertTrue(response.status_code in [200, 203])
575
        api_metadata2 = json.loads(response.content)['metadata']
576
        self.assertTrue('foo' in api_metadata2.keys())
577
        self.assertTrue(api_metadata2[metadata[0].meta_key], 'bar2')
578
        self.assertEqual(len(api_metadata2), len(metadata2))
579
        for db_m in metadata2:
580
            self.assertEqual(api_metadata2[db_m.meta_key], db_m.meta_value)
581

    
582
        # Create new meta
583
        request = {'meta': {'foo2': 'bar2'}}
584
        response = self.myput('servers/%d/metadata/foo2' % vm.id,
585
                              vm.userid, json.dumps(request), 'json')
586

    
587
        # Get the new meta
588
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
589
        meta = json.loads(response.content)['meta']
590
        self.assertEqual(meta['foo2'], 'bar2')
591

    
592
        # Delete the new meta
593
        response = self.mydelete('servers/%d/metadata/foo2' % vm.id, vm.userid)
594
        self.assertEqual(response.status_code, 204)
595

    
596
        # Try to get the deleted meta: should raise 404
597
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
598
        self.assertEqual(response.status_code, 404)
599

    
600
    def test_invalid_metadata(self):
601
        vm = self.vm
602
        response = self.mypost('servers/%d/metadata' % vm.id, vm.userid)
603
        self.assertBadRequest(response)
604
        self.assertEqual(len(vm.metadata.all()), 1)
605

    
606
    def test_invalid_metadata_server(self):
607
        response = self.mypost('servers/42/metadata', 'user')
608
        self.assertItemNotFound(response)
609

    
610
    def test_get_meta_invalid_key(self):
611
        vm = self.vm
612
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
613
        self.assertItemNotFound(response)
614

    
615

    
616
@patch('synnefo.api.util.get_image')
617
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
618
class ServerActionAPITest(ComputeAPITest):
619
    def test_actions(self, mrapi, mimage):
620
        actions = ['start', 'shutdown', 'reboot']
621
        vm = mfactory.VirtualMachineFactory()
622
        vm.operstate = "STOPPED"
623
        vm.save()
624
        mrapi().StartupInstance.return_value = 0
625
        mrapi().ShutdownInstance.return_value = 1
626
        mrapi().RebootInstance.return_value = 2
627
        for jobId, action in enumerate(actions):
628
            if action in ["shutdown", "reboot"]:
629
                vm.operstate = "STARTED"
630
            else:
631
                vm.operstate = "STOPPED"
632
            vm.task = None
633
            vm.task_job_id = None
634
            vm.save()
635
            val = {'type': 'HARD'} if action == 'reboot' else {}
636
            request = {action: val}
637
            response = self.mypost('servers/%d/action' % vm.id,
638
                                   vm.userid, json.dumps(request), 'json')
639
            self.assertEqual(response.status_code, 202)
640
            if action == 'shutdown':
641
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
642
                                 "STOP")
643
            else:
644
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
645
                                 action.upper())
646
            self.assertEqual(VirtualMachine.objects.get(id=vm.id).task_job_id,
647
                             jobId)
648

    
649
    def test_action_in_building_vm(self, mrapi, mimage):
650
        """Test building in progress"""
651
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
652
        request = {'start': {}}
653
        with mocked_quotaholder():
654
            response = self.mypost('servers/%d/action' % vm.id,
655
                                   vm.userid, json.dumps(request), 'json')
656
        self.assertEqual(response.status_code, 409)
657
        self.assertFalse(mrapi.mock_calls)
658

    
659
    def test_destroy_build_vm(self, mrapi, mimage):
660
        """Test building in progress"""
661
        vm = mfactory.VirtualMachineFactory()
662
        mrapi().DeleteInstance.return_value = 2
663
        response = self.mydelete('servers/%d' % vm.id,
664
                                 vm.userid)
665
        self.assertSuccess(response)
666
        mrapi().RemoveInstance.assert_called_once()
667

    
668
    def test_firewall(self, mrapi, mimage):
669
        vm = mfactory.VirtualMachineFactory()
670
        vm.operstate = "STOPPED"
671
        vm.save()
672
        request = {'firewallProfile': {'profile': 'PROTECTED'}}
673
        response = self.mypost('servers/%d/action' % vm.id,
674
                               vm.userid, json.dumps(request), 'json')
675
        self.assertBadRequest(response)
676
        request = {'firewallProfile': {'profile': 'PROTECTED', "nic": "10"}}
677
        response = self.mypost('servers/%d/action' % vm.id,
678
                               vm.userid, json.dumps(request), 'json')
679
        self.assertItemNotFound(response)
680
        nic = mfactory.NetworkInterfaceFactory(machine=vm)
681
        request = {'firewallProfile': {'profile': 'PROTECTED', "nic": nic.id}}
682
        response = self.mypost('servers/%d/action' % vm.id,
683
                               vm.userid, json.dumps(request), 'json')
684
        self.assertSuccess(response)
685
        mrapi().ModifyInstance.assert_called_once()
686

    
687
    def test_unsupported_firewall(self, mrapi, mimage):
688
        vm = mfactory.VirtualMachineFactory()
689
        vm.operstate = "STOPPED"
690
        vm.save()
691
        request = {'firewallProfile': {'profile': 'FOO'}}
692
        response = self.mypost('servers/%d/action' % vm.id,
693
                               vm.userid, json.dumps(request), 'json')
694
        self.assertBadRequest(response)
695
        self.assertFalse(mrapi.mock_calls)
696

    
697
    def test_resize_vm(self, mrapi, mimage):
698
        flavor = mfactory.FlavorFactory(cpu=1, ram=1024)
699
        # Check building VM
700
        vm = self.get_vm(flavor=flavor, operstate="BUILD")
701
        request = {'resize': {'flavorRef': flavor.id}}
702
        response = self.mypost('servers/%d/action' % vm.id,
703
                               vm.userid, json.dumps(request), 'json')
704
        self.assertFault(response, 409, "buildInProgress")
705
        # Check same Flavor
706
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
707
        request = {'resize': {'flavorRef': flavor.id}}
708
        response = self.mypost('servers/%d/action' % vm.id,
709
                               vm.userid, json.dumps(request), 'json')
710
        self.assertBadRequest(response)
711
        # Check flavor with different disk
712
        flavor2 = mfactory.FlavorFactory(disk=1024)
713
        flavor3 = mfactory.FlavorFactory(disk=2048)
714
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
715
        request = {'resize': {'flavorRef': flavor3.id}}
716
        response = self.mypost('servers/%d/action' % vm.id,
717
                               vm.userid, json.dumps(request), 'json')
718
        self.assertBadRequest(response)
719
        flavor2 = mfactory.FlavorFactory(disk_template="foo")
720
        flavor3 = mfactory.FlavorFactory(disk_template="baz")
721
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
722
        request = {'resize': {'flavorRef': flavor3.id}}
723
        response = self.mypost('servers/%d/action' % vm.id,
724
                               vm.userid, json.dumps(request), 'json')
725
        self.assertBadRequest(response)
726
        # Check success
727
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
728
        flavor4 = mfactory.FlavorFactory(disk_template=flavor.disk_template,
729
                                         disk=flavor.disk,
730
                                         cpu=4, ram=2048)
731
        request = {'resize': {'flavorRef': flavor4.id}}
732
        mrapi().ModifyInstance.return_value = 42
733
        response = self.mypost('servers/%d/action' % vm.id,
734
                               vm.userid, json.dumps(request), 'json')
735
        self.assertEqual(response.status_code, 202)
736
        vm = VirtualMachine.objects.get(id=vm.id)
737
        self.assertEqual(vm.task_job_id, 42)
738
        name, args, kwargs = mrapi().ModifyInstance.mock_calls[0]
739
        self.assertEqual(kwargs["beparams"]["vcpus"], 4)
740
        self.assertEqual(kwargs["beparams"]["minmem"], 2048)
741
        self.assertEqual(kwargs["beparams"]["maxmem"], 2048)
742

    
743
    def test_action_on_resizing_vm(self, mrapi, mimage):
744
        vm = mfactory.VirtualMachineFactory()
745
        vm.operstate = "RESIZE"
746
        vm.save()
747
        for action in VirtualMachine.ACTIONS:
748
            request = {action[0]: ""}
749
            response = self.mypost('servers/%d/action' % vm.id,
750
                                   vm.userid, json.dumps(request), 'json')
751
            self.assertBadRequest(response)
752
        # however you can destroy
753
        mrapi().DeleteInstance.return_value = 42
754
        response = self.mydelete('servers/%d' % vm.id,
755
                                 vm.userid)
756
        self.assertSuccess(response)
757

    
758
    def get_vm(self, flavor, operstate):
759
        vm = mfactory.VirtualMachineFactory(flavor=flavor)
760
        vm.operstate = operstate
761
        vm.backendjobstatus = "success"
762
        vm.save()
763
        return vm
764

    
765

    
766
class ServerVNCConsole(ComputeAPITest):
767
    def test_not_active_server(self):
768
        """Test console req for not ACTIVE server returns badRequest"""
769
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
770
        data = json.dumps({'console': {'type': 'vnc'}})
771
        response = self.mypost('servers/%d/action' % vm.id,
772
                               vm.userid, data, 'json')
773
        self.assertBadRequest(response)
774

    
775
    def test_active_server(self):
776
        """Test console req for ACTIVE server"""
777
        vm = mfactory.VirtualMachineFactory()
778
        vm.operstate = 'STARTED'
779
        vm.save()
780

    
781
        data = json.dumps({'console': {'type': 'vnc'}})
782
        with override_settings(settings, TEST=True):
783
            response = self.mypost('servers/%d/action' % vm.id,
784
                                   vm.userid, data, 'json')
785
        self.assertEqual(response.status_code, 200)
786
        reply = json.loads(response.content)
787
        self.assertEqual(reply.keys(), ['console'])
788
        console = reply['console']
789
        self.assertEqual(console['type'], 'vnc')
790
        self.assertEqual(set(console.keys()),
791
                         set(['type', 'host', 'port', 'password']))
792

    
793
    def test_wrong_console_type(self):
794
        """Test console req for ACTIVE server"""
795
        vm = mfactory.VirtualMachineFactory()
796
        vm.operstate = 'STARTED'
797
        vm.save()
798

    
799
        data = json.dumps({'console': {'type': 'foo'}})
800
        response = self.mypost('servers/%d/action' % vm.id,
801
                               vm.userid, data, 'json')
802
        self.assertBadRequest(response)