Skip to content

Commit

Permalink
Merge branch '2-cmdb'
Browse files Browse the repository at this point in the history
  • Loading branch information
RobbieHan committed Feb 23, 2019
2 parents 6b413bc + 2646254 commit 3182032
Show file tree
Hide file tree
Showing 16 changed files with 3,916 additions and 15 deletions.
63 changes: 61 additions & 2 deletions apps/cmdb/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from django import forms

from .models import Code
from .models import Code, DeviceInfo, ConnectionInfo, DeviceFile


class CodeCreateForm(forms.ModelForm):
Expand Down Expand Up @@ -43,4 +43,63 @@ def clean(self):
raise forms.ValidationError(msg)
if matching_code.filter(value=value).exists():
msg = 'value:{} 已经存在'.format(value)
raise forms.ValidationError(msg)
raise forms.ValidationError(msg)


class DeviceCreateForm(forms.ModelForm):
class Meta:
model = DeviceInfo
exclude = ['dev_connection']
error_messages = {
'hostname': {'required': '请填写设备地址'},
'buyDate': {'required': '请填写购买日期'},
'warrantyDate': {'required': '请填写到保日期'}
}

def clean(self):
cleaned_data = super(DeviceCreateForm, self).clean()
hostname = cleaned_data.get('hostname')

if DeviceInfo.objects.filter(hostname=hostname).count():
raise forms.ValidationError('设备地址:{}已存在'.format(hostname))


class DeviceUpdateForm(DeviceCreateForm):
def clean(self):
cleaned_data = self.cleaned_data
hostname = cleaned_data.get('hostname')

if self.instance:
matching_device = DeviceInfo.objects.exclude(pk=self.instance.pk)
if matching_device.filter(hostname=hostname).exists():
raise forms.ValidationError('设备地址:{}已存在'.format(hostname))


class ConnectionInfoForm(forms.ModelForm):

class Meta:
model = ConnectionInfo
fields = '__all__'

error_messages = {
'port': {'required': '端口不能为空'},
}

def clean(self):
cleaned_data = self.cleaned_data
username = cleaned_data.get('username')
password = cleaned_data.get('password')
private_key = cleaned_data.get('private_key')
auth_type = cleaned_data.get('auth_type')
if len(username) == 0:
raise forms.ValidationError('用户名不能为空!')
if auth_type == 'password' and len(password) == 0:
raise forms.ValidationError('认证类型为[密码]时,必须设置密码信息!')
if auth_type == 'private_key' and len(private_key) == 0:
raise forms.ValidationError('认证类型为[密钥]时,必须设置密钥信息!')


class DeviceFileUploadForm(forms.ModelForm):
class Meta:
model = DeviceFile
fields = '__all__'
14 changes: 7 additions & 7 deletions apps/cmdb/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Meta:
class Code(AbstractMode):
key = models.CharField(max_length=80, verbose_name='键')
value = models.CharField(max_length=80, verbose_name='值')
desc = models.BooleanField(default=True, verbose_name='备注')
desc = models.CharField(max_length=100, blank=True, default='', verbose_name='备注')

class Meta:
verbose_name = '字典'
Expand Down Expand Up @@ -53,11 +53,11 @@ class Meta:


class DeviceAbstract(models.Model):
sys_hostname = models.CharField(max_length=50, blank=True, default='', verbose_name='主机名')
mac_address = models.CharField(max_length=50, blank=True, default='', verbose_name='MAC地址')
sn_number = models.CharField(max_length=50, blank=True, default='', verbose_name='SN号码')
os_type = models.CharField(max_length=50, blank=True, default='', verbose_name='系统类型')
device_type = models.CharField(max_length=50, blank=True, default='', verbose_name='设备类型')
sys_hostname = models.CharField(max_length=150, blank=True, default='', verbose_name='主机名')
mac_address = models.CharField(max_length=150, blank=True, default='', verbose_name='MAC地址')
sn_number = models.CharField(max_length=150, blank=True, default='', verbose_name='SN号码')
os_type = models.CharField(max_length=150, blank=True, default='', verbose_name='系统类型')
device_type = models.CharField(max_length=150, blank=True, default='', verbose_name='设备类型')

class Meta:
abstract = True
Expand Down Expand Up @@ -100,7 +100,7 @@ class DeviceInfo(AbstractMode, DeviceAbstract, TimeAbstract):
warrantyDate = models.DateField(default=datetime.now, verbose_name="到保日期")
desc = models.TextField(blank=True, default='', verbose_name='备注信息')
changed_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
history = HistoricalRecords(excluded_fields=['add_time', 'modify_time'])
history = HistoricalRecords(excluded_fields=['add_time', 'modify_time', 'parent'])

class Meta:
verbose_name = '设备信息'
Expand Down
39 changes: 36 additions & 3 deletions apps/cmdb/signals.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,46 @@
import os

