/
admin.py
519 lines (398 loc) · 14 KB
/
admin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import logging
from django import forms
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from lck.django.common.admin import (
ForeignKeyAutocompleteTabularInline,
ModelAdmin,
)
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.template.defaultfilters import slugify
from ralph.business.admin import RolePropertyValueInline
from ralph.discovery import models
from ralph.discovery import models_device
from ralph.ui.forms.network import NetworkForm
SAVE_PRIORITY = 215
HOSTS_NAMING_TEMPLATE_REGEX = re.compile(r'<[0-9]+,[0-9]+>.*\.[a-zA-Z0-9]+')
def copy_network(modeladmin, request, queryset):
for net in queryset:
name = 'Copy of %s' % net.name
address = net.address.rsplit('/', 1)[0] + '/1'
new_net = models.Network(
name=name,
address=address,
gateway=net.gateway,
kind=net.kind,
data_center=net.data_center,
)
try:
new_net.save()
except ValidationError:
messages.error(request, "Network %s already exists." % address)
except Exception:
message = "Failed to create %s." % address
messages.error(request, message)
logging.exception(message)
else:
new_net.terminators = net.terminators.all()
new_net.save()
copy_network.short_description = "Copy network"
class NetworkAdmin(ModelAdmin):
def address(self):
return self.address
address.short_description = _("network address")
address.admin_order_field = 'min_ip'
def gateway(self):
return self.gateway
gateway.short_description = _("gateway address")
gateway.admin_order_field = 'gateway_as_int'
def terms(self):
return ", ".join([n.name for n in self.terminators.order_by('name')])
terms.short_description = _("network terminators")
list_display = ('name', 'vlan', address, gateway, terms, 'data_center',
'environment', 'kind')
list_filter = (
'data_center', 'terminators', 'environment', 'kind', 'dhcp_broadcast',
)
list_per_page = 250
radio_fields = {
'data_center': admin.HORIZONTAL,
'environment': admin.HORIZONTAL,
'kind': admin.HORIZONTAL,
}
search_fields = ('name', 'address', 'vlan')
filter_horizontal = ('terminators', 'racks', 'custom_dns_servers')
save_on_top = True
form = NetworkForm
actions = [copy_network]
admin.site.register(models.Network, NetworkAdmin)
class NetworkKindAdmin(ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
admin.site.register(models.NetworkKind, NetworkKindAdmin)
class NetworkTerminatorAdmin(ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
admin.site.register(models.NetworkTerminator, NetworkTerminatorAdmin)
class DataCenterAdmin(ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
admin.site.register(models.DataCenter, DataCenterAdmin)
class EnvironmentAdminForm(forms.ModelForm):
class Meta:
model = models.Environment
def clean_name(self):
name = self.cleaned_data['name'].strip()
if slugify(name) != name.lower():
raise forms.ValidationError(
_('You can use only this characters: [a-zA-Z0-9_-]')
)
return name
def clean_hosts_naming_template(self):
template = self.cleaned_data['hosts_naming_template']
if re.search("[^a-z0-9<>,\.|-]", template):
raise forms.ValidationError(
_("Please remove disallowed characters."),
)
for part in template.split("|"):
if not HOSTS_NAMING_TEMPLATE_REGEX.search(part):
raise forms.ValidationError(
_(
"Incorrect template structure. Please see example "
"below.",
),
)
return template
class EnvironmentAdmin(ModelAdmin):
list_display = (
'name',
'data_center',
'queue',
'domain',
'hosts_naming_template',
'next_server'
)
search_fields = ('name',)
form = EnvironmentAdminForm
list_filter = ('data_center', 'queue')
admin.site.register(models.Environment, EnvironmentAdmin)
class DiscoveryQueueAdmin(ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
admin.site.register(models.DiscoveryQueue, DiscoveryQueueAdmin)
class IPAddressForm(forms.ModelForm):
class Meta:
model = models.IPAddress
def clean(self):
address = self.cleaned_data.get('address')
hostname = self.cleaned_data.get('hostname')
if not address and hostname:
raise forms.ValidationError(_("Either address or hostname must "
"be provided."))
class IPAddressInline(ForeignKeyAutocompleteTabularInline):
model = models.IPAddress
readonly_fields = ('snmp_name', 'last_seen')
exclude = ('created', 'modified', 'dns_info', 'http_family',
'snmp_community', 'last_puppet')
edit_separately = True
extra = 0
related_search_fields = {
'device': ['^name'],
'network': ['^name'],
}
class ChildDeviceInline(ForeignKeyAutocompleteTabularInline):
model = models.Device
edit_separately = True
readonly_fields = ('name', 'model', 'sn', 'remarks', 'last_seen',)
exclude = ('name2', 'created', 'modified', 'boot_firmware', 'barcode',
'hard_firmware', 'diag_firmware', 'mgmt_firmware', 'price',
'purchase_date', 'warranty_expiration_date', 'role',
'support_expiration_date', 'deprecation_kind', 'margin_kind',
'chassis_position', 'position', 'support_kind', 'management',
'logical_parent')
extra = 0
related_search_fields = {
'model': ['^name'],
}
fk_name = 'parent'
class DeviceModelAdmin(ModelAdmin):
def count(self):
return models.Device.objects.filter(model=self).count()
list_display = ('name', 'type', count, 'created', 'modified')
list_filter = ('type',)
search_fields = ('name',)
admin.site.register(models.DeviceModel, DeviceModelAdmin)
class DeviceModelInline(admin.TabularInline):
model = models.DeviceModel
exclude = ('created', 'modified')
extra = 0
class DeviceForm(forms.ModelForm):
class Meta:
model = models.Device
def clean_sn(self):
sn = self.cleaned_data['sn']
if not sn:
sn = None
return sn
def clean_model(self):
model = self.cleaned_data['model']
if not model:
raise forms.ValidationError(_("Model is required"))
return model
def clean_barcode(self):
barcode = self.cleaned_data['barcode']
return barcode or None
def clean(self):
cleaned_data = super(DeviceForm, self).clean()
model = self.cleaned_data.get('model')
if all((
'ralph_assets' in settings.INSTALLED_APPS,
not self.instance.id, # only when we create new device
model
)):
if model and model.type not in models.ASSET_NOT_REQUIRED:
raise forms.ValidationError(
"Adding this type of devices is allowed only via "
"Assets module."
)
return cleaned_data
class ProcessorInline(ForeignKeyAutocompleteTabularInline):
model = models.Processor
# readonly_fields = ('label', 'index', 'speed')
exclude = ('created', 'modified')
extra = 0
related_search_fields = {
'model': ['^name'],
}
class MemoryInline(ForeignKeyAutocompleteTabularInline):
model = models.Memory
exclude = ('created', 'modified')
extra = 0
related_search_fields = {
'model': ['^name'],
}
class EthernetInline(ForeignKeyAutocompleteTabularInline):
model = models.Ethernet
exclude = ('created', 'modified')
extra = 0
related_search_fields = {
'model': ['^name'],
}
class StorageInline(ForeignKeyAutocompleteTabularInline):
model = models.Storage
readonly_fields = (
'label',
'size',
'sn',
'model',
'created',
'modified',
'mount_point',
)
extra = 0
related_search_fields = {
'model': ['^name'],
}
class InboundConnectionInline(ForeignKeyAutocompleteTabularInline):
model = models.Connection
extra = 1
related_search_fields = {
'outbound': ['^name']
}
fk_name = 'inbound'
verbose_name = _("Inbound Connection")
verbose_name_plural = _("Inbound Connections")
class OutboundConnectionInline(ForeignKeyAutocompleteTabularInline):
model = models.Connection
extra = 1
related_search_fields = {
'inbound': ['^name'],
}
fk_name = 'outbound'
verbose_name = _("Outbound Connection")
verbose_name_plural = _("Outbound Connections")
class DeviceAdmin(ModelAdmin):
form = DeviceForm
inlines = [
ProcessorInline,
MemoryInline,
EthernetInline,
StorageInline,
IPAddressInline,
ChildDeviceInline,
RolePropertyValueInline,
InboundConnectionInline,
OutboundConnectionInline,
]
list_display = ('name', 'sn', 'created', 'modified')
list_filter = ('model__type',)
list_per_page = 250
readonly_fields = ('last_seen',)
save_on_top = True
search_fields = ('name', 'name2', 'sn', 'model__type',
'model__name', 'ethernet__mac')
related_search_fields = {
'parent': ['^name'],
'logical_parent': ['^name'],
'venture': ['^name'],
'venture_role': ['^name'],
'management': ['^address', '^hostname'],
'model': ['^name', ],
}
def save_model(self, request, obj, form, change):
obj.save(user=request.user, sync_fields=True, priority=SAVE_PRIORITY)
def save_formset(self, request, form, formset, change):
if formset.model.__name__ == 'RolePropertyValue':
for instance in formset.save(commit=False):
instance.save(user=request.user)
else:
formset.save(commit=True)
admin.site.register(models.Device, DeviceAdmin)
class IPAliasInline(admin.TabularInline):
model = models.IPAlias
exclude = ('created', 'modified')
extra = 0
class IPAddressAdmin(ModelAdmin):
inlines = [IPAliasInline]
def ip_address(self):
"""Used for proper ordering."""
return self.address
ip_address.short_description = _("IP address")
ip_address.admin_order_field = 'number'
list_display = (
ip_address, 'hostname', 'device', 'snmp_name', 'is_public', 'created',
'modified',
)
list_filter = ('is_public', 'snmp_community')
list_per_page = 250
save_on_top = True
search_fields = ('address', 'hostname', 'number', 'snmp_name')
related_search_fields = {
'device': ['^name'],
'network': ['^name'],
'venture': ['^name'],
}
admin.site.register(models.IPAddress, IPAddressAdmin)
class DeprecationKindAdmin(ModelAdmin):
save_on_top = True
list_display = ('name', 'months', 'default')
admin.site.register(models.DeprecationKind, DeprecationKindAdmin)
class MarginKindAdmin(ModelAdmin):
save_on_top = True
admin.site.register(models.MarginKind, MarginKindAdmin)
class LoadBalancerVirtualServerAdmin(ModelAdmin):
pass
admin.site.register(
models.LoadBalancerVirtualServer,
LoadBalancerVirtualServerAdmin,
)
class LoadBalancerMemberAdmin(ModelAdmin):
pass
admin.site.register(
models.LoadBalancerMember,
LoadBalancerMemberAdmin,
)
class ComponentModelInline(admin.TabularInline):
model = models.ComponentModel
exclude = ('created', 'modified')
extra = 0
class ComponentModelAdmin(ModelAdmin):
def count(self):
return self.get_count()
list_filter = ('type',)
list_display = ('name', 'type', count, 'family',)
search_fields = ('name', 'type', 'group__name', 'family')
admin.site.register(models.ComponentModel, ComponentModelAdmin)
class GenericComponentAdmin(ModelAdmin):
search_fields = ('label', 'sn', 'model__name')
list_display = ('label', 'model', 'sn')
related_search_fields = {
'device': ['^name'],
'model': ['^name']
}
admin.site.register(models.GenericComponent, GenericComponentAdmin)
class DiskShareMountInline(ForeignKeyAutocompleteTabularInline):
model = models.DiskShareMount
exclude = ('created', 'modified')
related_search_fields = {
'device': ['^name'],
'server': ['^name'],
'address': ['^address'],
}
extra = 0
class DiskShareAdmin(ModelAdmin):
inlines = [DiskShareMountInline]
search_fields = ('wwn',)
related_search_fields = {
'device': ['^name'],
'model': ['^name']
}
admin.site.register(models.DiskShare, DiskShareAdmin)
class HistoryChangeAdmin(ModelAdmin):
list_display = ('date', 'user', 'device', 'component', 'field_name',
'old_value', 'new_value')
list_per_page = 250
readonly_fields = ('date', 'device', 'user', 'field_name', 'new_value',
'old_value', 'component')
search_fields = ('user__username', 'field_name', 'new_value')
admin.site.register(models.HistoryChange, HistoryChangeAdmin)
class DiscoveryWarningAdmin(ModelAdmin):
list_display = ('message', 'count', 'date', 'plugin', 'ip', 'device')
list_per_page = 250
readonly_fields = ('date', 'plugin', 'message', 'ip', 'count', 'device')
search_fields = ('plugin', 'ip', 'message')
admin.site.register(models.DiscoveryWarning, DiscoveryWarningAdmin)
class DeviceEnvironmentAdmin(ModelAdmin):
save_on_top = True
list_display = ('name',)
search_fields = ('name',)
admin.site.register(models_device.DeviceEnvironment, DeviceEnvironmentAdmin)