policy request and response handler implemented, dbmservice minor bugs were fixed

This commit is contained in:
Volkan Şahin 2016-03-17 17:55:27 +02:00
parent 656c6aab36
commit 77bce1f98f
4 changed files with 139 additions and 13 deletions

View file

@ -1,6 +1,7 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com> # Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
from base.Scope import Scope from base.Scope import Scope
import sqlite3 import sqlite3
@ -42,15 +43,13 @@ class AhenkDbService(object):
cols = ', '.join([str(x) for x in cols]) cols = ', '.join([str(x) for x in cols])
params = ', '.join(["?" for x in args]) params = ', '.join(["?" for x in args])
sql = "INSERT INTO "+table_name+" ("+cols+") VALUES ("+params+")" sql = "INSERT INTO "+table_name+" ("+cols+") VALUES ("+params+")"
self.cursor.execute(sql, tuple(args))
else: else:
update_list = "" update_list = ""
params = ', '.join(["?" for x in args]) params = ', '.join(["?" for x in args])
for index in range(len(cols)): for index in range(len(cols)):
update_list = update_list + " " + cols[index] +" = ?," update_list = update_list + " " + cols[index] +" = ?,"
update_list = update_list.strip(',') update_list = update_list.strip(',')
sql = "UPDATE "+table_name+" SET " + update_list + " " + criteria sql = "UPDATE "+table_name+" SET " + update_list + " where " + criteria
self.cursor.execute(sql, tuple(args)) self.cursor.execute(sql, tuple(args))
self.connection.commit() self.connection.commit()
else: else:
@ -58,8 +57,11 @@ class AhenkDbService(object):
except Exception as e: except Exception as e:
self.logger.error("Updating table error ! Table Name : " + str(table_name) + " " + str(e)) self.logger.error("Updating table error ! Table Name : " + str(table_name) + " " + str(e))
def delete(self): def delete(self,table_name,criteria):
sql = "DELETE FROM " + table_name + str(criteria) if self.cursor:
sql = "DELETE FROM " + table_name
if criteria:
sql+=' where '+str(criteria)
self.cursor.execute(sql) self.cursor.execute(sql)
self.connection.commit() self.connection.commit()
@ -71,7 +73,14 @@ class AhenkDbService(object):
try: try:
if not cols == "*": if not cols == "*":
cols = ', '.join([str(x) for x in cols]) cols = ', '.join([str(x) for x in cols])
sql = "SELECT "+cols+" FROM " + table_name + " where 1=1 and " + str(criteria) + " " + orderby sql = "SELECT "+cols+" FROM " + table_name
if criteria != "":
sql+=' where '
sql+=criteria
if orderby != "":
sql+=' order by '
sql+=orderby
self.cursor.execute(sql) self.cursor.execute(sql)
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
return rows return rows

View file

@ -6,6 +6,7 @@ import subprocess
from base.Scope import Scope from base.Scope import Scope
from base.messaging.MessageSender import MessageSender from base.messaging.MessageSender import MessageSender
from base.model.Task import Task from base.model.Task import Task
from base.model.Policy import Policy
import hashlib,json,os,stat,shutil import hashlib,json,os,stat,shutil
class ExecutionManager(object): class ExecutionManager(object):
@ -19,11 +20,65 @@ class ExecutionManager(object):
self.event_manager = scope.getEventManager() self.event_manager = scope.getEventManager()
self.task_manager = scope.getTaskManager() self.task_manager = scope.getTaskManager()
self.logger=scope.getLogger() self.logger=scope.getLogger()
self.db_service=scope.getDbService()
self.event_manager.register_event('EXECUTE_SCRIPT',self.execute_script) self.event_manager.register_event('EXECUTE_SCRIPT',self.execute_script)
self.event_manager.register_event('REQUEST_FILE',self.request_file) self.event_manager.register_event('REQUEST_FILE',self.request_file)
self.event_manager.register_event('MOVE_FILE',self.move_file) self.event_manager.register_event('MOVE_FILE',self.move_file)
self.event_manager.register_event('TASK',self.add_task) self.event_manager.register_event('TASK',self.add_task)
self.event_manager.register_event('POLICY',self.update_policies)
def update_policies(self,arg):
print("updating policies...")
policy = Policy(json.loads(arg))
#TODO get username from pam
username='volkan'
ahenk_policy_ver=self.db_service.select('policy',['version'],'type = \'A\'')
user_policy_version=self.db_service.select('policy',['version'],'type = \'U\' and name = \''+username+'\'')
installed_plugins=self.get_installed_plugins()
missing_plugins=[]
if policy.ahenk_policy_version != ahenk_policy_ver[0][0]:
ahenk_policy_id=self.db_service.select('policy',['id'],'type = \'A\'')
self.db_service.delete('profile','id='+str(ahenk_policy_id[0][0]))
self.db_service.update('policy',['version'],[str(policy.ahenk_policy_version)],'type=\'A\'')
for profile in policy.ahenk_profiles:
profile_columns=['id','label','description','is_overridable','is_active','profile_data','modify_date']
args=[str(ahenk_policy_id[0][0]),str(profile.label),str(profile.description),str(profile.is_overridable),str(profile.is_active),str(profile.profile_data),str(profile.modify_date)]
self.db_service.update('profile',profile_columns,args)
if profile.plugin.name not in installed_plugins and profile.plugin.name not in missing_plugins:
missing_plugins.append(profile.plugin.name)
else:
print("already there ahenk policy")
if policy.user_policy_version != user_policy_version[0][0]:
user_policy_id=self.db_service.select('policy',['id'],'type = \'U\' and name=\''+username+'\'')
self.db_service.delete('profile','id='+str(user_policy_id[0][0]))
self.db_service.update('policy',['version'],[str(policy.user_policy_version)],'type=\'U\' and name=\''+username+'\'')
for profile in policy.user_profiles:
profile_columns=['id','label','description','is_overridable','is_active','profile_data','modify_date']
args=[str(user_policy_id[0][0]),str(profile.label),str(profile.description),str(profile.is_overridable),str(profile.is_active),str(profile.profile_data),str(profile.modify_date)]
self.db_service.update('profile',profile_columns,args)
if profile.plugin.name not in installed_plugins and profile.plugin.name not in missing_plugins:
missing_plugins.append(profile.plugin.name)
else:
print("already there user policy")
print("updated policies")
print("but first need these plugins:"+str(missing_plugins))
def get_installed_plugins(self):
plugins=self.db_service.select('plugin',['name','version'])
p_list=[]
for p in plugins:
p_list.append(str(p[0])+'-'+str(p[1]))
return p_list
def add_task(self,arg): def add_task(self,arg):
self.logger.debug('[ExecutionManager] Adding new task...') self.logger.debug('[ExecutionManager] Adding new task...')

View file

@ -5,6 +5,7 @@ import sys, pwd, os, datetime, json
sys.path.append('../..') sys.path.append('../..')
from base.Scope import Scope from base.Scope import Scope
import configparser
class Messaging(object): class Messaging(object):
@ -12,10 +13,55 @@ class Messaging(object):
scope = Scope().getInstance() scope = Scope().getInstance()
self.logger = scope.getLogger() self.logger = scope.getLogger()
self.conf_manager = scope.getConfigurationManager() self.conf_manager = scope.getConfigurationManager()
self.db_service=scope.getDbService()
self.event_manger = scope.getEventManager() self.event_manger = scope.getEventManager()
# TODO can use sh commands or api for getting username and timestamp # TODO can use sh commands or api for getting username and timestamp
def policy_request_msg(self):
#TODO volkan
self.logger.debug('[Messaging] Creating policy request message')
############# Create policy tables #########################
columns=['id INTEGER PRIMARY KEY AUTOINCREMENT','type TEXT','version TEXT','name TEXT']
self.db_service.check_and_create_table('policy',columns)
columns=['id INTEGER','label TEXT','description TEXT','is_overridable INTEGER','is_active INTEGER','profile_data BLOB','modify_date TEXT']
self.db_service.check_and_create_table('profile',columns)
columns=['version TEXT','name TEXT','description TEXT']
self.db_service.check_and_create_table('plugin',columns)
############################################################
#cols=['type','version','name']
#args=['U','1','2559305d-a415-38e7-8498-2dbc458662a7']
#self.db_service.update('policy',cols,args,None)
colz=['version']
ahenk_version=self.db_service.select('policy',colz,'type = \'A\'')
username='volkan'
user_version=self.db_service.select('policy',colz,'type = \'U\' and name = \''+username+'\'')
if len(ahenk_version)==0:
ahenk_version.append(-1)
if len(user_version)==0:
user_version.append(-1)
data = {}
data['type'] = 'POLICY_REQUEST'
data['username'] = username
data['ahenkPolicyVersion'] = str(''.join(ahenk_version[0]))
data['userPolicyVersion'] =str(''.join(user_version[0]))
json_data = json.dumps(data)
self.logger.debug('[Messaging] Policy request message was created')
print(json_data)
return json_data
def login_msg(self): def login_msg(self):
data = {} data = {}
data['type'] = 'LOGIN' data['type'] = 'LOGIN'

View file

@ -14,12 +14,28 @@ class Profile(object):
return self.profile['id'] return self.profile['id']
@property @property
def params(self): def label(self):
return self.profile['params'] return self.profile['label']
@property @property
def date(self): def description(self):
return self.profile['date'] return self.profile['description']
@property
def is_overridable(self):
return self.profile['isoverridable']
@property
def is_active(self):
return self.profile['isactive']
@property
def modify_date(self):
return self.profile['modifydate']
@property
def profile_data(self):
return self.profile['profiledata']
@property @property
def plugin(self): def plugin(self):