Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / test / servers.py @ 78c165cf

History | View | Annotate | Download (30 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=["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, DEFAULT_INSTANCE_NETWORKS=["public"]):
363
            response = self.mypost('servers', 'test_user',
364
                                    json.dumps(request), 'json')
365
        self.assertFault(response, 403, "forbidden")
366
        # test wrong user
367
        request = deepcopy(self.request)
368
        request["server"]["networks"] = [bnet3.network.id]
369
        with override_settings(settings, DEFAULT_INSTANCE_NETWORKS=["public"]):
370
            with mocked_quotaholder():
371
                response = self.mypost('servers', 'dummy_user',
372
                                       json.dumps(request), 'json')
373
        self.assertItemNotFound(response)
374

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

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

    
420

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

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

    
436

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

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

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

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

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

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

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

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

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

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

    
503

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

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

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

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

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

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

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

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

    
644

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

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

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

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

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