Create connectors.py
taylor_socfortress committed
Jul 10, 2023 at 16:47 UTC
f642427f31f62c0f38312250d835aec363509d0a
1 file changed
+201
backend/app/services/connectors/connectors.py
new
+201
@@ -0,0 +1,201 @@
1
+from app.models.connectors import connector_factory, Connector, ConnectorFactory
2
+from app.models.models import Connectors, connectors_schema, ConnectorsAvailable
3
+from sqlalchemy.exc import SQLAlchemyError
4
+from loguru import logger
5
+from flask import current_app
6
+
7
+
8
+class ConnectorService:
9
+ def __init__(self, db):
10
+ self.db = db
11
+
12
+ def update_connector_in_db(self, connector_id: int, updated_data: dict):
13
+ logger.info(f"Updating connector {connector_id} with data {updated_data}")
14
+ try:
15
+ connector = (
16
+ self.db.session.query(Connectors).filter_by(id=connector_id).first()
17
+ )
18
+ if connector:
19
+ for key, value in updated_data.items():
20
+ if hasattr(connector, key):
21
+ setattr(connector, key, value)
22
+
23
+ self.db.session.commit()
24
+ return {
25
+ "success": True,
26
+ "message": f"Connector {connector_id} updated successfully",
27
+ "connector_name": connector.connector_name,
28
+ }
29
+
30
+ else:
31
+ return {
32
+ "success": False,
33
+ "message": f"No connector found with id {connector_id}",
34
+ }
35
+ except SQLAlchemyError as e:
36
+ return {"success": False, "message": f"Database error occurred: {e}"}
37
+
38
+ def process_connector(self, connector_name: str):
39
+ """
40
+ Creates a connector instance, verifies the connection, and returns the connector details.
41
+
42
+ Args:
43
+ connector_name (str): The name of the connector to be processed.
44
+
45
+ Returns:
46
+ dict: A dictionary containing the name of the connector and the status of the connection verification.
47
+ """
48
+ connector_instance = connector_factory.create(connector_name, connector_name)
49
+ connection_successful = connector_instance.verify_connection()
50
+ connection_details = Connector.get_connector_info_from_db(connector_name)
51
+ logger.info(f"Connection details: {connection_details}")
52
+ return {"name": connector_name, **connection_successful, **connection_details}
53
+
54
+ def validate_connector_exists(self, connector_id: int):
55
+ """
56
+ Validates that a connector exists in the database. Returns a dictionary containing the validation status and a message indicating the status.
57
+
58
+ Args:
59
+ connector_id (int): The id of the connector to be validated.
60
+
61
+ Returns:
62
+ dict: A dictionary containing the validation status and a message indicating the status.
63
+ """
64
+ try:
65
+ connector = (
66
+ current_app.extensions["sqlalchemy"]
67
+ .db.session.query(Connectors)
68
+ .filter_by(id=connector_id)
69
+ .first()
70
+ )
71
+ if connector:
72
+ return {
73
+ "message": "Connector exists",
74
+ "connector_name": connector.connector_name,
75
+ "success": True,
76
+ }
77
+ else:
78
+ return {
79
+ "message": f"No connector found with id {connector_id}",
80
+ "success": False,
81
+ }
82
+ except SQLAlchemyError as e:
83
+ return {"message": f"Database error occurred: {e}", "success": False}
84
+
85
+ def update_connector(self, connector_id: int, updated_data: dict):
86
+ """
87
+ Updates a connector in the database.
88
+
89
+ Args:
90
+ connector_id (int): The id of the connector to be updated.
91
+ updated_data (dict): A dictionary containing the updated data for the connector.
92
+
93
+ Returns:
94
+ dict: A dictionary containing the success status and a message indicating the status. If the update operation was successful, it returns the connector name.
95
+ """
96
+ try:
97
+ connector = (
98
+ self.db.session.query(Connectors).filter_by(id=connector_id).first()
99
+ )
100
+ if connector is None:
101
+ return {
102
+ "message": f"No connector found with id {connector_id}",
103
+ "success": False,
104
+ }
105
+
106
+ for key, value in updated_data.items():
107
+ if hasattr(connector, key):
108
+ setattr(connector, key, value)
109
+
110
+ self.db.session.commit()
111
+
112
+ return {
113
+ "message": "Connector updated successfully",
114
+ "connector_name": connector.connector_name,
115
+ "success": True,
116
+ }
117
+
118
+ except SQLAlchemyError as e:
119
+ return {"message": f"Database error occurred: {e}", "success": False}
120
+
121
+ def verify_connector_connection(self, connector_id: int):
122
+ """
123
+ Verifies the connection of a connector.
124
+
125
+ Args:
126
+ connector_id (int): The id of the connector to be verified.
127
+
128
+ Returns:
129
+ dict: A dictionary containing the success status and a message indicating the status. If the verification operation was successful, it returns the connector name.
130
+ """
131
+ try:
132
+ connector = (
133
+ self.db.session.query(Connectors).filter_by(id=connector_id).first()
134
+ )
135
+ if connector is None:
136
+ return {
137
+ "message": f"No connector found with id {connector_id}",
138
+ "success": False,
139
+ }
140
+ connector_instance = connector_factory.create(
141
+ connector.connector_name, connector.connector_name
142
+ )
143
+ connection_successful = connector_instance.verify_connection()
144
+ # Connection successful: {'connectionSuccessful': False}
145
+ if connection_successful.get("connectionSuccessful", False) is False:
146
+ return {
147
+ "message": "Connector connection failed",
148
+ "connector_name": connector.connector_name,
149
+ "success": True,
150
+ **connection_successful,
151
+ }
152
+ return {
153
+ "message": "Connector connection verified successfully",
154
+ "connector_name": connector.connector_name,
155
+ "success": True,
156
+ **connection_successful,
157
+ }
158
+ except SQLAlchemyError as e:
159
+ return {"message": f"Database error occurred: {e}", "success": False}
160
+
161
+ def validate_request_data(self, request_data: dict):
162
+ """
163
+ Validates the request data to ensure `connector_url`, `connector_username` and `connector_password` are present. Returns a dictionary containing the validation status and a message indicating the status.
164
+
165
+ Args:
166
+ request_data (dict): A dictionary containing the request data.
167
+
168
+ Returns:
169
+ dict: A dictionary containing the validation status and a message indicating the status.
170
+ """
171
+ if (
172
+ request_data.get("connector_url", None)
173
+ and request_data.get("connector_username", None)
174
+ and request_data.get("connector_password", None)
175
+ ):
176
+ return {"message": "Request data is valid", "success": True}
177
+ else:
178
+ return {
179
+ "message": "Request data is invalid. Ensure connector_url, connector_username and connector_password are present",
180
+ "success": False,
181
+ }
182
+
183
+ def validate_request_data_api_key(self, request_data: dict):
184
+ """
185
+ Validates the request data to ensure `connector_url` and `connector_api_key` are present. Returns a dictionary containing the validation status and a message indicating the status.
186
+
187
+ Args:
188
+ request_data (dict): A dictionary containing the request data.
189
+
190
+ Returns:
191
+ dict: A dictionary containing the validation status and a message indicating the status.
192
+ """
193
+ if request_data.get("connector_url", None) and request_data.get(
194
+ "connector_api_key", None
195
+ ):
196
+ return {"message": "Request data is valid", "success": True}
197
+ else:
198
+ return {
199
+ "message": "Request data is invalid. Ensure connector_url and connector_api_key are present",
200
+ "success": False,
201
+ }