models.py 22.9 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2017  Gabriel Détraz
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 24 25 26 27 28 29 30 31 32 33 34 35 36
"""
Definition des modèles de l'application topologie.

On défini les models suivants :

- stack (id, id_min, id_max et nom) regrouppant les switches
- switch : nom, nombre de port, et interface
machine correspondante (mac, ip, etc) (voir machines.models.interface)
- Port: relié à un switch parent par foreign_key, numero du port,
relié de façon exclusive à un autre port, une machine
(serveur ou borne) ou une prise murale
- room : liste des prises murales, nom et commentaire de l'état de
la prise
"""
37

38 39
from __future__ import unicode_literals

40 41
import itertools

chirac's avatar
chirac committed
42
from django.db import models
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
43
from django.db.models.signals import post_save, post_delete
grisel-davy's avatar
grisel-davy committed
44
from django.utils.functional import cached_property
45
from django.dispatch import receiver
46
from django.core.exceptions import ValidationError
47 48
from django.db import IntegrityError
from django.db import transaction
Fernet Laouen's avatar
Fernet Laouen committed
49
from django.utils.translation import ugettext_lazy as _
50
from reversion import revisions as reversion
chirac's avatar
chirac committed
51

52
from machines.models import Machine, regen
53 54
from re2o.mixins import AclMixin, RevMixin

55

56
class Stack(AclMixin, RevMixin, models.Model):
57 58
    """Un objet stack. Regrouppe des switchs en foreign key
    ,contient une id de stack, un switch id min et max dans
59
    le stack"""
60 61 62 63

    name = models.CharField(max_length=32, blank=True, null=True)
    stack_id = models.CharField(max_length=32, unique=True)
    details = models.CharField(max_length=255, blank=True, null=True)
64 65
    member_id_min = models.PositiveIntegerField()
    member_id_max = models.PositiveIntegerField()
66

67 68
    class Meta:
        permissions = (
69
            ("view_stack", _("Can view a stack object")),
70
        )
71 72
        verbose_name = _("switches stack")
        verbose_name_plural = _("switches stacks")
73

74 75 76 77
    def __str__(self):
        return " ".join([self.name, self.stack_id])

    def save(self, *args, **kwargs):
78
        self.clean()
79 80 81 82 83
        if not self.name:
            self.name = self.stack_id
        super(Stack, self).save(*args, **kwargs)

    def clean(self):
84
        """ Verification que l'id_max < id_min"""
85
        if self.member_id_max < self.member_id_min:
86 87 88 89
            raise ValidationError(
                    {'member_id_max': _("The maximum ID is less than the"
                                        " minimum ID.")}
            )
90

chirac's avatar
chirac committed
91

92
class AccessPoint(AclMixin, Machine):
93
    """Define a wireless AP. Inherit from machines.interfaces
94

95 96 97
    Definition pour une borne wifi , hérite de machines.interfaces
    """

98
    location = models.CharField(
99
        max_length=255,
100
        help_text=_("Details about the AP's location"),
101 102 103 104 105 106
        blank=True,
        null=True
    )

    class Meta:
        permissions = (
107
            ("view_accesspoint", _("Can view an access point object")),
108
        )
109 110
        verbose_name = _("access point")
        verbose_name_plural = _("access points")
111

grisel-davy's avatar
grisel-davy committed
112 113 114 115 116 117 118 119 120 121 122 123 124
    def port(self):
        """Return the queryset of ports for this device"""
        return Port.objects.filter(
            machine_interface__machine=self
        )

    def switch(self):
        """Return the switch where this is plugged"""
        return Switch.objects.filter(
            ports__machine_interface__machine=self
        )

    def building(self):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
125 126 127 128
        """
        Return the building of the AP/Server (building of the switchs
        connected to...)
        """
grisel-davy's avatar
grisel-davy committed
129 130 131 132 133 134 135 136 137 138 139
        return Building.objects.filter(
            switchbay__switch=self.switch()
        )

    @cached_property
    def short_name(self):
        return str(self.interface_set.first().domain.name)

    @classmethod
    def all_ap_in(cls, building_instance):
        """Get a building as argument, returns all ap of a building"""
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
140 141 142
        return cls.objects.filter(
            interface__port__switch__switchbay__building=building_instance
        )
grisel-davy's avatar
grisel-davy committed
143 144 145 146 147 148

    def __str__(self):
        return str(self.interface_set.first())


