models.py 22.1 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
grisel-davy's avatar
grisel-davy committed
43 44
from django.db.models.signals import pre_save, post_save, post_delete
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

grisel-davy's avatar
grisel-davy committed
55 56 57 58 59
from os.path import isfile 
from os import remove



60

61
class Stack(AclMixin, RevMixin, models.Model):
62 63
    """Un objet stack. Regrouppe des switchs en foreign key
    ,contient une id de stack, un switch id min et max dans
64
    le stack"""
65 66 67 68 69
    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)
70 71
    member_id_min = models.PositiveIntegerField()
    member_id_max = models.PositiveIntegerField()
72

73 74 75 76 77
    class Meta:
        permissions = (
            ("view_stack", "Peut voir un objet stack"),
        )

78 79 80 81
    def __str__(self):
        return " ".join([self.name, self.stack_id])

    def save(self, *args, **kwargs):
82
        self.clean()
83 84 85 86 87
        if not self.name:
            self.name = self.stack_id
        super(Stack, self).save(*args, **kwargs)

    def clean(self):
88
        """ Verification que l'id_max < id_min"""
89
        if self.member_id_max < self.member_id_min:
chirac's avatar
chirac committed
90
            raise ValidationError({'member_id_max': "L'id maximale est\
91
                inférieure à l'id minimale"})
92

chirac's avatar
chirac committed
93

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

97 98 99 100
    Definition pour une borne wifi , hérite de machines.interfaces
    """
    PRETTY_NAME = "Borne WiFi"

101
    location = models.CharField(
102 103 104 105 106 107 108 109
        max_length=255,
        help_text="Détails sur la localisation de l'AP",
        blank=True,
        null=True
    )

    class Meta:
        permissions = (
110
            ("view_accesspoint", "Peut voir une borne"),
111 112
        )

grisel-davy's avatar
grisel-davy committed
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
    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):
        """Return the building of the AP/Server (building of the switchs connected to...)"""
        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"""
        return cls.objects.filter(interface__port__switch__switchbay__building=building_instance)

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


class Server(Machine):
    """Dummy class, to retrieve servers of a building, or get switch of a server"""

    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):
        """Return the building of the AP/Server (building of the switchs connected to...)"""
        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"""
        return cls.objects.filter(interface__port__switch__switchbay__building=building_instance).exclude(accesspoint__isnull=False)

177 178 179
    def __str__(self):
        return str(self.interface_set.first())

180

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

Gabriel Detraz's avatar
Gabriel Detraz committed
195 196 197
    number = models.PositiveIntegerField(
        help_text="Nombre de ports"
    )
198
    stack = models.ForeignKey(
199
        'topologie.Stack',
200 201 202 203
        blank=True,
        null=True,
        on_delete=models.SET_NULL
        )
Gabriel Detraz's avatar
Gabriel Detraz committed
204 205 206 207 208
    stack_member_id = models.PositiveIntegerField(
        blank=True,
        null=True,
        help_text="Baie de brassage du switch"
    )
209 210 211 212
    model = models.ForeignKey(
        'topologie.ModelSwitch',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
213 214
        on_delete=models.SET_NULL,
        help_text="Modèle du switch"
215
    )
216 217 218 219
    switchbay = models.ForeignKey(
        'topologie.SwitchBay',
        blank=True,
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
220 221
        on_delete=models.SET_NULL,
        help_text="Baie de brassage du switch"
222
    )
223 224

    class Meta:
225
        unique_together = ('stack', 'stack_member_id')
226
        permissions = (
Gabriel Detraz's avatar
Gabriel Detraz committed
227
            ("view_switch", "Peut voir un objet switch"),
228
        )
chirac's avatar
chirac committed
229

230
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
231 232 233
        """ Verifie que l'id stack est dans le bon range
        Appelle également le clean de la classe parente"""
        super(Switch, self).clean()
234 235
        if self.stack is not None:
            if self.stack_member_id is not None:
236
                if (self.stack_member_id > self.stack.member_id_max) or\
chirac's avatar
chirac committed
237 238 239 240 241
                        (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"}
                        )
242
            else:
243 244
                raise ValidationError({'stack_member_id': "L'id dans la stack\
                    ne peut être nul"})
245

246
    def create_ports(self, begin, end):
247 248
        """ Crée les ports de begin à end si les valeurs données
        sont cohérentes. """
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

        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.")
273

274
    def main_interface(self):
275
        """ Returns the 'main' interface of the switch """
276 277
        return self.interface_set.first()

278
    def __str__(self):
279
        return str(self.main_interface())
280

chirac's avatar
chirac committed
281

282
class ModelSwitch(AclMixin, RevMixin, models.Model):
283
    """Un modèle (au sens constructeur) de switch"""
Gabriel Detraz's avatar
Gabriel Detraz committed
284
    PRETTY_NAME = "Modèle de switch"
285 286 287 288 289 290
    reference = models.CharField(max_length=255)
    constructor = models.ForeignKey(
        'topologie.ConstructorSwitch',
        on_delete=models.PROTECT
    )

291 292 293 294 295
    class Meta:
        permissions = (
            ("view_modelswitch", "Peut voir un objet modelswitch"),
        )

296
    def __str__(self):
297
        return str(self.constructor) + ' ' + self.reference
298 299


300
class ConstructorSwitch(AclMixin, RevMixin, models.Model):
301
    """Un constructeur de switch"""
Gabriel Detraz's avatar
Gabriel Detraz committed
302
    PRETTY_NAME = "Constructeur de switch"
303 304
    name = models.CharField(max_length=255)

305 306 307 308 309
    class Meta:
        permissions = (
            ("view_constructorswitch", "Peut voir un objet constructorswitch"),
        )

310
    def __str__(self):
311
        return self.name
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
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


352
class Port(AclMixin, RevMixin, models.Model):
353
    """ Definition d'un port. Relié à un switch(foreign_key),
354 355 356 357
    un port peut etre relié de manière exclusive à :
    - une chambre (room)
    - une machine (serveur etc) (machine_interface)
    - un autre port (uplink) (related)
358
    Champs supplémentaires :
359
    - RADIUS (mode STRICT : connexion sur port uniquement si machine
360 361
    d'un adhérent à jour de cotisation et que la chambre est également à
    jour de cotisation
362 363 364 365
    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
366
    de forcer un port sur un vlan particulier. S'additionne à la politique
367
    RADIUS"""
368
    PRETTY_NAME = "Port de switch"
369

370 371 372 373 374
    switch = models.ForeignKey(
        'Switch',
        related_name="ports",
        on_delete=models.CASCADE
    )
375
    port = models.PositiveIntegerField()
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    room = models.ForeignKey(
        'Room',
        on_delete=models.PROTECT,
        blank=True,
        null=True
        )
    machine_interface = models.ForeignKey(
        'machines.Interface',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
        )
    related = models.OneToOneField(
        'self',
        null=True,
        blank=True,
        related_name='related_port'
        )
394
    custom_profile = models.ForeignKey(
395 396
        'PortProfile',
        on_delete=models.PROTECT,
397 398 399
        blank=True,
        null=True
        )
400 401
    state = models.BooleanField(
        default=True,
402 403
        help_text='Port state Active',
        verbose_name=_("Port State Active")
404
    )
Dalahro's avatar
Dalahro committed
405
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
406 407

    class Meta:
408
        unique_together = ('switch', 'port')
409 410 411
        permissions = (
            ("view_port", "Peut voir un objet port"),
        )
412

413 414
    @cached_property
    def get_port_profil(self):
415 416
        """Return the config profil for this port
        :returns: the profile of self (port)"""
417 418 419 420 421 422 423 424 425 426
        def profil_or_nothing(profil):
            port_profil = PortProfile.objects.filter(profil_default=profil).first()
            if port_profil:
                return port_profil
            else:
                nothing = PortProfile.objects.filter(profil_default='nothing').first()
                if not nothing:
                    nothing = PortProfile.objects.create(profil_default='nothing', name='nothing', radius_type='NO')
                return nothing

427 428
        if self.custom_profile:
            return self.custom_profile
429
        elif self.related:
430
            return profil_or_nothing('uplink')
431
        elif self.machine_interface:
432 433
            if hasattr(self.machine_interface.machine, 'accesspoint'):
                return profil_or_nothing('access_point')
434
            else:
435
                return profil_or_nothing('asso_machine')
436
        elif self.room:
437
            return profil_or_nothing('room')
438
        else:
439
            return profil_or_nothing('nothing')
440

441 442 443 444 445 446 447 448 449
    @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))
450

451 452 453 454 455
    def make_port_related(self):
        """ Synchronise le port distant sur self"""
        related_port = self.related
        related_port.related = self
        related_port.save()
456

457 458 459 460 461 462
    def clean_port_related(self):
        """ Supprime la relation related sur self"""
        related_port = self.related_port
        related_port.related = None
        related_port.save()

463
    def clean(self):
464 465 466 467
        """ 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
468
        Si un port related point vers self, on nettoie la relation
469 470 471
        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
472 473
        if hasattr(self, 'switch'):
            if self.port > self.switch.number:
474 475 476 477 478 479 480 481 482 483
                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"
            )
484
        if self.related == self:
485 486 487
            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:
488 489 490 491
                raise ValidationError(
                    "Le port relié est déjà occupé, veuillez le libérer "
                    "avant de créer une relation"
                )
492
            else:
493
                self.make_port_related()
494
        elif hasattr(self, 'related_port'):
495
            self.clean_port_related()
chirac's avatar
chirac committed
496 497

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

chirac's avatar
chirac committed
500

501
class Room(AclMixin, RevMixin, models.Model):
502
    """Une chambre/local contenant une prise murale"""
503 504
    PRETTY_NAME = "Chambre/ Prise murale"

lhark's avatar
lhark committed
505
    name = models.CharField(max_length=255, unique=True)
chirac's avatar
chirac committed
506
    details = models.CharField(max_length=255, blank=True)
chirac's avatar
chirac committed
507

508 509
    class Meta:
        ordering = ['name']
510 511 512
        permissions = (
            ("view_room", "Peut voir un objet chambre"),
        )
513

chirac's avatar
chirac committed
514
    def __str__(self):
515
        return self.name
chirac's avatar
chirac committed
516

chirac's avatar
chirac committed
517

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

    class Meta:
        permissions = (
                ("view_port_profile", _("Can view a port profile object")),
        )
        verbose_name = _("Port profile")
        verbose_name_plural = _("Port profiles")

633 634 635 636 637 638
    security_parameters_fields = ['loop_protect', 'ra_guard', 'arp_protect', 'dhcpv6_snooping', 'dhcp_snooping', 'flow_control']

    @cached_property
    def security_parameters_enabled(self):
        return [parameter for parameter in self.security_parameters_fields if getattr(self, parameter)]

639 640 641 642
    @cached_property
    def security_parameters_as_str(self):
        return ','.join(self.security_parameters_enabled)

Fernet Laouen's avatar
Fernet Laouen committed
643 644 645 646
    def __str__(self):
        return self.name


647
@receiver(post_save, sender=AccessPoint)
648
def ap_post_save(**_kwargs):
649 650
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
651
    regen("graph_topo")
652 653

@receiver(post_delete, sender=AccessPoint)
654
def ap_post_delete(**_kwargs):
655 656
    """Regeneration des noms des bornes vers le controleur"""
    regen('unifi-ap-names')
grisel-davy's avatar
grisel-davy committed
657
    regen("graph_topo")
658

659
@receiver(post_delete, sender=Stack)
660
def stack_post_delete(**_kwargs):
661 662
    """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
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694

@receiver(post_save, sender=Port)
def port_post_save(**_kwargs):
    regen("graph_topo")

@receiver(post_delete, sender=Port)
def port_post_delete(**_kwargs):
    regen("graph_topo")

@receiver(post_save, sender=ModelSwitch)
def modelswitch_post_save(**_kwargs):
    regen("graph_topo")

@receiver(post_delete, sender=ModelSwitch)
def modelswitch_post_delete(**_kwargs):
    regen("graph_topo")

@receiver(post_save, sender=Building)
def building_post_save(**_kwargs):
    regen("graph_topo")

@receiver(post_delete, sender=Building)
def building_post_delete(**_kwargs):
    regen("graph_topo")

@receiver(post_save, sender=Switch)
def switch_post_save(**_kwargs):
    regen("graph_topo")

@receiver(post_delete, sender=Switch)
def switch_post_delete(**_kwargs):
    regen("graph_topo")