Convert str to bytes for py3 socket compatibility

socket.sendto() requires bytes and we need explicitly convert str to
bytes in py3.

Change-Id: Ib3f928963b11a2041caf1c3b15825125567ce360
Story: #2007537
Task: #39356
This commit is contained in:
Hang Yang 2020-04-09 15:51:57 -05:00
parent 70866d8bab
commit a24d703393
3 changed files with 12 additions and 5 deletions

View File

@ -80,7 +80,7 @@ class StatsdMetricLogger(metrics.MetricLogger):
with contextlib.closing(self._open_socket()) as sock:
try:
sock.settimeout(0.0)
sock.sendto(metric, self._target)
sock.sendto(metric.encode(), self._target)
except socket.error as e:
LOG.warning("Failed to send the metric value to host "
"%(host)s, port %(port)s. Error: %(error)s",

View File

@ -75,27 +75,27 @@ class TestStatsdMetricLogger(base.IronicLibTestCase):
self.ml._send('part1.part2', 2, 'type')
mock_socket.sendto.assert_called_once_with(
'part1.part2:2|type',
b'part1.part2:2|type',
('test-host', 4321))
mock_socket.close.assert_called_once_with()
mock_socket.reset_mock()
self.ml._send('part1.part2', 3.14159, 'type')
mock_socket.sendto.assert_called_once_with(
'part1.part2:3.14159|type',
b'part1.part2:3.14159|type',
('test-host', 4321))
mock_socket.close.assert_called_once_with()
mock_socket.reset_mock()
self.ml._send('part1.part2', 5, 'type')
mock_socket.sendto.assert_called_once_with(
'part1.part2:5|type',
b'part1.part2:5|type',
('test-host', 4321))
mock_socket.close.assert_called_once_with()
mock_socket.reset_mock()
self.ml._send('part1.part2', 5, 'type', sample_rate=0.5)
mock_socket.sendto.assert_called_once_with(
'part1.part2:5|type@0.5',
b'part1.part2:5|type@0.5',
('test-host', 4321))
mock_socket.close.assert_called_once_with()

View File

@ -0,0 +1,7 @@
---
fixes:
- |
Fixes an py3 compatibility issue in metrics_statsd where str need be
explicitly converted to bytes before send with socket.
See `Story 2007537 <https://storyboard.openstack.org/#!/story/2007537>`_
for details.