Ce serveur Gitlab sera éteint le 30 juin 2020, pensez à migrer vos projets vers les serveurs gitlab-research.centralesupelec.fr et gitlab-student.centralesupelec.fr !

models.py 22.3 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 64
    PRETTY_NAME = "Stack de switchs"

    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)
65 66
    member_id_min = models.PositiveIntegerField()
    member_id_max = models.PositiveIntegerField()
67

68 69 70 71 72
    class Meta:
        permissions = (
            ("view_stack", "Peut voir un objet stack"),
        )

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

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

    def clean(self):
83
        """ Verification que l'id_max < id_min"""
84
        if self.member_id_max < self.member_id_min:
chirac's avatar
chirac committed
85
            raise ValidationError({'member_id_max': "L'id maximale est\
86
                inférieure à l'id minimale"})
87

chirac's avatar
chirac committed
88

89
class AccessPoint(AclMixin, Machine):
90
    """Define a wireless AP. Inherit from machines.interfaces
91

92 93 94 95
    Definition pour une borne wifi , hérite de machines.interfaces
    """
    PRETTY_NAME = "Borne WiFi"

96
    location = models.CharField(
97 98 99 100 101 102 103 104
        max_length=255,
        help_text="Détails sur la localisation de l'AP",
        blank=True,
        null=True
    )

    class Meta:
        permissions = (
105
            ("view_accesspoint", "Peut voir une borne"),
106 107
        )

grisel-davy's avatar
grisel-davy committed
108 109 110 111 112 113 114 115 116 117 118 119 120
    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
121 122 123 124
        """
        Return the building of the AP/Server (building of the switchs
        connected to...)
        """
grisel-davy's avatar
grisel-davy committed
125 126 127 128 129 130 131 132 133 134 135
        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
136 137 138
        return cls.objects.filter(
            interface__port__switch__switchbay__building=building_instance
        )
grisel-davy's avatar
grisel-davy committed
139 140 141 142 143 144

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


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

    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
165 166 167 168
        """
        Return the building of the AP/Server
        (building of the switchs connected to...)
        """
grisel-davy's avatar
grisel-davy committed
169 170 171 172 173 174 175 176 177 178 179
        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
180 181 182
        return cls.objects.filter(
            interface__port__switch__switchbay__building=building_instance
        ).exclude(accesspoint__isnull=False)
grisel-davy's avatar
grisel-davy committed
183

184 185 186
    def __str__(self):
        return str(self.interface_set.first())

187

188
class Switch(AclMixin, Machine):
189
    """ Definition d'un switch. Contient un nombre de ports (number),
190 191 192
    un emplacement (location), un stack parent (optionnel, stack)
    et un id de membre dans le stack (stack_member_id)
    relié en onetoone à une interface
193
    Pourquoi ne pas avoir fait hériter switch de interface ?
194 195
    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
196 197 198 199
    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"""
200 201
    PRETTY_NAME = "Switch / Commutateur"

Gabriel Detraz's avatar
Gabriel Detraz committed
202 203 204
    number = models.PositiveIntegerField(
        help_text="Nombre de ports"
    )
205
    stack = models.ForeignKey(
206
        'topologie.Stack',
207 208 209
        blank=True,
        null=True,
        on_delete=models.SET_NULL
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
210
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
211 212 213 214 215
    stack_member_id = models.PositiveIntegerField(
        blank=True,
        null=True,
        help_text="Baie de brassage du switch"
    )
216 217 218 219
    model = models.ForeignKey(
        'topologie.ModelSwitch',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
220 221
        on_delete=models.SET_NULL,
        help_text="Modèle du switch"
222
    )
223 224 225 226
    switchbay = models.ForeignKey(
        'topologie.SwitchBay',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
227 228
        on_delete=models.SET_NULL,
        help_text="Baie de brassage du switch"
229
    )
230 231

    class Meta:
232
        unique_together = ('stack', 'stack_member_id')
233
        permissions = (
Gabriel Detraz's avatar
Gabriel Detraz committed
234
            ("view_switch", "Peut voir un objet switch"),
235
        )
chirac's avatar
chirac committed
236

237
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
238 239 240
        """ Verifie que l'id stack est dans le bon range
        Appelle également le clean de la classe parente"""
        super(Switch, self).clean()
241 242
        if self.stack is not None:
            if self.stack_member_id is not None:
243
                if (self.stack_member_id > self.stack.member_id_max) or\
chirac's avatar
chirac committed
244 245 246 247
                        (self.stack_member_id < self.stack.member_id_min):
                    raise ValidationError(
                        {'stack_member_id': "L'id de ce switch est en\
                            dehors des bornes permises pas la stack"}
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
248
                    )
249
            else:
250 251
                raise ValidationError({'stack_member_id': "L'id dans la stack\
                    ne peut être nul"})
252

253
    def create_ports(self, begin, end):
254 255
        """ Crée les ports de begin à end si les valeurs données
        sont cohérentes. """
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

        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:
            raise ValidationError("Port de fin inférieur au port de début !")
        if end - begin > self.number:
            raise ValidationError("Ce switch ne peut avoir autant de ports.")
        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()
                    reversion.set_comment("Création")
            except IntegrityError:
                ValidationError("Création d'un port existant.")
280

281
    def main_interface(self):
282
        """ Returns the 'main' interface of the switch """
283 284
        return self.interface_set.first()

Gabriel Detraz's avatar
Gabriel Detraz committed
285 286 287 288
    @cached_property
    def get_name(self):
        return self.name or self.main_interface().domain.name

289
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
290
        return str(self.get_name)
291

chirac's avatar
chirac committed
292

293
class ModelSwitch(AclMixin, RevMixin, models.Model):
294
    """Un modèle (au sens constructeur) de switch"""
Gabriel Detraz's avatar
Gabriel Detraz committed
295
    PRETTY_NAME = "Modèle de switch"
296 297 298 299 300 301
    reference = models.CharField(max_length=255)
    constructor = models.ForeignKey(
        'topologie.ConstructorSwitch',
        on_delete=models.PROTECT
    )

302 303 304 305 306
    class Meta:
        permissions = (
            ("view_modelswitch", "Peut voir un objet modelswitch"),
        )

307
    def __str__(self):
308
        return str(self.constructor) + ' ' + self.reference
309 310


311
class ConstructorSwitch(AclMixin, RevMixin, models.Model):
312
    """Un constructeur de switch"""
Gabriel Detraz's avatar
Gabriel Detraz committed
313
    PRETTY_NAME = "Constructeur de switch"
314 315
    name = models.CharField(max_length=255)

316 317 318 319 320
    class Meta:
        permissions = (
            ("view_constructorswitch", "Peut voir un objet constructorswitch"),
        )

321
    def __str__(self):
322
        return self.name
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
class SwitchBay(AclMixin, RevMixin, models.Model):
    """Une baie de brassage"""
    PRETTY_NAME = "Baie de brassage"
    name = models.CharField(max_length=255)
    building = models.ForeignKey(
        'Building',
        on_delete=models.PROTECT
    )
    info = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        help_text="Informations particulières"
    )

    class Meta:
        permissions = (
            ("view_switchbay", "Peut voir un objet baie de brassage"),
        )

    def __str__(self):
        return self.name


class Building(AclMixin, RevMixin, models.Model):
    """Un batiment"""
    PRETTY_NAME = "Batiment"
    name = models.CharField(max_length=255)

    class Meta:
        permissions = (
            ("view_building", "Peut voir un objet batiment"),
        )

    def __str__(self):
        return self.name


363
class Port(AclMixin, RevMixin, models.Model):
364
    """ Definition d'un port. Relié à un switch(foreign_key),
365 366 367 368
    un port peut etre relié de manière exclusive à :
    - une chambre (room)
    - une machine (serveur etc) (machine_interface)
    - un autre port (uplink) (related)
369
    Champs supplémentaires :
370
    - RADIUS (mode STRICT : connexion sur port uniquement si machine
371 372
    d'un adhérent à jour de cotisation et que la chambre est également à
    jour de cotisation
373 374 375 376
    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
377
    de forcer un port sur un vlan particulier. S'additionne à la politique
378
    RADIUS"""
379
    PRETTY_NAME = "Port de switch"
380

381 382 383 384 385
    switch = models.ForeignKey(
        'Switch',
        related_name="ports",
        on_delete=models.CASCADE
    )
386
    port = models.PositiveIntegerField()
387 388 389 390 391
    room = models.ForeignKey(
        'Room',
        on_delete=models.PROTECT,
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
392
    )
393 394 395 396 397
    machine_interface = models.ForeignKey(
        'machines.Interface',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
398
    )
399 400 401 402 403
    related = models.OneToOneField(
        'self',
        null=True,
        blank=True,
        related_name='related_port'
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
404
    )
405
    custom_profile = models.ForeignKey(
406 407
        'PortProfile',
        on_delete=models.PROTECT,
408 409
        blank=True,
        null=True
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
410
    )
411 412
    state = models.BooleanField(
        default=True,
413 414
        help_text='Port state Active',
        verbose_name=_("Port State Active")
415
    )
Dalahro's avatar
Dalahro committed
416
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
417 418

    class Meta:
419
        unique_together = ('switch', 'port')
420 421 422
        permissions = (
            ("view_port", "Peut voir un objet port"),
        )
423

424
    @cached_property
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
425 426
    def get_port_profile(self):
        """Return the config profile for this port
427
        :returns: the profile of self (port)"""
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
428 429 430 431 432
        def profile_or_nothing(profile):
            port_profile = PortProfile.objects.filter(
                profile_default=profile).first()
            if port_profile:
                return port_profile
433
            else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
434 435 436 437 438 439
                nothing_profile, _created = PortProfile.objects.get_or_create(
                    profile_default='nothing',
                    name='nothing',
                    radius_type='NO'
                )
                return nothing_profile
440

441 442
        if self.custom_profile:
            return self.custom_profile
443
        elif self.related:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
444
            return profile_or_nothing('uplink')
445
        elif self.machine_interface:
446
            if hasattr(self.machine_interface.machine, 'accesspoint'):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
447
                return profile_or_nothing('access_point')
448
            else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
449
                return profile_or_nothing('asso_machine')
450
        elif self.room:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
451
            return profile_or_nothing('room')
452
        else:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
453
            return profile_or_nothing('nothing')
454

455 456 457 458 459 460 461 462 463
    @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))
