diff --git a/prod_rmq_agents/expire_account.py b/prod_rmq_agents/expire_account.py new file mode 100644 index 0000000000000000000000000000000000000000..c5189db0a9c56ef5918e2cb26c0d5d97ccb2fb0b --- /dev/null +++ b/prod_rmq_agents/expire_account.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +import os +import json +import pika +import rc_util +from os import popen +from pathlib import Path +from rc_rmq import RCRMQ +import rabbit_config as rcfg +from datetime import date, timedelta + +task = "expire_account" + +args = rc_util.get_args() +logger = rc_util.get_logger(args) + +# Instantiate rabbitmq object +rc_rmq = RCRMQ({"exchange": rcfg.Exchange, "exchange_type": "topic"}) + + +def expire_account(ch, method, properties, body): + msg = json.loads(body) + username = msg["username"] + action = msg["action"] + msg["success"] = {} + msg["success"][task] = False + yesterday = date.today() - timedelta(days=1) + + corr_id = properties.correlation_id + reply_to = properties.reply_to + + try: + expire_account_cmd = f'/cm/local/apps/cmd/bin/cmsh -n -c "user;use {username}; set expirationdate {yesterday}; commit;"' + unexpire_account_cmd = f'/cm/local/apps/cmd/bin/cmsh -n -c "user;use {username}; set expirationdate 2037/12/31; commit;"' + + if action == 'lock': + block_ssh = popen(expire_account_cmd).read().rstrip() + elif action == 'unlock': + unblock_ssh = popen(unexpire_account_cmd).read().rstrip() + + msg["success"][task] = True + logger.info(f"ssh expiration set to yesterday for user {username}") + + except Exception: + msg["success"][task] = False + msg["errmsg"] = "Exception raised, while expiring user's ssh access, check the logs for stack trace" + logger.error("", exc_info=True) + + # send response to callback queue with it's correlation ID + if reply_to: + rc_rmq.publish_msg( + {"routing_key": reply_to, + "props": pika.BasicProperties( + correlation_id=corr_id, + ), + "msg": msg} + ) + + logger.debug(f"User {username} confirmation sent for {action}ing {task}") + + ch.basic_ack(delivery_tag=method.delivery_tag) + + +logger.info(f"Start listening to queue: {task}") +rc_rmq.bind_queue(queue=task, routing_key='lock.*', durable=True) +rc_rmq.bind_queue(queue=task, routing_key='unlock.*', durable=True) +rc_rmq.bind_queue(queue=task, routing_key='expiration.*', durable=True) + +rc_rmq.start_consume( + {"queue": task, "cb": expire_account} +) + +logger.info("Disconnected") +rc_rmq.disconnect()