summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/vyos/template.py10
-rw-r--r--python/vyos/util.py29
2 files changed, 34 insertions, 5 deletions
diff --git a/python/vyos/template.py b/python/vyos/template.py
index 6c73ce753..e4b253ed3 100644
--- a/python/vyos/template.py
+++ b/python/vyos/template.py
@@ -19,6 +19,7 @@ from jinja2 import Environment
from jinja2 import FileSystemLoader
from vyos.defaults import directories
+from vyos.util import chmod, chown, makedir
# reuse the same Environment to improve performance
@@ -32,7 +33,7 @@ _templates_mem = {
}
-def render(destination, template, content, trim_blocks=False, formater=None):
+def render(destination, template, content, trim_blocks=False, formater=None, permission=None, user=None, group=None):
"""
render a template from the template directory, it will raise on any errors
destination: the file where the rendered template must be saved
@@ -46,6 +47,10 @@ def render(destination, template, content, trim_blocks=False, formater=None):
(recovering the load time and overhead caused by having the file out of the code)
"""
+ # Create the directory if it does not exists
+ folder = os.path.dirname(destination)
+ makedir(folder, user, group)
+
# Setup a renderer for the given template
# This is cached and re-used for performance
if template not in _templates_mem[trim_blocks]:
@@ -63,3 +68,6 @@ def render(destination, template, content, trim_blocks=False, formater=None):
# Write client config file
with open(destination, 'w') as f:
f.write(content)
+
+ chmod(destination, permission)
+ chown(destination, user, group)
diff --git a/python/vyos/util.py b/python/vyos/util.py
index 504d36ef8..307decc87 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -213,10 +213,24 @@ def chown(path, user, group):
from pwd import getpwnam
from grp import getgrnam
- if os.path.exists(path):
- uid = getpwnam(user).pw_uid
- gid = getgrnam(group).gr_gid
- os.chown(path, uid, gid)
+ if user is None or group is None:
+ return False
+
+ if not os.path.exists(path):
+ return False
+
+ uid = getpwnam(user).pw_uid
+ gid = getgrnam(group).gr_gid
+ os.chown(path, uid, gid)
+ return True
+
+
+def chmod(path, bitmask):
+ if not os.path.exists(path):
+ return
+ if bitmask is None:
+ return
+ os.chmod(path, bitmask)
def chmod_600(path):
@@ -247,6 +261,13 @@ def chmod_755(path):
os.chmod(path, bitmask)
+def makedir(path, user=None, group=None):
+ if not os.path.exists(path):
+ return
+ os.mkdir(path)
+ chown(path, user, group)
+
+
def colon_separated_to_dict(data_string, uniquekeys=False):
""" Converts a string containing newline-separated entries
of colon-separated key-value pairs into a dict.