464

465 466 467 468 469
    def make_port_related(self):
        """ Synchronise le port distant sur self"""
        related_port = self.related
        related_port.related = self
        related_port.save()
470

471 472 473 474 475 476
    def clean_port_related(self):
        """ Supprime la relation related sur self"""
        related_port = self.related_port
        related_port.related = None
        related_port.save()

477
    def clean(self):
478 479 480 481
        """ 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
482
        Si un port related point vers self, on nettoie la relation
483 484 485
        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
486 487
        if hasattr(self, 'switch'):
            if self.port > self.switch.number:
488 489 490 491 492 493 494 495 496 497
                raise ValidationError(
                    "Ce port ne peut exister, numero trop élevé"
                )
        if (self.room and self.machine_interface or
                self.room and self.related or
                self.machine_interface and self.related):
            raise ValidationError(
                "Chambre, interface et related_port sont mutuellement "
                "exclusifs"
            )
498
        if self.related == self:
499 500 501
            raise ValidationError("On ne peut relier un port à lui même")
        if self.related and not self.related.related:
            if self.related.machine_interface or self.related.room:
502 503 504 505
                raise ValidationError(
                    "Le port relié est déjà occupé, veuillez le libérer "
                    "avant de créer une relation"
                )
506
            else:
507
                self.make_port_related()
508
        elif hasattr(self, 'related_port'):
509
            self.clean_port_related()
chirac's avatar
chirac committed
510 511

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

chirac's avatar
chirac committed
514

515
class Room(AclMixin, RevMixin, models.Model):
516
    """Une chambre/local contenant une prise murale"""
517 518
    PRETTY_NAME = "Chambre/ Prise murale"

lhark's avatar
lhark committed
519
    name = models.CharField(max_length=255, unique=True)
chirac's avatar
chirac committed
520
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
521

522 523
    class Meta:
        ordering = ['name']
524 525 526
        permissions = (
            ("view_room", "Peut voir un objet chambre"),
        )
527

chirac's avatar
chirac committed
528
    def __str__(self):
529
        return self.name
chirac's avatar
chirac committed
530

chirac's avatar
chirac committed
531

Gabriel Detraz's avatar
Gabriel Detraz committed
532
class PortProfile(AclMixin, RevMixin, models.Model):
Fernet Laouen's avatar
Fernet Laouen committed
533 534 535 536 537
    """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
538
    )
Fernet Laouen's avatar
Fernet Laouen committed
539 540 541
    MODES = (
        ('STRICT', 'STRICT'),
        ('COMMON', 'COMMON'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
542
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
543 544 545 546 547 548 549 550 551
    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
552 553
    )
    PROFIL_DEFAULT = (
Gabriel Detraz's avatar
Gabriel Detraz committed
554 555 556 557
        ('room', 'room'),
        ('accespoint', 'accesspoint'),
        ('uplink', 'uplink'),
        ('asso_machine', 'asso_machine'),
558
        ('nothing', 'nothing'),
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
559
    )
Fernet Laouen's avatar
Fernet Laouen committed
560
    name = models.CharField(max_length=255, verbose_name=_("Name"))
Gabriel Detraz's avatar
Gabriel Detraz committed
561 562 563 564 565 566 567 568
    profil_default = models.CharField(
        max_length=32,
        choices=PROFIL_DEFAULT,
        blank=True,
        null=True,
        unique=True,
        verbose_name=_("profil default")
    )
Fernet Laouen's avatar
Fernet Laouen committed
569
    vlan_untagged = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
570 571 572 573 574 575
        '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
576 577
    )
    vlan_tagged = models.ManyToManyField(
Gabriel Detraz's avatar
Gabriel Detraz committed
578 579 580 581 582
        'machines.Vlan',
        related_name='vlan_tagged',
        blank=True,
        verbose_name=_("VLAN(s) tagged")
    )
