Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / test / networks.py @ acda838e

History | View | Annotate | Download (19.8 kB)

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

    
34
import json
35
from mock import patch
36

    
37
from snf_django.utils.testing import BaseAPITest, mocked_quotaholder
38
from synnefo.db.models import Network, NetworkInterface
39
from synnefo.db import models_factory as mfactory
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

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

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

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

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

    
66

    
67
@patch('synnefo.logic.rapi_pool.GanetiRapiClient')
68
class NetworkAPITest(ComputeAPITest):
69
    def setUp(self):
70
        self.mac_prefixes = mfactory.MacPrefixPoolTableFactory()
71
        self.bridges = mfactory.BridgePoolTableFactory(base="link")
72
        self.user = 'dummy-user'
73
        self.net1 = mfactory.NetworkFactory(userid=self.user)
74
        self.vm1 = mfactory.VirtualMachineFactory(userid=self.user)
75
        self.nic1 = mfactory.NetworkInterfaceFactory(network=self.net1,
76
                                                     machine=self.vm1)
77
        self.nic2 = mfactory.NetworkInterfaceFactory(network=self.net1,
78
                                                     machine=self.vm1)
79
        self.net2 = mfactory.NetworkFactory(userid=self.user)
80
        self.nic3 = mfactory.NetworkInterfaceFactory(network=self.net2)
81
        super(NetworkAPITest, self).setUp()
82

    
83
    def assertNetworksEqual(self, db_net, api_net, detail=False):
84
        self.assertEqual(str(db_net.id), api_net["id"])
85
        self.assertEqual(db_net.name, api_net['name'])
86
        if detail:
87
            self.assertEqual(db_net.state, api_net['status'])
88
            self.assertEqual(db_net.flavor, api_net['type'])
89
            self.assertEqual(db_net.subnet, api_net['cidr'])
90
            self.assertEqual(db_net.subnet6, api_net['cidr6'])
91
            self.assertEqual(db_net.gateway, api_net['gateway'])
92
            self.assertEqual(db_net.gateway6, api_net['gateway6'])
93
            self.assertEqual(db_net.dhcp, api_net['dhcp'])
94
            self.assertEqual(db_net.public, api_net['public'])
95
            db_nics = ["nic-%d-%d" % (nic.machine.id, nic.index) for nic in
96
                       db_net.nics.filter(machine__userid=db_net.userid)]
97
            self.assertEqual(db_nics, api_net['attachments'])
98

    
99
    def test_create_network_1(self, mrapi):
100
        request = {
101
            'network': {'name': 'foo', "type": "MAC_FILTERED"}
102
        }
103
        with mocked_quotaholder():
104
            response = self.mypost('networks/', 'user1',
105
                                   json.dumps(request), 'json')
106
        self.assertEqual(response.status_code, 202)
107
        db_networks = Network.objects.filter(userid='user1')
108
        self.assertEqual(len(db_networks), 1)
109
        db_net = db_networks[0]
110
        api_net = json.loads(response.content)['network']
111
        self.assertNetworksEqual(db_net, api_net)
112
        mrapi.CreateNetwork.assert_called()
113
        mrapi.ConnectNetwork.assert_called()
114

    
115
    def test_invalid_data_1(self, mrapi):
116
        """Test invalid flavor"""
117
        request = {
118
            'network': {'name': 'foo', 'type': 'LoLo'}
119
            }
120
        response = self.mypost('networks/', 'user1',
121
                               json.dumps(request), 'json')
122
        self.assertBadRequest(response)
123
        self.assertEqual(len(Network.objects.filter(userid='user1')), 0)
124

    
125
    def test_invalid_data_2(self, mrapi):
126
        """Test invalid data/subnet"""
127
        request = {
128
            'network': {'name': 'foo',
129
                        'cidr': '10.0.0.0/8', "type":
130
                        "MAC_FILTERED"}
131
        }
132
        response = self.mypost('networks/', 'user1',
133
                               json.dumps(request), 'json')
134
        self.assertFault(response, 413, "overLimit")
135

    
136
    def test_invalid_data_3(self, mrapi):
137
        """Test unauthorized to create public network"""
138
        request = {
139
                'network': {'name': 'foo',
140
                            "public": "True",
141
                            "type": "MAC_FILTERED"}
142
            }
143
        response = self.mypost('networks/', 'user1',
144
                               json.dumps(request), 'json')
145
        self.assertFault(response, 403, "forbidden")
146

    
147
    def test_invalid_data_4(self, mrapi):
148
        """Test unauthorized to create network not in settings"""
