Skip to content

Commit ff0ee81

Browse files
committed
website monitor 3
1 parent 0d8691e commit ff0ee81

File tree

7 files changed

+556
-36
lines changed

7 files changed

+556
-36
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
'''
2+
AWS EC2 Instance interactions with boto3 library
3+
'''
4+
5+
import boto3
6+
7+
ec2_res = boto3.resource('ec2')
8+
instance = ec2_res.Instance('i-06fba9c3d9747cd17') # instance id
9+
10+
11+
def reboot_instance():
12+
# instance.reboot
13+
print('reboot_instance')
14+
response = instance.reboot()
15+
print('reboot response:')
16+
print(response)
17+
18+
19+
def stop_instance():
20+
print('stop_instance')
21+
# instance.stop
22+
response = instance.stop()
23+
print('stop response:')
24+
print(response)
25+
26+
27+
def start_instance():
28+
# start_instance
29+
print('start_instance')
30+
response = instance.start()
31+
print('start response:')
32+
print(response)
33+
34+
35+
def wait_instance_run():
36+
print('wait_instance_run')
37+
# instance.wait_until_running
38+
response = instance.wait_until_running()
39+
print('wait_instance_run response:')
40+
print(response)
41+
42+
43+
def wait_instance_stop():
44+
# instance.wait_until_stopped
45+
print('wait_instance_stop')
46+
response = instance.wait_until_stopped()
47+
print('wait_instance_stop response:')
48+
print(response)
49+
50+
51+
print(instance.state)
52+
print(instance.public_ip_address)
53+
54+
stop_instance()
55+
wait_instance_stop()
56+
57+
print(instance.state)
58+
59+
start_instance()
60+
wait_instance_run()
61+
62+
print(instance.state)
63+
print(instance.public_ip_address)

python_tips/linode_api.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#Needs cleaning
2+
3+
#restart linode server
4+
import linode_api4 #pip install linode-api4
5+
import os
6+
import paramiko
7+
import time
8+
9+
10+
LINODE_TOKEN = os.getenv('LINODE_TOKEN') #env var for LINODE ACCESS TOKEN
11+
12+
13+
def restart_container():
14+
ssh = paramiko.SSHClient()
15+
16+
# known_hosts prompt
17+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
18+
19+
# connect as ec2-user with .pem | root connection might require priv-key pub-key.pub
20+
ssh.connect(hostname='18.184.246.158',
21+
username="ec2-user",
22+
key_filename='/home/mltamd/.ssh/ec2-key-pair-frankfurt.pem')
23+
stdin, stdout, stderr = ssh.exec_command('docker start 06b420614a68')
24+
print(stdout.readlines())
25+
ssh.close()
26+
27+
28+
#restart linode server
29+
client = linode_api4.LinodeClient(LINODE_TOKEN)
30+
nginx_server = client.load(linode_api4.Instance, 123456789) #linode server id
31+
nginx_server.reboot()
32+
33+
#restart the app container
34+
while True:
35+
nginx_server = client.load(linode_api4.Instance, 123456789) #linode server id
36+
time.sleep(5)
37+
if nginx_server.status == 'running':
38+
time.sleep(10)
39+
restart_container()
40+
break

python_tips/python_remote_ssh_fabric.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
from fabric import Connection
22
from invoke import Responder
33

4+
# fabric creates a copy of known_hosts and automatically adds new hosts to it.
5+
# it doesn't change the original ./ssh/known_hosts
46
# set host 'ec2-monitor' in .ssh/config to be read automatically
57
# else must specify connection details here
68
result = Connection('ec2-monitor').run('docker ps', hide=True)
79
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
810
print(msg.format(result))
911

1012

11-
# other syntax
13+
""" # other syntax
1214
c = Connection('ec2-monitor')
1315
r = c.run('sudo whoami', hide=True)
1416
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
15-
print(msg.format(result))
17+
print(msg.format(result)) """
1618

1719

1820
# sudo password prompt

website_monitor/website-monitor.py

