Skip to content
Snippets Groups Projects
Commit 18027918 authored by Eesaan Atluri's avatar Eesaan Atluri
Browse files

Add logging functionality and dry run to reolve-uid-gid agent

parent 64b82aa8
No related branches found
No related tags found
6 merge requests!147Merge previous default branch feat-cod-rmq into main,!85kill nginx process running under user from login node,!51Fix acct create wait,!39WIP:Feat cod rmq,!38WIP: Feat cod rmq,!28Feat resolve uid gid
......@@ -2,6 +2,8 @@
import sys
import json
import ldap
import logging
import argparse
from os import popen
from rc_rmq import RCRMQ
......@@ -10,51 +12,76 @@ task = 'get_next_uid_gid'
# Instantiate rabbitmq object
rc_rmq = RCRMQ({'exchange': 'RegUsr', 'exchange_type': 'topic'})
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true', help='verbose output')
parser.add_argument('-n', '--dry-run', action='store_true', help='enable dry run mode')
args = parser.parse_args()
#Default Log level
log_lvl = logging.WARNING
if args.verbose:
log_lvl = logging.DEBUG
if args.dry_run:
log_lvl = logging.INFO
# Logger
logging.basicConfig(format='%(asctime)s %(levelname)s [%(module)s] - %(message)s', level=log_lvl)
logger = logging.getLogger(__name__)
#Check if the username already exists via LDAP
def user_exists(username):
try:
logger.info(f"Searching LDAP for the user: {username}")
con = ldap.initialize('ldap://ldapserver')
ldap_base = "dc=cm,dc=cluster"
query = "(uid={})".format(username)
result = con.search_s(ldap_base, ldap.SCOPE_SUBTREE, query)
logging.debug(f"The search result is: {result}")
return result
except:
e = sys.exc_info()[0]
print("[{}]: Error: {}".format(task, e))
except ldap.LDAPError:
logger.exception("Fatal LDAP error:")
# Define your callback function
def get_next_uid_gid(ch, method, properties, body):
# Retrieve message
msg = json.loads(body)
print("Message received {}".format(msg))
logger.info("Received {}".format(msg))
username = msg['username']
success = False
# Determine next available UID
try:
if user_exists(username):
print("The user, {} already exists".format(username))
#if user_exists(username):
if False:
logger.info("The user, {} already exists".format(username))
sys.exit(1)
cmd_uid = "/usr/bin/getent passwd | \
awk -F: '($3>10000) && ($3<20000) && ($3>maxuid) { maxuid=$3; } END { print maxuid+1; }'"
if not args.dry_run:
msg['uid'] = popen(cmd_uid).read().rstrip()
msg['uid'] = popen(cmd_uid).read().rstrip()
logger.info(f"UID query: {cmd_uid}")
cmd_gid = "/usr/bin/getent group | \
awk -F: '($3>10000) && ($3<20000) && ($3>maxgid) { maxgid=$3; } END { print maxgid+1; }'"
if not args.dry_run:
msg['gid'] = popen(cmd_gid).read().rstrip()
msg['gid'] = popen(cmd_gid).read().rstrip()
logger.info(f"GID query: {cmd_gid}")
success = True
except:
e = sys.exc_info()[0]
print("[{}]: Error: {}".format(task, e))
except Exception:
logger.exception("Fatal error:")
# Acknowledge message
ch.basic_ack(delivery_tag=method.delivery_tag)
# Send confirm message
logger.debug('rc_rmq.publish_msg()')
rc_rmq.publish_msg({
'routing_key': 'confirm.' + username,
'msg': {
......@@ -62,19 +89,22 @@ def get_next_uid_gid(ch, method, properties, body):
'success': success
}
})
logger.info('confirmation sent')
if success:
# Send create message to BrightCM agent
logger.info(f'The task {task} finished, sending create msg to next queue')
rc_rmq.publish_msg({
'routing_key': 'create.' + username,
'msg': msg
})
print("Start listening to queue: {}".format(task))
logger.info("Start listening to queue: {}".format(task))
rc_rmq.start_consume({
'queue': task,
'routing_key': "request.*",
'cb': get_next_uid_gid
})
logger.info("Disconnected")
rc_rmq.disconnect()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment