| 1 | import os |
| 2 | |
| 3 | import requests |
| 4 | from dotenv import load_dotenv |
| 5 | from loguru import logger |
| 6 | from sqlalchemy import select |
| 7 | |
| 8 | from app.auth.services.universal import get_scheduler_password |
| 9 | from app.db.db_session import get_db_session |
| 10 | from app.schedulers.models.scheduler import JobMetadata |
| 11 | |
| 12 | load_dotenv() |
| 13 | |
| 14 | |
| 15 | def scheduler_login(): |
| 16 | """ |
| 17 | Retrieves an authentication token for the scheduler user. |
| 18 | |
| 19 | Returns: |
| 20 | dict: The headers containing the authentication token. |
| 21 | Returns None if the token retrieval fails. |
| 22 | """ |
| 23 | # Get the password |
| 24 | password = get_scheduler_password() |
| 25 | |
| 26 | # Get an auth token |
| 27 | token_response = requests.post( |
| 28 | f"http://{os.getenv('SERVER_IP')}:5000/auth/token", |
| 29 | headers={ |
| 30 | "accept": "application/json", |
| 31 | "Content-Type": "application/x-www-form-urlencoded", |
| 32 | }, |
| 33 | data={ |
| 34 | "grant_type": "", |
| 35 | "username": "scheduler", |
| 36 | "password": password, |
| 37 | "scope": "", |
| 38 | }, |
| 39 | ) |
| 40 | |
| 41 | # Check if the token was successfully retrieved |
| 42 | if token_response.status_code == 200: |
| 43 | token = token_response.json().get("access_token") |
| 44 | # Use the token in the header of your subsequent requests |
| 45 | headers = {"Authorization": f"Bearer {token}"} |
| 46 | return headers |
| 47 | else: |
| 48 | print("Failed to retrieve token") |
| 49 | return None |
| 50 | |
| 51 | |
| 52 | async def get_scheduled_job_metadata(job_id: str) -> JobMetadata: |
| 53 | """ |
| 54 | Retrieves the metadata for a scheduled job. |
| 55 | |
| 56 | Args: |
| 57 | job_id (str): The ID of the scheduled job. |
| 58 | |
| 59 | Returns: |
| 60 | dict: The metadata for the scheduled job. |
| 61 | Returns None if the metadata retrieval fails. |
| 62 | """ |
| 63 | async with get_db_session() as session: |
| 64 | stmt = select(JobMetadata).where(JobMetadata.job_id == job_id) |
| 65 | result = await session.execute(stmt) |
| 66 | job_metadata = result.scalars().first() |
| 67 | if job_metadata: |
| 68 | return job_metadata |
| 69 | else: |
| 70 | logger.info(f"JobMetadata for {job_id} not found.") |
| 71 | return None |