-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor.py
More file actions
88 lines (61 loc) · 2 KB
/
monitor.py
File metadata and controls
88 lines (61 loc) · 2 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
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import psutil
from flask import Flask
# The app checks this file for the PID of the process to monitor.
PID_FILE = None
def get_pid():
"""Reads the process id from the PID file."""
if not os.path.exists(PID_FILE):
return False
with open(PID_FILE, 'r') as pidfile:
pid = pidfile.read()
return int(pid)
app = Flask(__name__)
# The health check will see if the worker process is running and report 200
# if it is and 503 otherwise.
@app.route('/_ah/health')
def health():
pid = get_pid()
if not pid:
return 'Worker pid not found', 503
try:
proc = psutil.Process(pid)
if not proc.is_running():
return 'Worker process exists, but is not running.', 503
except psutil.NoSuchProcess:
return 'Worker not running.', 503
return 'healthy', 200
# The stop handler is called by Google App Engine whenever an instance is going
# to be shut down. This allows this app to signal the worker to attempt to shut
# down gracefully.
@app.route('/_ah/stop')
def stop():
pid = get_pid()
if not pid:
return 'Worker pid not found.', 200
try:
proc = psutil.Process(pid)
proc.terminate()
except psutil.NoSuchProcess:
return 'Worker not running.', 503
return 'ok', 200
@app.route('/')
def index():
return health()
if __name__ == '__main__':
PID_FILE = sys.argv[1]
app.run('0.0.0.0', 8080)