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

import json

from snf_django.utils.testing import BaseAPITest, mocked_quotaholder
37
from synnefo.db.models import IPAddress
38
from synnefo.db.models_factory import (FloatingIPFactory, NetworkFactory,
39
                                       VirtualMachineFactory,
40
41
                                       NetworkInterfaceFactory,
                                       BackendNetworkFactory)
42
from mock import patch, Mock
43
from functools import partial
44

Christos Stavrakakis's avatar
Christos Stavrakakis committed
45
46
47
from synnefo.cyclades_settings import cyclades_services
from synnefo.lib.services import get_service_path
from synnefo.lib import join_urls
48

Christos Stavrakakis's avatar
Christos Stavrakakis committed
49
50
51
52
53

compute_path = get_service_path(cyclades_services, "compute", version="v2.0")
URL = join_urls(compute_path, "os-floating-ips")
NETWORKS_URL = join_urls(compute_path, "networks")
SERVERS_URL = join_urls(compute_path, "servers")
54

55
56
57

floating_ips = IPAddress.objects.filter(floating_ip=True)
FloatingIPPoolFactory = partial(NetworkFactory, public=True, deleted=False,
58
59
                                floating_ip_pool=True)

60

61
class FloatingIPAPITest(BaseAPITest):
62
63
64
65
66
67
    def test_no_floating_ip(self):
        response = self.get(URL)
        self.assertSuccess(response)
        self.assertEqual(json.loads(response.content)["floating_ips"], [])

    def test_list_ips(self):
68
69
        ip = FloatingIPFactory(userid="user1")
        FloatingIPFactory(userid="user1", deleted=True)
70
71
72
73
74
75
76
77
78
79
        with mocked_quotaholder():
            response = self.get(URL, "user1")
        self.assertSuccess(response)
        api_ip = json.loads(response.content)["floating_ips"][0]
        self.assertEqual(api_ip,
                         {"instance_id": str(ip.machine.id), "ip": ip.ipv4,
                          "fixed_ip": None, "id": str(ip.id),  "pool":
                          str(ip.network.id)})

    def test_get_ip(self):
80
        ip = FloatingIPFactory(userid="user1")
81
82
83
84
85
86
87
88
89
90
        with mocked_quotaholder():
            response = self.get(URL + "/%s" % ip.id, "user1")
        self.assertSuccess(response)
        api_ip = json.loads(response.content)["floating_ip"]
        self.assertEqual(api_ip,
                         {"instance_id": str(ip.machine.id), "ip": ip.ipv4,
                          "fixed_ip": None, "id": str(ip.id),  "pool":
                          str(ip.network.id)})

    def test_wrong_user(self):
91
        ip = FloatingIPFactory(userid="user1")
92
93
94
95
96
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, "user2")
        self.assertItemNotFound(response)

    def test_deleted_ip(self):
97
        ip = FloatingIPFactory(userid="user1", deleted=True)
98
99
100
101
102
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, "user1")
        self.assertItemNotFound(response)

    def test_reserve(self):
103
        net = FloatingIPPoolFactory(userid="test_user",
104
105
                                    subnet="192.168.2.0/24",
                                    gateway=None)
106
107
108
109
        request = {'pool': net.id}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertSuccess(response)
110
        ip = floating_ips.get()
111
112
113
114
115
        self.assertEqual(ip.ipv4, "192.168.2.1")
        self.assertEqual(ip.machine, None)
        self.assertEqual(ip.network, net)
        self.assertEqual(json.loads(response.content)["floating_ip"],
                         {"instance_id": None, "ip": "192.168.2.1",
116
117
                          "fixed_ip": None, "id": str(ip.id),
                          "pool": str(net.id)})
118

119
120
121
122
123
124
    def test_reserve_no_pool(self):
        # No networks
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps({}), "json")
        self.assertFault(response, 413, "overLimit")
        # Full network
125
        FloatingIPPoolFactory(userid="test_user",
126
127
                              subnet="192.168.2.0/32",
                              gateway=None)
128
129
130
131
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps({}), "json")
        self.assertFault(response, 413, "overLimit")
        # Success
132
        net2 = FloatingIPPoolFactory(userid="test_user",
133
134
                                     subnet="192.168.2.0/24",
                                     gateway=None)
135
136
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps({}), "json")
137
        self.assertSuccess(response)
138
        ip = floating_ips.get()
139
140
        self.assertEqual(json.loads(response.content)["floating_ip"],
                         {"instance_id": None, "ip": "192.168.2.1",
141
142
                          "fixed_ip": None, "id": str(ip.id),
                          "pool": str(net2.id)})
