Commit f763963c authored by Ad Schellevis's avatar Ad Schellevis Committed by Franco Fichtner

(configd) code style cleanups

(cherry picked from commit 9c84f2b4)
parent 52093041
...@@ -24,12 +24,17 @@ ...@@ -24,12 +24,17 @@
POSSIBILITY OF SUCH DAMAGE. POSSIBILITY OF SUCH DAMAGE.
""" """
def singleton(cls, *args, **kwargs): def singleton(cls, *args, **kwargs):
""" singleton pattern, use ad decorator """ singleton pattern, use ad decorator
:param cls:
""" """
instances = {} instances = {}
# noinspection PyShadowingNames
def getinstance(*args, **kwargs): def getinstance(*args, **kwargs):
if cls not in instances: if cls not in instances:
instances[cls] = cls(*args, **kwargs) instances[cls] = cls(*args, **kwargs)
return instances[cls] return instances[cls]
return getinstance return getinstance
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
from operator import itemgetter from operator import itemgetter
# noinspection PyPep8Naming
class Helpers(object): class Helpers(object):
def __init__(self, template_in_data): def __init__(self, template_in_data):
""" initialize template helpers """ initialize template helpers
...@@ -82,7 +84,7 @@ class Helpers(object): ...@@ -82,7 +84,7 @@ class Helpers(object):
return result return result
else: else:
# resort list by tag # resort list by tag
return sorted(result,key=itemgetter(sortBy)) return sorted(result, key=itemgetter(sortBy))
def getUUIDtag(self, uuid): def getUUIDtag(self, uuid):
""" retrieve tag name of registered uuid, returns __not_found__ if none available """ retrieve tag name of registered uuid, returns __not_found__ if none available
......
...@@ -28,14 +28,14 @@ ...@@ -28,14 +28,14 @@
package : configd package : configd
function: config handler function: config handler
""" """
__author__ = 'Ad Schellevis'
import os import os
import stat import stat
import collections import collections
import copy import copy
import xml.etree.cElementTree as ElementTree import xml.etree.cElementTree as ElementTree
__author__ = 'Ad Schellevis'
class Config(object): class Config(object):
def __init__(self, filename): def __init__(self, filename):
...@@ -62,14 +62,14 @@ class Config(object): ...@@ -62,14 +62,14 @@ class Config(object):
self._config_data['__uuid_tags__'] = self.__uuid_tags self._config_data['__uuid_tags__'] = self.__uuid_tags
self._file_mod = mod_time self._file_mod = mod_time
def _traverse(self, xmlNode): def _traverse(self, xml_node):
""" traverse xml node and return ordered dictionary structure """ traverse xml node and return ordered dictionary structure
:param xmlNode: ElementTree node :param xml_node: ElementTree node
:return: collections.OrderedDict :return: collections.OrderedDict
""" """
this_item = collections.OrderedDict() this_item = collections.OrderedDict()
if len(list(xmlNode)) > 0: if len(list(xml_node)) > 0:
for item in list(xmlNode): for item in list(xml_node):
item_content = self._traverse(item) item_content = self._traverse(item)
if 'uuid' in item.attrib: if 'uuid' in item.attrib:
self.__uuid_data[item.attrib['uuid']] = item_content self.__uuid_data[item.attrib['uuid']] = item_content
...@@ -88,7 +88,7 @@ class Config(object): ...@@ -88,7 +88,7 @@ class Config(object):
this_item[item.tag] = self._traverse(item) this_item[item.tag] = self._traverse(item)
else: else:
# last node, return text # last node, return text
return xmlNode.text return xml_node.text
return this_item return this_item
...@@ -98,14 +98,15 @@ class Config(object): ...@@ -98,14 +98,15 @@ class Config(object):
@param elem: cElementTree @param elem: cElementTree
@param level: Currentlevel @param level: Currentlevel
""" """
i = "\n" + level*" " i = "\n" + level * " "
if len(elem): if len(elem):
if not elem.text or not elem.text.strip(): if not elem.text or not elem.text.strip():
elem.text = i + " " elem.text = i + " "
for e in elem: for e in elem:
self.indent(e, level+1) self.indent(e, level + 1)
if not e.tail or not e.tail.strip(): if not e.tail or not e.tail.strip():
e.tail = i + " " e.tail = i + " "
# noinspection PyUnboundLocalVariable
if not e.tail or not e.tail.strip(): if not e.tail or not e.tail.strip():
e.tail = i e.tail = i
else: else:
......
...@@ -58,6 +58,7 @@ class Daemonize(object): ...@@ -58,6 +58,7 @@ class Daemonize(object):
def sigterm(self, signum, frame): def sigterm(self, signum, frame):
""" """
These actions will be done after SIGTERM. These actions will be done after SIGTERM.
:param frame:
""" """
self.logger.warn("Caught signal %s. Stopping daemon." % signum) self.logger.warn("Caught signal %s. Stopping daemon." % signum)
os.remove(self.pid) os.remove(self.pid)
......
...@@ -48,7 +48,7 @@ def execute(action, parameters): ...@@ -48,7 +48,7 @@ def execute(action, parameters):
# generate template # generate template
tmpl = template.Template(action.root_dir) tmpl = template.Template(action.root_dir)
conf = config.Config(action.config) conf = config.Config(action.config)
tmpl.setConfig(conf.get()) tmpl.set_config(conf.get())
filenames = tmpl.generate(parameters) filenames = tmpl.generate(parameters)
del conf del conf
...@@ -78,7 +78,7 @@ def execute(action, parameters): ...@@ -78,7 +78,7 @@ def execute(action, parameters):
# list all available configd actions # list all available configd actions
from processhandler import ActionHandler from processhandler import ActionHandler
act_handler = ActionHandler() act_handler = ActionHandler()
actions = act_handler.listActions(['message', 'description']) actions = act_handler.list_actions(['message', 'description'])
if unicode(parameters).lower() == 'json': if unicode(parameters).lower() == 'json':
import json import json
......
...@@ -28,9 +28,6 @@ ...@@ -28,9 +28,6 @@
package : configd package : configd
function: template handler, generate configuration files using templates function: template handler, generate configuration files using templates
""" """
__author__ = 'Ad Schellevis'
import os import os
import os.path import os.path
import syslog import syslog
...@@ -40,9 +37,10 @@ import codecs ...@@ -40,9 +37,10 @@ import codecs
import jinja2 import jinja2
import addons.template_helpers import addons.template_helpers
__author__ = 'Ad Schellevis'
class Template(object):
class Template(object):
def __init__(self, target_root_directory="/"): def __init__(self, target_root_directory="/"):
""" constructor """ constructor
:return: :return:
...@@ -54,11 +52,12 @@ class Template(object): ...@@ -54,11 +52,12 @@ class Template(object):
self._target_root_directory = target_root_directory self._target_root_directory = target_root_directory
# setup jinja2 environment # setup jinja2 environment
self._template_dir = os.path.dirname(os.path.abspath(__file__))+'/../templates/' self._template_dir = os.path.dirname(os.path.abspath(__file__)) + '/../templates/'
self._j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(self._template_dir), trim_blocks=True, self._j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(self._template_dir), trim_blocks=True,
extensions=["jinja2.ext.do",]) extensions=["jinja2.ext.do", ])
def _read_manifest(self, filename): @staticmethod
def _read_manifest(filename):
""" """
:param filename: manifest filename (path/+MANIFEST) :param filename: manifest filename (path/+MANIFEST)
...@@ -72,7 +71,8 @@ class Template(object): ...@@ -72,7 +71,8 @@ class Template(object):
return result return result
def _read_targets(self, filename): @staticmethod
def _read_targets(filename):
""" read raw target filename masks """ read raw target filename masks
:param filename: targets filename (path/+TARGETS) :param filename: targets filename (path/+TARGETS)
...@@ -118,18 +118,19 @@ class Template(object): ...@@ -118,18 +118,19 @@ class Template(object):
return result return result
def setConfig(self, config_data): def set_config(self, config_data):
""" set config data """ set config data
:param config_data: config data as dictionary/list structure :param config_data: config data as dictionary/list structure
:return: None :return: None
""" """
if type(config_data) in(dict, collections.OrderedDict): if type(config_data) in (dict, collections.OrderedDict):
self._config = config_data self._config = config_data
else: else:
# no data given, reset # no data given, reset
self._config = {} self._config = {}
def __find_string_tags(self, instr): @staticmethod
def __find_string_tags(instr):
""" """
:param instr: string with optional tags [field.$$] :param instr: string with optional tags [field.$$]
:return: :return:
...@@ -195,7 +196,8 @@ class Template(object): ...@@ -195,7 +196,8 @@ class Template(object):
return result return result
def _create_directory(self, filename): @staticmethod
def _create_directory(filename):
""" create directory """ create directory
:param filename: create path for filename ( if not existing ) :param filename: create path for filename ( if not existing )
:return: None :return: None
...@@ -232,7 +234,7 @@ class Template(object): ...@@ -232,7 +234,7 @@ class Template(object):
result_filenames[new_filename] = copy.deepcopy(result_filenames[filename]) result_filenames[new_filename] = copy.deepcopy(result_filenames[filename])
result_filenames[new_filename][key] = target_filters[target_filter][key] result_filenames[new_filename][key] = target_filters[target_filter][key]
template_filename = '%s/%s'%(module_name.replace('.', '/'), src_template) template_filename = '%s/%s' % (module_name.replace('.', '/'), src_template)
# parse template, make sure issues can be traced back to their origin # parse template, make sure issues can be traced back to their origin
try: try:
j2_page = self._j2_env.get_template(template_filename) j2_page = self._j2_env.get_template(template_filename)
...@@ -269,8 +271,8 @@ class Template(object): ...@@ -269,8 +271,8 @@ class Template(object):
# it was in the original template. # it was in the original template.
# It looks like Jinja sometimes isn't consistent on placing this last end-of-line in. # It looks like Jinja sometimes isn't consistent on placing this last end-of-line in.
if len(content) > 1 and content[-1] != '\n': if len(content) > 1 and content[-1] != '\n':
src_file = '%s%s'%(self._template_dir,template_filename) src_file = '%s%s' % (self._template_dir, template_filename)
src_file_handle = open(src_file,'r') src_file_handle = open(src_file, 'r')
src_file_handle.seek(-1, os.SEEK_END) src_file_handle.seek(-1, os.SEEK_END)
last_bytes_template = src_file_handle.read() last_bytes_template = src_file_handle.read()
src_file_handle.close() src_file_handle.close()
...@@ -299,7 +301,7 @@ class Template(object): ...@@ -299,7 +301,7 @@ class Template(object):
# direct match # direct match
do_generate = True do_generate = True
elif wildcard_pos == -1 and len(module_name) < len(template_name) \ elif wildcard_pos == -1 and len(module_name) < len(template_name) \
and '%s.'%module_name == template_name[0:len(module_name)+1]: and '%s.' % module_name == template_name[0:len(module_name) + 1]:
# match child item # match child item
do_generate = True do_generate = True
......
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