views.py 33.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 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.
chirac's avatar
chirac committed
22 23
"""
Page des vues de l'application topologie
24

chirac's avatar
chirac committed
25 26 27 28 29 30 31 32 33 34 35
Permet de créer, modifier et supprimer :
- un port (add_port, edit_port, del_port)
- un switch : les vues d'ajout et d'édition font appel aux forms de creation
de switch, mais aussi aux forms de machines.forms (domain, interface et
machine). Le views les envoie et les save en même temps. TODO : rationaliser
et faire que la creation de machines (interfaces, domain etc) soit gérée
coté models et forms de topologie
- une chambre (new_room, edit_room, del_room)
- une stack
- l'historique de tous les objets cités
"""
36 37
from __future__ import unicode_literals

38
from django.urls import reverse
Dalahro's avatar
Dalahro committed
39 40
from django.shortcuts import render, redirect
from django.contrib import messages
41
from django.contrib.auth.decorators import login_required
Dalahro's avatar
Dalahro committed
42
from django.db import IntegrityError
43
from django.db.models import ProtectedError, Prefetch
44
from django.core.exceptions import ValidationError
45
from django.contrib.staticfiles.storage import staticfiles_storage
grisel-davy's avatar
grisel-davy committed
46 47 48 49
from django.template.loader import get_template
from django.template import Context, Template, loader

import pprint
Dalahro's avatar
Dalahro committed
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
from users.views import form
from re2o.utils import re2o_paginator, SortTable
from re2o.acl import (
    can_create,
    can_edit,
    can_delete,
    can_view,
    can_view_all,
)
from machines.forms import (
    DomainForm,
    EditInterfaceForm,
    AddInterfaceForm
)
from machines.views import generate_ipv4_mbf_param
from machines.models import Interface
from preferences.models import AssoOption, GeneralOption

from .models import (
70 71 72 73 74
    Switch,
    Port,
    Room,
    Stack,
    ModelSwitch,
75
    ConstructorSwitch,
76 77
    AccessPoint,
    SwitchBay,
78 79
    Building,
    Server
80
)
81 82 83 84
from .forms import (
    EditPortForm,
    NewSwitchForm,
    EditSwitchForm,
85 86 87
    AddPortForm,
    EditRoomForm,
    StackForm,
88
    EditModelSwitchForm,
89
    EditConstructorSwitchForm,
90
    CreatePortsForm,
91
    AddAccessPointForm,
92 93 94
    EditAccessPointForm,
    EditSwitchBayForm,
    EditBuildingForm
95
)
96

97 98
from subprocess import Popen,PIPE

chirac's avatar
chirac committed
99

chirac's avatar
chirac committed
100
@login_required
101
@can_view_all(Switch)
Dalahro's avatar
Dalahro committed
102
def index(request):
103
    """ Vue d'affichage de tous les swicthes"""
104 105 106 107 108 109 110 111
    switch_list = (Switch.objects
                   .prefetch_related(Prefetch(
                       'interface_set',
                       queryset=(Interface.objects
                                 .select_related('ipv4__ip_type__extension')
                                 .select_related('domain__extension'))
                   ))
                   .select_related('stack'))
112 113 114 115 116 117
    switch_list = SortTable.sort(
        switch_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX
    )
118
    pagination_number = GeneralOption.get_cached_value('pagination_number')
119
    switch_list = re2o_paginator(request, switch_list, pagination_number)
120 121 122

    # make_machine_graph()

123 124 125 126 127
    return render(
        request,
        'topologie/index.html',
        {'switch_list': switch_list}
    )
chirac's avatar
chirac committed
128

Dalahro's avatar
Dalahro committed
129

chirac's avatar
chirac committed
130
@login_required
131 132
@can_view_all(Port)
@can_view(Switch)
133
def index_port(request, switch, switchid):
134
    """ Affichage de l'ensemble des ports reliés à un switch particulier"""
135 136 137 138 139 140 141 142 143 144 145 146
    port_list = (Port.objects
                 .filter(switch=switch)
                 .select_related('room')
                 .select_related('machine_interface__domain__extension')
                 .select_related('machine_interface__machine__user')
                 .select_related('related__switch')
                 .prefetch_related(Prefetch(
                     'related__switch__interface_set',
                     queryset=(Interface.objects
                               .select_related('domain__extension'))
                 ))
                 .select_related('switch'))
147 148 149 150 151 152
    port_list = SortTable.sort(
        port_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_PORT
    )
153 154 155 156 157 158 159 160 161
    return render(
        request,
        'topologie/index_p.html',
        {
            'port_list': port_list,
            'id_switch': switchid,
            'nom_switch': switch
        }
    )
chirac's avatar
chirac committed
162

Dalahro's avatar
Dalahro committed
163

