2019-09-01 23:39:53 +08:00
|
|
|
import asyncio
|
|
|
|
import time
|
2019-11-21 11:47:54 +08:00
|
|
|
from typing import Any, Awaitable, Callable, List
|
2019-08-31 00:18:22 +08:00
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
import multiaddr
|
|
|
|
from multiaddr import Multiaddr
|
2019-08-31 00:18:22 +08:00
|
|
|
from p2pclient import Client
|
2019-11-05 08:26:08 +08:00
|
|
|
import pytest
|
2019-08-31 00:18:22 +08:00
|
|
|
|
|
|
|
from libp2p.peer.id import ID
|
2019-09-01 23:39:53 +08:00
|
|
|
from libp2p.peer.peerinfo import PeerInfo, info_from_p2p_addr
|
2019-08-31 00:18:22 +08:00
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
from .constants import LOCALHOST_IP
|
2019-08-31 00:18:22 +08:00
|
|
|
from .envs import GO_BIN_PATH
|
|
|
|
|
|
|
|
P2PD_PATH = GO_BIN_PATH / "p2pd"
|
|
|
|
|
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
TIMEOUT_DURATION = 30
|
|
|
|
|
|
|
|
|
2019-11-21 11:47:54 +08:00
|
|
|
async def try_until_success(
|
|
|
|
coro_func: Callable[[], Awaitable[Any]], timeout: int = TIMEOUT_DURATION
|
|
|
|
) -> None:
|
2019-10-25 02:10:45 +08:00
|
|
|
"""
|
|
|
|
Keep running ``coro_func`` until either it succeed or time is up.
|
2019-10-24 14:41:10 +08:00
|
|
|
|
|
|
|
All arguments of ``coro_func`` should be filled, i.e. it should be
|
|
|
|
called without arguments.
|
2019-09-01 23:39:53 +08:00
|
|
|
"""
|
|
|
|
t_start = time.monotonic()
|
|
|
|
while True:
|
|
|
|
result = await coro_func()
|
|
|
|
if result:
|
|
|
|
break
|
|
|
|
if (time.monotonic() - t_start) >= timeout:
|
|
|
|
# timeout
|
2019-11-05 08:26:08 +08:00
|
|
|
pytest.fail(f"{coro_func} is still failing after `{timeout}` seconds")
|
2019-09-01 23:39:53 +08:00
|
|
|
await asyncio.sleep(0.01)
|
|
|
|
|
|
|
|
|
|
|
|
class P2PDProcess:
|
|
|
|
proc: asyncio.subprocess.Process
|
|
|
|
cmd: str = str(P2PD_PATH)
|
|
|
|
args: List[Any]
|
2019-09-04 22:19:11 +08:00
|
|
|
is_proc_running: bool
|
2019-09-01 23:39:53 +08:00
|
|
|
|
2019-09-02 17:32:15 +08:00
|
|
|
_tasks: List["asyncio.Future[Any]"]
|
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
control_maddr: Multiaddr,
|
|
|
|
is_secure: bool,
|
2019-09-02 17:32:15 +08:00
|
|
|
is_pubsub_enabled: bool = True,
|
|
|
|
is_gossipsub: bool = True,
|
|
|
|
is_pubsub_signing: bool = False,
|
|
|
|
is_pubsub_signing_strict: bool = False,
|
2019-09-01 23:39:53 +08:00
|
|
|
) -> None:
|
|
|
|
args = [f"-listen={str(control_maddr)}"]
|
|
|
|
# NOTE: To support `-insecure`, we need to hack `go-libp2p-daemon`.
|
|
|
|
if not is_secure:
|
|
|
|
args.append("-insecure=true")
|
|
|
|
if is_pubsub_enabled:
|
|
|
|
args.append("-pubsub")
|
|
|
|
if is_gossipsub:
|
|
|
|
args.append("-pubsubRouter=gossipsub")
|
|
|
|
else:
|
|
|
|
args.append("-pubsubRouter=floodsub")
|
|
|
|
if not is_pubsub_signing:
|
|
|
|
args.append("-pubsubSign=false")
|
|
|
|
if not is_pubsub_signing_strict:
|
|
|
|
args.append("-pubsubSignStrict=false")
|
|
|
|
# NOTE:
|
|
|
|
# Two other params are possibly what we want to configure:
|
|
|
|
# - gossipsubHeartbeatInterval: GossipSubHeartbeatInitialDelay = 100 * time.Millisecond # noqa: E501
|
|
|
|
# - gossipsubHeartbeatInitialDelay: GossipSubHeartbeatInterval = 1 * time.Second
|
|
|
|
# Referece: https://github.com/libp2p/go-libp2p-daemon/blob/b95e77dbfcd186ccf817f51e95f73f9fd5982600/p2pd/main.go#L348-L353 # noqa: E501
|
|
|
|
self.args = args
|
2019-09-04 22:19:11 +08:00
|
|
|
self.is_proc_running = False
|
2019-09-04 18:25:51 +08:00
|
|
|
|
2019-09-02 17:32:15 +08:00
|
|
|
self._tasks = []
|
2019-09-01 23:39:53 +08:00
|
|
|
|
2019-11-21 11:47:54 +08:00
|
|
|
async def wait_until_ready(self) -> None:
|
2019-09-01 23:39:53 +08:00
|
|
|
lines_head_pattern = (b"Control socket:", b"Peer ID:", b"Peer Addrs:")
|
|
|
|
lines_head_occurred = {line: False for line in lines_head_pattern}
|
|
|
|
|
2019-11-21 11:47:54 +08:00
|
|
|
async def read_from_daemon_and_check() -> bool:
|
2019-09-01 23:39:53 +08:00
|
|
|
line = await self.proc.stdout.readline()
|
|
|
|
for head_pattern in lines_head_occurred:
|
|
|
|
if line.startswith(head_pattern):
|
|
|
|
lines_head_occurred[head_pattern] = True
|
2019-09-04 20:35:42 +08:00
|
|
|
return all([value for value in lines_head_occurred.values()])
|
2019-09-01 23:39:53 +08:00
|
|
|
|
|
|
|
await try_until_success(read_from_daemon_and_check)
|
|
|
|
# Sleep a little bit to ensure the listener is up after logs are emitted.
|
|
|
|
await asyncio.sleep(0.01)
|
|
|
|
|
2019-09-02 17:32:15 +08:00
|
|
|
async def start_printing_logs(self) -> None:
|
|
|
|
async def _print_from_stream(
|
|
|
|
src_name: str, reader: asyncio.StreamReader
|
|
|
|
) -> None:
|
|
|
|
while True:
|
|
|
|
line = await reader.readline()
|
|
|
|
if line != b"":
|
|
|
|
print(f"{src_name}\t: {line.rstrip().decode()}")
|
|
|
|
await asyncio.sleep(0.01)
|
|
|
|
|
|
|
|
self._tasks.append(
|
|
|
|
asyncio.ensure_future(_print_from_stream("out", self.proc.stdout))
|
|
|
|
)
|
|
|
|
self._tasks.append(
|
|
|
|
asyncio.ensure_future(_print_from_stream("err", self.proc.stderr))
|
|
|
|
)
|
|
|
|
await asyncio.sleep(0)
|
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
async def start(self) -> None:
|
2019-09-04 22:19:11 +08:00
|
|
|
if self.is_proc_running:
|
|
|
|
return
|
2019-09-01 23:39:53 +08:00
|
|
|
self.proc = await asyncio.subprocess.create_subprocess_exec(
|
|
|
|
self.cmd,
|
|
|
|
*self.args,
|
|
|
|
stdout=asyncio.subprocess.PIPE,
|
|
|
|
stderr=asyncio.subprocess.PIPE,
|
|
|
|
bufsize=0,
|
|
|
|
)
|
2019-09-04 22:19:11 +08:00
|
|
|
self.is_proc_running = True
|
2019-09-01 23:39:53 +08:00
|
|
|
await self.wait_until_ready()
|
2019-09-02 17:32:15 +08:00
|
|
|
await self.start_printing_logs()
|
2019-09-01 23:39:53 +08:00
|
|
|
|
|
|
|
async def close(self) -> None:
|
2019-09-04 22:19:11 +08:00
|
|
|
if self.is_proc_running:
|
2019-09-04 18:25:51 +08:00
|
|
|
self.proc.terminate()
|
|
|
|
await self.proc.wait()
|
2019-09-04 22:19:11 +08:00
|
|
|
self.is_proc_running = False
|
2019-09-02 17:32:15 +08:00
|
|
|
for task in self._tasks:
|
|
|
|
task.cancel()
|
2019-09-01 23:39:53 +08:00
|
|
|
|
|
|
|
|
2019-08-31 00:18:22 +08:00
|
|
|
class Daemon:
|
2019-09-01 23:39:53 +08:00
|
|
|
p2pd_proc: P2PDProcess
|
2019-08-31 00:18:22 +08:00
|
|
|
control: Client
|
|
|
|
peer_info: PeerInfo
|
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
def __init__(
|
|
|
|
self, p2pd_proc: P2PDProcess, control: Client, peer_info: PeerInfo
|
|
|
|
) -> None:
|
|
|
|
self.p2pd_proc = p2pd_proc
|
2019-08-31 00:18:22 +08:00
|
|
|
self.control = control
|
|
|
|
self.peer_info = peer_info
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
|
|
|
return f"<Daemon {self.peer_id.to_string()[2:8]}>"
|
|
|
|
|
|
|
|
@property
|
|
|
|
def peer_id(self) -> ID:
|
|
|
|
return self.peer_info.peer_id
|
|
|
|
|
|
|
|
@property
|
|
|
|
def listen_maddr(self) -> Multiaddr:
|
|
|
|
return self.peer_info.addrs[0]
|
|
|
|
|
2019-09-01 23:39:53 +08:00
|
|
|
async def close(self) -> None:
|
|
|
|
await self.p2pd_proc.close()
|
|
|
|
await self.control.close()
|
|
|
|
|
2019-08-31 00:18:22 +08:00
|
|
|
|
|
|
|
async def make_p2pd(
|
2019-09-03 16:55:42 +08:00
|
|
|
daemon_control_port: int,
|
|
|
|
client_callback_port: int,
|
2019-08-31 00:18:22 +08:00
|
|
|
is_secure: bool,
|
2019-11-21 11:47:54 +08:00
|
|
|
is_pubsub_enabled: bool = True,
|
|
|
|
is_gossipsub: bool = True,
|
|
|
|
is_pubsub_signing: bool = False,
|
|
|
|
is_pubsub_signing_strict: bool = False,
|
2019-08-31 00:18:22 +08:00
|
|
|
) -> Daemon:
|
2019-09-03 16:55:42 +08:00
|
|
|
control_maddr = Multiaddr(f"/ip4/{LOCALHOST_IP}/tcp/{daemon_control_port}")
|
2019-09-01 23:39:53 +08:00
|
|
|
p2pd_proc = P2PDProcess(
|
|
|
|
control_maddr,
|
|
|
|
is_secure,
|
|
|
|
is_pubsub_enabled,
|
|
|
|
is_gossipsub,
|
|
|
|
is_pubsub_signing,
|
|
|
|
is_pubsub_signing_strict,
|
2019-08-31 00:18:22 +08:00
|
|
|
)
|
2019-09-01 23:39:53 +08:00
|
|
|
await p2pd_proc.start()
|
2019-09-03 16:55:42 +08:00
|
|
|
client_callback_maddr = Multiaddr(f"/ip4/{LOCALHOST_IP}/tcp/{client_callback_port}")
|
2019-08-31 00:18:22 +08:00
|
|
|
p2pc = Client(control_maddr, client_callback_maddr)
|
2019-09-01 23:39:53 +08:00
|
|
|
await p2pc.listen()
|
|
|
|
peer_id, maddrs = await p2pc.identify()
|
|
|
|
listen_maddr: Multiaddr = None
|
|
|
|
for maddr in maddrs:
|
|
|
|
try:
|
|
|
|
ip = maddr.value_for_protocol(multiaddr.protocols.P_IP4)
|
2019-09-04 20:49:14 +08:00
|
|
|
# NOTE: Check if this `maddr` uses `tcp`.
|
2019-09-01 23:39:53 +08:00
|
|
|
maddr.value_for_protocol(multiaddr.protocols.P_TCP)
|
|
|
|
except multiaddr.exceptions.ProtocolLookupError:
|
|
|
|
continue
|
|
|
|
if ip == LOCALHOST_IP:
|
|
|
|
listen_maddr = maddr
|
|
|
|
break
|
|
|
|
assert listen_maddr is not None, "no loopback maddr is found"
|
|
|
|
peer_info = info_from_p2p_addr(
|
|
|
|
listen_maddr.encapsulate(Multiaddr(f"/p2p/{peer_id.to_string()}"))
|
|
|
|
)
|
|
|
|
return Daemon(p2pd_proc, p2pc, peer_info)
|