Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
603 lines (492 loc) · 25.1 KB
/
Copy pathmain.py
File metadata and controls
603 lines (492 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#!/usr/bin/env python3
"""
ECAL Data Cold Storage Migration Script
This script interactively migrates ECAL data from regular storage to cold storage
and updates the database with new storage locations.
The script will:
1. Ask user to select migration type (ECAL IDs, single date, or date range)
2. Fetch matching records from database
3. Copy entire directory structure to cold storage
4. Update database with new cold storage locations
5. Delete source files after successful migration (by default)
Usage:
python ecal_migration.py
"""
import logging
import sys
from datetime import datetime, date, timedelta
from typing import List, Optional, Tuple
import psycopg2
from psycopg2.extras import RealDictCursor
from azure.storage.blob import BlobServiceClient, BlobClient, generate_blob_sas, BlobSasPermissions
from azure.core.exceptions import ResourceNotFoundError
import os
from urllib.parse import urlparse, parse_qs
import time
import re
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ECALMigrationManager:
def __init__(self, db_config: dict, source_connection_string: str, cold_storage_connection_string: str, cold_storage_container: str):
"""
Initialize the migration manager.
Args:
db_config: Database connection configuration
source_connection_string: Source Azure storage connection string
cold_storage_connection_string: Cold storage Azure connection string
cold_storage_container: Name of the cold storage container
"""
self.db_config = db_config
self.cold_storage_container = cold_storage_container
# Initialize both storage clients using connection strings
self.source_blob_service_client = BlobServiceClient.from_connection_string(source_connection_string)
self.cold_storage_blob_service_client = BlobServiceClient.from_connection_string(cold_storage_connection_string)
# Extract account name and key from source connection string for SAS token generation
self.source_account_name, self.source_account_key = self._parse_connection_string(source_connection_string)
def _parse_connection_string(self, connection_string: str) -> Tuple[str, str]:
"""
Parse Azure storage connection string to extract account name and key.
Args:
connection_string: Azure storage connection string
Returns:
Tuple of (account_name, account_key)
"""
try:
# Parse connection string components
parts = connection_string.split(';')
account_name = None
account_key = None
for part in parts:
if part.startswith('AccountName='):
account_name = part.split('=', 1)[1]
elif part.startswith('AccountKey='):
account_key = part.split('=', 1)[1]
if not account_name or not account_key:
raise ValueError("Could not extract AccountName or AccountKey from connection string")
return account_name, account_key
except Exception as e:
logger.error(f"Failed to parse connection string: {e}")
raise ValueError(f"Invalid connection string format: {e}")
def get_db_connection(self):
"""Create and return database connection."""
try:
conn = psycopg2.connect(**self.db_config)
return conn
except Exception as e:
logger.error(f"Failed to connect to database: {e}")
raise
def fetch_ecal_records_by_ids(self, ecal_ids: List[str]) -> List[dict]:
"""Fetch ECAL records by ecal_id list."""
conn = self.get_db_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cursor:
placeholders = ','.join(['%s'] * len(ecal_ids))
query = f"""
SELECT ecal_id, ecal_name, recording_start_time, upload_start_time,
upload_end_time, map, size_gb, length, is_valid,
invalid_reason_id, recording_end_time
FROM ecal
WHERE ecal_id IN ({placeholders})
"""
cursor.execute(query, ecal_ids)
records = cursor.fetchall()
logger.info(f"Found {len(records)} records for provided ecal_ids")
return [dict(record) for record in records]
finally:
conn.close()
def fetch_ecal_records_by_date(self, start_date: date, end_date: Optional[date] = None) -> List[dict]:
"""Fetch ECAL records by recording_start_time date range."""
if end_date is None:
end_date = start_date
conn = self.get_db_connection()
try:
with conn.cursor(cursor_factory=RealDictCursor) as cursor:
query = """
SELECT ecal_id, ecal_name, recording_start_time, upload_start_time,
upload_end_time, map, size_gb, length, is_valid,
invalid_reason_id, recording_end_time
FROM ecal
WHERE DATE(recording_start_time) BETWEEN %s AND %s
ORDER BY recording_start_time
"""
cursor.execute(query, (start_date, end_date))
records = cursor.fetchall()
logger.info(f"Found {len(records)} records between {start_date} and {end_date}")
return [dict(record) for record in records]
finally:
conn.close()
def parse_blob_url(self, blob_url: str) -> Tuple[str, str]:
"""
Parse Azure blob URL to extract container and blob name.
Args:
blob_url: Full Azure blob URL
Returns:
Tuple of (container_name, blob_name)
"""
parsed_url = urlparse(blob_url)
path_parts = parsed_url.path.lstrip('/').split('/', 1)
if len(path_parts) < 2:
raise ValueError(f"Invalid blob URL format: {blob_url}")
return path_parts[0], path_parts[1]
def extract_directory_path(self, ecal_name: str) -> str:
"""
Extract directory path from ECAL name URL.
For URL like: https://datacollectionblob.blob.core.windows.net/ecal-batchstore/recording/2025-02-14/14_feb_2025_edited/2025-02-14_15-33-21.053-124-184/2025-02-14_15-33-21.053.ecalmeas
Returns: recording/2025-02-14/14_feb_2025_edited/2025-02-14_15-33-21.053-124-184
Args:
ecal_name: Full ECAL URL
Returns:
Directory path to copy
"""
try:
_, blob_path = self.parse_blob_url(ecal_name)
# Split the path and remove the filename to get directory
path_parts = blob_path.split('/')
if len(path_parts) > 1:
# Remove the last part (filename) to get directory path
directory_path = '/'.join(path_parts[:-1])
logger.info(f"Extracted directory path: {directory_path}")
return directory_path
else:
raise ValueError(f"Cannot extract directory from path: {blob_path}")
except Exception as e:
logger.error(f"Failed to extract directory path from {ecal_name}: {e}")
raise
def list_blobs_in_directory(self, container_name: str, directory_path: str) -> List[str]:
"""
List all blobs in a directory (prefix).
Args:
container_name: Source container name
directory_path: Directory path to list
Returns:
List of blob names in the directory
"""
try:
container_client = self.source_blob_service_client.get_container_client(container_name)
blob_names = []
# List all blobs with the directory prefix
blob_list = container_client.list_blobs(name_starts_with=directory_path)
for blob in blob_list:
blob_names.append(blob.name)
logger.info(f"Found {len(blob_names)} blobs in directory {directory_path}")
return blob_names
except Exception as e:
logger.error(f"Failed to list blobs in directory {directory_path}: {e}")
raise
def copy_directory_to_cold_storage(self, source_url: str, ecal_id: str) -> str:
"""
Copy entire directory from source storage account to cold storage account.
Args:
source_url: Source ECAL URL (used to determine directory)
ecal_id: ECAL ID for organizing in cold storage
Returns:
New cold storage base URL for the ECAL file
"""
try:
# Extract directory path from source URL
source_container, _ = self.parse_blob_url(source_url)
directory_path = self.extract_directory_path(source_url)
# List all blobs in the source directory
blob_names = self.list_blobs_in_directory(source_container, directory_path)
if not blob_names:
raise ValueError(f"No blobs found in directory: {directory_path}")
copied_files = 0
main_ecal_file_url = None
# Copy each blob in the directory
for blob_name in blob_names:
try:
# Create destination blob name (maintain directory structure under cold storage)
dest_blob_name = f"{blob_name}"
# Get source and destination blob clients
source_blob_client = self.source_blob_service_client.get_blob_client(
container=source_container,
blob=blob_name
)
dest_blob_client = self.cold_storage_blob_service_client.get_blob_client(
container=self.cold_storage_container,
blob=dest_blob_name
)
# Check if source blob exists
if not source_blob_client.exists():
logger.warning(f"Source blob not found, skipping: {blob_name}")
continue
# Copy blob using SAS token for cross-account authentication
logger.info(f"Copying {blob_name}...")
# Generate SAS token for source blob (valid for 2 hours)
sas_token = generate_blob_sas(
account_name=self.source_account_name,
container_name=source_container,
blob_name=blob_name,
account_key=self.source_account_key,
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=2)
)
# Create source URL with SAS token for cross-account copy
source_url_with_sas = f"{source_blob_client.url}?{sas_token}"
copy_operation = dest_blob_client.start_copy_from_url(source_url_with_sas)
# Wait for copy to complete
max_wait_time = 3600 # 1 hour max wait time per file
wait_time = 0
logger.info(f"Copy status for {blob_name}: {copy_operation}")
while (copy_operation.get('copy_status') == 'pending' or copy_operation.get('status') == 'pending') and wait_time < max_wait_time:
time.sleep(10)
wait_time += 10
try:
copy_props = dest_blob_client.get_blob_properties()
copy_operation = copy_props.copy
except Exception as e:
logger.warning(f"Could not get copy status for {blob_name}: {e}")
if wait_time >= max_wait_time:
raise Exception(f"Copy operation timed out for {blob_name}")
logger.info(f"Copy status for {blob_name}: {copy_operation}")
if copy_operation.get('status') != 'success':
raise Exception(f"Copy operation failed for {blob_name}: {copy_operation.get('status')}")
copied_files += 1
logger.info(f"Successfully copied: {blob_name}")
# Check if this is the main ECAL file (ends with .ecalmeas)
if blob_name.endswith('.ecalmeas'):
# Construct the new cold storage URL for this file
cold_storage_account = self.cold_storage_blob_service_client.account_name
main_ecal_file_url = f"https://{cold_storage_account}.blob.core.windows.net/{self.cold_storage_container}/{dest_blob_name}"
except Exception as e:
logger.error(f"Failed to copy blob {blob_name}: {e}")
raise
if main_ecal_file_url is None:
raise ValueError("Could not find main ECAL file (.ecalmeas) in the directory")
logger.info(f"Successfully copied {copied_files} files from directory {directory_path} to cold storage")
logger.info(f"Main ECAL file location: {main_ecal_file_url}")
return main_ecal_file_url
except Exception as e:
logger.error(f"Failed to copy directory to cold storage: {e}")
raise
def update_ecal_record(self, ecal_id: str, new_cold_storage_url: str):
"""Update ECAL record with new cold storage location."""
conn = self.get_db_connection()
try:
with conn.cursor() as cursor:
query = """
UPDATE ecal
SET ecal_name = %s
WHERE ecal_id = %s
"""
cursor.execute(query, (new_cold_storage_url, ecal_id))
if cursor.rowcount == 0:
raise Exception(f"No record found with ecal_id: {ecal_id}")
conn.commit()
logger.info(f"Updated ecal_id {ecal_id} with new cold storage location")
except Exception as e:
conn.rollback()
logger.error(f"Failed to update ecal_id {ecal_id}: {e}")
raise
finally:
conn.close()
def delete_source_directory(self, source_url: str):
"""Delete source directory after successful migration."""
try:
source_container, _ = self.parse_blob_url(source_url)
directory_path = self.extract_directory_path(source_url)
# List all blobs in the directory
blob_names = self.list_blobs_in_directory(source_container, directory_path)
deleted_count = 0
for blob_name in blob_names:
try:
source_blob_client = self.source_blob_service_client.get_blob_client(
container=source_container,
blob=blob_name
)
source_blob_client.delete_blob()
deleted_count += 1
logger.info(f"Deleted source blob: {blob_name}")
except Exception as e:
logger.warning(f"Failed to delete source blob {blob_name}: {e}")
logger.info(f"Deleted {deleted_count} files from source directory: {directory_path}")
except Exception as e:
logger.warning(f"Failed to delete source directory for {source_url}: {e}")
def migrate_records(self, records: List[dict], delete_source: bool = False):
"""
Migrate a list of ECAL records to cold storage.
Args:
records: List of ECAL records to migrate
delete_source: Whether to delete source directories after successful migration
"""
successful_migrations = 0
failed_migrations = 0
for record in records:
ecal_id = record['ecal_id']
source_url = record['ecal_name']
try:
logger.info(f"Processing ecal_id: {ecal_id}")
# Check if already in cold storage
if 'cold-storage' in source_url:
logger.info(f"ECAL {ecal_id} already in cold storage, skipping")
continue
# Copy entire directory to cold storage
new_cold_storage_url = self.copy_directory_to_cold_storage(source_url, ecal_id)
# Update database
self.update_ecal_record(ecal_id, new_cold_storage_url)
# Optionally delete source directory
if delete_source:
self.delete_source_directory(source_url)
successful_migrations += 1
logger.info(f"Successfully migrated ecal_id: {ecal_id}")
except Exception as e:
failed_migrations += 1
logger.error(f"Failed to migrate ecal_id {ecal_id}: {e}")
continue
logger.info(f"Migration complete. Success: {successful_migrations}, Failed: {failed_migrations}")
def get_user_input():
"""Get input from user interactively."""
print("\n" + "="*60)
print(" ECAL Data Cold Storage Migration Tool")
print("="*60)
print("\nSelect the type of migration:")
print("1. Migrate by ECAL IDs")
print("2. Migrate by single date")
print("3. Migrate by date range")
while True:
try:
choice = input("\nEnter your choice (1-3): ").strip()
if choice in ['1', '2', '3']:
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
sys.exit(0)
if choice == '1':
print("\nEnter ECAL IDs (comma-separated):")
ecal_ids_input = input("ECAL IDs: ").strip()
if not ecal_ids_input:
print("Error: No ECAL IDs provided.")
sys.exit(1)
ecal_ids = [id.strip() for id in ecal_ids_input.split(',') if id.strip()]
print(f"Selected ECAL IDs: {ecal_ids}")
return 'ecal_ids', ecal_ids
elif choice == '2':
print("\nEnter date (YYYY-MM-DD format):")
date_input = input("Date: ").strip()
try:
target_date = datetime.strptime(date_input, '%Y-%m-%d').date()
print(f"Selected date: {target_date}")
return 'single_date', target_date
except ValueError:
print("Error: Invalid date format. Please use YYYY-MM-DD format.")
sys.exit(1)
else: # choice == '3'
print("\nEnter date range:")
start_date_input = input("Start date (YYYY-MM-DD): ").strip()
end_date_input = input("End date (YYYY-MM-DD): ").strip()
try:
start_date = datetime.strptime(start_date_input, '%Y-%m-%d').date()
end_date = datetime.strptime(end_date_input, '%Y-%m-%d').date()
if start_date > end_date:
print("Error: Start date cannot be after end date.")
sys.exit(1)
print(f"Selected date range: {start_date} to {end_date}")
return 'date_range', (start_date, end_date)
except ValueError:
print("Error: Invalid date format. Please use YYYY-MM-DD format.")
sys.exit(1)
def main():
print("Starting ECAL Cold Storage Migration...")
# Configuration for database
db_config = {
'host': os.getenv('DB_HOST', 'localhost'),
'database': os.getenv('DB_NAME', 'ecal_db'),
'user': os.getenv('DB_USER', 'username'),
'password': os.getenv('DB_PASSWORD', 'password'),
'port': os.getenv('DB_PORT', 5432)
}
# Azure Storage Connection Strings
source_connection_string = os.getenv('SOURCE_AZURE_CONNECTION_STRING', '')
cold_storage_connection_string = os.getenv('COLD_STORAGE_CONNECTION_STRING', '')
cold_storage_container = os.getenv('COLD_STORAGE_CONTAINER', 'ecal-cold-storage')
# Validate configuration
required_vars = [
('DB_HOST', db_config['host']),
('DB_NAME', db_config['database']),
('DB_USER', db_config['user']),
('DB_PASSWORD', db_config['password']),
('SOURCE_AZURE_CONNECTION_STRING', source_connection_string),
('COLD_STORAGE_CONNECTION_STRING', cold_storage_connection_string)
]
missing_vars = []
for var_name, value in required_vars:
if not value or (isinstance(value, str) and (value == 'localhost' and var_name == 'DB_HOST') or
value in ['ecal_db', 'username', 'password'] or value == ''):
missing_vars.append(var_name)
if missing_vars:
print("Error: Missing or default values for required environment variables:")
for var in missing_vars:
print(f" - {var}")
print("\nPlease set the following environment variables:")
print(" DB_HOST, DB_NAME, DB_USER, DB_PASSWORD")
print(" SOURCE_AZURE_CONNECTION_STRING (source storage connection string)")
print(" COLD_STORAGE_CONNECTION_STRING (cold storage connection string)")
print(" COLD_STORAGE_CONTAINER (optional, defaults to 'ecal-cold-storage')")
print("\nConnection string format:")
print(" DefaultEndpointsProtocol=https;AccountName=<account>;AccountKey=<key>;EndpointSuffix=core.windows.net")
sys.exit(1)
# Initialize migration manager
try:
migration_manager = ECALMigrationManager(
db_config,
source_connection_string,
cold_storage_connection_string,
cold_storage_container
)
logger.info("Successfully initialized migration manager")
logger.info(f"Source storage account: {migration_manager.source_blob_service_client.account_name}")
logger.info(f"Cold storage account: {migration_manager.cold_storage_blob_service_client.account_name}")
except Exception as e:
logger.error(f"Failed to initialize migration manager: {e}")
sys.exit(1)
# Get user input
input_type, input_data = get_user_input()
try:
# Fetch records based on input type
print(f"\nFetching records from database...")
if input_type == 'ecal_ids':
records = migration_manager.fetch_ecal_records_by_ids(input_data)
elif input_type == 'single_date':
records = migration_manager.fetch_ecal_records_by_date(input_data)
else: # date_range
start_date, end_date = input_data
records = migration_manager.fetch_ecal_records_by_date(start_date, end_date)
if not records:
print("No records found matching the criteria.")
print("Migration cancelled.")
return
# Display summary and confirm
print(f"\nFound {len(records)} record(s) to migrate:")
print("-" * 50)
for i, record in enumerate(records[:5], 1): # Show first 5 records
print(f"{i}. ECAL ID: {record['ecal_id']}")
print(f" Recording Start: {record['recording_start_time']}")
print(f" Size: {record['size_gb']:.2f} GB")
print(f" Current Location: {record['ecal_name'][:80]}...")
if len(records) > 5:
print(f" ... and {len(records) - 5} more record(s)")
print(f"\nTotal size to migrate: {sum(r['size_gb'] for r in records):.2f} GB")
print("\nNOTE: This will copy ENTIRE DIRECTORIES, not just individual files.")
print("NOTE: Source directories will be DELETED after successful migration to cold storage.")
confirm = input("\nDo you want to proceed with the migration? (yes/no): ").strip().lower()
if confirm not in ['yes', 'y']:
print("Migration cancelled by user.")
return
# Migrate records with source deletion enabled by default
print(f"\nStarting migration process...")
print("This may take some time depending on the directory sizes...")
migration_manager.migrate_records(records, delete_source=True)
print(f"\nMigration process completed!")
print("Check the logs above for detailed results.")
except Exception as e:
logger.error(f"Migration failed: {e}")
print(f"\nMigration failed: {e}")
sys.exit(1)
if __name__ == '__main__':
main()