Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / test / servers.py @ 1f638a85

History | View | Annotate | Download (18.9 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

    
36
from snf_django.utils.testing import BaseAPITest, mocked_quotaholder
37
from synnefo.db.models import VirtualMachine, VirtualMachineMetadata
38
from synnefo.db import models_factory as mfactory
39
from synnefo.logic.utils import get_rsapi_state
40
from synnefo.cyclades_settings import cyclades_services
41
from synnefo.lib.services import get_service_path
42
from synnefo.lib import join_urls
43

    
44
from mock import patch
45

    
46

    
47
class ComputeAPITest(BaseAPITest):
48
    def setUp(self, *args, **kwargs):
49
        super(ComputeAPITest, self).setUp(*args, **kwargs)
50
        self.compute_path = get_service_path(cyclades_services, 'compute',
51
                                             version='v2.0')
52
    def myget(self, path, *args, **kwargs):
53
        path = join_urls(self.compute_path, path)
54
        return self.get(path, *args, **kwargs)
55

    
56
    def myput(self, path, *args, **kwargs):
57
        path = join_urls(self.compute_path, path)
58
        return self.put(path, *args, **kwargs)
59

    
60
    def mypost(self, path, *args, **kwargs):
61
        path = join_urls(self.compute_path, path)
62
        return self.post(path, *args, **kwargs)
63

    
64
    def mydelete(self, path, *args, **kwargs):
65
        path = join_urls(self.compute_path, path)
66
        return self.delete(path, *args, **kwargs)
67

    
68

    
69
class ServerAPITest(ComputeAPITest):
70
    def setUp(self):
71
        self.user1 = 'user1'
72
        self.user2 = 'user2'
73
        self.vm1 = mfactory.VirtualMachineFactory(userid=self.user1)
74
        self.vm2 = mfactory.VirtualMachineFactory(userid=self.user2)
75
        self.vm3 = mfactory.VirtualMachineFactory(deleted=True,
76
                                                  userid=self.user1)
77
        self.vm4 = mfactory.VirtualMachineFactory(userid=self.user2)
78
        super(ServerAPITest, self).setUp()
79

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

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

    
97
    def test_server_list_detail(self):
98
        """Test if the servers list details are returned."""
99
        user = self.user2
100
        user_vms = {self.vm2.id: self.vm2,
101
                    self.vm4.id: self.vm4}
102

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

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

    
124
        db_vm_meta = mfactory.VirtualMachineMetadataFactory(vm=db_vm)
125

    
126
        response = self.myget('servers/%d' % db_vm.id, user)
127
        server = json.loads(response.content)['server']
128

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

    
147
        metadata = server['metadata']
148
        self.assertEqual(len(metadata), 1)
149
        self.assertEqual(metadata[db_vm_meta.meta_key], db_vm_meta.meta_value)
150
        self.assertSuccess(response)
151

    
152
    def test_server_building_nics(self):
153
        db_vm = self.vm2
154
        user = self.vm2.userid
155
        net1 = mfactory.NetworkFactory()
156
        net2 = mfactory.NetworkFactory()
157
        net3 = mfactory.NetworkFactory()
158
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net1,
159
                                         state="BUILDING")
160
        nic2 = mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net2,
161
                                                state="ACTIVE")
162
        mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net3,
163
                                         state="BUILDING")
164

    
165
        response = self.myget('servers/%d' % db_vm.id, user)
166
        server = json.loads(response.content)['server']
167
        nics = server["attachments"]
168
        self.assertEqual(len(nics), 1)
169
        self.assertEqual(nics[0]["network_id"], str(nic2.network_id))
170

    
171
    def test_noauthorized(self):
172
        """Test 404 for detail of other user vm"""
173
        db_vm = self.vm2
174

    
175
        response = self.myget('servers/%d' % db_vm.id, 'wrong_user')
176
        self.assertItemNotFound(response)
177

    
178
    def test_wrong_server(self):
179
        """Test 404 response if server does not exist."""
