Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / test / servers.py @ 9446e7e5

History | View | Annotate | Download (30.1 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 synnefo 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
        metadata = server['metadata']
153
        self.assertEqual(len(metadata), 1)
154
        self.assertEqual(metadata[db_vm_meta.meta_key], db_vm_meta.meta_value)
155
        self.assertSuccess(response)
156

    
157
    def test_server_building_nics(self):
158
        db_vm = self.vm2
159
        user = self.vm2.userid
160
        net1 = mfactory.NetworkFactory()
161
        net2 = mfactory.NetworkFactory()
162
        net3 = mfactory.NetworkFactory()
163
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net1,
164
                                         state="BUILDING")
165
        nic2 = mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net2,
166
                                                state="ACTIVE")
167
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net3,
168
                                         state="BUILDING")
169

    
170
        response = self.myget('servers/%d' % db_vm.id, user)
171
        server = json.loads(response.content)['server']
172
        nics = server["attachments"]
173
        self.assertEqual(len(nics), 1)
174
        self.assertEqual(nics[0]["network_id"], str(nic2.network_id))
175

    
176
    def test_noauthorized(self):
177
        """Test 404 for detail of other user vm"""
178
        db_vm = self.vm2
179

    
180
        response = self.myget('servers/%d' % db_vm.id, 'wrong_user')
181
        self.assertItemNotFound(response)
182

    
183
    def test_wrong_server(self):
184
        """Test 404 response if server does not exist."""
185
        response = self.myget('servers/%d' % 5000)
186
        self.assertItemNotFound(response)
187

    
188
    def test_create_server_empty(self):
189
        """Test if the create server call returns a 400 badRequest if
190
           no attributes are specified."""
191

    
192
        response = self.mypost('servers', params={})
193
        self.assertBadRequest(response)
194

    
195
    def test_rename_server(self):
196
        vm = self.vm2
197
        request = {'server': {'name': 'new_name'}}
198
        response = self.myput('servers/%d' % vm.id, vm.userid,
199
                              json.dumps(request), 'json')
200
        self.assertSuccess(response)
201
        self.assertEqual(VirtualMachine.objects.get(id=vm.id).name, "new_name")
202

    
203
    def test_catch_wrong_api_paths(self):
204
        response = self.myget('nonexistent')
205
        self.assertEqual(response.status_code, 400)
206
        try:
207
            error = json.loads(response.content)
208
        except ValueError:
209
            self.assertTrue(False)
210

    
211
    def test_method_not_allowed(self, *args):
212
        # /servers/ allows only POST, GET
213
        response = self.myput('servers', '', '')
214
        self.assertMethodNotAllowed(response)
215
        response = self.mydelete('servers')
216
        self.assertMethodNotAllowed(response)
217

    
218
        # /servers/<srvid>/ allows only GET, PUT, DELETE
219
        response = self.mypost("servers/42")
220
        self.assertMethodNotAllowed(response)
221

    
222
        # /imags/<srvid>/metadata/ allows only POST, GET
223
        response = self.myput('servers/42/metadata', '', '')
224
        self.assertMethodNotAllowed(response)
225
        response = self.mydelete('servers/42/metadata')
226
        self.assertMethodNotAllowed(response)
227

    
228
        # /imags/<srvid>/metadata/ allows only POST, GET
229
        response = self.myput('servers/42/metadata', '', '')
230
        self.assertMethodNotAllowed(response)
231
        response = self.mydelete('servers/42/metadata')
232
        self.assertMethodNotAllowed(response)
233

    
234
        # /imags/<srvid>/metadata/<key> allows only PUT, GET, DELETE
235
        response = self.mypost('servers/42/metadata/foo')
236
        self.assertMethodNotAllowed(response)
237

    
238

    
239
fixed_image = Mock()
240
fixed_image.return_value = {'location': 'pithos://foo',
241
                            'checksum': '1234',
242
                            "id": 1,
243
                            "name": "test_image",
244
                            'disk_format': 'diskdump'}
245

    
246

    
247
@patch('synnefo.api.util.get_image', fixed_image)
248
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
249
class ServerCreateAPITest(ComputeAPITest):
250
    def setUp(self):
251
        self.flavor = mfactory.FlavorFactory()
