Debian Codegraph @

python/tests/integration/test_PROTON_2111_container_ssl_ssldomain_object_leak.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License
18 #
19
20 """
21 PROTON-2111 python: memory leak on Container, SSL, and SSLDomain objects
22 """
23
24 from __future__ import absolute_import
25 from __future__ import division
26 from __future__ import print_function
27
28 import contextlib
29 import gc
30 import os
31 import platform
32 import socket
33 import threading
34 import unittest
35
36 import cproton
37
38 import proton.handlers
39 import proton.utils
40 import proton.reactor
41
42
43 class Broker(proton.handlers.MessagingHandler):
44 def __init__(self, acceptor_url, ssl_domain=None):
45 # type: (str, proton.SSLDomain) -> None
46 super(Broker, self).__init__()
47 self.acceptor_url = acceptor_url
48 self.ssl_domain = ssl_domain
49
50 self.acceptor = None
51 self._acceptor_opened_event = threading.Event()
52
53 self.on_message_ = threading.Event()
54
55 def get_acceptor_sockname(self):
56 # type: () -> (str, int)
57 self._acceptor_opened_event.wait()
58 if hasattr(self.acceptor, '_selectable'): # proton 0.30.0+
59 sockname = self.acceptor._selectable._delegate.getsockname()
60 else: # works in proton 0.27.0
61 selectable = cproton.pn_cast_pn_selectable(self.acceptor._impl)
62 fd = cproton.pn_selectable_get_fd(selectable)
63 s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
64 sockname = s.getsockname()
65 return sockname[:2]
66
67 def on_start(self, event):
68 self.acceptor = event.container.listen(self.acceptor_url, ssl_domain=self.ssl_domain)
69 self._acceptor_opened_event.set()
70
71 def on_link_opening(self, event):
72 link = event.link # type: proton.Link
73 if link.is_sender:
74 assert not link.remote_source.dynamic, "This cannot happen"
75 link.source.address = link.remote_source.address
76 elif link.remote_target.address:
77 link.target.address = link.remote_target.address
78
79 def on_message(self, event):
80 self.on_message_.set()
81
82
83 @contextlib.contextmanager
84 def test_broker(ssl_domain=None):
85 # type: (proton.SSLDomain) -> Broker
86 broker = Broker('localhost:0', ssl_domain=ssl_domain)
87 container = proton.reactor.Container(broker)
88 t = threading.Thread(target=container.run)
89 t.start()
90
91 yield broker
92
93 container.stop()
94 if broker.acceptor:
95 broker.acceptor.close()
96 t.join()
97
98
99 class SampleSender(proton.handlers.MessagingHandler):
100 def __init__(self, msg_id, urls, ssl_domain=None, *args, **kwargs):
101 # type: (str, str, proton.SSLDomain, *object, **object) -> None
102 super(SampleSender, self).__init__(*args, **kwargs)
103 self.urls = urls
104 self.msg_id = msg_id
105 self.ssl_domain = ssl_domain
106
107 def on_start(self, event):
108 # type: (proton.Event) -> None
109 conn = event.container.connect(url=self.urls, reconnect=False, ssl_domain=self.ssl_domain)
110 event.container.create_sender(conn, target='topic://VirtualTopic.event')
111
112 def on_sendable(self, event):
113 msg = proton.Message(body={'msg-id': self.msg_id, 'name': 'python'})
114 event.sender.send(msg)
115 event.sender.close()
116 event.connection.close()
117
118 def on_connection_error(self, event):
119 print("on_error", event)
120
121
122 class Proton2111Test(unittest.TestCase):
123 @unittest.skipIf(platform.system() == 'Windows', "TODO jdanek: Test is broken on Windows")
124 def test_send_message_ssl_no_object_leaks(self):
125 """Starts a broker with ssl acceptor, in a loop connects to it and sends message.
126
127 The test checks that number of Python objects is not increasing inside the loop.
128 """
129 cwd = os.path.dirname(__file__)
130 cert_file = os.path.join(cwd, 'certificates', 'localhost_ca1.pem')
131 key_file = os.path.join(cwd, 'certificates', 'localhost_ca1-key.pem')
132 certificate_db = os.path.join(cwd, 'certificates', 'ca1.pem')
133 password = None
134
135 broker_ssl_domain = proton.SSLDomain(proton.SSLDomain.MODE_SERVER)
136 broker_ssl_domain.set_credentials(cert_file, key_file, password=password)
137
138 client_ssl_domain = proton.SSLDomain(proton.SSLDomain.MODE_CLIENT)
139 client_ssl_domain.set_trusted_ca_db(certificate_db)
140 client_ssl_domain.set_peer_authentication(proton.SSLDomain.VERIFY_PEER)
141
142 def send_msg(msg_id, urls):
143 container = proton.reactor.Container(SampleSender(msg_id, urls, client_ssl_domain))
144 container.run()
145
146 with test_broker(ssl_domain=broker_ssl_domain) as broker:
147 urls = "amqps://{0}:{1}".format(*broker.get_acceptor_sockname())
148
149 gc.collect()
150 object_counts = []
151 for i in range(300):
152 send_msg(i + 1, urls)
153 broker.on_message_.wait() # message got through
154 broker.on_message_.clear()
155 gc.collect()
156 object_counts.append(len(gc.get_objects()))
157
158 # drop first few values, it is usually different (before counts settle)
159 object_counts = object_counts[2:]
160
161 diffs = [c - object_counts[0] for c in object_counts]
162 for diff in diffs:
163 # allow for random variation from initial value on some systems, but prohibit linear growth
164 self.assertTrue(diff <= 50, "Object counts should not be increasing: {0}".format(diffs))