180
        response = self.myget('servers/%d' % 5000)
181
        self.assertItemNotFound(response)
182

    
183
    def test_create_server_empty(self):
184
        """Test if the create server call returns a 400 badRequest if
185
           no attributes are specified."""
186

    
187
        response = self.mypost('servers', params={})
188
        self.assertBadRequest(response)
189

    
190
    def test_rename_server(self):
191
        vm = self.vm2
192
        request = {'server': {'name': 'new_name'}}
193
        response = self.myput('servers/%d' % vm.id, vm.userid,
194
                              json.dumps(request), 'json')
195
        self.assertSuccess(response)
196
        self.assertEqual(VirtualMachine.objects.get(id=vm.id).name, "new_name")
197

    
198
    def test_catch_wrong_api_paths(self):
199
        response = self.myget('nonexistent')
200
        self.assertEqual(response.status_code, 400)
201
        try:
202
            error = json.loads(response.content)
203
        except ValueError:
204
            self.assertTrue(False)
205

    
206

    
207
@patch('synnefo.api.util.get_image')
208
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
209
class ServerCreateAPITest(ComputeAPITest):
210
    def test_create_server(self, mrapi, mimage):
211
        """Test if the create server call returns the expected response
212
           if a valid request has been speficied."""
213
        mimage.return_value = {'location': 'pithos://foo',
214
                               'checksum': '1234',
215
                               "id": 1,
216
                               "name": "test_image",
217
                               'disk_format': 'diskdump'}
218
        mrapi().CreateInstance.return_value = 12
219
        flavor = mfactory.FlavorFactory()
220
        # Create public network and backend
221
        network = mfactory.NetworkFactory(public=True)
222
        backend = mfactory.BackendFactory()
223
        mfactory.BackendNetworkFactory(network=network, backend=backend)
224

    
225
        request = {
226
                    "server": {
227
                        "name": "new-server-test",
228
                        "userid": "test_user",
229
                        "imageRef": 1,
230
                        "flavorRef": flavor.id,
231
                        "metadata": {
232
                            "My Server Name": "Apache1"
233
                        },
234
                        "personality": []
235
                    }
236
        }
237
        with mocked_quotaholder():
238
            response = self.mypost('servers', 'test_user',
239
                                   json.dumps(request), 'json')
240
        self.assertEqual(response.status_code, 202)
241
        mrapi().CreateInstance.assert_called_once()
242

    
243
        api_server = json.loads(response.content)['server']
244
        self.assertEqual(api_server['status'], "BUILD")
245
        self.assertEqual(api_server['progress'], 0)
246
        self.assertEqual(api_server['metadata'],
247
                        {"My Server Name":  "Apache1"})
248
        self.assertTrue('adminPass' in api_server)
249

    
250
        db_vm = VirtualMachine.objects.get(userid='test_user')
251
        self.assertEqual(api_server['name'], db_vm.name)
252
        self.assertEqual(api_server['status'], db_vm.operstate)
253

    
254
        # Test drained flag in Network:
255
        network.drained = True
256
        network.save()
257
        with mocked_quotaholder():
258
            response = self.mypost('servers', 'test_user',
259
                                    json.dumps(request), 'json')
260
        self.assertEqual(response.status_code, 503, "serviceUnavailable")
261

    
262
    def test_create_server_no_flavor(self, mrapi, mimage):
263
        request = {
264
                    "server": {
265
                        "name": "new-server-test",
266
                        "userid": "test_user",
267
                        "imageRef": 1,
268
                        "flavorRef": 42,
269
                        "metadata": {
270
                            "My Server Name": "Apache1"
271
                        },
272
                        "personality": []
273
                    }
274
        }
275
        response = self.mypost('servers', 'test_user',
276
                               json.dumps(request), 'json')
277
        self.assertItemNotFound(response)
278

    
279

    
280
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
281
class ServerDestroyAPITest(ComputeAPITest):
282
    def test_delete_server(self, mrapi):
283
        vm = mfactory.VirtualMachineFactory()