252
        # Create public network and backend
253
        self.network = mfactory.NetworkFactory(public=True)
254
        self.backend = mfactory.BackendFactory()
255
        mfactory.BackendNetworkFactory(network=self.network,
256
                                       backend=self.backend,
257
                                       operstate="ACTIVE")
258
        self.request = {
259
                    "server": {
260
                        "name": "new-server-test",
261
                        "userid": "test_user",
262
                        "imageRef": 1,
263
                        "flavorRef": self.flavor.id,
264
                        "metadata": {
265
                            "My Server Name": "Apache1"
266
                        },
267
                        "personality": []
268
                    }
269
        }
270

    
271
    def test_create_server(self, mrapi):
272
        """Test if the create server call returns the expected response
273
           if a valid request has been speficied."""
274

    
275
        mrapi().CreateInstance.return_value = 12
276
        with override_settings(settings, DEFAULT_INSTANCE_NETWORKS=[]):
277
            with mocked_quotaholder():
278
                response = self.mypost('servers', 'test_user',
279
                                       json.dumps(self.request), 'json')
280
        self.assertEqual(response.status_code, 202)
281
        mrapi().CreateInstance.assert_called_once()
282

    
283
        api_server = json.loads(response.content)['server']
284
        self.assertEqual(api_server['status'], "BUILD")
285
        self.assertEqual(api_server['progress'], 0)
286
        self.assertEqual(api_server['metadata'],
287
                        {"My Server Name":  "Apache1"})
288
        self.assertTrue('adminPass' in api_server)
289

    
290
        db_vm = VirtualMachine.objects.get(userid='test_user')
291
        self.assertEqual(api_server['name'], db_vm.name)
292
        self.assertEqual(api_server['status'], db_vm.operstate)
293

    
294
        # Test drained flag in Network:
295
        self.network.drained = True
296
        self.network.save()
297
        with mocked_quotaholder():
298
            response = self.mypost('servers', 'test_user',
299
                                   json.dumps(self.request), 'json')
300
        self.assertEqual(response.status_code, 503, "serviceUnavailable")
301

    
302
    def test_create_network_settings(self, mrapi):
303
        mrapi().CreateInstance.return_value = 12
304
        bnet1 = mfactory.BackendNetworkFactory(operstate="ACTIVE",
305
                                               backend=self.backend)
306
        bnet2 = mfactory.BackendNetworkFactory(operstate="ACTIVE",
307
                                               backend=self.backend)
308
        bnet3 = mfactory.BackendNetworkFactory(network__userid="test_user",
309
                                               operstate="ACTIVE",
310
                                               backend=self.backend)
311
        bnet4 = mfactory.BackendNetworkFactory(network__userid="test_user",
312
                                               operstate="ACTIVE",
313
                                               backend=self.backend)
314
        # User requested private networks
315
        request = deepcopy(self.request)
316
        request["server"]["networks"] = [bnet3.network.id, bnet4.network.id]
317
        with override_settings(settings,
318
                DEFAULT_INSTANCE_NETWORKS=["SNF:ANY_PUBLIC", bnet1.network.id,
319
                                           bnet2.network.id]):
320
            with mocked_quotaholder():
321
                response = self.mypost('servers', 'test_user',
322
                                       json.dumps(request), 'json')
323
        self.assertEqual(response.status_code, 202)
324
        name, args, kwargs = mrapi().CreateInstance.mock_calls[0]
325
        self.assertEqual(len(kwargs["nics"]), 5)
326
        self.assertEqual(kwargs["nics"][0]["network"],
327
                         self.network.backend_id)
328
        self.assertEqual(kwargs["nics"][1]["network"],
329
                         bnet1.network.backend_id)
330
        self.assertEqual(kwargs["nics"][2]["network"],
331
                         bnet2.network.backend_id)
332
        self.assertEqual(kwargs["nics"][3]["network"],
333
                         bnet3.network.backend_id)
334
        self.assertEqual(kwargs["nics"][4]["network"],
335
                         bnet4.network.backend_id)
336

    
337
        request["server"]["floating_ips"] = []
338
        with override_settings(settings,
339
                DEFAULT_INSTANCE_NETWORKS=[bnet2.network.id]):
340
            with mocked_quotaholder():
341
                response = self.mypost('servers', 'test_user',
342
                                       json.dumps(request), 'json')
343
        self.assertEqual(response.status_code, 202)
344
        name, args, kwargs = mrapi().CreateInstance.mock_calls[1]
345
        self.assertEqual(len(kwargs["nics"]), 3)
346
        self.assertEqual(kwargs["nics"][0]["network"],
347
                         bnet2.network.backend_id)
348
        self.assertEqual(kwargs["nics"][1]["network"],
349
                         bnet3.network.backend_id)
350
        self.assertEqual(kwargs["nics"][2]["network"],
351
                         bnet4.network.backend_id)
352

    
353
        # test invalid network in DEFAULT_INSTANCE_NETWORKS
354
        with override_settings(settings, DEFAULT_INSTANCE_NETWORKS=[42]):
355
            response = self.mypost('servers', 'test_user',
356
                                   json.dumps(request), 'json')
357
        self.assertFault(response, 500, "internalServerError")
358

    
359
        # test connect to public netwok
360
        request = deepcopy(self.request)
361
        request["server"]["networks"] = [self.network.id]
362
        with override_settings(settings,
363
                               DEFAULT_INSTANCE_NETWORKS=["SNF:ANY_PUBLIC"]):
364
            response = self.mypost('servers', 'test_user',
365
                                    json.dumps(request), 'json')
366
        self.assertFault(response, 403, "forbidden")
367
        # test wrong user
368
        request = deepcopy(self.request)
369
        request["server"]["networks"] = [bnet3.network.id]
370
        with override_settings(settings,
371
                               DEFAULT_INSTANCE_NETWORKS=["SNF:ANY_PUBLIC"]):
372
            with mocked_quotaholder():
373
                response = self.mypost('servers', 'dummy_user',
374
                                       json.dumps(request), 'json')
375
        self.assertItemNotFound(response)
376

    
377
        # Test floating IPs
378
        request = deepcopy(self.request)
379
        request["server"]["networks"] = [bnet4.network.id]
380
        network = mfactory.NetworkFactory(subnet="10.0.0.0/24")
381
        mfactory.BackendNetworkFactory(network=network,
382
                                       backend=self.backend,
383
                                       operstate="ACTIVE")
384
        fp1 = mfactory.FloatingIPFactory(ipv4="10.0.0.2",
385
                                         userid="test_user",
386
                                         network=network, machine=None)
387
        fp2 = mfactory.FloatingIPFactory(ipv4="10.0.0.3", network=network,
388
                                         userid="test_user",
389
                                         machine=None)
390
        request["server"]["floating_ips"] = [fp1.ipv4, fp2.ipv4]
391
        with override_settings(settings,
392
                DEFAULT_INSTANCE_NETWORKS=[bnet3.network.id]):
393
            with mocked_quotaholder():
394
                response = self.mypost('servers', 'test_user',
395
                                     json.dumps(request), 'json')
396
        self.assertEqual(response.status_code, 202)
397
        api_server = json.loads(response.content)['server']
398
        vm = VirtualMachine.objects.get(id=api_server["id"])
399
        fp1 = FloatingIP.objects.get(id=fp1.id)
400
        fp2 = FloatingIP.objects.get(id=fp2.id)
401
        self.assertEqual(fp1.machine, vm)
402
        self.assertEqual(fp2.machine, vm)
403
        name, args, kwargs = mrapi().CreateInstance.mock_calls[2]
404
        self.assertEqual(len(kwargs["nics"]), 4)
405
        self.assertEqual(kwargs["nics"][0]["network"],
406
                         bnet3.network.backend_id)
407
        self.assertEqual(kwargs["nics"][1]["network"], network.backend_id)
408
        self.assertEqual(kwargs["nics"][1]["ip"], fp1.ipv4)
409
        self.assertEqual(kwargs["nics"][2]["network"], network.backend_id)
410
        self.assertEqual(kwargs["nics"][2]["ip"], fp2.ipv4)
411
        self.assertEqual(kwargs["nics"][3]["network"],
412
                         bnet4.network.backend_id)
413

    
414
    def test_create_server_no_flavor(self, mrapi):
415
        request = deepcopy(self.request)
