diff --git a/install_utils/apache2/re2o-tls.conf b/install_utils/apache2/re2o-tls.conf index 50334141..83e2cf13 100644 --- a/install_utils/apache2/re2o-tls.conf +++ b/install_utils/apache2/re2o-tls.conf @@ -21,6 +21,7 @@ Alias /static PATH/static_files + Alias /media PATH/media WSGIScriptAlias / PATH/re2o/wsgi.py WSGIProcessGroup re2o diff --git a/install_utils/apache2/re2o.conf b/install_utils/apache2/re2o.conf index 0e0fd668..680fb05d 100644 --- a/install_utils/apache2/re2o.conf +++ b/install_utils/apache2/re2o.conf @@ -14,6 +14,7 @@ Alias /static PATH/static_files + Alias /media PATH/media WSGIScriptAlias / PATH/re2o/wsgi.py WSGIProcessGroup re2o diff --git a/machines/migrations/0077_auto_20180409_2243.py b/machines/migrations/0077_auto_20180409_2243.py new file mode 100644 index 00000000..3ac63072 --- /dev/null +++ b/machines/migrations/0077_auto_20180409_2243.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.7 on 2018-04-09 20:43 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('machines', '0076_auto_20180130_1623'), + ] + + operations = [ + migrations.AlterField( + model_name='extension', + name='origin', + field=models.ForeignKey(blank=True, help_text='Enregistrement A associé à la zone', null=True, on_delete=django.db.models.deletion.PROTECT, to='machines.IpList'), + ), + ] diff --git a/machines/models.py b/machines/models.py index dc2dba65..5af11b36 100644 --- a/machines/models.py +++ b/machines/models.py @@ -484,7 +484,7 @@ class Extension(RevMixin, AclMixin, models.Model): help_text="Nom de la zone, doit commencer par un point (.example.org)" ) need_infra = models.BooleanField(default=False) - origin = models.OneToOneField( + origin = models.ForeignKey( 'IpList', on_delete=models.PROTECT, blank=True, diff --git a/machines/serializers.py b/machines/serializers.py index f1888750..42ca679d 100644 --- a/machines/serializers.py +++ b/machines/serializers.py @@ -175,7 +175,7 @@ class ExtensionSerializer(serializers.ModelSerializer): fields = ('name', 'origin', 'origin_v6', 'zone_entry', 'soa') def get_origin_ip(self, obj): - return obj.origin.ipv4 + return getattr(obj.origin, 'ipv4', None) def get_zone_name(self, obj): return str(obj.dns_entry) diff --git a/re2o/templatetags/acl.py b/re2o/templatetags/acl.py index d749b299..0f67169f 100644 --- a/re2o/templatetags/acl.py +++ b/re2o/templatetags/acl.py @@ -127,6 +127,8 @@ MODEL_NAME = { 'ConstructorSwitch' : topologie.models.ConstructorSwitch, 'Port' : topologie.models.Port, 'Room' : topologie.models.Room, + 'Building' : topologie.models.Building, + 'SwitchBay' : topologie.models.SwitchBay, # users 'User' : users.models.User, 'Adherent' : users.models.Adherent, diff --git a/re2o/utils.py b/re2o/utils.py index 8336aab5..3bbfffd4 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -220,10 +220,10 @@ class SortTable: TOPOLOGIE_INDEX = { 'switch_dns': ['interface__domain__name'], 'switch_ip': ['interface__ipv4__ipv4'], - 'switch_loc': ['location'], + 'switch_loc': ['switchbay__name'], 'switch_ports': ['number'], 'switch_stack': ['stack__name'], - 'default': ['location', 'stack', 'stack_member_id'] + 'default': ['switchbay', 'stack', 'stack_member_id'] } TOPOLOGIE_INDEX_PORT = { 'port_port': ['port'], @@ -238,6 +238,10 @@ class SortTable: 'room_name': ['name'], 'default': ['name'] } + TOPOLOGIE_INDEX_BUILDING = { + 'building_name': ['name'], + 'default': ['name'] + } TOPOLOGIE_INDEX_BORNE = { 'ap_name': ['interface__domain__name'], 'ap_ip': ['interface__ipv4__ipv4'], @@ -250,12 +254,17 @@ class SortTable: 'default': ['stack_id'], } TOPOLOGIE_INDEX_MODEL_SWITCH = { - 'model_switch_name': ['reference'], - 'model_switch__contructor' : ['constructor__name'], + 'model-switch_name': ['reference'], + 'model-switch_contructor' : ['constructor__name'], 'default': ['reference'], } + TOPOLOGIE_INDEX_SWITCH_BAY = { + 'switch-bay_name': ['name'], + 'switch-bay_building': ['building__name'], + 'default': ['name'], + } TOPOLOGIE_INDEX_CONSTRUCTOR_SWITCH = { - 'room_name': ['name'], + 'constructor-switch_name': ['name'], 'default': ['name'], } LOGS_INDEX = { diff --git a/re2o/views.py b/re2o/views.py index 991b8702..bd9b18cb 100644 --- a/re2o/views.py +++ b/re2o/views.py @@ -85,6 +85,8 @@ HISTORY_BIND = { 'modelswitch' : topologie.models.ModelSwitch, 'constructorswitch' : topologie.models.ConstructorSwitch, 'accesspoint' : topologie.models.AccessPoint, + 'switchbay' : topologie.models.SwitchBay, + 'building' : topologie.models.Building, }, 'machines' : { 'machine' : machines.models.Machine, diff --git a/topologie/admin.py b/topologie/admin.py index 6c64aec7..62ffd6c4 100644 --- a/topologie/admin.py +++ b/topologie/admin.py @@ -36,7 +36,9 @@ from .models import ( Stack, ModelSwitch, ConstructorSwitch, - AccessPoint + AccessPoint, + SwitchBay, + Building ) @@ -75,6 +77,16 @@ class ConstructorSwitchAdmin(VersionAdmin): pass +class SwitchBayAdmin(VersionAdmin): + """Administration d'une baie de brassage""" + pass + + +class BuildingAdmin(VersionAdmin): + """Administration d'un batiment""" + pass + + admin.site.register(Port, PortAdmin) admin.site.register(AccessPoint, AccessPointAdmin) admin.site.register(Room, RoomAdmin) @@ -82,3 +94,5 @@ admin.site.register(Switch, SwitchAdmin) admin.site.register(Stack, StackAdmin) admin.site.register(ModelSwitch, ModelSwitchAdmin) admin.site.register(ConstructorSwitch, ConstructorSwitchAdmin) +admin.site.register(Building, BuildingAdmin) +admin.site.register(SwitchBay, SwitchBayAdmin) diff --git a/topologie/forms.py b/topologie/forms.py index b8c3d8d1..bb0c2888 100644 --- a/topologie/forms.py +++ b/topologie/forms.py @@ -48,7 +48,9 @@ from .models import ( Stack, ModelSwitch, ConstructorSwitch, - AccessPoint + AccessPoint, + SwitchBay, + Building, ) from re2o.mixins import FormRevMixin @@ -146,7 +148,7 @@ class NewSwitchForm(NewMachineForm): """Permet de créer un switch : emplacement, paramètres machine, membre d'un stack (option), nombre de ports (number)""" class Meta(EditSwitchForm.Meta): - fields = ['name', 'location', 'number', 'stack', 'stack_member_id'] + fields = ['name', 'switchbay', 'number', 'stack', 'stack_member_id'] class EditRoomForm(FormRevMixin, ModelForm): @@ -168,6 +170,8 @@ class CreatePortsForm(forms.Form): class EditModelSwitchForm(FormRevMixin, ModelForm): """Permet d'éediter un modèle de switch : nom et constructeur""" + members = forms.ModelMultipleChoiceField(Switch.objects.all(), required=False) + class Meta: model = ModelSwitch fields = '__all__' @@ -175,6 +179,14 @@ class EditModelSwitchForm(FormRevMixin, ModelForm): def __init__(self, *args, **kwargs): prefix = kwargs.pop('prefix', self.Meta.model.__name__) super(EditModelSwitchForm, self).__init__(*args, prefix=prefix, **kwargs) + instance = kwargs.get('instance', None) + if instance: + self.initial['members'] = Switch.objects.filter(model=instance) + + def save(self, commit=True): + instance = super().save(commit) + instance.switch_set = self.cleaned_data['members'] + return instance class EditConstructorSwitchForm(FormRevMixin, ModelForm): @@ -186,3 +198,35 @@ class EditConstructorSwitchForm(FormRevMixin, ModelForm): def __init__(self, *args, **kwargs): prefix = kwargs.pop('prefix', self.Meta.model.__name__) super(EditConstructorSwitchForm, self).__init__(*args, prefix=prefix, **kwargs) + + +class EditSwitchBayForm(FormRevMixin, ModelForm): + """Permet d'éditer une baie de brassage""" + members = forms.ModelMultipleChoiceField(Switch.objects.all(), required=False) + + class Meta: + model = SwitchBay + fields = '__all__' + + def __init__(self, *args, **kwargs): + prefix = kwargs.pop('prefix', self.Meta.model.__name__) + super(EditSwitchBayForm, self).__init__(*args, prefix=prefix, **kwargs) + instance = kwargs.get('instance', None) + if instance: + self.initial['members'] = Switch.objects.filter(switchbay=instance) + + def save(self, commit=True): + instance = super().save(commit) + instance.switch_set = self.cleaned_data['members'] + return instance + + +class EditBuildingForm(FormRevMixin, ModelForm): + """Permet d'éditer le batiment""" + class Meta: + model = Building + fields = '__all__' + + def __init__(self, *args, **kwargs): + prefix = kwargs.pop('prefix', self.Meta.model.__name__) + super(EditBuildingForm, self).__init__(*args, prefix=prefix, **kwargs) diff --git a/topologie/management/commands/graph_topo.py b/topologie/management/commands/graph_topo.py deleted file mode 100644 index b5d61a80..00000000 --- a/topologie/management/commands/graph_topo.py +++ /dev/null @@ -1,228 +0,0 @@ -# -*- coding: utf-8 -*- -import sys -import json - -import six -from django.conf import settings -from django.core.management.base import BaseCommand, CommandError - -from topologie.management.modelviz import ModelGraph, generate_dot -from django_extensions.management.utils import signalcommand - -try: - import pygraphviz - HAS_PYGRAPHVIZ = True -except ImportError: - HAS_PYGRAPHVIZ = False - -try: - try: - import pydotplus as pydot - except ImportError: - import pydot - HAS_PYDOT = True -except ImportError: - HAS_PYDOT = False - - -class Command(BaseCommand): - help = "Creates a GraphViz dot file for the specified app names. You can pass multiple app names and they will all be combined into a single model. Output is usually directed to a dot file." - - can_import_settings = True - - def __init__(self, *args, **kwargs): - """Allow defaults for arguments to be set in settings.GRAPH_MODELS. - Each argument in self.arguments is a dict where the key is the - space-separated args and the value is our kwarg dict. - The default from settings is keyed as the long arg name with '--' - removed and any '-' replaced by '_'. - """ - self.arguments = { - '--pygraphviz': { - 'action': 'store_true', 'dest': 'pygraphviz', - 'help': 'Use PyGraphViz to generate the image.'}, - - '--pydot': {'action': 'store_true', 'dest': 'pydot', - 'help': 'Use PyDot(Plus) to generate the image.'}, - - '--disable-fields -d': { - 'action': 'store_true', 'dest': 'disable_fields', - 'help': 'Do not show the class member fields'}, - - '--group-models -g': { - 'action': 'store_true', 'dest': 'group_models', - 'help': 'Group models together respective to their ' - 'application'}, - - '--all-applications -a': { - 'action': 'store_true', 'dest': 'all_applications', - 'help': 'Automatically include all applications from ' - 'INSTALLED_APPS'}, - - '--output -o': { - 'action': 'store', 'dest': 'outputfile', - 'help': 'Render output file. Type of output dependend on file ' - 'extensions. Use png or jpg to render graph to image.'}, - - '--layout -l': { - 'action': 'store', 'dest': 'layout', 'default': 'dot', - 'help': 'Layout to be used by GraphViz for visualization. ' - 'Layouts: circo dot fdp neato nop nop1 nop2 twopi'}, - - '--verbose-names -n': { - 'action': 'store_true', 'dest': 'verbose_names', - 'help': 'Use verbose_name of models and fields'}, - - '--language -L': { - 'action': 'store', 'dest': 'language', - 'help': 'Specify language used for verbose_name localization'}, - - '--exclude-columns -x': { - 'action': 'store', 'dest': 'exclude_columns', - 'help': 'Exclude specific column(s) from the graph. ' - 'Can also load exclude list from file.'}, - - '--exclude-models -X': { - 'action': 'store', 'dest': 'exclude_models', - 'help': 'Exclude specific model(s) from the graph. Can also ' - 'load exclude list from file. Wildcards (*) are allowed.'}, - - '--include-models -I': { - 'action': 'store', 'dest': 'include_models', - 'help': 'Restrict the graph to specified models. Wildcards ' - '(*) are allowed.'}, - - '--inheritance -e': { - 'action': 'store_true', 'dest': 'inheritance', 'default': True, - 'help': 'Include inheritance arrows (default)'}, - - '--no-inheritance -E': { - 'action': 'store_false', 'dest': 'inheritance', - 'help': 'Do not include inheritance arrows'}, - - '--hide-relations-from-fields -R': { - 'action': 'store_false', 'dest': 'relations_as_fields', - 'default': True, - 'help': 'Do not show relations as fields in the graph.'}, - - '--disable-sort-fields -S': { - 'action': 'store_false', 'dest': 'sort_fields', - 'default': True, 'help': 'Do not sort fields'}, - - '--json': {'action': 'store_true', 'dest': 'json', - 'help': 'Output graph data as JSON'} - } - - defaults = getattr(settings, 'GRAPH_MODELS', None) - - if defaults: - for argument in self.arguments: - arg_split = argument.split(' ') - setting_opt = arg_split[0].lstrip('-').replace('-', '_') - if setting_opt in defaults: - self.arguments[argument]['default'] = defaults[setting_opt] - - super(Command, self).__init__(*args, **kwargs) - - def add_arguments(self, parser): - """Unpack self.arguments for parser.add_arguments.""" - parser.add_argument('app_label', nargs='*') - for argument in self.arguments: - parser.add_argument(*argument.split(' '), - **self.arguments[argument]) - - @signalcommand - def handle(self, *args, **options): - args = options['app_label'] - if len(args) < 1 and not options['all_applications']: - raise CommandError("need one or more arguments for appname") - - use_pygraphviz = options.get('pygraphviz', False) - use_pydot = options.get('pydot', False) - use_json = options.get('json', False) - if use_json and (use_pydot or use_pygraphviz): - raise CommandError("Cannot specify --json with --pydot or --pygraphviz") - - cli_options = ' '.join(sys.argv[2:]) - graph_models = ModelGraph(args, cli_options=cli_options, **options) - graph_models.generate_graph_data() - graph_data = graph_models.get_graph_data(as_json=use_json) - if use_json: - self.render_output_json(graph_data, **options) - return - - dotdata = generate_dot(graph_data) - if not six.PY3: - dotdata = dotdata.encode('utf-8') - if options['outputfile']: - if not use_pygraphviz and not use_pydot: - if HAS_PYGRAPHVIZ: - use_pygraphviz = True - elif HAS_PYDOT: - use_pydot = True - if use_pygraphviz: - self.render_output_pygraphviz(dotdata, **options) - elif use_pydot: - self.render_output_pydot(dotdata, **options) - else: - raise CommandError("Neither pygraphviz nor pydotplus could be found to generate the image") - else: - self.print_output(dotdata) - - def print_output(self, dotdata): - if six.PY3 and isinstance(dotdata, six.binary_type): - dotdata = dotdata.decode() - - print(dotdata) - - def render_output_json(self, graph_data, **kwargs): - output_file = kwargs.get('outputfile') - if output_file: - with open(output_file, 'wt') as json_output_f: - json.dump(graph_data, json_output_f) - else: - print(json.dumps(graph_data)) - - def render_output_pygraphviz(self, dotdata, **kwargs): - """Renders the image using pygraphviz""" - if not HAS_PYGRAPHVIZ: - raise CommandError("You need to install pygraphviz python module") - - version = pygraphviz.__version__.rstrip("-svn") - try: - if tuple(int(v) for v in version.split('.')) < (0, 36): - # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version) - import tempfile - tmpfile = tempfile.NamedTemporaryFile() - tmpfile.write(dotdata) - tmpfile.seek(0) - dotdata = tmpfile.name - except ValueError: - pass - - graph = pygraphviz.AGraph(dotdata) - graph.layout(prog=kwargs['layout']) - graph.draw(kwargs['outputfile']) - - def render_output_pydot(self, dotdata, **kwargs): - """Renders the image using pydot""" - if not HAS_PYDOT: - raise CommandError("You need to install pydot python module") - - graph = pydot.graph_from_dot_data(dotdata) - if not graph: - raise CommandError("pydot returned an error") - if isinstance(graph, (list, tuple)): - if len(graph) > 1: - sys.stderr.write("Found more then one graph, rendering only the first one.\n") - graph = graph[0] - - output_file = kwargs['outputfile'] - formats = ['bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf', - 'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap', - 'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf', - 'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg', - 'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot'] - ext = output_file[output_file.rfind('.') + 1:] - format = ext if ext in formats else 'raw' - graph.write(output_file, format=format) diff --git a/topologie/management/commands/modelviz.py b/topologie/management/commands/modelviz.py deleted file mode 100644 index 0f01bb4d..00000000 --- a/topologie/management/commands/modelviz.py +++ /dev/null @@ -1,405 +0,0 @@ -# -*- coding: utf-8 -*- -""" -modelviz.py - DOT file generator for Django Models -Based on: - Django model to DOT (Graphviz) converter - by Antonio Cavedoni - Adapted to be used with django-extensions -""" - -import datetime -import os -import re - -import six -from django.apps import apps -from django.db.models.fields.related import ( - ForeignKey, ManyToManyField, OneToOneField, RelatedField, -) -from django.contrib.contenttypes.fields import GenericRelation -from django.template import Context, Template, loader -from django.utils.encoding import force_bytes, force_str -from django.utils.safestring import mark_safe -from django.utils.translation import activate as activate_language - - -__version__ = "1.1" -__license__ = "Python" -__author__ = "Bas van Oostveen ", -__contributors__ = [ - "Antonio Cavedoni " - "Stefano J. Attardi ", - "limodou ", - "Carlo C8E Miron", - "Andre Campos ", - "Justin Findlay ", - "Alexander Houben ", - "Joern Hees ", - "Kevin Cherepski ", - "Jose Tomas Tocino ", - "Adam Dobrawy ", - "Mikkel Munch Mortensen ", - "Andrzej Bistram ", -] - - -def parse_file_or_list(arg): - if not arg: - return [] - if isinstance(arg, (list, tuple, set)): - return arg - if ',' not in arg and os.path.isfile(arg): - return [e.strip() for e in open(arg).readlines()] - return [e.strip() for e in arg.split(',')] - - -class ModelGraph(object): - def __init__(self, app_labels, **kwargs): - self.graphs = [] - self.cli_options = kwargs.get('cli_options', None) - self.disable_fields = kwargs.get('disable_fields', False) - self.include_models = parse_file_or_list( - kwargs.get('include_models', "") - ) - self.all_applications = kwargs.get('all_applications', False) - self.use_subgraph = kwargs.get('group_models', False) - self.verbose_names = kwargs.get('verbose_names', False) - self.inheritance = kwargs.get('inheritance', True) - self.relations_as_fields = kwargs.get("relations_as_fields", True) - self.sort_fields = kwargs.get("sort_fields", True) - self.language = kwargs.get('language', None) - if self.language is not None: - activate_language(self.language) - self.exclude_columns = parse_file_or_list( - kwargs.get('exclude_columns', "") - ) - self.exclude_models = parse_file_or_list( - kwargs.get('exclude_models', "") - ) - if self.all_applications: - self.app_labels = [app.label for app in apps.get_app_configs()] - else: - self.app_labels = app_labels - - def generate_graph_data(self): - self.process_apps() - - nodes = [] - for graph in self.graphs: - nodes.extend([e['name'] for e in graph['models']]) - - for graph in self.graphs: - for model in graph['models']: - for relation in model['relations']: - if relation is not None: - if relation['target'] in nodes: - relation['needs_node'] = False - - def get_graph_data(self, as_json=False): - now = datetime.datetime.now() - graph_data = { - 'created_at': now.strftime("%Y-%m-%d %H:%M"), - 'cli_options': self.cli_options, - 'disable_fields': self.disable_fields, - 'use_subgraph': self.use_subgraph, - } - - if as_json: - graph_data['graphs'] = [context.flatten() for context in self.graphs] - else: - graph_data['graphs'] = self.graphs - - return graph_data - - def add_attributes(self, field, abstract_fields): - if self.verbose_names and field.verbose_name: - label = force_bytes(field.verbose_name) - if label.islower(): - label = label.capitalize() - else: - label = field.name - - t = type(field).__name__ - if isinstance(field, (OneToOneField, ForeignKey)): - remote_field = field.remote_field if hasattr(field, 'remote_field') else field.rel # Remove me after Django 1.8 is unsupported - t += " ({0})".format(remote_field.field_name) - # TODO: ManyToManyField, GenericRelation - - return { - 'name': field.name, - 'label': label, - 'type': t, - 'blank': field.blank, - 'abstract': field in abstract_fields, - 'relation': isinstance(field, RelatedField), - 'primary_key': field.primary_key, - } - - def add_relation(self, field, model, extras=""): - if self.verbose_names and field.verbose_name: - label = force_bytes(field.verbose_name) - if label.islower(): - label = label.capitalize() - else: - label = field.name - - # show related field name - if hasattr(field, 'related_query_name'): - related_query_name = field.related_query_name() - if self.verbose_names and related_query_name.islower(): - related_query_name = related_query_name.replace('_', ' ').capitalize() - label = '{} ({})'.format(label, force_str(related_query_name)) - - # handle self-relationships and lazy-relationships - remote_field = field.remote_field if hasattr(field, 'remote_field') else field.rel # Remove me after Django 1.8 is unsupported - remote_field_model = remote_field.model if hasattr(remote_field, 'model') else remote_field.to # Remove me after Django 1.8 is unsupported - if isinstance(remote_field_model, six.string_types): - if remote_field_model == 'self': - target_model = field.model - else: - if '.' in remote_field_model: - app_label, model_name = remote_field_model.split('.', 1) - else: - app_label = field.model._meta.app_label - model_name = remote_field_model - target_model = apps.get_model(app_label, model_name) - else: - target_model = remote_field_model - - _rel = self.get_relation_context(target_model, field, label, extras) - - if _rel not in model['relations'] and self.use_model(_rel['target']): - return _rel - - def get_abstract_models(self, appmodels): - abstract_models = [] - for appmodel in appmodels: - abstract_models += [abstract_model for abstract_model in - appmodel.__bases__ if - hasattr(abstract_model, '_meta') and - abstract_model._meta.abstract] - abstract_models = list(set(abstract_models)) # remove duplicates - return abstract_models - - def get_app_context(self, app): - return Context({ - 'name': '"%s"' % app.name, - 'app_name': "%s" % app.name, - 'cluster_app_name': "cluster_%s" % app.name.replace(".", "_"), - 'models': [] - }) - - def get_appmodel_attributes(self, appmodel): - if self.relations_as_fields: - attributes = [field for field in appmodel._meta.local_fields] - else: - # Find all the 'real' attributes. Relations are depicted as graph edges instead of attributes - attributes = [field for field in appmodel._meta.local_fields if not - isinstance(field, RelatedField)] - return attributes - - def get_appmodel_abstracts(self, appmodel): - return [abstract_model.__name__ for abstract_model in - appmodel.__bases__ if - hasattr(abstract_model, '_meta') and - abstract_model._meta.abstract] - - def get_appmodel_context(self, appmodel, appmodel_abstracts): - context = { - 'app_name': appmodel.__module__.replace(".", "_"), - 'name': appmodel.__name__, - 'abstracts': appmodel_abstracts, - 'fields': [], - 'relations': [] - } - - if self.verbose_names and appmodel._meta.verbose_name: - context['label'] = force_bytes(appmodel._meta.verbose_name) - else: - context['label'] = context['name'] - - return context - - def get_bases_abstract_fields(self, c): - _abstract_fields = [] - for e in c.__bases__: - if hasattr(e, '_meta') and e._meta.abstract: - _abstract_fields.extend(e._meta.fields) - _abstract_fields.extend(self.get_bases_abstract_fields(e)) - return _abstract_fields - - def get_inheritance_context(self, appmodel, parent): - label = "multi-table" - if parent._meta.abstract: - label = "abstract" - if appmodel._meta.proxy: - label = "proxy" - label += r"\ninheritance" - return { - 'target_app': parent.__module__.replace(".", "_"), - 'target': parent.__name__, - 'type': "inheritance", - 'name': "inheritance", - 'label': label, - 'arrows': '[arrowhead=empty, arrowtail=none, dir=both]', - 'needs_node': True, - } - - def get_models(self, app): - appmodels = list(app.get_models()) - return appmodels - - def get_relation_context(self, target_model, field, label, extras): - return { - 'target_app': target_model.__module__.replace('.', '_'), - 'target': target_model.__name__, - 'type': type(field).__name__, - 'name': field.name, - 'label': label, - 'arrows': extras, - 'needs_node': True - } - - def process_attributes(self, field, model, pk, abstract_fields): - newmodel = model.copy() - if self.skip_field(field) or pk and field == pk: - return newmodel - newmodel['fields'].append(self.add_attributes(field, abstract_fields)) - return newmodel - - def process_apps(self): - for app_label in self.app_labels: - app = apps.get_app_config(app_label) - if not app: - continue - app_graph = self.get_app_context(app) - app_models = self.get_models(app) - abstract_models = self.get_abstract_models(app_models) - app_models = abstract_models + app_models - - for appmodel in app_models: - if not self.use_model(appmodel._meta.object_name): - continue - appmodel_abstracts = self.get_appmodel_abstracts(appmodel) - abstract_fields = self.get_bases_abstract_fields(appmodel) - model = self.get_appmodel_context(appmodel, appmodel_abstracts) - attributes = self.get_appmodel_attributes(appmodel) - - # find primary key and print it first, ignoring implicit id if other pk exists - pk = appmodel._meta.pk - if pk and not appmodel._meta.abstract and pk in attributes: - model['fields'].append(self.add_attributes(pk, abstract_fields)) - - for field in attributes: - model = self.process_attributes(field, model, pk, abstract_fields) - - if self.sort_fields: - model = self.sort_model_fields(model) - - for field in appmodel._meta.local_fields: - model = self.process_local_fields(field, model, abstract_fields) - - for field in appmodel._meta.local_many_to_many: - model = self.process_local_many_to_many(field, model) - - if self.inheritance: - # add inheritance arrows - for parent in appmodel.__bases__: - model = self.process_parent(parent, appmodel, model) - - app_graph['models'].append(model) - if app_graph['models']: - self.graphs.append(app_graph) - - def process_local_fields(self, field, model, abstract_fields): - newmodel = model.copy() - if (field.attname.endswith('_ptr_id') or # excluding field redundant with inheritance relation - field in abstract_fields or # excluding fields inherited from abstract classes. they too show as local_fields - self.skip_field(field)): - return newmodel - if isinstance(field, OneToOneField): - newmodel['relations'].append(self.add_relation(field, newmodel, '[arrowhead=none, arrowtail=none, dir=both]')) - elif isinstance(field, ForeignKey): - newmodel['relations'].append(self.add_relation(field, newmodel, '[arrowhead=none, arrowtail=dot, dir=both]')) - return newmodel - - def process_local_many_to_many(self, field, model): - newmodel = model.copy() - if self.skip_field(field): - return newmodel - if isinstance(field, ManyToManyField): - remote_field = field.remote_field if hasattr(field, 'remote_field') else field.rel # Remove me after Django 1.8 is unsupported - if hasattr(remote_field.through, '_meta') and remote_field.through._meta.auto_created: - newmodel['relations'].append(self.add_relation(field, newmodel, '[arrowhead=dot arrowtail=dot, dir=both]')) - elif isinstance(field, GenericRelation): - newmodel['relations'].append(self.add_relation(field, newmodel, mark_safe('[style="dotted", arrowhead=normal, arrowtail=normal, dir=both]'))) - return newmodel - - def process_parent(self, parent, appmodel, model): - newmodel = model.copy() - if hasattr(parent, "_meta"): # parent is a model - _rel = self.get_inheritance_context(appmodel, parent) - # TODO: seems as if abstract models aren't part of models.getModels, which is why they are printed by this without any attributes. - if _rel not in newmodel['relations'] and self.use_model(_rel['target']): - newmodel['relations'].append(_rel) - return newmodel - - def sort_model_fields(self, model): - newmodel = model.copy() - newmodel['fields'] = sorted(newmodel['fields'], key=lambda field: (not field['primary_key'], not field['relation'], field['label'])) - return newmodel - - def use_model(self, model_name): - """ - Decide whether to use a model, based on the model name and the lists of - models to exclude and include. - """ - # Check against exclude list. - if self.exclude_models: - for model_pattern in self.exclude_models: - model_pattern = '^%s$' % model_pattern.replace('*', '.*') - if re.search(model_pattern, model_name): - return False - # Check against exclude list. - elif self.include_models: - for model_pattern in self.include_models: - model_pattern = '^%s$' % model_pattern.replace('*', '.*') - if re.search(model_pattern, model_name): - return True - # Return `True` if `include_models` is falsey, otherwise return `False`. - return not self.include_models - - def skip_field(self, field): - if self.exclude_columns: - if self.verbose_names and field.verbose_name: - if field.verbose_name in self.exclude_columns: - return True - if field.name in self.exclude_columns: - return True - return False - - -def generate_dot(graph_data, template='django_extensions/graph_models/digraph.dot'): - t = loader.get_template(template) - - if not isinstance(t, Template) and not (hasattr(t, 'template') and isinstance(t.template, Template)): - raise Exception("Default Django template loader isn't used. " - "This can lead to the incorrect template rendering. " - "Please, check the settings.") - - c = Context(graph_data).flatten() - dot = t.render(c) - - return dot - - -def generate_graph_data(*args, **kwargs): - generator = ModelGraph(*args, **kwargs) - generator.generate_graph_data() - return generator.get_graph_data() - - -def use_model(model, include_models, exclude_models): - generator = ModelGraph([], include_models=include_models, exclude_models=exclude_models) - return generator.use_model(model) - diff --git a/topologie/migrations/0056_building_switchbay.py b/topologie/migrations/0056_building_switchbay.py new file mode 100644 index 00000000..3f705263 --- /dev/null +++ b/topologie/migrations/0056_building_switchbay.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.7 on 2018-04-07 17:41 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion +import re2o.mixins + + +class Migration(migrations.Migration): + + dependencies = [ + ('topologie', '0055_auto_20180329_0431'), + ] + + operations = [ + migrations.CreateModel( + name='Building', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ], + options={ + 'permissions': (('view_building', 'Peut voir un objet batiment'),), + }, + bases=(re2o.mixins.AclMixin, re2o.mixins.RevMixin, models.Model), + ), + migrations.CreateModel( + name='SwitchBay', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('info', models.CharField(blank=True, help_text='Informations particulières', max_length=255, null=True)), + ('building', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='topologie.Building')), + ('members', models.ManyToManyField(blank=True, related_name='bay_switches', to='topologie.Switch')), + ], + options={ + 'permissions': (('view_switchbay', 'Peut voir un objet baie de brassage'),), + }, + bases=(re2o.mixins.AclMixin, re2o.mixins.RevMixin, models.Model), + ), + ] diff --git a/topologie/migrations/0057_auto_20180408_0316.py b/topologie/migrations/0057_auto_20180408_0316.py new file mode 100644 index 00000000..e4a0d09b --- /dev/null +++ b/topologie/migrations/0057_auto_20180408_0316.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.7 on 2018-04-08 01:16 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('topologie', '0056_building_switchbay'), + ] + + operations = [ + migrations.RemoveField( + model_name='switchbay', + name='members', + ), + migrations.AddField( + model_name='switch', + name='switchbay', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='topologie.SwitchBay'), + ), + ] diff --git a/topologie/migrations/0058_remove_switch_location.py b/topologie/migrations/0058_remove_switch_location.py new file mode 100644 index 00000000..0d75fc67 --- /dev/null +++ b/topologie/migrations/0058_remove_switch_location.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.7 on 2018-04-08 02:06 +from __future__ import unicode_literals + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('topologie', '0057_auto_20180408_0316'), + ] + + operations = [ + migrations.RemoveField( + model_name='switch', + name='location', + ), + ] diff --git a/topologie/models.py b/topologie/models.py index abbdfa7a..2a42957b 100644 --- a/topologie/models.py +++ b/topologie/models.py @@ -121,7 +121,6 @@ class Switch(AclMixin, Machine): PRETTY_NAME = "Switch / Commutateur" - location = models.CharField(max_length=255) number = models.PositiveIntegerField() stack = models.ForeignKey( 'topologie.Stack', @@ -136,6 +135,12 @@ class Switch(AclMixin, Machine): null=True, on_delete=models.SET_NULL ) + switchbay = models.ForeignKey( + 'topologie.SwitchBay', + blank=True, + null=True, + on_delete=models.SET_NULL + ) class Meta: unique_together = ('stack', 'stack_member_id') @@ -186,8 +191,11 @@ class Switch(AclMixin, Machine): except IntegrityError: ValidationError("Création d'un port existant.") + def main_interface(self): + return self.interface_set.first() + def __str__(self): - return str(self.interface_set.first()) + return str(self.main_interface()) class ModelSwitch(AclMixin, RevMixin, models.Model): @@ -222,6 +230,44 @@ class ConstructorSwitch(AclMixin, RevMixin, models.Model): return self.name +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 + + class Port(AclMixin, RevMixin, models.Model): """ Definition d'un port. Relié à un switch(foreign_key), un port peut etre relié de manière exclusive à : diff --git a/topologie/templates/topologie/aff_building.html b/topologie/templates/topologie/aff_building.html new file mode 100644 index 00000000..878c85e8 --- /dev/null +++ b/topologie/templates/topologie/aff_building.html @@ -0,0 +1,62 @@ +{% comment %} +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. +{% endcomment %} + +{% load acl %} + +{% if building_list.paginator %} +{% include "pagination.html" with list=building_list %} +{% endif %} + + + + + + + + + {% for building in building_list %} + + + + + {% endfor %} +
{% include "buttons/sort.html" with prefix='building' col='name' text='Bâtiment' %}
{{building.name}} + + + + {% can_edit building %} + + + + {% acl_end %} + {% can_delete building %} + + + + {% acl_end %} +
+ +{% if building_list.paginator %} +{% include "pagination.html" with list=building_list %} +{% endif %} diff --git a/topologie/templates/topologie/aff_switch.html b/topologie/templates/topologie/aff_switch.html index bcbe5204..a8547243 100644 --- a/topologie/templates/topologie/aff_switch.html +++ b/topologie/templates/topologie/aff_switch.html @@ -28,12 +28,13 @@ with this program; if not, write to the Free Software Foundation, Inc., {% include "pagination.html" with list=switch_list %} {% endif %} +
- + @@ -50,7 +51,7 @@ with this program; if not, write to the Free Software Foundation, Inc., - + @@ -71,6 +72,7 @@ with this program; if not, write to the Free Software Foundation, Inc., {% endfor %}
{% include "buttons/sort.html" with prefix='switch' col='dns' text='Dns' %} {% include "buttons/sort.html" with prefix='switch' col='ip' text='Ipv4' %}{% include "buttons/sort.html" with prefix='switch' col='loc' text='Localisation' %}{% include "buttons/sort.html" with prefix='switch' col='loc' text='Emplacement' %} {% include "buttons/sort.html" with prefix='switch' col='ports' text='Ports' %} {% include "buttons/sort.html" with prefix='switch' col='stack' text='Stack' %} Id stack {{switch.interface_set.first.ipv4}}{{switch.location}}{{switch.switchbay}} {{switch.number}} {{switch.stack.name}} {{switch.stack_member_id}}
+
{% if switch_list.paginator %} {% include "pagination.html" with list=switch_list %} diff --git a/topologie/templates/topologie/aff_switch_bay.html b/topologie/templates/topologie/aff_switch_bay.html new file mode 100644 index 00000000..e8d11c60 --- /dev/null +++ b/topologie/templates/topologie/aff_switch_bay.html @@ -0,0 +1,68 @@ +{% comment %} +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. +{% endcomment %} + +{% load acl %} + +{% if switch_bay_list.paginator %} +{% include "pagination.html" with list=switch_bay_list %} +{% endif %} + + + + + + + + + + + + {% for switch_bay in switch_bay_list %} + + + + + + + + {% endfor %} +
{% include "buttons/sort.html" with prefix='switch-bay' col='name' text='Baie' %}{% include "buttons/sort.html" with prefix='switch-bay' col='building' text='Bâtiment' %}Info particulièresSwitchs du batiment
{{switch_bay.name}}{{switch_bay.building}}{{switch_bay.info}}{{switch_bay.switch_set.all |join:", "}} + + + + {% can_edit switch_bay %} + + + + {% acl_end %} + {% can_delete switch_bay %} + + + + {% acl_end %} +
+ +{% if switch_bay_list.paginator %} +{% include "pagination.html" with list=switch_bay_list %} +{% endif %} diff --git a/topologie/templates/topologie/index_model_switch.html b/topologie/templates/topologie/index_model_switch.html index e375dd36..19752b2a 100644 --- a/topologie/templates/topologie/index_model_switch.html +++ b/topologie/templates/topologie/index_model_switch.html @@ -41,6 +41,18 @@ with this program; if not, write to the Free Software Foundation, Inc.,
{% acl_end %} {% include "topologie/aff_constructor_switch.html" with constructor_switch_list=constructor_switch_list %} +

Baie de brassage

+{% can_create SwitchBay %} + Ajouter une baie de brassage +
+{% acl_end %} +{% include "topologie/aff_switch_bay.html" with switch_bay_list=switch_bay_list %} +

Batiment

+{% can_create Building %} + Ajouter un bâtiment +
+{% acl_end %} +{% include "topologie/aff_building.html" with building_list=building_list %}


diff --git a/topologie/templates/topologie/topo.html b/topologie/templates/topologie/topo.html index 019625f9..7d1662f0 100644 --- a/topologie/templates/topologie/topo.html +++ b/topologie/templates/topologie/topo.html @@ -36,7 +36,7 @@ with this program; if not, write to the Free Software Foundation, Inc., {% endif %}
{% csrf_token %} - {% massive_bootstrap_form topoform 'room,related,machine_interface' %} + {% massive_bootstrap_form topoform 'room,related,machine_interface,members' %} {% bootstrap_button action_name button_type="submit" icon="ok" %}

diff --git a/topologie/urls.py b/topologie/urls.py index d4b31717..66da7642 100644 --- a/topologie/urls.py +++ b/topologie/urls.py @@ -99,4 +99,24 @@ urlpatterns = [ url(r'^del_constructor_switch/(?P[0-9]+)$', views.del_constructor_switch, name='del-constructor-switch'), + url(r'^new_switch_bay/$', + views.new_switch_bay, + name='new-switch-bay' + ), + url(r'^edit_switch_bay/(?P[0-9]+)$', + views.edit_switch_bay, + name='edit-switch-bay'), + url(r'^del_switch_bay/(?P[0-9]+)$', + views.del_switch_bay, + name='del-switch-bay'), + url(r'^new_building/$', + views.new_building, + name='new-building' + ), + url(r'^edit_building/(?P[0-9]+)$', + views.edit_building, + name='edit-building'), + url(r'^del_building/(?P[0-9]+)$', + views.del_building, + name='del-building'), ] diff --git a/topologie/views.py b/topologie/views.py index 2534c371..51c00aa8 100644 --- a/topologie/views.py +++ b/topologie/views.py @@ -51,7 +51,9 @@ from topologie.models import ( Stack, ModelSwitch, ConstructorSwitch, - AccessPoint + AccessPoint, + SwitchBay, + Building ) from topologie.forms import EditPortForm, NewSwitchForm, EditSwitchForm from topologie.forms import ( @@ -62,7 +64,9 @@ from topologie.forms import ( EditConstructorSwitchForm, CreatePortsForm, AddAccessPointForm, - EditAccessPointForm + EditAccessPointForm, + EditSwitchBayForm, + EditBuildingForm ) from users.views import form from re2o.utils import re2o_paginator, SortTable @@ -200,6 +204,8 @@ def index_model_switch(request): """ Affichage de l'ensemble des modèles de switches""" model_switch_list = ModelSwitch.objects.select_related('constructor') constructor_switch_list = ConstructorSwitch.objects + switch_bay_list = SwitchBay.objects.select_related('building') + building_list = Building.objects.all() model_switch_list = SortTable.sort( model_switch_list, request.GET.get('col'), @@ -212,9 +218,23 @@ def index_model_switch(request): request.GET.get('order'), SortTable.TOPOLOGIE_INDEX_CONSTRUCTOR_SWITCH ) + 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 + ) return render(request, 'topologie/index_model_switch.html', { 'model_switch_list': model_switch_list, 'constructor_switch_list': constructor_switch_list, + 'switch_bay_list': switch_bay_list, + 'building_list' : building_list, }) @@ -635,6 +655,92 @@ def del_model_switch(request, model_switch, modelswitchid): }, 'topologie/delete.html', request) +@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éé") + return redirect(reverse('topologie:index-model-switch')) + return form({'topoform': switch_bay, 'action_name' : 'Ajouter'}, 'topologie/topo.html', request) + + +@login_required +@can_edit(SwitchBay) +def edit_switch_bay(request, switch_bay, switchbayid): + """ 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é") + return redirect(reverse('topologie:index-model-switch')) + return form({'topoform': switch_bay, 'action_name' : 'Editer'}, 'topologie/topo.html', request) + + +@login_required +@can_delete(SwitchBay) +def del_switch_bay(request, switch_bay, switchbayid): + """ 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: + messages.error(request, "La baie %s est affecté à un autre objet,\ + impossible de la supprimer (switch ou user)" % switch_bay) + return redirect(reverse('topologie:index-model-switch')) + return form({ + 'objet': switch_bay, + 'objet_name': 'Baie de switch' + }, 'topologie/delete.html', request) + + +@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éé") + return redirect(reverse('topologie:index-model-switch')) + return form({'topoform': building, 'action_name' : 'Ajouter'}, 'topologie/topo.html', request) + + +@login_required +@can_edit(Building) +def edit_building(request, building, buildingid): + """ 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é") + return redirect(reverse('topologie:index-model-switch')) + return form({'topoform': building, 'action_name' : 'Editer'}, 'topologie/topo.html', request) + + +@login_required +@can_delete(Building) +def del_building(request, building, buildingid): + """ Suppression d'un batiment""" + if request.method == "POST": + try: + building.delete() + messages.success(request, "La batiment a été détruit") + except ProtectedError: + messages.error(request, "Le batiment %s est affecté à un autre objet,\ + impossible de la supprimer (switch ou user)" % building) + return redirect(reverse('topologie:index-model-switch')) + return form({ + 'objet': building, + 'objet_name': 'Bâtiment' + }, 'topologie/delete.html', request) + + @login_required @can_create(ConstructorSwitch) def new_constructor_switch(request):