143

144
    def test_reserve_full(self):
145
        net = FloatingIPPoolFactory(userid="test_user",
146
                                    subnet="192.168.2.0/32")
147
148
149
150
151
        request = {'pool': net.id}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertEqual(response.status_code, 413)

152
    def test_reserve_with_address(self):
153
        net = FloatingIPPoolFactory(userid="test_user",
154
                                    subnet="192.168.2.0/24")
155
156
157
158
        request = {'pool': net.id, "address": "192.168.2.10"}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertSuccess(response)
159
        ip = floating_ips.get()
160
161
        self.assertEqual(json.loads(response.content)["floating_ip"],
                         {"instance_id": None, "ip": "192.168.2.10",
162
163
                          "fixed_ip": None, "id": str(ip.id), "pool":
                          str(net.id)})
164
165

        # Already reserved
166
        FloatingIPFactory(network=net, ipv4="192.168.2.3")
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        request = {'pool': net.id, "address": "192.168.2.3"}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertFault(response, 409, "conflict")

        # Already used
        pool = net.get_pool()
        pool.reserve("192.168.2.5")
        pool.save()
        # ..by another_user
        nic = NetworkInterfaceFactory(network=net, ipv4="192.168.2.5",
                                      machine__userid="test2")
        request = {'pool': net.id, "address": "192.168.2.5"}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertFault(response, 409, "conflict")
        # ..and by him
        nic.delete()
        NetworkInterfaceFactory(network=net, ipv4="192.168.2.5",
                                machine__userid="test_user")
        request = {'pool': net.id, "address": "192.168.2.5"}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertSuccess(response)

        # Address out of pool
        request = {'pool': net.id, "address": "192.168.3.5"}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertBadRequest(response)

198
    def test_release_in_use(self):
199
        ip = FloatingIPFactory()
200
201
202
203
204
205
206
207
208
209
210
211
        vm = ip.machine
        vm.operstate = "ACTIVE"
        vm.userid = ip.userid
        vm.save()
        vm.nics.create(index=0, ipv4=ip.ipv4, network=ip.network,
                       state="ACTIVE")
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, ip.userid)
        self.assertFault(response, 409, "conflict")
        # Also send a notification to remove the NIC and assert that FIP is in
        # use until notification from ganeti arrives
        request = {"removeFloatingIp": {"address": ip.ipv4}}
Christos Stavrakakis's avatar
Christos Stavrakakis committed
212
        url = SERVERS_URL + "/%s/action" % vm.id
213
214
215
216
217
        with patch('synnefo.logic.rapi_pool.GanetiRapiClient') as c:
            c().ModifyInstance.return_value = 10
            response = self.post(url, vm.userid, json.dumps(request),
                                 "json")
        self.assertEqual(response.status_code, 202)
218
219
220
221
222
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, ip.userid)
        self.assertFault(response, 409, "conflict")

    def test_release(self):
223
        ip = FloatingIPFactory(machine=None)
224
225
226
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, ip.userid)
        self.assertSuccess(response)
227
        ips_after = floating_ips.filter(id=ip.id)
228
        self.assertEqual(len(ips_after), 0)
229

230
231
    @patch("synnefo.logic.backend", Mock())
    def test_delete_network_with_floating_ips(self):
232
        ip = FloatingIPFactory(machine=None, network__flavor="IP_LESS_ROUTED")
233
234
235
        net = ip.network
        # Can not remove network with floating IPs
        with mocked_quotaholder():
Christos Stavrakakis's avatar
Christos Stavrakakis committed
236
            response = self.delete(NETWORKS_URL + "/%s" % net.id,
237
238
239
240
241
242
                                   net.userid)
        self.assertFault(response, 421, "networkInUse")
        # But we can with only deleted Floating Ips
        ip.deleted = True
        ip.save()
        with mocked_quotaholder():
Christos Stavrakakis's avatar
Christos Stavrakakis committed
243
            response = self.delete(NETWORKS_URL + "/%s" % net.id,
244
245
246
                                   net.userid)
        self.assertSuccess(response)

247

Christos Stavrakakis's avatar
Christos Stavrakakis committed
248
POOLS_URL = join_urls(compute_path, "os-floating-ip-pools")
249
250


251
class FloatingIPPoolsAPITest(BaseAPITest):
252
253
254
255
256
257
    def test_no_pool(self):
        response = self.get(POOLS_URL)
        self.assertSuccess(response)
        self.assertEqual(json.loads(response.content)["floating_ip_pools"], [])

    def test_list_pools(self):
