1
0
mirror of https://github.com/dkmstr/openuds.git synced 2024-12-25 23:21:41 +03:00

advancing on refactoring

This commit is contained in:
Adolfo Gómez García 2024-01-10 02:01:03 +01:00
parent 4f2b331bb8
commit f6c6578b00
No known key found for this signature in database
GPG Key ID: DD1ABF20724CDA23
87 changed files with 301 additions and 318 deletions

View File

@ -139,16 +139,16 @@ class ActorV3Action(Handler):
path = 'actor/v3'
@staticmethod
def actorResult(result: typing.Any = None, **kwargs: typing.Any) -> dict[str, typing.Any]:
def actor_result(result: typing.Any = None, **kwargs: typing.Any) -> dict[str, typing.Any]:
return rest_result(result=result, **kwargs)
@staticmethod
def setCommsUrl(userService: UserService, ip: str, port: int, secret: str):
userService.setCommsUrl(f'https://{ip}:{port}/actor/{secret}')
def set_comms_endpoint(userService: UserService, ip: str, port: int, secret: str):
userService.set_comms_endpoint(f'https://{ip}:{port}/actor/{secret}')
@staticmethod
def actorCertResult(key: str, certificate: str, password: str) -> dict[str, typing.Any]:
return ActorV3Action.actorResult(
return ActorV3Action.actor_result(
{
'private_key': key, # To be removed on 5.0
'key': key,
@ -170,7 +170,7 @@ class ActorV3Action(Handler):
raise BlockAccess() from None
def action(self) -> dict[str, typing.Any]:
return ActorV3Action.actorResult(error='Base action invoked')
return ActorV3Action.actor_result(error='Base action invoked')
def post(self) -> dict[str, typing.Any]:
try:
@ -248,9 +248,9 @@ class Test(ActorV3Action):
# Increase failed attempts
incFailedIp(self._request)
# And return test failed
return ActorV3Action.actorResult('invalid token', error='invalid token')
return ActorV3Action.actor_result('invalid token', error='invalid token')
return ActorV3Action.actorResult('ok')
return ActorV3Action.actor_result('ok')
class Register(ActorV3Action):
@ -329,7 +329,7 @@ class Register(ActorV3Action):
actorToken = Server.objects.create(**kwargs)
return ActorV3Action.actorResult(actorToken.token) # type: ignore # actorToken is always assigned
return ActorV3Action.actor_result(actorToken.token) # type: ignore # actorToken is always assigned
class Initialize(ActorV3Action):
@ -387,7 +387,7 @@ class Initialize(ActorV3Action):
os: typing.Any,
alias_token: typing.Optional[str],
) -> dict[str, typing.Any]:
return ActorV3Action.actorResult(
return ActorV3Action.actor_result(
{
'own_token': own_token or alias_token, # Compat with old actor versions, TBR on 5.0
'token': own_token or alias_token, # New token, will be used from now onwards
@ -497,10 +497,10 @@ class BaseReadyChange(ActorV3Action):
userService.log_ip(self._params['ip'])
userServiceInstance = userService.get_instance()
userServiceInstance.set_ip(self._params['ip'])
userService.updateData(userServiceInstance)
userService.update_data(userServiceInstance)
# Store communications url also
ActorV3Action.setCommsUrl(
ActorV3Action.set_comms_endpoint(
userService,
self._params['ip'],
int(self._params['port']),
@ -578,7 +578,7 @@ class Version(ActorV3Action):
userService.actor_version = self._params['version']
userService.log_ip(self._params['ip'])
return ActorV3Action.actorResult()
return ActorV3Action.actor_result()
class Login(ActorV3Action):
@ -620,7 +620,7 @@ class Login(ActorV3Action):
logger.debug('Max idle: %s', maxIdle)
src = userService.getConnectionSource()
session_id = userService.initSession() # creates a session for every login requested
session_id = userService.start_session() # creates a session for every login requested
if osManager: # For os managed services, let's check if we honor deadline
if osManager.ignore_deadline():
@ -637,7 +637,7 @@ class Login(ActorV3Action):
raise
self.notifyService(action=NotifyActionType.LOGIN)
return ActorV3Action.actorResult(
return ActorV3Action.actor_result(
{
'ip': src.ip,
'hostname': src.hostname,
@ -664,12 +664,12 @@ class Logout(ActorV3Action):
# Close session
# For compat, we have taken '' as "all sessions"
userService.closeSession(session_id)
userService.end_session(session_id)
if userService.in_use: # If already logged out, do not add a second logout (windows does this i.e.)
osmanagers.OSManager.logged_out(userService, username)
if osManager:
if osManager.is_removableOnLogout(userService):
if osManager.is_removable_on_logout(userService):
logger.debug('Removable on logout: %s', osManager)
userService.remove()
else:
@ -692,9 +692,9 @@ class Logout(ActorV3Action):
raise
self.notifyService(NotifyActionType.LOGOUT) # Logout notification
# Result is that we have not processed the logout in fact, but notified the service
return ActorV3Action.actorResult('notified')
return ActorV3Action.actor_result('notified')
return ActorV3Action.actorResult('ok')
return ActorV3Action.actor_result('ok')
class Log(ActorV3Action):
@ -719,7 +719,7 @@ class Log(ActorV3Action):
log.LogSource.ACTOR,
)
return ActorV3Action.actorResult('ok')
return ActorV3Action.actor_result('ok')
class Ticket(ActorV3Action):
@ -741,9 +741,9 @@ class Ticket(ActorV3Action):
raise BlockAccess() from None # If too many blocks...
try:
return ActorV3Action.actorResult(TicketStore.get(self._params['ticket'], invalidate=True))
return ActorV3Action.actor_result(TicketStore.get(self._params['ticket'], invalidate=True))
except TicketStore.DoesNotExist:
return ActorV3Action.actorResult(error='Invalid ticket')
return ActorV3Action.actor_result(error='Invalid ticket')
class Unmanaged(ActorV3Action):
@ -770,7 +770,7 @@ class Unmanaged(ActorV3Action):
dbService: Service = Service.objects.get(token=self._params['token'])
service: 'services.Service' = dbService.get_instance()
except Exception:
return ActorV3Action.actorResult(error='Invalid token')
return ActorV3Action.actor_result(error='Invalid token')
# Build the possible ids and ask service if it recognizes any of it
# If not recognized, will generate anyway the certificate, but will not be saved
@ -857,7 +857,7 @@ class Notify(ActorV3Action):
elif action == NotifyActionType.DATA:
self.notifyService(action)
return ActorV3Action.actorResult('ok')
return ActorV3Action.actor_result('ok')
except UserService.DoesNotExist:
# For blocking attacks
incFailedIp(self._request) # pylint: disable=protected-access

View File

@ -258,6 +258,6 @@ class Authenticators(ModelHandler):
for user in item.users.all():
for userService in user.userServices.all():
userService.user = None # type: ignore
userService.removeOrCancel()
userService.remove_or_cancel()
item.delete()

View File

@ -104,7 +104,7 @@ class Permissions(Handler):
'entity_id': entity.uuid, # type: ignore
'entity_name': entity.name, # type: ignore
'perm': perm.permission,
'perm_name': perm.permission_as_string,
'perm_name': perm.as_str,
}
)

View File

@ -511,7 +511,7 @@ class Publications(DetailHandler):
'revision': i.revision,
'publish_date': i.publish_date,
'state': i.state,
'reason': State.is_errored(i.state) and i.get_intance().error_reason() or '',
'reason': State.is_errored(i.state) and i.get_instance().error_reason() or '',
'state_date': i.state_date,
}
for i in parent.publications.all()

View File

@ -274,7 +274,7 @@ class Users(DetailHandler):
try:
assignedUserService.user = None # type: ignore # Remove assigned user (avoid cascade deletion)
assignedUserService.save(update_fields=['user'])
assignedUserService.removeOrCancel()
assignedUserService.remove_or_cancel()
except Exception:
logger.exception('Removing user service')
try:
@ -294,7 +294,7 @@ class Users(DetailHandler):
uuid = process_uuid(item)
user = parent.users.get(uuid=process_uuid(uuid))
res = []
groups = list(user.getGroups())
groups = list(user.get_groups())
for i in get_service_pools_for_groups(groups):
res.append(
{
@ -327,7 +327,7 @@ class Users(DetailHandler):
def cleanRelated(self, parent: 'Authenticator', item: str) -> dict[str, str]:
uuid = process_uuid(item)
user = parent.users.get(uuid=process_uuid(uuid))
user.cleanRelated()
user.clean_related_data()
return {'status': 'ok'}

View File

@ -347,7 +347,7 @@ class BaseModelHandler(Handler):
if isinstance(item, ManagedObjectModel):
i = item.get_instance()
i.initGui() # Defaults & stuff
res.update(i.valuesDict())
res.update(i.dict_of_values())
return res
# Exceptions

View File

@ -277,7 +277,7 @@ class RegexLdap(auths.Authenticator):
def mfa_identifier(self, username: str) -> str:
return self.storage.getPickle(self.mfaStorageKey(username)) or ''
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
return {
'host': self._host,
'port': self._port,

View File

@ -241,7 +241,7 @@ class SimpleLDAPAuthenticator(auths.Authenticator):
self._verifySsl = gui.toBool(values['verifySsl'])
self._certificate = values['certificate']
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
return {
'host': self._host,
'port': self._port,

View File

@ -131,8 +131,8 @@ def getRootUser() -> models.User:
)
user.manager = models.Authenticator() # type: ignore
# Fake overwrite some methods, a bit cheating? maybe? :)
user.getGroups = lambda: [] # type: ignore
user.updateLastAccess = lambda: None # type: ignore
user.get_groups = lambda: [] # type: ignore
user.update_last_access = lambda: None # type: ignore
# Override logout method to do nothing for this user
user.logout = lambda request: types.auth.SUCCESS_AUTH # type: ignore
return user
@ -175,7 +175,7 @@ def web_login_required(
return HttpResponseRedirect(reverse('page.login'))
if admin in (True, 'admin'):
if request.user.isStaff() is False or (
if request.user.is_staff() is False or (
admin == 'admin' and not request.user.is_admin
):
return HttpResponseForbidden(_('Forbidden'))
@ -424,7 +424,7 @@ def web_login(
# If for any reason the "uds" cookie is removed, recreated it
cookie = getUDSCookie(request, response)
user.updateLastAccess()
user.update_last_access()
request.authorized = (
False # For now, we don't know if the user is authorized until MFA is checked
)

View File

@ -97,7 +97,7 @@ class User:
else:
# From db
usr = DBUser.objects.get(pk=self._db_user.id) # @UndefinedVariable
self._groups = [Group(g) for g in usr.getGroups()]
self._groups = [Group(g) for g in usr.get_groups()]
return self._groups
def manager(self) -> 'AuthenticatorInstance':

View File

@ -173,7 +173,7 @@ class Scheduler:
job.last_execution = now
job.save(update_fields=['state', 'owner_server', 'last_execution'])
jobInstance = job.get_intance()
jobInstance = job.get_instance()
if jobInstance is None:
logger.error('Job instance can\'t be resolved for %s, removing it', job)

View File

@ -96,8 +96,8 @@ class NotificationsManager(metaclass=singleton.Singleton):
# Store the notification on local persistent storage
# Will be processed by UDS backend
try:
with Notification.atomicPersistent():
with Notification.atomic_persistent():
notify = Notification(group=group, identificator=identificator, level=level, message=message)
notify.savePersistent()
notify.save_persistent()
except Exception:
logger.info('Error saving notification %s, %s, %s, %s', group, identificator, level, message)

View File

@ -78,7 +78,7 @@ class PublicationOldMachinesCleaner(DelayedTask):
now = sql_datetime()
activePub: typing.Optional[
ServicePoolPublication
] = servicePoolPub.deployed_service.activePublication()
] = servicePoolPub.deployed_service.active_publication()
servicePoolPub.deployed_service.userServices.filter(in_use=True).update(
in_use=False, state_date=now
)
@ -115,7 +115,7 @@ class PublicationLauncher(DelayedTask):
return
servicePoolPub.state = State.PREPARING
servicePoolPub.save()
pi = servicePoolPub.get_intance()
pi = servicePoolPub.get_instance()
state = pi.publish()
servicePool: ServicePool = servicePoolPub.deployed_service
servicePool.current_pub_revision += 1
@ -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.get_intance()
publicationInstance = publication.get_instance()
logger.debug(
"publication instance class: %s", publicationInstance.__class__
)
@ -360,7 +360,7 @@ class PublicationManager(metaclass=singleton.Singleton):
return publication
try:
pubInstance = publication.get_intance()
pubInstance = publication.get_instance()
state = pubInstance.cancel()
publication.set_state(State.CANCELING)
PublicationFinishChecker.state_updater(
@ -387,7 +387,7 @@ class PublicationManager(metaclass=singleton.Singleton):
_('Can\'t unpublish publications with services in process')
)
try:
pubInstance = servicePoolPub.get_intance()
pubInstance = servicePoolPub.get_instance()
state = pubInstance.destroy()
servicePoolPub.set_state(State.REMOVING)
PublicationFinishChecker.state_updater(

View File

@ -97,7 +97,7 @@ def process_login(server: 'models.Server', data: dict[str, typing.Any]) -> typin
# Get the source of the connection and a new session id
src = userService.getConnectionSource()
session_id = userService.initSession() # creates a session for every login requested
session_id = userService.start_session() # creates a session for every login requested
osManager: typing.Optional[osmanagers.OSManager] = userService.getOsManagerInstance()
maxIdle = osManager.max_idle() if osManager else None
@ -134,12 +134,12 @@ def process_logout(server: 'models.Server', data: dict[str, typing.Any]) -> typi
userService = models.UserService.objects.get(uuid=data['userservice_uuid'])
session_id = data['userservice_uuid']
userService.closeSession(session_id)
userService.end_session(session_id)
if userService.in_use: # If already logged out, do not add a second logout (windows does this i.e.)
osmanagers.OSManager.logged_out(userService, data['username'])
osManager: typing.Optional[osmanagers.OSManager] = userService.getOsManagerInstance()
if not osManager or osManager.is_removableOnLogout(userService):
if not osManager or osManager.is_removable_on_logout(userService):
logger.debug('Removable on logout: %s', osManager)
userService.remove()

View File

@ -204,7 +204,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
raise ServiceNotReadyError()
if servicePool.service.get_type().publication_type is not None:
publication = servicePool.activePublication()
publication = servicePool.active_publication()
if publication:
assigned = self._create_assigned_user_service_at_db(publication, user)
operationsLogger.info(
@ -241,7 +241,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
raise Exception('This service type cannot assign asignables')
if servicePool.service.get_type().publication_type is not None:
publication = servicePool.activePublication()
publication = servicePool.active_publication()
if publication:
assigned = self._create_assigned_user_service_at_db(publication, user)
operationsLogger.info(
@ -579,7 +579,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
logger.debug('State: %s', state)
if state == State.FINISHED:
userService.updateData(userServiceInstance)
userService.update_data(userServiceInstance)
return True
userService.set_state(State.PREPARING)
@ -637,11 +637,11 @@ class UserServiceManager(metaclass=singleton.Singleton):
remove = False
with transaction.atomic():
userService = UserService.objects.select_for_update().get(id=userService.id)
activePublication = userService.deployed_service.activePublication()
active_publication = userService.deployed_service.active_publication()
if (
userService.publication
and activePublication
and userService.publication.id != activePublication.id
and active_publication
and userService.publication.id != active_publication.id
):
logger.debug(
'Old revision of user service, marking as removable: %s',
@ -659,7 +659,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
state = userServiceInstance.process_ready_from_os_manager(data)
logger.debug('State: %s', state)
if state == State.FINISHED:
userService.updateData(userServiceInstance)
userService.update_data(userServiceInstance)
logger.debug('Service is now ready')
elif userService.state in (
State.USABLE,
@ -740,7 +740,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
# Early log of "access try" so we can imagine what is going on
userService.setConnectionSource(types.connections.ConnectionSource(src_ip, client_hostname or src_ip))
if userService.isInMaintenance():
if userService.is_in_maintenance():
raise ServiceInMaintenanceMode()
if not userService.deployed_service.is_access_allowed():
@ -783,7 +783,7 @@ class UserServiceManager(metaclass=singleton.Singleton):
serviceNotReadyCode = 0x0001
ip = 'unknown'
# Test if the service is ready
if userService.isReady():
if userService.is_ready():
serviceNotReadyCode = 0x0002
log.log(
userService,

View File

@ -72,7 +72,7 @@ class StateUpdater:
if newState:
self.user_service.set_state(newState)
self.user_service.updateData(self.user_service_instance)
self.user_service.update_data(self.user_service_instance)
def log_ip(self):
ip = self.user_service_instance.get_ip()

View File

@ -80,7 +80,7 @@ class MessageProcessorThread(BaseThread):
not_before = sql_datetime() - datetime.timedelta(
seconds=DO_NOT_REPEAT.getInt()
)
for n in Notification.getPersistentQuerySet().all():
for n in Notification.get_persistent_queryset().all():
# If there are any other notification simmilar to this on default db, skip it
# Simmilar means that group, identificator and message are already been logged less than DO_NOT_REPEAT seconds ago
# from last time
@ -91,7 +91,7 @@ class MessageProcessorThread(BaseThread):
stamp__gt=not_before,
).exists():
# Remove it from the persistent db
n.deletePersistent()
n.delete_persistent()
continue
# Try to insert into Main DB
notify = (
@ -105,14 +105,14 @@ class MessageProcessorThread(BaseThread):
n.save(using='default')
# Delete from Persistent DB, first restore PK
n.pk = pk
n.deletePersistent()
n.delete_persistent()
logger.debug('Saved notification %s to main DB', n)
except Exception:
# try notificators, but keep on db with error
# Restore pk, and save locally so we can try again
n.pk = pk
try:
Notification.savePersistent(n)
Notification.save_persistent(n)
except Exception:
logger.error('Error saving notification %s to persistent DB', n)
continue

View File

@ -89,7 +89,7 @@ class Module(UserInterface, Environmentable, Serializable):
Anyway, if you override this method, you must also override previous one
* UserInterface Methods:
* :py:meth:`from from uds.core.ui.valuesDict`
* :py:meth:`from from uds.core.ui.dict_of_values`
This method, by default, provides the values contained in the form fields. If you don't override the marshal and
unmarshal, this method should be fine as is for you also.
@ -240,7 +240,7 @@ class Module(UserInterface, Environmentable, Serializable):
that contains the form data requested from user.
If you override marshal, unmarshal and inherited UserInterface method
valuesDict, you must also take account of values (dict) provided at the
dict_of_values, you must also take account of values (dict) provided at the
__init__ method of your class.
"""
UserInterface.__init__(self, values)

View File

@ -163,7 +163,7 @@ class OSManager(Module):
This function can update userService values. Normal operation will be remove machines if this state is not valid
"""
def is_removableOnLogout(self, userService: 'UserService') -> bool: # pylint: disable=unused-argument
def is_removable_on_logout(self, userService: 'UserService') -> bool: # pylint: disable=unused-argument
"""
If returns true, when actor notifies "logout", UDS will mark service for removal
can be overriden
@ -239,7 +239,7 @@ class OSManager(Module):
userService.properties['last_username'] = userName or 'unknown' # Store it for convenience
userServiceInstance = userService.get_instance()
userServiceInstance.user_logged_in(userName or 'unknown')
userService.updateData(userServiceInstance)
userService.update_data(userServiceInstance)
serviceIp = userServiceInstance.get_ip()
@ -303,7 +303,7 @@ class OSManager(Module):
userService.setInUse(False)
userServiceInstance = userService.get_instance()
userServiceInstance.user_logged_out(userName or 'unknown')
userService.updateData(userServiceInstance)
userService.update_data(userServiceInstance)
serviceIp = userServiceInstance.get_ip()

View File

@ -167,7 +167,7 @@ class Report(UserInterface):
that contains the form data requested from user.
If you override marshal, unmarshal and inherited UserInterface method
valuesDict, you must also take account of values (dict) provided at the
dict_of_values, you must also take account of values (dict) provided at the
__init__ method of your class.
"""
#

View File

@ -1356,7 +1356,7 @@ class UserInterface(metaclass=UserInterfaceType):
of this posibility in a near version...
"""
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
"""
Returns own data needed for user interaction as a dict of key-names ->
values. The values returned must be strings.
@ -1370,7 +1370,7 @@ class UserInterface(metaclass=UserInterfaceType):
return { 'host' : self.host, 'port' : self.port }
(Just the reverse of :py:meth:`.__init__`, __init__ receives this
dict, valuesDict must return the dict)
dict, dict_of_values must return the dict)
Names must coincide with fields declared.

View File

@ -50,13 +50,13 @@ logger = logging.getLogger(__name__)
def clean(obj: 'Model') -> None:
models.Permissions.cleanPermissions(objtype.ObjectType.from_model(obj).type, obj.pk)
models.Permissions.clean_permissions(objtype.ObjectType.from_model(obj), obj.pk)
def getPermissions(obj: 'Model') -> list[models.Permissions]:
return list(
models.Permissions.enumeratePermissions(
object_type=objtype.ObjectType.from_model(obj).type, object_id=obj.pk
models.Permissions.enumerate_permissions(
object_type=objtype.ObjectType.from_model(obj), object_id=obj.pk
)
)
@ -71,14 +71,14 @@ def effective_permissions(
# Just check permissions for staff members
# root means for "object type" not for an object
if for_type is False:
return models.Permissions.getPermissions(
return models.Permissions.get_permissions(
object_type=objtype.ObjectType.from_model(obj),
user=user,
object_id=obj.pk,
groups=user.groups.all(),
)
return models.Permissions.getPermissions(
return models.Permissions.get_permissions(
object_type=objtype.ObjectType.from_model(obj),
user=user,
groups=user.groups.all(),
@ -93,9 +93,9 @@ def add_user_permission(
permission: PermissionType = PermissionType.READ,
):
# Some permissions added to some object types needs at least READ_PERMISSION on parent
models.Permissions.addPermission(
models.Permissions.add_permission(
user=user,
object_type=objtype.ObjectType.from_model(obj).type,
object_type=objtype.ObjectType.from_model(obj),
object_id=obj.pk,
permission=permission,
)
@ -106,9 +106,9 @@ def add_group_permission(
obj: 'Model',
permission: PermissionType = PermissionType.READ,
):
models.Permissions.addPermission(
models.Permissions.add_permission(
group=group,
object_type=objtype.ObjectType.from_model(obj).type,
object_type=objtype.ObjectType.from_model(obj),
object_id=obj.pk,
permission=permission,
)

View File

@ -121,4 +121,4 @@ class HangedCleaner(Job):
log.LogLevel.ERROR,
f'Removing user service {us.friendly_name} because it seems to be hanged'
)
us.releaseOrCancel()
us.release_or_cancel()

View File

@ -134,7 +134,7 @@ class DeployedServiceRemover(Job):
if servicePool.userServices.all().count() == 0:
try:
logger.debug('All services removed, checking active publication')
if servicePool.activePublication() is not None:
if servicePool.active_publication() is not None:
logger.debug('Active publication found, unpublishing it')
servicePool.unpublish()
else:

View File

@ -101,7 +101,7 @@ class ServiceCacheUpdater(Job):
)
continue
if servicePool.activePublication() is None and spServiceInstance.publication_type is not None:
if servicePool.active_publication() is None and spServiceInstance.publication_type is not None:
logger.debug(
'Skipping. %s Needs publication but do not have one',
servicePool.name,
@ -232,12 +232,12 @@ class ServiceCacheUpdater(Job):
break
if valid is not None:
valid.moveToLevel(services.UserService.L1_CACHE)
valid.move_to_level(services.UserService.L1_CACHE)
return
try:
# This has a velid publication, or it will not be here
UserServiceManager().create_cache_for(
typing.cast(ServicePoolPublication, servicePool.activePublication()),
typing.cast(ServicePoolPublication, servicePool.active_publication()),
services.UserService.L1_CACHE,
)
except MaxServicesReachedError:
@ -273,7 +273,7 @@ class ServiceCacheUpdater(Job):
try:
# This has a velid publication, or it will not be here
UserServiceManager().create_cache_for(
typing.cast(ServicePoolPublication, servicePool.activePublication()),
typing.cast(ServicePoolPublication, servicePool.active_publication()),
services.UserService.L2_CACHE,
)
except MaxServicesReachedError:
@ -321,11 +321,11 @@ class ServiceCacheUpdater(Job):
break
if valid is not None:
valid.moveToLevel(services.UserService.L2_CACHE)
valid.move_to_level(services.UserService.L2_CACHE)
return
cache = cacheItems[0]
cache.removeOrCancel()
cache.remove_or_cancel()
def reduceL2Cache(
self,
@ -343,7 +343,7 @@ class ServiceCacheUpdater(Job):
)
# TODO: Look first for non finished cache items and cancel them?
cache: UserService = cacheItems[0]
cache.removeOrCancel()
cache.remove_or_cancel()
def run(self) -> None:
logger.debug('Starting cache checking')

View File

@ -57,7 +57,7 @@ def getSerializedFromManagedObject(
try:
obj = mod.get_instance()
gui = {i['name']: i['gui']['type'] for i in obj.guiDescription()}
values = obj.valuesDict()
values = obj.dict_of_values()
# Remove password fields
for k, v in gui.items():
if v == 'password':

View File

@ -160,7 +160,7 @@ def _process_request(request: 'ExtendedHttpRequest') -> typing.Optional['HttpRes
now
+ datetime.timedelta(
seconds=GlobalConfig.SESSION_DURATION_ADMIN.getInt()
if request.user.isStaff()
if request.user.is_staff()
else GlobalConfig.SESSION_DURATION_USER.getInt()
)
).isoformat() # store as ISO format, str, json serilizable

View File

@ -59,7 +59,7 @@ class Account(UUIDModel, TaggingMixin):
# objects: 'models.manager.Manager["Account"]'
usages: 'models.manager.RelatedManager[AccountUsage]'
def startUsageAccounting(self, userService: 'UserService') -> typing.Optional['AccountUsage']:
def start_accounting(self, userService: 'UserService') -> typing.Optional['AccountUsage']:
if hasattr(userService, 'accounting'): # Already has an account
return None
@ -82,7 +82,7 @@ class Account(UUIDModel, TaggingMixin):
end=start,
)
def stopUsageAccounting(self, userService: 'UserService') -> typing.Optional['AccountUsage']:
def stop_accounting(self, userService: 'UserService') -> typing.Optional['AccountUsage']:
# if one to one does not exists, attr is not there
if not hasattr(userService, 'accounting'):
return None

View File

@ -89,7 +89,7 @@ class Image(UUIDModel):
app_label = 'uds'
@staticmethod
def resizeAndConvert(image: PIL.Image.Image, size: tuple[int, int]) -> tuple[int, int, bytes]:
def to_resized_png(image: PIL.Image.Image, size: tuple[int, int]) -> tuple[int, int, bytes]:
"""
Resizes an image to the given size
"""
@ -99,7 +99,7 @@ class Image(UUIDModel):
return (image.width, image.height, output.getvalue())
@staticmethod
def prepareForDb(data: bytes) -> tuple[int, int, bytes]:
def prepare_for_db(data: bytes) -> tuple[int, int, bytes]:
try:
stream = io.BytesIO(data)
image = PIL.Image.open(stream)
@ -107,7 +107,7 @@ class Image(UUIDModel):
image = PIL.Image.new('RGBA', Image.MAX_IMAGE_SIZE)
# Max image size, keeping aspect and using antialias
return Image.resizeAndConvert(image, Image.MAX_IMAGE_SIZE)
return Image.to_resized_png(image, Image.MAX_IMAGE_SIZE)
@property
def data64(self) -> str:
@ -164,7 +164,7 @@ class Image(UUIDModel):
else:
raise ValueError('Invalid image type')
self.width, self.height, self.data = Image.prepareForDb(data)
self.width, self.height, self.data = Image.prepare_for_db(data)
# Setup thumbnail
with io.BytesIO(data) as input:
@ -191,10 +191,10 @@ class Image(UUIDModel):
"""
return len(self.data)
def imageResponse(self) -> HttpResponse:
def image_as_response(self) -> HttpResponse:
return HttpResponse(self.data, content_type='image/png')
def thumbnailResponse(self) -> HttpResponse:
def thumbnail_as_response(self) -> HttpResponse:
return HttpResponse(self.thumb, content_type='image/png')
def save(self, *args, **kwargs):

View File

@ -73,7 +73,7 @@ class Log(models.Model):
app_label = 'uds'
@property
def level_str(self) -> str:
def level_as_str(self) -> str:
# pylint: disable=import-outside-toplevel
from uds.core.util.log import LogLevel

View File

@ -126,7 +126,7 @@ class MetaPool(UUIDModel, TaggingMixin): # type: ignore
return False
return True
def isInMaintenance(self) -> bool:
def is_in_maintenance(self) -> bool:
"""If a Metapool is in maintenance (that is, all its pools are in maintenance)
Returns:

View File

@ -99,7 +99,7 @@ class Network(UUIDModel, TaggingMixin): # type: ignore
return int(number, 16)
@staticmethod
def networksFor(ip: str) -> collections.abc.Iterable['Network']:
def get_networks_for_ip(ip: str) -> collections.abc.Iterable['Network']:
"""
Returns the networks that are valid for specified ip in dotted quad (xxx.xxx.xxx.xxx)
"""
@ -195,6 +195,7 @@ class Network(UUIDModel, TaggingMixin): # type: ignore
ipInt, version = net.ip_to_long(ip)
return self.net_start <= ipInt <= self.net_end and self.version == version
# utility method to allow "in" operator
__contains__ = contains
def save(self, *args, **kwargs) -> None:

View File

@ -70,17 +70,17 @@ class Notification(models.Model):
app_label = 'uds'
@staticmethod
def getPersistentQuerySet() -> 'models.QuerySet[Notification]':
def get_persistent_queryset() -> 'models.QuerySet[Notification]':
return Notification.objects.using('persistent')
def savePersistent(self) -> None:
def save_persistent(self) -> None:
self.save(using='persistent')
def deletePersistent(self) -> None:
def delete_persistent(self) -> None:
self.delete(using='persistent')
@staticmethod
def atomicPersistent() -> 'transaction.Atomic':
def atomic_persistent() -> 'transaction.Atomic':
return transaction.atomic(using='persistent')

View File

@ -64,9 +64,7 @@ class OSManager(ManagedObjectModel, TaggingMixin):
ordering = ('name',)
app_label = 'uds'
def get_instance(
self, values: typing.Optional[dict[str, str]] = None
) -> 'osmanagers.OSManager':
def get_instance(self, values: typing.Optional[dict[str, str]] = None) -> 'osmanagers.OSManager':
return typing.cast('osmanagers.OSManager', super().get_instance(values=values))
def get_type(self) -> type['osmanagers.OSManager']:
@ -101,9 +99,6 @@ class OSManager(ManagedObjectModel, TaggingMixin):
self.delete()
return True
def __str__(self) -> str:
return f'{self.name} of type {self.data_type} (id:{self.id})'
@staticmethod
def pre_delete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
@ -116,9 +111,7 @@ class OSManager(ManagedObjectModel, TaggingMixin):
"""
to_delete: 'OSManager' = kwargs['instance']
if to_delete.deployedServices.count() > 0:
raise IntegrityError(
'Can\'t remove os managers with assigned deployed services'
)
raise IntegrityError('Can\'t remove os managers with assigned deployed services')
# Only tries to get instance if data is not empty
if to_delete.data != '':
s = to_delete.get_instance()
@ -127,6 +120,9 @@ class OSManager(ManagedObjectModel, TaggingMixin):
logger.debug('Before delete os manager %s', to_delete)
def __str__(self) -> str:
return f'{self.name} of type {self.data_type} (id:{self.id})'
# : Connects a pre deletion signal to OS Manager
models.signals.pre_delete.connect(OSManager.pre_delete, sender=OSManager)

View File

@ -90,37 +90,30 @@ class Permissions(UUIDModel):
# objects: 'models.manager.Manager[Permissions]'
@staticmethod
def addPermission(**kwargs) -> 'Permissions':
def add_permission(
*,
user: typing.Optional['User'] = None,
group: typing.Optional['Group'] = None,
object_type: 'objtype.ObjectType',
object_id: typing.Optional[int] = None,
permission: PermissionType = PermissionType.NONE,
) -> 'Permissions':
"""
Adds a permission to an object and an user or group
"""
user = kwargs.get('user', None)
group = kwargs.get('group', None)
if user is not None and group is not None:
if user and group:
raise Exception('Use only user or group, but not both')
if user is None and group is None:
raise Exception('Must at least indicate user or group')
object_type = kwargs.get('object_type', None)
if object_type is None:
raise Exception('At least an object type is required')
object_id = kwargs.get('object_id', None)
permission = kwargs.get('permission', PermissionType.NONE)
if user is not None:
q = Q(user=user)
else:
q = Q(group=group)
try:
existing: Permissions = Permissions.objects.filter(
q, object_type=object_type, object_id=object_id
)[
existing: Permissions = Permissions.objects.filter(q, object_type=object_type.type, object_id=object_id)[
0 # type: ignore # Slicing is not supported by pylance right now
]
existing.permission = permission
@ -132,13 +125,13 @@ class Permissions(UUIDModel):
ends=None,
user=user,
group=group,
object_type=object_type,
object_type=object_type.type,
object_id=object_id,
permission=permission,
)
@staticmethod
def getPermissions(
def get_permissions(
object_type: 'objtype.ObjectType',
object_id: typing.Optional[int] = None,
user: typing.Optional['User'] = None,
@ -174,28 +167,35 @@ class Permissions(UUIDModel):
return PermissionType.NONE
@staticmethod
def enumeratePermissions(object_type, object_id) -> 'models.QuerySet[Permissions]':
def enumerate_permissions(
object_type: 'objtype.ObjectType', object_id: int
) -> 'models.QuerySet[Permissions]':
"""
Get users permissions over object
"""
return Permissions.objects.filter(object_type=object_type, object_id=object_id)
return Permissions.objects.filter(object_type=object_type.type, object_id=object_id)
@staticmethod
def cleanPermissions(object_type, object_id) -> None:
Permissions.objects.filter(
object_type=object_type, object_id=object_id
).delete()
def clean_permissions(
object_type: 'objtype.ObjectType',
object_id: int,
user: typing.Optional['User'] = None,
group: typing.Optional['Group'] = None,
) -> None:
if user and group: # Using both is same as using none
user = None
group = None
if not user and not group:
q = Q()
elif user:
q = Q(user=user)
else:
q = Q(group=group)
@staticmethod
def cleanUserPermissions(user) -> None:
Permissions.objects.filter(user=user).delete()
@staticmethod
def cleanGroupPermissions(group) -> None:
Permissions.objects.filter(group=group).delete()
Permissions.objects.filter(Q(object_type=object_type.type), Q(object_id=object_id), q).delete()
@property
def permission_as_string(self) -> str:
def as_str(self) -> str:
return PermissionType(self.permission).as_str()
def __str__(self) -> str:

View File

@ -95,7 +95,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
return self.maintenance_mode
@staticmethod
def typeFilter(type_: str) -> collections.abc.Iterable['Provider']:
def type_filter(type_: str) -> collections.abc.Iterable['Provider']:
for i in Provider.objects.filter(data_type=type):
yield i

View File

@ -89,7 +89,7 @@ class Scheduler(models.Model):
"""
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore # pylint: disable=no-member
def get_intance(self) -> typing.Optional[jobs.Job]:
def get_instance(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

View File

@ -162,7 +162,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
return prov.get_service_by_type(self.data_type) or services.Service
@property
def maxServicesCountType(self) -> ServicesCountingType:
def services_counting_type(self) -> ServicesCountingType:
return ServicesCountingType.from_int(self.max_services_count_type)
def is_in_maintenance(self) -> bool:
@ -190,13 +190,13 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
def old_max_accounting_method(self) -> bool:
# Compatibility with old accounting method
# Counts only "creating and running" instances for max limit checking
return self.maxServicesCountType == ServicesCountingType.STANDARD
return self.services_counting_type == ServicesCountingType.STANDARD
@property
def new_max_accounting_method(self) -> bool:
# Compatibility with new accounting method,
# Counts EVERYTHING for max limit checking
return self.maxServicesCountType == ServicesCountingType.CONSERVATIVE
return self.services_counting_type == ServicesCountingType.CONSERVATIVE
def __str__(self) -> str:
return f'{self.name} of type {self.data_type} (id:{self.id})'

View File

@ -166,7 +166,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
"""
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore
def activePublication(self) -> typing.Optional['ServicePoolPublication']:
def active_publication(self) -> typing.Optional['ServicePoolPublication']:
"""
Returns the current valid publication for this deployed service.
@ -180,7 +180,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
except Exception:
return None
def transformsUserOrPasswordForService(self) -> bool:
def transforms_user_or_password_for_service(self) -> bool:
if self.osmanager:
return self.osmanager.get_type().transforms_user_or_password_for_service()
return False
@ -282,7 +282,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
)
def when_will_be_replaced(self, forUser: 'User') -> typing.Optional[datetime]:
activePub: typing.Optional['ServicePoolPublication'] = self.activePublication()
activePub: typing.Optional['ServicePoolPublication'] = self.active_publication()
# If no publication or current revision, it's not going to be replaced
if activePub is None:
return None
@ -472,7 +472,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
raises an IvalidServiceException if check fails
"""
if (
self.activePublication() is None
self.active_publication() is None
and self.service
and self.service.get_type().publication_type is not None
):
@ -502,7 +502,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
logger.debug('User: %s', user.id)
logger.debug('ServicePool: %s', self.id)
self.validate_groups(user.getGroups())
self.validate_groups(user.get_groups())
self.validate_publication()
@staticmethod
@ -599,7 +599,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
It checks that there is an active publication, and then redirects the request to the publication itself
"""
pub = self.activePublication()
pub = self.active_publication()
if pub:
pub.unpublish()

View File

@ -45,6 +45,7 @@ from .image import Image
logger = logging.getLogger(__name__)
# pylint: disable=no-member
class ServicePoolGroup(UUIDModel):
"""
@ -73,9 +74,6 @@ class ServicePoolGroup(UUIDModel):
db_table = 'uds__pools_groups'
app_label = 'uds'
def __str__(self) -> str:
return f'Service Pool group {self.name}({self.comments}): {self.image.name if self.image else ""}'
@property
def as_dict(self) -> collections.abc.MutableMapping[str, typing.Any]:
return {
@ -98,3 +96,6 @@ class ServicePoolGroup(UUIDModel):
[ServicePoolGroup]: Default ServicePoolGroup
"""
return ServicePoolGroup(uuid='', name=_('General'), comments='', priority=-10000)
def __str__(self) -> str:
return f'Service Pool group {self.name}({self.comments}): {self.image.name if self.image else ""}'

View File

@ -115,7 +115,7 @@ class ServicePoolPublication(UUIDModel):
"""
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore
def get_intance(self) -> 'services.Publication':
def get_instance(self) -> 'services.Publication':
"""
Instantiates the object this record contains.

View File

@ -104,7 +104,7 @@ class User(UUIDModel, properties.PropertiesMixin):
def get_owner_id_and_type(self) -> tuple[str, str]:
return self.uuid, 'user'
def getUsernameForAuth(self) -> str:
def get_username_for_auth(self) -> str:
"""
Return the username transformed for authentication.
This transformation is used for transports only, not for transforming
@ -129,13 +129,13 @@ class User(UUIDModel, properties.PropertiesMixin):
"""
return self.manager.get_instance()
def isStaff(self) -> bool:
def is_staff(self) -> bool:
"""
Return true if this user is admin or staff member
"""
return self.staff_member or self.is_admin
def updateLastAccess(self) -> None:
def update_last_access(self) -> None:
"""
Updates the last access for this user with the current time of the sql server
"""
@ -149,7 +149,7 @@ class User(UUIDModel, properties.PropertiesMixin):
"""
return self.get_manager().logout(request, self.name)
def getGroups(self) -> typing.Generator['Group', None, None]:
def get_groups(self) -> typing.Generator['Group', None, None]:
"""
returns the groups (and metagroups) this user belongs to
"""
@ -192,35 +192,14 @@ class User(UUIDModel, properties.PropertiesMixin):
# This group matches
yield g
# Get custom data
def getCustomData(self, key: str) -> typing.Optional[str]:
"""
Returns the custom data for this user for the provided key.
Usually custom data will be associated with transports, but can be custom data registered by ANY module.
Args:
key: key of the custom data to get
Returns:
The custom data for the key specified as a string (can be empty if key is not found).
If the key exists, the custom data will always contain something, but may be the values are the default ones.
"""
with storage.StorageAccess('manager' + str(self.manager.uuid)) as store:
return store[str(self.uuid) + '_' + key]
def __str__(self):
return f'{self.pretty_name} (id:{self.id})'
def cleanRelated(self) -> None:
def clean_related_data(self) -> None:
"""
Cleans up all related external data, such as mfa data, etc
"""
# If has mfa, remove related data
# If has mfa, remove related data
if self.manager.mfa:
self.manager.mfa.get_instance().reset_data(mfas.MFA.get_user_id(self))
@ -241,7 +220,7 @@ class User(UUIDModel, properties.PropertiesMixin):
to_delete.get_manager().remove_user(to_delete.name)
# If has mfa, remove related data
to_delete.cleanRelated()
to_delete.clean_related_data()
# Remove related stored values
with storage.StorageAccess('manager' + str(to_delete.manager.uuid)) as store:

View File

@ -42,6 +42,7 @@ from uds.core.environment import Environment
from uds.core.util import log, unique, properties
from uds.core.util.model import sql_datetime
from uds.core.util.state import State
from uds.models import service_pool
from uds.models.service_pool import ServicePool
from uds.models.service_pool_publication import ServicePoolPublication
from uds.models.user import User
@ -124,6 +125,11 @@ class UserService(UUIDModel, properties.PropertiesMixin):
models.Index(fields=['deployed_service', 'cache_level', 'state']),
]
# Helper to allow new names
@property
def service_pool(self) -> 'ServicePool':
return self.deployed_service
# For properties
def get_owner_id_and_type(self) -> tuple[str, str]:
return self.uuid, 'userservice'
@ -140,7 +146,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
"""
Returns True if this service is to be removed
"""
return self.properties.get('destroy_after', False) in ('y', True)
return self.properties.get('destroy_after', False) in ('y', True) # Compare to str to keep compatibility with old values
@destroy_after.setter
def destroy_after(self, value: bool) -> None:
@ -207,7 +213,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
publicationInstance = None
try: # We may have deleted publication...
if self.publication is not None:
publicationInstance = self.publication.get_intance()
publicationInstance = self.publication.get_instance()
except Exception:
# The publication to witch this item points to, does not exists
self.publication = None # type: ignore
@ -238,7 +244,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
)
return us
def updateData(self, userServiceInstance: 'services.UserService'):
def update_data(self, userServiceInstance: 'services.UserService'):
"""
Updates the data field with the serialized :py:class:uds.core.services.UserDeployment
@ -250,14 +256,14 @@ class UserService(UUIDModel, properties.PropertiesMixin):
self.data = userServiceInstance.serialize()
self.save(update_fields=['data'])
def getName(self) -> str:
def get_name(self) -> str:
"""
Returns the name of the user deployed service
"""
if self.friendly_name == '':
si = self.get_instance()
self.friendly_name = si.get_name()
self.updateData(si)
self.update_data(si)
return self.friendly_name
@ -268,7 +274,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
if self.unique_id == '':
si = self.get_instance()
self.unique_id = si.get_unique_id()
self.updateData(si)
self.update_data(si)
return self.unique_id
def storeValue(self, name: str, value: str) -> None:
@ -356,7 +362,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
"""
If the os manager changes the username or the password, this will return True
"""
return self.deployed_service.transformsUserOrPasswordForService()
return self.deployed_service.transforms_user_or_password_for_service()
def process_user_password(self, username: str, password: str) -> tuple[str, str]:
"""
@ -446,15 +452,15 @@ class UserService(UUIDModel, properties.PropertiesMixin):
# Start/stop accounting
if inUse:
self.startUsageAccounting()
self.start_accounting()
else:
self.stopUsageAccounting()
self.stop_accounting()
if not inUse: # Service released, check y we should mark it for removal
# If our publication is not current, mark this for removal
UserServiceManager().check_for_removal(self)
def startUsageAccounting(self) -> None:
def start_accounting(self) -> None:
# 1.- If do not have any account associated, do nothing
# 2.- If called but already accounting, do nothing
# 3.- If called and not accounting, start accounting
@ -462,18 +468,18 @@ class UserService(UUIDModel, properties.PropertiesMixin):
if self.deployed_service.account is None or hasattr(self, 'accounting'):
return
self.deployed_service.account.startUsageAccounting(self)
self.deployed_service.account.start_accounting(self)
def stopUsageAccounting(self) -> None:
def stop_accounting(self) -> None:
# 1.- If do not have any accounter associated, do nothing
# 2.- If called but not accounting, do nothing
# 3.- If called and accounting, stop accounting
if self.deployed_service.account is None or hasattr(self, 'accounting') is False:
return
self.deployed_service.account.stopUsageAccounting(self)
self.deployed_service.account.stop_accounting(self)
def initSession(self) -> str:
def start_session(self) -> str:
"""
Starts a new session for this user deployed service.
Returns the session id
@ -481,15 +487,15 @@ class UserService(UUIDModel, properties.PropertiesMixin):
session = self.sessions.create()
return session.session_id
def closeSession(self, sessionId: str) -> None:
if sessionId == '':
def end_session(self, session_id: str) -> None:
if session_id == '':
# Close all sessions
for session in self.sessions.all():
session.close()
else:
# Close a specific session
try:
session = self.sessions.get(session_id=sessionId)
session = self.sessions.get(session_id=session_id)
session.close()
except Exception: # Does not exists, log it and ignore it
logger.warning('Session %s does not exists for user deployed service', self.id)
@ -506,7 +512,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
"""
return State.is_preparing(self.state)
def isReady(self) -> bool:
def is_ready(self) -> bool:
"""
Returns if this service is ready (not preparing or marked for removal)
"""
@ -516,7 +522,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
# Call to isReady of the instance
return UserServiceManager().is_ready(self)
def isInMaintenance(self) -> bool:
def is_in_maintenance(self) -> bool:
return self.deployed_service.is_in_maintenance()
def remove(self) -> None:
@ -540,7 +546,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
UserServiceManager().cancel(self)
def removeOrCancel(self) -> None:
def remove_or_cancel(self) -> None:
"""
Marks for removal or cancels it, depending on state
"""
@ -549,13 +555,13 @@ class UserService(UUIDModel, properties.PropertiesMixin):
else:
self.cancel()
def releaseOrCancel(self) -> None:
def release_or_cancel(self) -> None:
"""
A much more convenient method name that "removeOrCancel" (i think :) )
"""
self.removeOrCancel()
self.remove_or_cancel()
def moveToLevel(self, cacheLevel: int) -> None:
def move_to_level(self, cacheLevel: int) -> None:
"""
Moves cache items betwen levels, managed directly
@ -567,7 +573,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
UserServiceManager().move_to_level(self, cacheLevel)
def setCommsUrl(self, commsUrl: typing.Optional[str] = None) -> None:
def set_comms_endpoint(self, commsUrl: typing.Optional[str] = None) -> None:
self.properties['comms_url'] = commsUrl
def get_comms_endpoint(
@ -602,7 +608,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
"""
return (
self.deployed_service.service and self.deployed_service.service.get_type().publication_type is None
) or self.publication == self.deployed_service.activePublication()
) or self.publication == self.deployed_service.active_publication()
# Utility for logging
def log(self, message: str, level: log.LogLevel = log.LogLevel.INFO) -> None:
@ -634,7 +640,7 @@ class UserService(UUIDModel, properties.PropertiesMixin):
# 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
to_delete.closeSession('')
to_delete.end_session('')
# Clear related logs to this user service
log.clear_logs(to_delete)

View File

@ -186,7 +186,7 @@ class LinuxOsADManager(LinuxOsManager):
def actor_data(self, userService: 'UserService') -> collections.abc.MutableMapping[str, typing.Any]:
return {
'action': 'rename_ad',
'name': userService.getName(),
'name': userService.get_name(),
'custom': {
'domain': self._domain,
'username': self._account,
@ -238,8 +238,8 @@ class LinuxOsADManager(LinuxOsManager):
self._automaticIdMapping = values[10]
super().unmarshal(codecs.decode(values[11].encode(), 'hex'))
def valuesDict(self) -> gui.ValuesDictType:
dct = super().valuesDict()
def dict_of_values(self) -> gui.ValuesDictType:
dct = super().dict_of_values()
dct['domain'] = self._domain
dct['account'] = self._account
dct['password'] = self._password

View File

@ -175,7 +175,7 @@ class LinuxOsFreeIPAManager(LinuxOsManager):
def actor_data(self, userService: 'UserService') -> collections.abc.MutableMapping[str, typing.Any]:
return {
'action': 'rename_ad',
'name': userService.getName(),
'name': userService.get_name(),
'custom': {
'domain': self._domain,
'username': self._account,
@ -224,8 +224,8 @@ class LinuxOsFreeIPAManager(LinuxOsManager):
self._automaticIdMapping = values[9]
super().unmarshal(codecs.decode(values[10].encode(), 'hex'))
def valuesDict(self) -> gui.ValuesDictType:
dct = super().valuesDict()
def dict_of_values(self) -> gui.ValuesDictType:
dct = super().dict_of_values()
dct['domain'] = self._domain
dct['account'] = self._account
dct['password'] = self._password

View File

@ -97,7 +97,7 @@ class LinuxOsManager(osmanagers.OSManager):
default=True,
)
def __setProcessUnusedMachines(self) -> None:
def _set_process_unused_machines(self) -> None:
self.processUnusedMachines = self._onLogout == 'remove'
def __init__(self, environment: 'Environment', values: 'Module.ValuesType') -> None:
@ -111,7 +111,7 @@ class LinuxOsManager(osmanagers.OSManager):
self._idle = -1
self._deadLine = True
self.__setProcessUnusedMachines()
self._set_process_unused_machines()
def release(self, userService: 'UserService') -> None:
pass
@ -119,7 +119,7 @@ class LinuxOsManager(osmanagers.OSManager):
def ignore_deadline(self) -> bool:
return not self._deadLine
def is_removableOnLogout(self, userService: 'UserService') -> bool:
def is_removable_on_logout(self, userService: 'UserService') -> bool:
'''
Says if a machine is removable on logout
'''
@ -131,11 +131,11 @@ class LinuxOsManager(osmanagers.OSManager):
return False
def getName(self, service: 'UserService') -> str:
def get_name(self, service: 'UserService') -> str:
"""
gets name from deployed
"""
return service.getName()
return service.get_name()
def do_log(self, service: 'UserService', data, origin=log.LogSource.OSMANAGER) -> None:
# Stores a log associated with this service
@ -153,14 +153,14 @@ class LinuxOsManager(osmanagers.OSManager):
def actor_data(
self, userService: 'UserService'
) -> collections.abc.MutableMapping[str, typing.Any]:
return {'action': 'rename', 'name': userService.getName()} # No custom data
return {'action': 'rename', 'name': userService.get_name()} # No custom data
def process_unused(self, userService: 'UserService') -> None:
"""
This will be invoked for every assigned and unused user service that has been in this state at least 1/2 of Globalconfig.CHECK_UNUSED_TIME
This function can update userService values. Normal operation will be remove machines if this state is not valid
"""
if self.is_removableOnLogout(userService):
if self.is_removable_on_logout(userService):
log.log(
userService,
log.LogLevel.INFO,
@ -210,9 +210,9 @@ class LinuxOsManager(osmanagers.OSManager):
gui.toBool(values[3]),
)
self.__setProcessUnusedMachines()
self._set_process_unused_machines()
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
return {
'onLogout': self._onLogout,
'idle': str(self._idle),

View File

@ -114,7 +114,7 @@ class LinuxRandomPassManager(LinuxOsManager):
) -> collections.abc.MutableMapping[str, typing.Any]:
return {
'action': 'rename',
'name': userService.getName(),
'name': userService.get_name(),
# Repeat data, to keep compat with old versions of Actor
# Will be removed in a couple of versions
@ -144,7 +144,7 @@ class LinuxRandomPassManager(LinuxOsManager):
self._userAccount = values[1].decode()
LinuxOsManager.unmarshal(self, codecs.decode(values[2], 'hex'))
def valuesDict(self) -> gui.ValuesDictType:
dic = LinuxOsManager.valuesDict(self)
def dict_of_values(self) -> gui.ValuesDictType:
dic = LinuxOsManager.dict_of_values(self)
dic['userAccount'] = self._userAccount
return dic

View File

@ -91,7 +91,7 @@ class TestOSManager(osmanagers.OSManager):
def release(self, userService: 'UserService') -> None:
logger.debug('User service %s released', userService)
def is_removableOnLogout(self, userService: 'UserService') -> bool:
def is_removable_on_logout(self, userService: 'UserService') -> bool:
'''
Says if a machine is removable on logout
'''
@ -103,11 +103,11 @@ class TestOSManager(osmanagers.OSManager):
return False
def getName(self, userService: 'UserService') -> str:
def get_name(self, userService: 'UserService') -> str:
"""
gets name from deployed
"""
return userService.getName()
return userService.get_name()
def do_log(self, service: 'UserService', data, origin=log.LogSource.OSMANAGER) -> None:
# Stores a log associated with this service
@ -125,14 +125,14 @@ class TestOSManager(osmanagers.OSManager):
def actor_data(
self, userService: 'UserService'
) -> collections.abc.MutableMapping[str, typing.Any]:
return {'action': 'rename', 'name': userService.getName()}
return {'action': 'rename', 'name': userService.get_name()}
def process_unused(self, userService: 'UserService') -> None:
"""
This will be invoked for every assigned and unused user service that has been in this state at least 1/2 of Globalconfig.CHECK_UNUSED_TIME
This function can update userService values. Normal operation will be remove machines if this state is not valid
"""
if self.is_removableOnLogout(userService):
if self.is_removable_on_logout(userService):
log.log(
userService,
log.LogLevel.INFO,

View File

@ -122,7 +122,7 @@ class WindowsOsManager(osmanagers.OSManager):
self.__setProcessUnusedMachines()
def is_removableOnLogout(self, userService: 'UserService') -> bool:
def is_removable_on_logout(self, userService: 'UserService') -> bool:
"""
Says if a machine is removable on logout
"""
@ -140,8 +140,8 @@ class WindowsOsManager(osmanagers.OSManager):
def ignore_deadline(self) -> bool:
return not self._deadLine
def getName(self, userService: 'UserService') -> str:
return userService.getName()
def get_name(self, userService: 'UserService') -> str:
return userService.get_name()
def do_log(self, userService: 'UserService', data: str, origin=log.LogSource.OSMANAGER):
# Stores a log associated with this service
@ -163,7 +163,7 @@ class WindowsOsManager(osmanagers.OSManager):
def actor_data(
self, userService: 'UserService'
) -> collections.abc.MutableMapping[str, typing.Any]:
return {'action': 'rename', 'name': userService.getName()} # No custom data
return {'action': 'rename', 'name': userService.get_name()} # No custom data
def process_user_password(
self, userService: 'UserService', username: str, password: str
@ -191,7 +191,7 @@ class WindowsOsManager(osmanagers.OSManager):
This will be invoked for every assigned and unused user service that has been in this state at least 1/2 of Globalconfig.CHECK_UNUSED_TIME
This function can update userService values. Normal operation will be remove machines if this state is not valid
"""
if self.is_removableOnLogout(userService):
if self.is_removable_on_logout(userService):
log.log(
userService,
log.LogLevel.INFO,
@ -249,7 +249,7 @@ class WindowsOsManager(osmanagers.OSManager):
self.__setProcessUnusedMachines()
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
return {
'onLogout': self._onLogout,
'idle': str(self._idle),

View File

@ -440,7 +440,7 @@ class WinDomainOsManager(WindowsOsManager):
def actor_data(self, userService: 'UserService') -> collections.abc.MutableMapping[str, typing.Any]:
return {
'action': 'rename_ad',
'name': userService.getName(),
'name': userService.get_name(),
# Repeat data, to keep compat with old versions of Actor
# Will be removed in a couple of versions
@ -503,8 +503,8 @@ class WinDomainOsManager(WindowsOsManager):
self._removeOnExit = 'y'
super().unmarshal(codecs.decode(values[5].encode(), 'hex'))
def valuesDict(self) -> gui.ValuesDictType:
dct = super().valuesDict()
def dict_of_values(self) -> gui.ValuesDictType:
dct = super().dict_of_values()
dct['domain'] = self._domain
dct['ou'] = self._ou
dct['account'] = self._account

View File

@ -127,7 +127,7 @@ class WinRandomPassManager(WindowsOsManager):
def actor_data(self, userService: 'UserService') -> collections.abc.MutableMapping[str, typing.Any]:
return {
'action': 'rename',
'name': userService.getName(),
'name': userService.get_name(),
# Repeat data, to keep compat with old versions of Actor
# Will be removed in a couple of versions
@ -158,8 +158,8 @@ class WinRandomPassManager(WindowsOsManager):
self._password = CryptoManager().decrypt(values[2])
super().unmarshal(codecs.decode(values[3].encode(), 'hex'))
def valuesDict(self) -> gui.ValuesDictType:
dic = super().valuesDict()
def dict_of_values(self) -> gui.ValuesDictType:
dic = super().dict_of_values()
dic['userAccount'] = self._userAccount
dic['password'] = self._password
return dic

View File

@ -144,7 +144,7 @@ class OVirtLinkedDeployment(services.UserService):
if self._name == '':
try:
self._name = self.name_generator().get(
self.service().getBaseName(), self.service().getLenName()
self.service().get_base_name(), self.service().getLenName()
)
except KeyError:
return NO_MORE_NAMES

View File

@ -442,7 +442,7 @@ class OVirtLinkedService(services.Service): # pylint: disable=too-many-public-m
"""
return self.parent().getMacRange()
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
Returns the base name
"""

View File

@ -112,7 +112,7 @@ class LiveDeployment(services.UserService): # pylint: disable=too-many-public-m
if self._name == '':
try:
self._name = self.name_generator().get(
self.service().getBaseName(), self.service().getLenName()
self.service().get_base_name(), self.service().getLenName()
)
except KeyError:
return NO_MORE_NAMES

View File

@ -300,7 +300,7 @@ class LiveService(services.Service):
"""
return self.parent().getNetInfo(machineId, networkId=None)
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
Returns the base name
"""

View File

@ -120,7 +120,7 @@ class LiveDeployment(services.UserService): # pylint: disable=too-many-public-m
if self._name == '':
try:
self._name = self.name_generator().get(
self.service().getBaseName(), self.service().getLenName()
self.service().get_base_name(), self.service().getLenName()
)
except KeyError:
return NO_MORE_NAMES

View File

@ -429,7 +429,7 @@ class LiveService(services.Service):
# vals = six.next(six.itervalues(net))[0]
return vals['OS-EXT-IPS-MAC:mac_addr'].upper(), vals['addr']
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
Returns the base name
"""

View File

@ -189,7 +189,7 @@ class IPMachinesService(IPServiceBase):
def get_token(self):
return self._token or None
def valuesDict(self) -> gui.ValuesDictType:
def dict_of_values(self) -> gui.ValuesDictType:
ips = (i.split('~')[0] for i in self._ips)
return {
'ipList': ensure.is_list(ips),

View File

@ -152,7 +152,7 @@ class TaskStatus(typing.NamedTuple):
def fromJson(dictionary: collections.abc.MutableMapping[str, typing.Any]) -> 'TaskStatus':
return convertFromDict(TaskStatus, dictionary['data'])
def isRunning(self) -> bool:
def is_running(self) -> bool:
return self.status == 'running'
def is_finished(self) -> bool:

View File

@ -151,7 +151,7 @@ class ProxmoxDeployment(services.UserService):
if self._name == '':
try:
self._name = self.name_generator().get(
self.service().getBaseName(), self.service().getLenName()
self.service().get_base_name(), self.service().getLenName()
)
except KeyError:
return NO_MORE_NAMES

View File

@ -87,7 +87,7 @@ class ProxmoxDeferredRemoval(jobs.Job):
) -> bool:
counter = 0
while (
providerInstance.getTaskInfo(upid.node, upid.upid).isRunning()
providerInstance.getTaskInfo(upid.node, upid.upid).is_running()
and counter < maxWait
):
time.sleep(0.3)

View File

@ -142,7 +142,7 @@ class ProxmoxPublication(services.Publication):
node, upid = self._task.split(',')
try:
task = self.service().getTaskInfo(node, upid)
if task.isRunning():
if task.is_running():
return State.RUNNING
except Exception as e:
logger.exception('Proxmox publication')

View File

@ -318,7 +318,7 @@ class ProxmoxLinkedService(services.Service): # pylint: disable=too-many-public
def setVmMac(self, vmId: int, mac: str) -> None:
self.parent().setVmMac(vmId, mac)
def getBaseName(self) -> str:
def get_base_name(self) -> str:
return self.baseName.value
def getLenName(self) -> int:

View File

@ -120,7 +120,7 @@ class SampleUserServiceOne(services.UserService):
name: str = typing.cast(str, self.storage.readData('name'))
if name is None:
name = self.name_generator().get(
self.service().getBaseName() + '-' + self.service().getColour(), 3
self.service().get_base_name() + '-' + self.service().getColour(), 3
)
# Store value for persistence
self.storage.saveData('name', name)

View File

@ -159,7 +159,7 @@ class SampleUserServiceTwo(services.UserService):
generate more names. (Generator are simple utility classes)
"""
if self._name == '':
self._name = self.name_generator().get(self.publication().getBaseName(), 3)
self._name = self.name_generator().get(self.publication().get_base_name(), 3)
# self._name will be stored when object is marshaled
return self._name

View File

@ -271,7 +271,7 @@ class SamplePublication(services.Publication):
# Methods provided below are specific for this publication
# and will be used by user deployments that uses this kind of publication
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
This sample method (just for this sample publication), provides
the name generater for this publication. This is just a sample, and

View File

@ -192,7 +192,7 @@ class ServiceOne(services.Service):
"""
return self.passw.value
def getBaseName(self) -> str:
def get_base_name(self) -> str:
return self.baseName.value
@ -236,7 +236,7 @@ class ServiceTwo(services.Service):
# No checks here
def getNames(self) -> str:
def get_names(self) -> str:
"""
For using at deployed services, really nothing
"""

View File

@ -79,7 +79,7 @@ class TestUserService(services.UserService):
def get_name(self) -> str:
if not self.data.name:
self.data.name = self.name_generator().get(self.service().getBaseName(), 3)
self.data.name = self.name_generator().get(self.service().get_base_name(), 3)
logger.info('Getting name of deployment %s', self.data)

View File

@ -102,7 +102,7 @@ class TestProvider(services.ServiceProvider):
) -> list[typing.Any]:
return [True, _('Nothing tested, but all went fine..')]
def getName(self) -> str:
def get_name(self) -> str:
"""
returns a random name for testing pourposes
"""

View File

@ -113,7 +113,7 @@ class TestPublication(services.Publication):
# Methods provided below are specific for this publication
# and will be used by user deployments that uses this kind of publication
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
This sample method (just for this sample publication), provides
the name generater for this publication. This is just a sample, and

View File

@ -75,11 +75,11 @@ class TestServiceNoCache(services.Service):
def parent(self) -> 'TestProvider':
return typing.cast('TestProvider', super().parent())
def getName(self) -> str:
return self.parent().getName() + '{' + self.type_name + '}'
def get_name(self) -> str:
return self.parent().get_name() + '{' + self.type_name + '}'
def getBaseName(self) -> str:
return self.parent().getName()
def get_base_name(self) -> str:
return self.parent().get_name()
class TestServiceCache(services.Service):
"""
@ -111,8 +111,8 @@ class TestServiceCache(services.Service):
def parent(self) -> 'TestProvider':
return typing.cast('TestProvider', super().parent())
def getName(self) -> str:
return self.parent().getName() + '{' + self.type_name + '}'
def get_name(self) -> str:
return self.parent().get_name() + '{' + self.type_name + '}'
def getBaseName(self) -> str:
return self.parent().getName()
def get_base_name(self) -> str:
return self.parent().get_name()

View File

@ -123,7 +123,7 @@ class XenLinkedDeployment(services.UserService):
if not self._name:
try:
self._name = self.name_generator().get(
self.service().getBaseName(), self.service().getLenName()
self.service().get_base_name(), self.service().getLenName()
)
except KeyError:
return NO_MORE_NAMES

View File

@ -312,7 +312,7 @@ class XenProvider(ServiceProvider): # pylint: disable=too-many-public-methods
return self.__getApi().getNetworks()
def cloneForTemplate(self, name: str, comments: str, machineId: str, sr: str):
task = self.__getApi().cloneVM(machineId, name, sr)
task = self.__getApi().clone_vm(machineId, name, sr)
logger.debug('Task for cloneForTemplate: %s', task)
return task

View File

@ -413,7 +413,7 @@ class XenLinkedService(services.Service): # pylint: disable=too-many-public-met
"""
return self.parent().getMacRange()
def getBaseName(self) -> str:
def get_base_name(self) -> str:
"""
Returns the base name
"""

View File

@ -399,9 +399,9 @@ class XenServer: # pylint: disable=too-many-public-methods
return self.Async.VM.resume(vmId, False, False)
return self.VM.resume(vmId, False, False)
def cloneVM(self, vmId: str, targetName: str, targetSR: typing.Optional[str] = None) -> str:
def clone_vm(self, vmId: str, target_name: str, target_sr: typing.Optional[str] = None) -> str:
"""
If targetSR is NONE:
If target_sr is NONE:
Clones the specified VM, making a new VM.
Clone automatically exploits the capabilities of the underlying storage repository
in which the VM's disk images are stored (e.g. Copy on Write).
@ -412,19 +412,19 @@ class XenServer: # pylint: disable=too-many-public-methods
'full disks' - i.e. not part of a CoW chain.
This function can only be called when the VM is in the Halted State.
"""
logger.debug('Cloning VM %s to %s on sr %s', vmId, targetName, targetSR)
logger.debug('Cloning VM %s to %s on sr %s', vmId, target_name, target_sr)
operations = self.VM.get_allowed_operations(vmId)
logger.debug('Allowed operations: %s', operations)
try:
if targetSR:
if target_sr:
if 'copy' not in operations:
raise XenException('Copy is not supported for this machine (maybe it\'s powered on?)')
task = self.Async.VM.copy(vmId, targetName, targetSR)
task = self.Async.VM.copy(vmId, target_name, target_sr)
else:
if 'clone' not in operations:
raise XenException('Clone is not supported for this machine (maybe it\'s powered on?)')
task = self.Async.VM.clone(vmId, targetName)
task = self.Async.VM.clone(vmId, target_name)
return task
except XenAPI.Failure as e:
raise XenFailure(e.details)
@ -536,8 +536,8 @@ class XenServer: # pylint: disable=too-many-public-methods
def removeTemplate(self, templateId: str) -> None:
self.removeVM(templateId)
def cloneTemplate(self, templateId: str, targetName: str) -> str:
def cloneTemplate(self, templateId: str, target_name: str) -> str:
"""
After cloning template, we must deploy the VM so it's a full usable VM
"""
return self.cloneVM(templateId, targetName)
return self.clone_vm(templateId, target_name)

View File

@ -319,7 +319,7 @@ class HTML5RDPTransport(transports.Transport):
user: 'models.User',
password: str,
) -> types.connections.ConnectionData:
username = user.getUsernameForAuth()
username = user.get_username_for_auth()
# Maybe this is called from another provider, as for example WYSE, that need all connections BEFORE
if isinstance(userService, models.UserService):

View File

@ -358,7 +358,7 @@ class BaseRDPTransport(transports.Transport):
*,
altUsername: typing.Optional[str]
) -> types.connections.ConnectionData:
username: str = altUsername or user.getUsernameForAuth()
username: str = altUsername or user.get_username_for_auth()
if self.fixedName.value:
username = self.fixedName.value

View File

@ -200,7 +200,7 @@ class BaseSpiceTransport(transports.Transport):
user: 'models.User',
password: str,
) -> types.connections.ConnectionData:
username = user.getUsernameForAuth()
username = user.get_username_for_auth()
if self.fixedName.value:
username = self.fixedName.value

View File

@ -111,7 +111,7 @@ class TestTransport(transports.Transport):
) -> str:
# Fix username/password acording to os manager
username: str = user.getUsernameForAuth()
username: str = user.get_username_for_auth()
username, password = userService.process_user_password(username, password)
url = self.testURL.value.replace('_IP_', ip).replace('_USER_', username)

View File

@ -112,7 +112,7 @@ class URLCustomTransport(transports.Transport):
) -> str:
# Fix username/password acording to os manager
username: str = user.getUsernameForAuth()
username: str = user.get_username_for_auth()
username, password = userService.process_user_password(username, password)
url = self.urlPattern.value.replace('_IP_', ip).replace('_USER_', username)

View File

@ -229,7 +229,7 @@ class BaseX2GOTransport(transports.Transport):
user: 'models.User',
password: str,
) -> types.connections.ConnectionData:
username = user.getUsernameForAuth()
username = user.get_username_for_auth()
# Get the type of service (VDI, VAPP, ...)
if isinstance(userService, models.UserService):

View File

@ -70,7 +70,7 @@ def uds_js(request: 'ExtendedHttpRequest') -> str:
if user:
role = (
'staff'
if user.isStaff() and not user.is_admin
if user.is_staff() and not user.is_admin
else 'admin'
if user.is_admin
else 'user'
@ -214,9 +214,9 @@ def uds_js(request: 'ExtendedHttpRequest') -> str:
}
info: typing.Optional[collections.abc.MutableMapping] = None
if user and user.isStaff():
if user and user.is_staff():
info = {
'networks': [n.name for n in Network.networksFor(request.ip)],
'networks': [n.name for n in Network.get_networks_for_ip(request.ip)],
'transports': [
t.name for t in Transport.objects.all() if t.is_ip_allowed(request.ip)
],
@ -289,7 +289,7 @@ def uds_js(request: 'ExtendedHttpRequest') -> str:
actors: list[dict[str, str]] = []
if user and user.isStaff(): # Add staff things
if user and user.is_staff(): # Add staff things
# If is admin (informational, REST api checks users privileges anyway...)
profile['admin'] = True
# REST auth

View File

@ -120,7 +120,7 @@ def getServicesData(
"""
# We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
groups = list(request.user.getGroups())
groups = list(request.user.get_groups())
availServicePools = list(
ServicePool.get_pools_for_groups(groups, request.user)
) # Pass in user to get "number_assigned" to optimize
@ -136,8 +136,8 @@ def getServicesData(
osType: 'types.os.KnownOS' = request.os.os
logger.debug('OS: %s', osType)
if request.user.isStaff():
nets = ','.join([n.name for n in Network.networksFor(request.ip)])
if request.user.is_staff():
nets = ','.join([n.name for n in Network.get_networks_for_ip(request.ip)])
tt = []
t: Transport
for t in Transport.objects.all().prefetch_related('networks'):
@ -250,7 +250,7 @@ def getServicesData(
)
else:
for member in meta.members.all():
# if pool.isInMaintenance():
# if pool.is_in_maintenance():
# continue
for t in member.pool.transports.all():
typeTrans = t.get_type()
@ -298,7 +298,7 @@ def getServicesData(
show_transports=len(metaTransports) > 1,
allow_users_remove=meta.allow_users_remove,
allow_users_reset=meta.allow_users_remove,
maintenance=meta.isInMaintenance(),
maintenance=meta.is_in_maintenance(),
not_accesible=not meta.isAccessAllowed(now),
in_use=in_use,
to_be_replaced=None,

View File

@ -50,6 +50,6 @@ if typing.TYPE_CHECKING:
def image(request: 'HttpRequest', idImage: str) -> 'HttpResponse':
try:
icon = Image.objects.get(uuid=process_uuid(idImage))
return icon.imageResponse()
return icon.image_as_response()
except Image.DoesNotExist:
return HttpResponse(DEFAULT_IMAGE, content_type='image/png')

View File

@ -108,7 +108,7 @@ def transportIcon(request: 'ExtendedHttpRequest', idTrans: str) -> HttpResponse:
def serviceImage(request: 'ExtendedHttpRequest', idImage: str) -> HttpResponse:
try:
icon = Image.objects.get(uuid=process_uuid(idImage))
return icon.imageResponse()
return icon.image_as_response()
except Image.DoesNotExist:
pass # Tries to get image from transport

View File

@ -71,7 +71,7 @@ class ModelAccountTest(UDSTestCase):
def test_start_single_userservice(self) -> None:
acc = models.Account.objects.create(name='Test Account')
for i in range(32):
acc.startUsageAccounting(self.user_services[0])
acc.start_accounting(self.user_services[0])
# Only one usage is createdm even with different accounters
self.assertEqual(acc.usages.count(), 1, f'loop {i}')
@ -80,7 +80,7 @@ class ModelAccountTest(UDSTestCase):
# no usage is created because already created one for that user service
for i in range(32):
acc = models.Account.objects.create(name='Test Account')
acc.startUsageAccounting(self.user_services[0])
acc.start_accounting(self.user_services[0])
self.assertEqual(acc.usages.count(), 0, f'loop {i}')
@ -88,7 +88,7 @@ class ModelAccountTest(UDSTestCase):
acc = models.Account.objects.create(name='Test Account')
for i in range(32):
for i in range(NUM_USERSERVICES):
acc.startUsageAccounting(self.user_services[i])
acc.start_accounting(self.user_services[i])
# Only one usage is createdm even with different accounters
self.assertEqual(acc.usages.count(), NUM_USERSERVICES, f'loop {i}'.format(i))
@ -98,22 +98,22 @@ class ModelAccountTest(UDSTestCase):
for i in range(32):
acc = models.Account.objects.create(name='Test Account')
for i in range(NUM_USERSERVICES):
acc.startUsageAccounting(self.user_services[i])
acc.start_accounting(self.user_services[i])
self.assertEqual(acc.usages.count(), 0, f'loop {i}')
def test_start_multiple(self) -> None:
for i in range(NUM_USERSERVICES):
acc = models.Account.objects.create(name='Test Account')
acc.startUsageAccounting(self.user_services[i])
acc.start_accounting(self.user_services[i])
self.assertEqual(acc.usages.count(), 1)
def test_end_single(self) -> None:
acc = models.Account.objects.create(name='Test Account')
for i in range(32): # will create 32 usages, because we close them all, even with one user service
acc.startUsageAccounting(self.user_services[i % NUM_USERSERVICES])
acc.stopUsageAccounting(self.user_services[i % NUM_USERSERVICES])
acc.start_accounting(self.user_services[i % NUM_USERSERVICES])
acc.stop_accounting(self.user_services[i % NUM_USERSERVICES])
self.assertEqual(acc.usages.count(), i + 1)
@ -123,19 +123,19 @@ class ModelAccountTest(UDSTestCase):
for _ in range(32):
acc = models.Account.objects.create(name='Test Account')
for j in range(NUM_USERSERVICES):
acc.startUsageAccounting(self.user_services[j])
acc.stopUsageAccounting(self.user_services[j])
acc.start_accounting(self.user_services[j])
acc.stop_accounting(self.user_services[j])
self.assertEqual(acc.usages.count(), NUM_USERSERVICES) # This acc will only have one usage
def test_account_usage(self) -> None:
acc = models.Account.objects.create(name='Test Account')
for i in range(NUM_USERSERVICES):
usage = acc.startUsageAccounting(self.user_services[i])
usage = acc.start_accounting(self.user_services[i])
self.assertIsNotNone(usage)
usage.start = usage.start - datetime.timedelta(seconds=32 + i) # type: ignore
usage.save(update_fields=['start']) # type: ignore
usage_end = acc.stopUsageAccounting(self.user_services[i])
usage_end = acc.stop_accounting(self.user_services[i])
self.assertIsNotNone(usage_end)
self.assertEqual(acc.usages.count(), NUM_USERSERVICES)

View File

@ -126,7 +126,7 @@ class UserinterfaceInternalTest(UDSTestCase):
def test_valuesDict(self):
ui = TestingUserInterface()
self.assertEqual(
ui.valuesDict(),
ui.dict_of_values(),
{
'str_field': DEFAULTS['str_field'],
'str_auto_field': DEFAULTS['str_auto_field'],