Alert on VM conditions with Azure Functions and Python

  • In Azure Portal will search for Function App and select the corresponding blade
  • We will select a Resource Group, a unique App name and Python as Runtime stack. We can leave other setting as default for now and choose Review + Create
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)

In params we add a dictionary with the key of “code” and the value of the content of our secret code.

We have defined also a dictionary structure consisting of the three keys (date, host, message) whose values can be overwritten by our code. In our example, first two keys are statically defined, the last one, message, carry the output of ps aux command.

--

--

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