Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / test / servers.py @ 920af09f

History | View | Annotate | Download (16.3 kB)

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

    
34
import json
35

    
36
from synnefo.api.tests import  BaseAPITest
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

    
41
from mock import patch
42

    
43

    
44
class ServerAPITest(BaseAPITest):
45
    def setUp(self):
46
        self.user1 = 'user1'
47
        self.user2 = 'user2'
48
        self.vm1 = mfactory.VirtualMachineFactory(userid=self.user1)
49
        self.vm2 = mfactory.VirtualMachineFactory(userid=self.user2)
50
        self.vm3 = mfactory.VirtualMachineFactory(deleted=True,
51
                                                  userid=self.user1)
52
        self.vm4 = mfactory.VirtualMachineFactory(userid=self.user2)
53

    
54
    def test_server_list_1(self):
55
        """Test if the expected list of servers is returned."""
56
        response = self.get('/api/v1.1/servers')
57
        self.assertSuccess(response)
58
        servers = json.loads(response.content)['servers']['values']
59
        self.assertEqual(servers, [])
60

    
61
    def test_server_list_2(self):
62
        """Test if the expected list of servers is returned."""
63
        response = self.get('/api/v1.1/servers', self.user1)
64
        self.assertSuccess(response)
65
        servers = json.loads(response.content)['servers']['values']
66
        db_server = self.vm1
67
        self.assertEqual(servers, [{'name': db_server.name,
68
                                    'id': db_server.id}])
69

    
70
    def test_server_list_detail(self):
71
        """Test if the servers list details are returned."""
72
        user = self.user2
73
        user_vms = {self.vm2.id: self.vm2,
74
                    self.vm4.id: self.vm4}
75

    
76
        response = self.get('/api/v1.1/servers/detail', user)
77
        servers = json.loads(response.content)['servers']['values']
78
        self.assertEqual(len(servers), len(user_vms))
79
        for api_vm in servers:
80
            db_vm = user_vms[api_vm['id']]
81
            self.assertEqual(api_vm['flavorRef'], db_vm.flavor.id)
82
            self.assertEqual(api_vm['hostId'], db_vm.hostid)
83
            self.assertEqual(api_vm['id'], db_vm.id)
84
            self.assertEqual(api_vm['imageRef'], db_vm.imageid)
85
            self.assertEqual(api_vm['name'], db_vm.name)
86
            self.assertEqual(api_vm['status'], get_rsapi_state(db_vm))
87
            self.assertSuccess(response)
88

    
89
    def test_server_detail(self):
90
        """Test if a server details are returned."""
91
        db_vm = self.vm2
92
        user = self.vm2.userid
93
        net = mfactory.NetworkFactory()
94
        nic = mfactory.NetworkInterfaceFactory(machine=self.vm2, network=net)
95

    
96
        db_vm_meta = mfactory.VirtualMachineMetadataFactory(vm=db_vm)
97

    
98
        response = self.get('/api/v1.1/servers/%d' % db_vm.id, user)
99
        server = json.loads(response.content)['server']
100

    
101
        self.assertEqual(server['flavorRef'], db_vm.flavor.id)
102
        self.assertEqual(server['hostId'], db_vm.hostid)
103
        self.assertEqual(server['id'], db_vm.id)
104
        self.assertEqual(server['imageRef'], db_vm.imageid)
105
        self.assertEqual(server['name'], db_vm.name)
106
        self.assertEqual(server['status'], get_rsapi_state(db_vm))
107
        api_nic = server['attachments']['values'][0]
108
        self.assertEqual(api_nic['network_id'], str(net.id))
109
        self.assertEqual(api_nic['mac_address'], nic.mac)
110
        self.assertEqual(api_nic['firewallProfile'], nic.firewall_profile)
111
        self.assertEqual(api_nic['ipv4'], nic.ipv4)
112
        self.assertEqual(api_nic['ipv6'], nic.ipv6)
113
        self.assertEqual(api_nic['id'], 'nic-%s-%s' % (db_vm.id, nic.index))
114

    
115
        metadata = server['metadata']['values']