416
        request["server"]["flavorRef"] = 42
417
        with mocked_quotaholder():
418
            response = self.mypost('servers', 'test_user',
419
                                   json.dumps(request), 'json')
420
        self.assertItemNotFound(response)
421

    
422

    
423
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
424
class ServerDestroyAPITest(ComputeAPITest):
425
    def test_delete_server(self, mrapi):
426
        vm = mfactory.VirtualMachineFactory()
427
        mrapi().DeleteInstance.return_value = 12
428
        response = self.mydelete('servers/%d' % vm.id, vm.userid)
429
        self.assertEqual(response.status_code, 204)
430
        mrapi().DeleteInstance.assert_called_once()
431

    
432
    def test_non_existing_delete_server(self, mrapi):
433
        vm = mfactory.VirtualMachineFactory()
434
        response = self.mydelete('servers/%d' % 42, vm.userid)
435
        self.assertItemNotFound(response)
436
        self.assertFalse(mrapi.mock_calls)
437

    
438

    
439
class ServerMetadataAPITest(ComputeAPITest):
440
    def setUp(self):
441
        self.vm = mfactory.VirtualMachineFactory()
442
        self.metadata = mfactory.VirtualMachineMetadataFactory(vm=self.vm)
443
        super(ServerMetadataAPITest, self).setUp()
444

    
445
    def test_get_metadata(self):
446
        vm = self.vm
447
        create_meta = lambda: mfactory.VirtualMachineMetadataFactory(vm=vm)
448
        metadata = [create_meta(), create_meta(), create_meta()]
449
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
450
        self.assertTrue(response.status_code in [200, 203])
451
        api_metadata = json.loads(response.content)['metadata']
452
        self.assertEqual(len(api_metadata), len(metadata) + 1)
453
        for db_m in metadata:
454
            self.assertEqual(api_metadata[db_m.meta_key], db_m.meta_value)
455

    
456
        request = {'metadata':
457
                        {'foo': 'bar'},
458
                        metadata[0].meta_key: 'bar2'
459
                  }
460
        response = self.mypost('servers/%d/metadata' % vm.id,
461
                             vm.userid, json.dumps(request), 'json')
462
        metadata2 = VirtualMachineMetadata.objects.filter(vm=vm)
463
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
464
        self.assertTrue(response.status_code in [200, 203])
465
        api_metadata2 = json.loads(response.content)['metadata']
466
        self.assertTrue('foo' in api_metadata2.keys())
467
        self.assertTrue(api_metadata2[metadata[0].meta_key], 'bar2')
468
        self.assertEqual(len(api_metadata2), len(metadata2))
469
        for db_m in metadata2:
470
            self.assertEqual(api_metadata2[db_m.meta_key], db_m.meta_value)
471

    
472
        # Create new meta
473
        request = {'meta': {'foo2': 'bar2'}}
474
        response = self.myput('servers/%d/metadata/foo2' % vm.id,
475
                              vm.userid, json.dumps(request), 'json')
476

    
477
        # Get the new meta
478
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
479
        meta = json.loads(response.content)['meta']
480
        self.assertEqual(meta['foo2'], 'bar2')
481

    
482
        # Delete the new meta
483
        response = self.mydelete('servers/%d/metadata/foo2' % vm.id, vm.userid)
484
        self.assertEqual(response.status_code, 204)
485

    
486
        # Try to get the deleted meta: should raise 404
487
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
488
        self.assertEqual(response.status_code, 404)
489

    
490
    def test_invalid_metadata(self):
491
        vm = self.vm
492
        response = self.mypost('servers/%d/metadata' % vm.id, vm.userid)
493
        self.assertBadRequest(response)
494
        self.assertEqual(len(vm.metadata.all()), 1)
495

    
496
    def test_invalid_metadata_server(self):
497
        response = self.mypost('servers/42/metadata', 'user')
498
        self.assertItemNotFound(response)
499

    
500
    def test_get_meta_invalid_key(self):
501
        vm = self.vm
502
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
503
        self.assertItemNotFound(response)
504

    
505

    
506
@patch('synnefo.api.util.get_image')
507
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
508
class ServerActionAPITest(ComputeAPITest):
509
    def test_actions(self, mrapi, mimage):