from django.dispatch import receiver
from django.db.models.signals import post_delete
from django.db.models.signals import post_delete, post_save

from .models import DeviceFile
from .models import DeviceFile, DeviceInfo, ConnectionInfo
from utils.db_utils import MongodbDriver


@receiver(post_delete, sender=DeviceFile)
def auto_delete_file(sender, instance, **kwargs):
if instance.file_content:
if os.path.isfile(instance.file_content.path):
os.remove(instance.file_content.path)
os.remove(instance.file_content.path)


@receiver(post_save, sender=DeviceInfo)
def auto_compare_diff(sender, instance, **kwargs):
record = instance.history.latest()
prev_record = record.prev_record
ope_type = {'~': 'update', '+': 'create', '-': 'delete'}
compare_result = {
'id': record.id,
'changed_by': record.changed_by.name,
'history_type': ope_type[record.history_type],
'history_date': record.history_date
}
changes = {}
if prev_record is not None:
delta = record.diff_against(prev_record)
for change in delta.changes:
changes[change.field] = [change.old, change.new]
compare_result['changes'] = changes
if compare_result['changes'] or compare_result['history_type'] == 'create':
try:
mongo = MongodbDriver(collection='change_compare')
mongo.insert(compare_result)
except Exception as e:
pass


@receiver(post_delete, sender=DeviceInfo)
def auto_delete_connection(sender, instance, **kwargs):
dev_connection = getattr(instance, 'dev_connection')
if dev_connection:
ConnectionInfo.objects.filter(id=dev_connection).delete()
3 changes: 3 additions & 0 deletions apps/cmdb/templatetags/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @Time : 2019/2/17 21:28
# @Author : RobbieHan
# @File : __init__.py.py
60 changes: 60 additions & 0 deletions apps/cmdb/templatetags/extra_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from django import template
from django.db.models.query import QuerySet
from django.contrib.auth import get_user_model

from cmdb.models import Code, Cabinet

register = template.Library()

User = get_user_model()


@register.simple_tag
def get_con(context, arg, field):
if isinstance(context, QuerySet):
context = context.values()
instance = [con for con in context if con['id'] == arg]
if instance:
return instance[0][field]
return ''


@register.filter(name='compare_result')
def get_change_compare(changes):
change_compare = []
for key, value in changes.items():
if key in ['network_type', 'service_type', 'operation_type']:
log = replace_log(key, value, Code, 'value')
elif key == 'dev_cabinet':
log = replace_log(key, value, Cabinet, 'number')
elif key == 'leader':
log = replace_log(key, value, User, 'name')
else:
log = '字段:"%(field)s",由:"%(old)s",变更为:"%(new)s"。' % {
'field': key,
'old': value[0],
'new': value[1]
}
change_compare.append(log)
return ','.join(str(i) for i in change_compare)


def replace_log(key, value, model, field):
old = value[0]
new = value[1]
log_format = '字段:"%(field)s",由:"%(old)s",变更为:"%(new)s"。'
try:
data = model.objects.filter(id=old).values()[0]
old_data = data[field]
except Exception:
old_data = old
try:
data = model.objects.filter(id=new).values()[0]
new_data = data[field]
except Exception:
new_data = new
return log_format % {
'field': key,
'old': old_data,
'new': new_data
}
11 changes: 11 additions & 0 deletions apps/cmdb/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,15 @@
path('eam/cabinet/list/', views_eam.CabinetListView.as_view(), name='eam-cabinet-list'),
path('eam/cabinet/delete/', views_eam.CabinetDeleteView.as_view(), name='eam-cabinet-delete'),

path('eam/device/', views_eam.DeviceView.as_view(), name='eam-device'),
path('eam/device/create/', views_eam.DeviceCreateView.as_view(), name='eam-device-create'),
path('eam/device/update/', views_eam.DeviceUpdateView.as_view(), name='eam-device-update'),
path('eam/device/list/', views_eam.DeviceListView.as_view(), name='eam-device-list'),
path('eam/device/delete/', views_eam.DeviceDeleteView.as_view(), name='eam-device-delete'),
path('eam/device/device2connection/', views_eam.Device2ConnectionView.as_view(), name='eam-device-device2connection'),
path('eam/device/detail/', views_eam.DeviceDetailView.as_view(), name='eam-device-detail'),
path('eam/device/upload/', views_eam.DeviceFileUploadView.as_view(), name='eam-device-upload'),
path('eam/device/file_delete/', views_eam.DeviceFileDeleteView.as_view(), name='eam-device-file_delete'),
path('eam/device/auto_update_device_info/', views_eam.AutoUpdateDeviceInfo.as_view(),
name='eam-device-auto_update_device_info'),
]
Loading

0 comments on commit 3182032

Please sign in to comment.