Alert on VM conditions with Azure Functions and Python

import logging

import azure.functions as func


def main(req: func.HttpRequest, outputBlob: func.Out[str]) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')

date = req.params.get('date')
host = req.params.get('host')
message = req.params.get('message')


if not date:
try:
req_body = req.get_json()
except ValueError:
pass
else:
date = req_body.get('date')

if not host:
try:
req_body = req.get_json()
except ValueError:
pass
else:
host = req_body.get('host')

if not message:
try:
req_body = req.get_json()
except ValueError:
pass
else:
message = req_body.get('message')


if date and host and message:
az_output = str(date) + str(host) + str(message)
outputBlob.set(az_output)
return func.HttpResponse(f"Hello, {host}. This HTTP triggered function executed successfully.")
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200
)

1. Implementation of Sender app

import requests
import os
import subprocess as sp

treshold = 1

used_memory = sp.getoutput("free -m | awk '/^Mem/ {print $3}'")
print(used_memory)

available_memory = sp.getoutput("free -m | awk '/^Mem/ {print $2}'")
print(available_memory)

memory_consumption = (float(used_memory) * 100/float(available_memory))

if memory_consumption > treshold:
print("Memory Usage Alert. Sending data to Storage")
output = sp. getoutput('ps aux')
data={}
data['date'] = "OvidiuBlabla"
data['host'] = "myhost"
data['message'] = output
params = {'code': 'ze7CDK1Qk_PHQFEBaM6bdgMknhM7OvPnMYtwqywVyjqI3AzIFuW0XxMQ=='}
response = requests.post('https://ovidiuborlean.azurewebsites.net/api/HttpTrigger1', params=params, json=data)
print(response.content)

curl -X POST https://ovidiuborlean.azurewebsites.net/api/HttpTrigger1?code=ze7CDK1Qk_PHQFEBaM6bdgMknhM7vPnMYtwqywVyjqI3AzFuW0XxMQ== -H “Content-Type: application/json” -d ‘{“date”: 123456, “host”: “VirtualaMachine”, “message”: “FailureAlert”}’

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store