Added isAvailable for more services

This commit is contained in:
Adolfo Gómez García 2022-01-18 13:21:44 +01:00
parent 0208c9b3f9
commit 7fc51ce513
10 changed files with 47 additions and 33 deletions

View File

@ -39,7 +39,7 @@ from django.utils.translation import gettext_noop as _
from uds.core.util import os_detector as OsDetector from uds.core.util import os_detector as OsDetector
from uds.core import Module from uds.core import Module
from uds.core.transports import protocols from uds.core.transports import protocols
from uds.core.util import connection from uds.core.util import net
# Not imported at runtime, just for type checking # Not imported at runtime, just for type checking
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
@ -116,14 +116,14 @@ class Transport(Module):
userService: 'models.UserService', userService: 'models.UserService',
ip: str, ip: str,
port: typing.Union[str, int], port: typing.Union[str, int],
timeout: int = 4, timeout: float = 4,
) -> bool: ) -> bool:
proxy: typing.Optional[ proxy: typing.Optional[
'models.Proxy' 'models.Proxy'
] = userService.deployed_service.service.proxy ] = userService.deployed_service.service.proxy
if proxy: if proxy:
return proxy.doTestServer(ip, port, timeout) return proxy.doTestServer(ip, port, timeout)
return connection.testServer(ip, str(port), timeout) return net.testConnection(ip, str(port), timeout)
def isAvailableFor(self, userService: 'models.UserService', ip: str) -> bool: def isAvailableFor(self, userService: 'models.UserService', ip: str) -> bool:
""" """

View File

@ -36,17 +36,5 @@ import socket
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# import Alias
def testServer(host: str, port: typing.Union[int, str], timeOut: float = 4) -> bool: from .net import testConnection as testServer
try:
logger.debug(
'Checking connection to %s:%s with %s seconds timeout', host, port, timeOut
)
sock = socket.create_connection((host, int(port)), timeOut)
sock.close()
except Exception as e:
logger.debug(
'Exception checking %s:%s with %s timeout: %s', host, port, timeOut, e
)
return False
return True

View File

@ -88,19 +88,19 @@ if not _libfuse_path:
def Reg32GetValue(rootkey, keyname, valname): def Reg32GetValue(rootkey, keyname, valname):
key, val = None, None key, val = None, None
try: try:
key = reg.OpenKey( key = reg.OpenKey( # type: ignore
rootkey, keyname, 0, reg.KEY_READ | reg.KEY_WOW64_32KEY rootkey, keyname, 0, reg.KEY_READ | reg.KEY_WOW64_32KEY # type: ignore
) )
val = str(reg.QueryValueEx(key, valname)[0]) val = str(reg.QueryValueEx(key, valname)[0]) # type: ignore
except WindowsError: # type: ignore except WindowsError: # type: ignore
pass pass
finally: finally:
if key is not None: if key is not None:
reg.CloseKey(key) reg.CloseKey(key) # type: ignore
return val return val
_libfuse_path = Reg32GetValue( _libfuse_path = Reg32GetValue(
reg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WinFsp", r"InstallDir" reg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WinFsp", r"InstallDir" # type: ignore
) )
if _libfuse_path: if _libfuse_path:
_libfuse_path += r"bin\winfsp-%s.dll" % ( _libfuse_path += r"bin\winfsp-%s.dll" % (
@ -713,7 +713,7 @@ class FuseOperations(ctypes.Structure):
def time_of_timespec(ts: c_timespec, use_ns=False): def time_of_timespec(ts: c_timespec, use_ns=False):
return ts.tv_sec * 10 ** 9 + ts.tv_nsec return ts.tv_sec * 10 ** 9 + ts.tv_nsec # type: ignore
def set_st_attrs(st: c_stat, attrs: typing.Mapping[str, int]) -> None: def set_st_attrs(st: c_stat, attrs: typing.Mapping[str, int]) -> None:

View File

@ -31,6 +31,7 @@
@author: Adolfo Gómez, dkmaster at dkmon dot com @author: Adolfo Gómez, dkmaster at dkmon dot com
""" """
import re import re
import socket
import logging import logging
import typing import typing
@ -231,3 +232,18 @@ def isValidFQDN(value: str) -> bool:
def isValidHost(value: str): def isValidHost(value: str):
return isValidIp(value) or isValidFQDN(value) return isValidIp(value) or isValidFQDN(value)
def testConnection(host: str, port: typing.Union[int, str], timeOut: float = 4) -> bool:
try:
logger.debug(
'Checking connection to %s:%s with %s seconds timeout', host, port, timeOut
)
sock = socket.create_connection((host, int(port)), timeOut)
sock.close()
except Exception as e:
logger.debug(
'Exception checking %s:%s with %s timeout: %s', host, port, timeOut, e
)
return False
return True

View File

@ -38,7 +38,7 @@ from django.db import models
from uds.core.environment import Environment from uds.core.environment import Environment
from uds.core.util import log from uds.core.util import log
from uds.core.util import unique from uds.core.util import unique
from uds.core.util import connection from uds.core.util import net
from .managed_object_model import ManagedObjectModel from .managed_object_model import ManagedObjectModel
from .tag import TaggingMixin from .tag import TaggingMixin
@ -188,11 +188,11 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
return self.provider.isInMaintenance() if self.provider else True return self.provider.isInMaintenance() if self.provider else True
def testServer( def testServer(
self, host: str, port: typing.Union[str, int], timeout: int = 4 self, host: str, port: typing.Union[str, int], timeout: float = 4
) -> bool: ) -> bool:
if self.proxy: if self.proxy:
return self.proxy.doTestServer(host, port, timeout) return self.proxy.doTestServer(host, port, timeout)
return connection.testServer(host, port, timeout) return net.testConnection(host, port, timeout)
def __str__(self) -> str: def __str__(self) -> str:
return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id) return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id)