116
        self.assertEqual(len(metadata), 1)
117
        self.assertEqual(metadata[db_vm_meta.meta_key], db_vm_meta.meta_value)
118
        self.assertSuccess(response)
119

    
120
    def test_noauthorized(self):
121
        """Test 404 for detail of other user vm"""
122
        db_vm = self.vm2
123

    
124
        response = self.get('/api/v1.1/servers/%d' % db_vm.id, 'wrong_user')
125
        self.assertItemNotFound(response)
126

    
127
    def test_wrong_server(self):
128
        """Test 404 response if server does not exist."""
129
        response = self.get('/api/v1.1/servers/%d' % 5000)
130
        self.assertItemNotFound(response)
131

    
132
    def test_create_server_empty(self):
133
        """Test if the create server call returns a 400 badRequest if
134
           no attributes are specified."""
135

    
136
        response = self.post('/api/v1.1/servers', params={})
137
        self.assertBadRequest(response)
138

    
139
    def test_rename_server(self):
140
        vm = self.vm2
141
        request = {'server': {'name': 'new_name'}}
142
        response = self.put('/api/v1.1/servers/%d' % vm.id, vm.userid,
143
                            json.dumps(request), 'json')
144
        self.assertSuccess(response)
145
        self.assertEqual(VirtualMachine.objects.get(id=vm.id).name, "new_name")
146

    
147

    
148
@patch('synnefo.api.util.get_image')
149
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
150
class ServerCreateAPITest(BaseAPITest):
151
    def test_create_server(self, mrapi, mimage):
152
        """Test if the create server call returns the expected response
153
           if a valid request has been speficied."""
154
        mimage.return_value = {'location': 'pithos://foo',
155
                               'checksum': '1234',
156
                               'disk_format': 'diskdump'}
157
        mrapi().CreateInstance.return_value = 12
158
        flavor = mfactory.FlavorFactory()
159
        # Create public network and backend
160
        network = mfactory.NetworkFactory(public=True)
161
        backend = mfactory.BackendFactory()
162
        mfactory.BackendNetworkFactory(network=network, backend=backend)
163

    
164
        request = {
165
                    "server": {
166
                        "name": "new-server-test",
167
                        "userid": "test_user",
168
                        "imageRef": 1,
169
                        "flavorRef": flavor.id,
170
                        "metadata": {
171
                            "My Server Name": "Apache1"
172
                        },
173
                        "personality": []
174
                    }
175
        }
176
        response = self.post('/api/v1.1/servers', 'test_user',
177
                                 json.dumps(request), 'json')
178
        self.assertEqual(response.status_code, 202)
179
        mrapi().CreateInstance.assert_called_once()
180

    
181
        api_server = json.loads(response.content)['server']
182
        self.assertEqual(api_server['status'], "BUILD")
183
        self.assertEqual(api_server['progress'], 0)
184
        self.assertEqual(api_server['metadata']['values'],
185
                        {"My Server Name":  "Apache1"})
186
        self.assertTrue('adminPass' in api_server)
187

    
188
        db_vm = VirtualMachine.objects.get(userid='test_user')
189
        self.assertEqual(api_server['name'], db_vm.name)
190
        self.assertEqual(api_server['status'], db_vm.operstate)
191

    
192
    def test_create_server_no_flavor(self, mrapi, mimage):
193
        request = {
194
                    "server": {
195
                        "name": "new-server-test",
196
                        "userid": "test_user",
197
                        "imageRef": 1,
198
                        "flavorRef": 42,
199
                        "metadata": {
200
                            "My Server Name": "Apache1"
201
                        },
202
                        "personality": []
203
                    }
204
        }
205
        response = self.post('/api/v1.1/servers', 'test_user',
206
                                 json.dumps(request), 'json')
207
        self.assertItemNotFound(response)
208

    
209

    
210
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
211
class ServerDestroyAPITest(BaseAPITest):
212
    def test_delete_server(self, mrapi):
213
        vm = mfactory.VirtualMachineFactory()
214
        response = self.delete('/api/v1.1/servers/%d' % vm.id, vm.userid)
