1
0
mirror of https://github.com/dkmstr/openuds.git synced 2024-12-22 13:34:04 +03:00

Linted all models

This commit is contained in:
Adolfo Gómez García 2023-04-17 02:47:31 +02:00
parent a88b0b59a5
commit b69076ac1a
No known key found for this signature in database
GPG Key ID: DD1ABF20724CDA23
20 changed files with 135 additions and 146 deletions

View File

@ -55,7 +55,7 @@ class OSManager(ManagedObjectModel, TaggingMixin):
# objects: 'models.manager.Manager[OSManager]'
deployedServices: 'models.manager.RelatedManager[ServicePool]'
class Meta(ManagedObjectModel.Meta):
class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order
"""
@ -80,7 +80,7 @@ class OSManager(ManagedObjectModel, TaggingMixin):
:note: We only need to get info from this, not access specific data (class specific info)
"""
# We only need to get info from this, not access specific data (class specific info)
from uds.core import osmanagers
from uds.core import osmanagers # pylint: disable=import-outside-toplevel
return osmanagers.factory().lookup(self.data_type) or osmanagers.OSManager
@ -101,10 +101,10 @@ class OSManager(ManagedObjectModel, TaggingMixin):
return True
def __str__(self) -> str:
return "{0} of type {1} (id:{2})".format(self.name, self.data_type, self.id)
return f'{self.name} of type {self.data_type} (id:{self.id})'
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Service class "Destroy" before deleting it from database.

View File

@ -85,7 +85,6 @@ class PermissionType(enum.IntEnum):
return self.value >= permission.value
class Permissions(UUIDModel):
"""
An OS Manager represents a manager for responding requests for agents inside services.
@ -118,9 +117,7 @@ class Permissions(UUIDModel):
object_type = models.SmallIntegerField(default=-1, db_index=True)
object_id = models.IntegerField(default=None, db_index=True, null=True, blank=True)
permission = models.SmallIntegerField(
default=PermissionType.NONE, db_index=True
)
permission = models.SmallIntegerField(default=PermissionType.NONE, db_index=True)
# "fake" declarations for type checking
# objects: 'models.manager.Manager[Permissions]'
@ -235,11 +232,8 @@ class Permissions(UUIDModel):
return PermissionType(self.permission).as_str()
def __str__(self) -> str:
return 'Permission {}, user {} group {} object_type {} object_id {} permission {}'.format(
self.uuid,
self.user,
self.group,
self.object_type,
self.object_id,
PermissionType(self.permission).as_str(),
return (
f'Permission {self.uuid}, user {self.user} group {self.group} '
f'object_type {self.object_type} object_id {self.object_id} '
f'permission {PermissionType(self.permission).as_str()}'
)

View File

@ -59,7 +59,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
# objects: 'models.manager.Manager[Provider]'
services: 'models.manager.RelatedManager[Service]'
class Meta(ManagedObjectModel.Meta):
class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order
"""
@ -76,7 +76,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
Returns:
The python type for this record object
"""
from uds.core import services # pylint: disable=redefined-outer-name
from uds.core import services # pylint: disable=import-outside-toplevel
return services.factory().lookup(self.data_type) or services.ServiceProvider
@ -94,10 +94,10 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
return self.maintenance_mode
def __str__(self) -> str:
return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id)
return f'Provider {self.name} of type {self.data_type} (id:{self.id})'
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Provider class "Destroy" before deleting it from database.
@ -106,7 +106,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore
:note: If destroy raises an exception, the deletion is not taken.
"""
from uds.core.util.permissions import clean
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
toDelete = kwargs['instance']
logger.debug('Before delete service provider %s', toDelete)

View File

