From 7e170a8b7466cc8bd6c3a926a6be19abc569a045 Mon Sep 17 00:00:00 2001 From: Benjamin Bertrand <benjamin.bertrand@esss.se> Date: Tue, 19 Dec 2017 08:50:46 +0100 Subject: [PATCH] Remove gateway from the network table A gateway should be an interface like any other IP. Use tag to identify it. --- app/models.py | 9 +++++++-- app/network/forms.py | 14 +++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/models.py b/app/models.py index e42df9f..2a64759 100644 --- a/app/models.py +++ b/app/models.py @@ -325,7 +325,6 @@ class Network(db.Model): address = db.Column(postgresql.CIDR, nullable=False, unique=True) first_ip = db.Column(postgresql.INET, nullable=False, unique=True) last_ip = db.Column(postgresql.INET, nullable=False, unique=True) - gateway = db.Column(postgresql.INET) description = db.Column(db.Text) admin_only = db.Column(db.Boolean, nullable=False, default=False) scope_id = db.Column(db.Integer, db.ForeignKey('network_scope.id'), nullable=False) @@ -380,6 +379,13 @@ class Network(db.Model): return [addr for addr in self.ip_range() if addr not in self.used_ips()] + def gateway(self): + """Return the network gateway""" + for interface in self.interfaces: + if 'gateway' in [tag.name for tag in interface.tags]: + return interface + return None + @staticmethod def ip_in_network(ip, address): """Ensure the IP is in the network @@ -432,7 +438,6 @@ class Network(db.Model): 'address': self.address, 'first_ip': self.first_ip, 'last_ip': self.last_ip, - 'gateway': self.gateway, 'vlan_id': self.vlan_id, 'description': self.description, 'admin_only': self.admin_only, diff --git a/app/network/forms.py b/app/network/forms.py index 443cb88..dc750f6 100644 --- a/app/network/forms.py +++ b/app/network/forms.py @@ -15,6 +15,17 @@ from wtforms import (SelectField, StringField, TextAreaField, from .. import utils, models +def validate_tags(form, field): + choices = dict(field.choices) + for tag_id in field.data: + tag_name = choices.get(tag_id) + if tag_name == 'gateway': + network = models.Network.query.get(form.network_id.data) + existing_gateway = network.gateway() + if existing_gateway is not None: + raise validators.ValidationError(f'A gateway is already defined for network {network}: {existing_gateway}') + + class NoValidateSelectField(SelectField): """SelectField with no choices validation @@ -65,7 +76,8 @@ class HostForm(FlaskForm): validators=[validators.InputRequired(), validators.Regexp(models.HOST_NAME_RE)], filters=[utils.lowercase_field]) mac_id = SelectField('MAC', coerce=utils.coerce_to_str_or_none) - tags = SelectMultipleField('Tags', coerce=utils.coerce_to_str_or_none) + tags = SelectMultipleField('Tags', coerce=utils.coerce_to_str_or_none, + validators=[validate_tags]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) -- GitLab