284
        response = self.mydelete('servers/%d' % vm.id, vm.userid)
285
        self.assertEqual(response.status_code, 204)
286
        mrapi().DeleteInstance.assert_called_once()
287

    
288
    def test_non_existing_delete_server(self, mrapi):
289
        vm = mfactory.VirtualMachineFactory()
290
        response = self.mydelete('servers/%d' % 42, vm.userid)
291
        self.assertItemNotFound(response)
292
        self.assertFalse(mrapi.mock_calls)
293

    
294

    
295
class ServerMetadataAPITest(ComputeAPITest):
296
    def setUp(self):
297
        self.vm = mfactory.VirtualMachineFactory()
298
        self.metadata = mfactory.VirtualMachineMetadataFactory(vm=self.vm)
299
        super(ServerMetadataAPITest, self).setUp()
300

    
301
    def test_get_metadata(self):
302
        vm = self.vm
303
        create_meta = lambda: mfactory.VirtualMachineMetadataFactory(vm=vm)
304
        metadata = [create_meta(), create_meta(), create_meta()]
305
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
306
        self.assertTrue(response.status_code in [200, 203])
307
        api_metadata = json.loads(response.content)['metadata']
308
        self.assertEqual(len(api_metadata), len(metadata) + 1)
309
        for db_m in metadata:
310
            self.assertEqual(api_metadata[db_m.meta_key], db_m.meta_value)
311

    
312
        request = {'metadata':
313
                        {'foo': 'bar'},
314
                        metadata[0].meta_key: 'bar2'
315
                  }
316
        response = self.mypost('servers/%d/metadata' % vm.id,
317
                             vm.userid, json.dumps(request), 'json')
318
        metadata2 = VirtualMachineMetadata.objects.filter(vm=vm)
319
        response = self.myget('servers/%d/metadata' % vm.id, vm.userid)
320
        self.assertTrue(response.status_code in [200, 203])
321
        api_metadata2 = json.loads(response.content)['metadata']
322
        self.assertTrue('foo' in api_metadata2.keys())
323
        self.assertTrue(api_metadata2[metadata[0].meta_key], 'bar2')
324
        self.assertEqual(len(api_metadata2), len(metadata2))
325
        for db_m in metadata2:
326
            self.assertEqual(api_metadata2[db_m.meta_key], db_m.meta_value)
327

    
328
        # Create new meta
329
        request = {'meta': {'foo2': 'bar2'}}
330
        response = self.myput('servers/%d/metadata/foo2' % vm.id,
331
                              vm.userid, json.dumps(request), 'json')
332

    
333
        # Get the new meta
334
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
335
        meta = json.loads(response.content)['meta']
336
        self.assertEqual(meta['foo2'], 'bar2')
337

    
338
        # Delete the new meta
339
        response = self.mydelete('servers/%d/metadata/foo2' % vm.id, vm.userid)
340
        self.assertEqual(response.status_code, 204)
341

    
342
        # Try to get the deleted meta: should raise 404
343
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
344
        self.assertEqual(response.status_code, 404)
345

    
346
    def test_invalid_metadata(self):
347
        vm = self.vm
348
        response = self.mypost('servers/%d/metadata' % vm.id, vm.userid)
349
        self.assertBadRequest(response)
350
        self.assertEqual(len(vm.metadata.all()), 1)
351

    
352
    def test_invalid_metadata_server(self):
353
        response = self.mypost('servers/42/metadata', 'user')
354
        self.assertItemNotFound(response)
355

    
356
    def test_get_meta_invalid_key(self):
357
        vm = self.vm
358
        response = self.myget('servers/%d/metadata/foo2' % vm.id, vm.userid)
359
        self.assertItemNotFound(response)
360

    
361

    
362
@patch('synnefo.api.util.get_image')
363
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
364
class ServerActionAPITest(ComputeAPITest):
365
    def test_actions(self, mrapi, mimage):
366
        actions = ['start', 'shutdown', 'reboot']
367
        vm = mfactory.VirtualMachineFactory()
