main
py 132 lines 4.47 KB
Raw
1 from typing import Any
2 from typing import Dict
3
4 from fastapi import HTTPException
5 from grafana_client import GrafanaApi
6 from loguru import logger
7
8 from app.connectors.utils import get_connector_info_from_db
9 from app.db.db_session import get_db_session
10
11
12 async def construct_grafana_url(connector_url: str, username: str, password: str, verify: bool = False) -> str:
13 """
14 Constructs a Grafana URL with embedded credentials.
15
16 Args:
17 connector_url (str): The base URL of the Grafana instance.
18 username (str): Username for Grafana authentication.
19 password (str): Password for Grafana authentication.
20 verify (bool, optional): Whether to verify SSL certificates. Defaults to True.
21
22 Returns:
23 str: The complete Grafana URL with credentials.
24 """
25 if "http://" in connector_url:
26 url = connector_url.replace("http://", f"http://{username}:{password}@")
27 elif "https://" in connector_url:
28 url = connector_url.replace("https://", f"https://{username}:{password}@")
29 else:
30 raise ValueError("Invalid connector URL format")
31
32 # Add the verify parameter to the URL
33 url += "?verify=" + str(verify).lower()
34
35 return url
36
37
38 async def verify_grafana_credentials(attributes: Dict[str, Any]) -> Dict[str, Any]:
39 """
40 Verifies the connection to Grafana service.
41
42 Returns:
43 dict: A dictionary containing 'connectionSuccessful' status and 'authToken' if the connection is successful.
44 """
45 logger.info(f"Verifying the Grafana connection to {attributes['connector_url']}")
46 connector_url = attributes["connector_url"]
47 username = attributes["connector_username"]
48 password = attributes["connector_password"]
49
50 grafana_url = await construct_grafana_url(connector_url, username, password, verify=False)
51
52 grafana_client = GrafanaApi.from_url(grafana_url)
53 try:
54 create_user = grafana_client.admin.create_user(
55 user={
56 "name": "test",
57 "email": "test@socfortress.co",
58 "login": "test",
59 "password": "this_is_a_test_user",
60 "OrgID": 1,
61 },
62 )
63 if create_user["message"] != "User created":
64 raise Exception(f"Failed to create user: {create_user['message']}")
65
66 grafana_client.admin.delete_user(
67 user_id=create_user["id"],
68 )
69
70 logger.info(f"Connection to {grafana_url} successful")
71 return {
72 "connectionSuccessful": True,
73 "message": "Grafana connection successful",
74 }
75 except Exception as e:
76 logger.error(f"Connection to {grafana_url} failed with error: {e}")
77 return {
78 "connectionSuccessful": False,
79 "message": f"Connection to {grafana_url} failed with error: {e}",
80 }
81
82
83 async def verify_grafana_connection(connector_name: str) -> str:
84 """
85 Returns the authentication token for the Grafana service.
86
87 Args:
88 connector_name (str): The name of the Grafana connector.
89
90 Returns:
91 str: Authentication token for the Grafana service.
92
93 Raises:
94 None
95
96 """
97 async with get_db_session() as session: # This will correctly enter the context manager
98 attributes = await get_connector_info_from_db(connector_name, session)
99 logger.info(f"Verifying the Grafana connection to {attributes['connector_url']}")
100 if attributes is None:
101 logger.error("No Grafana connector found in the database")
102 return None
103 return await verify_grafana_credentials(attributes)
104
105
106 async def create_grafana_client(connector_name: str) -> GrafanaApi:
107 """
108 Returns an GrafanaApi client for the Grafana service.
109
110 Returns:
111 GrafanaApi: GrafanaApi client for the Grafana service.
112 """
113 async with get_db_session() as session: # This will correctly enter the context manager
114 attributes = await get_connector_info_from_db(connector_name, session)
115 if attributes is None:
116 raise HTTPException(
117 status_code=500,
118 detail=f"No {connector_name} connector found in the database",
119 )
120 try:
121 grafana_url = await construct_grafana_url(
122 attributes["connector_url"],
123 attributes["connector_username"],
124 attributes["connector_password"],
125 verify=False,
126 )
127 return GrafanaApi.from_url(grafana_url)
128 except Exception as e:
129 raise HTTPException(
130 status_code=500,
131 detail=f"Failed to create Grafana client: {e}",
132 )