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
38
from synnefo.db.models import IPAddress
from synnefo.db.models_factory import (IPAddressFactory, 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
IPAddressPoolFactory = partial(NetworkFactory, public=True, deleted=False,
56
57
                                floating_ip_pool=True)

58

59
class IPAddressAPITest(BaseAPITest):
60
61
62
63
64
65
    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):
66
67
        ip = IPAddressFactory(userid="user1")
        IPAddressFactory(userid="user1", deleted=True)
68
69
70
71
72
73
74
75
76
77
        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):
78
        ip = IPAddressFactory(userid="user1")
79
80
81
82
83
84
85
86
87
88
        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):
89
        ip = IPAddressFactory(userid="user1")
90
91
92
93
94
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, "user2")
        self.assertItemNotFound(response)

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

    def test_reserve(self):
101
        net = IPAddressPoolFactory(userid="test_user",
102
103
                                    subnet="192.168.2.0/24",
                                    gateway=None)
104
105
106
107
        request = {'pool': net.id}
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps(request), "json")
        self.assertSuccess(response)
108
        ip = IPAddress.objects.get()
109
110
111
112
113
        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",
114
115
                          "fixed_ip": None, "id": str(ip.id),
                          "pool": str(net.id)})
116

117
118
119
120
121
122
    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
123
        IPAddressPoolFactory(userid="test_user",
124
125
                              subnet="192.168.2.0/32",
                              gateway=None)
126
127
128
129
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps({}), "json")
        self.assertFault(response, 413, "overLimit")
        # Success
130
        net2 = IPAddressPoolFactory(userid="test_user",
131
132
                                     subnet="192.168.2.0/24",
                                     gateway=None)
133
134
        with mocked_quotaholder():
            response = self.post(URL, "test_user", json.dumps({}), "json")
135
        self.assertSuccess(response)
136
        ip = IPAddress.objects.get()
137
138
        self.assertEqual(json.loads(response.content)["floating_ip"],
                         {"instance_id": None, "ip": "192.168.2.1",
139
140
                          "fixed_ip": None, "id": str(ip.id),
                          "pool": str(net2.id)})
141

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

150
    def test_reserve_with_address(self):
151
        net = IPAddressPoolFactory(userid="test_user",
152
                                    subnet="192.168.2.0/24")
153
154
155
156
        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)
157
        ip = IPAddress.objects.get()
158
159
        self.assertEqual(json.loads(response.content)["floating_ip"],
                         {"instance_id": None, "ip": "192.168.2.10",
160
161
                          "fixed_ip": None, "id": str(ip.id), "pool":
                          str(net.id)})
162
163

        # Already reserved
164
        IPAddressFactory(network=net, ipv4="192.168.2.3")
165
166
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
        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)

196
    def test_release_in_use(self):
197
        ip = IPAddressFactory()
198
199
200
201
202
203
204
205
206
207
208
209
        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
210
        url = SERVERS_URL + "/%s/action" % vm.id
211
212
213
214
215
        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)
216
217
218
219
220
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, ip.userid)
        self.assertFault(response, 409, "conflict")

    def test_release(self):
221
        ip = IPAddressFactory(machine=None)
222
223
224
        with mocked_quotaholder():
            response = self.delete(URL + "/%s" % ip.id, ip.userid)
        self.assertSuccess(response)
225
        ips_after = IPAddress.objects.filter(id=ip.id)
226
        self.assertEqual(len(ips_after), 0)
227

228
229
    @patch("synnefo.logic.backend", Mock())
    def test_delete_network_with_floating_ips(self):
230
        ip = IPAddressFactory(machine=None, network__flavor="IP_LESS_ROUTED")
231
232
233
        net = ip.network
        # Can not remove network with floating IPs
        with mocked_quotaholder():
Christos Stavrakakis's avatar
Christos Stavrakakis committed
234
            response = self.delete(NETWORKS_URL + "/%s" % net.id,
235
236
237
238
239
240
                                   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
241
            response = self.delete(NETWORKS_URL + "/%s" % net.id,
242
243
244
                                   net.userid)
        self.assertSuccess(response)

245

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


249
class IPAddressPoolsAPITest(BaseAPITest):
250
251
252
253
254
255
    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):
256
        net = IPAddressPoolFactory(subnet="192.168.0.0/30",
257
                                    gateway="192.168.0.1")
258
259
        NetworkFactory(public=True, deleted=True)
        NetworkFactory(public=False, deleted=False)
260
        NetworkFactory(public=True, deleted=False)
261
262
263
        response = self.get(POOLS_URL)
        self.assertSuccess(response)
        self.assertEqual(json.loads(response.content)["floating_ip_pools"],
264
                         [{"name": str(net.id), "size": 4, "free": 1}])
265
266


267
class IPAddressActionsTest(BaseAPITest):
268
269
270
271
272
273
274
    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
275
        url = SERVERS_URL + "/%s/action" % self.vm.id
276
277
278
279
280
281
282
283
284
285
        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
286
        url = SERVERS_URL + "/%s/action" % self.vm.id
287
288
289
290
291
        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()
292
        ip1 = IPAddressFactory(userid=self.vm.userid, machine=vm1)
293
294
        BackendNetworkFactory(network=ip1.network, backend=vm1.backend,
                              operstate='ACTIVE')
295
296
297
298
        request = {"addFloatingIp": {"address": ip1.ipv4}}
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertFault(response, 409, "conflict")
        # Success
299
        ip1 = IPAddressFactory(userid=self.vm.userid, machine=None)
300
301
        BackendNetworkFactory(network=ip1.network, backend=self.vm.backend,
                              operstate='ACTIVE')
302
        request = {"addFloatingIp": {"address": ip1.ipv4}}
303
        mock().ModifyInstance.return_value = 1
304
305
        response = self.post(url, self.vm.userid, json.dumps(request), "json")
        self.assertEqual(response.status_code, 202)
306
        ip1_after = IPAddress.objects.get(id=ip1.id)
307
308
        self.assertEqual(ip1_after.machine, self.vm)
        self.assertTrue(ip1_after.in_use())
309
310
311
        nic = self.vm.nics.get(ipv4=ip1_after.ipv4)
        nic.state = "ACTIVE"
        nic.save()
312
313
314
315
316
        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")
317
318
319
320

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