| 38 | namespace io { |
| 39 | |
| 40 | RandomServerSocket::RandomServerSocket(const std::string& host, uint16_t offset, uint16_t range, uint16_t retries) : |
| 41 | ServerSocket::ServerSocket(std::make_shared<org::apache::nifi::minifi::io::SocketContext>(std::make_shared<minifi::Configure>()), host, 0, 1) { |
| 42 | std::random_device rd; |
| 43 | std::mt19937 gen(rd()); |
| 44 | std::uniform_int_distribution<uint16_t> dis(offset, offset + range); |
| 45 | auto logger = logging::LoggerFactory<RandomServerSocket>::getLogger(); |
| 46 | for (uint16_t i = 0; i < retries; ++i) { |
| 47 | setPort(dis(gen)); |
| 48 | if (RandomServerSocket::initialize() == 0) { |
| 49 | logger->log_info("Created socket listens on generated port: %hu", getPort()); |
| 50 | return; |
| 51 | } |
| 52 | } |
| 53 | std::stringstream error; |
| 54 | error << "Couldn't bind to a port between " << offset << " and " << offset+range << " in " << retries << " try!"; |
| 55 | logger->log_error(error.str().c_str()); |
| 56 | throw Exception{ExceptionType::GENERAL_EXCEPTION, error.str()}; |
| 57 | } |
| 58 | |
| 59 | } /* namespace io */ |
| 60 | } /* namespace minifi */ |