Commit 89f6ea52 authored by Santhosh Kumar's avatar Santhosh Kumar

my updates

parent bd451927
from flask import Flask
from flask import Flask, request, jsonify
import ctypes
from prometheus_client import Counter, Gauge, start_http_server
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, CollectorRegistry
import psutil
import time
import multiprocessing
app = Flask(__name__)
......@@ -28,6 +31,66 @@ def clear_metrics():
registry = CollectorRegistry()
return generate_latest(registry), 200, {"Content-Type": CONTENT_TYPE_LATEST}
cpu_process = None
def occupy_cpu(percentage):
while True:
# Start time
start_time = time.time()
# Perform CPU-bound task
while (time.time() - start_time) < (percentage / 100):
pass
# Sleep to balance CPU usage
time.sleep(1 - (percentage / 100))
@app.route('/occupy_cpu/<int:percentage>', methods=['GET'])
def start_cpu_occupier(percentage):
global cpu_process
if 0 <= percentage <= 100:
# Kill previous process if exists
if cpu_process and cpu_process.is_alive():
cpu_process.terminate()
# Create a new process for occupying CPU
cpu_process = multiprocessing.Process(target=occupy_cpu, args=(percentage,))
cpu_process.start()
return jsonify({'message': f'CPU is being occupied at {percentage}%'}), 200
else:
return jsonify({'error': 'Invalid percentage, must be between 0 and 100'}), 400
memory_process = None
def allocate_memory(memory_size):
try:
memory_size = int(memory_size) * 1024*1024
except ValueError:
return jsonify({'error': 'Invalid memory size'}), 400
if memory_size <= 0:
return jsonify({'error': 'Memory size must be greater than 0'}), 400
# Allocate memory of specified size
ptr = ctypes.c_char * memory_size
memory_block = ptr()
return jsonify({'message': 'Memory allocated successfully'}), 200
@app.route('/allocate_memory/<int:memory_size>', methods=['GET'])
def start_memory_allocator(memory_size):
global memory_process
# Kill previous process if exists
if memory_process and memory_process.is_alive():
memory_process.terminate()
# Create a new process for memory allocation
memory_process = multiprocessing.Process(target=allocate_memory, args=(memory_size,))
memory_process.start()
return jsonify({'message': f'Memory allocated with size {memory_size}'}), 200
@app.route("/")
def hello():
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment