[Dev OpenGP] [102] daemon still in progress

[ Thread Index | Date Index | More opengp.tuxfamily.org/development Archives ]


Revision: 102
Author:   nicolaf
Date:     2009-03-26 14:31:19 +0100 (Thu, 26 Mar 2009)

Log Message:
-----------
daemon still in progress

Modified Paths:
--------------
    trunk/src/bin/ogpdaemon
    trunk/src/lib/ogp/core/__init__.py
    trunk/src/lib/ogp/core/ogpcore.py
    trunk/src/lib/ogp/etree/__init__.py
    trunk/src/lib/ogp/misc/__init__.py
    trunk/src/lib/ogp/plugins/ogpdaemon/ogpdaemon.py


Modified: trunk/src/bin/ogpdaemon
===================================================================
--- trunk/src/bin/ogpdaemon	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/bin/ogpdaemon	2009-03-26 13:31:19 UTC (rev 102)
@@ -1,33 +1,194 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*
 
+import logging
 from ogp.core import *
-from ogp.plugins import *
-import logging
+import sys
+from getopt import getopt
+import re
+from time import sleep
 
-uri = "ldap://localhost:389";
-userDn = "cn=admin,dc=ogp"
-passwd = "toor"
-dn='cn=mac1,ou=titi,ou=tutu,dc=ogp'
+LOG_FILE = '/var/log/ogpdaemon.log'
+CONF_FILE = '/etc/ogpdaemon.conf'
+SOAS_FILE = '/etc/ogpdaemon.soas'
+CONF_REGEXP='^(?P<key>([a-zA-Z]\w*))\s*=\s?(?P<value>(.*))$'
+SOAS_REGEXP='^(?P<key>([^\s]*))\s*=\s?(?P<value>(.*))$'
+LOCAL_PARAMETERS = ['uri', 'dn', 'passwd']
 
-logging.basicConfig(filename='/home/nico/log.log', level=logging.DEBUG,format='%(asctime)s %(levelname)-8s %(message)s')
-# Connection
-core = OgpCore(uri, userDn, passwd)
+def checkSOAs():
+	"""
+		Checks if a conf update is needed by comparing local and remote SOAs.
+		Returns False and stores new SOAs if an update is needed.
+	"""
+	oldSOAs={}
+	try:
+		f = open(SOAS_FILE, 'r')
+		p=re.compile(SOAS_REGEXP)
+		for l in f.readlines():
+			c = p.findall(l)
+			try:
+				key = c[0][0]
+				val = c[0][2]
+				oldSOAs[key] = int(val)
+			except:
+				pass
+		f.close()
+	except:
+		pass
+	
+	currentSOAs = core.pullSOAs(dn)
+	print oldSOAs
+	print currentSOAs
+	if currentSOAs != oldSOAs:
+		f = open(SOAS_FILE, 'w')
+		lines = []
+		for k in currentSOAs:
+			lines.append( "%s = %s\n" % (k, currentSOAs[k]))
+		f.writelines(lines)
+		f.close()
+		return False
+	else:
+		return True
 
+def parse_opts():
+	"""
+		Parses CL options and returns (loglevel, reload)
+	"""
+	try:
+		opts = getopt(sys.argv[1:], 'vrh', ['verbose', 'reload-conf', 'help'])[0]
+	except:
+		usage()
+		sys.exit(2)
+	loglevels=[logging.WARNING, logging.INFO, logging.DEBUG]
+	
+	loglevel=0
+	reload=False
 
+	for o in opts:
+		opt = o[0]
+		if opt in ['-h', '--help']:
+			usage()
+			sys.exit()
+		elif opt in ['-v', '--verbose']:
+				loglevel = loglevel + 1
+		elif opt in ['-r', '--reload-conf']:
+			reload = True
+		
+	if loglevel > 2:
+		loglevel = 2
+	return (reload, loglevels[loglevel])	
 
-requiredPlugins=core.getRequiredPlugins(dn)
-for pluginName in requiredPlugins:
-	if pluginName != 'ogpdaemon':
-		print "Installing conf for plugin '" + pluginName + "'...",
+def usage():
+	"""
+		Prints available CL options
+	"""
+	print "Usage: %s [ -h | --help] [ -r | --reload-conf ] [ -v | --verbose]" % sys.argv[0]
+	print "  -h | --help        : print this and stop."
+	print "  -r | --reload-conf : do not run as daemon, just reload configuration."
+	print "  -v | --verbose     : increase log verbosity."
+	quit()
+
+def load_conf():
+	"""
+		Reads conf from local file
+	"""
+	conf={}
+	p=re.compile(CONF_REGEXP)
+	f=open(CONF_FILE, 'r')
+	for l in f.readlines():
+		c = p.findall(l)
 		try:
-			pluginClass = Plugin.getPluginFromName(pluginName)
-			pluginInstance = pluginClass(dn)
-			pluginInstance.installConf()
-			print "\033[0;32mOK\033[0m."
-		except KeyError:
-			print "\033[0;31mfailed\033[0m. Plugin '" + pluginName + "' is missing!"
+			key = c[0][0]
+			val = c[0][2]
+			conf[key] = val
 		except:
-			print "\033[0;31mfailed\033[0m. Something went wrong!"
-		
+			pass
+	f.close()
+	return conf
 
+def save_conf(conf):
+	f = open(CONF_FILE, 'w')
+	lines = []
+	for k in conf:
+		if k in LOCAL_PARAMETERS:
+			lines.append( "%-6s = %s\n" % (k, conf[k]))
+	f.writelines(lines)
+	f.close()
+
+def installConf(core):
+	# if SOAS didnt change, do't do anything
+	print checkSOAs()
+	if not checkSOAs():
+		logging.info("SOAs didn't change, so skipping configuration installation.")
+		return
+	
+	requiredPlugins=core.getRequiredPlugins(dn)
+	for pluginName in requiredPlugins:
+		if pluginName != 'ogpdaemon':
+			print "Installing conf for plugin '" + pluginName + "'...",
+			try:
+				pluginClass = Plugin.getPluginFromName(pluginName)
+				pluginInstance = pluginClass(dn)
+				pluginInstance.installConf()
+				print "\033[0;32mOK\033[0m."
+				logging.info('Configuration installation for plugin %s successful.' % pluginName)
+			except KeyError:
+				print "\033[0;31mfailed\033[0m. Plugin '" + pluginName + "' is missing!"
+				logging.warning('Configuration installation for plugin %s failed. Plugin is missing!' % pluginName)
+			except:
+				print "\033[0;31mfailed\033[0m with %s." % sys.exc_info()[1]
+				logging.warning('Configuration installation for plugin %s failed with %s.' % (pluginName, sys.exc_info()[1]))
+						
+
+#getting options from command line
+(reload, loglevel) = parse_opts()
+
+#setting up logging
+logging.basicConfig(filename=LOG_FILE, level=loglevel, format='%(asctime)s %(levelname)-8s %(message)s')
+
+#getting local conf
+conf = load_conf()
+
+# Connection
+core = OgpCore(conf['uri'], conf['dn'], conf['passwd'])
+
+#loading plugins
+#should be done AFTER logging configuration
+from ogp.plugins import *
+
+#getting remote conf
+OgpDaemon  = Plugin.getPluginFromName('ogpdaemon')
+ogpdaemon  = OgpDaemon(conf['dn'])
+remoteConf = ogpdaemon.installConf()
+totalConf = conf.copy()
+for k in remoteConf:
+		totalConf[k] = remoteConf[k]
+
+#if remoteConf overrides uri, dn or passwd, save conf and reinitialize core
+for k in LOCAL_PARAMETERS:
+	if conf[k] != totalConf[k]:
+		save_conf(totalConf)
+		del core
+		core = OgpCore(totalConf['uri'], totalConf['dn'], totalConf['passwd'])
+		break
+
+conf = totalConf
+
+uri = conf['uri']
+dn = conf['dn']
+passwd = conf['passwd']
+updateOnStartup = bool(conf['updateOnStartup'])
+timeBetweenUpdates = int(conf['timeBetweenUpdates']) * 60
+
+if not updateOnStartup and not reload:
+	print "OGP Daemon has been disabled by remote configuration."
+	print "Run with --reload-conf to force"
+	logging.info("OGP Daemon has been disabled by remote configuration.")
+	exit(0)
+
+if reload:
+	installConf(core)
+else:
+	while True:
+		installConf(core)
+		sleep(timeBetweenUpdates)

Modified: trunk/src/lib/ogp/core/__init__.py
===================================================================
--- trunk/src/lib/ogp/core/__init__.py	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/lib/ogp/core/__init__.py	2009-03-26 13:31:19 UTC (rev 102)
@@ -3,6 +3,6 @@
 
 from ogpcore import *
 from ogpldapconsts import *
-import logging
+#import logging
 
-logging.debug('Loaded ogp.core.')
+#logging.debug('Loaded ogp.core.')

Modified: trunk/src/lib/ogp/core/ogpcore.py
===================================================================
--- trunk/src/lib/ogp/core/ogpcore.py	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/lib/ogp/core/ogpcore.py	2009-03-26 13:31:19 UTC (rev 102)
@@ -55,6 +55,10 @@
 		# Delegate access to implementation
 		return setattr(self.__instance, attr, value)
 
