Skip to content

Commit 6f42e3f

Browse files
krisctlprabhakk-mw
authored andcommitted
Use MWI_APP_HOST to update URL to be displayed in the matlab-proxy startup message.
fixes #69
1 parent e123971 commit 6f42e3f

File tree

5 files changed

+42
-39
lines changed

5 files changed

+42
-39
lines changed

Advanced-Usage.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ The following table describes all the environment variables that you can set to
1717
| **MLM_LICENSE_FILE** | string | `"1234@111.22.333.444"` | When you want to use either a license file or a network license manager to license MATLAB, specify this variable.</br> For example, specify the location of the network license manager to be `123@hostname`.|
1818
| **MWI_BASE_URL** | string | `"/matlab"` | Set to control the base URL of the app. MWI_BASE_URL should start with `/` or be `empty`. |
1919
| **MWI_APP_PORT** | integer | `8080` | Specify the port for the HTTP server to listen on. |
20-
| **MWI_APP_HOST** | string | `127.0.0.1` | Specify the host interface for the HTTP server to launch on. Defaults to `0.0.0.0` on POSIX and Windows systems.<br />With the default value, the server will be accessible remotely at the fully qualified domain name of the system. |
20+
| **MWI_APP_HOST** | string | `127.0.0.1` | Specify the host address to display the connection URL in the startup message.|
2121
| **MWI_LOG_LEVEL** | string | `"CRITICAL"` | Specify the Python log level to be one of the following `NOTSET`, `DEBUG`, `INFO`, `WARN`, `ERROR`, or `CRITICAL`. For more information on Python log levels, see [Logging Levels](https://docs.python.org/3/library/logging.html#logging-levels) .<br />The default value is `INFO`. |
2222
| **MWI_LOG_FILE** | string | `"/tmp/logs.txt"` | Specify the full path to the file where you want debug logs from this integration to be written. |
2323
| **MWI_ENABLE_WEB_LOGGING** | string | `"True"` | Set this value to `"True"` to see additional web server logs. |

matlab_proxy/app_state.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,29 @@
3333
MatlabInstallError,
3434
OnlineLicensingError,
3535
UIVisibleFatalError,
36-
XvfbError,
3736
WindowManagerError,
37+
XvfbError,
3838
log_error,
3939
)
4040

4141
logger = mwi.logger.get()
4242

4343