-34
This file was deleted.
+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import requests
2+
import smtplib
3+
import os
4+
import paramiko
5+
import time
6+
import boto3
7+
8+
# from dotenv import load_dotenv
9+
# load_dotenv()
10+
11+
EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS')
12+
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
13+
14+
15+
def send_notification(email_content):
16+
print(email_content)
17+
""" with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
18+
smtp.ehlo()
19+
smtp.starttls()
20+
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
21+
#smtp.sendmail(sender, receiver, message)
22+
email_content = f"Subject:WEB MONITOR ALERT\n{email_content}"
23+
smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, email_content) """
24+
25+
# assume we configured ec2 docker and containerd services to auto start on boot
26+
# check Official Post-Installation steps on Docker Install
27+
def restart_container():
28+
print("Restarting container...")
29+
ssh = paramiko.SSHClient()
30+
31+
# known_hosts prompt
32+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
33+
34+
# connect as ec2-user with .pem | root connection might require key and key.pub pair
35+
ssh.connect(hostname='18.192.106.193',
36+
username="ec2-user",
37+
key_filename='/home/mltamd/.ssh/ec2-key-pair-frankfurt.pem')
38+
stdin, stdout, stderr = ssh.exec_command('docker start 06b420614a68')
39+
print(stdout.readlines())
40+
ssh.close()
41+
42+
def reboot_server():
43+
print("Rebooting server...")
44+
ssh = paramiko.SSHClient()
45+
46+
# known_hosts prompt
47+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
48+
49+
# connect as ec2-user with .pem | root connection might require key and key.pub pair
50+
ssh.connect(hostname='18.192.106.193',
51+
username="ec2-user",
52+
key_filename='/home/mltamd/.ssh/ec2-key-pair-frankfurt.pem')
53+
stdin, stdout, stderr = ssh.exec_command('sudo reboot')
54+
print(stdout.readlines())
55+
ssh.close()
56+
print('------------ssh closed--------------')
57+
58+
59+
60+
def stop_and_start_server():
61+
ec2_res = boto3.resource('ec2')
62+
instance = ec2_res.Instance('i-06fba9c3d9747cd17')
63+
64+
65+
66+
67+
68+
69+
def wait_for_server_status_and_states_ok():
70+
print('Waiting server to be up..')
71+
while True:
72+
ec2 = boto3.client('ec2', region_name='eu-central-1')
73+
print('Waiting 10..')
74+
time.sleep(10)
75+
76+
# check instance state, status and system status from describe_instance_status
77+
response = ec2.describe_instance_status(
78+
IncludeAllInstances=True,
79+
InstanceIds=[
80+
'i-06fba9c3d9747cd17',
81+
]
82+
)
83+
84+
server_state = ''
85+
instance_status = ''
86+
system_status = ''
87+
88+
statuses = response["InstanceStatuses"]
89+
for status in statuses: #improve :no for, pick it up explicitly
90+
print(f"Instance {status['InstanceId']} state is: {status['InstanceState']['Name']} with instance status: {status['InstanceStatus']['Status']} and system status: {status['SystemStatus']['Status']}")
91+
print("#######")
92+
server_state = status['InstanceState']['Name']
93+
instance_status = status['InstanceStatus']['Status']
94+
system_status = status['SystemStatus']['Status']
95+
96+
if server_state == 'running' and instance_status == 'ok' and system_status == 'ok':
97+
print("Server is up...exiting waiting loop")
98+
time.sleep(2)
99+
break
100+
101+
102+
103+
try:
104+
r = requests.get(
105+
'http://ec2-18-192-106-193.eu-central-1.compute.amazonaws.com:8080/')
106+
if r.status_code == 200:
107+
print("Website is up!")
108+
else:
109+
print("Website is down!")
110+
# send email
111+
message = "Website is down!"
112+
send_notification(message)
113+
restart_container()
114+
except Exception as e:
115+
print(f"Connection error: {e}")
116+
message = "Connection error!"
117+
send_notification(message)
118+
print("Attempt to restart server and container. This may take some time...")
119+
reboot_server()
120+
wait_for_server_status_and_states_ok()
121+
restart_container()
122+
123+

0 commit comments

Comments
 (0)