510
        actions = ['start', 'shutdown', 'reboot']
511
        vm = mfactory.VirtualMachineFactory()
512
        vm.operstate = "STOPPED"
513
        vm.save()
514
        mrapi().StartupInstance.return_value = 0
515
        mrapi().ShutdownInstance.return_value = 1
516
        mrapi().RebootInstance.return_value = 2
517
        for jobId, action in enumerate(actions):
518
            if action in ["shutdown", "reboot"]:
519
                vm.operstate = "STARTED"
520
            else:
521
                vm.operstate = "STOPPED"
522
            vm.task = None
523
            vm.task_job_id = None
524
            vm.save()
525
            val = {'type': 'HARD'} if action == 'reboot' else {}
526
            request = {action: val}
527
            response = self.mypost('servers/%d/action' % vm.id,
528
                                   vm.userid, json.dumps(request), 'json')
529
            self.assertEqual(response.status_code, 202)
530
            if action == 'shutdown':
531
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
532
                                 "STOP")
533
            else:
534
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).task,
535
                                 action.upper())
536
            self.assertEqual(VirtualMachine.objects.get(id=vm.id).task_job_id,
537
                             jobId)
538

    
539
    def test_action_in_building_vm(self, mrapi, mimage):
540
        """Test building in progress"""
541
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
542
        request = {'start': {}}
543
        with mocked_quotaholder():
544
            response = self.mypost('servers/%d/action' % vm.id,
545
                                   vm.userid, json.dumps(request), 'json')
546
        self.assertEqual(response.status_code, 409)
547
        self.assertFalse(mrapi.mock_calls)
548

    
549
    def test_destroy_build_vm(self, mrapi, mimage):
550
        """Test building in progress"""
551
        vm = mfactory.VirtualMachineFactory()
552
        mrapi().DeleteInstance.return_value = 2
553
        response = self.mydelete('servers/%d' % vm.id,
554
                                 vm.userid)
555
        self.assertSuccess(response)
556
        mrapi().RemoveInstance.assert_called_once()
557

    
558
    def test_firewall(self, mrapi, mimage):
559
        vm = mfactory.VirtualMachineFactory()
560
        vm.operstate = "STOPPED"
561
        vm.save()
562
        request = {'firewallProfile': {'profile': 'PROTECTED'}}
563
        response = self.mypost('servers/%d/action' % vm.id,
564
                               vm.userid, json.dumps(request), 'json')
565
        self.assertEqual(response.status_code, 202)
566
        mrapi().ModifyInstance.assert_called_once()
567

    
568
    def test_unsupported_firewall(self, mrapi, mimage):
569
        vm = mfactory.VirtualMachineFactory()
570
        vm.operstate = "STOPPED"
571
        vm.save()
572
        request = {'firewallProfile': {'profile': 'FOO'}}
573
        response = self.mypost('servers/%d/action' % vm.id,
574
                               vm.userid, json.dumps(request), 'json')
575
        self.assertBadRequest(response)
576
        self.assertFalse(mrapi.mock_calls)
577

    
578
    def test_resize_vm(self, mrapi, mimage):
579
        flavor = mfactory.FlavorFactory(cpu=1, ram=1024)
580
        # Check building VM
581
        vm = self.get_vm(flavor=flavor, operstate="BUILD")
582
        request = {'resize': {'flavorRef': flavor.id}}
583
        response = self.mypost('servers/%d/action' % vm.id,
584
                             vm.userid, json.dumps(request), 'json')
585
        self.assertFault(response, 409, "buildInProgress")
586
        # Check same Flavor
587
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
588
        request = {'resize': {'flavorRef': flavor.id}}
589
        response = self.mypost('servers/%d/action' % vm.id,
590
                             vm.userid, json.dumps(request), 'json')
591
        self.assertBadRequest(response)
592
        # Check flavor with different disk
593
        flavor2 = mfactory.FlavorFactory(disk=1024)
594
        flavor3 = mfactory.FlavorFactory(disk=2048)
595
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
596
        request = {'resize': {'flavorRef': flavor3.id}}
597
        response = self.mypost('servers/%d/action' % vm.id,
598
                             vm.userid, json.dumps(request), 'json')