368
        vm.operstate = "STOPPED"
369
        vm.save()
370
        for action in actions:
371
            val = {'type': 'HARD'} if action == 'reboot' else {}
372
            request = {action: val}
373
            response = self.mypost('servers/%d/action' % vm.id,
374
                                   vm.userid, json.dumps(request), 'json')
375
            self.assertEqual(response.status_code, 202)
376
            if action == 'shutdown':
377
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).action,
378
                                 "STOP")
379
            else:
380
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).action,
381
                                 action.upper())
382

    
383
    def test_action_in_building_vm(self, mrapi, mimage):
384
        """Test building in progress"""
385
        vm = mfactory.VirtualMachineFactory()
386
        request = {'start': '{}'}
387
        response = self.mypost('servers/%d/action' % vm.id,
388
                               vm.userid, json.dumps(request), 'json')
389
        self.assertEqual(response.status_code, 409)
390
        self.assertFalse(mrapi.mock_calls)
391

    
392
    def test_destroy_build_vm(self, mrapi, mimage):
393
        """Test building in progress"""
394
        vm = mfactory.VirtualMachineFactory()
395
        response = self.mydelete('servers/%d' % vm.id, vm.userid)
396
        self.assertSuccess(response)
397
        mrapi().RemoveInstance.assert_called_once()
398

    
399
    def test_firewall(self, mrapi, mimage):
400
        vm = mfactory.VirtualMachineFactory()
401
        vm.operstate = "STOPPED"
402
        vm.save()
403
        request = {'firewallProfile': {'profile': 'PROTECTED'}}
404
        response = self.mypost('servers/%d/action' % vm.id,
405
                               vm.userid, json.dumps(request), 'json')
406
        self.assertEqual(response.status_code, 202)
407
        mrapi().ModifyInstance.assert_called_once()
408

    
409
    def test_unsupported_firewall(self, mrapi, mimage):
410
        vm = mfactory.VirtualMachineFactory()
411
        vm.operstate = "STOPPED"
412
        vm.save()
413
        request = {'firewallProfile': {'profile': 'FOO'}}
414
        response = self.mypost('servers/%d/action' % vm.id,
415
                               vm.userid, json.dumps(request), 'json')
416
        self.assertBadRequest(response)
417
        self.assertFalse(mrapi.mock_calls)
418

    
419

    
420
class ServerVNCConsole(ComputeAPITest):
421
    def test_not_active_server(self):
422
        """Test console req for not ACTIVE server returns badRequest"""
423
        vm = mfactory.VirtualMachineFactory()
424
        data = json.dumps({'console': {'type': 'vnc'}})
425
        response = self.mypost('servers/%d/action' % vm.id,
426
                               vm.userid, data, 'json')
427
        self.assertBadRequest(response)
428

    
429
    def test_active_server(self):
430
        """Test console req for ACTIVE server"""
431
        vm = mfactory.VirtualMachineFactory()
432
        vm.operstate = 'STARTED'
433
        vm.save()
434

    
435
        data = json.dumps({'console': {'type': 'vnc'}})
436
        response = self.mypost('servers/%d/action' % vm.id,
437
                               vm.userid, data, 'json')
438
        self.assertEqual(response.status_code, 200)
439
        reply = json.loads(response.content)
440
        self.assertEqual(reply.keys(), ['console'])
441
        console = reply['console']
442
        self.assertEqual(console['type'], 'vnc')
443
        self.assertEqual(set(console.keys()),
444
                         set(['type', 'host', 'port', 'password']))
445

    
446
    def test_wrong_console_type(self):
447
        """Test console req for ACTIVE server"""
448
        vm = mfactory.VirtualMachineFactory()
449
        vm.operstate = 'STARTED'
450
        vm.save()
451

    
452
        data = json.dumps({'console': {'type': 'foo'}})
453
        response = self.mypost('servers/%d/action' % vm.id,
454
                               vm.userid, data, 'json')
455
        self.assertBadRequest(response)