Fernet Laouen's avatar
Fernet Laouen committed
583
    radius_type = models.CharField(
Gabriel Detraz's avatar
Gabriel Detraz committed
584 585
        max_length=32,
        choices=TYPES,
586
        help_text="Type of radius auth : inactive, mac-address or 802.1X",
Gabriel Detraz's avatar
Gabriel Detraz committed
587
        verbose_name=_("RADIUS type")
Fernet Laouen's avatar
Fernet Laouen committed
588 589
    )
    radius_mode = models.CharField(
Gabriel Detraz's avatar
Gabriel Detraz committed
590 591 592
        max_length=32,
        choices=MODES,
        default='COMMON',
593
        help_text="In case of mac-auth : mode common or strict on this port",
Gabriel Detraz's avatar
Gabriel Detraz committed
594 595 596 597 598 599
        verbose_name=_("RADIUS mode")
    )
    speed = models.CharField(
        max_length=32,
        choices=SPEED,
        default='auto',
600
        help_text='Port speed limit',
Gabriel Detraz's avatar
Gabriel Detraz committed
601 602 603 604 605
        verbose_name=_("Speed")
    )
    mac_limit = models.IntegerField(
        null=True,
        blank=True,
606
        help_text='Limit of mac-address on this port',
Gabriel Detraz's avatar
Gabriel Detraz committed
607 608 609 610
        verbose_name=_("Mac limit")
    )
    flow_control = models.BooleanField(
        default=False,
611
        help_text='Flow control',
Gabriel Detraz's avatar
Gabriel Detraz committed
612 613 614 615
        verbose_name=_("Flow control")
    )
    dhcp_snooping = models.BooleanField(
        default=False,
616
        help_text='Protect against rogue dhcp',
Gabriel Detraz's avatar
Gabriel Detraz committed
617 618 619 620
        verbose_name=_("Dhcp snooping")
    )
    dhcpv6_snooping = models.BooleanField(
        default=False,
621
        help_text='Protect against rogue dhcpv6',
Gabriel Detraz's avatar
Gabriel Detraz committed
622 623 624 625
        verbose_name=_("Dhcpv6 snooping")
    )
    arp_protect = models.BooleanField(
        default=False,
626
        help_text='Check if ip is dhcp assigned',
Gabriel Detraz's avatar
Gabriel Detraz committed
627
        verbose_name=_("Arp protect")
Fernet Laouen's avatar
Fernet Laouen committed
628
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
629 630
    ra_guard = models.BooleanField(
        default=False,
631
        help_text='Protect against rogue ra',
Gabriel Detraz's avatar
Gabriel Detraz committed
632
        verbose_name=_("Ra guard")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
633
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
634 635
    loop_protect = models.BooleanField(
        default=False,
636
        help_text='Protect again loop',
Gabriel Detraz's avatar
Gabriel Detraz committed
637
        verbose_name=_("Loop Protect")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
638
    )
Fernet Laouen's avatar
Fernet Laouen committed
639 640 641

    class Meta:
        permissions = (
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
642
            ("view_port_profile", _("Can view a port profile object")),
Fernet Laouen's avatar
Fernet Laouen committed
643 644 645 646
        )
        verbose_name = _("Port profile")
        verbose_name_plural = _("Port profiles")

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
647 648 649 650 651 652 653 654
    security_parameters_fields = [
        'loop_protect',
        'ra_guard',
        'arp_protect',
        'dhcpv6_snooping',
        'dhcp_snooping',
        'flow_control'
    ]
655 656 657

    @cached_property
    def security_parameters_enabled(self):
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
658 659 660 661 662
        return [
            parameter
            for parameter in self.security_parameters_fields
            if getattr(self, parameter)
        ]
663

664 665 666 667
    @cached_property
    def security_parameters_as_str(self):
        return ','.join(self.security_parameters_enabled)

Fernet Laouen's avatar
Fernet Laouen committed
668 669 670 671
    def __str__(self):
        return self.name


672
@receiver(post_save, sender=AccessPoint)
673
def ap_post_save(**_kwargs):
674 675
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
676
    regen("graph_topo")
677

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

679
@receiver(post_delete, sender=AccessPoint)
680
def ap_post_delete(**_kwargs):
681 682
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
683
    regen("graph_topo")
684

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

686
@receiver(post_delete, sender=Stack)
687
def stack_post_delete(**_kwargs):
688 689
    """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
690

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

grisel-davy's avatar
grisel-davy committed
692 693 694 695
@receiver(post_save, sender=Port)
def port_post_save(**_kwargs):
    regen("graph_topo")

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

grisel-davy's avatar
grisel-davy committed
697 698 699 700
@receiver(post_delete, sender=Port)
def port_post_delete(**_kwargs):
    regen("graph_topo")

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

grisel-davy's avatar
grisel-davy committed
702 703 704 705
@receiver(post_save, sender=ModelSwitch)
def modelswitch_post_save(**_kwargs):
    regen("graph_topo")

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

grisel-davy's avatar
grisel-davy committed
707 708 709 710
@receiver(post_delete, sender=ModelSwitch)
def modelswitch_post_delete(**_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_save, sender=Building)
def building_post_save(**_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_delete, sender=Building)
def building_post_delete(**_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_save, sender=Switch)
def switch_post_save(**_kwargs):
    regen("graph_topo")

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

grisel-davy's avatar
grisel-davy committed
727 728 729
@receiver(post_delete, sender=Switch)
def switch_post_delete(**_kwargs):
    regen("graph_topo")