599
        self.assertBadRequest(response)
600
        flavor2 = mfactory.FlavorFactory(disk_template="foo")
601
        flavor3 = mfactory.FlavorFactory(disk_template="baz")
602
        vm = self.get_vm(flavor=flavor2, operstate="STOPPED")
603
        request = {'resize': {'flavorRef': flavor3.id}}
604
        response = self.mypost('servers/%d/action' % vm.id,
605
                             vm.userid, json.dumps(request), 'json')
606
        self.assertBadRequest(response)
607
        # Check success
608
        vm = self.get_vm(flavor=flavor, operstate="STOPPED")
609
        flavor4 = mfactory.FlavorFactory(disk_template=flavor.disk_template,
610
                                         disk=flavor.disk,
611
                                         cpu=4, ram=2048)
612
        request = {'resize': {'flavorRef': flavor4.id}}
613
        mrapi().ModifyInstance.return_value = 42
614
        response = self.mypost('servers/%d/action' % vm.id,
615
                             vm.userid, json.dumps(request), 'json')
616
        self.assertEqual(response.status_code, 202)
617
        vm = VirtualMachine.objects.get(id=vm.id)
618
        self.assertEqual(vm.task_job_id, 42)
619
        name, args, kwargs = mrapi().ModifyInstance.mock_calls[0]
620
        self.assertEqual(kwargs["beparams"]["vcpus"], 4)
621
        self.assertEqual(kwargs["beparams"]["minmem"], 2048)
622
        self.assertEqual(kwargs["beparams"]["maxmem"], 2048)
623

    
624
    def test_action_on_resizing_vm(self, mrapi, mimage):
625
        vm = mfactory.VirtualMachineFactory()
626
        vm.operstate = "RESIZE"
627
        vm.save()
628
        for action in VirtualMachine.ACTIONS:
629
            request = {action[0]: ""}
630
            response = self.mypost('servers/%d/action' % vm.id,
631
                                 vm.userid, json.dumps(request), 'json')
632
            self.assertBadRequest(response)
633
        # however you can destroy
634
        mrapi().DeleteInstance.return_value = 42
635
        response = self.mydelete('servers/%d' % vm.id,
636
                                 vm.userid)
637
        self.assertSuccess(response)
638

    
639
    def get_vm(self, flavor, operstate):
640
        vm = mfactory.VirtualMachineFactory(flavor=flavor)
641
        vm.operstate = operstate
642
        vm.backendjobstatus = "success"
643
        vm.save()
644
        return vm
645

    
646

    
647
class ServerVNCConsole(ComputeAPITest):
648
    def test_not_active_server(self):
649
        """Test console req for not ACTIVE server returns badRequest"""
650
        vm = mfactory.VirtualMachineFactory(operstate="BUILD")
651
        data = json.dumps({'console': {'type': 'vnc'}})
652
        response = self.mypost('servers/%d/action' % vm.id,
653
                               vm.userid, data, 'json')
654
        self.assertBadRequest(response)
655

    
656
    def test_active_server(self):
657
        """Test console req for ACTIVE server"""
658
        vm = mfactory.VirtualMachineFactory()
659
        vm.operstate = 'STARTED'
660
        vm.save()
661

    
662
        data = json.dumps({'console': {'type': 'vnc'}})
663
        with override_settings(settings, TEST=True):
664
            response = self.mypost('servers/%d/action' % vm.id,
665
                                   vm.userid, data, 'json')
666
        self.assertEqual(response.status_code, 200)
667
        reply = json.loads(response.content)
668
        self.assertEqual(reply.keys(), ['console'])
669
        console = reply['console']
670
        self.assertEqual(console['type'], 'vnc')
671
        self.assertEqual(set(console.keys()),
672
                         set(['type', 'host', 'port', 'password']))
673

    
674
    def test_wrong_console_type(self):
675
        """Test console req for ACTIVE server"""
676
        vm = mfactory.VirtualMachineFactory()
677
        vm.operstate = 'STARTED'
678
        vm.save()
679

    
680
        data = json.dumps({'console': {'type': 'foo'}})
681
        response = self.mypost('servers/%d/action' % vm.id,
682
                               vm.userid, data, 'json')
683
        self.assertBadRequest(response)