Skip to content

Commit 32aaa8c

Browse files
Bugfix: Host Interface for the server will default to 0.0.0.0 instead of localhost.
1 parent e1618d8 commit 32aaa8c

File tree

12 files changed

+128
-47
lines changed

12 files changed

+128
-47
lines changed

Advanced-Usage.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ The following table describes all the environment variables that you can set to
1818
| **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`.|
1919
| **MWI_BASE_URL** | string | `"/matlab"` | Set to control the base URL of the app. MWI_BASE_URL should start with `/` or be `empty`. |
2020
| **MWI_APP_PORT** | integer | `8080` | Specify the port for the HTTP server to listen on. |
21+
| **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. |
2122
| **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`. |
2223
| **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. |
2324
| **MWI_ENABLE_WEB_LOGGING** | string | `"True"` | Set this value to `"True"` to see additional web server logs. |

matlab_proxy/app.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
import aiohttp
1010
from aiohttp import web
11-
1211
from aiohttp_session import setup as aiohttp_session_setup
1312
from aiohttp_session.cookie_storage import EncryptedCookieStorage
1413
from cryptography import fernet
@@ -17,10 +16,10 @@
1716
from matlab_proxy import settings, util
1817
from matlab_proxy.app_state import AppState
1918
from matlab_proxy.default_configuration import config
20-
from matlab_proxy.util import mwi, list_servers
19+
from matlab_proxy.util import list_servers, mwi
2120
from matlab_proxy.util.mwi import environment_variables as mwi_env
22-
from matlab_proxy.util.mwi.exceptions import LicensingError
2321
from matlab_proxy.util.mwi import token_auth
22+
from matlab_proxy.util.mwi.exceptions import LicensingError
2423

2524
mimetypes.add_type("font/woff", ".woff")
2625
mimetypes.add_type("font/woff2", ".woff2")
@@ -589,7 +588,7 @@ def configure_and_start(app):
589588

590589
# Update the site origin in settings.
591590
# The origin will be used for communicating with the Embedded connector.
592-
app["settings"]["mwi_server_url"] = site.name + app["settings"]["base_url"]
591+
app["settings"]["mwi_server_url"] = util.get_access_url(app)
593592

594593
loop.run_until_complete(site.start())
595594

matlab_proxy/app_state.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11
# Copyright (c) 2020-2022 The MathWorks, Inc.
22

3-
import aiohttp
43
import asyncio
54
import errno
65
import json
76
import logging
87
import os
9-
import time
108
import socket
119
import sys
12-
10+
import time
1311
from collections import deque
1412
from datetime import datetime, timedelta, timezone
1513

14+
import aiohttp
15+
1616
from matlab_proxy import util
17-
from matlab_proxy.util.mwi import token_auth
18-
from matlab_proxy.util import mw, mwi, windows, system
17+
from matlab_proxy.util import mw, mwi, system, windows
1918
from matlab_proxy.util.mwi import environment_variables as mwi_env
19+
from matlab_proxy.util.mwi import token_auth
2020
from matlab_proxy.util.mwi.exceptions import (
2121
EmbeddedConnectorError,
2222
EntitlementError,
2323
InternalError,
2424
LicensingError,
2525
MatlabError,
26-
XvfbError,
2726
MatlabInstallError,
2827
OnlineLicensingError,
28+
XvfbError,
2929
log_error,
3030
)
3131

@@ -475,13 +475,10 @@ def prepare_lock_files_for_MATLAB_launch(self):
475475
)
476476
return
477477

478-
# When testing in github workflows, for windows container's, PermissionError is
478+
# For windows container's (when testing in github workflows) PermissionError and in linux, OSError is
479479
# thrown when trying to bind a used port from a previous test instead of the expected socket.error
480480
except (OSError, PermissionError) as e:
481-
if system.is_windows():
482-
pass
483-
else:
484-
raise e
481+
pass
485482

486483
except socket.error as e:
487484
if e.errno != errno.EADDRINUSE:
@@ -788,7 +785,7 @@ async def matlab_stderr_reader():
788785

789786
# The maximum amount of time in seconds the Embedded Connector can take
790787
# for lauching, before the matlab-proxy server concludes that something is wrong.
791-
self.embedded_connector_max_starting_duration = 15
788+
self.embedded_connector_max_starting_duration = 120
792789

793790
# In Windows systems, errors are raised as UI windows and cannot be captured programmatically.
794791
# So, check for how long the Embedded Connector is not up and then raise a generic error.

matlab_proxy/settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,9 @@ def get(config_name=matlab_proxy.get_default_config_name(), dev=False):
165165
"app_port": mwi.validators.validate_app_port_is_free(
166166
os.getenv(mwi_env.get_env_name_app_port())
167167
),
168+
# Set default to host interface to 0.0.0.0
168169
"host_interface": os.environ.get(
169-
mwi_env.get_env_name_app_host(), "localhost"
170+
mwi_env.get_env_name_app_host(), "0.0.0.0"
170171
),
171172
"mwapikey": str(uuid.uuid4()),
172173
"matlab_protocol": "https",

matlab_proxy/util/__init__.py

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,6 @@
1212
logger = mwi.logger.get()
1313

1414

