| 1 |
|
| 2 |
import sys |
| 3 |
import os |
| 4 |
import gitlab |
| 5 |
from sqlalchemy import text |
| 6 |
from sqlalchemy import create_engine, select, MetaData, Table, insert |
| 7 |
import concurrent.futures |
| 8 |
from functools import partial |
| 9 |
from gitlab.exceptions import GitlabGetError |
| 10 |
import concurrent.futures |
| 11 |
import multiprocessing |
| 12 |
from datetime import datetime, timedelta |
| 13 |
import logging |
| 14 |
import time |
| 15 |
from sqlalchemy.ext.declarative import declarative_base |
| 16 |
from sqlalchemy.orm import sessionmaker |
| 17 |
import json |
| 18 |
|
| 19 |
import configparser |
| 20 |
config = configparser.ConfigParser() |
| 21 |
|
| 22 |
|
| 23 |
s_config = """ |
| 24 |
[GITLAB] |
| 25 |
xxxxx |
| 26 |
xxxxx |
| 27 |
|
| 28 |
[HGITLAB] |
| 29 |
xxxxx |
| 30 |
xxxxx |
| 31 |
|
| 32 |
[GITLAB2] |
| 33 |
xxxxx |
| 34 |
xxxxx |
| 35 |
|
| 36 |
[DATABASE] |
| 37 |
xxxxx |
| 38 |
xxxxx |
| 39 |
""" |
| 40 |
|
| 41 |
config.read_string(s_config) |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
def main(): |
| 46 |
"""main function that runs the analyze method based on schedule |
| 47 |
# """ |
| 48 |
|
| 49 |
engine = connectDB() |
| 50 |
|
| 51 |
# or_code = sys.argv[1] |
| 52 |
# Configure the logger |
| 53 |
log_file_path = 'outputAllOrCode.log' |
| 54 |
logger = logging.getLogger(__name__) |
| 55 |
logger.setLevel(logging.INFO) |
| 56 |
file_handler = logging.FileHandler(log_file_path) |
| 57 |
file_handler.setLevel(logging.INFO) |
| 58 |
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') |
| 59 |
file_handler.setFormatter(formatter) |
| 60 |
logger.addHandler(file_handler) |
| 61 |
print("Automatically Mapping Technology and extentions from Repos to DB table") |
| 62 |
logger.info("Automatically Mapping Technology and extentions from Repos to DB table") |
| 63 |
|
| 64 |
orcode_query = "(select distinct(or_code)\ |
| 65 |
from master_orcode mo left join tbl_project_orcode_mapping tpo on(tpo.orcode_id = mo.id) left join projects_master pm\ |
| 66 |
on(pm.project_id = tpo.project_id) where mo.is_del != 1 and perspective in ('LINES_OF_CODE', 'COMBINATION') and \ |
| 67 |
mo.or_code in (select or_code from master_isg_projects where status != 'Closed'))" |
| 68 |
orcodes = engine.execute(orcode_query) |
| 69 |
orcode_list = [result[0] for result in orcodes] |
| 70 |
|
| 71 |
for orcode in orcode_list: |
| 72 |
print(f"Now Running for orcode {orcode}") |
| 73 |
mapTechExtensions(engine,orcode,logger) |
| 74 |
|
| 75 |
print("Script Executed now exiting code") |
| 76 |
logger.info("Script Executed now exiting code") |
| 77 |
exit(0) |
| 78 |
|
| 79 |
|
| 80 |
def mapTechExtensions(engine,or_code,logger): |
| 81 |
|
| 82 |
|
| 83 |
try: |
| 84 |
project_query = text("select git_project_id, path, domain from projects_master where project_id in \ |
| 85 |
(select project_id from tbl_project_orcode_mapping where orcode_id in\ |
| 86 |
(select id from master_orcode where or_code in (:or_code)))") |
| 87 |
result = engine.execute(project_query, or_code=or_code) |
| 88 |
rows = result.fetchall() |
| 89 |
|
| 90 |
# Create a metadata object |
| 91 |
metadata = MetaData(bind=engine) |
| 92 |
|
| 93 |
# Define the tbl_orcode_extension_mapping table |
| 94 |
tbl_orcode_extension_mapping = Table('tbl_orcode_extension_mapping', metadata, autoload=True) |
| 95 |
master_technology_extension_mapping = Table('master_technology_extension_mapping', metadata, autoload=True) |
| 96 |
tbl_extension_autosync_error_log = Table('tbl_extension_autosync_error_log', metadata, autoload=True) |
| 97 |
current_date = datetime.now() |
| 98 |
# Calculate the start date of the week (Monday) |
| 99 |
start_of_week = current_date - timedelta(days=current_date.weekday()) |
| 100 |
# Set the activation_date variable |
| 101 |
activation_date = start_of_week.date() |
| 102 |
disabled_extension_query = text("SELECT extension FROM master_disabled_extensions WHERE is_del = 0") |
| 103 |
disabled_extensions = engine.execute(disabled_extension_query) |
| 104 |
by_default_disabled_ext = [result[0] for result in disabled_extensions] |
| 105 |
# by_default_disabled_ext=['.txt','.log','.png','.jpeg','.tmp','.bak','.swp','.dmp'] |
| 106 |
official_domain = ['https://gitlab.kpit.com', 'https://h-gitlab.kpit.com', 'https://gitlab2.kpit.com'] |
| 107 |
|
| 108 |
for row in rows: |
| 109 |
if row: |
| 110 |
git_project_id, path, domain = row[0], row[1], row[2] |
| 111 |
|
| 112 |
if domain not in official_domain: |
| 113 |
continue |
| 114 |
# Create a connection |
| 115 |
conn = engine.connect() |
| 116 |
try: |
| 117 |
gl = connectGit(domain) |
| 118 |
project = gl.projects.get(git_project_id) |
| 119 |
except Exception as e: |
| 120 |
if(e.error_message=='404 Project Not Found'): |
| 121 |
# Insert error log into the tbl_extension_autosync_error_log table |
| 122 |
stmt = select([tbl_extension_autosync_error_log]).where( |
| 123 |
(tbl_extension_autosync_error_log.c.or_code == or_code) & |
| 124 |
(tbl_extension_autosync_error_log.c.git_project_id == git_project_id) |
| 125 |
) |
| 126 |
extensionResult = conn.execute(stmt) |
| 127 |
if not extensionResult.fetchone(): |
| 128 |
stmt = insert(tbl_extension_autosync_error_log).values( |
| 129 |
git_project_id=git_project_id, |
| 130 |
or_code=or_code, |
| 131 |
path=path, |
| 132 |
domain=domain, |
| 133 |
description=e.error_message |
| 134 |
) |
| 135 |
conn.execute(stmt) |
| 136 |
extensionResult.close() |
| 137 |
logger.error(f"{e}") |
| 138 |
|
| 139 |
# Set a timeout for list_file_extensions_all_branches |
| 140 |
timeout = 300 # 10 minutes in seconds |
| 141 |
# List project repository files |
| 142 |
# all_branch_extensions = list_file_extensions_all_branches(project) |
| 143 |
try: |
| 144 |
# Use multiprocessing.Pool to run the function with a timeout |
| 145 |
with multiprocessing.Pool(processes=1) as pool: |
| 146 |
result = pool.apply_async(list_file_extensions_all_branches, (project,)) |
| 147 |
all_branch_extensions = result.get(timeout=timeout) |
| 148 |
|
| 149 |
# Continue processing with 'all_branch_extensions' as needed |
| 150 |
print(all_branch_extensions) |
| 151 |
|
| 152 |
except multiprocessing.TimeoutError: |
| 153 |
print(f"Timeout occurred for project {git_project_id}. Continuing with the next project.") |
| 154 |
logger.error(f"Timeout occurred for project {git_project_id}. Continuing with the next project.") |
| 155 |
# Insert error log into the tbl_extension_autosync_error_log table |
| 156 |
stmt = select([tbl_extension_autosync_error_log]).where( |
| 157 |
(tbl_extension_autosync_error_log.c.or_code == or_code) & |
| 158 |
(tbl_extension_autosync_error_log.c.git_project_id == git_project_id) |
| 159 |
) |
| 160 |
extensionResult = conn.execute(stmt) |
| 161 |
if not extensionResult.fetchone(): |
| 162 |
stmt = insert(tbl_extension_autosync_error_log).values( |
| 163 |
git_project_id = git_project_id, |
| 164 |
or_code=or_code, |
| 165 |
path=path, |
| 166 |
domain=domain, |
| 167 |
description="Unable to fetch data from gitlab Timeout Error Occurred" |
| 168 |
) |
| 169 |
conn.execute(stmt) |
| 170 |
extensionResult.close() |
| 171 |
except Exception as e: |
| 172 |
print(f"An error occurred for project {git_project_id}: {e}") |
| 173 |
logger.error(f"An error occurred for project {git_project_id}: {e}") |
| 174 |
|
| 175 |
|
| 176 |
# with open('D:/CTO Project(Insights)/automateTechnologyExtensionMapping/tecnology.txt', 'r') as file: |
| 177 |
# TechnologyData = json.load(file) |
| 178 |
|
| 179 |
with open('/home/hrishikeshp/zdd/automateTechExtMapping/tecnology.txt', 'r') as file: |
| 180 |
TechnologyData = json.load(file) |
| 181 |
|
| 182 |
|
| 183 |
# is_active = 1 # extension should be set as active |
| 184 |
is_active = 0 # by default newly added extension should be set as disabled |
| 185 |
# Insert data into the table |
| 186 |
for extension in all_branch_extensions: |
| 187 |
name = "Misc Technology" # Default name if extension is not found |
| 188 |
type = "Misc Type" |
| 189 |
for tech_info in TechnologyData: |
| 190 |
if extension in tech_info['extensions']: |
| 191 |
name = tech_info['name'] |
| 192 |
type = tech_info['type'] |
| 193 |
break |
| 194 |
|
| 195 |
# Check if the combination of or_code and extension already exists |
| 196 |
stmt = select([tbl_orcode_extension_mapping]).where( |
| 197 |
(tbl_orcode_extension_mapping.c.or_code == or_code) & |
| 198 |
(tbl_orcode_extension_mapping.c.extension == extension) |
| 199 |
) |
| 200 |
extensionResult = conn.execute(stmt) |
| 201 |
|
| 202 |
|
| 203 |
# Insert into the tbl_orcode_extension_mapping table only if the combination does not exist |
| 204 |
if not extensionResult.fetchone(): |
| 205 |
# Insert into the tbl_orcode_extension_mapping table |
| 206 |
if extension in by_default_disabled_ext: |
| 207 |
stmt = insert(tbl_orcode_extension_mapping).values( |
| 208 |
or_code=or_code, |
| 209 |
technology_name=name, |
| 210 |
extension=extension, |
| 211 |
is_active=0, |
| 212 |
activation_date=activation_date, |
| 213 |
deactivation_date=activation_date |
| 214 |
) |
| 215 |
conn.execute(stmt) |
| 216 |
else: |
| 217 |
stmt = insert(tbl_orcode_extension_mapping).values( |
| 218 |
or_code=or_code, |
| 219 |
technology_name=name, |
| 220 |
extension=extension, |
| 221 |
is_active=is_active, |
| 222 |
activation_date=activation_date |
| 223 |
) |
| 224 |
conn.execute(stmt) |
| 225 |
|
| 226 |
extensionResult.close() |
| 227 |
|
| 228 |
# Check if the extension already exists in master extension table |
| 229 |
stmt2 = select([master_technology_extension_mapping]).where( |
| 230 |
(master_technology_extension_mapping.c.extension == extension) |
| 231 |
) |
| 232 |
masterTblExtensionResult = conn.execute(stmt2) |
| 233 |
|
| 234 |
# Insert into the tbl_orcode_extension_mapping table only if the combination does not exist |
| 235 |
if not masterTblExtensionResult.fetchone(): |
| 236 |
# Insert into the tbl_orcode_extension_mapping table |
| 237 |
stmt2 = insert(master_technology_extension_mapping).values( |
| 238 |
technology_name=name, |
| 239 |
technology_type=type, |
| 240 |
extension=extension, |
| 241 |
) |
| 242 |
conn.execute(stmt2) |
| 243 |
|
| 244 |
masterTblExtensionResult.close() |
| 245 |
|
| 246 |
# Close the database connection |
| 247 |
conn.close() |
| 248 |
# Print the file extensions |
| 249 |
print("Done For ",path) |
| 250 |
logger.info(f"Done for {path}") |
| 251 |
gl = None |
| 252 |
# for ext in all_branch_extensions: |
| 253 |
# print(ext) |
| 254 |
|
| 255 |
|
| 256 |
except Exception as e: |
| 257 |
print(e) |
| 258 |
logger.error(f"{e} error for or_code{or_code}") |
| 259 |
|
| 260 |
def list_file_extensions_all_branches(project): |
| 261 |
# Get a list of all branch names in the repository |
| 262 |
branches = project.branches.list(get_all=True) |
| 263 |
branches2 = list(map(lambda branch: branch.name, branches)) |
| 264 |
|
| 265 |
max_threads = 10 |
| 266 |
|
| 267 |
# Create a partial function with 'project' as a fixed argument |
| 268 |
# partial_func = partial(list_file_extensions_recursive, project=project) |
| 269 |
partial_func = partial(wrapper_function, project=project) |
| 270 |
|
| 271 |
|
| 272 |
try: |
| 273 |
# Create a ThreadPoolExecutor with the specified number of threads |
| 274 |
with concurrent.futures.ThreadPoolExecutor(max_threads) as executor: |
| 275 |
# Map the process_branch function to the branch_names list, running them in parallel |
| 276 |
# results = executor.map(partial_func, branches2) |
| 277 |
results = executor.map(partial_func, branches2) |
| 278 |
except GitlabGetError as e: |
| 279 |
# Handle the GitLab Get Error (HTTP 503) here |
| 280 |
print(f"GitLab server not responding. Error: {e}") |
| 281 |
except Exception as e: |
| 282 |
# Handle other exceptions here |
| 283 |
print(f"An error occurred: {e}") |
| 284 |
|
| 285 |
all_branch_extension_list = [] |
| 286 |
for result in results: |
| 287 |
all_branch_extension_list.extend(result) |
| 288 |
|
| 289 |
# Remove duplicates and empty strings |
| 290 |
unique_extensions = list(set(all_branch_extension_list)) |
| 291 |
if '' in unique_extensions: |
| 292 |
unique_extensions.remove('') |
| 293 |
|
| 294 |
return unique_extensions |
| 295 |
|
| 296 |
def wrapper_function(branch_name, project): |
| 297 |
try: |
| 298 |
return list_file_extensions_recursive(project, branch_name) |
| 299 |
except GitlabGetError as e: |
| 300 |
# Handle the GitLab Get Error (HTTP 503) specifically for this function |
| 301 |
print(f"GitLab server not responding for branch {branch_name}. Error: {e}") |
| 302 |
return set() # Return an empty set or handle it as appropriate |
| 303 |
|
| 304 |
def list_file_extensions_recursive(project,branch_name, path=""): |
| 305 |
# Initialize a set to store unique file extensions |
| 306 |
file_extensions = set() |
| 307 |
|
| 308 |
try: |
| 309 |
|
| 310 |
# List project repository files and folders for the specified branch |
| 311 |
items = project.repository_tree(path=path, ref=branch_name,get_all=True) |
| 312 |
|
| 313 |
# Iterate through the files and folders |
| 314 |
for item in items: |
| 315 |
if item["type"] == "blob": |
| 316 |
file_name = item["name"] |
| 317 |
file_extension = os.path.splitext(file_name)[1] |
| 318 |
file_extension = file_extension.lower() |
| 319 |
file_extensions.add(file_extension) |
| 320 |
elif item["type"] == "tree": |
| 321 |
# Recursively traverse into subfolders |
| 322 |
subfolder_path = os.path.join(path, item["name"]).replace("\\", "/") |
| 323 |
subfolder_extensions = list_file_extensions_recursive(project,branch_name,subfolder_path) |
| 324 |
file_extensions.update(subfolder_extensions) |
| 325 |
|
| 326 |
return file_extensions |
| 327 |
except GitlabGetError as e: |
| 328 |
# Handle the GitLab Get Error (HTTP 503) specifically for this function |
| 329 |
# print(f"GitLab server not responding for branch {branch_name}. Error: {e}") |
| 330 |
raise # Re-raise the exception to be caught in the wrapper_function |
| 331 |
except Exception as e: |
| 332 |
# Handle other exceptions here |
| 333 |
# print(f"An error occurred for branch {branch_name}: {e}") |
| 334 |
raise # Re-raise the exception to be caught in the wrapper_function |
| 335 |
|
| 336 |
def connectDB(): |
| 337 |
url = config.get('DATABASE', 'engine') |
| 338 |
db = config.get('DATABASE', 'db') |
| 339 |
try: |
| 340 |
engine = create_engine(url + db) |
| 341 |
return engine |
| 342 |
except Exception as ex: |
| 343 |
# print(ex) |
| 344 |
pass |
| 345 |
|
| 346 |
|
| 347 |
def domain_selector(domain): |
| 348 |
if 'https://gitlab2.kpit.com' == domain: |
| 349 |
return 'GITLAB2' |
| 350 |
if 'https://gitlab.kpit.com' == domain: |
| 351 |
return 'GITLAB' |
| 352 |
if 'https://h-gitlab.kpit.com' == domain: |
| 353 |
return 'HGITLAB' |
| 354 |
|
| 355 |
def connectGit(domain): |
| 356 |
domain_name = domain_selector(domain) |
| 357 |
# print ("domain name",domain_name) |
| 358 |
token = config.get(domain_name, 'private_token') |
| 359 |
url = config.get(domain_name, 'url') |
| 360 |
# print (token,url) |
| 361 |
try: |
| 362 |
gl = gitlab.Gitlab(url, private_token=token) |
| 363 |
return gl |
| 364 |
except Exception as ex: |
| 365 |
# print(ex) |
| 366 |
pass |
| 367 |
|
| 368 |
def newConnectGitFn(domain): |
| 369 |
domain_name = domain_selector(domain) |
| 370 |
# print ("domain name",domain_name) |
| 371 |
token = config.get(domain_name, 'private_token') |
| 372 |
url = config.get(domain_name, 'url') |
| 373 |
# print (token,url) |
| 374 |
try: |
| 375 |
gl = gitlab.Gitlab(url, private_token=token) |
| 376 |
return gl |
| 377 |
except Exception as ex: |
| 378 |
# print(ex) |
| 379 |
pass |
| 380 |
|
| 381 |
def create_table(conn, table_name): |
| 382 |
sql = f""" CREATE TABLE IF NOT EXISTS {table_name} ( |
| 383 |
id integer PRIMARY KEY, |
| 384 |
code text NOT NULL |
| 385 |
); |
| 386 |
""" |
| 387 |
try: |
| 388 |
c = conn.cursor() |
| 389 |
c.execute(sql) |
| 390 |
except Error as e: |
| 391 |
print(e) |
| 392 |
|
| 393 |
if __name__ == '__main__': |
| 394 |
main() |