chirac's avatar
chirac committed
164
@login_required
165
@can_view_all(Room)
chirac's avatar
chirac committed
166
def index_room(request):
167
    """ Affichage de l'ensemble des chambres"""
168
    room_list = Room.objects
169 170 171 172 173 174
    room_list = SortTable.sort(
        room_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_ROOM
    )
175
    pagination_number = GeneralOption.get_cached_value('pagination_number')
176
    room_list = re2o_paginator(request, room_list, pagination_number)
177 178 179 180 181
    return render(
        request,
        'topologie/index_room.html',
        {'room_list': room_list}
    )
chirac's avatar
chirac committed
182

chirac's avatar
chirac committed
183

184
@login_required
185 186
@can_view_all(AccessPoint)
def index_ap(request):
187
    """ Affichage de l'ensemble des bornes"""
188 189 190 191 192 193 194
    ap_list = (AccessPoint.objects
               .prefetch_related(Prefetch(
                   'interface_set',
                   queryset=(Interface.objects
                             .select_related('ipv4__ip_type__extension')
                             .select_related('domain__extension'))
               )))
195 196
    ap_list = SortTable.sort(
        ap_list,
197 198 199 200 201
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_BORNE
    )
    pagination_number = GeneralOption.get_cached_value('pagination_number')
202
    ap_list = re2o_paginator(request, ap_list, pagination_number)
203 204 205 206 207
    return render(
        request,
        'topologie/index_ap.html',
        {'ap_list': ap_list}
    )
208 209


210
@login_required
211
@can_view_all(Stack)
212 213
@can_view_all(Building)
@can_view_all(SwitchBay)
214
def index_physical_grouping(request):
chirac's avatar
chirac committed
215
    """Affichage de la liste des stacks (affiche l'ensemble des switches)"""
216 217 218 219
    stack_list = (Stack.objects
                  .prefetch_related(
                      'switch_set__interface_set__domain__extension'
                  ))
220 221
    building_list = Building.objects.all()
    switch_bay_list = SwitchBay.objects.select_related('building')
222 223 224 225 226 227
    stack_list = SortTable.sort(
        stack_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_STACK
    )
228 229 230 231 232 233 234 235 236 237 238 239
    building_list = SortTable.sort(
        building_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_BUILDING
    )
    switch_bay_list = SortTable.sort(
        switch_bay_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_SWITCH_BAY
    )
240 241 242 243 244 245 246 247 248
    return render(
        request,
        'topologie/index_physical_grouping.html',
        {
            'stack_list': stack_list,
            'switch_bay_list': switch_bay_list,
            'building_list': building_list,
        }
    )
249 250


251
@login_required
252 253
@can_view_all(ModelSwitch)
@can_view_all(ConstructorSwitch)
254 255
def index_model_switch(request):
    """ Affichage de l'ensemble des modèles de switches"""
256
    model_switch_list = ModelSwitch.objects.select_related('constructor')
257 258 259 260 261 262 263 264 265 266 267 268 269
    constructor_switch_list = ConstructorSwitch.objects
    model_switch_list = SortTable.sort(
        model_switch_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_MODEL_SWITCH
    )
    constructor_switch_list = SortTable.sort(
        constructor_switch_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.TOPOLOGIE_INDEX_CONSTRUCTOR_SWITCH
    )
270 271 272 273 274 275 276 277
    return render(
        request,
        'topologie/index_model_switch.html',
        {
            'model_switch_list': model_switch_list,
            'constructor_switch_list': constructor_switch_list,
        }
    )
278 279


chirac's avatar
chirac committed
280
@login_required
281
@can_create(Port)
282
def new_port(request, switchid):
283
    """ Nouveau port"""
Dalahro's avatar
Dalahro committed
284
    try:
285
        switch = Switch.objects.get(pk=switchid)
Dalahro's avatar
Dalahro committed
286 287
    except Switch.DoesNotExist:
        messages.error(request, u"Switch inexistant")
288
        return redirect(reverse('topologie:index'))
Dalahro's avatar
Dalahro committed
289 290 291 292 293
    port = AddPortForm(request.POST or None)
    if port.is_valid():
        port = port.save(commit=False)
        port.switch = switch
        try:
294
            port.save()
Dalahro's avatar
Dalahro committed
295 296
            messages.success(request, "Port ajouté")
        except IntegrityError:
chirac's avatar
chirac committed
297
            messages.error(request, "Ce port existe déjà")
