-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor-website.py
More file actions
70 lines (57 loc) · 2.1 KB
/
monitor-website.py
File metadata and controls
70 lines (57 loc) · 2.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
import requests
import smtplib
import os
import paramiko
import linode_api4
import time
import schedule
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')
LINODE_TOKEN = os.environ.get('LINODE_TOKEN')
def restart_server_and_container():
# restart linode server
print('Rebooting the server...')
client = linode_api4.LinodeClient(LINODE_TOKEN)
nginx_server = client.load(linode_api4.Instance, 24920590)
nginx_server.reboot()
# restart the application
while True:
nginx_server = client.load(linode_api4.Instance, 24920590)
if nginx_server.status == 'running':
time.sleep(5)
restart_container()
break
def send_notification(email_msg):
print('Sending an email...')
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.ehlo()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
message = f"Subject: SITE DOWN\n{email_msg}"
smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, message)
def restart_container():
print('Restarting the application...')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='139.162.130.236', username='root', key_filename='/Users/nanajanashia/.ssh/id_rsa')
stdin, stdout, stderr = ssh.exec_command('docker start c3e706bc905e')
print(stdout.readlines())
ssh.close()
def monitor_application():
try:
response = requests.get('http://li1388-236.members.linode.com:8080/')
if response.status_code == 200:
print('Application is running successfully!')
else:
print('Application Down. Fix it!')
msg = f'Application returned {response.status_code}'
send_notification(msg)
restart_container()
except Exception as ex:
print(f'Connection error happened: {ex}')
msg = 'Application not accessible at all'
send_notification(msg)
restart_server_and_container()
schedule.every(5).minutes.do(monitor_application)
while True:
schedule.run_pending()