149
        request = {
150
                'network': {'name': 'foo', 'type': 'CUSTOM'}
151
            }
152
        response = self.mypost('networks/', 'user1',
153
                               json.dumps(request), 'json')
154
        self.assertFault(response, 403, "forbidden")
155

    
156
    def test_invalid_subnet(self, mrapi):
157
        """Test invalid subnet"""
158
        request = {
159
            'network': {'name': 'foo',
160
                        'cidr': '10.0.0.10/27',
161
                        "type": "MAC_FILTERED"}
162
        }
163
        response = self.mypost('networks/', 'user1',
164
                               json.dumps(request), 'json')
165
        self.assertBadRequest(response)
166

    
167
    def test_invalid_gateway_1(self, mrapi):
168
        request = {
169
            'network': {'name': 'foo',
170
                        'cidr': '10.0.0.0/28',
171
                        'gateway': '10.0.0.0.300'}
172
        }
173
        response = self.mypost('networks/', 'user1',
174
                               json.dumps(request), 'json')
175
        self.assertBadRequest(response)
176

    
177
    def test_invalid_gateway_2(self, mrapi):
178
        request = {
179
            'network': {'name': 'foo',
180
                        'cidr': '10.0.0.0/28',
181
                        'gateway': '10.2.0.1'}
182
        }
183
        response = self.mypost('networks/', 'user1',
184
                               json.dumps(request), 'json')
185
        self.assertBadRequest(response)
186

    
187
    def test_invalid_network6(self, mrapi):
188
        request = {
189
            'network': {'name': 'foo',
190
                        'cidr': '10.0.0.0/28',
191
                        'subnet6': '10.0.0.0/28',
192
                        'gateway': '10.2.0.1'}
193
        }
194
        response = self.mypost('networks/', 'user1',
195
                               json.dumps(request), 'json')
196
        self.assertBadRequest(response)
197

    
198
    def test_invalid_gateway6(self, mrapi):
199
        request = {
200
            'network': {'name': 'foo',
201
                        'cidr': '10.0.0.0/28',
202
                        'subnet6': '2001:0db8:0123:4567:89ab:cdef:1234:5678',
203
                        'gateway': '10.2.0.1'}
204
        }
205
        response = self.mypost('networks/', 'user1',
206
                               json.dumps(request), 'json')
207
        self.assertBadRequest(response)
208

    
209
    def test_list_networks(self, mrapi):
210
        """Test that expected list of networks is returned."""
211
        # Create a deleted network
212
        mfactory.NetworkFactory(userid=self.user, deleted=True)
213

    
214
        response = self.myget('networks/', self.user)
215
        self.assertSuccess(response)
216

    
217
        db_nets = Network.objects.filter(userid=self.user, deleted=False)
218
        api_nets = json.loads(response.content)["networks"]
219

    
220
        self.assertEqual(len(db_nets), len(api_nets))
221
        for api_net in api_nets:
222
            net_id = api_net['id']
223
            self.assertNetworksEqual(Network.objects.get(id=net_id), api_net)
224

    
225
    def test_list_networks_detail(self, mrapi):
226
        """Test that expected networks details are returned."""
227
        # Create a deleted network
228
        mfactory.NetworkFactory(userid=self.user, deleted=True)
229

    
230
        response = self.myget('networks/detail', self.user)
231
        self.assertSuccess(response)
232

    
233
        db_nets = Network.objects.filter(userid=self.user, deleted=False)
234
        api_nets = json.loads(response.content)["networks"]
235

    
236
        self.assertEqual(len(db_nets), len(api_nets))
237
        for api_net in api_nets:
238
            net_id = api_net['id']
239
            self.assertNetworksEqual(Network.objects.get(id=net_id), api_net,
240
                                     detail=True)
241

    
242
    def test_get_network_building_nics(self, mrapi):
243
        net = mfactory.NetworkFactory()
244
        machine = mfactory.VirtualMachineFactory(userid=net.userid)
245
        mfactory.NetworkInterfaceFactory(network=net, machine=machine,
246
                                         state="BUILDING")
247
        response = self.myget('networks/%d' % net.id, net.userid)
248
        self.assertSuccess(response)
249
        api_net = json.loads(response.content)["network"]
250
        self.assertEqual(len(api_net["attachments"]), 0)
251

    
252
    def test_network_details_1(self, mrapi):
253
        """Test that expected details for a network are returned"""
254
        response = self.myget('networks/%d' % self.net1.id, self.net1.userid)
255
        self.assertSuccess(response)
256
        api_net = json.loads(response.content)["network"]
