Skip to content

Commit

Permalink
Added timeout and error handling for frpc tunnel (#5731)
Browse files Browse the repository at this point in the history
* added timeout and error handling for frpc tunnel

* add changeset

* lint

* typing

* spell

* tunneling

* lint

* strip

---------

Co-authored-by: gradio-pr-bot <[email protected]>
Co-authored-by: Abubakar Abid <[email protected]>
  • Loading branch information
3 people authored Sep 28, 2023
1 parent 8986685 commit c9af4f7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/honest-phones-like.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gradio": patch
---

fix:Added timeout and error handling for frpc tunnel
37 changes: 36 additions & 1 deletion gradio/tunneling.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import re
import stat
import subprocess
import sys
import time
from pathlib import Path
from typing import List

Expand All @@ -24,6 +26,12 @@
BINARY_FOLDER = Path(__file__).parent
BINARY_PATH = f"{BINARY_FOLDER / BINARY_FILENAME}"

TUNNEL_TIMEOUT_SECONDS = 30
TUNNEL_ERROR_MESSAGE = (
"Could not create share URL. "
"Please check the appended log from frpc for more information:"
)


class Tunnel:
def __init__(self, remote_host, remote_port, local_host, local_port, share_token):
Expand Down Expand Up @@ -88,16 +96,43 @@ def _start_tunnel(self, binary: str) -> str:
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
atexit.register(self.kill)
return self._read_url_from_tunnel_stream()

def _read_url_from_tunnel_stream(self) -> str:
start_timestamp = time.time()

log = []
url = ""

def _raise_tunnel_error():
log_text = "\n".join(log)
print(log_text, file=sys.stderr)
raise ValueError(f"{TUNNEL_ERROR_MESSAGE}\n{log_text}")

while url == "":
# check for timeout and log
if time.time() - start_timestamp >= TUNNEL_TIMEOUT_SECONDS:
_raise_tunnel_error()

assert self.proc is not None
if self.proc.stdout is None:
continue

line = self.proc.stdout.readline()
line = line.decode("utf-8")

if line == "":
continue

log.append(line.strip())

if "start proxy success" in line:
result = re.search("start proxy success: (.+)\n", line)
if result is None:
raise ValueError("Could not create share URL")
_raise_tunnel_error()
else:
url = result.group(1)
elif "login to server failed" in line:
_raise_tunnel_error()

return url

0 comments on commit c9af4f7

Please sign in to comment.