298
        return redirect(reverse(
299
            'topologie:index-port',
300 301 302 303 304 305
            kwargs={'switchid': switchid}
        ))
    return form(
        {'id_switch': switchid, 'topoform': port, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request)
chirac's avatar
chirac committed
306

Dalahro's avatar
Dalahro committed
307

chirac's avatar
chirac committed
308
@login_required
309
@can_edit(Port)
310
def edit_port(request, port_object, **_kwargs):
chirac's avatar
chirac committed
311 312
    """ Edition d'un port. Permet de changer le switch parent et
    l'affectation du port"""
313

314
    port = EditPortForm(request.POST or None, instance=port_object)
Dalahro's avatar
Dalahro committed
315
    if port.is_valid():
316 317 318
        if port.changed_data:
            port.save()
            messages.success(request, "Le port a bien été modifié")
319 320
        return redirect(reverse(
            'topologie:index-port',
321
            kwargs={'switchid': str(port_object.switch.id)}
322 323 324 325 326 327 328 329 330 331
        ))
    return form(
        {
            'id_switch': str(port_object.switch.id),
            'topoform': port,
            'action_name': 'Editer'
        },
        'topologie/topo.html',
        request
    )
chirac's avatar
chirac committed
332

chirac's avatar
chirac committed
333

334
@login_required
335
@can_delete(Port)
336
def del_port(request, port, **_kwargs):
337
    """ Supprime le port"""
Gabriel Detraz's avatar
Gabriel Detraz committed
338 339
    if request.method == "POST":
        try:
340 341
            port.delete()
            messages.success(request, "Le port a été détruit")
Gabriel Detraz's avatar
Gabriel Detraz committed
342
        except ProtectedError:
343 344 345 346 347
            messages.error(
                request,
                ("Le port %s est affecté à un autre objet, impossible "
                 "de le supprimer" % port)
            )
348 349
        return redirect(reverse(
            'topologie:index-port',
350 351
            kwargs={'switchid': str(port.switch.id)}
        ))
chirac's avatar
chirac committed
352 353
    return form({'objet': port}, 'topologie/delete.html', request)

Gabriel Detraz's avatar
Gabriel Detraz committed
354 355

@login_required
356
@can_create(Stack)
357
def new_stack(request):
358
    """Ajoute un nouveau stack : stackid_min, max, et nombre de switches"""
359
    stack = StackForm(request.POST or None)
chirac's avatar
chirac committed
360
    if stack.is_valid():
361
        stack.save()
chirac's avatar
chirac committed
362
        messages.success(request, "Stack crée")
Gabriel Detraz's avatar
Gabriel Detraz committed
363
        return redirect(reverse('topologie:index-physical-grouping'))
364 365 366 367 368
    return form(
        {'topoform': stack, 'action_name': 'Créer'},
        'topologie/topo.html',
        request
    )
369 370 371


@login_required
372
@can_edit(Stack)
373
def edit_stack(request, stack, **_kwargs):
chirac's avatar
chirac committed
374
    """Edition d'un stack (nombre de switches, nom...)"""
375 376
    stack = StackForm(request.POST or None, instance=stack)
    if stack.is_valid():
377 378
        if stack.changed_data:
            stack.save()
Gabriel Detraz's avatar
Gabriel Detraz committed
379
        return redirect(reverse('topologie:index-physical-grouping'))
380 381 382 383 384
    return form(
        {'topoform': stack, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
chirac's avatar
chirac committed
385

386

387
@login_required
388
@can_delete(Stack)
389
def del_stack(request, stack, **_kwargs):
chirac's avatar
chirac committed
390
    """Supprime un stack"""
391 392
    if request.method == "POST":
        try:
393 394
            stack.delete()
            messages.success(request, "La stack a eté détruite")
395
        except ProtectedError:
396 397 398 399 400
            messages.error(
                request,
                ("La stack %s est affectée à un autre objet, impossible "
                 "de la supprimer" % stack)
            )
401
        return redirect(reverse('topologie:index-physical-grouping'))
chirac's avatar
chirac committed
402 403
    return form({'objet': stack}, 'topologie/delete.html', request)

404

405
@login_required
406
@can_edit(Stack)
407
def edit_switchs_stack(request, stack, **_kwargs):
chirac's avatar
chirac committed
408
    """Permet d'éditer la liste des switches dans une stack et l'ajouter"""
409

410 411 412 413 414 415 416 417
    if request.method == "POST":
        pass
    else:
        context = {'stack': stack}
        context['switchs_stack'] = stack.switchs_set.all()
        context['switchs_autres'] = Switch.object.filter(stack=None)


chirac's avatar
chirac committed
418
@login_required
419
@can_create(Switch)
Dalahro's avatar
Dalahro committed
420
def new_switch(request):
chirac's avatar
chirac committed
421 422 423
    """ Creation d'un switch. Cree en meme temps l'interface et la machine
    associée. Vue complexe. Appelle successivement les 4 models forms
    adaptés : machine, interface, domain et switch"""
424
    switch = NewSwitchForm(
425 426 427
        request.POST or None,
        user=request.user
    )
428
    interface = AddInterfaceForm(
chirac's avatar
chirac committed
429
        request.POST or None,
430
        user=request.user
431
    )
432
    domain = DomainForm(
chirac's avatar
chirac committed
433 434
        request.POST or None,
        )
435
    if switch.is_valid() and interface.is_valid():
436
        user = AssoOption.get_cached_value('utilisateur_asso')
437
        if not user:
438 439 440 441 442
            messages.error(
                request,
                ("L'user association n'existe pas encore, veuillez le "
                 "créer ou le linker dans preferences")
            )
443
            return redirect(reverse('topologie:index'))
444 445 446 447
        new_switch_obj = switch.save(commit=False)
        new_switch_obj.user = user
        new_interface_obj = interface.save(commit=False)
        domain.instance.interface_parent = new_interface_obj
448
        if domain.is_valid():
449 450 451 452 453 454
            new_domain_obj = domain.save(commit=False)
            new_switch_obj.save()
            new_interface_obj.machine = new_switch_obj
            new_interface_obj.save()
            new_domain_obj.interface_parent = new_interface_obj
            new_domain_obj.save()
455 456
            messages.success(request, "Le switch a été créé")
            return redirect(reverse('topologie:index'))
457
    i_mbf_param = generate_ipv4_mbf_param(interface, False)
458 459 460 461 462 463 464 465 466 467 468
    return form(
        {
            'topoform': interface,
            'machineform': switch,
            'domainform': domain,
            'i_mbf_param': i_mbf_param,
            'device': 'switch',
        },
        'topologie/topo_more.html',
        request
    )
chirac's avatar
chirac committed
469

Dalahro's avatar
Dalahro committed
470

471
@login_required
472
@can_create(Port)
473
def create_ports(request, switchid):
474 475
    """ Création d'une liste de ports pour un switch."""
    try:
476
        switch = Switch.objects.get(pk=switchid)
477 478
    except Switch.DoesNotExist:
        messages.error(request, u"Switch inexistant")
479
        return redirect(reverse('topologie:index'))
480

481
    s_begin = s_end = 0
482 483
    nb_ports = switch.ports.count()
    if nb_ports > 0:
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
484 485 486
        ports = switch.ports.order_by('port').values('port')
        s_begin = ports.first().get('port')
        s_end = ports.last().get('port')
487

488 489
    port_form = CreatePortsForm(
        request.POST or None,
490
        initial={'begin': s_begin, 'end': s_end}
491
    )
492

493 494 495
    if port_form.is_valid():
        begin = port_form.cleaned_data['begin']
        end = port_form.cleaned_data['end']
496 497 498 499 500
        try:
            switch.create_ports(begin, end)
            messages.success(request, "Ports créés.")
        except ValidationError as e:
            messages.error(request, ''.join(e))
501 502
        return redirect(reverse(
            'topologie:index-port',
503
            kwargs={'switchid': switchid}
504
            ))
505 506 507 508 509
    return form(
        {'id_switch': switchid, 'topoform': port_form},
        'topologie/switch.html',
        request
    )
510

Dalahro's avatar
Dalahro committed
511

chirac's avatar
chirac committed
512
@login_required
513
@can_edit(Switch)
514
def edit_switch(request, switch, switchid):
chirac's avatar
chirac committed
515 516
    """ Edition d'un switch. Permet de chambre nombre de ports,
    place dans le stack, interface et machine associée"""
517

518
    switch_form = EditSwitchForm(
chirac's avatar
chirac committed
519
        request.POST or None,
520
        instance=switch,
521
        user=request.user
chirac's avatar
chirac committed
522
        )
523
    interface_form = EditInterfaceForm(
chirac's avatar
chirac committed
524
        request.POST or None,
525
        instance=switch.interface_set.first(),
526
        user=request.user
chirac's avatar
chirac committed
527
        )
528
    domain_form = DomainForm(
chirac's avatar
chirac committed
529
        request.POST or None,
530
        instance=switch.interface_set.first().domain
chirac's avatar
chirac committed
531
        )
532
    if switch_form.is_valid() and interface_form.is_valid():
533 534 535
        new_switch_obj = switch_form.save(commit=False)
        new_interface_obj = interface_form.save(commit=False)
        new_domain_obj = domain_form.save(commit=False)
536
        if switch_form.changed_data:
537
            new_switch_obj.save()
538
        if interface_form.changed_data:
539
            new_interface_obj.save()
540
        if domain_form.changed_data:
541
            new_domain_obj.save()
542
        messages.success(request, "Le switch a bien été modifié")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
543
        return redirect(reverse('topologie:index'))
544 545 546 547 548 549 550 551 552 553 554 555 556
    i_mbf_param = generate_ipv4_mbf_param(interface_form, False)
    return form(
        {
            'id_switch': switchid,
            'topoform': interface_form,
            'machineform': switch_form,
            'domainform': domain_form,
            'i_mbf_param': i_mbf_param,
            'device': 'switch',
        },
        'topologie/topo_more.html',
        request
    )
chirac's avatar
chirac committed
557

chirac's avatar
chirac committed
558

559
@login_required
560 561 562
@can_create(AccessPoint)
def new_ap(request):
    """ Creation d'une ap. Cree en meme temps l'interface et la machine
563 564
    associée. Vue complexe. Appelle successivement les 3 models forms
    adaptés : machine, interface, domain et switch"""
565
    ap = AddAccessPointForm(
566 567 568
        request.POST or None,
        user=request.user
    )
569
    interface = AddInterfaceForm(
570 571 572 573 574 575
        request.POST or None,
        user=request.user
    )
    domain = DomainForm(
        request.POST or None,
        )
576
    if ap.is_valid() and interface.is_valid():
577 578
        user = AssoOption.get_cached_value('utilisateur_asso')
        if not user:
579 580 581 582 583
            messages.error(
                request,
                ("L'user association n'existe pas encore, veuillez le "
                 "créer ou le linker dans preferences")
            )
584
            return redirect(reverse('topologie:index'))
585 586 587 588
        new_ap_obj = ap.save(commit=False)
        new_ap_obj.user = user
        new_interface_obj = interface.save(commit=False)
        domain.instance.interface_parent = new_interface_obj
589
        if domain.is_valid():
590 591 592 593 594 595
            new_domain_obj = domain.save(commit=False)
            new_ap_obj.save()
            new_interface_obj.machine = new_ap_obj
            new_interface_obj.save()
            new_domain_obj.interface_parent = new_interface_obj
            new_domain_obj.save()
596
            messages.success(request, "La borne a été créé")
597
            return redirect(reverse('topologie:index-ap'))
598
    i_mbf_param = generate_ipv4_mbf_param(interface, False)
599 600 601 602 603 604 605 606 607 608 609
    return form(
        {
            'topoform': interface,
            'machineform': ap,
            'domainform': domain,
            'i_mbf_param': i_mbf_param,
            'device': 'wifi ap',
        },
        'topologie/topo_more.html',
        request
    )
610 611 612


@login_required
613
@can_edit(AccessPoint)
614
def edit_ap(request, ap, **_kwargs):
615 616
    """ Edition d'un switch. Permet de chambre nombre de ports,
    place dans le stack, interface et machine associée"""
617
    interface_form = EditInterfaceForm(
618 619
        request.POST or None,
        user=request.user,
620
        instance=ap.interface_set.first()
621
    )
622
    ap_form = EditAccessPointForm(
623 624
        request.POST or None,
        user=request.user,
625
        instance=ap
626 627 628
    )
    domain_form = DomainForm(
        request.POST or None,
629
        instance=ap.interface_set.first().domain
630
        )
631
    if ap_form.is_valid() and interface_form.is_valid():
632 633
        user = AssoOption.get_cached_value('utilisateur_asso')
        if not user:
634 635 636 637 638
            messages.error(
                request,
                ("L'user association n'existe pas encore, veuillez le "
                 "créer ou le linker dans preferences")
            )
639
            return redirect(reverse('topologie:index-ap'))
640 641 642
        new_ap_obj = ap_form.save(commit=False)
        new_interface_obj = interface_form.save(commit=False)
        new_domain_obj = domain_form.save(commit=False)
643
        if ap_form.changed_data:
644
            new_ap_obj.save()
645
        if interface_form.changed_data:
646
            new_interface_obj.save()
647
        if domain_form.changed_data:
648
            new_domain_obj.save()
649
        messages.success(request, "La borne a été modifiée")
650
        return redirect(reverse('topologie:index-ap'))
651 652 653 654 655 656 657 658 659 660 661 662 663
    i_mbf_param = generate_ipv4_mbf_param(interface_form, False)
    return form(
        {
            'topoform': interface_form,
            'machineform': ap_form,
            'domainform': domain_form,
            'i_mbf_param': i_mbf_param,
            'device': 'wifi ap',
        },
        'topologie/topo_more.html',
        request
    )

664

chirac's avatar
chirac committed
665
@login_required
666
@can_create(Room)
chirac's avatar
chirac committed
667
def new_room(request):
668
    """Nouvelle chambre """
chirac's avatar
chirac committed
669 670
    room = EditRoomForm(request.POST or None)
    if room.is_valid():
671
        room.save()
chirac's avatar
chirac committed
672
        messages.success(request, "La chambre a été créé")
673
        return redirect(reverse('topologie:index-room'))
674 675 676 677 678
    return form(
        {'topoform': room, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request
    )
chirac's avatar
chirac committed
679

chirac's avatar
chirac committed
680 681

@login_required
682
@can_edit(Room)
683
def edit_room(request, room, **_kwargs):
684
    """ Edition numero et details de la chambre"""
chirac's avatar
chirac committed
685 686
    room = EditRoomForm(request.POST or None, instance=room)
    if room.is_valid():
687 688 689
        if room.changed_data:
            room.save()
            messages.success(request, "La chambre a bien été modifiée")
690
        return redirect(reverse('topologie:index-room'))
691 692 693 694 695
    return form(
        {'topoform': room, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
chirac's avatar
chirac committed
696

chirac's avatar
chirac committed
697 698

@login_required
699
@can_delete(Room)
700
def del_room(request, room, **_kwargs):
701
    """ Suppression d'un chambre"""
chirac's avatar
chirac committed
702
    if request.method == "POST":
703
        try:
704 705
            room.delete()
            messages.success(request, "La chambre/prise a été détruite")
706
        except ProtectedError:
707 708 709 710 711
            messages.error(
                request,
                ("La chambre %s est affectée à un autre objet, impossible "
                 "de la supprimer (switch ou user)" % room)
            )
712
        return redirect(reverse('topologie:index-room'))
713 714 715 716 717
    return form(
        {'objet': room, 'objet_name': 'Chambre'},
        'topologie/delete.html',
        request
    )
718 719 720


@login_required
721
@can_create(ModelSwitch)
722 723 724 725
def new_model_switch(request):
    """Nouveau modèle de switch"""
    model_switch = EditModelSwitchForm(request.POST or None)
    if model_switch.is_valid():
726
        model_switch.save()
727
        messages.success(request, "Le modèle a été créé")
728
        return redirect(reverse('topologie:index-model-switch'))
729 730 731 732 733
    return form(
        {'topoform': model_switch, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request
    )
734 735 736


@login_required
737
@can_edit(ModelSwitch)
738
def edit_model_switch(request, model_switch, **_kwargs):
739
    """ Edition d'un modèle de switch"""
740

741 742 743 744
    model_switch = EditModelSwitchForm(
        request.POST or None,
        instance=model_switch
    )
745
    if model_switch.is_valid():
746 747 748
        if model_switch.changed_data:
            model_switch.save()
            messages.success(request, "Le modèle a bien été modifié")
749
        return redirect(reverse('topologie:index-model-switch'))
750 751 752 753 754
    return form(
        {'topoform': model_switch, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
755 756 757


@login_required
758
@can_delete(ModelSwitch)
759
def del_model_switch(request, model_switch, **_kwargs):
760 761 762
    """ Suppression d'un modèle de switch"""
    if request.method == "POST":
        try:
763 764
            model_switch.delete()
            messages.success(request, "Le modèle a été détruit")
765
        except ProtectedError:
766 767 768 769 770
            messages.error(
                request,
                ("Le modèle %s est affectée à un autre objet, impossible "
                 "de la supprimer (switch ou user)" % model_switch)
            )
771
        return redirect(reverse('topologie:index-model-switch'))
772 773 774 775 776
    return form(
        {'objet': model_switch, 'objet_name': 'Modèle de switch'},
        'topologie/delete.html',
        request
    )
777 778


779 780 781 782 783 784 785 786
@login_required
@can_create(SwitchBay)
def new_switch_bay(request):
    """Nouvelle baie de switch"""
    switch_bay = EditSwitchBayForm(request.POST or None)
    if switch_bay.is_valid():
        switch_bay.save()
        messages.success(request, "La baie a été créé")
787
        return redirect(reverse('topologie:index-physical-grouping'))
788 789 790 791 792
    return form(
        {'topoform': switch_bay, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request
    )
793 794 795 796


@login_required
@can_edit(SwitchBay)
797
def edit_switch_bay(request, switch_bay, **_kwargs):
798 799 800 801 802 803
    """ Edition d'une baie de switch"""
    switch_bay = EditSwitchBayForm(request.POST or None, instance=switch_bay)
    if switch_bay.is_valid():
        if switch_bay.changed_data:
            switch_bay.save()
            messages.success(request, "Le switch a bien été modifié")
804
        return redirect(reverse('topologie:index-physical-grouping'))
805 806 807 808 809
    return form(
        {'topoform': switch_bay, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
810 811 812 813


@login_required
@can_delete(SwitchBay)
814
def del_switch_bay(request, switch_bay, **_kwargs):
815 816 817 818 819 820
    """ Suppression d'une baie de switch"""
    if request.method == "POST":
        try:
            switch_bay.delete()
            messages.success(request, "La baie a été détruite")
        except ProtectedError:
821 822 823 824 825
            messages.error(
                request,
                ("La baie %s est affecté à un autre objet, impossible "
                 "de la supprimer (switch ou user)" % switch_bay)
            )
826
        return redirect(reverse('topologie:index-physical-grouping'))
827 828 829 830 831
    return form(
        {'objet': switch_bay, 'objet_name': 'Baie de switch'},
        'topologie/delete.html',
        request
    )
832 833


834 835 836 837 838 839 840 841
@login_required
@can_create(Building)
def new_building(request):
    """Nouveau batiment"""
    building = EditBuildingForm(request.POST or None)
    if building.is_valid():
        building.save()
        messages.success(request, "Le batiment a été créé")
842
        return redirect(reverse('topologie:index-physical-grouping'))
843 844 845 846 847
    return form(
        {'topoform': building, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request
    )
848 849 850 851


@login_required
@can_edit(Building)
852
def edit_building(request, building, **_kwargs):
853 854 855 856 857 858
    """ Edition d'un batiment"""
    building = EditBuildingForm(request.POST or None, instance=building)
    if building.is_valid():
        if building.changed_data:
            building.save()
            messages.success(request, "Le batiment a bien été modifié")
859
        return redirect(reverse('topologie:index-physical-grouping'))
860 861 862 863 864
    return form(
        {'topoform': building, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
865 866 867 868


@login_required
@can_delete(Building)
869
def del_building(request, building, **_kwargs):
870 871 872 873 874 875
    """ Suppression d'un batiment"""
    if request.method == "POST":
        try:
            building.delete()
            messages.success(request, "La batiment a été détruit")
        except ProtectedError:
876 877 878 879 880
            messages.error(
                request,
                ("Le batiment %s est affecté à un autre objet, impossible "
                 "de la supprimer (switch ou user)" % building)
            )
881
        return redirect(reverse('topologie:index-physical-grouping'))
882 883 884 885 886
    return form(
        {'objet': building, 'objet_name': 'Bâtiment'},
        'topologie/delete.html',
        request
    )
887 888


889
@login_required
890
@can_create(ConstructorSwitch)
891 892 893 894
def new_constructor_switch(request):
    """Nouveau constructeur de switch"""
    constructor_switch = EditConstructorSwitchForm(request.POST or None)
    if constructor_switch.is_valid():
895
        constructor_switch.save()
896
        messages.success(request, "Le constructeur a été créé")
897
        return redirect(reverse('topologie:index-model-switch'))
898 899 900 901 902
    return form(
        {'topoform': constructor_switch, 'action_name': 'Ajouter'},
        'topologie/topo.html',
        request
    )
903 904 905


@login_required
906
@can_edit(ConstructorSwitch)
907
def edit_constructor_switch(request, constructor_switch, **_kwargs):
908
    """ Edition d'un constructeur de switch"""
909

910 911 912 913
    constructor_switch = EditConstructorSwitchForm(
        request.POST or None,
        instance=constructor_switch
    )
914
    if constructor_switch.is_valid():
915 916 917
        if constructor_switch.changed_data:
            constructor_switch.save()
            messages.success(request, "Le modèle a bien été modifié")
918
        return redirect(reverse('topologie:index-model-switch'))
919 920 921 922 923
    return form(
        {'topoform': constructor_switch, 'action_name': 'Editer'},
        'topologie/topo.html',
        request
    )
924 925 926


@login_required
927
@can_delete(ConstructorSwitch)
928
def del_constructor_switch(request, constructor_switch, **_kwargs):
929 930 931
    """ Suppression d'un constructeur de switch"""
    if request.method == "POST":
        try:
932 933
            constructor_switch.delete()
            messages.success(request, "Le constructeur a été détruit")
934
        except ProtectedError:
935 936 937 938 939
            messages.error(
                request,
                ("Le constructeur %s est affecté à un autre objet, impossible "
                 "de la supprimer (switch ou user)" % constructor_switch)
            )
940
        return redirect(reverse('topologie:index-model-switch'))
941 942 943 944
    return form({
        'objet': constructor_switch,
        'objet_name': 'Constructeur de switch'
        }, 'topologie/delete.html', request)
945 946 947 948 949 950


def make_machine_graph():
    """
    Crée le fichier dot et l'image du graph des Switchs
    """
951
    dico={'subs':[],'links':[],'alone':[],'colors':{'head':"#7f0505",'back':"#b5adad",'texte':"#563d01",'border_bornes':"#02078e",'head_bornes':"#25771c",'head_server':"#1c3777"}}
952 953 954 955 956
    missing=[]
    detected=[]
    for sw in Switch.objects.all():
        if(sw not in detected):
            missing.append(sw)
grisel-davy's avatar
grisel-davy committed
957
    for building in Building.objects.all():#Parcour tous les batiments
958
        dico['subs'].append({'bat_id':building.id,'bat_name':building,'switchs':[],'bornes':[],'machines':[]})
grisel-davy's avatar
grisel-davy committed
959 960
        for switch in Switch.objects.filter(switchbay__building=building):#Parcour tous les switchs de ce batiment
            dico['subs'][-1]['switchs'].append({'name':switch.main_interface().domain.name,'nombre':switch.number,'model':switch.model,'id':switch.id,'batiment':building,'ports':[]})
grisel-davy's avatar
grisel-davy committed
961 962 963
            for p in switch.ports.all().filter(related__isnull=False):#Parcour tout les ports liés de ce switch 
                dico['subs'][-1]['switchs'][-1]['ports'].append({'numero':p.port,'related':p.related.switch.main_interface().domain.name})

grisel-davy's avatar
grisel-davy committed
964
        for ap in AccessPoint.all_ap_in(building):
965 966 967 968 969 970
            dico['subs'][-1]['bornes'].append({'name':ap.short_name,'switch':ap.switch()[0].main_interface().domain.name,'port':ap.switch()[0].ports.filter(machine_interface__machine=ap)[0].port})
        for server in Server.all_server_in(building):
            dico['subs'][-1]['machines'].append({'name':server.short_name,'switch':server.switch()[0].main_interface().domain.name,'port':Port.objects.filter(machine_interface__machine=server)[0].port})

        # for ma in Allmachines_in(building):
        #     dico['subs'][-1]['machines'].append({'name':ma.short_name,'id':ma.id,'switch':ma.switch()[0].main_interface().domain.name,'port':ma.switch()[0].ports.filter(machine_interface__machine=ap)[0].port})
grisel-davy's avatar
grisel-davy committed
971 972


grisel-davy's avatar
grisel-davy committed
973 974 975 976
    while(missing!=[]):#Tant que la liste des oubliés n'est pas vide i.e on les a pas tous passer
        links,new_detected=recursive_switchs(missing[0].ports.all().filter(related=None).first(),None,[missing[0]])
        for link in links:
            dico['links'].append(link)
977
        missing=[i for i in missing if i not in new_detected]#on recrée la liste des oubliés et des detectés
978
        detected+=new_detected
grisel-davy's avatar
grisel-davy committed
979 980 981
    for switch in Switch.objects.all().filter(switchbay__isnull=True).exclude(ports__related__isnull=False):#Tous ceux qui ne sont ni connectés ni dans un batiment
        dico['alone'].append({'id':switch.id,'name':switch.main_interface().domain.name})
    dot_data=generate_image(dico)
982
    fichier = open("media/images/switchs.dot","w")
grisel-davy's avatar
grisel-davy committed
983
    fichier.write(dot_data)
984 985 986 987
    fichier.close()
    unflatten = Popen(["unflatten","-l", "3", "media/images/switchs.dot"], stdout=PIPE)
    image = Popen(["dot", "-Tpng", "-o", "media/images/switchs.png"], stdin=unflatten.stdout, stdout=PIPE)

grisel-davy's avatar
grisel-davy committed
988 989 990 991 992 993 994 995 996 997 998
def generate_image(data,template='topologie/graph_switch.dot'):
    t = loader.get_template(template)
    if not isinstance(t, Template) and not (hasattr(t, 'template') and isinstance(t.template, Template)):
        raise Exception("Le template par défaut de Django n'est pas utilisé."
                        "Cela peut mener à des erreurs de rendu."
                        "Vérifiez les paramètres")
    c = Context(data).flatten()
    dot = t.render(c)
    return(dot)

def recursive_switchs(port_start, switch_before, detected):
999 1000 1001
    """
    Parcour récursivement le switchs auquel appartient port_start pour trouver les ports suivants liés
    """
grisel-davy's avatar
grisel-davy committed
1002 1003
    links_return=[]#Liste de dictionaires qui stockes les nouveaux liens détéctés
    l_ports=port_start.switch.ports.filter(related__isnull=False)#Liste des ports dont le related est non null
1004
    for port in l_ports:
grisel-davy's avatar
grisel-davy committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        if port.related.switch!=switch_before and port.related.switch!=port.switch:#Pas le switch dont on vient, pas le switch actuel
            detected.append(port_start.switch)
            detected.append(port.related.switch)
            links={'depart':port_start.switch.id,'arrive':port.related.switch.id}
            links_down, detected = recursive_switchs(port.related, port_start.switch, detected)
            links_return.append(links)
            for link in links_down:
                if(link!=[]):
                    links_return.append(link)
    return (links_return, detected)