258
        net = FloatingIPPoolFactory(subnet="192.168.0.0/30",
259
                                    gateway="192.168.0.1")
260
261
        NetworkFactory(public=True, deleted=True)
        NetworkFactory(public=False, deleted=False)
262
        NetworkFactory(public=True, deleted=False)
263
264
265
        response = self.get(POOLS_URL)
        self.assertSuccess(response)
        self.assertEqual(json.loads(response.content)["floating_ip_pools"],
266
                         [{"name": str(net.id), "size": 4, "free": 1}])
267
268


269
class FloatingIPActionsTest(BaseAPITest):
270
271
272
273
274
275
276
    def setUp(self):
        vm = VirtualMachineFactory()
        vm.operstate = "ACTIVE"
        vm.save()
        self.vm = vm

    def test_bad_request(self):
Christos Stavrakakis's avatar
Christos Stavrakakis committed
277
        url = SERVERS_URL + "/%s/action" % self.vm.id
278
279
280
281
282
283
284
285
286
287
        response = self.post(url, self.vm.userid, json.dumps({}), "json")
        self.assertBadRequest(response)
        response = self.post(url, self.vm.userid,
                             json.dumps({"addFloatingIp": {}}),
                             "json")
        self.assertBadRequest(response)

    @patch('synnefo.logic.rapi_pool.GanetiRapiClient')
    def test_add_floating_ip(self, mock):
        # Not exists
Christos Stavrakakis's avatar
Christos Stavrakakis committed
288
        url = SERVERS_URL + "/%s/action" % self.vm.id
289
290
291
292
293
        request = {"addFloatingIp": {"address": "10.0.0.1"}}
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertItemNotFound(response)
        # In use
        vm1 = VirtualMachineFactory()
294
        ip1 = FloatingIPFactory(userid=self.vm.userid, machine=vm1)
295
296
        BackendNetworkFactory(network=ip1.network, backend=vm1.backend,
                              operstate='ACTIVE')
297
298
299
300
        request = {"addFloatingIp": {"address": ip1.ipv4}}
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertFault(response, 409, "conflict")
        # Success
301
        ip1 = FloatingIPFactory(userid=self.vm.userid, machine=None)
302
303
        BackendNetworkFactory(network=ip1.network, backend=self.vm.backend,
                              operstate='ACTIVE')
304
        request = {"addFloatingIp": {"address": ip1.ipv4}}
305
        mock().ModifyInstance.return_value = 1
306
307
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertEqual(response.status_code, 202)
308
        ip1_after = floating_ips.get(id=ip1.id)
309
310
        self.assertEqual(ip1_after.machine, self.vm)
        self.assertTrue(ip1_after.in_use())
311
312
313
        nic = self.vm.nics.get(ipv4=ip1_after.ipv4)
        nic.state = "ACTIVE"
        nic.save()
314
315
316
317
318
        response = self.get(SERVERS_URL + "/%s" % self.vm.id,
                            self.vm.userid)
        self.assertSuccess(response)
        nic = json.loads(response.content)["server"]["attachments"][0]
        self.assertEqual(nic["OS-EXT-IPS:type"], "floating")
319
320
321
322

    @patch('synnefo.logic.rapi_pool.GanetiRapiClient')
    def test_remove_floating_ip(self, mock):
        # Not exists
Christos Stavrakakis's avatar
Christos Stavrakakis committed
323
        url = SERVERS_URL + "/%s/action" % self.vm.id
324
325
326
327
        request = {"removeFloatingIp": {"address": "10.0.0.1"}}
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertItemNotFound(response)
        # Not In Use
328
        ip1 = FloatingIPFactory(userid=self.vm.userid, machine=None)
329
330
331
332
        request = {"removeFloatingIp": {"address": ip1.ipv4}}
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertItemNotFound(response)
        # Success
333
        ip1 = FloatingIPFactory(userid=self.vm.userid, machine=self.vm)
334
335
        NetworkInterfaceFactory(machine=self.vm, ipv4=ip1.ipv4)
        request = {"removeFloatingIp": {"address": ip1.ipv4}}
336
        mock().ModifyInstance.return_value = 2
337
338
339
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertEqual(response.status_code, 202)
        # Yet used. Wait for the callbacks
340
        ip1_after = floating_ips.get(id=ip1.id)
341
342
        self.assertEqual(ip1_after.machine, self.vm)
        self.assertTrue(ip1_after.in_use())