def _wait_for_and_browse_urls(self, conn, consumer, timeout):
        start = time.time()
        browser = None
        consumer.qos(prefetch_count=self.max_active_browsers)

        while not self._consumer_stop.is_set() and time.time() - start < timeout and not self._reconnect_requested:
            try:
                browser = self._browser_pool.acquire() # raises KeyError if none available
                browser.start()

                def callback(body, message):
                    try:
                        client_id = body.get('clientId')
                        url = body['url']
                        metadata = body.get('metadata')
                        behavior_parameters = body.get('behaviorParameters')
                    except:
                        self.logger.error("unable to decipher message %s",
                                          message, exc_info=True)
                        self.logger.error("discarding bad message")
                        message.reject()
                        browser.stop()
                        self._browser_pool.release(browser)
                        return
                    self._start_browsing_page(browser, message, client_id, url,
                                              metadata, behavior_parameters)

                consumer.callbacks = [callback]

                while True:
                    try:
                        conn.drain_events(timeout=0.5)
                        break # out of "while True" to acquire another browser
                    except socket.timeout:
                        pass
                    except socket.error:
                        self.logger.error("problem consuming messages from AMQP, will try reconnecting after active browsing finishes", exc_info=True)
                        self._reconnect_requested = True

                    if self._consumer_stop.is_set() or time.time() - start >= timeout or self._reconnect_requested:
                        browser.stop()
                        self._browser_pool.release(browser)
                        break

            except KeyError:
                # no browsers available
                time.sleep(0.5)
            except:
                self.logger.critical("problem with browser initialization", exc_info=True)
                time.sleep(0.5)
            finally:
                consumer.callbacks = None
dataset/ETHPy150Open internetarchive/umbra/umbra/controller.py/AmqpBrowserController._wait_for_and_browse_urls/original