aic-utils 0.2__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {aic_utils-0.2 → aic_utils-0.5.0}/PKG-INFO +4 -4
- aic_utils-0.5.0/README.md +1 -0
- aic_utils-0.5.0/aic_utils/__init__.py +3 -0
- aic_utils-0.5.0/aic_utils/aic.py +337 -0
- aic_utils-0.5.0/aic_utils/gitlab_manager.py +109 -0
- {aic_utils-0.2 → aic_utils-0.5.0}/aic_utils.egg-info/PKG-INFO +4 -4
- {aic_utils-0.2 → aic_utils-0.5.0}/aic_utils.egg-info/SOURCES.txt +2 -1
- aic_utils-0.5.0/aic_utils.egg-info/requires.txt +1 -0
- {aic_utils-0.2 → aic_utils-0.5.0}/setup.py +3 -3
- aic_utils-0.2/README.md +0 -1
- aic_utils-0.2/aic_utils/__init__.py +0 -4
- aic_utils-0.2/aic_utils/aic_utils.py +0 -22
- aic_utils-0.2/aic_utils.egg-info/requires.txt +0 -1
- {aic_utils-0.2 → aic_utils-0.5.0}/aic_utils.egg-info/dependency_links.txt +0 -0
- {aic_utils-0.2 → aic_utils-0.5.0}/aic_utils.egg-info/top_level.txt +0 -0
- {aic_utils-0.2 → aic_utils-0.5.0}/setup.cfg +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: aic_utils
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: AIC API wrapper
|
|
5
5
|
Home-page: https://github.com/dylandoyle11/aic_utils
|
|
6
6
|
Author: Dylan D
|
|
7
7
|
Author-email: dylan.doyle@jdpa.com
|
|
@@ -9,6 +9,6 @@ Classifier: Programming Language :: Python :: 3
|
|
|
9
9
|
Classifier: License :: OSI Approved :: MIT License
|
|
10
10
|
Classifier: Operating System :: OS Independent
|
|
11
11
|
Description-Content-Type: text/markdown
|
|
12
|
-
Requires-Dist:
|
|
12
|
+
Requires-Dist: google-cloud-storage
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
FUNCTIONS FOR AIC
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
FUNCTIONS FOR AIC
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import json
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
from google.cloud import storage
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from .gitlab_manager import GitLabManager
|
|
8
|
+
|
|
9
|
+
class AIC():
|
|
10
|
+
timestamp = datetime.today().strftime('%Y%m%d')
|
|
11
|
+
|
|
12
|
+
def __init__(self, api_key, project, workspace, pipelines=[]):
|
|
13
|
+
self.base_url = 'https://prod.jdpower.ai/apis/core/v1'
|
|
14
|
+
self.api_key = api_key
|
|
15
|
+
self.headers = {
|
|
16
|
+
'accept': '*/*',
|
|
17
|
+
'api-key': api_key
|
|
18
|
+
}
|
|
19
|
+
self.project_id = self.get_project(project)
|
|
20
|
+
self.workspace_id = self.get_workspace(workspace)
|
|
21
|
+
self.drive_id = self.get_drive_id()
|
|
22
|
+
# self.get_data()
|
|
23
|
+
self.pipelines = self.pop_pipelines()
|
|
24
|
+
self.pipeline_configs = self.pop_pipeline_config(pipelines)
|
|
25
|
+
self.gitlab_manager = GitLabManager(self)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def get_data(self):
|
|
29
|
+
print(f'Project ID: {self.project_id}')
|
|
30
|
+
print(f'Workspace ID: {self.workspace_id}')
|
|
31
|
+
print(f'Drive ID: {self.drive_id}')
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_config(self):
|
|
35
|
+
return self.pipeline_configs
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_project(self, project):
|
|
39
|
+
url = f"{self.base_url}/projects"
|
|
40
|
+
response = requests.get(url, headers=self.headers)
|
|
41
|
+
for obj in response.json():
|
|
42
|
+
if obj['name'] == project:
|
|
43
|
+
return obj['$id']
|
|
44
|
+
raise Exception(f'No project with name {project} found')
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_workspace(self, workspace):
|
|
48
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces"
|
|
49
|
+
response = requests.get(url, headers=self.headers)
|
|
50
|
+
for obj in response.json():
|
|
51
|
+
if obj['name'] == workspace:
|
|
52
|
+
return obj['$id']
|
|
53
|
+
raise Exception(f'No workspace with name {workspace} found')
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def pop_pipelines(self):
|
|
57
|
+
pipelines = []
|
|
58
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/jobs"
|
|
59
|
+
response = requests.get(url, headers=self.headers)
|
|
60
|
+
for obj in response.json()['jobs']:
|
|
61
|
+
# print(f"Creating pipeline object: {obj['title']} ID: {obj['$id']}")
|
|
62
|
+
pipelines.append({'name':obj.get('title','NO TITLE'), 'id':obj['$id']})
|
|
63
|
+
return pipelines
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def fetch_pipeline_config(self, pipeline):
|
|
67
|
+
"""Fetch a single pipeline configuration."""
|
|
68
|
+
name = pipeline['name']
|
|
69
|
+
id = pipeline['id']
|
|
70
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/jobs/{id}"
|
|
71
|
+
print(f'Retrieving config for {name}...')
|
|
72
|
+
response = requests.get(url, headers=self.headers)
|
|
73
|
+
if response.status_code == 200:
|
|
74
|
+
data = response.json()
|
|
75
|
+
return {'name': name, 'jobConfig': data['jobConfig'], 'id':data['jobConfig']['$id']}
|
|
76
|
+
else:
|
|
77
|
+
print(f'Failed to fetch {name}: {response.status_code}')
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def pop_pipeline_config(self, pipelines):
|
|
82
|
+
"""Fetch configurations for the given pipelines in parallel using ThreadPoolExecutor."""
|
|
83
|
+
configs = []
|
|
84
|
+
with ThreadPoolExecutor() as executor:
|
|
85
|
+
pipeline_map = {pipeline_name.upper(): pipeline_name for pipeline_name in pipelines}
|
|
86
|
+
futures = {executor.submit(self.fetch_pipeline_config, pipeline): pipeline['name'] for pipeline in self.pipelines if pipeline['name'].upper() in pipeline_map}
|
|
87
|
+
for future in futures:
|
|
88
|
+
result = future.result()
|
|
89
|
+
if result:
|
|
90
|
+
configs.append(result)
|
|
91
|
+
else:
|
|
92
|
+
print(f'Pipeline {futures[future]} not found or failed to fetch.')
|
|
93
|
+
|
|
94
|
+
return configs
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_drive_id(self, drive_name="config"):
|
|
98
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/drives"
|
|
99
|
+
response = requests.get(url, headers=self.headers)
|
|
100
|
+
drives = response.json()
|
|
101
|
+
for drive in drives:
|
|
102
|
+
if drive['name'] == drive_name:
|
|
103
|
+
print(f'Drive location added: {drive_name}')
|
|
104
|
+
return drive['$id']
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def upload_json(self, file_name, json_content):
|
|
109
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/drives/{self.drive_id}/upload-file"
|
|
110
|
+
# Adjusting the files parameter to match the expected format
|
|
111
|
+
|
|
112
|
+
headers = {
|
|
113
|
+
'accept': '*/*', # Accept any response type
|
|
114
|
+
'api-key': self.api_key, # Include your API key
|
|
115
|
+
'Content-Type': 'text/plain' # Specify JSON content type
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
# Send the request with the json parameter to ensure JSON format
|
|
120
|
+
response = requests.post(url, headers=headers, json=json_content, params={'path': '.', 'fileName': file_name})
|
|
121
|
+
response.raise_for_status() # Check for HTTP errors
|
|
122
|
+
return response.json() # Return the JSON response from the server
|
|
123
|
+
except requests.exceptions.HTTPError as err:
|
|
124
|
+
print(f'HTTP error occurred: {err}') # Handle HTTP errors
|
|
125
|
+
print(f'Status Code: {response.status_code}')
|
|
126
|
+
print(f'Response Text: {response.text}')
|
|
127
|
+
except Exception as err:
|
|
128
|
+
print(f'Other error occurred: {err}') # Handle other exceptions
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# Method to push pipeline configs to GitLab
|
|
133
|
+
def push_to_gitlab(self, pipelines=[]):
|
|
134
|
+
for config in self.pipeline_configs:
|
|
135
|
+
file_content = json.dumps(config['jobConfig'], indent=4)
|
|
136
|
+
file_name = f"{config['name']}.json"
|
|
137
|
+
repo_name = config['name'].replace(" ", "_")
|
|
138
|
+
self.gitlab_manager.push_file_to_repo(repo_name, file_name, file_content)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def upload_configs_to_drive(self):
|
|
142
|
+
for config in self.pipeline_configs:
|
|
143
|
+
json = config['config']
|
|
144
|
+
file_name = f"{config['name']}_{AIC.timestamp}.json"
|
|
145
|
+
response = self.upload_json(file_name, json)
|
|
146
|
+
print(response)
|
|
147
|
+
|
|
148
|
+
def get_files_from_drive(self, drive_id=None):
|
|
149
|
+
if not drive_id:
|
|
150
|
+
drive_id = self.drive_id
|
|
151
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/drives/{drive_id}/files"
|
|
152
|
+
|
|
153
|
+
params = {
|
|
154
|
+
'path': '.','filePattern': '*.'}
|
|
155
|
+
response = requests.get(url, headers=self.headers, params=params)
|
|
156
|
+
if response.status_code == 200:
|
|
157
|
+
files = response.json()
|
|
158
|
+
for file in files:
|
|
159
|
+
print(file['items'])
|
|
160
|
+
else:
|
|
161
|
+
print(response.json())
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def download_file(self, drive_id, file_name):
|
|
165
|
+
"""
|
|
166
|
+
Download a file from the storage drive and return its content in memory.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
drive_id (str): The ID of the drive to download the file from.
|
|
170
|
+
file_name (str): The name of the file to be downloaded.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
str: The content of the file as a string if successful, otherwise None.
|
|
174
|
+
"""
|
|
175
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/drives/{drive_id}/files"
|
|
176
|
+
params = {
|
|
177
|
+
'path': '.',
|
|
178
|
+
'filePattern': file_name
|
|
179
|
+
}
|
|
180
|
+
response = requests.get(url, headers=self.headers, params=params)
|
|
181
|
+
|
|
182
|
+
if response.status_code == 200:
|
|
183
|
+
try:
|
|
184
|
+
files = response.json()
|
|
185
|
+
if files and 'items' in files and len(files['items']) > 0:
|
|
186
|
+
file_info = files['items'][0]
|
|
187
|
+
gs_path = file_info.get('gsPath')
|
|
188
|
+
|
|
189
|
+
if gs_path:
|
|
190
|
+
return self.download_from_gcs(gs_path)
|
|
191
|
+
else:
|
|
192
|
+
print(f"'gsPath' missing in file info: {file_info}")
|
|
193
|
+
else:
|
|
194
|
+
print(f"No matching files found for pattern: {file_name}. Response: {files}")
|
|
195
|
+
except ValueError as e:
|
|
196
|
+
print(f"Failed to parse JSON response: {e}")
|
|
197
|
+
else:
|
|
198
|
+
print(f"Failed to download file {file_name}: {response.status_code}")
|
|
199
|
+
print(f"Response Text: {response.text}")
|
|
200
|
+
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
def download_from_gcs(self, gs_path):
|
|
204
|
+
"""
|
|
205
|
+
Download content from Google Cloud Storage using the gs_path.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
gs_path (str): The Google Cloud Storage path (gs://bucket_name/path/to/file).
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
str: The content of the file as a string if successful, otherwise None.
|
|
212
|
+
"""
|
|
213
|
+
# Extract the bucket name and blob name from the gs_path
|
|
214
|
+
try:
|
|
215
|
+
gcs_client = storage.Client() # Ensure this client is correctly authenticated
|
|
216
|
+
bucket_name, blob_name = gs_path.replace("gs://", "").split("/", 1)
|
|
217
|
+
bucket = gcs_client.bucket(bucket_name)
|
|
218
|
+
blob = bucket.blob(blob_name)
|
|
219
|
+
|
|
220
|
+
# Download the content as a string
|
|
221
|
+
content = blob.download_as_text()
|
|
222
|
+
return content
|
|
223
|
+
except Exception as e:
|
|
224
|
+
print(f"Error downloading from GCS: {str(e)}")
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def delete_file(self, drive_id, file_id):
|
|
229
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/drives/{drive_id}/delete-files"
|
|
230
|
+
response = requests.post(url, headers=self.headers, json={"fileIds": [file_id]})
|
|
231
|
+
return response.status_code == 200
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@staticmethod
|
|
237
|
+
def push_source_code(AIC_prod, AIC_qa, prod_to_qa=False, qa_to_prod=False, pipelines=[]):
|
|
238
|
+
"""
|
|
239
|
+
Overwrite pipeline configurations between production and QA based on the specified direction
|
|
240
|
+
and only for the specified pipelines.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
AIC_prod: Instance of AIC with production pipeline configurations.
|
|
244
|
+
AIC_qa: Instance of AIC with QA pipeline configurations.
|
|
245
|
+
prod_to_qa: Boolean indicating whether to overwrite QA with production configurations.
|
|
246
|
+
qa_to_prod: Boolean indicating whether to overwrite production with QA configurations.
|
|
247
|
+
pipelines: List of pipeline names that should be processed for pushing configurations.
|
|
248
|
+
"""
|
|
249
|
+
if not pipelines:
|
|
250
|
+
raise ValueError("List of pipelines is empty. Please specify tables to push source code.")
|
|
251
|
+
|
|
252
|
+
if (prod_to_qa and qa_to_prod) or (not prod_to_qa and not qa_to_prod):
|
|
253
|
+
raise ValueError(f"Incorrect push configuration: prod_to_qa={prod_to_qa}, qa_to_prod={qa_to_prod}.")
|
|
254
|
+
for prod_pipeline in AIC_prod.pipeline_configs:
|
|
255
|
+
prod_name = prod_pipeline['name']
|
|
256
|
+
|
|
257
|
+
# Continue only if the production pipeline is in the specified pipelines list
|
|
258
|
+
if prod_name not in pipelines:
|
|
259
|
+
continue # Skip to the next pipeline if not in the list
|
|
260
|
+
|
|
261
|
+
for qa_pipeline in AIC_qa.pipeline_configs:
|
|
262
|
+
qa_name = qa_pipeline['name']
|
|
263
|
+
|
|
264
|
+
# Continue only if the QA pipeline is in the specified pipelines list
|
|
265
|
+
if qa_name not in pipelines:
|
|
266
|
+
continue # Skip if not in the list
|
|
267
|
+
|
|
268
|
+
if prod_name == qa_name:
|
|
269
|
+
if prod_to_qa:
|
|
270
|
+
# Overwrite QA config with Production config
|
|
271
|
+
print(f"Overwriting QA config with Production config for pipeline: {prod_name} -> {qa_name}")
|
|
272
|
+
original_id = qa_pipeline['jobConfig']['$id']
|
|
273
|
+
qa_pipeline['jobConfig'] = prod_pipeline['jobConfig']
|
|
274
|
+
# Update the $id in QA jobConfig to match the source $id
|
|
275
|
+
qa_pipeline['jobConfig']['$id'] = original_id
|
|
276
|
+
# Write the updated config to the QA pipeline
|
|
277
|
+
AIC_qa.write_config_to_pipeline(qa_pipeline)
|
|
278
|
+
|
|
279
|
+
elif qa_to_prod:
|
|
280
|
+
# Overwrite Production config with QA config
|
|
281
|
+
print(f"Overwriting Production config with QA config for pipeline: {qa_name} -> {prod_name}")
|
|
282
|
+
original_id = prod_pipeline['jobConfig']['$id']
|
|
283
|
+
prod_pipeline['jobConfig'] = qa_pipeline['jobConfig']
|
|
284
|
+
# Update the $id in Production jobConfig to match the source $id
|
|
285
|
+
prod_pipeline['jobConfig']['$id'] = original_id
|
|
286
|
+
# Write the updated config to the Production pipeline
|
|
287
|
+
AIC_prod.write_config_to_pipeline(prod_pipeline)
|
|
288
|
+
break # Stop searching once a match is found
|
|
289
|
+
else:
|
|
290
|
+
# If no matching pipeline is found
|
|
291
|
+
print(f'No matching pipelines for {prod_name}')
|
|
292
|
+
|
|
293
|
+
def write_config_to_pipeline(self, config):
|
|
294
|
+
"""
|
|
295
|
+
Upload the given configuration to the corresponding pipeline job.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
config: Dictionary containing the pipeline configuration and name.
|
|
299
|
+
"""
|
|
300
|
+
# Extract the job ID and configuration details
|
|
301
|
+
job_id = config.get('id') # Ensure 'id' is part of the config dictionary
|
|
302
|
+
job_config = config['jobConfig']
|
|
303
|
+
name = config['name']
|
|
304
|
+
|
|
305
|
+
# Construct the upload URL
|
|
306
|
+
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/jobs"
|
|
307
|
+
|
|
308
|
+
# Set headers for JSON content
|
|
309
|
+
headers = {
|
|
310
|
+
'accept': '*/*',
|
|
311
|
+
'api-key': self.api_key,
|
|
312
|
+
'Content-Type': 'application/json'
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
# Print debug information
|
|
316
|
+
print(f"Attempting to update the pipeline: {name}")
|
|
317
|
+
print(f"Job ID: {job_id}")
|
|
318
|
+
# print(f"URL: {url}")
|
|
319
|
+
# print(f"Headers: {headers}")
|
|
320
|
+
# print(f"Payload: {json.dumps(job_config, indent=4)}") # Print the payload for debugging
|
|
321
|
+
|
|
322
|
+
try:
|
|
323
|
+
# Send the request to update the pipeline configuration
|
|
324
|
+
response = requests.post(url, headers=headers, json=job_config)
|
|
325
|
+
response.raise_for_status() # Check for HTTP errors
|
|
326
|
+
print(f"Successfully updated the pipeline: {name}")
|
|
327
|
+
if response.json()['jobId'] != job_id:
|
|
328
|
+
print('PUSH CONFIGURATION INCORRECT. REVIEW DESTINATION TABLE')
|
|
329
|
+
print(response.json()) # Print the server's response
|
|
330
|
+
except requests.exceptions.HTTPError as err:
|
|
331
|
+
print(f'HTTP error occurred while updating pipeline {name}: {err}')
|
|
332
|
+
print(f'Status Code: {response.status_code}')
|
|
333
|
+
print(f'Response Text: {response.text}')
|
|
334
|
+
except Exception as err:
|
|
335
|
+
print(f'Other error occurred while updating pipeline {name}: {err}')
|
|
336
|
+
return None
|
|
337
|
+
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import requests
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
|
|
5
|
+
class GitLabManager:
|
|
6
|
+
def __init__(self, aic_instance, gitlab_token=None, gitlab_namespace='pin/pin-analytics/pin-fusion-2.0/pipelines', gitlab_base_url='https://git.autodatacorp.org/api/v4'):
|
|
7
|
+
self.aic = aic_instance
|
|
8
|
+
self.gitlab_base_url = gitlab_base_url
|
|
9
|
+
self.gitlab_namespace = gitlab_namespace
|
|
10
|
+
|
|
11
|
+
# Try to read GitLab token from storage if not provided
|
|
12
|
+
if gitlab_token:
|
|
13
|
+
self.gitlab_token = gitlab_token
|
|
14
|
+
else:
|
|
15
|
+
try:
|
|
16
|
+
self.gitlab_token = self.read_gitlab_token()
|
|
17
|
+
except ValueError as e:
|
|
18
|
+
print(f"Error: {e}")
|
|
19
|
+
print("GitLab token is required. Skipping GitLab integration.")
|
|
20
|
+
self.gitlab_token = None
|
|
21
|
+
return # Exit initialization if no token is found
|
|
22
|
+
|
|
23
|
+
self.headers = {
|
|
24
|
+
'Private-Token': self.gitlab_token,
|
|
25
|
+
'Content-Type': 'application/json'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
# Check and report the token expiration status immediately upon creation
|
|
29
|
+
if self.gitlab_token:
|
|
30
|
+
print('GitLab instance created.')
|
|
31
|
+
self.check_token_expiration()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def read_gitlab_token(self):
|
|
36
|
+
"""Reads the GitLab token from the storage drive."""
|
|
37
|
+
try:
|
|
38
|
+
content = self.aic.download_file(self.aic.drive_id, 'gitlab_token.txt')
|
|
39
|
+
if content:
|
|
40
|
+
return content.strip()
|
|
41
|
+
else:
|
|
42
|
+
raise ValueError("GitLab token file is empty or not found.")
|
|
43
|
+
except Exception as e:
|
|
44
|
+
print(f"Error reading GitLab token: {str(e)}")
|
|
45
|
+
raise ValueError("Failed to read GitLab token from storage.")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def generate_hash(self, content):
|
|
49
|
+
"""Generates a hash for the given content."""
|
|
50
|
+
return hashlib.md5(content.encode('utf-8')).hexdigest()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_existing_file_content(self, repo_name, file_name):
|
|
54
|
+
"""Fetches the existing content of a file from the specified repository in GitLab."""
|
|
55
|
+
project_url = f"{self.gitlab_base_url}/projects/{repo_name.replace('/', '%2F')}/repository/files/{file_name}?ref=main"
|
|
56
|
+
try:
|
|
57
|
+
response = requests.get(project_url, headers=self.headers)
|
|
58
|
+
if response.status_code == 200:
|
|
59
|
+
file_info = response.json()
|
|
60
|
+
return file_info.get('content')
|
|
61
|
+
else:
|
|
62
|
+
print(f"Failed to fetch existing file content: {response.status_code}")
|
|
63
|
+
print(f"Response: {response.text}")
|
|
64
|
+
return None
|
|
65
|
+
except Exception as e:
|
|
66
|
+
print(f"Error fetching existing file content: {str(e)}")
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def push_file(self, repo_name, file_name, file_content):
|
|
71
|
+
"""Pushes a file to the specified repository in GitLab, only if the content has changed."""
|
|
72
|
+
if self.use_hash_comparison:
|
|
73
|
+
# Fetch existing content and compare hashes
|
|
74
|
+
existing_content = self.get_existing_file_content(repo_name, file_name)
|
|
75
|
+
if existing_content:
|
|
76
|
+
existing_hash = self.generate_hash(existing_content)
|
|
77
|
+
current_hash = self.generate_hash(file_content)
|
|
78
|
+
|
|
79
|
+
# Compare hashes
|
|
80
|
+
if existing_hash == current_hash:
|
|
81
|
+
print(f"No changes detected for {file_name}. Skipping push.")
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
print(f"Configuration has changed for {file_name}. Pushing update.")
|
|
85
|
+
project_url = f"{self.gitlab_base_url}/projects/{repo_name.replace('/', '%2F')}/repository/files/{file_name}"
|
|
86
|
+
data = {
|
|
87
|
+
'branch': 'main',
|
|
88
|
+
'content': file_content,
|
|
89
|
+
'commit_message': f"Update {file_name} - {datetime.now().strftime('%Y-%m-%d')}"
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
# Attempt to create or update the file
|
|
94
|
+
response = requests.post(project_url, headers=self.headers, json=data)
|
|
95
|
+
if response.status_code == 201:
|
|
96
|
+
print(f"Successfully created {file_name} in repository: {repo_name}")
|
|
97
|
+
elif response.status_code == 400 and "already exists" in response.text:
|
|
98
|
+
# File exists; try updating instead
|
|
99
|
+
response = requests.put(project_url, headers=self.headers, json=data)
|
|
100
|
+
if response.status_code == 200:
|
|
101
|
+
print(f"Successfully updated {file_name} in repository: {repo_name}")
|
|
102
|
+
else:
|
|
103
|
+
print(f"Failed to update {file_name} in repository: {repo_name}")
|
|
104
|
+
print(f"Response: {response.text}")
|
|
105
|
+
else:
|
|
106
|
+
print(f"Failed to push {file_name} to repository: {repo_name}")
|
|
107
|
+
print(f"Response: {response.text}")
|
|
108
|
+
except Exception as e:
|
|
109
|
+
print(f"Error pushing file to GitLab: {str(e)}")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: aic_utils
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: AIC API wrapper
|
|
5
5
|
Home-page: https://github.com/dylandoyle11/aic_utils
|
|
6
6
|
Author: Dylan D
|
|
7
7
|
Author-email: dylan.doyle@jdpa.com
|
|
@@ -9,6 +9,6 @@ Classifier: Programming Language :: Python :: 3
|
|
|
9
9
|
Classifier: License :: OSI Approved :: MIT License
|
|
10
10
|
Classifier: Operating System :: OS Independent
|
|
11
11
|
Description-Content-Type: text/markdown
|
|
12
|
-
Requires-Dist:
|
|
12
|
+
Requires-Dist: google-cloud-storage
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
FUNCTIONS FOR AIC
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
google-cloud-storage
|
|
@@ -4,15 +4,15 @@ from setuptools import setup, find_packages
|
|
|
4
4
|
|
|
5
5
|
setup(
|
|
6
6
|
name='aic_utils',
|
|
7
|
-
version='0.
|
|
7
|
+
version='0.5.0',
|
|
8
8
|
packages=find_packages(),
|
|
9
9
|
install_requires=[
|
|
10
|
-
'
|
|
10
|
+
'google-cloud-storage',
|
|
11
11
|
# Add other dependencies here
|
|
12
12
|
],
|
|
13
13
|
author='Dylan D',
|
|
14
14
|
author_email='dylan.doyle@jdpa.com',
|
|
15
|
-
description='
|
|
15
|
+
description='AIC API wrapper',
|
|
16
16
|
long_description=open('README.md').read(),
|
|
17
17
|
long_description_content_type='text/markdown',
|
|
18
18
|
url='https://github.com/dylandoyle11/aic_utils',
|
aic_utils-0.2/README.md
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
TEST
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
# aic_utils.py
|
|
2
|
-
|
|
3
|
-
import pandas as pd
|
|
4
|
-
|
|
5
|
-
def get_dataset_id(alias, QA):
|
|
6
|
-
# MAP WRITES TO QA OR PROD TABLES
|
|
7
|
-
df = pyspark_utils.get_pandas_from_aic_table('Silver',
|
|
8
|
-
'LKP_QA_TABLE_MAPPING')
|
|
9
|
-
row = df[df['alias'] == alias]
|
|
10
|
-
|
|
11
|
-
# Choose the appropriate column based on QA flag
|
|
12
|
-
if QA:
|
|
13
|
-
target_col = 'qa_dataset'
|
|
14
|
-
else:
|
|
15
|
-
target_col = 'prod_dataset'
|
|
16
|
-
|
|
17
|
-
# Return the dataset ID
|
|
18
|
-
if not row.empty:
|
|
19
|
-
return row.iloc[0][target_col]
|
|
20
|
-
else:
|
|
21
|
-
raise ValueError("Alias not found in mapping table")
|
|
22
|
-
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
pandas
|
|
File without changes
|
|
File without changes
|
|
File without changes
|