class Server(Machine):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
149 150 151
    """
    Dummy class, to retrieve servers of a building, or get switch of a server
    """
grisel-davy's avatar
grisel-davy committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

    class Meta:
        proxy = True

    def port(self):
        """Return the queryset of ports for this device"""
        return Port.objects.filter(
            machine_interface__machine=self
        )

    def switch(self):
        """Return the switch where this is plugged"""
        return Switch.objects.filter(
            ports__machine_interface__machine=self
        )

    def building(self):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
169 170 171 172
        """
        Return the building of the AP/Server
        (building of the switchs connected to...)
        """
grisel-davy's avatar
grisel-davy committed
173 174 175 176 177 178 179 180 181 182 183
        return Building.objects.filter(
            switchbay__switch=self.switch()
        )

    @cached_property
    def short_name(self):
        return str(self.interface_set.first().domain.name)

    @classmethod
    def all_server_in(cls, building_instance):
        """Get a building as argument, returns all server of a building"""
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
184 185 186
        return cls.objects.filter(
            interface__port__switch__switchbay__building=building_instance
        ).exclude(accesspoint__isnull=False)
grisel-davy's avatar
grisel-davy committed
187

188 189 190
    def __str__(self):
        return str(self.interface_set.first())

191

192
class Switch(AclMixin, Machine):
193
    """ Definition d'un switch. Contient un nombre de ports (number),
194 195 196
    un emplacement (location), un stack parent (optionnel, stack)
    et un id de membre dans le stack (stack_member_id)
    relié en onetoone à une interface
197
    Pourquoi ne pas avoir fait hériter switch de interface ?
198 199
    Principalement par méconnaissance de la puissance de cette façon de faire.
    Ceci étant entendu, django crée en interne un onetoone, ce qui a un
200 201 202 203
    effet identique avec ce que l'on fait ici

    Validation au save que l'id du stack est bien dans le range id_min
    id_max de la stack parente"""
204

Gabriel Detraz's avatar
Gabriel Detraz committed
205
    number = models.PositiveIntegerField(
206
        help_text=_("Number of ports")
Gabriel Detraz's avatar
Gabriel Detraz committed
207
    )
