def get_cron_tasks(cron_task_id=None, user='******'): """Function to return all the user created cron.""" cron_list = [] try: db_path, err = config.get_db_path() if err: raise Exception(err) if cron_task_id is None: query = 'select * from cron_tasks' else: query = 'select * from cron_tasks where cron_task_id=%s' % cron_task_id cron_db_entries, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if cron_db_entries: cron = crontab.CronTab(user) for cron_db_entry in cron_db_entries: cron_dict = {} cron_dict['description'] = cron_db_entry['description'] cron_dict['command'] = cron_db_entry['command'] cron_dict['cron_task_id'] = cron_db_entry['cron_task_id'] jobs = cron.find_comment(str(cron_db_entry['cron_task_id'])) if jobs: for job in jobs: cron_dict['schedule_description'] = job.description( use_24hour_time_format=True) cron_dict['job'] = job break cron_list.append(cron_dict) except Exception, e: return None, 'Error listing all cron entries : %s' % str(e)
def get_org_info(): """Return organization's information args: None returns: dict with keys- 'org_name', 'unit_name', 'unit_id', 'subunit_name', 'subunit_id' """ ret_dict = {} try: db_path, err = config.get_db_path() if err: raise Exception(err) cmd = "select * from org_info" ret, err = db.get_single_row(db_path, cmd) if err: raise Exception(err) if ret: # return the dict which has all the fields ret_dict = ret except Exception, e: return None, 'Could not fetch details of the organisation: %s' % e
def main(): lg = None try: scripts_log, err = config.get_scripts_log_path() if err: raise Exception(err) lg, err = logger.get_script_logger( 'Task processor', scripts_log, level=logging.DEBUG) lck, err = lock.get_lock('task_processor') if err: raise Exception(err) if not lck: raise Exception('Could not acquire lock. Exiting.') logger.log_or_print( 'Task processor execution initiated.', lg, level='info') db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = tasks_utils.process_tasks() if err: raise Exception(err) except Exception, e: str = 'Error running the task processor : %s' % e lock.release_lock('task_processor') logger.log_or_print(str, lg, level='critical') return -1
def delete_event_notification(ent_id): """Remove an event notification - from the triggers table and from the cron. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ent, err = get_event_notification_trigger(ent_id) if err: raise Exception(err) # print ent ret, err = delete_event_notification_holdings(ent_id) if err: raise Exception(err) ret, err = delete_event_notification_trigger(ent_id) if err: raise Exception(err) ret, err = scheduler_utils.delete_cron(ent['cron_task_id']) if err: raise Exception(err) if ent['notification_type_id'] == 1: ret, err = mail.delete_event_notification_configuration( ent['enc_id']) if err: raise Exception(err) except Exception, e: raise Exception(err)
def generate_alert_email_body(alert_id): """Given an alert id, generate the appropriate email message body for that alert """ msg = None try: db_path, err = config.get_db_path() if err: raise Exception(err) query = 'select * from alerts where alert_id = "%s"' % alert_id entry, err = db.get_single_row(db_path, query) # print entry if err: raise Exception(err) fat, err = datetime_utils.convert_from_epoch(entry['first_alert_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) lut, err = datetime_utils.convert_from_epoch(entry['last_update_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) msg = 'Alert time: %s\nAlert message: %s.' % (lut, entry['alert_str']) if entry['repeat_count'] > 1: msg += ' This alert has been generated %d times since %s.' % ( entry['repeat_count'], fat) except Exception, e: return None, 'Error generating alert email message body : %s' % str(e)
def new_alerts_present(username): """Check for new alerts based on the last access time for the specified user.""" ret = False try: db_path, err = config.get_db_path() if err: raise Exception(err) query = 'select * from admin_alerts where user = "******"' % username entry, err = db.get_single_row(db_path, query) if err: raise Exception(err) if not entry: ret = True # print entry query = 'select count(*) as count from alerts where last_update_time > "%d"' % entry[ 'last_refresh_time'] # print query entry, err = db.get_single_row(db_path, query) # print entry, err if err: raise Exception(err) if entry and int(entry['count']) > 0: ret = True except Exception, e: return False, 'Error checking for new alerts : %s' % str(e)
def main(): lg = None try: scripts_log, err = config.get_scripts_log_path() if err: raise Exception(err) lg, err = logger.get_script_logger('Task processor', scripts_log, level=logging.DEBUG) lck, err = lock.get_lock('task_processor') if err: raise Exception(err) if not lck: raise Exception('Could not acquire lock. Exiting.') logger.log_or_print('Task processor execution initiated.', lg, level='info') db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = tasks_utils.process_tasks() if err: raise Exception(err) except Exception, e: str = 'Error running the task processor : %s' % e lock.release_lock('task_processor') logger.log_or_print(str, lg, level='critical') return -1
def record_event_notification_holding(event_id, event_type_id, event_subtype_id=-1, subsystem_type_id=-1, severity_type_id=-1): """Create an notification holding entry by looking up the triggers table for all matching entries.. """ try: ent_list, err = get_event_notification_triggers( event_type_id=event_type_id, event_subtype_id=event_subtype_id, subsystem_type_id=subsystem_type_id, severity_type_id=severity_type_id) if err: raise Exception(err) # print ent_list if ent_list: db_path, err = config.get_db_path() if err: raise Exception(err) command_list = [] for ent in ent_list: cmd = [ 'insert into event_notifications_holding(event_id, ent_id, status) values (?,?,?)', (event_id, ent['ent_id'], 1,)] command_list.append(cmd) # print command_list ret, err = db.execute_iud(db_path, command_list) if err: raise Exception(err) except Exception, e: return False, 'Error recording event notifications : %s' % str(e)
def create_share(name, comment, guest_ok, read_only, path, display_path, browseable, users, groups, vol, hosts_allow=None, hosts_deny=None): """Create a new share in the db.""" try: db_path, err = config.get_db_path() if err: raise Exception(err) platform, err = config.get_platform() if err: raise Exception(err) d, err = get_auth_settings() if err: raise Exception(err) if not d: raise Exception( "Authentication settings not set. Please set authentication settings before creating shares.") shl, err = get_shares_list() if err: raise Exception(err) if shl: for sh in shl: if sh["name"] == name: raise Exception("A share with that name already exists") share_id, err = db.execute_iud(db_path, [["insert into samba_shares (name, vol, path, display_path, comment, read_only, guest_ok, browseable, share_id, hosts_allow, hosts_deny) values (?,?, ?,?,?,?,?,?,NULL,?,?)", ( name, vol, path, display_path, comment, read_only, guest_ok, browseable, hosts_allow, hosts_deny,)]], True) if err: raise Exception(err) # print share_id, err except Exception, e: return False, 'Error creating CIFS share : %s' % str(e)
def delete_all_tasks(): """Delete all entries from tasks table and terminate running tasks """ try: tasks, err = get_tasks() if err: raise Exception(err) for task in tasks: if str(task['status']) == 'running': ret, err = stop_task(int(task['task_id'])) if err: # best effort pass db_path, err = config.get_db_path() if err: raise Exception(err) # Deleting entries from tasks table will also remove related # entries in subtasks table; cascading deletions. cmd_list = [['delete from tasks'], ] status, err = db.execute_iud(db_path, cmd_list) if err: raise Exception(err) except Exception, e: return False, 'Error removing tasks: %s' % e
def get_reference_table_entries(table_name_list): """Load the reference table entries for the tables passed """ return_dict = None try: if table_name_list: return_dict = {} db_path, err = config.get_db_path() if err: raise Exception(err) basic_reference_table_list = [] for table_name in table_name_list: if table_name in [ 'reference_event_types', 'reference_notification_types', 'reference_severity_types', 'reference_subsystem_types' ]: basic_reference_table_list.append(table_name) for table in table_name_list: query = 'select * from %s' % table ref_list, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if ref_list: if table in basic_reference_table_list: td = {} for r in ref_list: td[r['id']] = r['description'] return_dict[table] = td elif table in ['reference_event_subtypes']: return_dict[table] = ref_list except Exception, e: return None, 'Error getting reference table entries : %s' % str(e)
def get_entries(audit_id=None, start_time=None): """Get either all or a specific audit entry(ies) from the db """ al = [] try: if start_time and audit_id: raise Exception('Incompatible parameters passed') db_path, err = config.get_db_path() if err: raise Exception(err) if audit_id: query = 'select * from audit where audit_id="%d" order by audit_id desc' % int( audit_id) else: if not start_time: query = 'select * from audit order by audit_id desc' else: query = 'select * from audit where audit_time >= %d order by audit_id desc' % int( start_time) rows, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if rows: for row in rows: audit_entry, err = _parse_audit_entry(row) if err: raise Exception(err) al.append(audit_entry) except Exception, e: return None, 'Error loading audit entries : %s' % str(e)
def create_cron_task(command, description, min="1", hour='*', day='*', dow='*', month='*', user='******', task_type_id=0): cron_task_id = None try: if not command or not description: raise Exception('Invalid parameters') db_path, err = config.get_db_path() if err: raise Exception(err) cmd = [ 'insert into cron_tasks(command,description, task_type_id) values (?,?,?)', (command, description, task_type_id)] cron_task_id, err = db.execute_iud(db_path, [cmd], get_rowid=True) if err: raise Exception(err) log_dir, err = config.get_cron_log_dir_path() if err: raise Exception(err) if not os.path.isdir(log_dir): os.mkdir(log_dir) log_file = '%s/%d.log' % (log_dir, cron_task_id) command = '%s >> %s 2>&1' % (command, log_file) cron = crontab.CronTab(user) job = cron.new(command=command, comment='%d' % cron_task_id) job.setall(min, hour, day, dow, month) if job.is_valid(): job.enable() cron.write() else: raise Exception('Cron entry not valid.') except Exception, e: return None, 'Error creating cron entry : %s' % str(e)
def get_event_notification_trigger(ent_id): """Get the trigger entry corresponding to the passed trigger id """ return_dict = None try: db_path, err = config.get_db_path() if err: raise Exception(err) query = 'select * from event_notification_triggers where ent_id=%d' % int( ent_id) return_dict, err = db.get_single_row(db_path, query) if err: raise Exception(err) if return_dict: cron_list, err = scheduler_utils.get_cron_tasks( return_dict['cron_task_id']) if err: raise Exception(err) if cron_list: return_dict['schedule_description'] = cron_list[0][ 'schedule_description'] return_dict['description'] = cron_list[0]['description'] except Exception, e: return None, 'Error retrieving event notification trigger : %s' % str( e)
def delete_event_notification(ent_id): """Remove an event notification - from the triggers table and from the cron. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ent, err = get_event_notification_trigger(ent_id) if err: raise Exception(err) # print ent ret, err = delete_event_notification_holdings(ent_id) if err: raise Exception(err) ret, err = delete_event_notification_trigger(ent_id) if err: raise Exception(err) ret, err = scheduler_utils.delete_cron(ent['cron_task_id']) if err: raise Exception(err) if ent['notification_type_id'] == 1: ret, err = mail.delete_event_notification_configuration( ent['enc_id']) if err: raise Exception(err) except Exception, e: raise Exception(err)
def delete_task(task_id): """Terminate the task if it's running and delete the task entry """ try: is_stopped, err = stop_task(task_id) if err: # best effort # only remote replication tasks can be stopped(currently) pass db_path, err = config.get_db_path() if err: raise Exception(err) # Deleting entries from tasks table will also remove related # entries in subtasks table; cascading deletions. cmd_list = [ ['delete from tasks where task_id = %s' % task_id], ] status, err = db.execute_iud(db_path, cmd_list) if err: raise Exception(err) except Exception, e: return False, 'Error removing task : %s' % e
def delete_all_tasks(): """Delete all entries from tasks table and terminate running tasks """ try: tasks, err = get_tasks() if err: raise Exception(err) for task in tasks: if str(task['status']) == 'running': ret, err = stop_task(int(task['task_id'])) if err: # best effort pass db_path, err = config.get_db_path() if err: raise Exception(err) # Deleting entries from tasks table will also remove related # entries in subtasks table; cascading deletions. cmd_list = [ ['delete from tasks'], ] status, err = db.execute_iud(db_path, cmd_list) if err: raise Exception(err) except Exception, e: return False, 'Error removing tasks: %s' % e
def new_alerts_present(username): """Check for new alerts based on the last access time for the specified user.""" ret = False try: db_path, err = config.get_db_path() if err: raise Exception(err) query = 'select * from admin_alerts where user = "******"' % username entry, err = db.get_single_row(db_path, query) if err: raise Exception(err) if not entry: ret = True # print entry query = 'select count(*) as count from alerts where last_update_time > "%d"' % entry[ 'last_refresh_time'] # print query entry, err = db.get_single_row(db_path, query) # print entry, err if err: raise Exception(err) if entry and int(entry['count']) > 0: ret = True except Exception, e: return False, 'Error checking for new alerts : %s' % str(e)
def generate_alert_email_body(alert_id): """Given an alert id, generate the appropriate email message body for that alert """ msg = None try: db_path, err = config.get_db_path() if err: raise Exception(err) query = 'select * from alerts where alert_id = "%s"' % alert_id entry, err = db.get_single_row(db_path, query) # print entry if err: raise Exception(err) fat, err = datetime_utils.convert_from_epoch( entry['first_alert_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) lut, err = datetime_utils.convert_from_epoch( entry['last_update_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) msg = 'Alert time: %s\nAlert message: %s.' % (lut, entry['alert_str']) if entry['repeat_count'] > 1: msg += ' This alert has been generated %d times since %s.' % ( entry['repeat_count'], fat) except Exception, e: return None, 'Error generating alert email message body : %s' % str(e)
def get_event_notification_holdings(id, mode='by_event_notification_trigger_id'): """Get all holding entries either by trigger id or by event_id """ enh_list = None try: if mode not in ['by_event_notification_trigger_id', 'by_event_id']: raise Exception('Unknown mode specified.') db_path, err = config.get_db_path() if err: raise Exception(err) if mode == 'by_event_id': query = 'select event_notifications_holding.* from event_notifications_holding inner join event_notification_triggers on (event_notifications_holding.ent_id = event_notification_triggers.ent_id and event_notification_triggers.event_type_id = %d)' % int( id) elif mode == 'by_event_notification_trigger_id': query = 'select * from event_notifications_holding where ent_id = %d' % int( id) # print query enh_list, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) except Exception, e: return None, 'Error retrieving event notification holdings of type %s: %s' % ( id, str(e))
def get_entries(audit_id=None, start_time=None): """Get either all or a specific audit entry(ies) from the db """ al = [] try: if start_time and audit_id: raise Exception('Incompatible parameters passed') db_path, err = config.get_db_path() if err: raise Exception(err) if audit_id: query = 'select * from audit where audit_id="%d" order by audit_id desc' % int( audit_id) else: if not start_time: query = 'select * from audit order by audit_id desc' else: query = 'select * from audit where audit_time >= %d order by audit_id desc' % int( start_time) rows, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if rows: for row in rows: audit_entry, err = _parse_audit_entry(row) if err: raise Exception(err) al.append(audit_entry) except Exception, e: return None, 'Error loading audit entries : %s' % str(e)
def get_tasks_by_cron_task_id(cron_task_id, get_last_by=False, status_list=None): tasks = [] try: status_qry = '' db_path, err = config.get_db_path() if err: raise Exception(err) if status_list: list_len = len(status_list) for idx, status in enumerate(status_list): if idx < (list_len - 1): status_qry = '%s status="%s" or ' % (status_qry, str(status)) elif idx == (list_len - 1): status_qry = '%s status="%s"' % (status_qry, str(status)) status_qry = 'and (%s)' % status_qry if get_last_by is False: query = 'select * from tasks where cron_task_id="%d" %s' % (int( cron_task_id), status_qry) else: query = 'select * from tasks where cron_task_id="%d" %s order by "%s" desc limit 1' % ( int(cron_task_id), status_qry, str(get_last_by)) tasks, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) except Exception, e: return None, 'Error retrieving tasks by cron task id: %s' % e
def update_auth_method(security): """Update the currently set authentication method in the db. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) d, err = get_auth_settings() if err: raise Exception(err) cl = [] if not d: # Insert a default entry before they modify the settings.. cl.append(["insert into samba_global_common (id, workgroup, netbios_name, security, include_homes_section) values (?, ?, ?, ?, ?)", (1, 'workgroup', 'netbios_name', security, True,)]) else: cl.append( ["update samba_global_common set security='%s' where id=1" % security]) platform, err = config.get_platform() if err: raise Exception(err) ret, err = db.execute_iud(db_path, cl) if err: raise Exception(err) except Exception, e: return False, 'Error changing authentication method : %s' % str(e)
def get_tasks_by_cron_task_id(cron_task_id, get_last_by=False, status_list=None): tasks = [] try: status_qry = '' db_path, err = config.get_db_path() if err: raise Exception(err) if status_list: list_len = len(status_list) for idx, status in enumerate(status_list): if idx < (list_len - 1): status_qry = '%s status="%s" or ' % (status_qry, str(status)) elif idx == (list_len - 1): status_qry = '%s status="%s"' % (status_qry, str(status)) status_qry = 'and (%s)' % status_qry if get_last_by is False: query = 'select * from tasks where cron_task_id="%d" %s' % ( int(cron_task_id), status_qry) else: query = 'select * from tasks where cron_task_id="%d" %s order by "%s" desc limit 1' % ( int(cron_task_id), status_qry, str(get_last_by)) tasks, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) except Exception, e: return None, 'Error retrieving tasks by cron task id: %s' % e
def get_reference_table_entries(table_name_list): """Load the reference table entries for the tables passed """ return_dict = None try: if table_name_list: return_dict = {} db_path, err = config.get_db_path() if err: raise Exception(err) basic_reference_table_list = [] for table_name in table_name_list: if table_name in ['reference_event_types', 'reference_notification_types', 'reference_severity_types', 'reference_subsystem_types']: basic_reference_table_list.append(table_name) for table in table_name_list: query = 'select * from %s' % table ref_list, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if ref_list: if table in basic_reference_table_list: td = {} for r in ref_list: td[r['id']] = r['description'] return_dict[table] = td elif table in ['reference_event_subtypes']: return_dict[table] = ref_list except Exception, e: return None, 'Error getting reference table entries : %s' % str(e)
def save_email_settings(d): """Save the email server settings """ conn = None try: db_path, err = config.get_db_path() if err: raise Exception(err) d1, err = db.get_single_row(db_path, "select * from email_config") if err: raise Exception(err) if d1: # Config exists so update ret, err = db.execute_iud(db_path, [["update email_config set server=?, port=?, username=?, pswd=?, tls=? where id = ?", ( d["server"], d["port"], d["username"], d["pswd"], d["tls"], 1,)]]) if err: raise Exception(err) else: # No config exists so insert ret, err = db.execute_iud(db_path, [["insert into email_config (server, port, username, pswd, tls, id) values (?,?,?,?,?,?)", ( d["server"], d["port"], d["username"], d["pswd"], d["tls"], 1, )]]) if err: raise Exception(err) except Exception, e: return False, 'Error saving email settings : %s' % str(e)
def create_event_notification_trigger(event_type_id, event_subtype_id, subsystem_type_id, notification_type_id, severity_type_id, enc_id, cron_task_id): """Create an entry in the triggers table with the supplied params. """ ent_id = None try: db_path, err = config.get_db_path() if err: raise Exception(err) ent_id, err = db.execute_iud(db_path, [[ "insert into event_notification_triggers (event_type_id, event_subtype_id, subsystem_type_id, notification_type_id, severity_type_id, enc_id, cron_task_id) values (?,?,?,?,?,?,?)", ( event_type_id, event_subtype_id, subsystem_type_id, notification_type_id, severity_type_id, enc_id, cron_task_id, ) ]], get_rowid=True) if err: raise Exception(err) except Exception, e: return None, 'Error creating event notification trigger : %s' % str(e)
def _get_repeat_entry(alert_dict, past_x_seconds=900): """Check the db to see if the passed alert is a repeat of an existing alert entry in the past x seconds """ result = None try: db_path, err = config.get_db_path() if err: raise Exception(err) now, err = datetime_utils.get_epoch(when='now', num_previous_days=0) if alert_dict['component']: query = "select * from alerts where severity_type_id = '%d' and subsystem_type_id = '%d' and component = '%s' and alert_str=\"%s\" and first_alert_time >= %d;" % ( alert_dict['severity_type_id'], alert_dict['subsystem_type_id'], alert_dict['component'], alert_dict['alert_str'], now - past_x_seconds) else: query = "select * from alerts where severity_type_id = '%d' and subsystem_type_id = '%d' and alert_str=\"%s\" and first_alert_time >= %d);" % ( alert_dict['severity_type_id'], alert_dict['subsystem_type_id'], alert_dict['alert_str'], now - past_x_seconds) # print query result, err = db.get_single_row(db_path, query) if err: raise Exception(err) # print result, err except Exception, e: return None, 'Error checking for repeats : %s' % str(e)
def set_log_level(level): try: db_path, err = config.get_db_path() if err: raise Exception(err) if level not in [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]: logger.setLevel(logging.INFO) else: d1, err = db.get_single_row( db_path, "select * from global_params") if err: raise Exception(err) cmd_list = [] if d1: cmd = [ "update global_params set logging_level=? where id = ?", (level, 1,)] else: cmd = [ "insert into global_params (logging_level, id) values(?,?)", (level, 1,)] cmd_list.append(cmd) ret, err = db.execute_iud(db_path, cmd_list) if err: raise Exception(err) logger.setLevel(level) except Exception, e: return False, 'Error setting log level : %s' % str(e)
def delete_cron(cron_task_id, user='******'): """Delete a cron by the cron_task_id.""" try: db_path, err = config.get_db_path() if err: raise Exception(err) query_tasks = 'select * from tasks where cron_task_id="%d"' % int( cron_task_id) tasks, err = db.get_multiple_rows(db_path, query_tasks) if err: raise Exception(err) cmd_list = [] cmd_list.append( ['delete from cron_tasks where cron_task_id=%d' % int(cron_task_id)]) cmd_list.append( ['update tasks set status="cancelled" where cron_task_id=%d and (status is not "completed" and status is not "failed")' % int(cron_task_id)]) if tasks: for task in tasks: cmd_list.append( ['update subtasks set status="cancelled" where task_id=%d and (status is not "completed" and status is not "failed")' % task['task_id']]) ret, err = db.execute_iud(db_path, cmd_list) if err: raise Exception(err) cron = crontab.CronTab(user) cron.remove_all(comment=str(cron_task_id)) cron.write() except Exception, e: return False, "Error deleting cron entry : %s" % str(e)
def update_auth_method(security): """Update the currently set authentication method in the db. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) d, err = get_auth_settings() if err: raise Exception(err) cl = [] if not d: # Insert a default entry before they modify the settings.. cl.append([ "insert into samba_global_common (id, workgroup, netbios_name, security, include_homes_section) values (?, ?, ?, ?, ?)", ( 1, 'workgroup', 'netbios_name', security, True, ) ]) else: cl.append([ "update samba_global_common set security='%s' where id=1" % security ]) platform, err = config.get_platform() if err: raise Exception(err) ret, err = db.execute_iud(db_path, cl) if err: raise Exception(err) except Exception, e: return False, 'Error changing authentication method : %s' % str(e)
def get_shares_list(): """Load the list of currently created shares from the db. """ l = [] try: db_path, err = config.get_db_path() if err: raise Exception(err) l, err = db.get_multiple_rows(db_path, 'select * from samba_shares') if err: raise Exception(err) except Exception, e: return None, 'Error loading CIFS shares list : %s' % str(e)
def delete_auth_settings(): """ Delete all authentication settings from the db. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [["delete from samba_global_common "], [ "delete from samba_global_ad"]]) if err: raise Exception(err) except Exception, e: return False, 'Error deleting authentication settings : %s' % str(e)
def _get_and_parse_alerts(query): """Load the results from the db and do the appropriate time conversions if possible. """ alerts_list = [] try: # print query db_path, err = config.get_db_path() if err: raise Exception(err) alerts_list, err = db.get_multiple_rows(db_path, query) # print alerts_list if err: raise Exception(err) if alerts_list: severity_defs, err = _load_definitions('severity') if err: raise Exception(err) subsystem_defs, err = _load_definitions('subsystem') if err: raise Exception(err) for al in alerts_list: # print al for defn in severity_defs: if defn['id'] == al['severity_type_id']: al['severity'] = defn['description'] for defn in subsystem_defs: if defn['id'] == al['subsystem_type_id']: al['subsystem'] = defn['description'] try: fat, err = datetime_utils.convert_from_epoch( al['first_alert_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) lut, err = datetime_utils.convert_from_epoch( al['last_update_time'], return_format='str', str_format='%c', to='local') if err: raise Exception(err) al['first_alert_time'] = fat al['last_update_time'] = lut except Exception, e: print str(e) pass except Exception, e: return None, 'Error getting and parsing alerts : %s' % str(e)
def get_shares_list(): """Load the list of currently created shares from the db. """ l = [] try: db_path, err = config.get_db_path() if err: raise Exception(err) l, err = db.get_multiple_rows(db_path, 'select * from samba_shares') if err: raise Exception(err) except Exception, e: return None, 'Error loading CIFS shares list : %s' % str(e)
def get_rsync_share_details(name): share = None try: db_path, err = config.get_db_path() if err: raise Exception(err) share, err = db.get_single_row( db_path, "select * from rsync_shares where name='%s'" % name) if not share: raise Exception("Specified share not found ") except Exception, e: return False, 'Error deleting the share: %s' % str(e)
def delete_email_settings(): """Remove the email server settings """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [["delete from email_config "]]) if err: raise Exception(err) except Exception, e: return False, 'Error deleting email settings : %s' % str(e)
def update_event_notification_trigger_cron_id(ent_id, cron_task_id): """Update the cron id for the trigger - this is because we dont know it in advance when creating the trigger. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [ ["update event_notification_triggers set cron_task_id=? where ent_id = ?", (cron_task_id, ent_id,)]]) if err: raise Exception(err) except Exception, e: return False, "Error updating event notification trigger's cron task id : %s" % str(e)
def record_alerts(alerts_list): """Record a set of passed list containing alert dictionaries into the DB.""" try: db_path, err = config.get_db_path() if err: raise Exception(err) if alerts_list: now, err = datetime_utils.get_epoch( when='now', num_previous_days=0) if err: raise Exception(er) for alert in alerts_list: # print alert command_list = [] result, err = _get_repeat_entry(alert) # print 'repeat', result, err if err: raise Exception(err) update_alert_id = None if result: cmd = ['update alerts set repeat_count=%d, last_update_time="%d" where alert_id=%d' % ( int(result['repeat_count']) + 1, now, result['alert_id'])] update_alert_id = result['alert_id'] # print 'updating!', cmd else: if 'component' not in alert or (not alert['component']): cmd = [ 'insert into alerts(first_alert_time, last_update_time, severity_type_id, subsystem_type_id, alert_str) values (?,?,?,?,?)', (now, now, alert['severity_type_id'], alert['subsystem_type_id'], alert['alert_str'],)] else: cmd = [ 'insert into alerts(first_alert_time, last_update_time, severity_type_id, subsystem_type_id, component, alert_str) values (?,?,?,?,?,?)', (now, now, alert['severity_type_id'], alert['subsystem_type_id'], alert['component'], alert['alert_str'],)] command_list.append(cmd) # print command_list rowid, err = db.execute_iud( db_path, command_list, get_rowid=True) if err: raise Exception(err) if update_alert_id: alert_id = update_alert_id else: alert_id = rowid ret, err = event_notifications.record_event_notification_holding( event_id=alert_id, event_type_id=1, subsystem_type_id=alert['subsystem_type_id'], severity_type_id=alert['severity_type_id']) # print ret, err if err: raise Exception(err) except Exception, e: # print str(e) return False, 'Error recording alerts : %s' % str(e)
def delete_event_notification_trigger(ent_id): """Remove the specified triggers table entry. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [ ["delete from event_notification_triggers where ent_id='%d'" % int(ent_id)]]) if err: raise Exception(err) except Exception, e: return False, 'Error removing event notification trigger : %s' % str(e)
def delete_event_notification_holdings(ent_id): """Remove all the holdings entries corresponding to the specified trigger id """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [ ["delete from event_notifications_holding where ent_id='%d'" % int(ent_id)]]) if err: raise Exception(err) except Exception, e: return False, 'Error removing event notification holdings : %s' % str(e)
def delete_event_notification_holding(enh_id): """Remove a specific holding entry """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud( db_path, [["delete from event_notifications_holding where enh_id=%d" % enh_id]]) if err: raise Exception(err) except Exception, e: return False, 'Error removing event notification holding: %s' % str(e)
def delete_event_notification_configuration(enc_id): """Remove an email configuration entry that will be used for a particular trigger. """ try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.execute_iud(db_path, [ ["delete from event_notification_configuration_email where enc_id='%d'" % int(enc_id)]]) if err: raise Exception(err) except Exception, e: return False, 'Error deleting event notification configuration : %s' % str(e)
def get_cron_tasks(cron_task_id=None, user='******', task_type_id=None): """Function to return all the user created cron.""" cron_list = [] try: db_path, err = config.get_db_path() if err: raise Exception(err) ref_task_types, err = db.get_multiple_rows(db_path, 'select * from reference_task_types') if err: raise Exception(err) ref_task_types_dict = {} for ref_task_type in ref_task_types: ref_task_types_dict[ref_task_type['id']] = ref_task_type['description'] if cron_task_id is None: query = 'select * from cron_tasks' if task_type_id: query = '%s where task_type_id=%s'%(query, task_type_id) else: query = 'select * from cron_tasks where cron_task_id=%s' % cron_task_id if task_type_id: query = '%s and task_type_id=%s'%(query, task_type_id) cron_db_entries, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) if cron_db_entries: cron = crontab.CronTab(user) for cron_db_entry in cron_db_entries: if cron_db_entry['task_type_id'] not in ref_task_types_dict: raise Exception('Unknown task type %d found in scheduled tasks'%cron_db_entry['task_type_id']) cron_dict = {} cron_dict['description'] = cron_db_entry['description'] cron_dict['command'] = cron_db_entry['command'] cron_dict['cron_task_id'] = cron_db_entry['cron_task_id'] cron_dict['task_type_id'] = cron_db_entry['task_type_id'] cron_dict['task_type_description'] = ref_task_types_dict[cron_db_entry['task_type_id']] jobs = cron.find_comment(str(cron_db_entry['cron_task_id'])) if jobs: for job in jobs: cron_dict['schedule_description'] = job.description( use_24hour_time_format=True) cron_dict['job'] = job break cron_list.append(cron_dict) except Exception, e: return None, 'Error listing all cron entries : %s' % str(e)
def create_event_notification_configuration(recipient_list_str): """Create an email configuration entry that will be used for a particular trigger. """ enc_id = None try: db_path, err = config.get_db_path() if err: raise Exception(err) enc_id, err = db.execute_iud(db_path, [ ["insert into event_notification_configuration_email (recipient_list) values (?)", (recipient_list_str, )]], get_rowid=True) if err: raise Exception(err) except Exception, e: return None, 'Error creating event notification configuration: %s' % str(e)
def get_event_notification_configuration(enc_id): """Get a particular email configuration.. """ ret = None try: db_path, err = config.get_db_path() if err: raise Exception(err) ret, err = db.get_single_row( db_path, "select * from event_notification_configuration_email where enc_id = %d" % enc_id) if err: raise Exception(err) except Exception, e: return None, 'Error retrieving email notification configuration : %s' % str(e)
def get_queued_emails(): """Get all entries in the email_queue table """ eq_list = None try: db_path, err = config.get_db_path() if err: raise Exception(err) query = "select * from email_queue where status in (1,2)" eq_list, err = db.get_multiple_rows(db_path, query) if err: raise Exception(err) except Exception, e: return None, 'Error retrieving queued emails: %s' % str(e)