+	def __del__(self):
+		logging.debug('OgpCore.__del__()')
+		OgpCore.__instance = None
+
 	def getInstance():
 		"""
 			Returns the core unique instance
@@ -226,9 +230,9 @@
 				pluginConf: a XML tree reprensenting the XML configuration. Its root must be <plugin name="[pluginName]">
 			"""
 			logging.debug('OgpCore.__ogpcore.pushPluginConf(dn=' + repr(dn) + 'pluginConf=' + pluginConf.toString() + ')')
-			logging.info('OgpCore: pushing conf for plugin ' + pluginName + ' on ' + repr(dn) + '.')
 			#replace current <plugin name="..." /> entry
 			pluginName = pluginConf.get(OgpXmlConsts.ATTR_PLUGIN_NAME)
+			logging.info('OgpCore: pushing conf for plugin ' + pluginName + ' on ' + repr(dn) + '.')
 			currentConf = self.__pullConf(dn)
 			for p in currentConf:
 				if p.get(OgpXmlConsts.ATTR_PLUGIN_NAME) == pluginName:
@@ -316,6 +320,9 @@
 			logging.debug('OgpCore.__ogpcore.__pullConf(dn=' + repr(dn) + ')')
 			try:
 				return fromstring(self.pullAttributes(dn,[OgpLDAPConsts.ATTR_CONFIG])[OgpLDAPConsts.ATTR_CONFIG][0], OGP_PARSER)
+			except KeyError:
+				logging.info('OgpCore: no conf at dn=%s' % repr(dn))
+				return None
 			except:
 				logging.error('OgpCore: __pullConf failed with ' + repr(sys.exc_info()[1]) + '.')
 				raise
@@ -324,6 +331,9 @@
 			logging.debug('OgpCore.__ogpcore.__pullSOA(dn=' + repr(dn) + ')')
 			try:
 				return int(self.pullAttributes(dn, [OgpLDAPConsts.ATTR_OGPSOA])[OgpLDAPConsts.ATTR_OGPSOA][0])
+			except KeyError:
+				logging.info('OgpCore: no conf at dn=%s' % repr(dn))
+				return None
 			except:
 				logging.error('OgpCore: __pullSOA failed with ' + repr(sys.exc_info()[1]) + '.')
 				raise

Modified: trunk/src/lib/ogp/etree/__init__.py
===================================================================
--- trunk/src/lib/ogp/etree/__init__.py	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/lib/ogp/etree/__init__.py	2009-03-26 13:31:19 UTC (rev 102)
@@ -4,7 +4,7 @@
 from lxml.etree import *
 from elementmethods  import *
 from ogpxmlconsts import *
-import logging
+#import logging
 
 def parse(source, parser=None):
 	if not hasattr(source, "read"):
@@ -22,4 +22,4 @@
 OGP_PARSER.set_element_class_lookup(ElementDefaultClassLookup(element=OgpElement))
 Element = OGP_PARSER.makeelement
 
-logging.debug('Loaded ogp.etree.')
+#logging.debug('Loaded ogp.etree.')

Modified: trunk/src/lib/ogp/misc/__init__.py
===================================================================
--- trunk/src/lib/ogp/misc/__init__.py	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/lib/ogp/misc/__init__.py	2009-03-26 13:31:19 UTC (rev 102)
@@ -6,4 +6,4 @@
 		return s
 	else:
 		s = str(s).strip().lower()
-		return not s in ['false','f','n','0','']
+		return not s in ['false','f','n','no','0','']

Modified: trunk/src/lib/ogp/plugins/ogpdaemon/ogpdaemon.py
===================================================================
--- trunk/src/lib/ogp/plugins/ogpdaemon/ogpdaemon.py	2009-03-26 13:25:10 UTC (rev 101)
+++ trunk/src/lib/ogp/plugins/ogpdaemon/ogpdaemon.py	2009-03-26 13:31:19 UTC (rev 102)
@@ -52,13 +52,16 @@
 		logging.debug('OgpDaemon.installConf()')
 		logging.info('OgpDaemon: retrieving conf.')
 
-		local = {}
-		remote = {}
+		conf = {}
+		#local params should not be returned if not set
 		for p in self.__localParams:
-			local[p] = self.__getParam(p, True)
+			c = self.__getParam(p, True)
+			if c is not None:
+				conf[p] = c
+		#remote param should be returned as default if not set
 		for p in self.__remoteParams:
-			remote[p] = self.__getParam(p, True)
-		return {'local':local,'remote':remote}
+			conf[p] = self.__getParam(p, True)
+		return conf
 
 	def __getParam(self, param, fullTree=False):
 		logging.debug('OgpDaemon.__getParam(param=' + repr(param) + ', fullTree=' + repr(fullTree) + ')')


Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/