15-
def get_event_loop():
16-
"""Returns an asyncio event loop by checking the current python version and uses the appropriate
17-
asyncio API
18-
19-
Returns:
20-
asyncio.loop: asyncio event loop.
21-
"""
22-
# get_running_loop() api is available for python >= 3.7
23-
try:
24-
# Try to get an existing event loop.
25-
# If there's no running event loop, raise RuntimeError.
26-
loop = asyncio.get_running_loop()
27-
except RuntimeError:
28-
# If execution reached this except block, it implies that there
29-
# was no running event loop. So, create one.
30-
loop = asyncio.get_event_loop()
31-
32-
return loop
33-
34-
3515
def parse_cli_args():
3616
"""Parses CLI arguments passed to the main() function.
3717
@@ -214,3 +194,37 @@ def get_child_processes(parent_process):
214194
break
215195

216196
return child_processes
197+
198+
199+
def get_access_url(app):
200+
"""Returns the url at which the server will be accessible at
201+
202+
Args:
203+
app (aiohttp.web.Application): The web application from aiottp package
204+
205+
Returns:
206+
str: complete url at which the server will be accessible.
207+
"""
208+
base_url = app["settings"]["base_url"]
209+
port = app["settings"]["app_port"]
210+
211+
ssl_context = app["settings"]["ssl_context"]
212+
host_interface = app["settings"]["host_interface"]
213+
214+
access_protocol = "https" if ssl_context else "http"
215+
216+
# When host interface is set to 0.0.0.0, in a windows system, the server will not be accessible.
217+
# Setting the value to fqdn, will allow it be remotely and locally accessible.
218+
219+
# NOTE: When windows container support is introduced this will need to be tweaked accordingly.
220+
if host_interface == "0.0.0.0" and system.is_windows():
221+
import socket
222+
223+
hostname = socket.gethostname()
224+
fqdn = socket.getfqdn(hostname)
225+
226+
url = f"{access_protocol}://{fqdn}:{port}{base_url}"
227+
else:
228+
url = f"{access_protocol}://{host_interface}:{port}{base_url}"
229+
230+
return url

matlab_proxy/util/list_servers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33

44
import glob
55
import os
6-
import matlab_proxy.util as mwi_util
6+
77
import matlab_proxy.settings as mwi_settings
8+
import matlab_proxy.util as mwi_util
89

910

1011
def print_server_info():

matlab_proxy/util/mwi/token_auth.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
# This file contains functions required to enable token based authentication in the server.
44

5+
import os
6+
import secrets
7+
58
from aiohttp import web
6-
from aiohttp_session import setup, get_session, new_session
9+
from aiohttp_session import get_session, new_session, setup
710
from aiohttp_session.cookie_storage import EncryptedCookieStorage
811
from matlab_proxy.util.mwi import environment_variables as mwi_env
9-
import os
10-
import secrets
12+
1113
from . import logger as mwi_logger
1214

1315
logger = mwi_logger.get()

matlab_proxy/util/system.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Copyright 2022 The MathWorks, Inc.
22
import os
3-
import signal
43
import platform
4+
import signal
55

66
"""Contains methods and helpers which return OS specific information
77
"""

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def run(self):
6666

6767
setuptools.setup(
6868
name="matlab-proxy",
69-
version="0.4.0",
69+
version="0.4.1",
7070
url=config["doc_url"],
7171
author="The MathWorks, Inc.",
7272
author_email="cloud@mathworks.com",

tests/test_app.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99
from aiohttp import web
1010
from matlab_proxy import app, util
11+
from matlab_proxy.util.mwi import environment_variables as mwi_env
1112
from matlab_proxy.util.mwi.exceptions import MatlabInstallError
1213

1314

@@ -540,3 +541,41 @@ async def test_set_termination_integration_delete(test_server):
540541
assert resp.status == 200 and resp_json["loadUrl"] == "../"
541542
except ProcessLookupError:
542543
pass
544+
545+
546+
def test_get_access_url(test_server):
547+
"""Should return a url with 127.0.0.1 in test mode
548+
549+
Args:
550+
test_server (aiohttp.web.Application): Application Server
551+
"""
552+
assert "127.0.0.1" in util.get_access_url(test_server.app)
553+
554+
555+
@pytest.fixture(name="non_test_env")
556+
def non_test_env_fixture(monkeypatch):
557+
"""Monkeypatches MWI_TEST env var to false
558+
559+
Args:
560+
monkeypatch (_pytest.monkeypatch.MonkeyPatch): To monkeypatch env vars
561+
"""
562+
monkeypatch.setenv(mwi_env.get_env_name_testing(), "false")
563+
564+
565+
@pytest.fixture(name="non_default_host_interface")
566+
def non_default_host_interface_fixture(monkeypatch):
567+
"""Monkeypatches MWI_TEST env var to false
568+
569+
Args:
570+
monkeypatch (_pytest.monkeypatch.MonkeyPatch): To monkeypatch env vars
571+
"""
572+
monkeypatch.setenv(mwi_env.get_env_name_app_host(), "0.0.0.0")
573+
574+
575+
# For pytest fixtures, order of arguments matter.
576+
# First set the default host interface to a non-default value
577+
# Then set MWI_TEST to false and then create an instance of the test_server
578+
# This order will set the test_server with appropriate values.
579+
def test_get_access_url_non_dev(non_default_host_interface, non_test_env, test_server):
580+
"""Test to check access url to not be 127.0.0.1 in non-dev mode"""
581+
assert "127.0.0.1" not in util.get_access_url(test_server.app)

0 commit comments

Comments
 (0)