mirror of
https://github.com/dkmstr/openuds.git
synced 2025-01-11 05:17:55 +03:00
Refactoring and fixes found in the process
This commit is contained in:
parent
92f83ebe52
commit
6814796ba5
@ -190,7 +190,7 @@ class ActorV3Action(Handler):
|
||||
def notifyService(self, action: NotifyActionType) -> None:
|
||||
try:
|
||||
# If unmanaged, use Service locator
|
||||
service: 'services.Service' = Service.objects.get(token=self._params['token']).getInstance()
|
||||
service: 'services.Service' = Service.objects.get(token=self._params['token']).get_instance()
|
||||
|
||||
# We have a valid service, now we can make notifications
|
||||
|
||||
@ -495,7 +495,7 @@ class BaseReadyChange(ActorV3Action):
|
||||
userService = self.getUserService()
|
||||
# Stores known IP and notifies it to deployment
|
||||
userService.logIP(self._params['ip'])
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
userServiceInstance.setIp(self._params['ip'])
|
||||
userService.updateData(userServiceInstance)
|
||||
|
||||
@ -768,7 +768,7 @@ class Unmanaged(ActorV3Action):
|
||||
|
||||
try:
|
||||
dbService: Service = Service.objects.get(token=self._params['token'])
|
||||
service: 'services.Service' = dbService.getInstance()
|
||||
service: 'services.Service' = dbService.get_instance()
|
||||
except Exception:
|
||||
return ActorV3Action.actorResult(error='Invalid token')
|
||||
|
||||
|
@ -154,7 +154,7 @@ class Authenticators(ModelHandler):
|
||||
|
||||
def item_as_dict(self, item: 'Model') -> dict[str, typing.Any]:
|
||||
item = ensure.is_instance(item, Authenticator)
|
||||
type_ = item.getType()
|
||||
type_ = item.get_type()
|
||||
return {
|
||||
'numeric_id': item.id,
|
||||
'id': item.uuid,
|
||||
@ -168,7 +168,7 @@ class Authenticators(ModelHandler):
|
||||
'mfa_id': item.mfa.uuid if item.mfa else '',
|
||||
'small_name': item.small_name,
|
||||
'users_count': item.users.count(),
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'type_info': self.typeInfo(type_),
|
||||
'permission': permissions.getEffectivePermission(self._user, item),
|
||||
@ -199,7 +199,7 @@ class Authenticators(ModelHandler):
|
||||
|
||||
limit = int(self._params.get('limit', '50'))
|
||||
|
||||
auth = item.getInstance()
|
||||
auth = item.get_instance()
|
||||
|
||||
canDoSearch = (
|
||||
type_ == 'user'
|
||||
|
@ -231,7 +231,7 @@ class Auths(Handler):
|
||||
paramAll: bool = self._params.get('all', 'false').lower() == 'true'
|
||||
auth: Authenticator
|
||||
for auth in Authenticator.objects.all():
|
||||
theType = auth.getType()
|
||||
theType = auth.get_type()
|
||||
if paramAll or (theType.isCustom() is False and theType.typeType not in ('IP',)):
|
||||
yield {
|
||||
'authId': auth.uuid, # Deprecated, use 'auth_id'
|
||||
|
@ -105,7 +105,7 @@ class MFA(ModelHandler):
|
||||
|
||||
def item_as_dict(self, item: 'Model') -> dict[str, typing.Any]:
|
||||
item = ensure.is_instance(item, models.MFA)
|
||||
type_ = item.getType()
|
||||
type_ = item.get_type()
|
||||
return {
|
||||
'id': item.uuid,
|
||||
'name': item.name,
|
||||
@ -113,7 +113,7 @@ class MFA(ModelHandler):
|
||||
'validity': item.validity,
|
||||
'tags': [tag.tag for tag in item.tags.all()],
|
||||
'comments': item.comments,
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'permission': permissions.getEffectivePermission(self._user, item),
|
||||
}
|
||||
|
@ -114,7 +114,7 @@ class Notifiers(ModelHandler):
|
||||
|
||||
def item_as_dict(self, item: 'Model') -> dict[str, typing.Any]:
|
||||
item = ensure.is_instance(item, Notifier)
|
||||
type_ = item.getType()
|
||||
type_ = item.get_type()
|
||||
return {
|
||||
'id': item.uuid,
|
||||
'name': item.name,
|
||||
@ -122,7 +122,7 @@ class Notifiers(ModelHandler):
|
||||
'enabled': item.enabled,
|
||||
'tags': [tag.tag for tag in item.tags.all()],
|
||||
'comments': item.comments,
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'permission': permissions.getEffectivePermission(self._user, item),
|
||||
}
|
||||
|
@ -65,13 +65,13 @@ class OsManagers(ModelHandler):
|
||||
]
|
||||
|
||||
def osmToDict(self, osm: OSManager) -> dict[str, typing.Any]:
|
||||
type_ = osm.getType()
|
||||
type_ = osm.get_type()
|
||||
return {
|
||||
'id': osm.uuid,
|
||||
'name': osm.name,
|
||||
'tags': [tag.tag for tag in osm.tags.all()],
|
||||
'deployed_count': osm.deployedServices.count(),
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'servicesTypes': [type_.servicesType], # A list for backward compatibility. TODO: To be removed when admin interface is changed
|
||||
'comments': osm.comments,
|
||||
|
@ -83,13 +83,13 @@ class Providers(ModelHandler):
|
||||
table_row_style = {'field': 'maintenance_mode', 'prefix': 'row-maintenance-'}
|
||||
|
||||
def item_as_dict(self, item: 'Provider') -> dict[str, typing.Any]:
|
||||
type_ = item.getType()
|
||||
type_ = item.get_type()
|
||||
|
||||
# Icon can have a lot of data (1-2 Kbytes), but it's not expected to have a lot of services providers, and even so, this will work fine
|
||||
offers = [
|
||||
{
|
||||
'name': gettext(t.name()),
|
||||
'type': t.getType(),
|
||||
'type': t.get_type(),
|
||||
'description': gettext(t.description()),
|
||||
'icon': t.icon64().replace('\n', ''),
|
||||
}
|
||||
@ -106,7 +106,7 @@ class Providers(ModelHandler):
|
||||
.count(),
|
||||
'maintenance_mode': item.maintenance_mode,
|
||||
'offers': offers,
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'comments': item.comments,
|
||||
'permission': permissions.getEffectivePermission(self._user, item),
|
||||
|
@ -327,7 +327,7 @@ class ServersGroups(ModelHandler):
|
||||
{'tags': {'title': _('tags'), 'visible': False}},
|
||||
]
|
||||
|
||||
def getTypes(self, *args, **kwargs) -> typing.Generator[dict[str, typing.Any], None, None]:
|
||||
def get_types(self, *args, **kwargs) -> typing.Generator[dict[str, typing.Any], None, None]:
|
||||
for i in types.servers.ServerSubtype.manager().enum():
|
||||
v = types.rest.TypeInfo(
|
||||
name=i.description, type=f'{i.type.name}@{i.subtype}', description='', icon=i.icon
|
||||
|
@ -68,7 +68,7 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
|
||||
|
||||
@staticmethod
|
||||
def serviceInfo(item: models.Service) -> dict[str, typing.Any]:
|
||||
info = item.getType()
|
||||
info = item.get_type()
|
||||
|
||||
return {
|
||||
'icon': info.icon64().replace('\n', ''),
|
||||
@ -95,7 +95,7 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
|
||||
:param item: Service item (db)
|
||||
:param full: If full is requested, add "extra" fields to complete information
|
||||
"""
|
||||
itemType = item.getType()
|
||||
itemType = item.get_type()
|
||||
retVal = {
|
||||
'id': item.uuid,
|
||||
'name': item.name,
|
||||
@ -180,14 +180,14 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
|
||||
[models.Tag.objects.get_or_create(tag=val)[0] for val in tags]
|
||||
)
|
||||
|
||||
serviceInstance = service.getInstance(self._params)
|
||||
serviceInstance = service.get_instance(self._params)
|
||||
|
||||
# Store token if this service provides one
|
||||
service.token = serviceInstance.getToken() or None # If '', use "None" to
|
||||
|
||||
service.data = (
|
||||
serviceInstance.serialize()
|
||||
) # This may launch an validation exception (the getInstance(...) part)
|
||||
) # This may launch an validation exception (the get_instance(...) part)
|
||||
|
||||
service.save()
|
||||
except models.Service.DoesNotExist:
|
||||
@ -255,29 +255,29 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
|
||||
{'tags': {'title': _('tags'), 'visible': False}},
|
||||
]
|
||||
|
||||
def getTypes(
|
||||
def get_types(
|
||||
self, parent: 'Model', forType: typing.Optional[str]
|
||||
) -> collections.abc.Iterable[dict[str, typing.Any]]:
|
||||
parent = ensure.is_instance(parent, models.Provider)
|
||||
logger.debug('getTypes parameters: %s, %s', parent, forType)
|
||||
logger.debug('get_types parameters: %s, %s', parent, forType)
|
||||
offers: list[dict[str, typing.Any]] = []
|
||||
if forType is None:
|
||||
offers = [
|
||||
{
|
||||
'name': _(t.name()),
|
||||
'type': t.getType(),
|
||||
'type': t.get_type(),
|
||||
'description': _(t.description()),
|
||||
'icon': t.icon64().replace('\n', ''),
|
||||
}
|
||||
for t in parent.getType().getProvidedServices()
|
||||
for t in parent.get_type().getProvidedServices()
|
||||
]
|
||||
else:
|
||||
for t in parent.getType().getProvidedServices():
|
||||
if forType == t.getType():
|
||||
for t in parent.get_type().getProvidedServices():
|
||||
if forType == t.get_type():
|
||||
offers = [
|
||||
{
|
||||
'name': _(t.name()),
|
||||
'type': t.getType(),
|
||||
'type': t.get_type(),
|
||||
'description': _(t.description()),
|
||||
'icon': t.icon64().replace('\n', ''),
|
||||
}
|
||||
@ -292,7 +292,7 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
|
||||
parent = ensure.is_instance(parent, models.Provider)
|
||||
try:
|
||||
logger.debug('getGui parameters: %s, %s', parent, forType)
|
||||
parentInstance = parent.getInstance()
|
||||
parentInstance = parent.get_instance()
|
||||
serviceType = parentInstance.getServiceByType(forType)
|
||||
if not serviceType:
|
||||
raise self.invalidItemException(f'Gui for {forType} not found')
|
||||
|
@ -491,7 +491,7 @@ class ServicesPools(ModelHandler):
|
||||
raise RequestError(gettext('Base service does not exist anymore')) from None
|
||||
|
||||
try:
|
||||
serviceType = service.getType()
|
||||
serviceType = service.get_type()
|
||||
|
||||
if serviceType.publicationType is None:
|
||||
self._params['publish_on_save'] = False
|
||||
@ -626,7 +626,7 @@ class ServicesPools(ModelHandler):
|
||||
def actionsList(self, item: 'Model') -> typing.Any:
|
||||
item = ensure.is_instance(item, ServicePool)
|
||||
validActions: tuple[dict, ...] = ()
|
||||
itemInfo = item.service.getType() # type: ignore
|
||||
itemInfo = item.service.get_type() # type: ignore
|
||||
if itemInfo.usesCache is True:
|
||||
validActions += (
|
||||
CALENDAR_ACTION_INITIAL,
|
||||
@ -659,7 +659,7 @@ class ServicesPools(ModelHandler):
|
||||
|
||||
def listAssignables(self, item: 'Model') -> typing.Any:
|
||||
item = ensure.is_instance(item, ServicePool)
|
||||
service = item.service.getInstance() # type: ignore
|
||||
service = item.service.get_instance() # type: ignore
|
||||
return [gui.choiceItem(i[0], i[1]) for i in service.listAssignables()]
|
||||
|
||||
def createFromAssignable(self, item: 'Model') -> typing.Any:
|
||||
|
@ -123,7 +123,7 @@ class Transports(ModelHandler):
|
||||
for x in ServicePool.objects.filter(service__isnull=False)
|
||||
.order_by('name')
|
||||
.prefetch_related('service')
|
||||
if transportType.protocol in x.service.getType().allowedProtocols
|
||||
if transportType.protocol in x.service.get_type().allowedProtocols
|
||||
],
|
||||
'label': gettext('Service Pools'),
|
||||
'tooltip': gettext('Currently assigned services pools'),
|
||||
@ -149,7 +149,7 @@ class Transports(ModelHandler):
|
||||
|
||||
def item_as_dict(self, item: 'Model') -> dict[str, typing.Any]:
|
||||
item = ensure.is_instance(item, Transport)
|
||||
type_ = item.getType()
|
||||
type_ = item.get_type()
|
||||
pools = list(item.deployedServices.all().values_list('uuid', flat=True))
|
||||
return {
|
||||
'id': item.uuid,
|
||||
@ -164,7 +164,7 @@ class Transports(ModelHandler):
|
||||
'pools': pools,
|
||||
'pools_count': len(pools),
|
||||
'deployed_count': item.deployedServices.count(),
|
||||
'type': type_.getType(),
|
||||
'type': type_.get_type(),
|
||||
'type_name': type_.name(),
|
||||
'protocol': type_.protocol,
|
||||
'permission': permissions.getEffectivePermission(self._user, item),
|
||||
|
@ -385,9 +385,9 @@ class Transports(DetailHandler):
|
||||
|
||||
def getItems(self, parent: 'Model', item: typing.Optional[str]):
|
||||
parent = ensure.is_instance(parent, models.ServicePool)
|
||||
def getType(trans):
|
||||
def get_type(trans: 'models.Transport'):
|
||||
try:
|
||||
return self.typeAsDict(trans.getType())
|
||||
return self.typeAsDict(trans.get_type())
|
||||
except Exception: # No type found
|
||||
return None
|
||||
|
||||
@ -395,13 +395,13 @@ class Transports(DetailHandler):
|
||||
{
|
||||
'id': i.uuid,
|
||||
'name': i.name,
|
||||
'type': getType(i),
|
||||
'type': get_type(i),
|
||||
'comments': i.comments,
|
||||
'priority': i.priority,
|
||||
'trans_type': _(i.getType().name()),
|
||||
'trans_type': _(i.get_type().name()),
|
||||
}
|
||||
for i in parent.transports.all()
|
||||
if getType(i)
|
||||
if get_type(i)
|
||||
]
|
||||
|
||||
def getTitle(self, parent: 'Model') -> str:
|
||||
@ -511,7 +511,7 @@ class Publications(DetailHandler):
|
||||
'revision': i.revision,
|
||||
'publish_date': i.publish_date,
|
||||
'state': i.state,
|
||||
'reason': State.isErrored(i.state) and i.getInstance().reasonOfError() or '',
|
||||
'reason': State.isErrored(i.state) and i.get_intance().reasonOfError() or '',
|
||||
'state_date': i.state_date,
|
||||
}
|
||||
for i in parent.publications.all()
|
||||
|
@ -223,7 +223,7 @@ class Users(DetailHandler):
|
||||
user = None
|
||||
try:
|
||||
with transaction.atomic():
|
||||
auth = parent.getInstance()
|
||||
auth = parent.get_instance()
|
||||
if item is None: # Create new
|
||||
auth.createUser(
|
||||
fields
|
||||
@ -394,7 +394,7 @@ class Groups(DetailHandler):
|
||||
},
|
||||
]
|
||||
|
||||
def getTypes(self, parent: 'Model', forType: typing.Optional[str]):
|
||||
def get_types(self, parent: 'Model', forType: typing.Optional[str]):
|
||||
parent = ensure.is_instance(parent, Authenticator)
|
||||
tDct = {
|
||||
'group': {'name': _('Group'), 'description': _('UDS Group')},
|
||||
@ -433,7 +433,7 @@ class Groups(DetailHandler):
|
||||
raise RequestError(_('Group name is required'))
|
||||
fields = self.readFieldsFromParams(valid_fields)
|
||||
is_pattern = fields.get('name', '').find('pat:') == 0
|
||||
auth = parent.getInstance()
|
||||
auth = parent.get_instance()
|
||||
if not item: # Create new
|
||||
if not is_meta and not is_pattern:
|
||||
auth.createGroup(
|
||||
|
@ -284,7 +284,7 @@ class BaseModelHandler(Handler):
|
||||
"""
|
||||
res = types.rest.TypeInfo(
|
||||
name=_(type_.name()),
|
||||
type=type_.getType(),
|
||||
type=type_.get_type(),
|
||||
description=_(type_.description()),
|
||||
icon=type_.icon64().replace('\n', ''),
|
||||
).as_dict(**self.typeInfo(type_))
|
||||
@ -345,7 +345,7 @@ class BaseModelHandler(Handler):
|
||||
:param res: Dictionary to "extend" with instance key-values pairs
|
||||
"""
|
||||
if isinstance(item, ManagedObjectModel):
|
||||
i = item.getInstance()
|
||||
i = item.get_instance()
|
||||
i.initGui() # Defaults & stuff
|
||||
res.update(i.valuesDict())
|
||||
return res
|
||||
@ -495,7 +495,7 @@ class DetailHandler(BaseModelHandler):
|
||||
# gui = self.getGui(parent, None)
|
||||
# return sorted(gui, key=lambda f: f['gui']['order'])
|
||||
if self._args[0] == TYPES:
|
||||
types_ = self.getTypes(parent, None)
|
||||
types_ = self.get_types(parent, None)
|
||||
logger.debug('Types: %s', types_)
|
||||
return types_
|
||||
if self._args[0] == GUI:
|
||||
@ -517,7 +517,7 @@ class DetailHandler(BaseModelHandler):
|
||||
gui = self.getGui(parent, self._args[1])
|
||||
return sorted(gui, key=lambda f: f['gui']['order'])
|
||||
if self._args[0] == TYPES:
|
||||
types_ = self.getTypes(parent, self._args[1])
|
||||
types_ = self.get_types(parent, self._args[1])
|
||||
logger.debug('Types: %s', types_)
|
||||
return types_
|
||||
if self._args[1] == LOG:
|
||||
@ -665,7 +665,7 @@ class DetailHandler(BaseModelHandler):
|
||||
# raise RequestError('Gui not provided for this type of object')
|
||||
return []
|
||||
|
||||
def getTypes(
|
||||
def get_types(
|
||||
self, parent: models.Model, forType: typing.Optional[str]
|
||||
) -> collections.abc.Iterable[dict[str, typing.Any]]:
|
||||
"""
|
||||
@ -766,13 +766,13 @@ class ModelHandler(BaseModelHandler):
|
||||
"""
|
||||
return []
|
||||
|
||||
def getTypes(self, *args, **kwargs) -> typing.Generator[dict[str, typing.Any], None, None]:
|
||||
def get_types(self, *args, **kwargs) -> typing.Generator[dict[str, typing.Any], None, None]:
|
||||
for type_ in self.enum_types():
|
||||
yield self.typeAsDict(type_)
|
||||
|
||||
def getType(self, type_: str) -> dict[str, typing.Any]:
|
||||
def get_type(self, type_: str) -> dict[str, typing.Any]:
|
||||
found = None
|
||||
for v in self.getTypes():
|
||||
for v in self.get_types():
|
||||
if v['type'] == type_:
|
||||
found = v
|
||||
break
|
||||
@ -1005,7 +1005,7 @@ class ModelHandler(BaseModelHandler):
|
||||
if self._args[0] == OVERVIEW:
|
||||
return list(self.getItems())
|
||||
if self._args[0] == TYPES:
|
||||
return list(self.getTypes())
|
||||
return list(self.get_types())
|
||||
if self._args[0] == TABLEINFO:
|
||||
return self.processTableFields(
|
||||
self.table_title,
|
||||
@ -1037,7 +1037,7 @@ class ModelHandler(BaseModelHandler):
|
||||
elif self._args[0] == TYPES:
|
||||
if nArgs != 2:
|
||||
raise self.invalidRequestException()
|
||||
return self.getType(self._args[1])
|
||||
return self.get_type(self._args[1])
|
||||
elif self._args[0] == GUI:
|
||||
if nArgs != 2:
|
||||
raise self.invalidRequestException()
|
||||
@ -1139,7 +1139,7 @@ class ModelHandler(BaseModelHandler):
|
||||
data_type: typing.Optional[str] = self._params.get('data_type', self._params.get('type'))
|
||||
if data_type:
|
||||
item.data_type = data_type
|
||||
item.data = item.getInstance(self._params).serialize()
|
||||
item.data = item.get_instance(self._params).serialize()
|
||||
|
||||
item.save()
|
||||
|
||||
|
@ -305,7 +305,7 @@ def authenticate(
|
||||
return AuthResult(user=getRootUser())
|
||||
|
||||
gm = auths.GroupsManager(authenticator)
|
||||
authInstance = authenticator.getInstance()
|
||||
authInstance = authenticator.get_instance()
|
||||
if useInternalAuthenticate is False:
|
||||
res = authInstance.authenticate(username, password, gm, request)
|
||||
else:
|
||||
@ -356,7 +356,7 @@ def authenticateViaCallback(
|
||||
the groups of this user so your getGroups will work correctly.
|
||||
"""
|
||||
gm = auths.GroupsManager(authenticator)
|
||||
authInstance = authenticator.getInstance()
|
||||
authInstance = authenticator.get_instance()
|
||||
|
||||
# If there is no callback for this authenticator...
|
||||
if authInstance.authCallback is auths.Authenticator.authCallback:
|
||||
@ -487,7 +487,7 @@ def webLogout(
|
||||
exit_url = exit_url or exit_page
|
||||
try:
|
||||
if request.user:
|
||||
authenticator = request.user.manager.getInstance()
|
||||
authenticator = request.user.manager.get_instance()
|
||||
username = request.user.name
|
||||
logout = authenticator.logout(request, username)
|
||||
if logout and logout.success == types.auth.AuthenticationState.REDIRECT:
|
||||
|
@ -170,7 +170,7 @@ class Scheduler:
|
||||
job.last_execution = now
|
||||
job.save(update_fields=['state', 'owner_server', 'last_execution'])
|
||||
|
||||
jobInstance = job.getInstance()
|
||||
jobInstance = job.get_intance()
|
||||
|
||||
if jobInstance is None:
|
||||
logger.error('Job instance can\'t be resolved for %s, removing it', job)
|
||||
|
@ -115,7 +115,7 @@ class PublicationLauncher(DelayedTask):
|
||||
return
|
||||
servicePoolPub.state = State.PREPARING
|
||||
servicePoolPub.save()
|
||||
pi = servicePoolPub.getInstance()
|
||||
pi = servicePoolPub.get_intance()
|
||||
state = pi.publish()
|
||||
servicePool: ServicePool = servicePoolPub.deployed_service
|
||||
servicePool.current_pub_revision += 1
|
||||
@ -182,7 +182,7 @@ class PublicationFinishChecker(DelayedTask):
|
||||
doPublicationCleanup = (
|
||||
True
|
||||
if osm is None
|
||||
else not osm.getInstance().isPersistent()
|
||||
else not osm.get_instance().isPersistent()
|
||||
)
|
||||
|
||||
if doPublicationCleanup:
|
||||
@ -246,7 +246,7 @@ class PublicationFinishChecker(DelayedTask):
|
||||
if publication.state != self._state:
|
||||
logger.debug('Task overrided by another task (state of item changed)')
|
||||
else:
|
||||
publicationInstance = publication.getInstance()
|
||||
publicationInstance = publication.get_intance()
|
||||
logger.debug(
|
||||
"publication instance class: %s", publicationInstance.__class__
|
||||
)
|
||||
@ -360,7 +360,7 @@ class PublicationManager(metaclass=singleton.Singleton):
|
||||
return publication
|
||||
|
||||
try:
|
||||
pubInstance = publication.getInstance()
|
||||
pubInstance = publication.get_intance()
|
||||
state = pubInstance.cancel()
|
||||
publication.setState(State.CANCELING)
|
||||
PublicationFinishChecker.checkAndUpdateState(
|
||||
@ -387,7 +387,7 @@ class PublicationManager(metaclass=singleton.Singleton):
|
||||
_('Can\'t unpublish publications with services in process')
|
||||
)
|
||||
try:
|
||||
pubInstance = servicePoolPub.getInstance()
|
||||
pubInstance = servicePoolPub.get_intance()
|
||||
state = pubInstance.destroy()
|
||||
servicePoolPub.setState(State.REMOVING)
|
||||
PublicationFinishChecker.checkAndUpdateState(
|
||||
|
@ -108,7 +108,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
"""
|
||||
Checks if the maximum number of user services for this service has been reached
|
||||
"""
|
||||
serviceInstance = service.getInstance()
|
||||
serviceInstance = service.get_instance()
|
||||
# Early return, so no database count is needed
|
||||
if serviceInstance.maxUserServices == consts.UNLIMITED:
|
||||
return False
|
||||
@ -185,7 +185,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
publication,
|
||||
)
|
||||
cache = self._createCacheAtDb(publication, cacheLevel)
|
||||
ci = cache.getInstance()
|
||||
ci = cache.get_instance()
|
||||
state = ci.deployForCache(cacheLevel)
|
||||
|
||||
UserServiceOpChecker.checkAndUpdateState(cache, ci, state)
|
||||
@ -203,7 +203,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
)
|
||||
raise ServiceNotReadyError()
|
||||
|
||||
if servicePool.service.getType().publicationType is not None:
|
||||
if servicePool.service.get_type().publicationType is not None:
|
||||
publication = servicePool.activePublication()
|
||||
if publication:
|
||||
assigned = self._createAssignedAtDb(publication, user)
|
||||
@ -225,7 +225,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
)
|
||||
assigned = self._createAssignedAtDbForNoPublication(servicePool, user)
|
||||
|
||||
assignedInstance = assigned.getInstance()
|
||||
assignedInstance = assigned.get_instance()
|
||||
state = assignedInstance.deployForUser(user)
|
||||
|
||||
UserServiceOpChecker.makeUnique(assigned, assignedInstance, state)
|
||||
@ -236,11 +236,11 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
"""
|
||||
Creates an assigned service from an "assignable" id
|
||||
"""
|
||||
serviceInstance = servicePool.service.getInstance()
|
||||
serviceInstance = servicePool.service.get_instance()
|
||||
if not serviceInstance.canAssign():
|
||||
raise Exception('This service type cannot assign asignables')
|
||||
|
||||
if servicePool.service.getType().publicationType is not None:
|
||||
if servicePool.service.get_type().publicationType is not None:
|
||||
publication = servicePool.activePublication()
|
||||
if publication:
|
||||
assigned = self._createAssignedAtDb(publication, user)
|
||||
@ -265,7 +265,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
assigned = self._createAssignedAtDbForNoPublication(servicePool, user)
|
||||
|
||||
# Now, get from serviceInstance the data
|
||||
assignedInstance = assigned.getInstance()
|
||||
assignedInstance = assigned.get_instance()
|
||||
state = serviceInstance.assignFromAssignables(assignableId, user, assignedInstance)
|
||||
# assigned.updateData(assignedInstance)
|
||||
|
||||
@ -280,7 +280,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
"""
|
||||
cache.refresh_from_db()
|
||||
logger.debug('Moving cache %s to level %s', cache, cacheLevel)
|
||||
cacheInstance = cache.getInstance()
|
||||
cacheInstance = cache.get_instance()
|
||||
state = cacheInstance.moveToCache(cacheLevel)
|
||||
cache.cache_level = cacheLevel
|
||||
cache.save(update_fields=['cache_level'])
|
||||
@ -308,7 +308,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
return self.remove(userService)
|
||||
|
||||
operationsLogger.info('Canceling userService %s', userService.name)
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
|
||||
if (
|
||||
not userServiceInstance.supportsCancel()
|
||||
@ -341,7 +341,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
userService.setInUse(False) # For accounting, ensure that it is not in use right now
|
||||
userService.save()
|
||||
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
state = userServiceInstance.destroy()
|
||||
|
||||
# Data will be serialized on makeUnique process
|
||||
@ -374,7 +374,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
def getAssignationForUser(
|
||||
self, servicePool: ServicePool, user: User
|
||||
) -> typing.Optional[UserService]: # pylint: disable=too-many-branches
|
||||
if servicePool.service.getInstance().spawnsNew is False:
|
||||
if servicePool.service.get_instance().spawnsNew is False:
|
||||
assignedUserService = self.getExistingAssignationForUser(servicePool, user)
|
||||
else:
|
||||
assignedUserService = None
|
||||
@ -503,7 +503,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
return cache
|
||||
|
||||
# Can't assign directly from L2 cache... so we check if we can create e new service in the limits requested
|
||||
serviceType = servicePool.service.getType()
|
||||
serviceType = servicePool.service.get_type()
|
||||
if serviceType.usesCache:
|
||||
inAssigned = (
|
||||
servicePool.assignedUserServices().filter(self.getStateFilter(servicePool.service)).count()
|
||||
@ -537,7 +537,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
serviceIsntance is just a helper, so if we already have deserialized deployedService
|
||||
"""
|
||||
removing = self.getUserServicesInStatesForProvider(servicePool.service.provider, [State.REMOVING])
|
||||
serviceInstance = servicePool.service.getInstance()
|
||||
serviceInstance = servicePool.service.get_instance()
|
||||
if (
|
||||
serviceInstance.isAvailable()
|
||||
and removing >= serviceInstance.parent().getMaxRemovingServices()
|
||||
@ -553,7 +553,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
preparingForProvider = self.getUserServicesInStatesForProvider(
|
||||
servicePool.service.provider, [State.PREPARING]
|
||||
)
|
||||
serviceInstance = servicePool.service.getInstance()
|
||||
serviceInstance = servicePool.service.get_instance()
|
||||
if self.maximumUserServicesDeployed(servicePool.service) or (
|
||||
preparingForProvider >= serviceInstance.parent().getMaxPreparingServices()
|
||||
and serviceInstance.parent().getIgnoreLimits() is False
|
||||
@ -570,7 +570,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
return False
|
||||
|
||||
logger.debug('Service %s is usable, checking it via setReady', userService)
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
try:
|
||||
state = userServiceInstance.setReady()
|
||||
except Exception as e:
|
||||
@ -591,12 +591,12 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
def reset(self, userService: UserService) -> None:
|
||||
userService.refresh_from_db()
|
||||
|
||||
if not userService.deployed_service.service.getType().canReset:
|
||||
if not userService.deployed_service.service.get_type().canReset:
|
||||
return
|
||||
|
||||
operationsLogger.info('Reseting %s', userService)
|
||||
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
try:
|
||||
userServiceInstance.reset()
|
||||
except Exception:
|
||||
@ -632,7 +632,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
"""
|
||||
osManager = userService.deployed_service.osmanager
|
||||
# If os manager says "machine is persistent", do not try to delete "previous version" assigned machines
|
||||
doPublicationCleanup = True if not osManager else not osManager.getInstance().isPersistent()
|
||||
doPublicationCleanup = True if not osManager else not osManager.get_instance().isPersistent()
|
||||
|
||||
if doPublicationCleanup:
|
||||
remove = False
|
||||
@ -655,7 +655,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
|
||||
def notifyReadyFromOsManager(self, userService: UserService, data: typing.Any) -> None:
|
||||
try:
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
logger.debug('Notifying user service ready state')
|
||||
state = userServiceInstance.notifyReadyFromOsManager(data)
|
||||
logger.debug('State: %s', state)
|
||||
@ -750,12 +750,12 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
if not idTransport: # Find a suitable transport
|
||||
t: Transport
|
||||
for t in userService.deployed_service.transports.order_by('priority'):
|
||||
typeTrans = t.getType()
|
||||
typeTrans = t.get_type()
|
||||
if (
|
||||
typeTrans
|
||||
and t.isValidForIp(srcIp)
|
||||
and t.is_ip_allowed(srcIp)
|
||||
and typeTrans.supportsOs(os.os)
|
||||
and t.isValidForOs(os.os)
|
||||
and t.is_os_allowed(os.os)
|
||||
):
|
||||
idTransport = t.uuid
|
||||
break
|
||||
@ -770,7 +770,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
raise InvalidServiceException()
|
||||
|
||||
# If transport is not available for the request IP...
|
||||
if not transport.isValidForIp(srcIp):
|
||||
if not transport.is_ip_allowed(srcIp):
|
||||
msg = _('The requested transport {} is not valid for {}').format(transport.name, srcIp)
|
||||
logger.error(msg)
|
||||
raise InvalidServiceException(msg)
|
||||
@ -793,7 +793,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
log.LogSource.WEB,
|
||||
)
|
||||
# If ready, show transport for this service, if also ready ofc
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
ip = userServiceInstance.getIp()
|
||||
userService.logIP(ip) # Update known ip
|
||||
logger.debug('IP: %s', ip)
|
||||
@ -818,7 +818,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
)
|
||||
if ip:
|
||||
serviceNotReadyCode = 0x0003
|
||||
transportInstance = transport.getInstance()
|
||||
transportInstance = transport.get_instance()
|
||||
if transportInstance.isAvailableFor(userService, ip):
|
||||
log.doLog(userService, log.LogLevel.INFO, "User service ready", log.LogSource.WEB)
|
||||
self.notifyPreconnect(
|
||||
@ -964,13 +964,13 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
else:
|
||||
q = pool.transports.filter(uuid=idTransport)
|
||||
for t in q.order_by('priority'):
|
||||
typeTrans = t.getType()
|
||||
typeTrans = t.get_type()
|
||||
if (
|
||||
typeTrans
|
||||
and t.getType()
|
||||
and t.isValidForIp(srcIp)
|
||||
and t.get_type()
|
||||
and t.is_ip_allowed(srcIp)
|
||||
and typeTrans.supportsOs(os.os)
|
||||
and t.isValidForOs(os.os)
|
||||
and t.is_os_allowed(os.os)
|
||||
):
|
||||
found = (pool, t)
|
||||
break
|
||||
@ -991,7 +991,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
if meta.ha_policy == types.pools.HighAvailabilityPolicy.ENABLED:
|
||||
# Check that servide is accessible
|
||||
if (
|
||||
not alreadyAssigned.deployed_service.service.getInstance().isAvailable()
|
||||
not alreadyAssigned.deployed_service.service.get_instance().isAvailable()
|
||||
): # Not available, mark for removal
|
||||
alreadyAssigned.release()
|
||||
raise Exception() # And process a new access
|
||||
@ -1015,7 +1015,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
|
||||
for pool in pools: # Pools are already sorted, and "full" pools are filtered out
|
||||
if meta.ha_policy == types.pools.HighAvailabilityPolicy.ENABLED:
|
||||
# If not available, skip it
|
||||
if pool.service.getInstance().isAvailable() is False:
|
||||
if pool.service.get_instance().isAvailable() is False:
|
||||
continue
|
||||
|
||||
# Ensure transport is available for the OS
|
||||
|
@ -124,7 +124,7 @@ def notifyPreconnect(userService: 'UserService', info: types.connections.Connect
|
||||
Notifies a preconnect to an user service
|
||||
"""
|
||||
src = userService.getConnectionSource()
|
||||
if userService.deployed_service.service.getInstance().notifyPreconnect(userService, info) is True:
|
||||
if userService.deployed_service.service.get_instance().notifyPreconnect(userService, info) is True:
|
||||
return # Ok, service handled it
|
||||
|
||||
_requestActor(
|
||||
|
@ -59,7 +59,7 @@ class StateUpdater:
|
||||
):
|
||||
self.userService = userService
|
||||
self.userServiceInstance = (
|
||||
userServiceInstance if userServiceInstance is not None else userService.getInstance()
|
||||
userServiceInstance if userServiceInstance is not None else userService.get_instance()
|
||||
)
|
||||
|
||||
def setError(self, msg: typing.Optional[str] = None):
|
||||
@ -278,7 +278,7 @@ class UserServiceOpChecker(DelayedTask):
|
||||
logger.debug('Task overrided by another task (state of item changed)')
|
||||
# This item is no longer valid, returning will not check it again (no checkLater called)
|
||||
return
|
||||
ci = uService.getInstance()
|
||||
ci = uService.get_instance()
|
||||
logger.debug("uService instance class: %s", ci.__class__)
|
||||
state = ci.checkState()
|
||||
UserServiceOpChecker.checkAndUpdateState(uService, ci, state)
|
||||
|
@ -70,7 +70,7 @@ class MessageProcessorThread(BaseThread):
|
||||
or time.time() - self._cached_stamp > CACHE_TIMEOUT
|
||||
):
|
||||
self._cached_providers = [
|
||||
(p.level, p.getInstance()) for p in Notifier.objects.filter(enabled=True)
|
||||
(p.level, p.get_instance()) for p in Notifier.objects.filter(enabled=True)
|
||||
]
|
||||
self._cached_stamp = time.time()
|
||||
return self._cached_providers
|
||||
|
@ -144,7 +144,7 @@ class Module(UserInterface, Environmentable, Serializable):
|
||||
return _(cls.typeName)
|
||||
|
||||
@classmethod
|
||||
def getType(cls: type['Module']) -> str:
|
||||
def get_type(cls: type['Module']) -> str:
|
||||
"""
|
||||
Returns typeType
|
||||
|
||||
|
@ -237,7 +237,7 @@ class OSManager(Module):
|
||||
uniqueId = userService.unique_id
|
||||
userService.setInUse(True)
|
||||
userService.properties['last_username'] = userName or 'unknown' # Store it for convenience
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
userServiceInstance.userLoggedIn(userName or 'unknown')
|
||||
userService.updateData(userServiceInstance)
|
||||
|
||||
@ -301,7 +301,7 @@ class OSManager(Module):
|
||||
|
||||
uniqueId = userService.unique_id
|
||||
userService.setInUse(False)
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
userServiceInstance.userLoggedOut(userName or 'unknown')
|
||||
userService.updateData(userServiceInstance)
|
||||
|
||||
|
@ -144,7 +144,7 @@ class ServiceProvider(module.Module):
|
||||
the typeType that Service has.
|
||||
"""
|
||||
for _type in cls.offers:
|
||||
if _type.getType() == typeName:
|
||||
if _type.get_type() == typeName:
|
||||
return _type
|
||||
return None
|
||||
|
||||
|
@ -61,7 +61,7 @@ class ServiceProviderFactory(factory.ModuleFactory[ServiceProvider]):
|
||||
# We will check that if service provided by "provider" needs
|
||||
# cache, but service do not provides publicationType,
|
||||
# that service will not be registered and it will be informed
|
||||
typeName = type_.getType().lower()
|
||||
typeName = type_.get_type().lower()
|
||||
|
||||
if typeName in self.providers():
|
||||
logger.debug('%s already registered as Service Provider', type_)
|
||||
|
@ -49,7 +49,7 @@ class Attribute:
|
||||
self._type = theType
|
||||
self.setValue(value)
|
||||
|
||||
def getType(self) -> typing.Type:
|
||||
def get_type(self) -> typing.Type:
|
||||
return self._type
|
||||
|
||||
def getValue(self) -> typing.Any:
|
||||
@ -131,7 +131,7 @@ class AutoAttributes(Serializable):
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
'AutoAttributes('
|
||||
+ ', '.join(f'{k}={v.getType().__name__}' for k, v in self.attrs.items())
|
||||
+ ', '.join(f'{k}={v.get_type().__name__}' for k, v in self.attrs.items())
|
||||
+ ')'
|
||||
)
|
||||
|
||||
@ -139,7 +139,7 @@ class AutoAttributes(Serializable):
|
||||
return (
|
||||
'<AutoAttribute '
|
||||
+ ','.join(
|
||||
f'{k} ({v.getType()}) = {v.getStrValue()}'
|
||||
f'{k} ({v.get_type()}) = {v.getStrValue()}'
|
||||
for k, v in self.attrs.items()
|
||||
)
|
||||
+ '>'
|
||||
|
@ -232,7 +232,7 @@ class Config:
|
||||
def isLongText(self) -> bool:
|
||||
return self._longText
|
||||
|
||||
def getType(self) -> int:
|
||||
def get_type(self) -> int:
|
||||
return self._type
|
||||
|
||||
def getParams(self) -> typing.Any:
|
||||
@ -356,7 +356,7 @@ class Config:
|
||||
if cfg.isCrypted() is True and addCrypt is False:
|
||||
continue
|
||||
|
||||
if cfg.getType() == Config.FieldType.PASSWORD and addCrypt is False:
|
||||
if cfg.get_type() == Config.FieldType.PASSWORD and addCrypt is False:
|
||||
continue
|
||||
|
||||
# add section if it do not exists
|
||||
@ -366,7 +366,7 @@ class Config:
|
||||
'value': cfg.get(),
|
||||
'crypt': cfg.isCrypted(),
|
||||
'longText': cfg.isLongText(),
|
||||
'type': cfg.getType(),
|
||||
'type': cfg.get_type(),
|
||||
'params': cfg.getParams(),
|
||||
'help': cfg.getHelp(),
|
||||
}
|
||||
|
@ -65,4 +65,4 @@ class ModuleFactory(Factory[T]):
|
||||
Inserts an object into the factory.
|
||||
'''
|
||||
# logger.debug('Adding %s as %s', type_.type(), type_.__module__)
|
||||
super().put(type_.getType().lower(), type_)
|
||||
super().put(type_.get_type().lower(), type_)
|
||||
|
@ -153,14 +153,14 @@ class PropertiesMixin:
|
||||
return PropertyAccessor(owner_id=owner_id, owner_type=owner_type)
|
||||
|
||||
@staticmethod
|
||||
def _deleteSignal(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
toDelete: 'PropertiesMixin' = kwargs['instance']
|
||||
def _pre_delete_signal(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
to_delete: 'PropertiesMixin' = kwargs['instance']
|
||||
# We are deleting the object, so we delete the properties too
|
||||
# Remember that properties is a generic table, does not have any cascade delete
|
||||
toDelete.properties.clear()
|
||||
to_delete.properties.clear()
|
||||
|
||||
@staticmethod
|
||||
def setupSignals(model: 'type[models.Model]') -> None:
|
||||
def setup_signals(model: 'type[models.Model]') -> None:
|
||||
"""Connects a pre deletion signal to delete properties
|
||||
Note that this method must be added to every class creation that inherits from PropertiesMixin
|
||||
Or the properties will not be deleted on deletion of the object
|
||||
@ -168,4 +168,4 @@ class PropertiesMixin:
|
||||
Args:
|
||||
model (type[models.Model]): Model to connect the signal to
|
||||
"""
|
||||
signals.pre_delete.connect(PropertiesMixin._deleteSignal, sender=model)
|
||||
signals.pre_delete.connect(PropertiesMixin._pre_delete_signal, sender=model)
|
||||
|
@ -77,7 +77,7 @@ class AssignedAndUnused(Job):
|
||||
)
|
||||
# If do not needs os manager, this is
|
||||
if ds.osmanager:
|
||||
osm = ds.osmanager.getInstance()
|
||||
osm = ds.osmanager.get_instance()
|
||||
if osm.processUnusedMachines:
|
||||
logger.debug(
|
||||
'Processing unused services for %s, %s', ds, ds.osmanager
|
||||
|
@ -92,7 +92,7 @@ class ServiceCacheUpdater(Job):
|
||||
for servicePool in servicePoolsNeedingCaching:
|
||||
servicePool.userServices.update() # Cleans cached queries
|
||||
# If this deployedService don't have a publication active and needs it, ignore it
|
||||
spServiceInstance = servicePool.service.getInstance() # type: ignore
|
||||
spServiceInstance = servicePool.service.get_instance() # type: ignore
|
||||
|
||||
if spServiceInstance.usesCache is False:
|
||||
logger.debug(
|
||||
|
@ -55,7 +55,7 @@ def getSerializedFromManagedObject(
|
||||
removableFields: typing.Optional[list[str]] = None,
|
||||
) -> collections.abc.Mapping[str, typing.Any]:
|
||||
try:
|
||||
obj = mod.getInstance()
|
||||
obj = mod.get_instance()
|
||||
gui = {i['name']: i['gui']['type'] for i in obj.guiDescription()}
|
||||
values = obj.valuesDict()
|
||||
# Remove password fields
|
||||
|
@ -87,7 +87,7 @@ class Authenticator(ManagedObjectModel, TaggingMixin):
|
||||
ordering = ('name',)
|
||||
app_label = 'uds'
|
||||
|
||||
def getInstance(self, values=None) -> auths.Authenticator:
|
||||
def get_instance(self, values=None) -> auths.Authenticator:
|
||||
"""
|
||||
Instantiates the object this record contains.
|
||||
|
||||
@ -105,13 +105,13 @@ class Authenticator(ManagedObjectModel, TaggingMixin):
|
||||
if self.id is None:
|
||||
return auths.Authenticator(environment.Environment.getTempEnv(), values, uuid=self.uuid)
|
||||
|
||||
auType = self.getType()
|
||||
env = self.getEnvironment()
|
||||
auType = self.get_type()
|
||||
env = self.get_environment()
|
||||
auth = auType(env, values, uuid=self.uuid)
|
||||
self.deserialize(auth, values)
|
||||
return auth
|
||||
|
||||
def getType(self) -> type[auths.Authenticator]:
|
||||
def get_type(self) -> type[auths.Authenticator]:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -268,7 +268,7 @@ class Authenticator(ManagedObjectModel, TaggingMixin):
|
||||
authsList = Authenticator.objects.all().order_by('priority', 'name')
|
||||
|
||||
for auth in authsList:
|
||||
if auth.getType() and (not auth.getType().isCustom() or tag != 'disabled'):
|
||||
if auth.get_type() and (not auth.get_type().isCustom() or tag != 'disabled'):
|
||||
yield auth
|
||||
|
||||
@staticmethod
|
||||
@ -284,13 +284,13 @@ class Authenticator(ManagedObjectModel, TaggingMixin):
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from uds.core.util.permissions import clean
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
toDelete: 'Authenticator' = kwargs['instance']
|
||||
|
||||
logger.debug('Before delete auth %s', toDelete)
|
||||
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data != '':
|
||||
s = toDelete.getInstance()
|
||||
s = toDelete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
|
||||
|
@ -98,7 +98,7 @@ class Group(UUIDModel):
|
||||
|
||||
:note: The returned value is an instance of the authenticator class used to manage this user, not a db record.
|
||||
"""
|
||||
return self.manager.getInstance()
|
||||
return self.manager.get_instance()
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.is_meta:
|
||||
@ -107,7 +107,7 @@ class Group(UUIDModel):
|
||||
return f'Group {self.name}(id:{self.id}) from auth {self.manager.name}'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -115,17 +115,17 @@ class Group(UUIDModel):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete = kwargs['instance']
|
||||
to_delete: 'Group' = kwargs['instance']
|
||||
# Todelete is a group
|
||||
|
||||
# We invoke removeGroup. If this raises an exception, group will not
|
||||
# be removed
|
||||
toDelete.getManager().removeGroup(toDelete.name)
|
||||
to_delete.getManager().removeGroup(to_delete.name)
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
logger.debug('Deleted group %s', toDelete)
|
||||
logger.debug('Deleted group %s', to_delete)
|
||||
|
||||
|
||||
models.signals.pre_delete.connect(Group.beforeDelete, sender=Group)
|
||||
models.signals.pre_delete.connect(Group.pre_delete, sender=Group)
|
||||
|
@ -65,7 +65,7 @@ class ManagedObjectModel(UUIDModel):
|
||||
|
||||
abstract = True
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents
|
||||
"""
|
||||
@ -82,9 +82,9 @@ class ManagedObjectModel(UUIDModel):
|
||||
if not values and self.data:
|
||||
obj.deserialize(self.data)
|
||||
|
||||
self._cachedInstance = None # Ensures returns correct value on getInstance
|
||||
self._cachedInstance = None # Ensures returns correct value on get_instance
|
||||
|
||||
def getInstance(
|
||||
def get_instance(
|
||||
self, values: typing.Optional[dict[str, str]] = None
|
||||
) -> Module:
|
||||
"""
|
||||
@ -104,9 +104,9 @@ class ManagedObjectModel(UUIDModel):
|
||||
if self._cachedInstance and values is None:
|
||||
return self._cachedInstance
|
||||
|
||||
klass = self.getType()
|
||||
klass = self.get_type()
|
||||
|
||||
env = self.getEnvironment()
|
||||
env = self.get_environment()
|
||||
obj = klass(env, values)
|
||||
self.deserialize(obj, values)
|
||||
|
||||
@ -114,16 +114,16 @@ class ManagedObjectModel(UUIDModel):
|
||||
|
||||
return obj
|
||||
|
||||
def getType(self) -> type[Module]:
|
||||
def get_type(self) -> type[Module]:
|
||||
"""
|
||||
Returns the type of self (as python type)
|
||||
Must be overriden!!!
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
f'getType has not been implemented for {self.__class__.__name__}'
|
||||
f'get_type has not been implemented for {self.__class__.__name__}'
|
||||
)
|
||||
|
||||
def isOfType(self, type_: str) -> bool:
|
||||
def is_type(self, type_: str) -> bool:
|
||||
"""
|
||||
return True if self if of the requested type, else returns False
|
||||
"""
|
||||
|
@ -261,7 +261,7 @@ class MetaPool(UUIDModel, TaggingMixin): # type: ignore
|
||||
return meta
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs): # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs): # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -272,7 +272,7 @@ class MetaPool(UUIDModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
toDelete: 'MetaPool' = kwargs['instance']
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
@ -285,7 +285,7 @@ class MetaPool(UUIDModel, TaggingMixin): # type: ignore
|
||||
|
||||
|
||||
# Connects a pre deletion signal
|
||||
signals.pre_delete.connect(MetaPool.beforeDelete, sender=MetaPool)
|
||||
signals.pre_delete.connect(MetaPool.pre_delete, sender=MetaPool)
|
||||
|
||||
|
||||
class MetaPoolMember(UUIDModel):
|
||||
|
@ -61,12 +61,12 @@ class MFA(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
# objects: 'models.BaseManager[MFA]'
|
||||
authenticators: 'models.manager.RelatedManager[Authenticator]'
|
||||
|
||||
def getInstance(
|
||||
def get_instance(
|
||||
self, values: typing.Optional[dict[str, str]] = None
|
||||
) -> 'mfas.MFA':
|
||||
return typing.cast('mfas.MFA', super().getInstance(values=values))
|
||||
return typing.cast('mfas.MFA', super().get_instance(values=values))
|
||||
|
||||
def getType(self) -> type['mfas.MFA']:
|
||||
def get_type(self) -> type['mfas.MFA']:
|
||||
"""Get the type of the object this record represents.
|
||||
|
||||
The type is a Python type, it obtains this MFA and associated record field.
|
||||
@ -86,7 +86,7 @@ class MFA(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
return f'MFA {self.name} of type {self.data_type} (id:{self.id})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -95,22 +95,22 @@ class MFA(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete: 'MFA' = kwargs['instance']
|
||||
to_delete: 'MFA' = kwargs['instance']
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data:
|
||||
if to_delete.data:
|
||||
try:
|
||||
s = toDelete.getInstance()
|
||||
s = to_delete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
'Error processing deletion of notifier %s: %s (forced deletion)',
|
||||
toDelete.name,
|
||||
to_delete.name,
|
||||
e,
|
||||
)
|
||||
|
||||
logger.debug('Before delete mfa provider %s', toDelete)
|
||||
logger.debug('Before delete mfa provider %s', to_delete)
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to OS Manager
|
||||
models.signals.pre_delete.connect(MFA.beforeDelete, sender=MFA)
|
||||
models.signals.pre_delete.connect(MFA.pre_delete, sender=MFA)
|
||||
|
@ -211,10 +211,10 @@ class Network(UUIDModel, TaggingMixin): # type: ignore
|
||||
return f'Network {self.name} ({self.net_string}) from {self.str_net_start} to {self.str_net_end} ({self.version})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
toDelete: 'Network' = kwargs['instance']
|
||||
|
||||
logger.debug('Before delete auth %s', toDelete)
|
||||
|
||||
@ -223,4 +223,4 @@ class Network(UUIDModel, TaggingMixin): # type: ignore
|
||||
|
||||
|
||||
# Connects a pre deletion signal to Authenticator
|
||||
models.signals.pre_delete.connect(Network.beforeDelete, sender=Network)
|
||||
models.signals.pre_delete.connect(Network.pre_delete, sender=Network)
|
||||
|
@ -101,7 +101,7 @@ class Notifier(ManagedObjectModel, TaggingMixin):
|
||||
db_table = 'uds_notify_prov'
|
||||
app_label = 'uds'
|
||||
|
||||
def getType(self) -> type['NotificationProviderModule']:
|
||||
def get_type(self) -> type['NotificationProviderModule']:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -117,15 +117,15 @@ class Notifier(ManagedObjectModel, TaggingMixin):
|
||||
raise Exception(f'Notifier type not found: {self.data_type}')
|
||||
return kind
|
||||
|
||||
def getInstance(
|
||||
def get_instance(
|
||||
self, values: typing.Optional[dict[str, str]] = None
|
||||
) -> 'NotificationProviderModule':
|
||||
return typing.cast(
|
||||
'NotificationProviderModule', super().getInstance(values=values)
|
||||
'NotificationProviderModule', super().get_instance(values=values)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -134,22 +134,22 @@ class Notifier(ManagedObjectModel, TaggingMixin):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete: 'Notifier' = kwargs['instance']
|
||||
to_delete: 'Notifier' = kwargs['instance']
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data:
|
||||
if to_delete.data:
|
||||
try:
|
||||
s = toDelete.getInstance()
|
||||
s = to_delete.get_instance()
|
||||
s.destroy() # Invokes the destruction of "related own data"
|
||||
s.env.clearRelatedData() # Clears related data, such as storage, cache, etc...
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
'Error processing deletion of notifier %s: %s (forced deletion)',
|
||||
toDelete.name,
|
||||
to_delete.name,
|
||||
e,
|
||||
)
|
||||
|
||||
logger.debug('Before delete notification provider %s', toDelete)
|
||||
logger.debug('Before delete notification provider %s', to_delete)
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to OS Manager
|
||||
models.signals.pre_delete.connect(Notifier.beforeDelete, sender=Notifier)
|
||||
models.signals.pre_delete.connect(Notifier.pre_delete, sender=Notifier)
|
||||
|
@ -64,12 +64,12 @@ class OSManager(ManagedObjectModel, TaggingMixin):
|
||||
ordering = ('name',)
|
||||
app_label = 'uds'
|
||||
|
||||
def getInstance(
|
||||
def get_instance(
|
||||
self, values: typing.Optional[dict[str, str]] = None
|
||||
) -> 'osmanagers.OSManager':
|
||||
return typing.cast('osmanagers.OSManager', super().getInstance(values=values))
|
||||
return typing.cast('osmanagers.OSManager', super().get_instance(values=values))
|
||||
|
||||
def getType(self) -> type['osmanagers.OSManager']:
|
||||
def get_type(self) -> type['osmanagers.OSManager']:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -105,7 +105,7 @@ class OSManager(ManagedObjectModel, TaggingMixin):
|
||||
return f'{self.name} of type {self.data_type} (id:{self.id})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -114,19 +114,19 @@ class OSManager(ManagedObjectModel, TaggingMixin):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete = kwargs['instance']
|
||||
if toDelete.deployedServices.count() > 0:
|
||||
to_delete: 'OSManager' = kwargs['instance']
|
||||
if to_delete.deployedServices.count() > 0:
|
||||
raise IntegrityError(
|
||||
'Can\'t remove os managers with assigned deployed services'
|
||||
)
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data != '':
|
||||
s = toDelete.getInstance()
|
||||
if to_delete.data != '':
|
||||
s = to_delete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
|
||||
logger.debug('Before delete os manager %s', toDelete)
|
||||
logger.debug('Before delete os manager %s', to_delete)
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to OS Manager
|
||||
models.signals.pre_delete.connect(OSManager.beforeDelete, sender=OSManager)
|
||||
models.signals.pre_delete.connect(OSManager.pre_delete, sender=OSManager)
|
||||
|
@ -68,7 +68,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
ordering = ('name',)
|
||||
app_label = 'uds'
|
||||
|
||||
def getType(self) -> type['ServiceProvider']:
|
||||
def get_type(self) -> type['ServiceProvider']:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -81,11 +81,11 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
|
||||
return services.factory().lookup(self.data_type) or services.ServiceProvider
|
||||
|
||||
def getInstance(
|
||||
def get_instance(
|
||||
self, values: typing.Optional[dict[str, str]] = None
|
||||
) -> 'ServiceProvider':
|
||||
prov: 'ServiceProvider' = typing.cast(
|
||||
'ServiceProvider', super().getInstance(values=values)
|
||||
'ServiceProvider', super().get_instance(values=values)
|
||||
)
|
||||
# Set uuid
|
||||
prov.setUuid(self.uuid)
|
||||
@ -103,7 +103,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
return f'Provider {self.name} of type {self.data_type} (id:{self.id})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Provider class "Destroy" before deleting it from database.
|
||||
|
||||
@ -114,21 +114,21 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
logger.debug('Before delete service provider %s', toDelete)
|
||||
to_delete: 'Provider' = kwargs['instance']
|
||||
logger.debug('Before delete service provider %s', to_delete)
|
||||
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data != '':
|
||||
s = toDelete.getInstance()
|
||||
if to_delete.data != '':
|
||||
s = to_delete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
# Clears related permissions
|
||||
clean(toDelete)
|
||||
clean(to_delete)
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to Provider
|
||||
signals.pre_delete.connect(Provider.beforeDelete, sender=Provider)
|
||||
signals.pre_delete.connect(Provider.pre_delete, sender=Provider)
|
||||
|
@ -83,13 +83,13 @@ class Scheduler(models.Model):
|
||||
|
||||
app_label = 'uds'
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents
|
||||
"""
|
||||
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore # pylint: disable=no-member
|
||||
|
||||
def getInstance(self) -> typing.Optional[jobs.Job]:
|
||||
def get_intance(self) -> typing.Optional[jobs.Job]:
|
||||
"""
|
||||
Returns an instance of the class that this record of the Scheduler represents. This clas is derived
|
||||
of uds.core.jobs.Job.Job
|
||||
@ -97,22 +97,22 @@ class Scheduler(models.Model):
|
||||
jobInstance = jobs.factory().lookup(self.name)
|
||||
|
||||
if jobInstance:
|
||||
return jobInstance(self.getEnvironment())
|
||||
return jobInstance(self.get_environment())
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to remove environment for sheduled task
|
||||
"""
|
||||
toDelete = kwargs['instance']
|
||||
toDelete: 'Scheduler' = kwargs['instance']
|
||||
logger.debug('Deleting sheduled task %s', toDelete)
|
||||
toDelete.getEnvironment().clearRelatedData()
|
||||
toDelete.get_environment().clearRelatedData()
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f'Scheduled task {self.name}, every {self.frecuency}, last execution at {self.last_execution}, state = {self.state}'
|
||||
|
||||
|
||||
# Connects a pre deletion signal to Scheduler
|
||||
models.signals.pre_delete.connect(Scheduler.beforeDelete, sender=Scheduler)
|
||||
models.signals.pre_delete.connect(Scheduler.pre_delete, sender=Scheduler)
|
||||
|
@ -397,5 +397,5 @@ class Server(UUIDModel, TaggingMixin, properties.PropertiesMixin):
|
||||
return f'<RegisterdServer {self.token} of type {self.server_type.name} created on {self.stamp} by {self.username} from {self.ip}/{self.hostname}>'
|
||||
|
||||
|
||||
properties.PropertiesMixin.setupSignals(Server)
|
||||
properties.PropertiesMixin.setupSignals(ServerGroup)
|
||||
properties.PropertiesMixin.setup_signals(Server)
|
||||
properties.PropertiesMixin.setup_signals(ServerGroup)
|
||||
|
@ -99,7 +99,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
app_label = 'uds'
|
||||
constraints = [models.UniqueConstraint(fields=['provider', 'name'], name='u_srv_provider_name')]
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents
|
||||
"""
|
||||
@ -113,7 +113,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
},
|
||||
)
|
||||
|
||||
def getInstance(self, values: typing.Optional[dict[str, str]] = None) -> 'services.Service':
|
||||
def get_instance(self, values: typing.Optional[dict[str, str]] = None) -> 'services.Service':
|
||||
"""
|
||||
Instantiates the object this record contains.
|
||||
|
||||
@ -132,11 +132,11 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
# logger.debug('Got cached instance instead of deserializing a new one for {}'.format(self.name))
|
||||
return self._cachedInstance
|
||||
|
||||
prov: 'services.ServiceProvider' = self.provider.getInstance()
|
||||
prov: 'services.ServiceProvider' = self.provider.get_instance()
|
||||
sType = prov.getServiceByType(self.data_type)
|
||||
|
||||
if sType:
|
||||
obj = sType(self.getEnvironment(), prov, values, uuid=self.uuid)
|
||||
obj = sType(self.get_environment(), prov, values, uuid=self.uuid)
|
||||
self.deserialize(obj, values)
|
||||
else:
|
||||
raise Exception(f'Service type of {self.data_type} is not recogniced by provider {prov.name}')
|
||||
@ -145,7 +145,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
|
||||
return obj
|
||||
|
||||
def getType(self) -> type['services.Service']:
|
||||
def get_type(self) -> type['services.Service']:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -158,7 +158,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
from uds.core import services # pylint: disable=import-outside-toplevel,redefined-outer-name
|
||||
|
||||
prov: type['services.ServiceProvider'] = self.provider.getType()
|
||||
prov: type['services.ServiceProvider'] = self.provider.get_type()
|
||||
return prov.getServiceByType(self.data_type) or services.Service
|
||||
|
||||
@property
|
||||
@ -202,7 +202,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
return f'{self.name} of type {self.data_type} (id:{self.id})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -213,21 +213,21 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
to_delete: 'Service' = kwargs['instance']
|
||||
|
||||
logger.debug('Before delete service %s', toDelete)
|
||||
logger.debug('Before delete service %s', to_delete)
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data != '':
|
||||
s = toDelete.getInstance()
|
||||
if to_delete.data != '':
|
||||
s = to_delete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
# Clears related permissions
|
||||
clean(toDelete)
|
||||
clean(to_delete)
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to Service
|
||||
models.signals.pre_delete.connect(Service.beforeDelete, sender=Service)
|
||||
models.signals.pre_delete.connect(Service.pre_delete, sender=Service)
|
||||
|
@ -160,7 +160,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
db_table = 'uds__deployed_service'
|
||||
app_label = 'uds'
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents
|
||||
"""
|
||||
@ -182,7 +182,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
|
||||
def transformsUserOrPasswordForService(self) -> bool:
|
||||
if self.osmanager:
|
||||
return self.osmanager.getType().transformsUserOrPasswordForService()
|
||||
return self.osmanager.get_type().transformsUserOrPasswordForService()
|
||||
return False
|
||||
|
||||
def processUserPassword(self, username: str, password: str) -> tuple[str, str]:
|
||||
@ -288,7 +288,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
return None
|
||||
|
||||
# If has os manager, check if it is persistent
|
||||
if self.osmanager and self.osmanager.getInstance().isPersistent():
|
||||
if self.osmanager and self.osmanager.get_instance().isPersistent():
|
||||
return None
|
||||
|
||||
# Return the date
|
||||
@ -368,7 +368,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
name: Name of the value to store
|
||||
value: Value of the value to store
|
||||
"""
|
||||
self.getEnvironment().storage.put(name, value)
|
||||
self.get_environment().storage.put(name, value)
|
||||
|
||||
def recoverValue(self, name: str) -> typing.Any:
|
||||
"""
|
||||
@ -380,7 +380,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
Returns:
|
||||
Stored value, None if no value was stored
|
||||
"""
|
||||
return typing.cast(str, self.getEnvironment().storage.get(name))
|
||||
return typing.cast(str, self.get_environment().storage.get(name))
|
||||
|
||||
def setState(self, state: str, save: bool = True) -> None:
|
||||
"""
|
||||
@ -474,7 +474,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
if (
|
||||
self.activePublication() is None
|
||||
and self.service
|
||||
and self.service.getType().publicationType is not None
|
||||
and self.service.get_type().publicationType is not None
|
||||
):
|
||||
raise InvalidServiceException()
|
||||
|
||||
@ -520,7 +520,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
from uds.core import services # pylint: disable=import-outside-toplevel
|
||||
|
||||
servicesNotNeedingPub = [t.getType() for t in services.factory().servicesThatDoNotNeedPublication()]
|
||||
servicesNotNeedingPub = [t.get_type() for t in services.factory().servicesThatDoNotNeedPublication()]
|
||||
# Get services that HAS publications
|
||||
query = (
|
||||
ServicePool.objects.filter(
|
||||
@ -640,7 +640,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
"""
|
||||
maxs = self.max_srvs
|
||||
if maxs == 0 and self.service:
|
||||
maxs = self.service.getInstance().maxUserServices
|
||||
maxs = self.service.get_instance().maxUserServices
|
||||
|
||||
if cachedValue == -1:
|
||||
cachedValue = self.assignedUserServices().filter(state__in=states.userService.VALID_STATES).count()
|
||||
@ -658,7 +658,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
log.doLog(self, level, message, log.LogSource.INTERNAL)
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -674,7 +674,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
toDelete: 'ServicePool' = kwargs['instance']
|
||||
|
||||
logger.debug('Deleting Service Pool %s', toDelete)
|
||||
toDelete.getEnvironment().clearRelatedData()
|
||||
toDelete.get_environment().clearRelatedData()
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
@ -720,4 +720,4 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
|
||||
|
||||
|
||||
# Connects a pre deletion signal to Authenticator
|
||||
models.signals.pre_delete.connect(ServicePool.beforeDelete, sender=ServicePool)
|
||||
models.signals.pre_delete.connect(ServicePool.pre_delete, sender=ServicePool)
|
||||
|
@ -109,13 +109,13 @@ class ServicePoolPublication(UUIDModel):
|
||||
ordering = ('publish_date',)
|
||||
app_label = 'uds'
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents
|
||||
"""
|
||||
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore
|
||||
|
||||
def getInstance(self) -> 'services.Publication':
|
||||
def get_intance(self) -> 'services.Publication':
|
||||
"""
|
||||
Instantiates the object this record contains.
|
||||
|
||||
@ -132,9 +132,9 @@ class ServicePoolPublication(UUIDModel):
|
||||
"""
|
||||
if not self.deployed_service.service:
|
||||
raise Exception('No service assigned to publication')
|
||||
serviceInstance = self.deployed_service.service.getInstance()
|
||||
serviceInstance = self.deployed_service.service.get_instance()
|
||||
osManager = self.deployed_service.osmanager
|
||||
osManagerInstance = osManager.getInstance() if osManager else None
|
||||
osManagerInstance = osManager.get_instance() if osManager else None
|
||||
|
||||
# Sanity check, so it's easier to find when we have created
|
||||
# a service that needs publication but do not have
|
||||
@ -145,7 +145,7 @@ class ServicePoolPublication(UUIDModel):
|
||||
)
|
||||
|
||||
publication = serviceInstance.publicationType(
|
||||
self.getEnvironment(),
|
||||
self.get_environment(),
|
||||
service=serviceInstance,
|
||||
osManager=osManagerInstance,
|
||||
revision=self.revision,
|
||||
@ -200,7 +200,7 @@ class ServicePoolPublication(UUIDModel):
|
||||
publicationManager().cancel(self)
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -209,17 +209,17 @@ class ServicePoolPublication(UUIDModel):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete: ServicePoolPublication = kwargs['instance']
|
||||
toDelete.getEnvironment().clearRelatedData()
|
||||
to_delete: ServicePoolPublication = kwargs['instance']
|
||||
to_delete.get_environment().clearRelatedData()
|
||||
|
||||
# Delete method is invoked directly by PublicationManager,
|
||||
# Destroying a publication is not obligatory an 1 step action.
|
||||
# It's handled as "publish", and as so, it can be a multi-step process
|
||||
|
||||
# Clears related logs
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
logger.debug('Deleted publication %s', toDelete)
|
||||
logger.debug('Deleted publication %s', to_delete)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return (
|
||||
@ -228,4 +228,4 @@ class ServicePoolPublication(UUIDModel):
|
||||
|
||||
|
||||
# Connects a pre deletion signal to Authenticator
|
||||
models.signals.pre_delete.connect(ServicePoolPublication.beforeDelete, sender=ServicePoolPublication)
|
||||
models.signals.pre_delete.connect(ServicePoolPublication.pre_delete, sender=ServicePoolPublication)
|
||||
|
@ -276,7 +276,7 @@ class TicketStore(UUIDModel):
|
||||
host = data['h']
|
||||
|
||||
if not host:
|
||||
host = userService.getInstance().getIp()
|
||||
host = userService.get_instance().getIp()
|
||||
|
||||
return (user, userService, host, data['p'], data['e'])
|
||||
except Exception as e:
|
||||
|
@ -91,10 +91,10 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
ordering = ('name',)
|
||||
app_label = 'uds'
|
||||
|
||||
def getInstance(self, values: typing.Optional[dict[str, str]] = None) -> 'transports.Transport':
|
||||
return typing.cast('transports.Transport', super().getInstance(values=values))
|
||||
def get_instance(self, values: typing.Optional[dict[str, str]] = None) -> 'transports.Transport':
|
||||
return typing.cast('transports.Transport', super().get_instance(values=values))
|
||||
|
||||
def getType(self) -> type['transports.Transport']:
|
||||
def get_type(self) -> type['transports.Transport']:
|
||||
"""
|
||||
Get the type of the object this record represents.
|
||||
|
||||
@ -107,7 +107,7 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
"""
|
||||
return transports.factory().lookup(self.data_type) or transports.Transport
|
||||
|
||||
def isValidForIp(self, ipStr: str) -> bool:
|
||||
def is_ip_allowed(self, ipStr: str) -> bool:
|
||||
"""
|
||||
Checks if this transport is valid for the specified IP.
|
||||
|
||||
@ -142,7 +142,7 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
# Deny, must not be in any network
|
||||
return not exists
|
||||
|
||||
def isValidForOs(self, os: 'types.os.KnownOS') -> bool:
|
||||
def is_os_allowed(self, os: 'types.os.KnownOS') -> bool:
|
||||
"""If this transport is configured to be valid for the specified OS.
|
||||
|
||||
Args:
|
||||
@ -157,7 +157,7 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
return f'{self.name} of type {self.data_type} (id:{self.id})'
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -168,12 +168,12 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
"""
|
||||
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
|
||||
|
||||
toDelete = kwargs['instance']
|
||||
toDelete: 'Transport' = kwargs['instance']
|
||||
|
||||
logger.debug('Before delete transport %s', toDelete)
|
||||
# Only tries to get instance if data is not empty
|
||||
if toDelete.data != '':
|
||||
s = toDelete.getInstance()
|
||||
s = toDelete.get_instance()
|
||||
s.destroy()
|
||||
s.env.clearRelatedData()
|
||||
|
||||
@ -182,4 +182,4 @@ class Transport(ManagedObjectModel, TaggingMixin):
|
||||
|
||||
|
||||
# : Connects a pre deletion signal to OS Manager
|
||||
models.signals.pre_delete.connect(Transport.beforeDelete, sender=Transport)
|
||||
models.signals.pre_delete.connect(Transport.pre_delete, sender=Transport)
|
||||
|
@ -127,7 +127,7 @@ class User(UUIDModel, properties.PropertiesMixin):
|
||||
|
||||
:note: The returned value is an instance of the authenticator class used to manage this user, not a db record.
|
||||
"""
|
||||
return self.manager.getInstance()
|
||||
return self.manager.get_instance()
|
||||
|
||||
def isStaff(self) -> bool:
|
||||
"""
|
||||
@ -222,10 +222,10 @@ class User(UUIDModel, properties.PropertiesMixin):
|
||||
# If has mfa, remove related data
|
||||
# If has mfa, remove related data
|
||||
if self.manager.mfa:
|
||||
self.manager.mfa.getInstance().resetData(mfas.MFA.getUserId(self))
|
||||
self.manager.mfa.get_instance().resetData(mfas.MFA.getUserId(self))
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -234,35 +234,35 @@ class User(UUIDModel, properties.PropertiesMixin):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete: User = kwargs['instance']
|
||||
to_delete: User = kwargs['instance']
|
||||
|
||||
# first, we invoke removeUser. If this raises an exception, user will not
|
||||
# be removed
|
||||
toDelete.getManager().removeUser(toDelete.name)
|
||||
to_delete.getManager().removeUser(to_delete.name)
|
||||
|
||||
# If has mfa, remove related data
|
||||
toDelete.cleanRelated()
|
||||
to_delete.cleanRelated()
|
||||
|
||||
# Remove related stored values
|
||||
with storage.StorageAccess('manager' + str(toDelete.manager.uuid)) as store:
|
||||
with storage.StorageAccess('manager' + str(to_delete.manager.uuid)) as store:
|
||||
for key in store.keys():
|
||||
store.delete(key)
|
||||
|
||||
# now removes all "child" of this user, if it has children
|
||||
User.objects.filter(parent=toDelete.id).delete()
|
||||
User.objects.filter(parent=to_delete.id).delete()
|
||||
|
||||
# Remove related logs
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
# Removes all user services assigned to this user (unassign it and mark for removal)
|
||||
for us in toDelete.userServices.all():
|
||||
for us in to_delete.userServices.all():
|
||||
us.assignToUser(None)
|
||||
us.remove()
|
||||
|
||||
logger.debug('Deleted user %s', toDelete)
|
||||
logger.debug('Deleted user %s', to_delete)
|
||||
|
||||
# Connect to pre delete signal
|
||||
signals.pre_delete.connect(User.beforeDelete, sender=User)
|
||||
signals.pre_delete.connect(User.pre_delete, sender=User)
|
||||
|
||||
# Connects the properties signals
|
||||
properties.PropertiesMixin.setupSignals(User)
|
||||
properties.PropertiesMixin.setup_signals(User)
|
||||
|
@ -156,7 +156,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
"""
|
||||
del self.properties['destroy_after']
|
||||
|
||||
def getEnvironment(self) -> Environment:
|
||||
def get_environment(self) -> Environment:
|
||||
"""
|
||||
Returns an environment valid for the record this object represents.
|
||||
|
||||
@ -178,7 +178,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
},
|
||||
)
|
||||
|
||||
def getInstance(self) -> 'services.UserService':
|
||||
def get_instance(self) -> 'services.UserService':
|
||||
"""
|
||||
Instantiates the object this record contains. In this case, the instantiated object needs also
|
||||
the os manager and the publication, so we also instantiate those here.
|
||||
@ -198,21 +198,21 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
servicePool = self.deployed_service
|
||||
if not servicePool.service:
|
||||
raise Exception('Service not found')
|
||||
serviceInstance = servicePool.service.getInstance()
|
||||
serviceInstance = servicePool.service.get_instance()
|
||||
if serviceInstance.needsManager is False or not servicePool.osmanager:
|
||||
osmanagerInstance = None
|
||||
else:
|
||||
osmanagerInstance = servicePool.osmanager.getInstance()
|
||||
osmanagerInstance = servicePool.osmanager.get_instance()
|
||||
# We get active publication
|
||||
publicationInstance = None
|
||||
try: # We may have deleted publication...
|
||||
if self.publication is not None:
|
||||
publicationInstance = self.publication.getInstance()
|
||||
publicationInstance = self.publication.get_intance()
|
||||
except Exception:
|
||||
# The publication to witch this item points to, does not exists
|
||||
self.publication = None # type: ignore
|
||||
logger.exception(
|
||||
'Got exception at getInstance of an userService %s (seems that publication does not exists!)',
|
||||
'Got exception at get_instance of an userService %s (seems that publication does not exists!)',
|
||||
self,
|
||||
)
|
||||
if serviceInstance.userServiceType is None:
|
||||
@ -220,7 +220,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
f'Class {serviceInstance.__class__.__name__} needs userServiceType but it is not defined!!!'
|
||||
)
|
||||
us = serviceInstance.userServiceType(
|
||||
self.getEnvironment(),
|
||||
self.get_environment(),
|
||||
service=serviceInstance,
|
||||
publication=publicationInstance,
|
||||
osmanager=osmanagerInstance,
|
||||
@ -255,7 +255,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
Returns the name of the user deployed service
|
||||
"""
|
||||
if self.friendly_name == '':
|
||||
si = self.getInstance()
|
||||
si = self.get_instance()
|
||||
self.friendly_name = si.getName()
|
||||
self.updateData(si)
|
||||
|
||||
@ -266,7 +266,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
Returns the unique id of the user deployed service
|
||||
"""
|
||||
if self.unique_id == '':
|
||||
si = self.getInstance()
|
||||
si = self.get_instance()
|
||||
self.unique_id = si.getUniqueId()
|
||||
self.updateData(si)
|
||||
return self.unique_id
|
||||
@ -297,7 +297,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
# To transition between old stor at storage table and new properties table
|
||||
# If value is found on property, use it, else, try to recover it from storage
|
||||
if val is None:
|
||||
val = typing.cast(str, self.getEnvironment().storage.get(name))
|
||||
val = typing.cast(str, self.get_environment().storage.get(name))
|
||||
return val
|
||||
|
||||
def setConnectionSource(self, src: types.connections.ConnectionSource) -> None:
|
||||
@ -343,7 +343,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
def getOsManagerInstance(self) -> typing.Optional['osmanagers.OSManager']:
|
||||
osManager = self.getOsManager()
|
||||
if osManager:
|
||||
return osManager.getInstance()
|
||||
return osManager.get_instance()
|
||||
return None
|
||||
|
||||
def needsOsManager(self) -> bool:
|
||||
@ -380,11 +380,11 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
servicePool = self.deployed_service
|
||||
if not servicePool.service:
|
||||
raise Exception('Service not found')
|
||||
serviceInstance = servicePool.service.getInstance()
|
||||
serviceInstance = servicePool.service.get_instance()
|
||||
if serviceInstance.needsManager is False or not servicePool.osmanager:
|
||||
return (username, password)
|
||||
|
||||
return servicePool.osmanager.getInstance().processUserPassword(self, username, password)
|
||||
return servicePool.osmanager.get_instance().processUserPassword(self, username, password)
|
||||
|
||||
def setState(self, state: str) -> None:
|
||||
"""
|
||||
@ -599,7 +599,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
Returns True if this user service does not needs an publication, or if this deployed service publication is the current one
|
||||
"""
|
||||
return (
|
||||
self.deployed_service.service and self.deployed_service.service.getType().publicationType is None
|
||||
self.deployed_service.service and self.deployed_service.service.get_type().publicationType is None
|
||||
) or self.publication == self.deployed_service.activePublication()
|
||||
|
||||
# Utility for logging
|
||||
@ -617,7 +617,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
|
||||
"""
|
||||
Used to invoke the Service class "Destroy" before deleting it from database.
|
||||
|
||||
@ -626,21 +626,21 @@ class UserService(UUIDModel, properties.PropertiesMixin):
|
||||
|
||||
:note: If destroy raises an exception, the deletion is not taken.
|
||||
"""
|
||||
toDelete: 'UserService' = kwargs['instance']
|
||||
to_delete: 'UserService' = kwargs['instance']
|
||||
# Clear environment
|
||||
toDelete.getEnvironment().clearRelatedData()
|
||||
to_delete.get_environment().clearRelatedData()
|
||||
# Ensure all sessions are closed (invoke with '' to close all sessions)
|
||||
# In fact, sessions are going to be deleted also, but we give then
|
||||
# the oportunity to execute some code before deleting them
|
||||
toDelete.closeSession('')
|
||||
to_delete.closeSession('')
|
||||
|
||||
# Clear related logs to this user service
|
||||
log.clearLogs(toDelete)
|
||||
log.clearLogs(to_delete)
|
||||
|
||||
logger.debug('Deleted user service %s', toDelete)
|
||||
logger.debug('Deleted user service %s', to_delete)
|
||||
|
||||
|
||||
# Connects a pre deletion signal to Authenticator
|
||||
signals.pre_delete.connect(UserService.beforeDelete, sender=UserService)
|
||||
signals.pre_delete.connect(UserService.pre_delete, sender=UserService)
|
||||
# Connects the properties signals
|
||||
properties.PropertiesMixin.setupSignals(UserService)
|
||||
properties.PropertiesMixin.setup_signals(UserService)
|
||||
|
@ -30,7 +30,7 @@ class TelegramReceiver(jobs.Job):
|
||||
|
||||
# Get all Notifiers that are telegram notifiers
|
||||
for telegramDbNotifier in Notifier.objects.filter(data_Type=notifier.TELEGRAM_TYPE):
|
||||
n = typing.cast(notifier.TelegramNotifier, telegramDbNotifier.getInstance())
|
||||
n = typing.cast(notifier.TelegramNotifier, telegramDbNotifier.get_instance())
|
||||
|
||||
if n is None:
|
||||
logger.error('Notifier %s is not a Telegram notifier', telegramDbNotifier.name)
|
||||
|
@ -96,8 +96,8 @@ class OVirtDeferredRemoval(jobs.Job):
|
||||
):
|
||||
logger.debug('Provider %s if os type ovirt', provider)
|
||||
|
||||
storage = provider.getEnvironment().storage
|
||||
instance: OVirtProvider = typing.cast(OVirtProvider, provider.getInstance())
|
||||
storage = provider.get_environment().storage
|
||||
instance: OVirtProvider = typing.cast(OVirtProvider, provider.get_instance())
|
||||
|
||||
for i in storage.filter('tRm'):
|
||||
vmId = i[1].decode()
|
||||
|
@ -66,7 +66,7 @@ class OpenGnsysMaintainer(jobs.Job):
|
||||
# Locate all services inside the provider
|
||||
service: models.Service
|
||||
for service in provider.services.all():
|
||||
instance: OGService = typing.cast(OGService, service.getInstance())
|
||||
instance: OGService = typing.cast(OGService, service.get_instance())
|
||||
since = getSqlDatetime() - datetime.timedelta(
|
||||
hours=instance.maxReservationTime.num() - 8
|
||||
) # If less than 8 hours of reservation...
|
||||
|
@ -103,9 +103,9 @@ class ProxmoxDeferredRemoval(jobs.Job):
|
||||
):
|
||||
logger.debug('Provider %s if os type proxmox', dbProvider)
|
||||
|
||||
storage = dbProvider.getEnvironment().storage
|
||||
storage = dbProvider.get_environment().storage
|
||||
instance: provider.ProxmoxProvider = typing.cast(
|
||||
provider.ProxmoxProvider, dbProvider.getInstance()
|
||||
provider.ProxmoxProvider, dbProvider.get_instance()
|
||||
)
|
||||
|
||||
for i in storage.filter('tRm'):
|
||||
|
@ -323,7 +323,7 @@ class HTML5RDPTransport(transports.Transport):
|
||||
|
||||
# Maybe this is called from another provider, as for example WYSE, that need all connections BEFORE
|
||||
if isinstance(userService, models.UserService):
|
||||
cdata = userService.getInstance().getConnectionData()
|
||||
cdata = userService.get_instance().getConnectionData()
|
||||
if cdata:
|
||||
username = cdata[1] or username
|
||||
password = cdata[2] or password
|
||||
|
@ -422,7 +422,7 @@ class BaseRDPTransport(transports.Transport):
|
||||
) -> types.connections.ConnectionData:
|
||||
username = None
|
||||
if isinstance(userService, UserService):
|
||||
cdata = userService.getInstance().getConnectionData()
|
||||
cdata = userService.get_instance().getConnectionData()
|
||||
if cdata:
|
||||
username = cdata[1] or username
|
||||
password = cdata[2] or password
|
||||
|
@ -83,7 +83,7 @@ class SPICETransport(BaseSpiceTransport):
|
||||
request: 'ExtendedHttpRequestWithUser',
|
||||
) -> 'transports.TransportScript':
|
||||
try:
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
con: typing.Optional[collections.abc.MutableMapping[str, typing.Any]] = userServiceInstance.getConsoleConnection()
|
||||
except Exception:
|
||||
logger.exception('Error getting console connection data')
|
||||
|
@ -149,7 +149,7 @@ class BaseSpiceTransport(transports.Transport):
|
||||
"""
|
||||
ready = self.cache.get(ip)
|
||||
if ready is None:
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
con = userServiceInstance.getConsoleConnection()
|
||||
|
||||
logger.debug('Connection data: %s', con)
|
||||
|
@ -100,7 +100,7 @@ class TSPICETransport(BaseSpiceTransport):
|
||||
request: 'ExtendedHttpRequestWithUser',
|
||||
) -> transports.TransportScript:
|
||||
try:
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
con = userServiceInstance.getConsoleConnection()
|
||||
except Exception:
|
||||
logger.exception('Error getting console connection data')
|
||||
|
@ -237,7 +237,7 @@ class BaseX2GOTransport(transports.Transport):
|
||||
else:
|
||||
service = userService.service
|
||||
|
||||
servicesTypeProvided = service.getType().servicesTypeProvided
|
||||
servicesTypeProvided = service.get_type().servicesTypeProvided
|
||||
|
||||
if self.fixedName.value != '':
|
||||
username = self.fixedName.value
|
||||
|
@ -65,9 +65,9 @@ class LoginForm(forms.Form):
|
||||
choices = []
|
||||
|
||||
for a in Authenticator.get_by_tag(tag):
|
||||
if not a.getType(): # Not existing manager for the auth?
|
||||
if not a.get_type(): # Not existing manager for the auth?
|
||||
continue
|
||||
if a.getType().isCustom() and tag == 'disabled':
|
||||
if a.get_type().isCustom() and tag == 'disabled':
|
||||
continue
|
||||
choices.append((a.uuid, a.name))
|
||||
|
||||
|
@ -107,7 +107,7 @@ def checkLogin( # pylint: disable=too-many-branches, too-many-statements
|
||||
)
|
||||
maxTries = GlobalConfig.MAX_LOGIN_TRIES.getInt()
|
||||
# Get instance..
|
||||
authInstance = authenticator.getInstance()
|
||||
authInstance = authenticator.get_instance()
|
||||
# Check if user is locked
|
||||
if (
|
||||
authInstance.blockUserOnLoginFailures is True
|
||||
|
@ -105,7 +105,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
|
||||
# Filter out non accesible authenticators (using origin)
|
||||
authenticators = [
|
||||
a for a in authenticators if a.getInstance().isAccesibleFrom(request)
|
||||
a for a in authenticators if a.get_instance().isAccesibleFrom(request)
|
||||
]
|
||||
|
||||
# logger.debug('Authenticators PRE: %s', authenticators)
|
||||
@ -117,7 +117,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
x
|
||||
for x in authenticators
|
||||
if x.small_name == tag
|
||||
or (tag == 'disabled' and x.getType().isCustom() is False)
|
||||
or (tag == 'disabled' and x.get_type().isCustom() is False)
|
||||
]
|
||||
|
||||
# No autenticator can reach the criteria, let's do a final try
|
||||
@ -126,7 +126,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
try:
|
||||
authenticators = []
|
||||
for a in Authenticator.objects.exclude(state=consts.auth.DISABLED).order_by('priority'):
|
||||
if a.getInstance().isAccesibleFrom(request):
|
||||
if a.get_instance().isAccesibleFrom(request):
|
||||
authenticators.append(a)
|
||||
break
|
||||
except Exception:
|
||||
@ -140,7 +140,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
|
||||
# the auths for client
|
||||
def getAuthInfo(auth: Authenticator):
|
||||
theType = auth.getType()
|
||||
theType = auth.get_type()
|
||||
return {
|
||||
'id': auth.uuid,
|
||||
'name': auth.name,
|
||||
@ -157,7 +157,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
{'id': k, 'name': gettext(v)} for k, v in settings.LANGUAGES
|
||||
],
|
||||
'authenticators': [
|
||||
getAuthInfo(auth) for auth in authenticators if auth.getType()
|
||||
getAuthInfo(auth) for auth in authenticators if auth.get_type()
|
||||
],
|
||||
'mfa': request.session.get('mfa', None),
|
||||
'tag': tag,
|
||||
@ -218,7 +218,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
|
||||
info = {
|
||||
'networks': [n.name for n in Network.networksFor(request.ip)],
|
||||
'transports': [
|
||||
t.name for t in Transport.objects.all() if t.isValidForIp(request.ip)
|
||||
t.name for t in Transport.objects.all() if t.is_ip_allowed(request.ip)
|
||||
],
|
||||
'ip': request.ip,
|
||||
'ip_proxy': request.ip_proxy,
|
||||
|
@ -141,7 +141,7 @@ def getServicesData(
|
||||
tt = []
|
||||
t: Transport
|
||||
for t in Transport.objects.all().prefetch_related('networks'):
|
||||
if t.isValidForIp(request.ip):
|
||||
if t.is_ip_allowed(request.ip):
|
||||
tt.append(t.name)
|
||||
validTrans = ','.join(tt)
|
||||
|
||||
@ -150,14 +150,15 @@ def getServicesData(
|
||||
|
||||
# Metapool helpers
|
||||
def transportIterator(member) -> collections.abc.Iterable[Transport]:
|
||||
t: Transport
|
||||
for t in member.pool.transports.all().order_by('priority'):
|
||||
try:
|
||||
typeTrans = t.getType()
|
||||
typeTrans = t.get_type()
|
||||
if (
|
||||
typeTrans
|
||||
and t.validForIp(request.ip)
|
||||
and t.is_ip_allowed(request.ip)
|
||||
and typeTrans.supportsOs(osType)
|
||||
and t.validForOs(osType)
|
||||
and t.is_os_allowed(osType)
|
||||
):
|
||||
yield t
|
||||
except Exception as e:
|
||||
@ -252,12 +253,12 @@ def getServicesData(
|
||||
# if pool.isInMaintenance():
|
||||
# continue
|
||||
for t in member.pool.transports.all():
|
||||
typeTrans = t.getType()
|
||||
typeTrans = t.get_type()
|
||||
if (
|
||||
typeTrans
|
||||
and t.isValidForIp(request.ip)
|
||||
and t.is_ip_allowed(request.ip)
|
||||
and typeTrans.supportsOs(osType)
|
||||
and t.isValidForOs(osType)
|
||||
and t.is_os_allowed(osType)
|
||||
):
|
||||
metaTransports = [
|
||||
{
|
||||
@ -340,12 +341,12 @@ def getServicesData(
|
||||
for t in sorted(
|
||||
sPool.transports.all(), key=lambda x: x.priority
|
||||
): # In memory sort, allows reuse prefetched and not too big array
|
||||
typeTrans = t.getType()
|
||||
typeTrans = t.get_type()
|
||||
if (
|
||||
typeTrans
|
||||
and t.isValidForIp(request.ip)
|
||||
and t.is_ip_allowed(request.ip)
|
||||
and typeTrans.supportsOs(osType)
|
||||
and t.isValidForOs(osType)
|
||||
and t.is_os_allowed(osType)
|
||||
):
|
||||
if typeTrans.ownLink:
|
||||
link = reverse('TransportOwnLink', args=('F' + sPool.uuid, t.uuid)) # type: ignore
|
||||
@ -453,7 +454,7 @@ def enableService(
|
||||
|
||||
userService.properties['accessed_by_client'] = False # Reset accesed property to
|
||||
|
||||
typeTrans = trans.getType()
|
||||
typeTrans = trans.get_type()
|
||||
|
||||
error = '' # No error
|
||||
|
||||
|
@ -122,8 +122,8 @@ def authCallback_stage2(request: 'ExtendedHttpRequestWithUser', ticketId: str) -
|
||||
|
||||
# If MFA is provided, we need to redirect to MFA page
|
||||
request.authorized = True
|
||||
if authenticator.getType().providesMfa() and authenticator.mfa:
|
||||
authInstance = authenticator.getInstance()
|
||||
if authenticator.get_type().providesMfa() and authenticator.mfa:
|
||||
authInstance = authenticator.get_instance()
|
||||
if authInstance.mfaIdentifier(result.user.name):
|
||||
request.authorized = False # We can ask for MFA so first disauthorize user
|
||||
response = HttpResponseRedirect(reverse('page.mfa'))
|
||||
@ -156,7 +156,7 @@ def authInfo(request: 'HttpRequest', authName: str) -> HttpResponse:
|
||||
)
|
||||
if not authenticator:
|
||||
raise Exception('Authenticator not found')
|
||||
authInstance = authenticator.getInstance()
|
||||
authInstance = authenticator.get_instance()
|
||||
if typing.cast(typing.Any, authInstance.getInfo) == auths.Authenticator.getInfo:
|
||||
raise Exception() # This authenticator do not provides info
|
||||
|
||||
@ -183,7 +183,7 @@ def customAuth(request: 'HttpRequest', idAuth: str) -> HttpResponse:
|
||||
auth = Authenticator.objects.get(uuid=processUuid(idAuth))
|
||||
except Authenticator.DoesNotExist:
|
||||
auth = Authenticator.objects.get(pk=idAuth)
|
||||
res = auth.getInstance().getJavascript(request)
|
||||
res = auth.get_instance().getJavascript(request)
|
||||
if not res:
|
||||
res = ''
|
||||
except Exception:
|
||||
@ -259,7 +259,7 @@ def ticketAuth(
|
||||
res = UserServiceManager().getService(request.user, request.os, request.ip, poolUuid, None, False)
|
||||
_, userService, _, transport, _ = res
|
||||
|
||||
transportInstance = transport.getInstance()
|
||||
transportInstance = transport.get_instance()
|
||||
if transportInstance.ownLink is True:
|
||||
link = reverse(
|
||||
'TransportOwnLink', args=('A' + userService.uuid, transport.uuid) # type: ignore
|
||||
|
@ -119,8 +119,7 @@ def login(request: ExtendedHttpRequest, tag: typing.Optional[str] = None) -> Htt
|
||||
|
||||
# If MFA is provided, we need to redirect to MFA page
|
||||
request.authorized = True
|
||||
if loginResult.user.manager.getType().providesMfa() and loginResult.user.manager.mfa:
|
||||
# authInstance = loginResult.user.manager.getInstance()
|
||||
if loginResult.user.manager.get_type().providesMfa() and loginResult.user.manager.mfa:
|
||||
request.authorized = False
|
||||
response = HttpResponseRedirect(reverse('page.mfa'))
|
||||
|
||||
@ -190,8 +189,8 @@ def mfa(request: ExtendedHttpRequest) -> HttpResponse: # pylint: disable=too-ma
|
||||
return HttpResponseRedirect(reverse('page.index'))
|
||||
|
||||
# Obtain MFA data
|
||||
authInstance = request.user.manager.getInstance()
|
||||
mfaInstance = typing.cast('mfas.MFA', mfaProvider.getInstance())
|
||||
authInstance = request.user.manager.get_instance()
|
||||
mfaInstance = typing.cast('mfas.MFA', mfaProvider.get_instance())
|
||||
|
||||
# Get validity duration
|
||||
validity = mfaProvider.validity * 60
|
||||
|
@ -99,7 +99,7 @@ def transportIcon(request: 'ExtendedHttpRequest', idTrans: str) -> HttpResponse:
|
||||
]
|
||||
else:
|
||||
transport = Transport.objects.get(uuid=processUuid(idTrans))
|
||||
return HttpResponse(transport.getInstance().icon(), content_type='image/png')
|
||||
return HttpResponse(transport.get_instance().icon(), content_type='image/png')
|
||||
except Exception:
|
||||
return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
|
||||
|
||||
@ -114,7 +114,7 @@ def serviceImage(request: 'ExtendedHttpRequest', idImage: str) -> HttpResponse:
|
||||
|
||||
try:
|
||||
transport: Transport = Transport.objects.get(uuid=processUuid(idImage))
|
||||
return HttpResponse(transport.getInstance().icon(), content_type='image/png')
|
||||
return HttpResponse(transport.get_instance().icon(), content_type='image/png')
|
||||
except Exception:
|
||||
return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
|
||||
|
||||
@ -163,7 +163,7 @@ def userServiceStatus(request: 'ExtendedHttpRequestWithUser', idService: str, id
|
||||
if userService:
|
||||
# Service exists...
|
||||
try:
|
||||
userServiceInstance = userService.getInstance()
|
||||
userServiceInstance = userService.get_instance()
|
||||
ip = userServiceInstance.getIp()
|
||||
userService.logIP(ip)
|
||||
# logger.debug('Res: %s %s %s %s %s', ip, userService, userServiceInstance, transport, transportInstance)
|
||||
@ -206,7 +206,7 @@ def action(request: 'ExtendedHttpRequestWithUser', idService: str, actionString:
|
||||
elif (
|
||||
actionString == 'reset'
|
||||
and userService.deployed_service.allow_users_reset
|
||||
and userService.deployed_service.service.getType().canReset # type: ignore
|
||||
and userService.deployed_service.service.get_type().canReset # type: ignore
|
||||
):
|
||||
rebuild = True
|
||||
log.doLog(
|
||||
|
2
server/tests/fixtures/authenticators.py
vendored
2
server/tests/fixtures/authenticators.py
vendored
@ -54,7 +54,7 @@ def createAuthenticator(
|
||||
authenticator.name = 'Testing authenticator'
|
||||
authenticator.comments = 'Tesging authenticator'
|
||||
authenticator.data_type = InternalDBAuth.typeType
|
||||
authenticator.data = authenticator.getInstance().serialize()
|
||||
authenticator.data = authenticator.get_instance().serialize()
|
||||
authenticator.save()
|
||||
|
||||
return authenticator
|
||||
|
2
server/tests/fixtures/notifiers.py
vendored
2
server/tests/fixtures/notifiers.py
vendored
@ -53,7 +53,7 @@ def createEmailNotifier(
|
||||
notifier.name = 'Testing email notifier'
|
||||
notifier.comments = 'Testing email notifier'
|
||||
notifier.data_type = EmailNotifier.typeType
|
||||
instance: EmailNotifier = typing.cast(EmailNotifier, notifier.getInstance())
|
||||
instance: EmailNotifier = typing.cast(EmailNotifier, notifier.get_instance())
|
||||
# Fill up fields
|
||||
instance.hostname.value = (host or 'localhost') + (
|
||||
'' if port == 0 else ':' + str(port)
|
||||
|
6
server/tests/fixtures/services.py
vendored
6
server/tests/fixtures/services.py
vendored
@ -58,7 +58,7 @@ def createProvider() -> models.Provider:
|
||||
provider.name = 'Testing provider {}'.format(glob['provider_id'])
|
||||
provider.comments = 'Tesging provider comment {}'.format(glob['provider_id'])
|
||||
provider.data_type = TestProvider.typeType
|
||||
provider.data = provider.getInstance().serialize()
|
||||
provider.data = provider.get_instance().serialize()
|
||||
provider.save()
|
||||
glob['provider_id'] += 1
|
||||
|
||||
@ -74,11 +74,11 @@ def createService(
|
||||
name='Service {}'.format(glob['service_id']),
|
||||
data_type=TestServiceCache.typeType,
|
||||
data=TestServiceCache(
|
||||
environment.Environment(str(glob['service_id'])), provider.getInstance()
|
||||
environment.Environment(str(glob['service_id'])), provider.get_instance()
|
||||
).serialize()
|
||||
if useCachingVersion
|
||||
else TestServiceNoCache(
|
||||
environment.Environment(str(glob['service_id'])), provider.getInstance()
|
||||
environment.Environment(str(glob['service_id'])), provider.get_instance()
|
||||
).serialize(),
|
||||
token=generators.random_string(16) + str(glob['service_id']),
|
||||
)
|
||||
|
@ -77,7 +77,7 @@ class EmailNotifierTest(UDSTestCase):
|
||||
enableHtml=False
|
||||
)
|
||||
|
||||
notifier.getInstance().notify(
|
||||
notifier.get_instance().notify(
|
||||
'Group',
|
||||
'Identificator',
|
||||
messaging.LogLevel.CRITICAL,
|
||||
|
Loading…
Reference in New Issue
Block a user