class Node(OrgModelMixin, SomeNodesMixin, FamilyMixin, NodeAssetsMixin): id = models.UUIDField(default=uuid.uuid4, primary_key=True) key = models.CharField(unique=True, max_length=64, verbose_name=_("Key")) # '1:1:1:1' value = models.CharField(max_length=128, verbose_name=_("Value")) full_value = models.CharField(max_length=4096, verbose_name=_('Full value'), default='') child_mark = models.IntegerField(default=0) date_create = models.DateTimeField(auto_now_add=True) parent_key = models.CharField(max_length=64, verbose_name=_("Parent key"), db_index=True, default='') assets_amount = models.IntegerField(default=0) objects = OrgManager.from_queryset(NodeQuerySet)() is_node = True _parents = None class Meta: verbose_name = _("Node") ordering = ['parent_key', 'value'] def __str__(self): return self.full_value # def __eq__(self, other): # if not other: # return False # return self.id == other.id # def __gt__(self, other): self_key = [int(k) for k in self.key.split(':')] other_key = [int(k) for k in other.key.split(':')] self_parent_key = self_key[:-1] other_parent_key = other_key[:-1] if self_parent_key and self_parent_key == other_parent_key: return self.value > other.value return self_key > other_key def __lt__(self, other): return not self.__gt__(other) @property def name(self): return self.value def computed_full_value(self): # 不要在列表中调用该属性 values = self.__class__.objects.filter( key__in=self.get_ancestor_keys() ).values_list('key', 'value') values = [v for k, v in sorted(values, key=lambda x: len(x[0]))] values.append(str(self.value)) return '/' + '/'.join(values) @property def level(self): return len(self.key.split(':')) def as_tree_node(self): from common.tree import TreeNode name = '{} ({})'.format(self.value, self.assets_amount) data = { 'id': self.key, 'name': name, 'title': name, 'pId': self.parent_key, 'isParent': True, 'open': self.is_org_root(), 'meta': { 'node': { "id": self.id, "name": self.name, "value": self.value, "key": self.key, "assets_amount": self.assets_amount, }, 'type': 'node' } } tree_node = TreeNode(**data) return tree_node def has_children_or_has_assets(self): if self.children or self.get_assets().exists(): return True return False def delete(self, using=None, keep_parents=False): if self.has_children_or_has_assets(): return return super().delete(using=using, keep_parents=keep_parents) def update_child_full_value(self): nodes = self.get_all_children(with_self=True) sort_key_func = lambda n: [int(i) for i in n.key.split(':')] nodes_sorted = sorted(list(nodes), key=sort_key_func) nodes_mapper = {n.key: n for n in nodes_sorted} for node in nodes_sorted: parent = nodes_mapper.get(node.parent_key) if not parent: logger.error(f'Node parent node in mapper: {node.parent_key} {node.value}') continue node.full_value = parent.full_value + '/' + node.value self.__class__.objects.bulk_update(nodes, ['full_value']) def save(self, *args, **kwargs): self.full_value = self.computed_full_value() instance = super().save(*args, **kwargs) self.update_child_full_value() return instance
class Asset(ProtocolsMixin, NodesRelationMixin, OrgModelMixin): # Important PLATFORM_CHOICES = ( ('Linux', 'Linux'), ('Unix', 'Unix'), ('MacOS', 'MacOS'), ('BSD', 'BSD'), ('Windows', 'Windows'), ('Windows2016', 'Windows(2016)'), ('Other', 'Other'), ) id = models.UUIDField(default=uuid.uuid4, primary_key=True) ip = models.CharField(max_length=128, verbose_name=_('IP'), db_index=True) hostname = models.CharField(max_length=128, verbose_name=_('Hostname')) protocol = models.CharField(max_length=128, default=ProtocolsMixin.PROTOCOL_SSH, choices=ProtocolsMixin.PROTOCOL_CHOICES, verbose_name=_('Protocol')) port = models.IntegerField(default=22, verbose_name=_('Port')) protocols = models.CharField(max_length=128, default='ssh/22', blank=True, verbose_name=_("Protocols")) platform = models.CharField(max_length=128, choices=PLATFORM_CHOICES, default='Linux', verbose_name=_('Platform')) domain = models.ForeignKey("assets.Domain", null=True, blank=True, related_name='assets', verbose_name=_("Domain"), on_delete=models.SET_NULL) nodes = models.ManyToManyField('assets.Node', default=default_node, related_name='assets', verbose_name=_("Nodes")) is_active = models.BooleanField(default=True, verbose_name=_('Is active')) # Auth admin_user = models.ForeignKey('assets.AdminUser', on_delete=models.PROTECT, null=True, verbose_name=_("Admin user"), related_name='assets') # Some information public_ip = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Public IP')) number = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Asset number')) # Collect vendor = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('Vendor')) model = models.CharField(max_length=54, null=True, blank=True, verbose_name=_('Model')) sn = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('Serial number')) cpu_model = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('CPU model')) cpu_count = models.IntegerField(null=True, verbose_name=_('CPU count')) cpu_cores = models.IntegerField(null=True, verbose_name=_('CPU cores')) cpu_vcpus = models.IntegerField(null=True, verbose_name=_('CPU vcpus')) memory = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('Memory')) disk_total = models.CharField(max_length=1024, null=True, blank=True, verbose_name=_('Disk total')) disk_info = models.CharField(max_length=1024, null=True, blank=True, verbose_name=_('Disk info')) os = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('OS')) os_version = models.CharField(max_length=16, null=True, blank=True, verbose_name=_('OS version')) os_arch = models.CharField(max_length=16, blank=True, null=True, verbose_name=_('OS arch')) hostname_raw = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Hostname raw')) labels = models.ManyToManyField('assets.Label', blank=True, related_name='assets', verbose_name=_("Labels")) created_by = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Created by')) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date created')) comment = models.TextField(max_length=128, default='', blank=True, verbose_name=_('Comment')) objects = OrgManager.from_queryset(AssetQuerySet)() _connectivity = None def __str__(self): return '{0.hostname}({0.ip})'.format(self) @property def is_valid(self): warning = '' if not self.is_active: warning += ' inactive' if warning: return False, warning return True, warning def is_windows(self): if self.platform in ("Windows", "Windows2016"): return True else: return False def is_unixlike(self): if self.platform not in ("Windows", "Windows2016", "Other"): return True else: return False def is_support_ansible(self): return self.has_protocol('ssh') and self.platform not in ("Other", ) @property def cpu_info(self): info = "" if self.cpu_model: info += self.cpu_model if self.cpu_count and self.cpu_cores: info += "{}*{}".format(self.cpu_count, self.cpu_cores) return info @property def hardware_info(self): if self.cpu_count: return '{} Core {} {}'.format( self.cpu_vcpus or self.cpu_count * self.cpu_cores, self.memory, self.disk_total) else: return '' @property def connectivity(self): if self._connectivity: return self._connectivity if not self.admin_user: return Connectivity.unknown() connectivity = self.admin_user.get_asset_connectivity(self) return connectivity @connectivity.setter def connectivity(self, value): if not self.admin_user: return self.admin_user.set_asset_connectivity(self, value) def get_auth_info(self): if not self.admin_user: return {} self.admin_user.load_specific_asset_auth(self) info = { 'username': self.admin_user.username, 'password': self.admin_user.password, 'private_key': self.admin_user.private_key_file, } return info def as_node(self): from .node import Node fake_node = Node() fake_node.id = self.id fake_node.key = self.id fake_node.value = self.hostname fake_node.asset = self fake_node.is_node = False return fake_node def as_tree_node(self, parent_node): from common.tree import TreeNode icon_skin = 'file' if self.platform.lower() == 'windows': icon_skin = 'windows' elif self.platform.lower() == 'linux': icon_skin = 'linux' data = { 'id': str(self.id), 'name': self.hostname, 'title': self.ip, 'pId': parent_node.key, 'isParent': False, 'open': False, 'iconSkin': icon_skin, 'meta': { 'type': 'asset', 'asset': { 'id': self.id, 'hostname': self.hostname, 'ip': self.ip, 'protocols': self.protocols_as_list, 'platform': self.platform, } } } tree_node = TreeNode(**data) return tree_node class Meta: unique_together = [('org_id', 'hostname')] verbose_name = _("Asset") @classmethod def generate_fake(cls, count=100): from .user import AdminUser, SystemUser from random import seed, choice from django.db import IntegrityError from .node import Node from orgs.utils import get_current_org from orgs.models import Organization org = get_current_org() if not org or not org.is_real(): Organization.default().change_to() nodes = list(Node.objects.all()) seed() for i in range(count): ip = [str(i) for i in random.sample(range(255), 4)] asset = cls(ip='.'.join(ip), hostname='.'.join(ip), admin_user=choice(AdminUser.objects.all()), created_by='Fake') try: asset.save() asset.protocols = 'ssh/22' if nodes and len(nodes) > 3: _nodes = random.sample(nodes, 3) else: _nodes = [Node.default_node()] asset.nodes.set(_nodes) logger.debug('Generate fake asset : %s' % asset.ip) except IntegrityError: print('Error continue') continue
class Node(OrgModelMixin, SomeNodesMixin, TreeMixin, FamilyMixin, FullValueMixin, NodeAssetsMixin): id = models.UUIDField(default=uuid.uuid4, primary_key=True) key = models.CharField(unique=True, max_length=64, verbose_name=_("Key")) # '1:1:1:1' value = models.CharField(max_length=128, verbose_name=_("Value")) child_mark = models.IntegerField(default=0) date_create = models.DateTimeField(auto_now_add=True) objects = OrgManager.from_queryset(NodeQuerySet)() is_node = True _parents = None class Meta: verbose_name = _("Node") ordering = ['key'] def __str__(self): return self.value # def __eq__(self, other): # if not other: # return False # return self.id == other.id # def __gt__(self, other): self_key = [int(k) for k in self.key.split(':')] other_key = [int(k) for k in other.key.split(':')] self_parent_key = self_key[:-1] other_parent_key = other_key[:-1] if self_parent_key and self_parent_key == other_parent_key: return self.value > other.value return self_key > other_key def __lt__(self, other): return not self.__gt__(other) @property def name(self): return self.value @property def level(self): return len(self.key.split(':')) @classmethod def refresh_nodes(cls): cls.refresh_tree() @classmethod def refresh_assets(cls): cls.refresh_node_assets() def as_tree_node(self): from common.tree import TreeNode name = '{} ({})'.format(self.value, self.assets_amount) data = { 'id': self.key, 'name': name, 'title': name, 'pId': self.parent_key, 'isParent': True, 'open': self.is_org_root(), 'meta': { 'node': { "id": self.id, "name": self.name, "value": self.value, "key": self.key, "assets_amount": self.assets_amount, }, 'type': 'node' } } tree_node = TreeNode(**data) return tree_node def has_children_or_has_assets(self): if self.children or self.get_assets().exists(): return True return False def delete(self, using=None, keep_parents=False): if self.has_children_or_has_assets(): return return super().delete(using=using, keep_parents=keep_parents) @classmethod def generate_fake(cls, count=100): import random org = get_current_org() if not org or not org.is_real(): Organization.default().change_to() nodes = list(cls.objects.all()) if count > 100: length = 100 else: length = count for i in range(length): node = random.choice(nodes) child = node.create_child('Node {}'.format(i)) print("{}. {}".format(i, child))
class Node(OrgModelMixin, SomeNodesMixin, FamilyMixin, NodeAssetsMixin): id = models.UUIDField(default=uuid.uuid4, primary_key=True) key = models.CharField(unique=True, max_length=64, verbose_name=_("Key")) # '1:1:1:1' value = models.CharField(max_length=128, verbose_name=_("Value")) child_mark = models.IntegerField(default=0) date_create = models.DateTimeField(auto_now_add=True) parent_key = models.CharField(max_length=64, verbose_name=_("Parent key"), db_index=True, default='') assets_amount = models.IntegerField(default=0) objects = OrgManager.from_queryset(NodeQuerySet)() is_node = True _parents = None class Meta: verbose_name = _("Node") ordering = ['key'] def __str__(self): return self.value # def __eq__(self, other): # if not other: # return False # return self.id == other.id # def __gt__(self, other): self_key = [int(k) for k in self.key.split(':')] other_key = [int(k) for k in other.key.split(':')] self_parent_key = self_key[:-1] other_parent_key = other_key[:-1] if self_parent_key and self_parent_key == other_parent_key: return self.value > other.value return self_key > other_key def __lt__(self, other): return not self.__gt__(other) @property def name(self): return self.value @lazyproperty def full_value(self): # 不要在列表中调用该属性 values = self.__class__.objects.filter( key__in=self.get_ancestor_keys()).values_list('key', 'value') values = [v for k, v in sorted(values, key=lambda x: len(x[0]))] values.append(self.value) return ' / '.join(values) @property def level(self): return len(self.key.split(':')) def as_tree_node(self): from common.tree import TreeNode name = '{} ({})'.format(self.value, self.assets_amount) data = { 'id': self.key, 'name': name, 'title': name, 'pId': self.parent_key, 'isParent': True, 'open': self.is_org_root(), 'meta': { 'node': { "id": self.id, "name": self.name, "value": self.value, "key": self.key, "assets_amount": self.assets_amount, }, 'type': 'node' } } tree_node = TreeNode(**data) return tree_node def has_children_or_has_assets(self): if self.children or self.get_assets().exists(): return True return False def delete(self, using=None, keep_parents=False): if self.has_children_or_has_assets(): return return super().delete(using=using, keep_parents=keep_parents)