diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..791cf14 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +coordinates_cache.json +__pycache__/ +*.pyc +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..51cd6d4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +EXPOSE 8000 + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/README.md b/README.md index 96061c3..2b749dd 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,195 @@ -# dvirlabs-project +# Open-Meteo Coordinates Service +A FastAPI-based microservice that queries the Open-Meteo Geocoding API to retrieve coordinates for various cities. The service includes caching, Prometheus metrics, and Grafana dashboards for monitoring. +## Features -## Getting started +- **RESTful API** for retrieving city coordinates +- **Intelligent caching** to reduce external API calls +- **Prometheus metrics** for observability +- **Pre-configured Grafana dashboards** with 5 panels +- **Docker Compose** setup for easy deployment -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## Prerequisites -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +- Docker +- Docker Compose -## Add your files +## Quick Start -* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files -* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: +1. **Clone the repository** + ```bash + cd open-meteo-service + ``` -``` -cd existing_repo -git remote add origin https://gitlab.com/dvirlabs-group/dvirlabs-project.git -git branch -M main -git push -uf origin main +2. **Start all services** + ```bash + docker compose up --build + ``` + +3. **Access the services** + - API: http://localhost:8000/docs + - Prometheus: http://localhost:9090 + - Grafana: http://localhost:3000 (admin/admin) + +## API Documentation + +### Endpoints + +#### `GET /coordinates` +Retrieve coordinates for all configured cities. + +**Response:** +```json +{ + "source": "cache", + "data": { + "Tel Aviv": { + "name": "Tel Aviv", + "latitude": 32.08088, + "longitude": 34.78057, + "country": "Israel" + }, + ... + } +} ``` -## Integrate with your tools +#### `GET /coordinates/{city}` +Retrieve coordinates for a specific city. -* [Set up project integrations](https://gitlab.com/dvirlabs-group/dvirlabs-project/-/settings/integrations) +**Parameters:** +- `city` (path) - City name (e.g., "Ashkelon", "London") -## Collaborate with your team +**Example:** +```bash +curl http://localhost:8000/coordinates/Paris +``` -* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/) -* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/) -* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically) -* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/) -* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) +**Response:** +```json +{ + "source": "open-meteo", + "data": { + "name": "Paris", + "latitude": 48.85341, + "longitude": 2.3488, + "country": "France" + } +} +``` -## Test and Deploy +#### `GET /metrics` +Prometheus metrics endpoint exposing service metrics. -Use the built-in continuous integration in GitLab. +**Example:** +```bash +curl http://localhost:8000/metrics +``` -* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/) -* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/) -* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/) -* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/) -* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/) +#### `GET /healthz` +Health check endpoint. -*** +**Response:** +```json +{ + "status": "ok" +} +``` -# Editing this README +## Metrics -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +The service exposes the following Prometheus metrics: -## Suggestions for a good README +### HTTP Metrics +- **`http_requests_total`** - Counter of total HTTP requests + - Labels: `endpoint`, `method`, `status` + +- **`http_request_duration_seconds`** - Histogram of request durations + - Labels: `endpoint`, `method` -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +### Cache Metrics +- **`coordinates_cache_hits_total`** - Counter of cache hits +- **`coordinates_cache_misses_total`** - Counter of cache misses -## Name -Choose a self-explaining name for your project. +### External API Metrics +- **`openmeteo_api_calls_total`** - Counter of calls to Open-Meteo Geocoding API + - Labels: `city` -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +## Grafana Dashboard -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +The pre-configured dashboard includes 5 panels: -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +1. **Request Rate** - Requests per second by endpoint +2. **Request Duration p95** - 95th percentile latency +3. **Cache Hits vs Misses** - Cache effectiveness +4. **Open-Meteo Calls by City** - External API usage per city +5. **Requests by Status** - HTTP status code distribution -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +Access the dashboard at http://localhost:3000 after logging in with `admin/admin`. -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +## Caching -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +The service uses a local JSON file (`coordinates_cache.json`) to cache city coordinates: +- Reduces external API calls +- Shared across all API endpoints +- Persists between requests (not container restarts) +- Automatically updated when new cities are queried -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +## Development -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +### Project Structure +``` +. +├── app/ +│ ├── main.py # FastAPI application +│ ├── service.py # Business logic & caching +│ └── metrics.py # Prometheus metrics definitions +├── grafana/ +│ ├── provisioning/ # Auto-configured datasources & dashboards +│ └── dashboards/ # Dashboard JSON definitions +├── docker-compose.yml # Service orchestration +├── Dockerfile # Python app container +├── prometheus.yml # Prometheus scrape configuration +└── requirements.txt # Python dependencies +``` -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +### Stop Services +```bash +docker compose down +``` -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +### View Logs +```bash +docker compose logs -f open-meteo-service +``` -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +### Rebuild After Code Changes +```bash +docker compose up --build +``` + +## Configuration + +### Environment Variables +- `CACHE_FILE` - Path to cache file (default: `coordinates_cache.json`) + +### Scrape Interval +Edit `prometheus.yml` to adjust the scrape interval (default: 15s). + +## Testing + +Generate test traffic to populate metrics: +```bash +# Test all endpoints +curl http://localhost:8000/coordinates +curl http://localhost:8000/coordinates/Paris +curl http://localhost:8000/coordinates/London + +# Generate load +for i in {1..10}; do curl -s http://localhost:8000/coordinates > /dev/null; done +``` ## License -For open source projects, say how it is licensed. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +MIT diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..b8965c2 --- /dev/null +++ b/app/main.py @@ -0,0 +1,36 @@ +from fastapi import FastAPI, Response +from prometheus_client import generate_latest, CONTENT_TYPE_LATEST + +from .service import get_all_coordinates, get_coordinates_for_city +from .metrics import RequestTimer + +app = FastAPI(title="Open-Meteo Coordinates Service") + + +@app.get("/coordinates") +def coordinates(): + with RequestTimer(endpoint="/coordinates", method="GET") as t: + try: + return get_all_coordinates() + except Exception: + t.set_status("500") + raise + + +@app.get("/coordinates/{city}") +def coordinates_for_city(city: str): + with RequestTimer(endpoint="/coordinates/{city}", method="GET") as t: + try: + return get_coordinates_for_city(city) + except Exception: + t.set_status("500") + raise + +@app.get("/metrics") +def metrics(): + return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST) + + +@app.get("/healthz") +def healthz(): + return {"status": "ok"} diff --git a/app/metrics.py b/app/metrics.py new file mode 100644 index 0000000..78aa00a --- /dev/null +++ b/app/metrics.py @@ -0,0 +1,54 @@ +import time +from prometheus_client import Counter, Histogram + +HTTP_REQUESTS_TOTAL = Counter( + "http_requests_total", + "Total HTTP requests", + ["endpoint", "method", "status"], +) + +HTTP_REQUEST_DURATION_SECONDS = Histogram( + "http_request_duration_seconds", + "HTTP request duration in seconds", + ["endpoint", "method"], +) + +CACHE_HITS_TOTAL = Counter( + "coordinates_cache_hits_total", + "Total cache hits for coordinates", +) + +CACHE_MISSES_TOTAL = Counter( + "coordinates_cache_misses_total", + "Total cache misses for coordinates", +) + +OPENMETEO_CALLS_TOTAL = Counter( + "openmeteo_api_calls_total", + "Total calls made to Open-Meteo Geocoding API", + ["city"], +) + + +class RequestTimer: + """Small helper to measure request duration and emit metrics.""" + def __init__(self, endpoint: str, method: str): + self.endpoint = endpoint + self.method = method + self.start = None + self.status = "200" + + def __enter__(self): + self.start = time.time() + return self + + def set_status(self, status: str): + self.status = status + + def __exit__(self, exc_type, exc, tb): + HTTP_REQUESTS_TOTAL.labels( + endpoint=self.endpoint, method=self.method, status=self.status + ).inc() + HTTP_REQUEST_DURATION_SECONDS.labels( + endpoint=self.endpoint, method=self.method + ).observe(time.time() - self.start) diff --git a/app/service.py b/app/service.py new file mode 100644 index 0000000..da86b8e --- /dev/null +++ b/app/service.py @@ -0,0 +1,78 @@ +import json +import os +from typing import Dict, Any + +import requests +from .metrics import CACHE_HITS_TOTAL, CACHE_MISSES_TOTAL, OPENMETEO_CALLS_TOTAL + +API_URL = "https://geocoding-api.open-meteo.com/v1/search" +CITIES = ["Tel Aviv", "Beer Sheva", "Jerusalem", "Szeged"] + +CACHE_FILE = os.environ.get("CACHE_FILE", "coordinates_cache.json") + + +def _fetch_coordinates(city: str) -> Dict[str, Any]: + OPENMETEO_CALLS_TOTAL.labels(city=city).inc() + + params = {"name": city, "count": 1} + r = requests.get(API_URL, params=params, timeout=10) + r.raise_for_status() + data = r.json() + + if "results" not in data or not data["results"]: + raise ValueError(f"No results found for {city}") + + result = data["results"][0] + return { + "name": result.get("name"), + "latitude": result.get("latitude"), + "longitude": result.get("longitude"), + "country": result.get("country"), + } + + +def _load_cache() -> Dict[str, Any] | None: + if os.path.exists(CACHE_FILE): + with open(CACHE_FILE, "r", encoding="utf-8") as f: + return json.load(f) + return None + + +def _save_cache(data: Dict[str, Any]) -> None: + with open(CACHE_FILE, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + + +def get_all_coordinates() -> Dict[str, Any]: + cached = _load_cache() + if cached: + CACHE_HITS_TOTAL.inc() + return {"source": "cache", "data": cached} + + CACHE_MISSES_TOTAL.inc() + + results: Dict[str, Any] = {} + for city in CITIES: + results[city] = _fetch_coordinates(city) + + _save_cache(results) + return {"source": "open-meteo", "data": results} + + +def get_coordinates_for_city(city: str) -> Dict[str, Any]: + cached = _load_cache() + if cached and city in cached: + CACHE_HITS_TOTAL.inc() + return {"source": "cache", "data": cached[city]} + + CACHE_MISSES_TOTAL.inc() + + result = _fetch_coordinates(city) + + # Update cache with the new city + if cached is None: + cached = {} + cached[city] = result + _save_cache(cached) + + return {"source": "open-meteo", "data": result} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..92addad --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,54 @@ +version: '3.8' + +services: + open-meteo-service: + build: + context: . + dockerfile: Dockerfile + image: open-meteo-service:local + container_name: open-meteo-service + ports: + - "8000:8000" + networks: + - monitoring + + prometheus: + image: prom/prometheus:latest + container_name: prometheus + ports: + - "9090:9090" + volumes: + - ./prometheus.yml:/etc/prometheus/prometheus.yml + - prometheus_data:/prometheus + command: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + networks: + - monitoring + depends_on: + - open-meteo-service + + grafana: + image: grafana/grafana:latest + container_name: grafana + ports: + - "3000:3000" + environment: + - GF_SECURITY_ADMIN_PASSWORD=admin + - GF_SECURITY_ADMIN_USER=admin + volumes: + - grafana_data:/var/lib/grafana + - ./grafana/provisioning:/etc/grafana/provisioning + - ./grafana/dashboards:/var/lib/grafana/dashboards + networks: + - monitoring + depends_on: + - prometheus + +networks: + monitoring: + driver: bridge + +volumes: + prometheus_data: + grafana_data: diff --git a/grafana/dashboards/open-meteo-service.json b/grafana/dashboards/open-meteo-service.json new file mode 100644 index 0000000..9fbc437 --- /dev/null +++ b/grafana/dashboards/open-meteo-service.json @@ -0,0 +1,107 @@ +{ + "uid": "open-meteo-service", + "title": "Open-Meteo Service", + "timezone": "browser", + "schemaVersion": 38, + "version": 1, + "refresh": "10s", + "time": { + "from": "now-15m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "type": "timeseries", + "title": "Request Rate", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "sum(rate(http_requests_total[5m])) by (endpoint, method)", + "legendFormat": "{{endpoint}} {{method}}", + "refId": "A" + } + ] + }, + { + "id": 2, + "type": "timeseries", + "title": "Request Duration p95", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { "x": 12, "y": 0, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, endpoint, method))", + "legendFormat": "{{endpoint}} {{method}}", + "refId": "A" + } + ] + }, + { + "id": 3, + "type": "timeseries", + "title": "Cache Hits vs Misses", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { "x": 0, "y": 8, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "rate(coordinates_cache_hits_total[5m])", + "legendFormat": "hits", + "refId": "A" + }, + { + "expr": "rate(coordinates_cache_misses_total[5m])", + "legendFormat": "misses", + "refId": "B" + } + ] + }, + { + "id": 4, + "type": "timeseries", + "title": "Open-Meteo Calls by City", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { "x": 12, "y": 8, "w": 12, "h": 8 }, + "targets": [ + { + "expr": "sum(rate(openmeteo_api_calls_total[5m])) by (city)", + "legendFormat": "{{city}}", + "refId": "A" + } + ] + }, + { + "id": 5, + "type": "timeseries", + "title": "Requests by Status", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { "x": 0, "y": 16, "w": 24, "h": 8 }, + "targets": [ + { + "expr": "sum(rate(http_requests_total[5m])) by (status)", + "legendFormat": "{{status}}", + "refId": "A" + } + ] + } + ], + "templating": { + "list": [] + } +} diff --git a/grafana/provisioning/dashboards/dashboard.yml b/grafana/provisioning/dashboards/dashboard.yml new file mode 100644 index 0000000..ea7dac0 --- /dev/null +++ b/grafana/provisioning/dashboards/dashboard.yml @@ -0,0 +1,10 @@ +apiVersion: 1 + +providers: + - name: default + type: file + disableDeletion: false + editable: true + updateIntervalSeconds: 10 + options: + path: /var/lib/grafana/dashboards diff --git a/grafana/provisioning/datasources/datasource.yml b/grafana/provisioning/datasources/datasource.yml new file mode 100644 index 0000000..369ea61 --- /dev/null +++ b/grafana/provisioning/datasources/datasource.yml @@ -0,0 +1,9 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + uid: prometheus diff --git a/prometheus.yml b/prometheus.yml new file mode 100644 index 0000000..ae9e38a --- /dev/null +++ b/prometheus.yml @@ -0,0 +1,12 @@ +global: + scrape_interval: 15s + +scrape_configs: + - job_name: "prometheus" + static_configs: + - targets: ["prometheus:9090"] + + - job_name: "open-meteo-service" + metrics_path: "/metrics" + static_configs: + - targets: ["open-meteo-service:8000"] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2b999f6 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +fastapi==0.115.8 +uvicorn[standard]==0.30.6 +requests==2.32.3 +prometheus-client==0.21.1