jumpserver/apps/assets/models.py

415 lines
16 KiB
Python
Raw Normal View History

2016-08-14 14:10:10 +00:00
# coding:utf-8
2016-09-04 09:15:26 +00:00
from __future__ import unicode_literals, absolute_import
2016-08-08 16:43:11 +00:00
2016-09-18 16:07:52 +00:00
import functools
2016-08-08 16:43:11 +00:00
from django.db import models
2016-10-26 11:10:14 +00:00
from django.core import serializers
2016-09-06 13:39:21 +00:00
import logging
2016-09-04 09:15:26 +00:00
from django.utils.translation import ugettext_lazy as _
2016-11-06 16:39:26 +00:00
from django.core.exceptions import ValidationError
2016-08-08 16:43:11 +00:00
2016-11-06 16:39:26 +00:00
from common.utils import signer, validate_ssh_private_key
2016-09-07 16:40:59 +00:00
2016-09-06 13:39:21 +00:00
logger = logging.getLogger(__name__)
2016-08-14 14:10:10 +00:00
class IDC(models.Model):
2016-09-04 09:15:26 +00:00
name = models.CharField(max_length=32, verbose_name=_('Name'))
bandwidth = models.CharField(max_length=32, blank=True, verbose_name=_('Bandwidth'))
contact = models.CharField(max_length=16, blank=True, verbose_name=_('Contact'))
phone = models.CharField(max_length=32, blank=True, verbose_name=_('Phone'))
address = models.CharField(max_length=128, blank=True, verbose_name=_("Address"))
2016-09-19 09:25:41 +00:00
intranet = models.TextField(blank=True, verbose_name=_('Intranet'))
extranet = models.TextField(blank=True, verbose_name=_('Extranet'))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Date added'))
2016-09-04 09:15:26 +00:00
operator = models.CharField(max_length=32, blank=True, verbose_name=_('Operator'))
created_by = models.CharField(max_length=32, blank=True, verbose_name=_('Created by'))
2016-09-04 11:05:47 +00:00
comment = models.TextField(blank=True, verbose_name=_('Comment'))
2016-08-14 14:10:10 +00:00
def __unicode__(self):
return self.name
2016-09-18 16:07:52 +00:00
@classmethod
def initial(cls):
return cls.objects.get_or_create(name=_('Default'), created_by=_('System'), comment=_('Default IDC'))[0]
2016-08-14 14:10:10 +00:00
class Meta:
db_table = 'idc'
2016-09-07 13:03:18 +00:00
@classmethod
def generate_fake(cls, count=100):
from random import seed, choice
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
idc = cls(name=forgery_py.name.full_name(),
bandwidth='200M',
contact=forgery_py.name.full_name(),
phone=forgery_py.address.phone(),
address=forgery_py.address.city() + forgery_py.address.street_address(),
operator=choice(['北京联通', '北京电信', 'BGP全网通']),
comment=forgery_py.lorem_ipsum.sentence(),
created_by='Fake')
try:
idc.save()
logger.debug('Generate fake asset group: %s' % idc.name)
except IntegrityError:
print('Error continue')
continue
2016-08-14 14:10:10 +00:00
class AssetExtend(models.Model):
2016-09-17 16:10:08 +00:00
key = models.CharField(max_length=64, verbose_name=_('KEY'))
value = models.CharField(max_length=64, verbose_name=_('VALUE'))
2016-09-04 11:05:47 +00:00
created_by = models.CharField(max_length=32, blank=True, verbose_name=_("Created by"))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True, null=True)
2016-09-04 11:05:47 +00:00
comment = models.TextField(blank=True, verbose_name=_('Comment'))
2016-09-04 09:43:03 +00:00
def __unicode__(self):
2016-09-09 16:29:57 +00:00
return '%(key)s: %(value)s' % {'key': self.key, 'value': self.value}
@classmethod
def initial(cls):
for k, v in (
(_('status'), _('In use')),
(_('status'), _('Out of use')),
(_('type'), _('Server')),
(_('type'), _('VM')),
(_('type'), _('Switch')),
(_('type'), _('Router')),
(_('type'), _('Firewall')),
(_('type'), _('Storage')),
(_('env'), _('Production')),
(_('env'), _('Development')),
(_('env'), _('Testing')),
):
cls.objects.create(key=k, value=v, created_by='System')
2016-09-04 09:43:03 +00:00
class Meta:
2016-09-06 13:39:21 +00:00
db_table = 'asset_extend'
2016-09-18 16:07:52 +00:00
unique_together = ('key', 'value')
2016-08-14 14:10:10 +00:00
2016-11-06 16:39:26 +00:00
def private_key_validator(value):
if not validate_ssh_private_key(value):
raise ValidationError(
_('%(value)s is not an even number'),
params={'value': value},
)
2016-09-04 09:43:03 +00:00
class AdminUser(models.Model):
2016-09-06 10:43:13 +00:00
name = models.CharField(max_length=128, unique=True, verbose_name=_('Name'))
username = models.CharField(max_length=16, verbose_name=_('Username'))
2016-11-06 16:39:26 +00:00
_password = models.CharField(max_length=256, blank=True, null=True, verbose_name=_('Password'))
_private_key = models.CharField(max_length=4096, blank=True, null=True, verbose_name=_('SSH private key'),
validators=[private_key_validator,])
2016-09-08 10:12:53 +00:00
_public_key = models.CharField(max_length=4096, blank=True, verbose_name=_('SSH public key'))
2016-09-04 11:05:47 +00:00
comment = models.TextField(blank=True, verbose_name=_('Comment'))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True, null=True)
2016-09-08 10:12:53 +00:00
created_by = models.CharField(max_length=32, null=True, verbose_name=_('Created by'))
2016-08-14 14:10:10 +00:00
2016-09-04 09:43:03 +00:00
def __unicode__(self):
return self.name
2016-08-14 14:10:10 +00:00
2016-09-07 16:40:59 +00:00
@property
def password(self):
2016-11-06 14:45:26 +00:00
return signer.unsign(self._password)
2016-09-07 16:40:59 +00:00
@password.setter
def password(self, password_raw):
2016-11-01 09:21:16 +00:00
self._password = signer.sign(password_raw)
2016-09-07 16:40:59 +00:00
@property
def private_key(self):
2016-11-01 09:21:16 +00:00
return signer.unsign(self._private_key)
2016-09-07 16:40:59 +00:00
@private_key.setter
def private_key(self, private_key_raw):
2016-11-01 09:21:16 +00:00
self._private_key = signer.sign(private_key_raw)
2016-09-07 16:40:59 +00:00
@property
def public_key(self):
2016-11-01 09:21:16 +00:00
return signer.unsign(self._public_key)
2016-09-07 16:40:59 +00:00
@public_key.setter
def public_key(self, public_key_raw):
2016-11-01 09:21:16 +00:00
self._public_key = signer.sign(public_key_raw)
2016-09-07 16:40:59 +00:00
2016-11-06 14:45:26 +00:00
@property
def assets_amount(self):
return self.assets.count()
2016-09-04 09:43:03 +00:00
class Meta:
2016-09-06 13:39:21 +00:00
db_table = 'admin_user'
2016-09-04 09:43:03 +00:00
2016-09-07 16:40:59 +00:00
@classmethod
def generate_fake(cls, count=100):
2016-09-08 10:12:53 +00:00
from random import seed
2016-09-07 16:40:59 +00:00
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
obj = cls(name=forgery_py.name.full_name(),
username=forgery_py.internet.user_name(),
password=forgery_py.lorem_ipsum.word(),
comment=forgery_py.lorem_ipsum.sentence(),
created_by='Fake')
try:
obj.save()
logger.debug('Generate fake asset group: %s' % obj.name)
except IntegrityError:
print('Error continue')
continue
2016-09-04 09:43:03 +00:00
2016-09-06 13:39:21 +00:00
class SystemUser(models.Model):
2016-09-04 11:05:47 +00:00
PROTOCOL_CHOICES = (
('ssh', 'ssh'),
)
name = models.CharField(max_length=128, unique=True, verbose_name=_('Name'))
2016-09-06 10:43:13 +00:00
username = models.CharField(max_length=16, verbose_name=_('Username'))
2016-09-08 16:09:49 +00:00
_password = models.CharField(max_length=256, blank=True, verbose_name=_('Password'))
protocol = models.CharField(max_length=16, choices=PROTOCOL_CHOICES, default='ssh', verbose_name=_('Protocol'))
_private_key = models.CharField(max_length=4096, blank=True, verbose_name=_('SSH private key'))
_public_key = models.CharField(max_length=4096, blank=True, verbose_name=_('SSH public key'))
as_default = models.BooleanField(default=False, verbose_name=_('As default'))
2016-09-04 11:05:47 +00:00
auto_push = models.BooleanField(default=True, verbose_name=_('Auto push'))
auto_update = models.BooleanField(default=True, verbose_name=_('Auto update pass/key'))
2016-09-08 16:09:49 +00:00
sudo = models.TextField(max_length=4096, default='/user/bin/whoami', verbose_name=_('Sudo'))
shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell'))
2016-09-04 11:05:47 +00:00
home = models.CharField(max_length=64, blank=True, verbose_name=_('Home'))
2016-09-08 16:09:49 +00:00
uid = models.IntegerField(null=True, blank=True, verbose_name=_('Uid'))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True)
2016-09-07 16:40:59 +00:00
created_by = models.CharField(max_length=32, blank=True, verbose_name=_('Created by'))
2016-09-08 16:09:49 +00:00
comment = models.TextField(max_length=128, blank=True, verbose_name=_('Comment'))
2016-08-14 14:10:10 +00:00
2016-09-04 09:43:03 +00:00
def __unicode__(self):
return self.name
2016-08-14 14:10:10 +00:00
2016-09-08 16:09:49 +00:00
@property
def password(self):
2016-11-01 11:31:35 +00:00
return signer.unsign(self._password)
2016-09-08 16:09:49 +00:00
@password.setter
def password(self, password_raw):
2016-11-01 09:21:16 +00:00
self._password = signer.sign(password_raw)
2016-09-08 16:09:49 +00:00
@property
def private_key(self):
2016-11-01 11:31:35 +00:00
return signer.unsign(self._private_key)
2016-09-08 16:09:49 +00:00
@private_key.setter
def private_key(self, private_key_raw):
2016-11-01 11:31:35 +00:00
self._private_key = signer.sign(private_key_raw)
2016-09-08 16:09:49 +00:00
@property
def public_key(self):
2016-11-01 11:31:35 +00:00
return signer.unsign(self._public_key)
2016-09-08 16:09:49 +00:00
@public_key.setter
def public_key(self, public_key_raw):
2016-11-01 11:31:35 +00:00
self._public_key = signer.sign(public_key_raw)
2016-09-08 16:09:49 +00:00
2016-09-16 12:53:10 +00:00
def get_assets_inherit_from_asset_groups(self):
assets = set()
asset_groups = self.asset_groups.all()
for asset_group in asset_groups:
for asset in asset_group.assets.all():
setattr(asset, 'is_inherit_from_asset_groups', True)
setattr(asset, 'inherit_from_asset_groups',
getattr(asset, b'inherit_from_asset_groups', set()).add(asset_group))
assets.add(asset)
return assets
def get_assets(self):
assets = set(self.assets.all()) | self.get_assets_inherit_from_asset_groups()
return list(assets)
2016-11-06 14:45:26 +00:00
@property
def assets_amount(self):
return self.assets.count()
2016-09-04 09:43:03 +00:00
class Meta:
2016-09-06 13:39:21 +00:00
db_table = 'system_user'
2016-09-08 16:09:49 +00:00
@classmethod
def generate_fake(cls, count=100):
from random import seed
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
obj = cls(name=forgery_py.name.full_name(),
username=forgery_py.internet.user_name(),
password=forgery_py.lorem_ipsum.word(),
comment=forgery_py.lorem_ipsum.sentence(),
created_by='Fake')
try:
obj.save()
logger.debug('Generate fake asset group: %s' % obj.name)
except IntegrityError:
print('Error continue')
continue
2016-09-06 13:39:21 +00:00
class AssetGroup(models.Model):
name = models.CharField(max_length=64, unique=True, verbose_name=_('Name'))
2016-09-19 17:13:50 +00:00
system_users = models.ManyToManyField(SystemUser, related_name='asset_groups', blank=True)
2016-09-06 13:39:21 +00:00
created_by = models.CharField(max_length=32, blank=True, verbose_name=_('Created by'))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Date added'))
2016-09-06 13:39:21 +00:00
comment = models.TextField(blank=True, verbose_name=_('Comment'))
2016-08-14 14:10:10 +00:00
2016-09-04 09:43:03 +00:00
def __unicode__(self):
return self.name
2016-08-14 14:10:10 +00:00
2016-09-04 09:43:03 +00:00
class Meta:
2016-09-06 13:39:21 +00:00
db_table = 'asset_group'
@classmethod
def initial(cls):
2016-09-17 16:10:08 +00:00
asset_group = cls(name=_('Default'), comment=_('Default asset group'))
2016-09-06 13:39:21 +00:00
asset_group.save()
@classmethod
def generate_fake(cls, count=100):
from random import seed
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
group = cls(name=forgery_py.name.full_name(),
comment=forgery_py.lorem_ipsum.sentence(),
created_by='Fake')
try:
group.save()
logger.debug('Generate fake asset group: %s' % group.name)
except IntegrityError:
print('Error continue')
continue
2016-09-04 09:50:30 +00:00
2016-09-04 10:06:14 +00:00
2016-09-18 16:07:52 +00:00
def get_default_extend(key, value):
2016-09-19 16:39:33 +00:00
try:
return AssetExtend.objects.get_or_create(key=key, value=value)[0]
except:
return None
2016-09-18 16:07:52 +00:00
def get_default_idc():
return IDC.initial()
2016-09-17 16:10:08 +00:00
2016-09-18 16:07:52 +00:00
2016-09-04 10:06:14 +00:00
class Asset(models.Model):
2016-10-28 07:09:38 +00:00
ip = models.GenericIPAddressField(max_length=32, verbose_name=_('IP'), db_index=True)
2016-09-04 10:06:14 +00:00
other_ip = models.CharField(max_length=255, null=True, blank=True, verbose_name=_('Other IP'))
remote_card_ip = models.CharField(max_length=16, null=True, blank=True, verbose_name=_('Remote card IP'))
2016-10-28 07:09:38 +00:00
hostname = models.CharField(max_length=128, unique=True, verbose_name=_('Hostname'))
2016-09-17 15:43:41 +00:00
port = models.IntegerField(default=22, verbose_name=_('Port'))
2016-09-17 06:50:14 +00:00
groups = models.ManyToManyField(AssetGroup, blank=True, related_name='assets', verbose_name=_('Asset groups'))
admin_user = models.ForeignKey(AdminUser, null=True, blank=True, related_name='assets',
2016-09-08 10:12:53 +00:00
on_delete=models.SET_NULL, verbose_name=_("Admin user"))
2016-09-16 08:09:11 +00:00
system_users = models.ManyToManyField(SystemUser, blank=True, related_name='assets', verbose_name=_("System User"))
2016-11-09 11:29:15 +00:00
idc = models.ForeignKey(IDC, blank=True, null=True, related_name='assets',
2016-09-19 16:39:33 +00:00
on_delete=models.SET_NULL, verbose_name=_('IDC'),)
2016-09-08 10:12:53 +00:00
mac_address = models.CharField(max_length=20, null=True, blank=True, verbose_name=_("Mac address"))
2016-09-04 10:06:14 +00:00
brand = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('Brand'))
2016-09-17 15:43:41 +00:00
cpu = models.CharField(max_length=64, null=True, blank=True, verbose_name=_('CPU'))
2016-09-04 10:06:14 +00:00
memory = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('Memory'))
disk = models.CharField(max_length=1024, null=True, blank=True, verbose_name=_('Disk'))
os = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('OS'))
cabinet_no = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Cabinet number'))
cabinet_pos = models.IntegerField(null=True, blank=True, verbose_name=_('Cabinet position'))
2016-09-17 06:50:14 +00:00
number = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Asset number'))
2016-09-18 16:07:52 +00:00
status = models.ForeignKey(AssetExtend, null=True, blank=True,
2016-09-19 16:39:33 +00:00
related_name="status_asset", verbose_name=_('Asset status'),)
# default=functools.partial(get_default_extend, 'status', 'In use'))
2016-09-28 04:05:34 +00:00
type = models.ForeignKey(AssetExtend, blank=True,null=True, limit_choices_to={'key': 'type'},
2016-09-19 16:39:33 +00:00
related_name="type_asset", verbose_name=_('Asset type'),)
# default=functools.partial(get_default_extend, 'type','Server'))
env = models.ForeignKey(AssetExtend, blank=True, null=True, limit_choices_to={'key': 'env'},
related_name="env_asset", verbose_name=_('Asset environment'),)
# default=functools.partial(get_default_extend, 'env', 'Production'))
2016-09-17 06:50:14 +00:00
sn = models.CharField(max_length=128, null=True, blank=True, verbose_name=_('Serial number'))
created_by = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Created by'))
2016-09-04 10:06:14 +00:00
is_active = models.BooleanField(default=True, verbose_name=_('Is active'))
2016-10-15 15:34:02 +00:00
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name=_('Date added'))
2016-10-20 11:01:57 +00:00
comment = models.TextField(max_length=128, default='', blank=True, verbose_name=_('Comment'))
tags = models.ManyToManyField('Tag', blank=True, verbose_name=_('Tags'))
2016-09-04 10:06:14 +00:00
def __unicode__(self):
2016-09-08 16:09:49 +00:00
return '%(ip)s:%(port)s' % {'ip': self.ip, 'port': self.port}
2016-09-04 10:06:14 +00:00
2016-11-06 13:29:04 +00:00
@property
2016-09-19 16:39:33 +00:00
def is_valid(self):
warning = ''
if not self.is_active:
warning += ' inactive'
else:
return True, ''
return False, warning
2016-09-04 10:06:14 +00:00
2016-10-26 11:10:14 +00:00
def json(self):
pass
2016-09-04 10:06:14 +00:00
class Meta:
db_table = 'asset'
2016-09-18 16:07:52 +00:00
unique_together = ('ip', 'port')
2016-09-04 10:06:14 +00:00
2016-09-07 12:05:42 +00:00
@classmethod
def generate_fake(cls, count=100):
2016-09-16 08:09:11 +00:00
from random import seed, choice
2016-09-07 12:05:42 +00:00
import forgery_py
from django.db import IntegrityError
seed()
for i in range(count):
2016-09-17 15:43:41 +00:00
asset = cls(ip='%s.%s.%s.%s' % (i, i, i, i),
hostname=forgery_py.internet.user_name(True),
2016-09-16 08:09:11 +00:00
admin_user=choice(AdminUser.objects.all()),
idc=choice(IDC.objects.all()),
2016-09-07 12:05:42 +00:00
port=22,
created_by='Fake')
try:
asset.save()
2016-09-16 08:09:11 +00:00
asset.system_users = [choice(SystemUser.objects.all()) for i in range(3)]
asset.groups = [choice(AssetGroup.objects.all()) for i in range(3)]
2016-09-07 12:05:42 +00:00
logger.debug('Generate fake asset : %s' % asset.ip)
except IntegrityError:
print('Error continue')
continue
2016-09-04 10:06:14 +00:00
2016-09-17 15:43:41 +00:00
class Tag(models.Model):
2016-10-15 15:34:02 +00:00
name = models.CharField(max_length=64, unique=True, verbose_name=_('Name'))
2016-10-16 14:12:13 +00:00
created_time = models.DateTimeField(auto_now_add=True, verbose_name=_('Create time'))
2016-10-07 15:04:37 +00:00
created_by = models.CharField(max_length=32, null=True, blank=True, verbose_name=_('Created by'))
2016-09-04 10:06:14 +00:00
def __unicode__(self):
2016-10-07 15:04:37 +00:00
return self.name
2016-09-04 10:06:14 +00:00
2016-10-15 15:34:02 +00:00
__str__ = __unicode__
2016-09-04 10:06:14 +00:00
class Meta:
2016-09-18 16:07:52 +00:00
db_table = 'tag'
2016-09-04 10:06:14 +00:00
2016-09-07 16:40:59 +00:00
2016-09-19 16:39:33 +00:00
def init_all_models():
2016-09-17 16:10:08 +00:00
for cls in (AssetExtend, AssetGroup):
cls.initial()
2016-09-04 10:06:14 +00:00
2016-09-07 16:40:59 +00:00
def generate_fake():
2016-09-16 08:09:11 +00:00
for cls in (AssetGroup, IDC, AdminUser, SystemUser, Asset):
2016-09-07 16:40:59 +00:00
cls.generate_fake()
2016-09-18 16:07:52 +00:00
def flush_all():
for cls in (AssetGroup, AssetExtend, IDC, AdminUser, SystemUser, Asset):
cls.objects.all().delete()