Commit 13f6f65e authored by Ad Schellevis's avatar Ad Schellevis

added template engine for new features, including example templates for demonstration purposes.

This shouldn't break any current features and only works after installation of the jinja2 python package.

To test, execute
	./execute_command.py template reload OPNsense.Sample
parent ad276991
[reload]
command:template.reload
parameters:%s
type:inline
message:generate template %s
config:/conf/config.xml
......@@ -2,7 +2,7 @@
"""
Copyright (c) 2014 Ad Schellevis
part of opnSense (https://www.opnsense.org/)
part of OPNsense (https://www.opnsense.org/)
All rights reserved.
......@@ -61,7 +61,11 @@ except socket.error, msg:
# send command and await response
try:
print ('send:%s '%exec_command)
sock.send(exec_command)
print ('response:%s'% sock.recv(4096))
finally:
sock.close()
"""
Copyright (c) 2015 Ad Schellevis
part of OPNsense (https://www.opnsense.org/)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------------
package : check_reload_status
function: config handler
"""
__author__ = 'Ad Schellevis'
import os
import stat
import collections
import copy
import xml.etree.cElementTree as ElementTree
class Config(object):
def __init__(self,filename):
self._filename = filename
self._config_data = {}
self._file_mod = 0
self._load()
def _load(self):
""" load config ( if timestamp is changed )
:return:
"""
mod_time = os.stat(self._filename)[stat.ST_MTIME]
if self._file_mod != mod_time:
xml_node = ElementTree.parse(self._filename)
root = xml_node.getroot()
self._config_data = self._traverse(root)
self._file_mod = mod_time
def _traverse(self,xmlNode):
""" traverse xml node and return ordered dictionary structure
:param xmlNode: ElementTree node
:return: collections.OrderedDict
"""
this_item = collections.OrderedDict()
if len(list(xmlNode)) > 0 :
for item in list(xmlNode):
item_content = self._traverse(item)
if this_item.has_key(item.tag):
if type(this_item[item.tag]) != list:
tmp_item = copy.deepcopy(this_item[item.tag])
this_item[item.tag] = []
this_item[item.tag].append(tmp_item)
if item_content != None:
# skip empty fields
this_item[item.tag].append(item_content)
elif item_content != None:
# create a new named item
this_item[item.tag] = self._traverse(item)
else:
# last node, return text
return xmlNode.text
return this_item
def indent(self,elem, level=0):
""" indent cElementTree (prettyprint fix)
used from : http://infix.se/2007/02/06/gentlemen-indent-your-xml
@param elem: cElementTree
@param level: Currentlevel
"""
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
for e in elem:
self.indent(e, level+1)
if not e.tail or not e.tail.strip():
e.tail = i + " "
if not e.tail or not e.tail.strip():
e.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def get(self):
""" get active config data, load from disc if file in memory is different
:return: dictionary
"""
# refresh config if source xml is changed
self._load()
return self._config_data
\ No newline at end of file
"""
Copyright (c) 2014 Ad Schellevis
part of OPNsense (https://www.opnsense.org/)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------------
package : check_reload_status
function: unix domain socket process worker process
"""
__author__ = 'Ad Schellevis'
import syslog
def execute(action,parameters):
""" wrapper for inline functions
:param action: action object ( processhandler.Action type )
:param parameters: parameter string
:return: status ( string )
"""
if action.command == 'template.reload':
import template
import config
tmpl = template.Template()
conf = config.Config(action.config)
tmpl.setConfig(conf.get())
filenames = tmpl.generate(parameters)
# send generated filenames to syslog
for filename in filenames:
syslog.syslog(syslog.LOG_DEBUG,' %s generated %s' % ( parameters, filename ) )
del conf
del tmpl
return 'OK'
return 'ERR'
\ No newline at end of file
"""
Copyright (c) 2014 Ad Schellevis
part of opnSense (https://www.opnsense.org/)
part of OPNsense (https://www.opnsense.org/)
All rights reserved.
......@@ -43,6 +43,7 @@ import threading
import ConfigParser
import glob
import time
import ph_inline_actions
class Handler(object):
""" Main handler class, opens unix domain socket and starts listening
......@@ -52,7 +53,7 @@ class Handler(object):
processflow:
Handler ( waits for client )
-> new client is send to HandlerClient
-> execute ActionHandler command
-> execute ActionHandler command using Action objects
<- send back result string
"""
def __init__(self,socket_filename,config_path,simulation_mode=False):
......@@ -164,77 +165,6 @@ class HandlerClient(threading.Thread):
finally:
self.connection.close()
class Action(object):
""" Action class, handles actual system calls. set command, parameters (template) type and log message
"""
def __init__(self):
""" setup default properties
:return:
"""
self.command = None
self.parameters = None
self.type = None
self.message = None
self._parameter_start_pos = 0
def setParameterStartPos(self,pos):
"""
:param pos: start position of parameter list
:return: position
"""
self._parameter_start_pos = pos
def getParameterStartPos(self):
""" getter for _parameter_start_pos
:return: start position of parameter list ( first argument can be part of action to start )
"""
return self._parameter_start_pos
def execute(self,parameters):
""" execute an action
:param parameters: list of parameters
:return:
"""
# validate input
if self.type == None:
return 'No action type'
elif self.type.lower() == 'script':
if self.command == None:
return 'No command'
try:
script_command = self.command
if self.parameters != None and type(self.parameters) == str:
script_command = '%s %s'%(script_command,self.parameters)
if script_command.find('%s') > -1 and len(parameters) > 0:
# use command execution parameters in action parameter template
script_command = script_command % tuple(parameters[0:script_command.count('%s')])
# execute script command
if self.message != None:
if self.message.count('%s') > 0 and parameters != None and len(parameters) > 0:
syslog.syslog(syslog.LOG_NOTICE,self.message % tuple(parameters[0:self.message.count('%s')]) )
else:
syslog.syslog(syslog.LOG_NOTICE,self.message)
exit_status = subprocess.call(script_command, shell=True)
except:
print traceback.format_exc()
# todo log traceback on exception
return 'Execute error'
# send response
if exit_status == 0 :
return 'OK'
else:
return 'Error (%d)'%exit_status
return 'Unknown action type'
class ActionHandler(object):
""" Start/stop services and functions using configuration data definced in conf/actions_<topic>.conf
"""
......@@ -330,3 +260,100 @@ class ActionHandler(object):
print ('execute %s.%s with parameters : %s '%(command,action,parameters) )
print ('action object %s (%s)' % (action_obj,action_obj.command) )
print ('---------------------------------------------------------------------')
class Action(object):
""" Action class, handles actual (system) calls.
set command, parameters (template) type and log message
"""
def __init__(self):
""" setup default properties
:return:
"""
self.command = None
self.parameters = None
self.type = None
self.message = None
self._parameter_start_pos = 0
def setParameterStartPos(self,pos):
"""
:param pos: start position of parameter list
:return: position
"""
self._parameter_start_pos = pos
def getParameterStartPos(self):
""" getter for _parameter_start_pos
:return: start position of parameter list ( first argument can be part of action to start )
"""
return self._parameter_start_pos
def execute(self,parameters):
""" execute an action
:param parameters: list of parameters
:return:
"""
# validate input
if self.type == None:
return 'No action type'
elif self.type.lower() == 'script':
#
# script command, execute a shell script and return (simple) status
#
if self.command == None:
return 'No command'
try:
script_command = self.command
if self.parameters != None and type(self.parameters) == str:
script_command = '%s %s'%(script_command,self.parameters)
if script_command.find('%s') > -1 and len(parameters) > 0:
# use command execution parameters in action parameter template
script_command = script_command % tuple(parameters[0:script_command.count('%s')])
# execute script command
if self.message != None:
if self.message.count('%s') > 0 and parameters != None and len(parameters) > 0:
syslog.syslog(syslog.LOG_NOTICE,self.message % tuple(parameters[0:self.message.count('%s')]) )
else:
syslog.syslog(syslog.LOG_NOTICE,self.message)
exit_status = subprocess.call(script_command, shell=True)
except:
syslog.syslog(syslog.LOG_ERR, 'Script action failed at %s'%traceback.format_exc())
return 'Execute error'
# send response
if exit_status == 0 :
return 'OK'
else:
return 'Error (%d)'%exit_status
elif self.type.lower() == 'inline':
# Handle inline service actions
try:
# match parameters, serialize to parameter string defined by action template
if len(parameters) > 0:
inline_act_parameters = self.parameters % tuple(parameters)
else:
inline_act_parameters = ''
# send message to syslog
if self.message != None:
if self.message.count('%s') > 0 and parameters != None and len(parameters) > 0:
syslog.syslog(syslog.LOG_NOTICE,self.message % tuple(parameters[0:self.message.count('%s')]) )
else:
syslog.syslog(syslog.LOG_NOTICE,self.message)
return ph_inline_actions.execute(self,inline_act_parameters)
except:
syslog.syslog(syslog.LOG_ERR, 'Inline action failed at %s'%traceback.format_exc())
return 'Execute error'
return 'Unknown action type'
This diff is collapsed.
name: opnsense-sample
version: 0.1
origin: opnsense/sample
comment: OPNsense configuration template example
desc: creates some files in /tmp/.../ based on reporting definitions found in +TARGETS
maintainer: ad@opnsense.org
www: https://opnsense.org
prefix: /
example_config.txt:/tmp/template_sample/test_[interfaces.%.if]_[version].conf
example_simple_page.txt:/tmp/template_sample/simple_page.txt
\ No newline at end of file
{% extends "/OPNsense/Sample/example_parent.txt" %}
{% block content %}
For demonstration purposes this template is based upon another template in the OPNsense/Sample module.
The block named "content" is replaced with this data
In the +TARGETS file, the name of the output is describes as elements of the config data, because we will receive
all of the config.xml data when rendering this template, we have to filter the parts we need.
For example, only use this interfaces data:
{% for key,item in interfaces.iteritems() %}
{% if TARGET_FILTERS['interfaces.'+key] %}
my interface name is {{ key }}, connected to {{ item.if }} using {{ item.ipaddr }}
{% endif %}
{% endfor %}
{% endblock %}
the parent template
{% block content %}{% endblock %}
This is a very simple example of how to generate configuration files based on templates.
In +TARGETS you can find the mapping between this template and the output it should generate.
Now lets retrieve some configuration data from the OPNsense configuration file:
last change date : {{ lastchange|default('unknown') }}
version according to config.xml : {{ version|default('?') }}
list of configured network interfaces :
{% for key,item in interfaces.iteritems() %}
interface {{ key }}
--- interface {{ item.if }}
--- address {{ item.ipaddr }}
--- subnet {{ item.subnet }}
{% endfor %}
and a short list of firewall rules created (multiple rule items in filter section):
{% for item in filter.rule%}
descr : {{ item.descr }}
type : {{ item.type }}
interface : {{ item.interface }} ( which has ip {{ interfaces[item.interface].ipaddr }} )
{% endfor %}
The full documentation for the template engine can be found at : http://jinja.pocoo.org/docs/dev/templates/
A sample with multiple output files ( for example based on interface ) can be found in the example_config.txt template
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment