When activated, this Google Cloud Function checks the status of a specific URL and tracks the time it took to ping and alongside the HTTP status. If the URL is unresponsive, the function initiates a webhook. Although not mandatory, it's optimized for use with RestartVMService which will automatically restart a Google Cloud VM when the hosted URL becomes unavailable.
A Cloud Function that pings a URL, reports its status and triggers a webhook if there are issues.
- Create a v1 Cloud Function in the Google Cloud Platform Console.
- Set the trigger to HTTP.
- Paste the code from this repository into the Cloud Function editor.
- Set the environment variables
pingURL
andwebhookURL
to the URL of the site you want to monitor and the URL of the webhook, respectively. - Save the Cloud Function.
The Cloud Function first pings the URL using the Axios library. If the response status code is 200 or 300, the function reports that the site is up. Otherwise, the function reports that the site is down and triggers the webhook.
The following example shows how to use the httpPing Cloud Function to monitor a website:
export const httpPing = async (req, res) => {
const status = await pingSite();
res.status(200).send(`Site Status: ${status}`);
};
In this example, the pingSite
function is used to ping the website. The status
variable is then used to set the response status code and message.
When successfully executed you should see logs related to your Cloud Function which look like:
[Ping Response] HTTP Status: 200, Time Taken: 123ms
[Processed State] HTTP Status: 200, Time Taken: 123ms
If the Cloud Function is not working, you can check the following:
- Make sure that the Cloud Function is triggered correctly.
- Make sure that the environment variables
pingURL
andwebhookURL
are set correctly. - Check the logs for the Cloud Function to see if there are any errors.
- Go to the Cloud Scheduler page in the Google Cloud Platform Console.
- Click Create Job.
- Select the HTTP trigger.
- Enter the URL of the Cloud Function as the target URL.
- Set the schedule to run every Minute * * * * *.
- Click Create.
The Cloud Function will now be triggered every minute by Google Cloud schedule.