-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy-stack.py
More file actions
573 lines (508 loc) · 23 KB
/
deploy-stack.py
File metadata and controls
573 lines (508 loc) · 23 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
import os
import uuid
import requests
import sys
import time
API_TOKEN = os.environ.get('SI_API_TOKEN')
WORKSPACE_ID = os.environ.get("SI_WORKSPACE_ID")
API_URL = "https://api.systeminit.com"
if not API_TOKEN or not WORKSPACE_ID:
error_msg = "Missing required environment variables: SI_API_TOKEN or SI_WORKSPACE_ID"
write_error_to_file(error_msg)
raise ValueError(error_msg)
headers = {
'Authorization': f'Bearer {API_TOKEN}',
'Content-Type': 'application/json'
}
def write_error_to_file(error_message):
"""Write error message to file for workflow consumption."""
try:
with open('./error', 'w') as f:
f.write(error_message)
except Exception as e:
print(f"Failed to write error to file: {e}")
def get_action_logs(change_set_id, func_run_id):
"""Retrieves logs for a specific function run."""
try:
response = requests.get(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/funcs/runs/{func_run_id}',
headers=headers)
response.raise_for_status()
logs_data = response.json()
# Check for logs in the response - they're nested under funcRun.logs.logs
func_run = logs_data.get("funcRun", {})
if func_run and "logs" in func_run:
logs_obj = func_run["logs"]
if isinstance(logs_obj, dict) and "logs" in logs_obj:
return logs_obj["logs"]
return []
except Exception as e:
print(f"❌ Failed to retrieve logs for func run {func_run_id}: {e}")
return []
def wait_for_merge_success(change_set_id,
timeout_seconds=300,
poll_interval=10):
"""Waits until all actions are 'Success' or the change set is 'Applied' with no actions."""
start_time = time.time()
while time.time() - start_time < timeout_seconds:
response = requests.get(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/merge_status',
headers=headers)
response.raise_for_status()
merge_data = response.json()
change_set = merge_data.get("changeSet", {})
actions = merge_data.get("actions", [])
if not actions:
status = change_set.get("status")
if status == "Applied":
print("✅ Change set applied with no actions.")
return True
else:
print(
f"⏳ No actions found. Change set status: {status}. Waiting..."
)
else:
states = [action["state"] for action in actions]
if all(state == "Success" for state in states):
print("✅ All actions succeeded.")
return True
else:
failed_actions = [
action for action in actions if action["state"] == "Failed"
]
if failed_actions:
print(
f"❌ {len(failed_actions)} action(s) failed. Outputting logs:"
)
for action in failed_actions:
print(
f"\n--- Logs for failed action: {action.get('displayName', action.get('name', 'Unknown'))} ---"
)
func_run_id = action.get("funcRunId")
# If no funcRunId in merge_status, get it from the detailed actions endpoint
if not func_run_id:
try:
action_response = requests.get(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/actions',
headers=headers)
action_response.raise_for_status()
actions_data = action_response.json()
for action_detail in actions_data.get(
"actions", []):
if action_detail.get("id") == action.get(
"id"):
func_run_id = action_detail.get(
"funcRunId")
break
except Exception as e:
print(
f"Failed to get detailed action info: {e}")
if func_run_id:
# Try to get logs from HEAD first, then fallback to change_set_id
logs = get_action_logs("head", func_run_id)
if not logs:
logs = get_action_logs(change_set_id,
func_run_id)
error_message = ""
if logs:
for log in logs:
timestamp = log.get("timestamp", "")
stream = log.get("stream", "")
message = log.get("message", "")
print(f"[{timestamp}] {stream}: {message}")
# Capture error messages for the error file (for EC2 deployment context)
if stream == "output" and (
"error" in message.lower()
or "message" in message):
try:
# Try to parse JSON and extract error message
import json
output_data = json.loads(
message.split("Output: ")[1]
if "Output: " in
message else message)
if "message" in output_data:
error_message = output_data[
"message"]
except:
error_message = message
else:
print("No logs available for this action.")
# Save error details to file for E2E workflow to read
if error_message:
write_error_to_file(error_message)
else:
print("No func run ID available for this action.")
print("--- End of logs ---\n")
return False # Exit immediately when actions fail
else:
print(f"⏳ Action states: {states}. Waiting...")
time.sleep(poll_interval)
# Get final status and output logs for any failed actions before timeout
try:
response = requests.get(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/merge_status',
headers=headers)
response.raise_for_status()
merge_data = response.json()
actions = merge_data.get("actions", [])
failed_actions = [
action for action in actions if action["state"] == "Failed"
]
if failed_actions:
print(
f"❌ {len(failed_actions)} action(s) failed. Outputting logs:")
for action in failed_actions:
print(
f"\n--- Logs for failed action: {action.get('displayName', 'Unknown')} ---"
)
func_run_id = action.get("funcRunId")
if func_run_id:
logs = get_action_logs(change_set_id, func_run_id)
if logs:
for log in logs:
timestamp = log.get("timestamp", "")
stream = log.get("stream", "")
message = log.get("message", "")
print(f"[{timestamp}] {stream}: {message}")
else:
print("No logs available for this action.")
else:
print("No func run ID available for this action.")
print("--- End of logs ---\n")
except Exception as e:
print(f"Failed to retrieve final action status: {e}")
# Write timeout error to file before raising
timeout_msg = f"Action execution timeout: Merge not successful for ChangeSet {change_set_id} after {timeout_seconds}s"
write_error_to_file(timeout_msg)
raise TimeoutError(f"❌ {timeout_msg}")
def get_public_ip(change_set_id,
component_id,
timeout_seconds=60,
poll_interval=3):
url = f"{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/components/{component_id}"
start_time = time.time()
while time.time() - start_time < timeout_seconds:
response = requests.get(url, headers=headers)
response.raise_for_status()
component = response.json().get("component", {})
for prop in component.get("resourceProps", []):
if prop.get("path") == "root/resource_value/PublicIp":
public_ip = prop.get("value")
if public_ip:
print(f"✅ Public IP found: {public_ip}")
return public_ip
print("⏳ Public IP not ready yet, retrying...")
time.sleep(poll_interval)
ip_timeout_msg = f"Public IP lookup timeout: Instance public IP not available after {timeout_seconds}s"
write_error_to_file(ip_timeout_msg)
raise TimeoutError(f"❌ {ip_timeout_msg}")
def manage_component(change_set_id, component_id, manager_component_id):
try:
response = requests.post(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/components/{component_id}/manage',
headers=headers,
json={"componentId": manager_component_id})
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_msg = f"HTTP error setting manager for component '{component_id}': {e}"
if hasattr(e, 'response') and e.response:
error_msg += f" - Response: {e.response.text}"
raise Exception(error_msg)
except Exception as e:
raise Exception(
f"Failed to set manager for component '{component_id}': {str(e)}")
def force_apply_with_retry(change_set_id,
timeout_seconds=120,
retry_interval=5):
"""Force apply change set with retry logic for if DVU roots still exist."""
start_time = time.time()
while time.time() - start_time < timeout_seconds:
try:
force_apply_url = f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/force_apply'
response = requests.post(force_apply_url,
headers={
'Authorization':
f'Bearer {API_TOKEN}',
'accept': 'application/json'
},
data='')
response.raise_for_status()
print('Change set applied successfully.')
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 428: # PRECONDITION_REQUIRED == DVU
elapsed = time.time() - start_time
remaining = timeout_seconds - elapsed
print(
f'⏳ DVU Roots still present. Retrying in {retry_interval}s... ({remaining:.1f}s remaining)'
)
if remaining > retry_interval:
time.sleep(retry_interval)
continue
else:
break
else:
raise e
force_apply_timeout_msg = f"Force apply timeout: Change set apply failed after {timeout_seconds}s - DVUs still processing"
write_error_to_file(force_apply_timeout_msg)
raise TimeoutError(f"❌ {force_apply_timeout_msg}")
def create_change_set(name):
try:
response = requests.post(f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets',
headers=headers,
json={'changeSetName': name})
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_msg = f"HTTP error creating change set '{name}': {e}"
if hasattr(e, 'response') and e.response:
error_msg += f" - Response: {e.response.text}"
raise Exception(error_msg)
except Exception as e:
raise Exception(f"Failed to create change set '{name}': {str(e)}")
def create_component(change_set_id, schema_name, name, options=None):
request_body = {'schemaName': schema_name, 'name': name}
if options:
request_body.update(options)
# print(request_body)
try:
response = requests.post(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}/components',
headers=headers,
json=request_body)
response.raise_for_status()
# print(response.json())
return response.json()
except requests.exceptions.HTTPError as e:
error_msg = f"HTTP error creating component '{name}' with schema '{schema_name}': {e}"
if hasattr(e, 'response') and e.response:
error_msg += f" - Response: {e.response.text}"
raise Exception(error_msg)
except Exception as e:
raise Exception(f"Failed to create component '{name}': {str(e)}")
def get_change_set(change_set_id):
response = requests.get(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}',
headers=headers)
return response
def delete_change_set(change_set_id):
response = requests.delete(
f'{API_URL}/v1/w/{WORKSPACE_ID}/change-sets/{change_set_id}',
headers=headers)
response.raise_for_status()
return response.json()
MANAGER_COMPONENT_ID = "01JY7K7ZBMPHG22RVTNSA6GB0Z"
def main():
try:
print('Starting System Initiative Environment Setup')
branch_name = "main"
environment_uuid = uuid.uuid4()
change_set_name = f"Environment {environment_uuid}"
print(f'Creating change set: {change_set_name}')
try:
change_set_data = create_change_set(change_set_name)
change_set_id = change_set_data["changeSet"]["id"]
print(f'Created ChangeSet ID: {change_set_id}')
except Exception as e:
error_msg = f"Failed to create change set '{change_set_name}': {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
try:
with open('provision.sh', 'r') as f:
userdata_template = f.read()
except FileNotFoundError:
error_msg = "Deployment setup error: provision.sh script not found"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
except Exception as e:
error_msg = f"Failed to read provision.sh script: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
userdata_script = userdata_template.replace('{{BRANCH}}', branch_name)
userdata_options = {
"attributes": {
"/domain/userdataContent": userdata_script
},
"viewName": "Environments",
}
print('Creating Userdata component...')
try:
userdata_data = create_component(
change_set_id, "Userdata", f'userdata-{str(environment_uuid)}',
userdata_options)
userdata_component_id = userdata_data["component"]["id"]
print(f'Userdata component ID: {userdata_component_id}')
except Exception as e:
error_msg = f"Failed to create Userdata component: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
print(
f'Setting manager for Userdata component {userdata_component_id}...'
)
try:
manage_component(change_set_id, userdata_component_id,
MANAGER_COMPONENT_ID)
print('Userdata component now managed.')
except Exception as e:
error_msg = f"Failed to set manager for Userdata component: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
ec2_options = {
"attributes": {
"/domain/InstanceType": "c6i.16xlarge",
"/domain/BlockDeviceMappings/0": {
"DeviceName": "/dev/sda1",
"Ebs": {
"DeleteOnTermination": True,
"VolumeSize": 100,
"VolumeType": "gp3"
}
},
"/domain/Tags/0": {
"Key": "Name",
"Value": "frontend-ci-validation-test-machine"
},
"/domain/SecurityGroupIds/0": {
"$source": {
"component": "frontend-ci-validation-sg",
"path": "/resource_value/GroupId",
}
},
"/domain/ImageId": {
"$source": {
"component": "Arch Linux",
"path": "/domain/ImageId",
}
},
"/domain/SubnetId": {
"$source": {
"component": "frontend-ci-validation-subnet-pub-1",
"path": "/resource_value/SubnetId",
}
},
"/domain/KeyName": {
"$source": {
"component": "frontend-ci-validation-kp",
"path": "/domain/KeyName",
}
},
"/domain/extra/Region": {
"$source": {
"component": "us-east-1",
"path": "/domain/region"
}
},
"/domain/UserData": {
"$source": {
"component": f'userdata-{str(environment_uuid)}',
"path": "/domain/userdataContentBase64"
}
},
"/domain/IamInstanceProfile": {
"$source": {
"component": "ci-validation-instance-instance-profile",
"path": "/domain/InstanceProfileName"
}
},
"/secrets/AWS Credential": {
"$source": {
"component": "si-tools-sandbox",
"path": "/secrets/AWS Credential"
}
}
},
"viewName": "Environments",
}
print("Creating EC2 instance component...")
try:
ec2_data = create_component( # Super annoying it doesn't tell you what a misaligned prop mapping is
change_set_id, # would be so much better if it returned something like the valid schema for the
"AWS::EC2::Instance", # attempted connection. It also breaks copy and paste of the component
str(environment_uuid),
ec2_options)
ec2_component_id = ec2_data["component"]["id"]
print(f'EC2 component ID: {ec2_component_id}')
except Exception as e:
error_msg = f"Failed to create EC2 instance component: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
print(f'Setting manager for EC2 component {ec2_component_id}...')
try:
manage_component(change_set_id, ec2_component_id,
MANAGER_COMPONENT_ID)
print('EC2 component now managed.')
except Exception as e:
error_msg = f"Failed to set manager for EC2 component: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
print(f'Force applying change set {change_set_id}...')
try:
force_apply_with_retry(change_set_id)
except Exception as e:
error_msg = f"Failed to apply change set: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
print("Waiting for actions to complete...")
success = wait_for_merge_success(change_set_id)
if not success:
# Error should already be written by wait_for_merge_success, but ensure we have one
if not os.path.exists('./error'):
write_error_to_file(
"Deployment actions failed - check logs for details")
print("❌ Actions failed. Exiting.")
sys.exit(1)
print("All actions completed successfully...")
base_change_set_id = "head"
print("Querying for public IP...")
ip_output_file = './ip'
try:
public_ip = get_public_ip(base_change_set_id, ec2_component_id,
120, 5)
print(f"Instance is reachable at: {public_ip}")
with open(ip_output_file, 'w') as f:
f.write(f'{public_ip}')
except Exception as e:
error_msg = f"Failed to retrieve or save public IP: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
except TimeoutError as e:
error_msg = f"Deployment timeout: {str(e)}"
write_error_to_file(error_msg)
print(error_msg)
sys.exit(1)
except requests.exceptions.HTTPError as err:
error_msg = f"HTTP Error during deployment: {err}"
if hasattr(err, 'response') and err.response:
error_msg += f" - Response: {err.response.text}"
write_error_to_file(error_msg)
print(f'HTTP Error: {err}')
print(f'Response: {err.response.text}')
sys.exit(1)
except Exception as err:
error_msg = f"Unexpected deployment error: {str(err)}"
write_error_to_file(error_msg)
print(f'General Error: {err}')
sys.exit(1)
finally:
if change_set_id:
try:
response = get_change_set(change_set_id)
if response.status_code == 200:
print(f'Cleaning up change set {change_set_id}...')
delete_change_set(change_set_id)
print('Change set deleted.')
except Exception as cleanup_err:
print(f'Failed to cleanup change set: {cleanup_err}')
if __name__ == '__main__':
main()