|
| 1 | +import time |
| 2 | +import socket |
| 3 | +import json |
| 4 | +import azure.functions as func |
| 5 | +import logging |
| 6 | +from time import perf_counter |
| 7 | + |
| 8 | +# Global variable for hostname |
| 9 | +hostname = socket.gethostname() |
| 10 | + |
| 11 | +# Simulate the busySpin function |
| 12 | +def busy_spin(duration_ms: int) -> None: |
| 13 | + end_time = perf_counter() + duration_ms / 1000 # Convert ms to seconds |
| 14 | + while perf_counter() < end_time: |
| 15 | + continue |
| 16 | + |
| 17 | +# Convert TraceFunctionExecution |
| 18 | +def trace_function_execution(start: float, time_left_milliseconds: int) -> str: |
| 19 | + time_consumed_milliseconds = int((time.time() - start) * 1000) |
| 20 | + if time_consumed_milliseconds < time_left_milliseconds: |
| 21 | + time_left_milliseconds -= time_consumed_milliseconds |
| 22 | + if time_left_milliseconds > 0: |
| 23 | + busy_spin(time_left_milliseconds) |
| 24 | + |
| 25 | + return f"OK - {hostname}" |
| 26 | + |
| 27 | +# The handler function for Azure Functions (Python) |
| 28 | +def main(req: func.HttpRequest) -> func.HttpResponse: |
| 29 | + logging.info("Processing request.") |
| 30 | + |
| 31 | + start_time = time.time() |
| 32 | + |
| 33 | + # Parse JSON request body |
| 34 | + try: |
| 35 | + req_body = req.get_json() |
| 36 | + logging.info(f"Request body: {req_body}") |
| 37 | + except ValueError: |
| 38 | + logging.error("Invalid JSON received.") |
| 39 | + return func.HttpResponse( |
| 40 | + json.dumps({"error": "Invalid JSON"}), |
| 41 | + status_code=400, |
| 42 | + mimetype="application/json" |
| 43 | + ) |
| 44 | + |
| 45 | + runtime_milliseconds = req_body.get('RuntimeInMilliSec', 1000) |
| 46 | + memory_mebibytes = req_body.get('MemoryInMebiBytes', 128) |
| 47 | + |
| 48 | + logging.info(f"Runtime requested: {runtime_milliseconds} ms, Memory: {memory_mebibytes} MiB") |
| 49 | + |
| 50 | + # Trace the function execution (busy work simulation) |
| 51 | + result_msg = trace_function_execution(start_time, runtime_milliseconds) |
| 52 | + |
| 53 | + # Prepare the response |
| 54 | + response = { |
| 55 | + "Status": "Success", |
| 56 | + "Function": req.url.split("/")[-1], |
| 57 | + "MachineName": hostname, |
| 58 | + "ExecutionTime": int((time.time() - start_time) * 1_000_000), |
| 59 | + "DurationInMicroSec": int((time.time() - start_time) * 1_000_000), |
| 60 | + "MemoryUsageInKb": memory_mebibytes * 1024, |
| 61 | + "Message": result_msg |
| 62 | + } |
| 63 | + |
| 64 | + logging.info(f"Response: {response}") |
| 65 | + |
| 66 | + return func.HttpResponse( |
| 67 | + json.dumps(response), |
| 68 | + status_code=200, |
| 69 | + mimetype="application/json" |
| 70 | + ) |
| 71 | + |
0 commit comments