View File

@ -675,7 +675,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
return 100 * cachedValue // maxs return 100 * cachedValue // maxs
def testServer(self, host, port, timeout=4) -> bool: def testServer(self, host: str, port: typing.Union[str, int], timeout: float=4) -> bool:
return self.service.testServer(host, port, timeout) return self.service.testServer(host, port, timeout)
# parent accessors # parent accessors

View File

@ -33,14 +33,14 @@ import logging
import typing import typing
from django.utils.translation import gettext_noop as _ from django.utils.translation import gettext_noop as _
from uds.core import services from uds.core import services
from uds.core.ui import gui from uds.core.ui import gui
from uds.core.util import validators from uds.core.util import validators
from uds.core.util.cache import Cache
from .service import OVirtLinkedService from uds.core.util.decorators import allowCache
from . import client from . import client
from .service import OVirtLinkedService
# Not imported at runtime, just for type checking # Not imported at runtime, just for type checking
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
@ -508,6 +508,13 @@ class OVirtProvider(
) -> typing.Optional[typing.MutableMapping[str, typing.Any]]: ) -> typing.Optional[typing.MutableMapping[str, typing.Any]]:
return self.__getApi().getConsoleConnection(machineId) return self.__getApi().getConsoleConnection(machineId)
@allowCache('reachable', Cache.SHORT_VALIDITY)
def isAvailable(self) -> bool:
"""
Check if aws provider is reachable
"""
return self.testConnection()
@staticmethod @staticmethod
def test(env: 'Environment', data: 'Module.ValuesType') -> typing.List[typing.Any]: def test(env: 'Environment', data: 'Module.ValuesType') -> typing.List[typing.Any]:
""" """

View File

@ -466,3 +466,6 @@ class OVirtLinkedService(Service): # pylint: disable=too-many-public-methods
self, machineId: str self, machineId: str
) -> typing.Optional[typing.MutableMapping[str, typing.Any]]: ) -> typing.Optional[typing.MutableMapping[str, typing.Any]]:
return self.parent().getConsoleConnection(machineId) return self.parent().getConsoleConnection(machineId)
def isAvailable(self) -> bool:
return self.parent().isAvailable()

View File

@ -40,8 +40,6 @@ from django.db import transaction
from uds.models import getSqlDatetimeAsUnix from uds.models import getSqlDatetimeAsUnix
from uds.core.ui import gui from uds.core.ui import gui
from uds.core.util import log from uds.core.util import log
from uds.core.util import connection
from uds.core.util import config
from uds.core.util import net from uds.core.util import net
from uds.core.services import types as serviceTypes from uds.core.services import types as serviceTypes
@ -271,7 +269,7 @@ class IPMachinesService(IPServiceBase):
self._port > 0 and not wolENABLED self._port > 0 and not wolENABLED
): # If configured WOL, check is a nonsense ): # If configured WOL, check is a nonsense
if ( if (
connection.testServer(theIP, self._port, timeOut=0.5) net.testConnection(theIP, self._port, timeOut=0.5)
is False is False
): ):
# Log into logs of provider, so it can be "shown" on services logs # Log into logs of provider, so it can be "shown" on services logs

View File

@ -36,6 +36,8 @@ from uds.core import services
from uds.core.ui import gui from uds.core.ui import gui
from uds.core.util import validators from uds.core.util import validators
from uds.core.util.unique_id_generator import UniqueIDGenerator from uds.core.util.unique_id_generator import UniqueIDGenerator
from uds.core.util.cache import Cache
from uds.core.util.decorators import allowCache
from .service import ProxmoxLinkedService from .service import ProxmoxLinkedService