44+
def _get_server_urls(server_url: str, mwi_auth_token_str: str) -> list[str]:
45+
"""Returns list of server URLs including user supplied hostname, if any."""
46+
# By default mwi_server_url usually points to 0.0.0.0 as the hostname, but this does not work well
47+
# on some browsers. Specifically on Safari (MacOS), hence the replace op with localhost.
48+
server_urls_with_auth_token = [
49+
f'{server_url.replace("0.0.0.0", "localhost")}{mwi_auth_token_str}'
50+
]
51+
if user_supplied_hostname := os.getenv(mwi_env.get_env_name_app_host(), "").strip():
52+
server_urls_with_auth_token.append(
53+
f'{server_urls_with_auth_token[0].replace("localhost", user_supplied_hostname)}'
54+
)
55+
56+
return server_urls_with_auth_token
57+
58+
4459
class AppState:
4560
"""A Class which represents the state of the App.
4661
This class handles state of MATLAB, MATLAB Licensing and Xvfb.
@@ -219,15 +234,15 @@ def __get_cached_config_file(self):
219234
def __delete_cached_config_file(self):
220235
"""Deletes the cached config file"""
221236
try:
222-
logger.debug(f"Deleting any cached config files!")
237+
logger.debug("Deleting any cached config files!")
223238
os.remove(self.__get_cached_config_file())
224239
except FileNotFoundError:
225240
# The file being absent is acceptable.
226241
pass
227242

228243
def __reset_and_delete_cached_config(self):
229244
"""Reset licensing variable of the class and removes the cached config file."""
230-
logger.debug(f"Resetting cached config information...")
245+
logger.debug("Resetting cached config information...")
231246
self.licensing = None
232247
self.__delete_cached_config_file()
233248

@@ -263,7 +278,7 @@ async def init_licensing(self):
263278
f"{mwi_env.get_env_name_mwi_use_existing_license()} variable set in environment"
264279
)
265280
logger.info(
266-
f"!!! Starting MATLAB without providing any additional licensing information. This requires MATLAB to have been activated on the machine from which its being started !!!"
281+
"!!! Starting MATLAB without providing any additional licensing information. This requires MATLAB to have been activated on the machine from which its being started !!!"
267282
)
268283

269284
# Delete old config info from cache to ensure its wiped out first before persisting new info.
@@ -342,7 +357,7 @@ async def init_licensing(self):
342357
else:
343358
# Somethings wrong, licensing is neither NLM or MHLM
344359
self.__reset_and_delete_cached_config()
345-
except Exception as e:
360+
except Exception:
346361
self.__reset_and_delete_cached_config()
347362

348363
async def __update_matlab_state_based_on_connector_state(self):
@@ -900,16 +915,11 @@ def create_server_info_file(self):
900915
self.mwi_server_session_files["mwi_server_info_file"] = mwi_server_info_file
901916
logger.debug(f"Server info stored into: {mwi_server_info_file}")
902917

903-
# By default mwi_server_url usually points to 0.0.0.0 as the hostname, but this does not work well
904-
# on some browsers. Specifically on Safari (MacOS)
905-
server_url = (
906-
self.settings["mwi_server_url"].replace("0.0.0.0", "localhost")
907-
+ mwi_auth_token_str
908-
)
909-
910918
mwi.logger.log_startup_info(
911919
title=f"matlab-proxy-app running on {self.settings['app_port']}",
912-
matlab_url=server_url,
920+
matlab_urls=_get_server_urls(
921+
self.settings["mwi_server_url"], mwi_auth_token_str
922+
),
913923
)
914924
logger.info(f"MATLAB Root: {self.settings['matlab_path']}")
915925

@@ -1103,7 +1113,7 @@ async def __start_xvfb_process(self):
11031113

11041114
# FileNotFoundError: is thrown if Xvfb is not found on System Path.
11051115
# XvfbError: is thrown if something went wrong when starting Xvfb process.
1106-
except (FileNotFoundError, XvfbError) as err:
1116+
except (FileNotFoundError, XvfbError):
11071117
self.error = XvfbError(
11081118
"""Unable to start the Xvfb process. Ensure Xvfb is installed and is available on the System Path. See https://github.com/mathworks/matlab-proxy#requirements for information on Xvfb"""
11091119
)
@@ -1309,7 +1319,7 @@ async def start_matlab(self, restart_matlab=False):
13091319
# to MATLAB state by other functions/tasks until the lock is released, ensuring consistency. It's released early only in case of exceptions.
13101320
await self.matlab_state_updater_lock.acquire()
13111321
self.set_matlab_state("starting")
1312-
logger.info(f"Starting MATLAB...")
1322+
logger.info("Starting MATLAB...")
13131323

13141324
# Clear MATLAB errors and logging
13151325
self.error = None

matlab_proxy/settings.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from matlab_proxy.util import mwi, system
2222
from matlab_proxy.util.cookie_jar import HttpOnlyCookieJar
2323
from matlab_proxy.util.mwi import environment_variables as mwi_env
24-
from matlab_proxy.util.mwi import token_auth, session_name
24+
from matlab_proxy.util.mwi import session_name, token_auth
2525
from matlab_proxy.util.mwi.exceptions import (
2626
FatalError,
2727
MatlabInstallError,
@@ -191,7 +191,7 @@ def get_dev_settings(config):
191191
"create_xvfb_cmd": create_xvfb_cmd,
192192
"base_url": os.environ.get(mwi_env.get_env_name_base_url(), ""),
193193
"app_port": os.environ.get(mwi_env.get_env_name_app_port(), 8000),
194-
"host_interface": os.environ.get(mwi_env.get_env_name_app_host(), "127.0.0.1"),
194+
"host_interface": "127.0.0.1",
195195
"mwapikey": str(uuid.uuid4()),
196196
"matlab_protocol": "http",
197197
"matlab_display": ":1",
@@ -329,8 +329,8 @@ def get_server_settings(config_name):
329329
"base_url": mwi.validators.validate_base_url(
330330
os.getenv(mwi_env.get_env_name_base_url(), "")
331331
),
332-
# Set default to host interface to 0.0.0.0
333-
"host_interface": os.environ.get(mwi_env.get_env_name_app_host(), "0.0.0.0"),
332+
# Set host interface to 0.0.0.0 to bind on all interfaces
333+
"host_interface": "0.0.0.0",
334334
# not_exception_safe, can_terminate_process by throwing FatalError
335335
"app_port": mwi.validators.validate_app_port_is_free(
336336
os.getenv(mwi_env.get_env_name_app_port())

matlab_proxy/util/mwi/logger.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
# Copyright 2020-2025 The MathWorks, Inc.
22
"""Functions to access & control the logging behavior of the app"""
33

4-
from . import environment_variables as mwi_env
5-
6-
from pathlib import Path
7-
from rich.console import Console
8-
from rich.table import Table
94
import logging
105
import os
116
import sys
127
import time
8+
from pathlib import Path
9+
10+
from rich.console import Console
11+
from rich.table import Table
12+
13+
from . import environment_variables as mwi_env
1314

1415
logging.getLogger("aiohttp_session").setLevel(logging.ERROR)
1516

@@ -144,7 +145,7 @@ def __is_invalid_log_level(log_level):
144145
return not hasattr(logging, log_level)
145146

146147

147-
def log_startup_info(title=None, matlab_url=None):
148+
def log_startup_info(title=None, matlab_urls=[]):
148149
"""Logs the startup information to the console and log file if specified."""
149150
logger = __get_mw_logger()
150151
print_as_table = False
@@ -155,7 +156,7 @@ def log_startup_info(title=None, matlab_url=None):
155156
console = Console()
156157
# Number of additional characters used by the table
157158
padding = 4
158-
print_as_table = len(matlab_url) + padding <= console.width
159+
print_as_table = all(len(url) + padding <= console.width for url in matlab_urls)
159160

160161
if print_as_table:
161162
table = Table(
@@ -168,11 +169,13 @@ def log_startup_info(title=None, matlab_url=None):
168169
)
169170
table.add_column(overflow="fold", style="bold green", justify="center")
170171
table.add_row(header_info)
171-
table.add_row(matlab_url)
172+
for url in matlab_urls:
173+
table.add_row(url)
172174
console.print(table)
173175

174176
if os.getenv(mwi_env.get_env_name_log_file(), None) or not print_as_table:
175-
logger.critical(f"{header_info} {matlab_url}")
177+
urls = "\n\t".join(matlab_urls)
178+
logger.critical(f"{header_info}\n\t{urls}")
176179

177180

178181
class _ColoredFormatter(logging.Formatter):

tests/unit/test_app.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -924,16 +924,6 @@ def test_get_access_url_non_dev_windows(
924924
assert "127.0.0.1" in util.get_access_url(test_server.app)
925925

926926

927-
@pytest.mark.skipif(
928-
platform.system() == "Windows", reason="Testing the non-Windows access URL"
929-
)
930-
def test_get_access_url_non_dev_posix(
931-
non_default_host_interface, non_test_env, test_server
932-
):
933-
"""Test to check access url to be 0.0.0.0 in non-dev mode on Linux/Darwin"""
934-
assert "0.0.0.0" in util.get_access_url(test_server.app)
935-
936-
937927
@pytest.fixture(name="set_licensing_info_mock_fetch_single_entitlement")
938928
def set_licensing_info_mock_fetch_single_entitlement_fixture():
939929
"""Fixture that returns a single entitlement

0 commit comments

Comments
 (0)