Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions monitoring/add-metrics/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Используем Python как базовый образ
FROM python:3.10-slim

# Устанавливаем рабочую директорию
WORKDIR /app

# Копируем файлы проекта
COPY . /app

# Устанавливаем зависимости
RUN pip install --no-cache-dir -r requirements.txt

# Открываем порт для работы API
EXPOSE 8000

# Запускаем приложение
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Binary file not shown.
22 changes: 22 additions & 0 deletions monitoring/add-metrics/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
version: '3.8'

services:
api:
build:
context: .
dockerfile: Dockerfile
container_name: jusan-monitoring-api
ports:
- "8000:8000"
volumes:
- .:/app
restart: always

prometheus:
image: prom/prometheus:latest
container_name: prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
restart: always
84 changes: 84 additions & 0 deletions monitoring/add-metrics/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, Gauge, make_asgi_app
import time

# Инициализация приложения FastAPI
app = FastAPI()

# Определение метрик
http_requests_total = Counter(
'http_requests_total', 'Number of HTTP requests received', ['method', 'endpoint']
)
http_requests_milliseconds = Histogram(
'http_requests_milliseconds', 'Duration of HTTP requests in milliseconds', ['method', 'endpoint']
)
last_sum1n = Gauge('last_sum1n', 'Value stores last result of sum1n')
last_fibo = Gauge('last_fibo', 'Value stores last result of fibo')
last_calculator = Gauge('last_calculator', 'Value stores last result of calculator')
errors_calculator_total = Counter(
'errors_calculator_total', 'Number of errors in calculator'
)

# Middleware для отслеживания запросов
@app.middleware("http")
async def metrics_middleware(request: Request, call_next):
start_time = time.time()
method = request.method
endpoint = request.url.path
http_requests_total.labels(method=method, endpoint=endpoint).inc()

try:
response = await call_next(request)
except Exception as e:
if endpoint == "/calculator":
errors_calculator_total.inc()
raise e
finally:
duration = (time.time() - start_time) * 1000
http_requests_milliseconds.labels(method=method, endpoint=endpoint).observe(duration)

return response

# Обработчики запросов
@app.get("/sum1n")
def sum1n(n: int):
result = sum(range(1, n + 1))
last_sum1n.set(result)
return {"result": result}

@app.get("/fibo")
def fibo(n: int):
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

result = fibonacci(n)
last_fibo.set(result)
return {"result": result}

@app.get("/calculator")
def calculator(operation: str, a: float, b: float):
try:
if operation == "add":
result = a + b
elif operation == "subtract":
result = a - b
elif operation == "multiply":
result = a * b
elif operation == "divide":
if b == 0:
raise ZeroDivisionError
result = a / b
else:
raise ValueError("Invalid operation")
last_calculator.set(result)
return {"result": result}
except (ValueError, ZeroDivisionError) as e:
errors_calculator_total.inc()
return {"error": str(e)}

# Настройка Prometheus Exporter
from starlette.middleware import Middleware
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
7 changes: 7 additions & 0 deletions monitoring/add-metrics/prometheus.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
global:
scrape_interval: 15s

scrape_configs:
- job_name: 'fastapi'
static_configs:
- targets: ['api:8000']
3 changes: 3 additions & 0 deletions monitoring/add-metrics/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fastapi
uvicorn
prometheus-client==0.16.0
79 changes: 73 additions & 6 deletions python/легкие вопросы/Readme.Md
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,46 @@ Sample Input:
Sample Output:
1

ответ:
def int_cmp(a, b):
if a > b:
return 1
elif a == b:
return 0
else:
return -1
a, b = map(int, input().split())
print(int_cmp(a, b))

##max-of-three
Дается три числа a, b и c. Вернуть максимальное число из них.
Sample Input:
42 1 0
Sample Output:
42

ответ
def max_of_three(a, b, c):
return max(a, b, c)
a, b, c = map(int, input("Введите три числа через пробел: ").split())
print(max_of_three(a, b, c))

#Циклы
##sqr-sum-1-n
Вернуть сумму квадратов чисел от 1 до n включительно.
Ограничения
1 <= n <= 10860



Sample Input:
3
Sample Output:
14

ответ
def sqr_sum(n):
return (n * (n + 1) * (2 * n + 1)) // 6
n = int(input("Введите число n: "))
print(sqr_sum(n))




Expand All @@ -40,7 +59,13 @@ Sample Input:
0 4
Sample Output:
0 2 4

ответ
def print_even(a, b):
for i in range(a, b + 1):
if i % 2 == 0:
print(i, end=" ")
a, b = map(int, input().split())
print_even(a, b)

##pow-a-b
Вернуть число a в степени b. Используя цикл.
Expand All @@ -51,7 +76,14 @@ Sample Input:
2 6
Sample Output:
64

ответ
def power(a, b):
result = 1
for _ in range(b):
result *= a
return result
a, b = map(int, input().split())
print(power(a, b))


##calc-deposit
Expand All @@ -68,6 +100,13 @@ Sample Input:
Sample Output:
1050.0

ответ
def calc_deposit(n, k, b):
for _ in range(n):
b += b * (k / 100)
return b
n, k, b = map(int, input().split())
print(calc_deposit(n, k, b))



Expand All @@ -82,7 +121,13 @@ Sample Input:
[1, 2, 3]
Sample Output:
1

ответ
def min_array(arr):
if len(arr) == 0:
return 0
return min(arr)
arr = [1, 2, 3]
print(min_array(arr))

##range
Реализовать функцию range, которая создает массив размером n, заполняет ячейки значениями от 1 до n и возвращает созданный массив.
Expand All @@ -101,6 +146,11 @@ Sample Input:
Sample Output:
[1, 2, 3, 4, 5]

ответ
def range_array(n):
return [i for i in range(1, n + 1)]
n = int(input())
print(range_array(n))

##sum
Реализовать функцию sum, которая возвращает сумму чисел массива.
Expand All @@ -115,6 +165,11 @@ Sample Input:
[1, 2, 3]
Sample Output:
6
ответ
def sum_array(arr):
return sum(arr)
arr = [1, 2, 3]
print(sum_array(arr))

##sort
Реализовать функцию sort, которая принимает массив array(int[]). Функция должна отсортировать массив по возрастанию.
Expand All @@ -136,3 +191,15 @@ Sample Input:
Sample Output:
[1, 2, 3]

ответ
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
arr = [7, 5, 9, 1, 4]
selection_sort(arr)
print(arr)
Loading