-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathec2_user_data_starter.py
More file actions
383 lines (320 loc) · 12.1 KB
/
ec2_user_data_starter.py
File metadata and controls
383 lines (320 loc) · 12.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
#!/usr/bin/env python3
"""
AWS EC2 User Data Server Starter
Uses EC2 User Data to start servers on instance launch/reboot
"""
import boto3
import json
import time
from datetime import datetime
class EC2UserDataStarter:
def __init__(self, instance_id='i-0b072b78a8c21dada', region='us-east-1'):
self.instance_id = instance_id
self.region = region
self.ec2_client = None
self.ssm_client = None
def initialize_clients(self):
"""Initialize AWS clients"""
try:
self.ec2_client = boto3.client('ec2', region_name=self.region)
self.ssm_client = boto3.client('ssm', region_name=self.region)
print("✅ AWS clients initialized")
return True
except Exception as e:
print(f"❌ Failed to initialize AWS clients: {e}")
return False
def get_instance_details(self):
"""Get instance details"""
print(f"🔍 Getting instance details...")
try:
response = self.ec2_client.describe_instances(
InstanceIds=[self.instance_id]
)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
return instance
except Exception as e:
print(f"❌ Error getting instance details: {e}")
return None
def create_startup_script(self):
"""Create startup script for user data"""
script = '''#!/bin/bash
# Terradev Telemetry Server Startup Script
echo "🚀 Starting Terradev Telemetry Servers..."
# Update system
sudo apt update -y
sudo apt install -y python3 python3-pip curl
# Install dependencies
pip3 install flask flask-cors requests
# Create server directory
mkdir -p /home/ubuntu/terradev
cd /home/ubuntu/terradev
# Create production telemetry server
cat > production_telemetry_server.py << 'EOF'
#!/usr/bin/env python3
import json
import sqlite3
from datetime import datetime
from flask import Flask, jsonify, request
app = Flask(__name__)
def init_db():
conn = sqlite3.connect('telemetry.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS telemetry_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
machine_id TEXT,
action TEXT,
timestamp TEXT,
details TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
@app.route('/health')
def health():
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'version': '1.0.0-aws',
'server': 'production'
})
@app.route('/log-usage', methods=['POST'])
def log_usage():
try:
data = request.get_json()
conn = sqlite3.connect('telemetry.db')
cursor = conn.cursor()
cursor.execute('''
INSERT INTO telemetry_logs (machine_id, action, timestamp, details)
VALUES (?, ?, ?, ?)
''', (
data.get('machine_id'),
data.get('action'),
data.get('timestamp'),
json.dumps(data.get('details', {}))
))
conn.commit()
conn.close()
return jsonify({
'status': 'success',
'message': 'Telemetry logged successfully',
'timestamp': datetime.now().isoformat()
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/user-stats')
def user_stats():
conn = sqlite3.connect('telemetry.db')
cursor = conn.cursor()
cursor.execute('SELECT COUNT(DISTINCT machine_id) FROM telemetry_logs')
total_users = cursor.fetchone()[0] or 0
conn.close()
return jsonify({
'total_users': total_users,
'active_users_today': 0,
'server_info': {
'version': '1.0.0-aws',
'timestamp': datetime.now().isoformat()
}
})
if __name__ == '__main__':
init_db()
app.run(host='0.0.0.0', port=8080)
EOF
# Create fallback telemetry server
cat > fallback_server.py << 'EOF'
#!/usr/bin/env python3
import json
import sqlite3
from datetime import datetime
from flask import Flask, jsonify, request
app = Flask(__name__)
def init_db():
conn = sqlite3.connect('telemetry_fallback.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS telemetry_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
machine_id TEXT,
action TEXT,
timestamp TEXT,
details TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
@app.route('/health')
def health():
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'version': '1.0.0-fallback',
'server': 'fallback'
})
@app.route('/log-usage', methods=['POST'])
def log_usage():
try:
data = request.get_json()
conn = sqlite3.connect('telemetry_fallback.db')
cursor = conn.cursor()
cursor.execute('''
INSERT INTO telemetry_logs (machine_id, action, timestamp, details)
VALUES (?, ?, ?, ?)
''', (
data.get('machine_id'),
data.get('action'),
data.get('timestamp'),
json.dumps(data.get('details', {}))
))
conn.commit()
conn.close()
return jsonify({
'status': 'success',
'message': 'Telemetry logged successfully (fallback)',
'timestamp': datetime.now().isoformat()
})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
init_db()
app.run(host='0.0.0.0', port=8081)
EOF
# Start servers
echo "Starting production server..."
nohup python3 production_telemetry_server.py > production.log 2>&1 &
echo "Starting fallback server..."
nohup python3 fallback_server.py > fallback.log 2>&1 &
# Wait for servers to start
sleep 10
# Test servers
echo "Testing production server..."
curl -s http://localhost:8080/health || echo "Production server not ready"
echo "Testing fallback server..."
curl -s http://localhost:8081/health || echo "Fallback server not ready"
# Setup port forwarding/security
sudo ufw allow 8080
sudo ufw allow 8081
sudo ufw allow 80
sudo ufw allow 443
echo "✅ Terradev telemetry servers started!"
echo "📊 Production: http://$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4):8080"
echo "📊 Fallback: http://$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4):8081"
'''
return script
def update_instance_user_data(self):
"""Update instance user data and restart"""
print("🔄 Updating instance user data...")
try:
# Get current instance details
instance = self.get_instance_details()
if not instance:
return False
# Create startup script
startup_script = self.create_startup_script()
# Stop the instance
print("🛑 Stopping instance...")
self.ec2_client.stop_instances(InstanceIds=[self.instance_id])
# Wait for instance to stop
print("⏳ Waiting for instance to stop...")
waiter = self.ec2_client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[self.instance_id])
# Update user data
print("📝 Updating user data...")
self.ec2_client.modify_instance_attribute(
InstanceId=self.instance_id,
UserData=startup_script
)
# Start the instance
print("🚀 Starting instance...")
self.ec2_client.start_instances(InstanceIds=[self.instance_id])
# Wait for instance to start
print("⏳ Waiting for instance to start...")
waiter = self.ec2_client.get_waiter('instance_running')
waiter.wait(InstanceIds=[self.instance_id])
print("✅ Instance restarted with new user data")
return True
except Exception as e:
print(f"❌ Error updating user data: {e}")
return False
def run_startup_commands(self):
"""Run startup commands via SSM (if available)"""
print("🚀 Attempting to run startup commands...")
commands = [
"cd /home/ubuntu && mkdir -p terradev && cd terradev",
"pip3 install flask flask-cors requests",
"curl -s 'https://raw.githubusercontent.com/theoddden/terradev/main/production_telemetry_server.py' -o production_telemetry_server.py || echo 'Using local copy'",
"curl -s 'https://raw.githubusercontent.com/theoddden/terradev/main/fallback_server.py' -o fallback_server.py || echo 'Using local copy'",
"nohup python3 production_telemetry_server.py > production.log 2>&1 &",
"nohup python3 fallback_server.py > fallback.log 2>&1 &",
"sleep 15",
"curl -s http://localhost:8080/health || echo 'Production not ready'",
"curl -s http://localhost:8081/health || echo 'Fallback not ready'"
]
for command in commands:
try:
print(f"📤 Running: {command[:50]}...")
response = self.ssm_client.send_command(
InstanceIds=[self.instance_id],
DocumentName='AWS-RunShellScript',
Parameters={'commands': [command]}
)
command_id = response['Command']['CommandId']
print(f"✅ Command sent: {command_id}")
# Wait a bit between commands
time.sleep(5)
except Exception as e:
print(f"❌ Error running command: {e}")
def deploy_and_start(self):
"""Complete deployment"""
print("🚀 EC2 User Data Server Deployment")
print("=" * 50)
# Initialize clients
if not self.initialize_clients():
return False
# Get instance details
instance = self.get_instance_details()
if not instance:
return False
print(f"📍 Instance: {instance['InstanceId']}")
print(f"🌐 IP: {instance.get('PublicIpAddress')}")
print(f"🏷️ Tags: {instance.get('Tags', [])}")
# Try SSM commands first (less disruptive)
print("\n🚀 Attempting SSM deployment...")
self.run_startup_commands()
# Wait and check
print("\n⏳ Waiting 30 seconds for servers to start...")
time.sleep(30)
# Test connectivity
ip = instance.get('PublicIpAddress')
print(f"\n🔍 Testing connectivity to {ip}...")
try:
import requests
response = requests.get(f"http://{ip}:8080/health", timeout=10)
if response.status_code == 200:
print("✅ Production server is running!")
print(f"📊 Dashboard: http://{ip}:8080/dashboard")
else:
print("⚠️ Production server responding but not healthy")
except:
print("❌ Production server not accessible")
try:
response = requests.get(f"http://{ip}:8081/health", timeout=10)
if response.status_code == 200:
print("✅ Fallback server is running!")
else:
print("⚠️ Fallback server responding but not healthy")
except:
print("❌ Fallback server not accessible")
print(f"\n🎉 Deployment completed!")
print(f"📊 Server URLs:")
print(f" Production API: http://{ip}:8080")
print(f" Fallback API: http://{ip}:8081")
print(f" Health Check: http://{ip}:8080/health")
print(f" Dashboard: http://{ip}:8080/dashboard")
return True
if __name__ == '__main__':
starter = EC2UserDataStarter()
starter.deploy_and_start()