In this post, I will demo how to create a python script to check a url(website/webservice)‘s health periodically and automatically .
2. Environment
Python 2.x or 3.x
Linux system
3. The solution
3.1 The environment
Suppose we hava a web service which provides some sort of services to users, now we want it to run always and if it’s not healthy, we should restart the service automatically.
The service URL prefix is:
And we also have a restart script for this service located at:
3.2 Add a health check endpoint for our service
For health check purpose, we should add a dedicated endpoint to be accessed by the health check script, it should be fast , here is our implementation in java language:
It means that if we caccess the below url:
We should get this result(http response status code equals 200):
Otherwise , the status code should not be 200 , just as the picture shows:
It health check fails, the restart script should be run immediately.
3.3 Setup the logger and imports for python script
Before coding the business, we should setup the environment for our script, just as follows:
In the above code, we use the logging module in python to setup a daily rolling file handler for our program, it would create a log file everyday with the suffix year-month-day. You can view more information about the TimedRotatingFileHandler from this website.
The parameter when="midnight" in TimedRotatingFileHandler means that it would Roll over at midnight.
3.4 Implement the health check function with python
First, we need a function to check the status of the service, just as follows:
You can see that , the above function would return True only when the service response code is 200 and the responsecontent is world, or else, it would return False to the caller.
For python 2.x , we can use:
For python 3.x , you can replace the urllib.urlopen with follows:
3.5 Implement the periodically checking logic
Now we should create a function to run the health check periodically and restart the service automatically if the check fails.
3.6 The main function
At last, we should provide the main function to execute the whole script:
3.7 Save the script and execute it in background
Then we save the above script as healthcheck_myservice.py, and execute in background as follows:
Then we can check the log as follows:
We can get these logs:
It works!
4. The whole script
5. Summary
In this post, I demonstrated how to use python to do health check job in linux.