Skip to content

Commit

Permalink
Handle exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
ElijahAhianyo committed May 3, 2024
1 parent 829a6b3 commit 9fb55f3
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 36 deletions.
90 changes: 57 additions & 33 deletions reflex/utils/prerequisites.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ class Template(Base):
class CpuInfo(Base):
"""Model to save cpu info."""

manufacturer_id: str
model_name: str
address_width: int
manufacturer_id: Optional[str]
model_name: Optional[str]
address_width: Optional[int]


def check_latest_package_version(package_name: str):
Expand Down Expand Up @@ -1422,6 +1422,21 @@ def initialize_app(app_name: str, template: str | None = None):
telemetry.send("init", template=template)


def format_address_width(address_width) -> int | None:
"""Cast address width to an int.
Args:
address_width: The address width.
Returns:
Address width int
"""
try:
return int(address_width) if address_width else None
except ValueError:
return None


@functools.lru_cache(maxsize=None)
def get_cpu_info() -> CpuInfo | None:
"""Get the CPU info of the underlining host.
Expand All @@ -1431,39 +1446,47 @@ def get_cpu_info() -> CpuInfo | None:
"""
platform_os = platform.system()
cpuinfo = {}
if platform_os == "Windows":
cmd = "wmic cpu get addresswidth,caption,manufacturer /FORMAT:csv"
output = processes.execute_command_and_return_output(cmd)
val = output.splitlines()[-1].split(",")[1:]
cpuinfo["manufacturer_id"] = val[2]
cpuinfo["model_name"] = val[1].split("Family")[0].strip()
cpuinfo["address_width"] = int(val[0])
elif platform_os == "Linux":
output = processes.execute_command_and_return_output("lscpu")
lines = output.split("\n")
for line in lines:
if "Architecture" in line:
cpuinfo["address_width"] = (
64 if line.split(":")[1].strip() == "x86_64" else 32
)
if "Vendor ID:" in line:
cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
if "Model name" in line:
cpuinfo["model_name"] = line.split(":")[1].strip()
elif platform_os == "Darwin":
cpuinfo["address_width"] = int(
processes.execute_command_and_return_output("getconf LONG_BIT")
)
cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
"sysctl -n machdep.cpu.brand_string"
)
cpuinfo["model_name"] = processes.execute_command_and_return_output("uname -m")
try:
if platform_os == "Windows":
cmd = "wmic cpu get addresswidth,caption,manufacturer /FORMAT:csv"
output = processes.execute_command_and_return_output(cmd)
if output:
val = output.splitlines()[-1].split(",")[1:]
cpuinfo["manufacturer_id"] = val[2]
cpuinfo["model_name"] = val[1].split("Family")[0].strip()
cpuinfo["address_width"] = format_address_width(val[0])
elif platform_os == "Linux":
output = processes.execute_command_and_return_output("lscpu")
if output:
lines = output.split("\n")
for line in lines:
if "Architecture" in line:
cpuinfo["address_width"] = (
64 if line.split(":")[1].strip() == "x86_64" else 32
)
if "Vendor ID:" in line:
cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
if "Model name" in line:
cpuinfo["model_name"] = line.split(":")[1].strip()
elif platform_os == "Darwin":
cpuinfo["address_width"] = format_address_width(
processes.execute_command_and_return_output("getconf LONG_BIT")
)
cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
"sysctl -n machdep.cpu.brand_string"
)
cpuinfo["model_name"] = processes.execute_command_and_return_output(
"uname -m"
)
except Exception as err:
console.error(f"Failed to retrieve CPU info. {err}")
return None

return (
CpuInfo(
manufacturer_id=cpuinfo.get("manufacturer_id"), # type: ignore
model_name=cpuinfo.get("model_name"), # type: ignore
address_width=cpuinfo.get("address_width"), # type: ignore
manufacturer_id=cpuinfo.get("manufacturer_id"),
model_name=cpuinfo.get("model_name"),
address_width=cpuinfo.get("address_width"),
)
if cpuinfo
else None
Expand All @@ -1483,5 +1506,6 @@ def is_windows_bun_supported() -> bool:
constants.IS_WINDOWS
and cpu_info is not None
and cpu_info.address_width == 64
and cpu_info.model_name is not None
and "ARM" not in cpu_info.model_name
)
10 changes: 8 additions & 2 deletions reflex/utils/processes.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def run_process_with_fallback(args, *, show_status_message, fallback=None, **kwa
)


def execute_command_and_return_output(command):
def execute_command_and_return_output(command) -> str | None:
"""Execute a command and return the output.
Args:
Expand All @@ -358,4 +358,10 @@ def execute_command_and_return_output(command):
Returns:
The output of the command.
"""
return subprocess.check_output(command, shell=True).decode().strip()
try:
return subprocess.check_output(command, shell=True).decode().strip()
except subprocess.SubprocessError as err:
console.error(
f"The command `{command}` failed with error: {err}. This will return None."
)
return None
5 changes: 4 additions & 1 deletion reflex/utils/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ def _prepare_event(event: str, **kwargs) -> dict:
else:
# for python 3.11 & 3.12
stamp = datetime.now(UTC).isoformat()

cpuinfo = get_cpu_info()

return {
"api_key": "phc_JoMo0fOyi0GQAooY3UyO9k0hebGkMyFJrrCw1Gt5SGb",
"event": event,
Expand All @@ -135,7 +138,7 @@ def _prepare_event(event: str, **kwargs) -> dict:
"python_version": get_python_version(),
"cpu_count": get_cpu_count(),
"memory": get_memory(),
"cpu_info": dict(get_cpu_info()) if get_cpu_info() else {}, # type: ignore
"cpu_info": dict(cpuinfo) if cpuinfo else {},
**(
{"template": template}
if (template := kwargs.get("template")) is not None
Expand Down

0 comments on commit 9fb55f3

Please sign in to comment.