@ -76,7 +76,7 @@ class Scheduler(models.Model):
# objects: 'models.manager.Manager[Scheduler]'
id: int # Primary key (Autogenerated by model, just for type checking)
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -87,7 +87,7 @@ class Scheduler(models.Model):
"""
Returns an environment valid for the record this object represents
"""
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore
return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore # pylint: disable=no-member
def getInstance(self) -> typing.Optional[jobs.Job]:
"""
@ -111,9 +111,7 @@ class Scheduler(models.Model):
toDelete.getEnvironment().clearRelatedData()
def __str__(self) -> str:
return 'Scheduled task {}, every {}, last execution at {}, state = {}'.format(
self.name, self.frecuency, self.last_execution, self.state
)
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

View File

@ -46,8 +46,8 @@ from .provider import Provider
# Not imported at runtime, just for type checking
if typing.TYPE_CHECKING:
from uds.core import services
from uds.models.service_pool import ServicePool
from uds.core import services
logger = logging.getLogger(__name__)
@ -63,10 +63,10 @@ class ServiceTokenAlias(models.Model):
)
alias = models.CharField(max_length=64, unique=True)
def __str__(self):
return self.alias
def __str__(self) -> str:
return str(self.alias) # pylint complains about CharField
# pylint: disable=no-member
class Service(ManagedObjectModel, TaggingMixin): # type: ignore
"""
A Service represents an specidied type of service offered to final users,
@ -93,7 +93,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
deployedServices: 'models.manager.RelatedManager[ServicePool]'
aliases: 'models.manager.RelatedManager[ServiceTokenAlias]'
class Meta(ManagedObjectModel.Meta):
class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -149,9 +149,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
self.deserialize(obj, values)
else:
raise Exception(
'Service type of {} is not recogniced by provider {}'.format(
self.data_type, prov
)
f'Service type of {self.data_type} is not recogniced by provider {prov.name}'
)
self._cachedInstance = obj
@ -169,6 +167,8 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
:note: We only need to get info from this, not access specific data (class specific info)
"""
from uds.core import services # pylint: disable=import-outside-toplevel,redefined-outer-name
prov: typing.Type['services.ServiceProvider'] = self.provider.getType()
return prov.getServiceByType(self.data_type) or services.Service
@ -194,10 +194,10 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
return self.max_services_count_type == 1
def __str__(self) -> str:
return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id)
return f'{self.name} of type {self.data_type} (id:{self.id})'
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Service class "Destroy" before deleting it from database.
@ -206,7 +206,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
:note: If destroy raises an exception, the deletion is not taken.
"""
from uds.core.util.permissions import clean
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
toDelete = kwargs['instance']

View File

@ -159,7 +159,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore
calendaraction_set: 'models.manager.RelatedManager[CalendarAction]'
changelog: 'models.manager.RelatedManager[ServicePoolPublicationChangelog]'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare the name of the table at database
"""

View File

@ -44,13 +44,12 @@ from .image import Image
logger = logging.getLogger(__name__)
# pylint: disable=no-member
class ServicePoolGroup(UUIDModel):
"""
A deployed service is the Service produced element that is assigned finally to an user (i.e. a Virtual Machine, etc..)
"""
# pylint: disable=model-missing-unicode
name = models.CharField(max_length=128, default='', db_index=True, unique=True)
comments = models.CharField(max_length=256, default='')
priority = models.IntegerField(default=0, db_index=True)
@ -65,7 +64,7 @@ class ServicePoolGroup(UUIDModel):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[ServicePoolGroup]'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare the name of the table at database
"""
@ -74,9 +73,7 @@ class ServicePoolGroup(UUIDModel):
app_label = 'uds'
def __str__(self) -> str:
return 'Service Pool group {}({}): {}'.format(
self.name, self.comments, self.image.name if self.image else ''
)
return f'Service Pool group {self.name}({self.comments}): {self.image.name if self.image else ""}'
@property
def as_dict(self) -> typing.MutableMapping[str, typing.Any]:

View File

