Skip to content
This repository has been archived by the owner on Jul 9, 2020. It is now read-only.

Commit

Permalink
Merge 2c011d1 into ff7065f
Browse files Browse the repository at this point in the history
  • Loading branch information
NoumbissiValere committed Jun 11, 2020
2 parents ff7065f + 2c011d1 commit c5b3e37
Show file tree
Hide file tree
Showing 11 changed files with 821 additions and 618 deletions.
34 changes: 34 additions & 0 deletions README.rst
Expand Up @@ -50,6 +50,40 @@ Current features
* **template tags**: tag templates to automate different types of auto-configurations (eg: mesh, WDS, 4G)
* **simple HTTP resources**: allow devices to automatically download configuration updates
* **VPN management**: easily create VPN servers and clients
* **Template variables**: makes it possible to declare context (configuration variables) in template configuration while setting the default values for these declared context in the default values field to bypass validation.

we can create a configuration in advanced mode with the following:

.. code-block:: python
{
"interfaces": [
{
"type": "ethernet",
"name": "eth1",
"mtu": 1500,
"mac": "{{mac}}",
"autostart": true,
"disabled": false,
"addresses": [],
"network": ""
}
]
}
with the configuration above, we will need to set our default values field with the following
json value specifying a default value for the `{{mac}}` variable.

.. code-block:: python
{
"mac": "00:0a:95:9d:68:17"
}
**note**: the following condition must be met for us to pass the validation:
- default_values must be a valid json
- values in default_values must be correctly set in JSON format
- default values must be set for all declared variables.

Project goals
-------------
Expand Down
1 change: 1 addition & 0 deletions django_netjsonconfig/base/admin.py
Expand Up @@ -370,6 +370,7 @@ class AbstractTemplateAdmin(BaseConfigAdmin):
'vpn',
'auto_cert',
'tags',
'default_values',
'default',
'config',
'created',
Expand Down
10 changes: 8 additions & 2 deletions django_netjsonconfig/base/base.py
Expand Up @@ -148,15 +148,21 @@ def get_backend_instance(self, template_instances=None):
"""
backend = self.backend_class
kwargs = {'config': self.get_config()}
context = {}
# determine if we can pass templates
# expecting a many2many relationship
if hasattr(self, 'templates'):
if template_instances is None:
template_instances = self.templates.all()
kwargs['templates'] = [t.config for t in template_instances]
templates_list = list()
for t in template_instances:
templates_list.append(t.config)
context.update(t.get_context())
kwargs['templates'] = templates_list
# pass context to backend if get_context method is defined
if hasattr(self, 'get_context'):
kwargs['context'] = self.get_context()
context.update(self.get_context())
kwargs['context'] = context
backend_instance = backend(**kwargs)
# remove accidentally duplicated files when combining config and templates
# this may happen if a device uses multiple VPN client templates
Expand Down
28 changes: 21 additions & 7 deletions django_netjsonconfig/base/template.py
@@ -1,10 +1,12 @@
from collections import OrderedDict
from copy import copy

from django.contrib.admin.models import ADDITION, LogEntry
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from taggit.managers import TaggableManager

from ..settings import DEFAULT_AUTO_CERT
Expand Down Expand Up @@ -73,6 +75,19 @@ class AbstractTemplate(BaseConfig):
'valid only for the VPN type'
),
)
default_values = JSONField(
_('Default Values'),
default=dict,
blank=True,
help_text=_(
'A dictionary containing the default '
'values for the variables used by this '
'template; these default variables will '
'be used during schema validation.'
),
load_kwargs={'object_pairs_hook': OrderedDict},
dump_kwargs={'indent': 4},
)
__template__ = True

class Meta:
Expand Down Expand Up @@ -114,7 +129,6 @@ def clean(self, *args, **kwargs):
* clears VPN specific fields if type is not VPN
* automatically determines configuration if necessary
"""
super().clean(*args, **kwargs)
if self.type == 'vpn' and not self.vpn:
raise ValidationError(
{'vpn': _('A VPN must be selected when template type is "VPN"')}
Expand All @@ -124,14 +138,14 @@ def clean(self, *args, **kwargs):
self.auto_cert = False
if self.type == 'vpn' and not self.config:
self.config = self.vpn.auto_client(auto_cert=self.auto_cert)
super().clean(*args, **kwargs)

def get_context(self):
c = {
'id': str(self.id),
'name': self.name,
}
c.update(super().get_context())
return c
context = {}
if self.default_values:
context = copy(self.default_values)
context.update(super().get_context())
return context

def clone(self, user):
clone = copy(self)
Expand Down
27 changes: 27 additions & 0 deletions django_netjsonconfig/migrations/0044_template_default_values.py
@@ -0,0 +1,27 @@
# Generated by Django 3.0.4 on 2020-04-08 23:46

import collections
from django.db import migrations
import jsonfield.fields


class Migration(migrations.Migration):

dependencies = [
('django_netjsonconfig', '0043_add_indexes_on_ip_fields'),
]

operations = [
migrations.AddField(
model_name='template',
name='default_values',
field=jsonfield.fields.JSONField(
blank=True,
default=dict,
dump_kwargs={'ensure_ascii': False, 'indent': 4},
help_text='A dictionary containing the default values for the variables used by this template; these default variables will be used during schema validation.',
load_kwargs={'object_pairs_hook': collections.OrderedDict},
verbose_name='Default Values',
),
),
]

0 comments on commit c5b3e37

Please sign in to comment.