208
    stack = models.ForeignKey(
209
        'topologie.Stack',
210 211 212
        blank=True,
        null=True,
        on_delete=models.SET_NULL
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
213
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
214 215
    stack_member_id = models.PositiveIntegerField(
        blank=True,
216
        null=True
Gabriel Detraz's avatar
Gabriel Detraz committed
217
    )
218 219 220 221
    model = models.ForeignKey(
        'topologie.ModelSwitch',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
222
        on_delete=models.SET_NULL,
223
        help_text=_("Switch model")
224
    )
225 226 227 228
    switchbay = models.ForeignKey(
        'topologie.SwitchBay',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
229
        on_delete=models.SET_NULL,
230
    )
231 232

    class Meta:
233
        unique_together = ('stack', 'stack_member_id')
234
        permissions = (
235
            ("view_switch", _("Can view a switch object")),
236
        )
237 238
        verbose_name = _("switch")
        verbose_name_plural = _("switches")
chirac's avatar
chirac committed
239

240
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
241 242 243
        """ Verifie que l'id stack est dans le bon range
        Appelle également le clean de la classe parente"""
        super(Switch, self).clean()
244 245
        if self.stack is not None:
            if self.stack_member_id is not None:
246
                if (self.stack_member_id > self.stack.member_id_max) or\
chirac's avatar
chirac committed
247 248
                        (self.stack_member_id < self.stack.member_id_min):
                    raise ValidationError(
249 250 251
                        {'stack_member_id': _("The switch ID exceeds the"
                                              " limits allowed by the stack.")}
                        )
252
            else:
253 254 255 256
                raise ValidationError(
                        {'stack_member_id': _("The stack member ID can't be"
                                              " void.")}
                )
257

258
    def create_ports(self, begin, end):
259 260
        """ Crée les ports de begin à end si les valeurs données
        sont cohérentes. """
261 262 263 264 265 266 267 268 269

        s_begin = s_end = 0
        nb_ports = self.ports.count()
        if nb_ports > 0:
            ports = self.ports.order_by('port').values('port')
            s_begin = ports.first().get('port')
            s_end = ports.last().get('port')

        if end < begin:
270 271
            raise ValidationError(_("The end port is less than the start"
                                    " port."))
272
        if end - begin > self.number:
273
            raise ValidationError(_("This switch can't have that many ports."))
274 275 276 277 278 279 280 281 282
        begin_range = range(begin, s_begin)
        end_range = range(s_end+1, end+1)
        for i in itertools.chain(begin_range, end_range):
            port = Port()
            port.switch = self
            port.port = i
            try:
                with transaction.atomic(), reversion.create_revision():
                    port.save()
283
                    reversion.set_comment(_("Creation"))
284
            except IntegrityError:
285
                ValidationError(_("Creation of an existing port."))
286

287
    def main_interface(self):
288
        """ Returns the 'main' interface of the switch """
289 290
        return self.interface_set.first()

Gabriel Detraz's avatar
Gabriel Detraz committed
291 292 293 294
    @cached_property
    def get_name(self):
        return self.name or self.main_interface().domain.name

295
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
296
        return str(self.get_name)
297

chirac's avatar
chirac committed
298

299
class ModelSwitch(AclMixin, RevMixin, models.Model):
300
    """Un modèle (au sens constructeur) de switch"""
301

302 303 304 305 306 307
    reference = models.CharField(max_length=255)
    constructor = models.ForeignKey(
        'topologie.ConstructorSwitch',
        on_delete=models.PROTECT
    )

308 309
    class Meta:
        permissions = (
310
            ("view_modelswitch", _("Can view a switch model object")),
311
        )
312 313
        verbose_name = _("switch model")
        verbose_name_plural = _("switch models")
314

315
    def __str__(self):
316
        return str(self.constructor) + ' ' + self.reference
317 318


319
class ConstructorSwitch(AclMixin, RevMixin, models.Model):
320
    """Un constructeur de switch"""
321

322 323
    name = models.CharField(max_length=255)

324 325
    class Meta:
        permissions = (
326 327
            ("view_constructorswitch", _("Can view a switch constructor"
                                         " object")),
328
        )
329 330
        verbose_name = _("switch constructor")
        verbose_name_plural = ("switch constructors")
331

332
    def __str__(self):
333
        return self.name
334 335


336 337
class SwitchBay(AclMixin, RevMixin, models.Model):
    """Une baie de brassage"""
338

339 340 341 342 343 344 345 346
    name = models.CharField(max_length=255)
    building = models.ForeignKey(
        'Building',
        on_delete=models.PROTECT
    )
    info = models.CharField(
        max_length=255,
        blank=True,
347
        null=True
348 349 350 351
    )

    class Meta:
        permissions = (
352
            ("view_switchbay", _("Can view a switch bay object")),
353
        )
354 355
        verbose_name = _("switch bay")
        verbose_name_plural = _("switch bays")
356 357 358 359 360 361 362

    def __str__(self):
        return self.name


class Building(AclMixin, RevMixin, models.Model):
    """Un batiment"""
363

364 365 366 367
    name = models.CharField(max_length=255)

    class Meta:
        permissions = (
368
            ("view_building", _("Can view a building object")),
369
        )
370 371
        verbose_name = _("building")
        verbose_name_plural = _("buildings")
372 373 374 375 376

    def __str__(self):
        return self.name


377
class Port(AclMixin, RevMixin, models.Model):
378
    """ Definition d'un port. Relié à un switch(foreign_key),
379 380 381 382
    un port peut etre relié de manière exclusive à :
    - une chambre (room)
    - une machine (serveur etc) (machine_interface)
    - un autre port (uplink) (related)
383
    Champs supplémentaires :
384
    - RADIUS (mode STRICT : connexion sur port uniquement si machine
385 386
    d'un adhérent à jour de cotisation et que la chambre est également à
    jour de cotisation
387 388 389 390
    mode COMMON : vérification uniquement du statut de la machine
    mode NO : accepte toute demande venant du port et place sur le vlan normal
    mode BLOQ : rejet de toute authentification
    - vlan_force : override la politique générale de placement vlan, permet
391
    de forcer un port sur un vlan particulier. S'additionne à la politique
392
    RADIUS"""
393

394 395 396 397 398
    switch = models.ForeignKey(
        'Switch',
        related_name="ports",
        on_delete=models.CASCADE
    )
399
    port = models.PositiveIntegerField()
400 401 402 403 404
    room = models.ForeignKey(
        'Room',
        on_delete=models.PROTECT,
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
405
    )
406 407 408 409 410
    machine_interface = models.ForeignKey(
        'machines.Interface',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
411
    )
412 413 414 415 416
    related = models.OneToOneField(
        'self',
        null=True,
        blank=True,
        related_name='related_port'
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
417
    )
418
    custom_profile = models.ForeignKey(
419 420
        'PortProfile',
        on_delete=models.PROTECT,
421 422
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
423
    )
424 425
    state = models.BooleanField(
        default=True,
426
        help_text='Port state Active',
427
        verbose_name=_("Port state Active")
428
    )
Dalahro's avatar
Dalahro committed
429
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
430 431

    class Meta:
432
        unique_together = ('switch', 'port')
433
        permissions = (
434
            ("view_port", _("Can view a port object")),
435
        )
436 437
        verbose_name = _("port")
        verbose_name_plural = _("ports")
438

439
    @cached_property
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
440 441
    def get_port_profile(self):
        """Return the config profile for this port
442
        :returns: the profile of self (port)"""
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
443 444
        def profile_or_nothing(profile):
            port_profile = PortProfile.objects.filter(
445
                profil_default=profile).first()
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
446 447
            if port_profile:
                return port_profile
448
            else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
449 450 451 452 453 454
                nothing_profile, _created = PortProfile.objects.get_or_create(
                    profile_default='nothing',
                    name='nothing',
                    radius_type='NO'
                )
                return nothing_profile
455

456 457
        if self.custom_profile:
            return self.custom_profile
458
        elif self.related:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
459
            return profile_or_nothing('uplink')
460
        elif self.machine_interface:
461
            if hasattr(self.machine_interface.machine, 'accesspoint'):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
462
                return profile_or_nothing('access_point')
463
            else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
464
                return profile_or_nothing('asso_machine')
465
        elif self.room:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
466
            return profile_or_nothing('room')
467
        else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
468
            return profile_or_nothing('nothing')
469

470 471 472 473 474 475 476 477 478
    @classmethod
    def get_instance(cls, portid, *_args, **kwargs):
        return (cls.objects
                .select_related('machine_interface__domain__extension')
                .select_related('machine_interface__machine__switch')
                .select_related('room')
                .select_related('related')
                .prefetch_related('switch__interface_set__domain__extension')
                .get(pk=portid))
479

480 481 482 483 484
    def make_port_related(self):
        """ Synchronise le port distant sur self"""
        related_port = self.related
        related_port.related = self
        related_port.save()
485

486 487 488 489 490 491
    def clean_port_related(self):
        """ Supprime la relation related sur self"""
        related_port = self.related_port
        related_port.related = None
        related_port.save()

492
    def clean(self):
493 494 495 496
        """ Verifie que un seul de chambre, interface_parent et related_port
        est rempli. Verifie que le related n'est pas le port lui-même....
        Verifie que le related n'est pas déjà occupé par une machine ou une
        chambre. Si ce n'est pas le cas, applique la relation related
497
        Si un port related point vers self, on nettoie la relation
498 499 500
        A priori pas d'autre solution que de faire ça à la main. A priori
        tout cela est dans un bloc transaction, donc pas de problème de
        cohérence"""
lhark's avatar
lhark committed
501 502
        if hasattr(self, 'switch'):
            if self.port > self.switch.number:
503
                raise ValidationError(
504
                    _("The port can't exist, its number is too great.")
505 506 507 508 509
                )
        if (self.room and self.machine_interface or
                self.room and self.related or
                self.machine_interface and self.related):
            raise ValidationError(
510
                _("Room, interface and related port are mutually exclusive.")
511
            )
512
        if self.related == self:
513
            raise ValidationError(_("A port can't be related to itself."))
514 515
        if self.related and not self.related.related:
            if self.related.machine_interface or self.related.room:
516
                raise ValidationError(
517 518
                    _("The related port is already used, please clear it"
                      " before creating the relation.")
519
                )
520
            else:
521
                self.make_port_related()
522
        elif hasattr(self, 'related_port'):
523
            self.clean_port_related()
chirac's avatar
chirac committed
524 525

    def __str__(self):
chirac's avatar
chirac committed
526
        return str(self.switch) + " - " + str(self.port)
chirac's avatar
chirac committed
527

chirac's avatar
chirac committed
528

529
class Room(AclMixin, RevMixin, models.Model):
530
    """Une chambre/local contenant une prise murale"""
531

lhark's avatar
lhark committed
532
    name = models.CharField(max_length=255, unique=True)
chirac's avatar
chirac committed
533
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
534

535 536
    class Meta:
        ordering = ['name']
537
        permissions = (
538
            ("view_room", _("Can view a room object")),
539
        )
540 541
        verbose_name = _("room")
        verbose_name_plural = _("rooms")
542

chirac's avatar
chirac committed
543
    def __str__(self):
544
        return self.name
chirac's avatar
chirac committed
545

chirac's avatar
chirac committed
546

Gabriel Detraz's avatar
Gabriel Detraz committed
547
class PortProfile(AclMixin, RevMixin, models.Model):
Fernet Laouen's avatar
Fernet Laouen committed
548 549 550 551 552
    """Contains the information of the ports' configuration for a switch"""
    TYPES = (
        ('NO', 'NO'),
        ('802.1X', '802.1X'),
        ('MAC-radius', 'MAC-radius'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
553
    )
Fernet Laouen's avatar
Fernet Laouen committed
554 555 556
    MODES = (
        ('STRICT', 'STRICT'),
        ('COMMON', 'COMMON'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
557
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
558 559 560 561 562 563 564 565 566
    SPEED = (
        ('10-half', '10-half'),
        ('100-half', '100-half'),
        ('10-full', '10-full'),
        ('100-full', '100-full'),
        ('1000-full', '1000-full'),
        ('auto', 'auto'),
        ('auto-10', 'auto-10'),
        ('auto-100', 'auto-100'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
567 568
    )
    PROFIL_DEFAULT = (
Gabriel Detraz's avatar
Gabriel Detraz committed
569 570 571 572
        ('room', 'room'),
        ('accespoint', 'accesspoint'),
        ('uplink', 'uplink'),
        ('asso_machine', 'asso_machine'),
573
        ('nothing', 'nothing'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
574
    )
Fernet Laouen's avatar
Fernet Laouen committed
575
    name = models.CharField(max_length=255, verbose_name=_("Name"))
Gabriel Detraz's avatar
Gabriel Detraz committed
576 577 578 579 580 581
    profil_default = models.CharField(
        max_length=32,
        choices=PROFIL_DEFAULT,
        blank=True,
        null=True,
        unique=True,
582
        verbose_name=_("Default profile")
Gabriel Detraz's avatar
Gabriel Detraz committed
583
    )
Fernet Laouen's avatar
Fernet Laouen committed
584
    vlan_untagged = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
585 586 587 588 589 590
        'machines.Vlan',
        related_name='vlan_untagged',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        verbose_name=_("VLAN untagged")
Fernet Laouen's avatar
Fernet Laouen committed
591 592
    )
    vlan_tagged = models.ManyToManyField(
Gabriel Detraz's avatar
Gabriel Detraz committed
593 594 595 596 597
        'machines.Vlan',
        related_name='vlan_tagged',
        blank=True,
        verbose_name=_("VLAN(s) tagged")
    )
Fernet Laouen's avatar
Fernet Laouen committed
598
    radius_type = models.CharField(
Gabriel Detraz's avatar
Gabriel Detraz committed
599 600
        max_length=32,
        choices=TYPES,
601 602
        help_text=_("Type of RADIUS authentication : inactive, MAC-address or"
                    " 802.1X"),
Gabriel Detraz's avatar
Gabriel Detraz committed
603
        verbose_name=_("RADIUS type")
Fernet Laouen's avatar
Fernet Laouen committed
604 605
    )
    radius_mode = models.CharField(
Gabriel Detraz's avatar
Gabriel Detraz committed
606 607 608
        max_length=32,
        choices=MODES,
        default='COMMON',
609 610
        help_text=_("In case of MAC-authentication : mode COMMON or STRICT on"
                    " this port"),
Gabriel Detraz's avatar
Gabriel Detraz committed
611 612 613 614 615 616
        verbose_name=_("RADIUS mode")
    )
    speed = models.CharField(
        max_length=32,
        choices=SPEED,
        default='auto',
617
        help_text=_("Port speed limit"),
Gabriel Detraz's avatar
Gabriel Detraz committed
618 619 620 621
    )
    mac_limit = models.IntegerField(
        null=True,
        blank=True,
622 623
        help_text=_("Limit of MAC-address on this port"),
        verbose_name=_("MAC limit")
Gabriel Detraz's avatar
Gabriel Detraz committed
624 625 626
    )
    flow_control = models.BooleanField(
        default=False,
627
        help_text=_("Flow control"),
Gabriel Detraz's avatar
Gabriel Detraz committed
628 629 630
    )
    dhcp_snooping = models.BooleanField(
        default=False,
631 632
        help_text=_("Protect against rogue DHCP"),
        verbose_name=_("DHCP snooping")
Gabriel Detraz's avatar
Gabriel Detraz committed
633 634 635
    )
    dhcpv6_snooping = models.BooleanField(
        default=False,
636 637
        help_text=_("Protect against rogue DHCPv6"),
        verbose_name=_("DHCPv6 snooping")
Gabriel Detraz's avatar
Gabriel Detraz committed
638 639 640
    )
    arp_protect = models.BooleanField(
        default=False,
641 642
        help_text=_("Check if IP adress is DHCP assigned"),
        verbose_name=_("ARP protection")
Fernet Laouen's avatar
Fernet Laouen committed
643
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
644 645
    ra_guard = models.BooleanField(
        default=False,
646 647
        help_text=_("Protect against rogue RA"),
        verbose_name=_("RA guard")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
648
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
649 650
    loop_protect = models.BooleanField(
        default=False,
651 652
        help_text=_("Protect against loop"),
        verbose_name=_("Loop protection")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
653
    )
Fernet Laouen's avatar
Fernet Laouen committed
654 655 656

    class Meta:
        permissions = (
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
657
            ("view_port_profile", _("Can view a port profile object")),
Fernet Laouen's avatar
Fernet Laouen committed
658
        )
659 660
        verbose_name = _("port profile")
        verbose_name_plural = _("port profiles")
Fernet Laouen's avatar
Fernet Laouen committed
661

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
662 663 664 665 666 667 668 669
    security_parameters_fields = [
        'loop_protect',
        'ra_guard',
        'arp_protect',
        'dhcpv6_snooping',
        'dhcp_snooping',
        'flow_control'
    ]
670 671 672

    @cached_property
    def security_parameters_enabled(self):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
673 674 675 676 677
        return [
            parameter
            for parameter in self.security_parameters_fields
            if getattr(self, parameter)
        ]
678

679 680 681 682
    @cached_property
    def security_parameters_as_str(self):
        return ','.join(self.security_parameters_enabled)

Fernet Laouen's avatar
Fernet Laouen committed
683 684 685 686
    def __str__(self):
        return self.name


687
@receiver(post_save, sender=AccessPoint)
688
def ap_post_save(**_kwargs):
689 690
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
691
    regen("graph_topo")
692

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
693

694
@receiver(post_delete, sender=AccessPoint)
695
def ap_post_delete(**_kwargs):
696 697
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
698
    regen("graph_topo")
699

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
700

701
@receiver(post_delete, sender=Stack)
702
def stack_post_delete(**_kwargs):
703 704
    """Vide les id des switches membres d'une stack supprimée"""
    Switch.objects.filter(stack=None).update(stack_member_id=None)
grisel-davy's avatar
grisel-davy committed
705

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
706

grisel-davy's avatar
grisel-davy committed
707 708 709 710
@receiver(post_save, sender=Port)
def port_post_save(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
711

grisel-davy's avatar
grisel-davy committed
712 713 714 715
@receiver(post_delete, sender=Port)
def port_post_delete(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
716

grisel-davy's avatar
grisel-davy committed
717 718 719 720
@receiver(post_save, sender=ModelSwitch)
def modelswitch_post_save(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
721

grisel-davy's avatar
grisel-davy committed
722 723 724 725
@receiver(post_delete, sender=ModelSwitch)
def modelswitch_post_delete(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
726

grisel-davy's avatar
grisel-davy committed
727 728 729 730
@receiver(post_save, sender=Building)
def building_post_save(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
731

grisel-davy's avatar
grisel-davy committed
732 733 734 735
@receiver(post_delete, sender=Building)
def building_post_delete(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
736

grisel-davy's avatar
grisel-davy committed
737 738 739 740
@receiver(post_save, sender=Switch)
def switch_post_save(**_kwargs):
    regen("graph_topo")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
741

grisel-davy's avatar
grisel-davy committed
742 743 744
@receiver(post_delete, sender=Switch)
def switch_post_delete(**_kwargs):
    regen("graph_topo")
745