✨ Also test if DNS works in connectivity check
Should hopefully unearth cases where the system has a connection to the internet but name resolution is broken in some way. We default to resolving octoprint.org.
This commit is contained in:
1 parent
b930fb0edb
commit
aab012d530
16 files changed
+460
-199
No files matched your search
@@ -99,6 +99,14 @@ Test paths or URLs
|
||||
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the test result!
|
||||
|
||||
resolution
|
||||
Tests whether a provided hostname can be resolved (via DNS lookup). Supported parameters are:
|
||||
|
||||
* ``name``: The host name to test. Mandatory.
|
||||
|
||||
The ``resolution`` command returns :http:statuscode:`200` with a :ref:`Resolution test result <sec-api-util-datamodel-resolutiontestresult>`
|
||||
when the test could be performed. The status code of the response does NOT reflect the test result!
|
||||
|
||||
Requires the ``ADMIN`` permission.
|
||||
|
||||
**Example 1**
|
||||
@@ -286,6 +294,32 @@ Test paths or URLs
|
||||
"result": true
|
||||
}
|
||||
|
||||
**Example 7**
|
||||
|
||||
Test whether a host name can be resolved successfully.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/util/test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"command": "resolution",
|
||||
"name": "octoprint"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "octoprint.org",
|
||||
"result": true
|
||||
}
|
||||
|
||||
:json command: The command to execute, currently either ``path`` or ``url``
|
||||
:json path: ``path`` command only: the path to test
|
||||
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
|
||||
@@ -302,6 +336,7 @@ Test paths or URLs
|
||||
:json host: ``server`` command only: the server to test
|
||||
:json port: ``server`` command only: the port to test
|
||||
:json protocol: ``server`` command only: the protocol to test
|
||||
:json name: ``resolution`` command only: the host name to test
|
||||
:statuscode 200: No error occurred
|
||||
|
||||
.. _sec-api-util-datamodel:
|
||||
@@ -409,3 +444,25 @@ Server test result
|
||||
- 1
|
||||
- bool
|
||||
- ``true`` if the check passed.
|
||||
|
||||
.. _sec-api-util-datamodel-resolutiontestresult:
|
||||
|
||||
Resolution test result
|
||||
----------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- string
|
||||
- The host name that was tested.
|
||||
* - ``result``
|
||||
- 1
|
||||
- bool
|
||||
- ``true`` if the check passed.
|
||||
@@ -187,7 +187,7 @@
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.util.testUrl("127.0.0.1", 1234, {"protocol": "udp"})
|
||||
OctoPrint.util.testServer("127.0.0.1", 1234, {"protocol": "udp"})
|
||||
.done(function(response) {
|
||||
if (response.result) {
|
||||
// check passed
|
||||
@@ -203,6 +203,30 @@
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.util.testResolution(name, additional, opts)
|
||||
|
||||
Test if a host name can be resolved.
|
||||
|
||||
**Example**
|
||||
|
||||
Test if ``octoprint.org`` can be resolved.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.util.testResolution("octoprint.org")
|
||||
.done(function(response) {
|
||||
if (response.result) {
|
||||
// check passed
|
||||
} else {
|
||||
// check failed
|
||||
}
|
||||
});
|
||||
|
||||
:param string name: Host name to test
|
||||
:param object additional: Additional parameters for the test command
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ref:`Util API <sec-api-util>`
|
||||
|
||||
@@ -559,15 +559,22 @@ def init_connectivity_checker(settings, event_manager):
|
||||
connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = settings.getInt(["server", "onlineCheck", "port"])
|
||||
connectivityName = settings.get(["server", "onlineCheck", "name"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
def on_connectivity_change(old_value, new_value, connection_working=None, resolution_working=None):
|
||||
event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value,
|
||||
new=new_value,
|
||||
connection=connection_working,
|
||||
resolution=resolution_working))
|
||||
|
||||
connectivityChecker = ConnectivityChecker(connectivityInterval,
|
||||
connectivityHost,
|
||||
port=connectivityPort,
|
||||
name=connectivityName,
|
||||
enabled=connectivityEnabled,
|
||||
on_change=on_connectivity_change)
|
||||
connectivityChecker.check_immediately()
|
||||
connectivityChecker.log_full_report()
|
||||
|
||||
return connectivityChecker
|
||||
|
||||
|
||||
@@ -346,11 +346,6 @@ class Server(object):
|
||||
JsonEncoding.add_encoder(permissions.OctoPrintPermission, lambda obj: obj.as_dict())
|
||||
|
||||
# start regular check if we are connected to the internet
|
||||
connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"])
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
|
||||
def on_connectivity_change(old_value, new_value):
|
||||
eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
|
||||
|
||||
@@ -362,15 +357,18 @@ class Server(object):
|
||||
connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"])
|
||||
connectivityHost = self._settings.get(["server", "onlineCheck", "host"])
|
||||
connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"])
|
||||
connectivityName = self._settings.get(["server", "onlineCheck", "name"])
|
||||
|
||||
if connectivityChecker.enabled != connectivityEnabled \
|
||||
or connectivityChecker.interval != connectivityInterval \
|
||||
or connectivityChecker.host != connectivityHost \
|
||||
or connectivityChecker.port != connectivityPort:
|
||||
or connectivityChecker.port != connectivityPort \
|
||||
or connectivityChecker.name != connectivityName:
|
||||
connectivityChecker.enabled = connectivityEnabled
|
||||
connectivityChecker.interval = connectivityInterval
|
||||
connectivityChecker.host = connectivityHost
|
||||
connectivityChecker.port = connectivityPort
|
||||
connectivityChecker.name = connectivityName
|
||||
connectivityChecker.check_immediately()
|
||||
|
||||
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
|
||||
|
||||
@@ -306,7 +306,8 @@ def utilTest():
|
||||
valid_commands = dict(
|
||||
path=["path"],
|
||||
url=["url"],
|
||||
server=["host", "port"]
|
||||
server=["host", "port"],
|
||||
resolution=["name"]
|
||||
)
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -319,6 +320,8 @@ def utilTest():
|
||||
return _test_url(data)
|
||||
elif command == "server":
|
||||
return _test_server(data)
|
||||
elif command == "resolution":
|
||||
return _test_resolution(data)
|
||||
|
||||
def _test_path(data):
|
||||
import os
|
||||
@@ -564,3 +567,14 @@ def _test_server(data):
|
||||
result=reachable)
|
||||
|
||||
return jsonify(**result)
|
||||
|
||||
def _test_resolution(data):
|
||||
name = data["name"]
|
||||
|
||||
from octoprint.util.net import resolve_host
|
||||
resolvable = len(resolve_host(name)) > 0
|
||||
|
||||
result = dict(name=name,
|
||||
result=resolvable)
|
||||
|
||||
return jsonify(**result)
|
||||
@@ -243,7 +243,8 @@ def getSettings():
|
||||
"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
|
||||
"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
|
||||
"host": s.get(["server", "onlineCheck", "host"]),
|
||||
"port": s.getInt(["server", "onlineCheck", "port"])
|
||||
"port": s.getInt(["server", "onlineCheck", "port"]),
|
||||
"name": s.get(["server", "onlineCheck", "name"])
|
||||
},
|
||||
"pluginBlacklist": {
|
||||
"enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]),
|
||||
@@ -562,6 +563,7 @@ def _saveSettings(data):
|
||||
pass
|
||||
if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"])
|
||||
if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"])
|
||||
if "name" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "name"], data["server"]["onlineCheck"]["name"])
|
||||
if "pluginBlacklist" in data["server"]:
|
||||
if "enabled" in data["server"]["pluginBlacklist"]: s.setBoolean(["server", "pluginBlacklist", "enabled"], data["server"]["pluginBlacklist"]["enabled"])
|
||||
if "url" in data["server"]["pluginBlacklist"]: s.set(["server", "pluginBlacklist", "url"], data["server"]["pluginBlacklist"]["url"])
|
||||
|
||||
@@ -204,7 +204,8 @@ default_settings = {
|
||||
"enabled": None,
|
||||
"interval": 15 * 60, # 15 min
|
||||
"host": "8.8.8.8",
|
||||
"port": 53
|
||||
"port": 53,
|
||||
"name": "octoprint.org"
|
||||
},
|
||||
"pluginBlacklist": {
|
||||
"enabled": None,
|
||||
|
||||
@@ -55,6 +55,15 @@
|
||||
return this.test("server", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testResolution = function(name, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.name = name;
|
||||
|
||||
return this.test("resolution", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
|
||||
return OctoPrintUtilClient;
|
||||
});
|
||||
@@ -248,6 +248,7 @@ $(function() {
|
||||
self.server_onlineCheck_interval = ko.observable();
|
||||
self.server_onlineCheck_host = ko.observable();
|
||||
self.server_onlineCheck_port = ko.observable();
|
||||
self.server_onlineCheck_name = ko.observable();
|
||||
|
||||
self.server_pluginBlacklist_enabled = ko.observable();
|
||||
self.server_pluginBlacklist_url = ko.observable();
|
||||
@@ -275,6 +276,14 @@ $(function() {
|
||||
self.server_onlineCheckOk(false);
|
||||
self.server_onlineCheckBroken(false);
|
||||
};
|
||||
self.server_onlineCheckResolutionText = ko.observable();
|
||||
self.server_onlineCheckResolutionOk = ko.observable(false);
|
||||
self.server_onlineCheckResolutionBroken = ko.observable(false);
|
||||
self.server_onlineCheckResolutionReset = function() {
|
||||
self.server_onlineResolutionCheckText("");
|
||||
self.server_onlineResolutionCheckOk(false);
|
||||
self.server_onlineResolutionCheckBroken(false);
|
||||
};
|
||||
|
||||
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
|
||||
self.testFolderConfigText = {};
|
||||
@@ -479,6 +488,27 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.testOnlineConnectivityResolutionConfigBusy = ko.observable(false);
|
||||
self.testOnlineConnectivityResolutionConfig = function() {
|
||||
if (!self.server_onlineCheck_name()) return;
|
||||
if (self.testOnlineConnectivityResolutionConfigBusy()) return;
|
||||
|
||||
self.testOnlineConnectivityResolutionConfigBusy(true);
|
||||
OctoPrint.util.testResolution(self.server_onlineCheck_name())
|
||||
.done(function(response) {
|
||||
if (!response.result) {
|
||||
self.server_onlineCheckResolutionText(gettext("Name cannot be resolved"));
|
||||
} else {
|
||||
self.server_onlineCheckResolutionText(gettext("Name can be resolved"));
|
||||
}
|
||||
self.server_onlineCheckResolutionOk(response.result);
|
||||
self.server_onlineCheckResolutionBroken(!response.result);
|
||||
})
|
||||
.always(function() {
|
||||
self.testOnlineConnectivityResolutionConfigBusy(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.testFolderConfigBusy = ko.observable(false);
|
||||
self.testFolderConfig = function(folder) {
|
||||
var observable = "folder_" + folder;
|
||||
@@ -520,6 +550,7 @@ $(function() {
|
||||
self.onSettingsHidden = function() {
|
||||
self.webcam_ffmpegPathReset();
|
||||
self.server_onlineCheckReset();
|
||||
self.server_onlineCheckResolutionReset();
|
||||
self.testFolderConfigReset();
|
||||
};
|
||||
|
||||
|
||||
@@ -15,5 +15,19 @@
|
||||
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckTest.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckTestConnectivity.jinja2" %}
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<p>{% trans %}
|
||||
If you also want to check if name resolution works (strongly recommended), define a host name
|
||||
to check name resolution against. If you don't know what to set here, the default value
|
||||
(OctoPrint's domain) should work. If you don't want to perform regular resolution checks along
|
||||
side with the general connectivity check, leave the field empty.
|
||||
{% endtrans %}</p>
|
||||
</div>
|
||||
|
||||
{% include "snippets/settings/server/serverOnlineCheckName.jinja2" %}
|
||||
{% include "snippets/settings/server/serverOnlineCheckTestResolution.jinja2" %}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<div class="control-group" title="{{ _('Hostname to try to resolve to check for internet connectivity')|edq }}" data-bind="css: {error: server_onlineCheckResolutionBroken, success: server_onlineCheckResolutionOk}">
|
||||
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Hostname') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-small" data-bind="value: server_onlineCheck_name" id="settings-serverOnlineCheckName">
|
||||
</div>
|
||||
</div>
|
||||
File renamed without changes.
+6
@@ -0,0 +1,6 @@
|
||||
<div class="control-group" title="{{ _('Test')|edq }}" data-bind="css: {error: server_onlineCheckResolutionBroken, success: server_onlineCheckResolutionOk}">
|
||||
<div class="controls">
|
||||
<button class="btn" data-bind="click: testOnlineConnectivityResolutionConfig, enable: server_onlineCheck_name() && !testOnlineConnectivityResolutionConfigBusy(), css: {disabled: !server_onlineCheck_name() || testOnlineConnectivityResolutionConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testOnlineConnectivityResolutionConfigBusy"></i> {{ _('Test name resolution') }}</button>
|
||||
<span class="help-block" data-bind="visible: server_onlineCheckResolutionBroken() || server_onlineCheckResolutionOk(), text: server_onlineCheckResolutionText"></span>
|
||||
</div>
|
||||
</div>
|
||||
+10
-186
@@ -36,6 +36,11 @@ except ImportError:
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring, unicode
|
||||
|
||||
|
||||
from octoprint.util.net import interface_addresses, address_for_client, server_reachable
|
||||
from octoprint.util.connectivity import ConnectivityChecker
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -1008,71 +1013,12 @@ class DefaultOrderedDict(collections.OrderedDict):
|
||||
class Object(object):
|
||||
pass
|
||||
|
||||
def interface_addresses(family=None):
|
||||
"""
|
||||
Retrieves all of the host's network interface addresses.
|
||||
"""
|
||||
|
||||
import netifaces
|
||||
if not family:
|
||||
family = netifaces.AF_INET
|
||||
|
||||
for interface in netifaces.interfaces():
|
||||
try:
|
||||
ifaddresses = netifaces.ifaddresses(interface)
|
||||
except Exception:
|
||||
continue
|
||||
if family in ifaddresses:
|
||||
for ifaddress in ifaddresses[family]:
|
||||
if not ifaddress["addr"].startswith("169.254."):
|
||||
yield ifaddress["addr"]
|
||||
|
||||
def address_for_client(host, port, timeout=3.05):
|
||||
"""
|
||||
Determines the address of the network interface on this host needed to connect to the indicated client host and port.
|
||||
"""
|
||||
|
||||
for address in interface_addresses():
|
||||
try:
|
||||
if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
|
||||
return address
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
|
||||
"""
|
||||
Checks if a server is reachable
|
||||
|
||||
Args:
|
||||
host (str): host to check against
|
||||
port (int): port to check against
|
||||
timeout (float): timeout for check
|
||||
proto (str): ``tcp`` or ``udp``
|
||||
source (str): optional, socket used for check will be bound against this address if provided
|
||||
|
||||
Returns:
|
||||
boolean: True if a connection to the server could be opened, False otherwise
|
||||
"""
|
||||
|
||||
import socket
|
||||
|
||||
if proto not in ("tcp", "udp"):
|
||||
raise ValueError("proto must be either 'tcp' or 'udp'")
|
||||
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
if source is not None:
|
||||
sock.bind((source, 0))
|
||||
sock.connect((host, port))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def guess_mime_type(data):
|
||||
import filetype
|
||||
return filetype.guess_mime(data)
|
||||
|
||||
|
||||
def parse_mime_type(mime):
|
||||
import cgi
|
||||
|
||||
@@ -1685,132 +1631,6 @@ class TypeAlreadyInQueue(Exception):
|
||||
self.type = t
|
||||
|
||||
|
||||
class ConnectivityChecker(object):
|
||||
"""
|
||||
Regularly checks for online connectivity.
|
||||
|
||||
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
|
||||
seconds and sets the ``online`` status accordingly.
|
||||
"""
|
||||
|
||||
def __init__(self, interval, host, port, enabled=True, on_change=None):
|
||||
self._interval = interval
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._enabled = enabled
|
||||
self._on_change = on_change
|
||||
|
||||
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
|
||||
|
||||
# we initialize the online flag to True if we are not enabled (we don't know any better
|
||||
# but these days it's probably a sane default)
|
||||
self._online = not self._enabled
|
||||
|
||||
self._check_worker = None
|
||||
self._check_mutex = threading.RLock()
|
||||
|
||||
self._run()
|
||||
|
||||
@property
|
||||
def online(self):
|
||||
"""Current online status, True if online, False if offline."""
|
||||
with self._check_mutex:
|
||||
return self._online
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
"""DNS host to query."""
|
||||
with self._check_mutex:
|
||||
return self._host
|
||||
|
||||
@host.setter
|
||||
def host(self, value):
|
||||
with self._check_mutex:
|
||||
self._host = value
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
"""DNS port to query."""
|
||||
with self._check_mutex:
|
||||
return self._port
|
||||
|
||||
@port.setter
|
||||
def port(self, value):
|
||||
with self._check_mutex:
|
||||
self._port = value
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
"""Interval between consecutive automatic checks."""
|
||||
return self._interval
|
||||
|
||||
@interval.setter
|
||||
def interval(self, value):
|
||||
self._interval = value
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
"""Whether the check is enabled or not."""
|
||||
return self._enabled
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value):
|
||||
with self._check_mutex:
|
||||
old_enabled = self._enabled
|
||||
self._enabled = value
|
||||
|
||||
if not self._enabled:
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
old_value = self._online
|
||||
self._online = True
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
elif self._enabled and not old_enabled:
|
||||
self._run()
|
||||
|
||||
def check_immediately(self):
|
||||
"""Check immediately and return result."""
|
||||
with self._check_mutex:
|
||||
self._perform_check()
|
||||
return self.online
|
||||
|
||||
def _run(self):
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
self._check_worker = RepeatedTimer(self._interval, self._perform_check,
|
||||
run_first=True)
|
||||
self._check_worker.start()
|
||||
|
||||
def _perform_check(self):
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
with self._check_mutex:
|
||||
self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port))
|
||||
|
||||
old_value = self._online
|
||||
self._online = server_reachable(self._host, port=self._port)
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
def _trigger_change(self, old_value, new_value):
|
||||
self._logger.info("Connectivity changed from {} to {}".format("online" if old_value else "offline",
|
||||
"online" if new_value else "offline"))
|
||||
if callable(self._on_change):
|
||||
self._on_change(old_value, new_value)
|
||||
|
||||
|
||||
class CaseInsensitiveSet(collections.Set):
|
||||
"""
|
||||
Basic case insensitive set
|
||||
@@ -1866,3 +1686,7 @@ def generate_api_key():
|
||||
import uuid
|
||||
|
||||
return ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
|
||||
|
||||
def map_boolean(value, true_text, false_text):
|
||||
return true_text if value else false_text
|
||||
@@ -0,0 +1,194 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from octoprint.util.net import server_reachable, resolve_host
|
||||
|
||||
class ConnectivityChecker(object):
|
||||
"""
|
||||
Regularly checks for online connectivity.
|
||||
|
||||
Tries to open a connection to the provided ``host`` and ``port`` every ``interval``
|
||||
seconds and sets the ``online`` status accordingly.
|
||||
|
||||
If a ``name``is provided, also tries to resolve that name to a valid IP address
|
||||
during connectivity check and only set ``online`` to ``True`` if that succeeds as well.
|
||||
"""
|
||||
|
||||
def __init__(self, interval, host, port, name=None, enabled=True, on_change=None):
|
||||
self._interval = interval
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._name = name
|
||||
self._enabled = enabled
|
||||
self._on_change = on_change
|
||||
|
||||
self._logger = logging.getLogger(__name__ + ".connectivity_checker")
|
||||
|
||||
# we initialize the online flag to True if we are not enabled (we don't know any better
|
||||
# but these days it's probably a sane default)
|
||||
self._connection_working = not self._enabled
|
||||
self._resolution_working = not self._enabled or self._name is None
|
||||
|
||||
self._check_worker = None
|
||||
self._check_mutex = threading.RLock()
|
||||
|
||||
self._run()
|
||||
|
||||
@property
|
||||
def online(self):
|
||||
"""Current online status, True if online, False if offline."""
|
||||
with self._check_mutex:
|
||||
return self._online
|
||||
|
||||
@property
|
||||
def _online(self):
|
||||
return self._connection_working and self._resolution_working
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
"""DNS host to query."""
|
||||
with self._check_mutex:
|
||||
return self._host
|
||||
|
||||
@host.setter
|
||||
def host(self, value):
|
||||
with self._check_mutex:
|
||||
self._host = value
|
||||
|
||||
@property
|
||||
def port(self):
|
||||
"""DNS port to query."""
|
||||
with self._check_mutex:
|
||||
return self._port
|
||||
|
||||
@port.setter
|
||||
def port(self, value):
|
||||
with self._check_mutex:
|
||||
self._port = value
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
with self._check_mutex:
|
||||
return self._name
|
||||
|
||||
@name.setter
|
||||
def name(self, value):
|
||||
with self._check_mutex:
|
||||
self._name = value
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
"""Interval between consecutive automatic checks."""
|
||||
return self._interval
|
||||
|
||||
@interval.setter
|
||||
def interval(self, value):
|
||||
self._interval = value
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
"""Whether the check is enabled or not."""
|
||||
return self._enabled
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value):
|
||||
with self._check_mutex:
|
||||
old_enabled = self._enabled
|
||||
self._enabled = value
|
||||
|
||||
if not self._enabled:
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
old_value = self._online
|
||||
self._connection_working = self._resolution_working = True
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
elif self._enabled and not old_enabled:
|
||||
self._run()
|
||||
|
||||
def check_immediately(self):
|
||||
"""Check immediately and return result."""
|
||||
with self._check_mutex:
|
||||
self._perform_check()
|
||||
return self.online
|
||||
|
||||
def log_full_report(self):
|
||||
from octoprint.util import map_boolean
|
||||
|
||||
with self._check_mutex:
|
||||
self._logger.info("Connectivity state is currently: {}".format(map_boolean(self.online, "online", "offline")))
|
||||
self.log_details()
|
||||
|
||||
def log_change_report(self, old_value, new_value, include_details=False):
|
||||
from octoprint.util import map_boolean
|
||||
|
||||
with self._check_mutex:
|
||||
self._logger.info("Connectivity changed from {} to {}".format(map_boolean(old_value, "online", "offline"),
|
||||
map_boolean(new_value, "online", "offline")))
|
||||
if include_details:
|
||||
self.log_details()
|
||||
|
||||
def log_details(self):
|
||||
from octoprint.util import map_boolean
|
||||
self._logger.info("Connecting to {}:{} is {}".format(self._host,
|
||||
self._port,
|
||||
map_boolean(self._connection_working,
|
||||
"working",
|
||||
"not working")))
|
||||
if self._name:
|
||||
self._logger.info("Resolving {} is {}".format(self._name,
|
||||
map_boolean(self._resolution_working,
|
||||
"working",
|
||||
"not working")))
|
||||
def _run(self):
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
if self._check_worker is not None:
|
||||
self._check_worker.cancel()
|
||||
|
||||
self._check_worker = RepeatedTimer(self._interval, self._perform_check,
|
||||
run_first=True)
|
||||
self._check_worker.start()
|
||||
|
||||
def _perform_check(self):
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
with self._check_mutex:
|
||||
self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port))
|
||||
|
||||
old_value = self._online
|
||||
self._connection_working = server_reachable(self._host, port=self._port)
|
||||
|
||||
if self._name:
|
||||
if self._connection_working:
|
||||
self._logger.debug("Checking if we can resolve {}...".format(self._name))
|
||||
self._resolution_working = len(resolve_host(self._name)) > 0
|
||||
else:
|
||||
self._resolution_working = False
|
||||
else:
|
||||
self._resolution_working = True
|
||||
|
||||
if old_value != self._online:
|
||||
self._trigger_change(old_value, self._online)
|
||||
|
||||
def _trigger_change(self, old_value, new_value):
|
||||
self.log_change_report(old_value, new_value, include_details=not new_value)
|
||||
if callable(self._on_change):
|
||||
self._on_change(old_value,
|
||||
new_value,
|
||||
connection_working=self._connection_working,
|
||||
resolution_working=self._resolution_working)
|
||||
@@ -9,6 +9,7 @@ import sys
|
||||
import netaddr
|
||||
import netifaces
|
||||
import logging
|
||||
import threading
|
||||
|
||||
_cached_check_v6 = None
|
||||
def check_v6():
|
||||
@@ -117,3 +118,76 @@ def unmap_v4_as_v6(address):
|
||||
# ipv6 mapped ipv4 address, unmap
|
||||
address = address[len("::ffff:"):]
|
||||
return address
|
||||
|
||||
|
||||
def interface_addresses(family=None):
|
||||
"""
|
||||
Retrieves all of the host's network interface addresses.
|
||||
"""
|
||||
|
||||
import netifaces
|
||||
if not family:
|
||||
family = netifaces.AF_INET
|
||||
|
||||
for interface in netifaces.interfaces():
|
||||
try:
|
||||
ifaddresses = netifaces.ifaddresses(interface)
|
||||
except Exception:
|
||||
continue
|
||||
if family in ifaddresses:
|
||||
for ifaddress in ifaddresses[family]:
|
||||
if not ifaddress["addr"].startswith("169.254."):
|
||||
yield ifaddress["addr"]
|
||||
|
||||
|
||||
def address_for_client(host, port, timeout=3.05):
|
||||
"""
|
||||
Determines the address of the network interface on this host needed to connect to the indicated client host and port.
|
||||
"""
|
||||
|
||||
for address in interface_addresses():
|
||||
try:
|
||||
if server_reachable(host, port, timeout=timeout, proto="udp", source=address):
|
||||
return address
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
|
||||
"""
|
||||
Checks if a server is reachable
|
||||
|
||||
Args:
|
||||
host (str): host to check against
|
||||
port (int): port to check against
|
||||
timeout (float): timeout for check
|
||||
proto (str): ``tcp`` or ``udp``
|
||||
source (str): optional, socket used for check will be bound against this address if provided
|
||||
|
||||
Returns:
|
||||
boolean: True if a connection to the server could be opened, False otherwise
|
||||
"""
|
||||
|
||||
import socket
|
||||
|
||||
if proto not in ("tcp", "udp"):
|
||||
raise ValueError("proto must be either 'tcp' or 'udp'")
|
||||
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
if source is not None:
|
||||
sock.bind((source, 0))
|
||||
sock.connect((host, port))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def resolve_host(host):
|
||||
import socket
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
try:
|
||||
return [to_unicode(x[4][0]) for x in socket.getaddrinfo(host, 80)]
|
||||
except Exception:
|
||||
return []
|
||||
Reference in new issue
Block a user