215
        self.assertEqual(response.status_code, 204)
216
        mrapi().DeleteInstance.assert_called_once()
217

    
218
    def test_non_existing_delete_server(self, mrapi):
219
        vm = mfactory.VirtualMachineFactory()
220
        response = self.delete('/api/v1.1/servers/%d' % 42, vm.userid)
221
        self.assertItemNotFound(response)
222
        self.assertFalse(mrapi.mock_calls)
223

    
224

    
225
class ServerMetadataAPITest(BaseAPITest):
226
    def setUp(self):
227
        self.vm = mfactory.VirtualMachineFactory()
228
        self.metadata = mfactory.VirtualMachineMetadataFactory(vm=self.vm)
229

    
230
    def test_get_metadata(self):
231
        vm = self.vm
232
        create_meta = lambda: mfactory.VirtualMachineMetadataFactory(vm=vm)
233
        metadata = [create_meta(), create_meta(), create_meta()]
234
        response = self.get('/api/v1.1/servers/%d/meta' % vm.id, vm.userid)
235
        self.assertTrue(response.status_code in [200, 203])
236
        api_metadata = json.loads(response.content)['metadata']['values']
237
        self.assertEqual(len(api_metadata), len(metadata) + 1)
238
        for db_m in metadata:
239
            self.assertEqual(api_metadata[db_m.meta_key], db_m.meta_value)
240

    
241
        request = {'metadata':
242
                        {'foo': 'bar'},
243
                        metadata[0].meta_key: 'bar2'
244
                  }
245
        response = self.post('/api/v1.1/servers/%d/meta' % vm.id, vm.userid,
246
                             json.dumps(request), 'json')
247
        metadata2 = VirtualMachineMetadata.objects.filter(vm=vm)
248
        response = self.get('/api/v1.1/servers/%d/meta' % vm.id, vm.userid)
249
        self.assertTrue(response.status_code in [200, 203])
250
        api_metadata2 = json.loads(response.content)['metadata']['values']
251
        self.assertTrue('foo' in api_metadata2.keys())
252
        self.assertTrue(api_metadata2[metadata[0].meta_key], 'bar2')
253
        self.assertEqual(len(api_metadata2), len(metadata2))
254
        for db_m in metadata2:
255
            self.assertEqual(api_metadata2[db_m.meta_key], db_m.meta_value)
256

    
257
        # Create new meta
258
        request = {'meta': {'foo2': 'bar2'}}
259
        response = self.put('/api/v1.1/servers/%d/meta/foo2' % vm.id,
260
                            vm.userid, json.dumps(request), 'json')
261

    
262
        # Get the new meta
263
        response = self.get('/api/v1.1/servers/%d/meta/foo2' % vm.id,
264
                            vm.userid)
265
        meta = json.loads(response.content)['meta']
266
        self.assertEqual(meta['foo2'], 'bar2')
267

    
268
        # Delete the new meta
269
        response = self.delete('/api/v1.1/servers/%d/meta/foo2' % vm.id,
270
                               vm.userid)
271
        self.assertEqual(response.status_code, 204)
272

    
273
        # Try to get the deleted meta: should raise 404
274
        response = self.get('/api/v1.1/servers/%d/meta/foo2' % vm.id,
275
                            vm.userid)
276
        self.assertEqual(response.status_code, 404)
277

    
278
    def test_invalid_metadata(self):
279
        vm = self.vm
280
        response = self.post('/api/v1.1/servers/%d/meta' % vm.id, vm.userid)
281
        self.assertBadRequest(response)
282
        self.assertEqual(len(vm.metadata.all()), 1)
283

    
284
    def test_invalid_metadata_server(self):
285
        response = self.post('/api/v1.1/servers/42/meta', 'user')
286
        self.assertItemNotFound(response)
287

    
288
    def test_get_meta_invalid_key(self):
289
        vm = self.vm
290
        response = self.get('/api/v1.1/servers/%d/meta/foo2' % vm.id,
291
                            vm.userid)
292
        self.assertItemNotFound(response)
293

    
294

    
295
@patch('synnefo.api.util.get_image')
296
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
297
class ServerActionAPITest(BaseAPITest):
298
    def test_actions(self, mrapi, mimage):
299
        actions = ['start', 'shutdown', 'reboot']
300
        vm = mfactory.VirtualMachineFactory()
301
        vm.operstate = "STOPPED"
302
        vm.save()
303
        for action in actions:
304
            val = {'type': 'HARD'} if action == 'reboot' else {}
305
            request = {action: val}
306
            response = self.post('/api/v1.1/servers/%d/action' % vm.id,
307
                                vm.userid, json.dumps(request), 'json')
308
            self.assertEqual(response.status_code, 202)
309
            if action == 'shutdown':
310
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).action,
311
                                 "STOP")
312
            else:
313
                self.assertEqual(VirtualMachine.objects.get(id=vm.id).action,
314
                                 action.upper())
315

    
316
    def test_action_in_building_vm(self, mrapi, mimage):
317
        """Test building in progress"""
318
        vm = mfactory.VirtualMachineFactory()
319
        request = {'start': '{}'}
320
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
321
                             vm.userid, json.dumps(request), 'json')
322
        self.assertEqual(response.status_code, 409)
323
        self.assertFalse(mrapi.mock_calls)
324

    
325
    def test_destroy_build_vm(self, mrapi, mimage):
326
        """Test building in progress"""
327
        vm = mfactory.VirtualMachineFactory()
328
        response = self.delete('/api/v1.1/servers/%d' % vm.id,
329
                             vm.userid)
330
        self.assertSuccess(response)
331
        mrapi().RemoveInstance.assert_called_once()
332

    
333
    def test_firewall(self, mrapi, mimage):
334
        vm = mfactory.VirtualMachineFactory()
335
        vm.operstate = "STOPPED"
336
        vm.save()
337
        request = {'firewallProfile': {'profile': 'PROTECTED'}}
338
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
339
                             vm.userid, json.dumps(request), 'json')
340
        self.assertEqual(response.status_code, 202)
341
        mrapi().ModifyInstance.assert_called_once()
342

    
343
    def test_unsupported_firewall(self, mrapi, mimage):
344
        vm = mfactory.VirtualMachineFactory()
345
        vm.operstate = "STOPPED"
346
        vm.save()
347
        request = {'firewallProfile': {'profile': 'FOO'}}
348
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
349
                             vm.userid, json.dumps(request), 'json')
350
        self.assertBadRequest(response)
351
        self.assertFalse(mrapi.mock_calls)
352

    
353

    
354
class ServerVNCConsole(BaseAPITest):
355
    def test_not_active_server(self):
356
        """Test console req for not ACTIVE server returns badRequest"""
357
        vm = mfactory.VirtualMachineFactory()
358
        data = json.dumps({'console': {'type': 'vnc'}})
359
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
360
                             vm.userid, data, 'json')
361
        self.assertBadRequest(response)
362

    
363
    def test_active_server(self):
364
        """Test console req for ACTIVE server"""
365
        vm = mfactory.VirtualMachineFactory()
366
        vm.operstate = 'STARTED'
367
        vm.save()
368

    
369
        data = json.dumps({'console': {'type': 'vnc'}})
370
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
371
                             vm.userid, data, 'json')
372
        self.assertEqual(response.status_code, 200)
373
        reply = json.loads(response.content)
374
        self.assertEqual(reply.keys(), ['console'])
375
        console = reply['console']
376
        self.assertEqual(console['type'], 'vnc')
377
        self.assertEqual(set(console.keys()),
378
                         set(['type', 'host', 'port', 'password']))
379

    
380
    def test_wrong_console_type(self):
381
        """Test console req for ACTIVE server"""
382
        vm = mfactory.VirtualMachineFactory()
383
        vm.operstate = 'STARTED'
384
        vm.save()
385

    
386
        data = json.dumps({'console': {'type': 'foo'}})
387
        response = self.post('/api/v1.1/servers/%d/action' % vm.id,
388
                             vm.userid, data, 'json')
389
        self.assertBadRequest(response)