257
        self.assertNetworksEqual(self.net1, api_net, detail=True)
258

    
259
    def test_invalid_network(self, mrapi):
260
        """Test details for non-existing network."""
261
        response = self.myget('networks/%d' % 42, self.net1.userid)
262
        self.assertItemNotFound(response)
263

    
264
    def test_rename_network(self, mrapi):
265
        request = {'network': {'name': "new_name"}}
266
        response = self.myput('networks/%d' % self.net2.id,
267
                              self.net2.userid, json.dumps(request), 'json')
268
        self.assertEqual(response.status_code, 204)
269
        self.assertEqual(Network.objects.get(id=self.net2.id).name, "new_name")
270
        # Check invalid
271
        request = {'name': "new_name"}
272
        response = self.myput('networks/%d' % self.net2.id,
273
                              self.net2.userid, json.dumps(request), 'json')
274
        self.assertBadRequest(response)
275

    
276
    def test_rename_deleted_network(self, mrapi):
277
        net = mfactory.NetworkFactory(deleted=True)
278
        request = {'network': {'name': "new_name"}}
279
        response = self.myput('networks/%d' % net.id,
280
                              net.userid, json.dumps(request), 'json')
281
        self.assertBadRequest(response)
282

    
283
    def test_rename_public_network(self, mrapi):
284
        net = mfactory.NetworkFactory(public=True)
285
        request = {'network': {'name': "new_name"}}
286
        response = self.myput('networks/%d' % net.id,
287
                              self.net2.userid, json.dumps(request), 'json')
288
        self.assertFault(response, 403, 'forbidden')
289

    
290
    def test_delete_network(self, mrapi):
291
        net = mfactory.NetworkFactory(deleted=False, state='ACTIVE',
292
                                      link="link-10")
293
        with mocked_quotaholder():
294
            response = self.mydelete('networks/%d' % net.id, net.userid)
295
        self.assertEqual(response.status_code, 204)
296
        net = Network.objects.get(id=net.id, userid=net.userid)
297
        self.assertEqual(net.action, 'DESTROY')
298
        mrapi.DeleteNetwork.assert_called()
299

    
300
    def test_delete_public_network(self, mrapi):
301
        net = mfactory.NetworkFactory(public=True)
302
        response = self.mydelete('networks/%d' % net.id, self.net2.userid)
303
        self.assertFault(response, 403, 'forbidden')
304
        self.assertFalse(mrapi.called)
305

    
306
    def test_delete_deleted_network(self, mrapi):
307
        net = mfactory.NetworkFactory(deleted=True)
308
        response = self.mydelete('networks/%d' % net.id, net.userid)
309
        self.assertBadRequest(response)
310

    
311
    def test_delete_network_in_use(self, mrapi):
312
        net = self.net1
313
        response = self.mydelete('networks/%d' % net.id, net.userid)
314
        self.assertFault(response, 421, 'networkInUse')
315
        self.assertFalse(mrapi.called)
316

    
317
    def test_add_nic(self, mrapi):
318
        user = 'userr'
319
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
320
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
321
        mrapi().ModifyInstance.return_value = 1
322
        request = {'add': {'serverRef': vm.id}}
323
        response = self.mypost('networks/%d/action' % net.id,
324
                               net.userid, json.dumps(request), 'json')
325
        self.assertEqual(response.status_code, 202)
326

    
327
    def test_add_nic_to_deleted_network(self, mrapi):
328
        user = 'userr'
329
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
330
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user,
331
                                      deleted=True)
332
        request = {'add': {'serverRef': vm.id}}
333
        response = self.mypost('networks/%d/action' % net.id,
334
                               net.userid, json.dumps(request), 'json')
335
        self.assertBadRequest(response)
336
        self.assertFalse(mrapi.called)
337

    
338
    def test_add_nic_to_public_network(self, mrapi):
339
        user = 'userr'
340
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
341
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user, public=True)
342
        request = {'add': {'serverRef': vm.id}}
343
        response = self.mypost('networks/%d/action' % net.id,
344
                               net.userid, json.dumps(request), 'json')
345
        self.assertFault(response, 403, 'forbidden')
346
        self.assertFalse(mrapi.called)
347

    
348
    def test_add_nic_malformed_1(self, mrapi):
349
        user = 'userr'
350
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
351
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
352
        request = {'add': {'serveRef': vm.id}}
353
        response = self.mypost('networks/%d/action' % net.id,
354
                               net.userid, json.dumps(request), 'json')
355
        self.assertBadRequest(response)
356
        self.assertFalse(mrapi.called)
357

    
358
    def test_add_nic_malformed_2(self, mrapi):
359
        user = 'userr'
360
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
361
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
362
        request = {'add': {'serveRef': [vm.id, 22]}}
363
        response = self.mypost('networks/%d/action' % net.id,
364
                               net.userid, json.dumps(request), 'json')
365
        self.assertBadRequest(response)
366
        self.assertFalse(mrapi.called)
367

    
368
    def test_add_nic_not_active(self, mrapi):
369
        """Test connecting VM to non-active network"""
370
        user = 'dummy'
371
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
372
        net = mfactory.NetworkFactory(state='PENDING', subnet='10.0.0.0/31',
373
                                      userid=user)
374
        request = {'add': {'serverRef': vm.id}}
375
        response = self.mypost('/api/v1.1/networks/%d/action' % net.id,
376
                               net.userid, json.dumps(request), 'json')
377
        # Test that returns BuildInProgress
378
        self.assertEqual(response.status_code, 409)
379
        self.assertFalse(mrapi.called)
380

    
381
    def test_add_nic_full_network(self, mrapi):
382
        """Test connecting VM to a full network"""
383
        user = 'userr'
384
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user,
385
                                            operstate="STARTED")
386
        net = mfactory.NetworkFactory(state='ACTIVE', subnet='10.0.0.0/30',
387
                                      userid=user, dhcp=True)
388
        pool = net.get_pool()
389
        while not pool.empty():
390
            pool.get()
391
        pool.save()
392
        pool = net.get_pool()
393
        self.assertTrue(pool.empty())
394
        request = {'add': {'serverRef': vm.id}}
395
        response = self.mypost('networks/%d/action' % net.id,
396
                               net.userid, json.dumps(request), 'json')
397
        # Test that returns OverLimit
398
        self.assertEqual(response.status_code, 413)
399
        self.assertFalse(mrapi.called)
400

    
401
    def test_remove_nic(self, mrapi):
402
        user = 'userr'
403
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
404
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
405
        nic = mfactory.NetworkInterfaceFactory(machine=vm, network=net)
406
        mrapi().ModifyInstance.return_value = 1
407
        request = {'remove': {'attachment': 'nic-%s-%s' % (vm.id, nic.index)}}
408
        response = self.mypost('networks/%d/action' % net.id,
409
                               net.userid, json.dumps(request), 'json')
410
        self.assertEqual(response.status_code, 202)
411
        self.assertTrue(NetworkInterface.objects.get(id=nic.id).dirty)
412
        vm.task = None
413
        vm.task_job_id = None
414
        vm.save()
415
        # Remove dirty nic
416
        response = self.mypost('networks/%d/action' % net.id,
417
                               net.userid, json.dumps(request), 'json')
418
        self.assertFault(response, 409, 'buildInProgress')
419

    
420
    def test_remove_nic_malformed(self, mrapi):
421
        user = 'userr'
422
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
423
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
424
        nic = mfactory.NetworkInterfaceFactory(machine=vm, network=net)
425
        request = {'remove':
426
                    {'att234achment': 'nic-%s-%s' % (vm.id, nic.index)}
427
                  }
428
        response = self.mypost('networks/%d/action' % net.id,
429
                               net.userid, json.dumps(request), 'json')
430
        self.assertBadRequest(response)
431

    
432
    def test_remove_nic_malformed_2(self, mrapi):
433
        user = 'userr'
434
        vm = mfactory.VirtualMachineFactory(name='yo', userid=user)
435
        net = mfactory.NetworkFactory(state='ACTIVE', userid=user)
436
        request = {'remove':
437
                    {'attachment': 'nic-%s' % vm.id}
438
                  }
439
        response = self.mypost('networks/%d/action' % net.id,
440
                               net.userid, json.dumps(request), 'json')
441
        self.assertBadRequest(response)
442

    
443
    def test_catch_wrong_api_paths(self, *args):
444
        response = self.myget('nonexistent')
445
        self.assertEqual(response.status_code, 400)
446
        try:
447
            error = json.loads(response.content)
448
        except ValueError:
449
            self.assertTrue(False)
450

    
451
    def test_method_not_allowed(self, *args):
452
        # /networks/ allows only POST, GET
453
        response = self.myput('networks', '', '')
454
        self.assertMethodNotAllowed(response)
455
        response = self.mydelete('networks')
456
        self.assertMethodNotAllowed(response)
457

    
458
        # /networks/<srvid>/ allows only GET, PUT, DELETE
459
        response = self.mypost("networks/42")
460
        self.assertMethodNotAllowed(response)