#!/usr/bin/env python31# -*- coding: utf-8 -*-2#***************************************************************************3# _ _ ____ _4# Project ___| | | | _ \| |5# / __| | | | |_) | |6# | (__| |_| | _ <| |___7# \___|\___/|_| \_\_____|8#9# Copyright (C) Daniel Stenberg, <[email protected]>, et al.10#11# This software is licensed as described in the file COPYING, which12# you should have received as part of this distribution. The terms13# are also available at https://curl.se/docs/copyright.html.14#15# You may opt to use, copy, modify, merge, publish, distribute and/or sell16# copies of the Software, and permit persons to whom the Software is17# furnished to do so, under the terms of the COPYING file.18#19# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY20# KIND, either express or implied.21#22# SPDX-License-Identifier: curl23#24###########################################################################25#26import logging27import os28import socket29from collections.abc import Callable30from typing import Dict3132from filelock import FileLock3334log = logging.getLogger(__name__)353637def alloc_port_set(port_specs: Dict[str, int]) -> Dict[str, int]:38socks = []39ports = {}40for name, ptype in port_specs.items():41try:42s = socket.socket(type=ptype)43s.bind(('', 0))44ports[name] = s.getsockname()[1]45socks.append(s)46except Exception as e:47raise e48for s in socks:49s.close()50return ports515253def alloc_ports_and_do(port_spec: Dict[str, int],54do_func: Callable[[Dict[str, int]], bool],55gen_dir, max_tries=1) -> bool:56lock_file = os.path.join(gen_dir, 'ports.lock')57with FileLock(lock_file):58for _ in range(max_tries):59port_set = alloc_port_set(port_spec)60if do_func(port_set):61return True62return False636465