diff --git a/khk/lambda/lambda_function.py b/khk/lambda/lambda_function.py new file mode 100644 index 000000000..456364d78 --- /dev/null +++ b/khk/lambda/lambda_function.py @@ -0,0 +1,101 @@ +import json +import os +import requests +import boto3 +import time +from typing import Dict, Any + + +def get_sqs_client(): + if __name__ == "__main__": + # for local testing, load temporary credentials. see notes.md + try: + with open('assume_role_output.json', 'r') as f: + credentials = json.load(f)['Credentials'] + + session = boto3.Session( + aws_access_key_id=credentials['AccessKeyId'], + aws_secret_access_key=credentials['SecretAccessKey'], + aws_session_token=credentials['SessionToken'] + ) + return session.client('sqs', region_name='us-west-2') + except FileNotFoundError: + print("Warning: assume_role_output.json not found. Using default credentials.") + return boto3.client('sqs') + else: + # When running in Lambda, use the role attached to the function + return boto3.client('sqs') + + +sqs = get_sqs_client() +DAILY_API_KEY = os.environ.get('DAILY_API_KEY') +SQS_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/955740203061/khk-sqs-launch-day-demos' + + +def create_daily_room() -> Dict[str, Any]: + if not DAILY_API_KEY: + raise ValueError("DAILY_API_KEY environment variable is not set") + + url = "https://api.daily.co/v1/rooms" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {DAILY_API_KEY}" + } + + exp = int(time.time()) + 305 + payload = { + "properties": { + "exp": exp, + "eject_at_room_exp": True + } + } + + response = requests.post(url, headers=headers, json=payload) + response = requests.post(url, headers=headers, json=payload) + response.raise_for_status() + return response.json() + + +def send_to_sqs(room_info: Dict[str, Any]) -> None: + if not SQS_QUEUE_URL: + raise ValueError("SQS_QUEUE_URL environment variable is not set") + + if sqs: + sqs.send_message( + QueueUrl=SQS_QUEUE_URL, + MessageBody=json.dumps(room_info) + ) + print(f"Message sent to SQS queue: {SQS_QUEUE_URL}") + else: + print(f"Simulated sending message to SQS queue: {SQS_QUEUE_URL}") + print(f"Message body: {json.dumps(room_info, indent=2)}") + + +def lambda_handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]: + try: + print("Creating Daily room...") + daily_room = create_daily_room() + print(f"Daily room created: {json.dumps(daily_room, indent=2)}") + + print("Sending room info to SQS...") + send_to_sqs(daily_room) + + return { + 'statusCode': 200, + 'body': json.dumps({"room_url": daily_room['url']}) + } + except Exception as e: + print(f"Error occurred: {str(e)}") + return { + 'statusCode': 500, + 'body': json.dumps(f'Error: {str(e)}') + } + + +if __name__ == "__main__": + # Simulate the Lambda event and context + event = {} + context = None + + result = lambda_handler(event, context) + print(f"Lambda handler result: {json.dumps(result, indent=2)}") diff --git a/khk/lambda/requirements.txt b/khk/lambda/requirements.txt new file mode 100644 index 000000000..a873d9293 --- /dev/null +++ b/khk/lambda/requirements.txt @@ -0,0 +1,2 @@ +requests +boto3 diff --git a/khk/sqs-runner/sqs-runner.py b/khk/sqs-runner/sqs-runner.py index 152f22529..ecd770dfe 100644 --- a/khk/sqs-runner/sqs-runner.py +++ b/khk/sqs-runner/sqs-runner.py @@ -1,7 +1,3 @@ -# - block while running bot -# - watchdog timer -# - build docker and deploy to eks - import boto3 import json import subprocess @@ -26,7 +22,7 @@ QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/955740203061/khk-sqs-launch-day SUBPROCESS_PROGRAM = 'your_subprocess_program.py' # Timeout in seconds -TIMEOUT = 620 +TIMEOUT = 320 # ------------ Configuration ------------ # @@ -99,7 +95,7 @@ def delete_message(sqs, receipt_handle): # os.kill(process.pid, signal.SIGKILL) # return False -def start_bot(room_url): +def run_bot(room_url): runner_settings = RunnerSettings() # Check passed room URL exists, we should assume that it already has a sip set up @@ -128,20 +124,33 @@ def start_bot(room_url): ) bot_settings_str = bot_settings.model_dump_json(exclude_none=True) - subprocess.Popen( + process = subprocess.Popen( [f"python3 -m bot -s '{bot_settings_str}'"], shell=True, bufsize=1, cwd=os.path.dirname(os.path.abspath(__file__))) + + start_time = time.time() + while time.time() - start_time < TIMEOUT: + if process.poll() is not None: + # process has finished + print("BOT EXITED BEFORE TIMEOUT") + return + time.sleep(1) + # process did not exit. need to kill -9 it + print("KILLING BOT PROCESS") + os.kill(process.pid, signal.SIGKILL) except Exception as e: raise HTTPException( status_code=500, detail=f"Failed to start subprocess: {e}") def main(): + print("sqs-runner.py - started.") sqs = setup_sqs() while True: + print("sqs-runner.py - polling") message = receive_message(sqs) if message: delete_message(sqs, message['ReceiptHandle']) @@ -149,16 +158,7 @@ def main(): message_body = json.loads(message['Body']) print(f"Received message. {message_body}") - start_bot(message_body['url']) - - # success = run_subprocess(message_body) - # if success: - # print("Subprocess completed successfully.") - # else: - # print("Subprocess timed out and was terminated.") - - else: - print("No messages received. Continuing to poll...") + run_bot(message_body['url']) if __name__ == "__main__":