1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2012 New Dream Network, LLC (DreamHost)
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may
6
# not use this file except in compliance with the License. You may obtain
7
# a copy of the License at
9
# http://www.apache.org/licenses/LICENSE-2.0
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
# License for the specific language governing permissions and limitations
17
# @author: Mark McClain, DreamHost
22
import unittest2 as unittest
25
from quantum.agent.metadata import agent
28
class FakeConf(object):
29
admin_user = 'quantum'
30
admin_password = 'password'
31
admin_tenant_name = 'tenant'
32
auth_url = 'http://127.0.0.1'
33
auth_strategy = 'keystone'
34
auth_region = 'region'
35
nova_metadata_ip = '9.9.9.9'
36
nova_metadata_port = 8775
37
metadata_proxy_shared_secret = 'secret'
40
class TestMetadataProxyHandler(unittest.TestCase):
42
self.qclient_p = mock.patch('quantumclient.v2_0.client.Client')
43
self.qclient = self.qclient_p.start()
45
self.log_p = mock.patch.object(agent, 'LOG')
46
self.log = self.log_p.start()
48
self.handler = agent.MetadataProxyHandler(FakeConf)
56
with mock.patch.object(self.handler, '_get_instance_id') as get_id:
57
get_id.return_value = 'id'
58
with mock.patch.object(self.handler, '_proxy_request') as proxy:
59
proxy.return_value = 'value'
61
retval = self.handler(req)
62
self.assertEqual(retval, 'value')
64
def test_call_no_instance_match(self):
66
with mock.patch.object(self.handler, '_get_instance_id') as get_id:
67
get_id.return_value = None
68
retval = self.handler(req)
69
self.assertIsInstance(retval, webob.exc.HTTPNotFound)
71
def test_call_internal_server_error(self):
73
with mock.patch.object(self.handler, '_get_instance_id') as get_id:
74
get_id.side_effect = Exception
75
retval = self.handler(req)
76
self.assertIsInstance(retval, webob.exc.HTTPInternalServerError)
77
self.assertEqual(len(self.log.mock_calls), 2)
79
def _get_instance_id_helper(self, headers, list_ports_retval,
80
networks=None, router_id=None):
81
headers['X-Forwarded-For'] = '192.168.1.1'
82
req = mock.Mock(headers=headers)
84
def mock_list_ports(*args, **kwargs):
85
return {'ports': list_ports_retval.pop(0)}
87
self.qclient.return_value.list_ports.side_effect = mock_list_ports
88
retval = self.handler._get_instance_id(req)
92
username=FakeConf.admin_user,
93
tenant_name=FakeConf.admin_tenant_name,
94
region_name=FakeConf.auth_region,
95
auth_url=FakeConf.auth_url,
96
password=FakeConf.admin_password,
97
auth_strategy=FakeConf.auth_strategy)
102
mock.call().list_ports(
104
device_owner='network:router_interface'
109
mock.call().list_ports(
110
network_id=networks or [],
111
fixed_ips=['ip_address=192.168.1.1'])
114
self.qclient.assert_has_calls(expected)
118
def test_get_instance_id_router_id(self):
121
'X-Quantum-Router-ID': router_id
124
networks = ['net1', 'net2']
126
[{'network_id': 'net1'}, {'network_id': 'net2'}],
127
[{'device_id': 'device_id'}]
131
self._get_instance_id_helper(headers, ports, networks=networks,
132
router_id=router_id),
136
def test_get_instance_id_router_id_no_match(self):
139
'X-Quantum-Router-ID': router_id
142
networks = ['net1', 'net2']
144
[{'network_id': 'net1'}, {'network_id': 'net2'}],
149
self._get_instance_id_helper(headers, ports, networks=networks,
150
router_id=router_id),
153
def test_get_instance_id_network_id(self):
154
network_id = 'the_id'
156
'X-Quantum-Network-ID': network_id
160
[{'device_id': 'device_id'}]
164
self._get_instance_id_helper(headers, ports, networks=['the_id']),
168
def test_get_instance_id_network_id_no_match(self):
169
network_id = 'the_id'
171
'X-Quantum-Network-ID': network_id
177
self._get_instance_id_helper(headers, ports, networks=['the_id'])
180
def _proxy_request_test_helper(self, response_code):
181
hdrs = {'X-Forwarded-For': '8.8.8.8'}
182
req = mock.Mock(path_info='/the_path', query_string='', headers=hdrs)
183
resp = mock.Mock(status=response_code)
184
with mock.patch.object(self.handler, '_sign_instance_id') as sign:
185
sign.return_value = 'signed'
186
with mock.patch('httplib2.Http') as mock_http:
187
mock_http.return_value.request.return_value = (resp, 'content')
189
retval = self.handler._proxy_request('the_id', req)
190
mock_http.assert_has_calls([
192
'http://9.9.9.9:8775/the_path',
194
'X-Forwarded-For': '8.8.8.8',
195
'X-Instance-ID-Signature': 'signed',
196
'X-Instance-ID': 'the_id'
203
def test_proxy_request_200(self):
204
self.assertEqual('content', self._proxy_request_test_helper(200))
206
def test_proxy_request_403(self):
207
self.assertIsInstance(self._proxy_request_test_helper(403),
208
webob.exc.HTTPForbidden)
210
def test_proxy_request_404(self):
211
self.assertIsInstance(self._proxy_request_test_helper(404),
212
webob.exc.HTTPNotFound)
214
def test_proxy_request_500(self):
215
self.assertIsInstance(self._proxy_request_test_helper(500),
216
webob.exc.HTTPInternalServerError)
218
def test_proxy_request_other_code(self):
219
with self.assertRaises(Exception) as e:
220
self._proxy_request_test_helper(302)
222
def test_sign_instance_id(self):
224
self.handler._sign_instance_id('foo'),
225
'773ba44693c7553d6ee20f61ea5d2757a9a4f4a44d2841ae4e95b52e4cd62db4'
229
class TestUnixDomainHttpProtocol(unittest.TestCase):
230
def test_init_empty_client(self):
231
u = agent.UnixDomainHttpProtocol(mock.Mock(), '', mock.Mock())
232
self.assertEqual(u.client_address, ('<local>', 0))
234
def test_init_with_client(self):
235
u = agent.UnixDomainHttpProtocol(mock.Mock(), 'foo', mock.Mock())
236
self.assertEqual(u.client_address, 'foo')
239
class TestUnixDomainWSGIServer(unittest.TestCase):
241
self.eventlet_p = mock.patch.object(agent, 'eventlet')
242
self.eventlet = self.eventlet_p.start()
243
self.server = agent.UnixDomainWSGIServer('test')
246
self.eventlet_p.stop()
248
def test_start(self):
249
mock_app = mock.Mock()
250
with mock.patch.object(self.server, 'pool') as pool:
251
self.server.start(mock_app, '/the/path')
252
self.eventlet.assert_has_calls([
255
family=socket.AF_UNIX,
259
pool.spawn_n.assert_called_once_with(
262
self.eventlet.listen.return_value
266
with mock.patch.object(agent, 'logging') as logging:
267
self.server._run('app', 'sock')
269
self.eventlet.wsgi.server.called_once_with(
273
agent.UnixDomainHttpProtocol,
276
self.assertTrue(len(logging.mock_calls))
279
class TestUnixDomainMetadataProxy(unittest.TestCase):
281
self.cfg_p = mock.patch.object(agent, 'cfg')
282
self.cfg = self.cfg_p.start()
283
self.cfg.CONF.metadata_proxy_socket = '/the/path'
288
def test_init_doesnot_exists(self):
289
with mock.patch('os.path.isdir') as isdir:
290
with mock.patch('os.makedirs') as makedirs:
291
isdir.return_value = False
292
p = agent.UnixDomainMetadataProxy(mock.Mock())
294
isdir.assert_called_once_with('/the')
295
makedirs.assert_called_once_with('/the', 0755)
297
def test_init_exists(self):
298
with mock.patch('os.path.isdir') as isdir:
299
with mock.patch('os.unlink') as unlink:
300
isdir.return_value = True
301
p = agent.UnixDomainMetadataProxy(mock.Mock())
303
isdir.assert_called_once_with('/the')
304
unlink.assert_called_once_with('/the/path')
306
def test_init_exists_unlink_no_file(self):
307
with mock.patch('os.path.isdir') as isdir:
308
with mock.patch('os.unlink') as unlink:
309
with mock.patch('os.path.exists') as exists:
310
isdir.return_value = True
311
exists.return_value = False
312
unlink.side_effect = OSError
314
p = agent.UnixDomainMetadataProxy(mock.Mock())
316
isdir.assert_called_once_with('/the')
317
unlink.assert_called_once_with('/the/path')
318
exists.assert_called_once_with('/the/path')
320
def test_init_exists_unlink_fails_file_still_exists(self):
321
with mock.patch('os.path.isdir') as isdir:
322
with mock.patch('os.unlink') as unlink:
323
with mock.patch('os.path.exists') as exists:
324
isdir.return_value = True
325
exists.return_value = True
326
unlink.side_effect = OSError
328
with self.assertRaises(OSError):
329
p = agent.UnixDomainMetadataProxy(mock.Mock())
331
isdir.assert_called_once_with('/the')
332
unlink.assert_called_once_with('/the/path')
333
exists.assert_called_once_with('/the/path')
336
with mock.patch.object(agent, 'MetadataProxyHandler') as handler:
337
with mock.patch.object(agent, 'UnixDomainWSGIServer') as server:
338
with mock.patch('os.path.isdir') as isdir:
339
with mock.patch('os.makedirs') as makedirs:
340
isdir.return_value = False
342
p = agent.UnixDomainMetadataProxy(self.cfg.CONF)
345
isdir.assert_called_once_with('/the')
346
makedirs.assert_called_once_with('/the', 0755)
347
server.assert_has_calls([
348
mock.call('quantum-metadata-agent'),
349
mock.call().start(handler.return_value,
355
with mock.patch.object(agent, 'UnixDomainMetadataProxy') as proxy:
356
with mock.patch('eventlet.monkey_patch') as eventlet:
357
with mock.patch.object(agent, 'config') as config:
358
with mock.patch.object(agent, 'cfg') as cfg:
361
self.assertTrue(eventlet.called)
362
self.assertTrue(config.setup_logging.called)
363
proxy.assert_has_calls([