-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
264 lines (221 loc) · 10.1 KB
/
lambda_function.py
File metadata and controls
264 lines (221 loc) · 10.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
import boto3
import json
from datetime import datetime
import time
def lambda_handler(event, context):
"""
Runs S3 inventory analysis and saves results as CSV files with proper headers
Uses simplified path structure: source-stats/type/YYYYMMDD.csv
"""
athena = boto3.client('athena', region_name='us-west-2')
s3 = boto3.client('s3', region_name='us-west-2')
# Configuration - Update these for your environment
results_bucket = 'us-west-2.opendata.source.coop'
results_prefix = 'source/source-stats/'
database = 'source_stats'
workgroup = 'primary'
# Use the most recent inventory date (June 29, 2025)
date_str = '250629'
print(f"Starting analysis for inventory date {date_str}")
# Define queries with proper headers and deduplication
queries = {
'accounts': {
'query': '''
SELECT
split_part(key, '/', 1) as account,
COUNT(DISTINCT split_part(key, '/', 2)) as repositories,
COUNT(*) as objects,
round(SUM(size) / 1024.0 / 1024.0 / 1024.0, 2) as storage_gb,
round(AVG(size) / 1024.0 / 1024.0, 2) as avg_object_size_mb,
MIN(last_modified_date) as oldest_file,
MAX(last_modified_date) as newest_file
FROM (
SELECT DISTINCT key, size, last_modified_date
FROM inventory_data
WHERE key LIKE '%/%'
) deduplicated
GROUP BY split_part(key, '/', 1)
ORDER BY storage_gb DESC
''',
'header': 'account,repositories,objects,storage_gb,avg_object_size_mb,oldest_file,newest_file'
},
'repositories': {
'query': '''
SELECT
split_part(key, '/', 1) as account,
split_part(key, '/', 2) as repository,
COUNT(*) as objects,
round(SUM(size) / 1024.0 / 1024.0 / 1024.0, 2) as storage_gb,
round(AVG(size) / 1024.0 / 1024.0, 2) as avg_object_size_mb,
MIN(last_modified_date) as oldest_file,
MAX(last_modified_date) as newest_file
FROM (
SELECT DISTINCT key, size, last_modified_date
FROM inventory_data
WHERE key LIKE '%/%/%'
) deduplicated
GROUP BY split_part(key, '/', 1), split_part(key, '/', 2)
ORDER BY storage_gb DESC
''',
'header': 'account,repository,objects,storage_gb,avg_object_size_mb,oldest_file,newest_file'
},
'source': {
'query': '''
WITH deduplicated_data AS (
SELECT DISTINCT key, size, last_modified_date
FROM inventory_data
WHERE key LIKE '%/%/%'
)
SELECT
'Total Accounts' as metric,
CAST(COUNT(DISTINCT split_part(key, '/', 1)) AS VARCHAR) as value
FROM deduplicated_data
UNION ALL
SELECT
'Total Repositories',
CAST(COUNT(DISTINCT split_part(key, '/', 1) || '/' || split_part(key, '/', 2)) AS VARCHAR)
FROM deduplicated_data
UNION ALL
SELECT
'Total Objects',
CAST(COUNT(*) AS VARCHAR)
FROM deduplicated_data
UNION ALL
SELECT
'Total Storage (TB)',
CAST(round(SUM(size) / 1024.0 / 1024.0 / 1024.0 / 1024.0, 2) AS VARCHAR)
FROM deduplicated_data
''',
'header': 'metric,value'
}
}
def wait_for_query_completion(execution_id, timeout=300):
"""Wait for Athena query to complete"""
start_time = time.time()
while time.time() - start_time < timeout:
response = athena.get_query_execution(QueryExecutionId=execution_id)
status = response['QueryExecution']['Status']['State']
if status in ['SUCCEEDED']:
return True
elif status in ['FAILED', 'CANCELLED']:
print(f"Query {execution_id} failed: {response['QueryExecution']['Status']}")
return False
time.sleep(10)
print(f"Query {execution_id} timed out")
return False
def create_csv_with_header(analysis_type, query_info, date_str):
"""Create CSV file with proper header using simplified path structure"""
temp_location = f's3://source-inventories/temp/source-stats/{analysis_type}/{date_str}/'
# Handle special naming for source summary file
if analysis_type == 'source':
filename = f'source-stats-summary-{date_str}.csv'
else:
filename = f'source-stats-{analysis_type}-{date_str}.csv'
final_location = f'{results_prefix}{analysis_type}/{filename}'
# Run query and output to temp location
unload_query = f'''
UNLOAD (
{query_info['query']}
)
TO '{temp_location}'
WITH (
format = 'TEXTFILE',
field_delimiter = ',',
compression = 'NONE'
)
'''
# Execute query
response = athena.start_query_execution(
QueryString=unload_query,
QueryExecutionContext={'Database': database},
ResultConfiguration={
'OutputLocation': f's3://source-inventories/temp/athena/'
},
WorkGroup=workgroup
)
execution_id = response['QueryExecutionId']
if not wait_for_query_completion(execution_id):
return False
# List files in temp location
temp_prefix = f"temp/source-stats/{analysis_type}/{date_str}/"
response = s3.list_objects_v2(Bucket='source-inventories', Prefix=temp_prefix)
if 'Contents' not in response:
print(f"No files found in temp location for {analysis_type}")
return False
# Find the data file (not manifest)
data_files = [obj['Key'] for obj in response['Contents']
if not obj['Key'].endswith('manifest.csv') and not obj['Key'].endswith('.metadata')]
if not data_files:
print(f"No data files found for {analysis_type}")
return False
# Concatenate all data files with header
csv_content = query_info['header'] + '\n'
for file_key in data_files:
# Get file content
obj_response = s3.get_object(Bucket='source-inventories', Key=file_key)
file_content = obj_response['Body'].read().decode('utf-8')
csv_content += file_content
# Write final CSV file
s3.put_object(
Bucket=results_bucket,
Key=final_location,
Body=csv_content,
ContentType='text/csv'
)
# Clean up temp files
for file_key in data_files:
s3.delete_object(Bucket='source-inventories', Key=file_key)
print(f"✅ Created {final_location}")
return True
def cleanup_directories():
"""Clean up temporary directories after processing"""
try:
# Clean up athena temp directory in source-inventories bucket
response = s3.list_objects_v2(Bucket='source-inventories', Prefix='temp/athena/')
if 'Contents' in response:
delete_objects = [{'Key': obj['Key']} for obj in response['Contents']]
if delete_objects:
s3.delete_objects(
Bucket='source-inventories',
Delete={'Objects': delete_objects}
)
print(f"🧹 Cleaned up {len(delete_objects)} files from source-inventories/temp/athena/")
# Clean up source-stats temp directory in source-inventories bucket
response = s3.list_objects_v2(Bucket='source-inventories', Prefix='temp/source-stats/')
if 'Contents' in response:
delete_objects = [{'Key': obj['Key']} for obj in response['Contents']]
if delete_objects:
s3.delete_objects(
Bucket='source-inventories',
Delete={'Objects': delete_objects}
)
print(f"🧹 Cleaned up {len(delete_objects)} files from source-inventories/temp/source-stats/")
except Exception as e:
print(f"⚠️ Warning: Could not clean up temp directories: {str(e)}")
# Process each analysis type
results = []
for analysis_type, query_info in queries.items():
try:
if create_csv_with_header(analysis_type, query_info, date_str):
# Use the same naming logic as in create_csv_with_header
if analysis_type == 'source':
filename = f'source-stats-summary-{date_str}.csv'
else:
filename = f'source-stats-{analysis_type}-{date_str}.csv'
results.append(f"{analysis_type}/{filename}")
print(f"✅ {analysis_type} completed successfully")
else:
print(f"❌ {analysis_type} failed")
except Exception as e:
print(f"❌ Error processing {analysis_type}: {str(e)}")
# Clean up temporary directories
cleanup_directories()
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Analysis completed - simplified structure',
'date': date_str,
'files': results,
'structure': 'source/source-stats/[type]/source-stats-[type]-YYMMDD.csv'
})
}