@ -65,7 +65,7 @@ class ServicePoolPublicationChangelog(models.Model):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[ServicePoolPublicationChangelog]'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -74,9 +74,7 @@ class ServicePoolPublicationChangelog(models.Model):
app_label = 'uds'
def __str__(self) -> str:
return 'Revision log for publication {}, rev {}: {}'.format(
self.publication.name, self.revision, self.log
)
return f'Changelog for publication {self.publication.name}, rev {self.revision}: {self.log}'
class ServicePoolPublication(UUIDModel):
@ -105,7 +103,7 @@ class ServicePoolPublication(UUIDModel):
# objects: 'models.manager.Manager["ServicePoolPublication"]'
userServices: 'models.manager.RelatedManager[UserService]'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -146,9 +144,7 @@ class ServicePoolPublication(UUIDModel):
if serviceInstance.publicationType is None:
raise Exception(
'Class {} do not have defined publicationType but needs to be published!!!'.format(
serviceInstance.__class__
)
f'Class {serviceInstance.__class__.__name__} do not have defined publicationType but needs to be published!!!'
)
publication = serviceInstance.publicationType(
@ -208,7 +204,7 @@ class ServicePoolPublication(UUIDModel):
publicationManager().cancel(self)
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Service class "Destroy" before deleting it from database.
@ -230,9 +226,7 @@ class ServicePoolPublication(UUIDModel):
logger.debug('Deleted publication %s', toDelete)
def __str__(self) -> str:
return 'Publication {}, rev {}, state {}'.format(
self.deployed_service.name, self.revision, State.toString(self.state)
)
return f'Publication {self.deployed_service.name}, rev {self.revision}, state {State.toString(self.state)}'
# Connects a pre deletion signal to Authenticator

View File

@ -53,7 +53,7 @@ class StatsCounters(models.Model):
# "fake" declarations for type checking
objects: 'models.manager.Manager[StatsCounters]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare db table
"""

View File

@ -82,7 +82,7 @@ class StatsCountersAccum(models.Model):
# "fake" declarations for type checking
objects: 'models.manager.Manager[StatsCountersAccum]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare db table
"""
@ -215,7 +215,7 @@ class StatsCountersAccum(models.Model):
sum=models.Sum('v_sum'),
)
"""Stores accumulated data in StatsCountersAccum"""
# Stores accumulated data in StatsCountersAccum
# Acummulate data, only register if there is data
accumulated: typing.List[StatsCountersAccum] = [
StatsCountersAccum(

View File

@ -33,13 +33,9 @@ Author: Adolfo Gómez, dkmaster at dkmon dot com
import datetime
import logging
import typing
import types
from django.db import models
from .util import NEVER_UNIX
from .util import getSqlDatetimeAsUnix
logger = logging.getLogger(__name__)
@ -62,7 +58,7 @@ class StatsEvents(models.Model):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[StatsEvents]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare db table
"""
@ -160,7 +156,7 @@ class StatsEvents(models.Model):
# Return record as csv line using separator (default: ',')
def toCsv(self, sep: str = ',') -> str:
from uds.core.util.stats.events import EVENT_NAMES, TYPES_NAMES
from uds.core.util.stats.events import EVENT_NAMES, TYPES_NAMES # pylint: disable=import-outside-toplevel
return sep.join(
[
@ -176,12 +172,7 @@ class StatsEvents(models.Model):
)
def __str__(self):
return 'Log of {}({}): {} - {} - {}, {}, {}'.format(
self.owner_type,
self.owner_id,
self.event_type,
self.stamp,
self.fld1,
self.fld2,
self.fld3,
return (
f'Log of {self.owner_type}({self.owner_id}): {self.event_type} - {self.stamp}, '
f'{self.fld1}, {self.fld2}, {self.fld3}'
)

View File

@ -53,7 +53,7 @@ class Storage(models.Model):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[Storage]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare the name of the table at database
"""
@ -61,6 +61,4 @@ class Storage(models.Model):
app_label = 'uds'
def __str__(self) -> str:
return '{} {} > str= {}, {}'.format(
self.owner, self.key, self.data, '/'.join([self.attr1 or ''])
)
return f'{self.owner} {self.key} > str= {self.data}, {self.attr1 or ""}'

View File

@ -81,7 +81,7 @@ class Tag(UUIDModel):
servicepool_set: 'models.manager.RelatedManager[ServicePool]'
transport_set: 'models.manager.RelatedManager[Transport]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare db table
"""
@ -91,14 +91,14 @@ class Tag(UUIDModel):
@property
def vtag(self) -> str:
return self.tag.capitalize()
return str(self.tag).capitalize()
def __str__(self) -> str:
return 'Tag: {} {}'.format(self.uuid, self.tag)
return f'Tag: {self.uuid} {self.tag}'
class TaggingMixin(models.Model):
tags = models.ManyToManyField(Tag)
class Meta:
class Meta: # pylint: disable=too-few-public-methods
abstract = True

View File

@ -76,7 +76,7 @@ class TicketStore(UUIDModel):
class InvalidTicket(Exception):
pass
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare the name of the table at database
"""
@ -114,13 +114,16 @@ class TicketStore(UUIDModel):
data = cryptoManager().AESCrypt(data, owner.encode())
owner = SECURED # So data is REALLY encrypted
return TicketStore.objects.create(
return (
TicketStore.objects.create(
stamp=getSqlDatetime(),
data=data,
validator=validator,
validity=validity,
owner=owner,
).uuid or ''
).uuid
or ''
)
@staticmethod
def get(
@ -151,11 +154,15 @@ class TicketStore(UUIDModel):
data, typing.cast(str, owner).encode()
)
data = pickle.loads(data) # nosec: Tickets are generated by us, so we know they are safe
data = pickle.loads(
data
) # nosec: Tickets are generated by us, so we know they are safe
# If has validator, execute it
if t.validator:
validator: ValidatorType = pickle.loads(t.validator) # nosec: Tickets are generated by us, so we know they are safe
validator: ValidatorType = pickle.loads(
t.validator
) # nosec: Tickets are generated by us, so we know they are safe
if validator(data) is False:
raise TicketStore.InvalidTicket('Validation failed')
@ -166,7 +173,7 @@ class TicketStore(UUIDModel):
return data
except TicketStore.DoesNotExist:
raise TicketStore.InvalidTicket('Does not exists')
raise TicketStore.InvalidTicket('Does not exists') from None
@staticmethod
def update(
@ -188,7 +195,9 @@ class TicketStore(UUIDModel):
data, typing.cast(str, owner).encode()
)
dct = pickle.loads(data)
dct = pickle.loads(
data
) # nosec: Tickets are ONLY generated by us, so we know they are safe
# invoke check function
if checkFnc(dct) is False:
@ -222,7 +231,7 @@ class TicketStore(UUIDModel):
t.validity = validity
t.save(update_fields=['validity', 'stamp'])
except TicketStore.DoesNotExist:
raise TicketStore.InvalidTicket('Does not exists')
raise TicketStore.InvalidTicket('Does not exists') from None
# Especific methods for tunnel
@staticmethod
@ -302,12 +311,14 @@ class TicketStore(UUIDModel):
TicketStore.objects.filter(stamp__lt=cleanSince).delete()
def __str__(self) -> str:
data = pickle.loads(self.data) if self.owner != SECURED else '{Secure Ticket}' # nosec: Tickets are generated by us, so we know they are safe
return 'Ticket id: {}, Owner: {}, Stamp: {}, Validity: {}, Data: {}'.format(
self.uuid,
self.owner,
self.stamp,
self.validity,
data,
# Tickets are generated by us, so we know they are safe
data = (
pickle.loads(self.data) # nosec
if self.owner != SECURED
else '{Secure Ticket}'
)
return (
f'Ticket id: {self.uuid}, Owner: {self.owner}, Stamp: {self.stamp}, '
f'Validity: {self.validity}, Data: {data}'
)

View File

@ -62,7 +62,6 @@ class Transport(ManagedObjectModel, TaggingMixin):
ALLOW = 'a'
DENY = 'd'
# pylint: disable=model-missing-unicode
priority = models.IntegerField(default=0, db_index=True)
net_filtering = models.CharField(max_length=1, default=NO_FILTERING, db_index=True)
# We store allowed oss as a comma-separated list
@ -76,7 +75,7 @@ class Transport(ManagedObjectModel, TaggingMixin):
deployedServices: 'models.manager.RelatedManager[ServicePool]'
networks: 'models.manager.RelatedManager[Network]'
class Meta(ManagedObjectModel.Meta):
class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order
"""
@ -140,13 +139,13 @@ class Transport(ManagedObjectModel, TaggingMixin):
Returns:
bool: True if this transport is valid for the specified OS, False otherwise
"""
return not self.allowed_oss or os.name in self.allowed_oss.split(',')
return not self.allowed_oss or os.name in str(self.allowed_oss).split(',')
def __str__(self) -> str:
return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id)
return f'{self.name} of type {self.data_type} (id:{self.id})'
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Service class "Destroy" before deleting it from database.
@ -155,7 +154,7 @@ class Transport(ManagedObjectModel, TaggingMixin):
:note: If destroy raises an exception, the deletion is not taken.
"""
from uds.core.util.permissions import clean
from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel
toDelete = kwargs['instance']

View File

@ -52,7 +52,7 @@ class TunnelToken(models.Model):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[TunnelToken]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['ip', 'hostname'], name='tt_ip_hostname')
@ -73,6 +73,4 @@ class TunnelToken(models.Model):
return False
def __str__(self):
return '<TunnelToken {} created on {} by {} from {}/{}>'.format(
self.token, self.stamp, self.username, self.ip, self.hostname
)
return f'<TunnelToken {self.token} created on {self.stamp} by {self.username} from {self.ip}/{self.hostname}>'

View File

@ -52,7 +52,7 @@ class UniqueId(models.Model):
# "fake" declarations for type checking
# objects: 'models.manager.Manager[UniqueId]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -64,6 +64,4 @@ class UniqueId(models.Model):
]
def __str__(self) -> str:
return u"{0} {1}.{2}, assigned is {3}".format(
self.owner, self.basename, self.seq, self.assigned
)
return f'{self.owner} {self.basename}.{self.seq}, assigned is {self.assigned}'

View File

@ -51,6 +51,7 @@ if typing.TYPE_CHECKING:
logger = logging.getLogger(__name__)
# pylint: disable=no-member
class User(UUIDModel):
"""
This class represents a single user, associated with one authenticator
@ -83,7 +84,7 @@ class User(UUIDModel):
userServices: 'models.manager.RelatedManager[UserService]'
permissions: 'models.manager.RelatedManager[Permissions]'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -204,9 +205,7 @@ class User(UUIDModel):
return store[str(self.uuid) + '_' + key]
def __str__(self):
return 'User {} (id:{}) from auth {}'.format(
self.name, self.id, self.manager.name
)
return f'{self.pretty_name} (id:{self.id})'
def cleanRelated(self) -> None:
"""
@ -217,9 +216,8 @@ class User(UUIDModel):
if self.manager.mfa:
self.manager.mfa.getInstance().resetData(mfas.MFA.getUserId(self))
@staticmethod
def beforeDelete(sender, **kwargs) -> None:
def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument
"""
Used to invoke the Service class "Destroy" before deleting it from database.

View File

@ -59,7 +59,9 @@ if typing.TYPE_CHECKING:
logger = logging.getLogger(__name__)
class UserService(UUIDModel): # pylint: disable=too-many-public-methods
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class UserService(UUIDModel):
"""
This is the base model for assigned user service and cached user services.
This are the real assigned services to users. ServicePool is the container (the group) of this elements.
@ -110,7 +112,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
) # Cache level must be 1 for L1 or 2 for L2, 0 if it is not cached service
src_hostname = models.CharField(max_length=MAX_DNS_NAME_LENGTH, default='')
src_ip = models.CharField(max_length=MAX_IPV6_LENGTH, default='') # Source IP of the user connecting to the service. Max length is 45 chars (ipv6)
src_ip = models.CharField(
max_length=MAX_IPV6_LENGTH, default=''
) # Source IP of the user connecting to the service. Max length is 45 chars (ipv6)
# "fake" declarations for type checking
# objects: 'models.manager.Manager["UserService"]'
@ -118,7 +122,7 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
sessions: 'models.manager.RelatedManager[UserServiceSession]'
accounting: 'AccountUsage'
class Meta(UUIDModel.Meta):
class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -316,8 +320,12 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
self.src_ip = ip[:MAX_IPV6_LENGTH]
self.src_hostname = hostname[:MAX_DNS_NAME_LENGTH]
if(len(ip) > MAX_IPV6_LENGTH or len(hostname) > MAX_DNS_NAME_LENGTH):
logger.info('Truncated connection source data to %s/%s', self.src_ip, self.src_hostname)
if len(ip) > MAX_IPV6_LENGTH or len(hostname) > MAX_DNS_NAME_LENGTH:
logger.info(
'Truncated connection source data to %s/%s',
self.src_ip,
self.src_hostname,
)
self.save(update_fields=['src_ip', 'src_hostname'])
@ -330,7 +338,10 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
:note: If the transport did not notified this data, this may be "empty"
"""
return (self.src_ip or '0.0.0.0', self.src_hostname or 'unknown') # nosec: no binding address
return (
self.src_ip or '0.0.0.0', # nosec: not a binding address
self.src_hostname or 'unknown',
)
def getOsManager(self) -> typing.Optional['OSManager']:
return self.deployed_service.osmanager
@ -436,7 +447,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
:note: If the state is Fase (set to not in use), a check for removal of this deployed service is launched.
"""
from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel
# pylint: disable=import-outside-toplevel
from uds.core.managers import userServiceManager
self.in_use = inUse
self.in_use_date = getSqlDatetime()
@ -513,9 +525,10 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
"""
Returns if this service is ready (not preparing or marked for removal)
"""
# Call to isReady of the instance
from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel
# pylint: disable=import-outside-toplevel
from uds.core.managers import userServiceManager
# Call to isReady of the instance
return userServiceManager().isReady(self)
def isInMaintenance(self) -> bool:
@ -537,7 +550,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
"""
Asks the UserServiceManager to cancel the current operation of this user deployed service.
"""
from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel
# pylint: disable=import-outside-toplevel
from uds.core.managers import userServiceManager
userServiceManager().cancel(self)
@ -563,7 +577,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
Args:
cacheLevel: New cache level to put object in
"""
from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel
# pylint: disable=import-outside-toplevel
from uds.core.managers import userServiceManager
userServiceManager().moveToLevel(self, cacheLevel)
@ -617,9 +632,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
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)
or self.publication == self.deployed_service.activePublication()
)
self.deployed_service.service
and self.deployed_service.service.getType().publicationType is None
) or self.publication == self.deployed_service.activePublication()
# Utility for logging
def log(self, message: str, level: int = log.INFO) -> None:

View File

@ -55,7 +55,7 @@ class UserServiceProperty(models.Model): # pylint: disable=too-many-public-meth
# "fake" declarations for type checking
# objects: 'models.manager.Manager[UserServiceProperty]'
class Meta:
class Meta: # pylint: disable=too-few-public-methods
"""
Meta class to declare default order and unique multiple field index
"""
@ -69,6 +69,4 @@ class UserServiceProperty(models.Model): # pylint: disable=too-many-public-meth
]
def __str__(self) -> str:
return "Property of {}. {}={}".format(
self.user_service.pk, self.name, self.value
)
return f'Property of {self.user_service.pk}. {self.name}={self.value}'