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
165 changes: 165 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/


.DS_Store
5 changes: 5 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
98 changes: 75 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,83 @@
# Instructions
# Server Inventory Manager

You are developing an inventory management software solution for a cloud services company that provisions servers in multiple data centers. You must build a CRUD app for tracking the state of all the servers.
A CRUD application to manage server inventory across data centers. Built with FastAPI and PostgreSQL using raw SQL.

Deliverables:
- PR to https://github.com/Mathpix/hiring-challenge-devops-python that includes:
- API code
- CLI code
- pytest test suite
- Working Docker Compose stack
## Features
- REST API for Server management.
- CLI tool.
- Raw SQL implementation.
- Hostname uniqueness enforcement.
- IP address and State validation.

Short API.md on how to run everything, also a short API and CLI spec
## Prerequisites
- Docker & Docker Compose
- Python 3.11+ (if running CLI locally)

Required endpoints:
- POST /servers → create a server
- GET /servers → list all servers
- GET /servers/{id} → get one server
- PUT /servers/{id} → update server
- DELETE /servers/{id} → delete server
## Project Structure

Requirements:
- Use FastAPI or Flask
- Store data in PostgreSQL
- Use raw SQL
```text
├── app
│ ├── database.py # Raw SQL wrapper
│ ├── main.py # API Endpoints
│ └── models.py # Pydantic schemas
├── cli
│ └── main.py # CLI Tool
├── tests
│ └── test_api.py # Pytest suite
├── docker-compose.yml
└── Dockerfile
```

Validate that:
- hostname is unique
- IP address looks like an IP
## How to Run

State is one of: active, offline, retired
### 1. Start the Application
Build and start the API and Database containers:

```bash
docker-compose up --build
```

The API will be accessible at: http://localhost:8000
Automatic API Docs (Swagger UI): http://localhost:8000/docs

### 2. Run the Test Suite
Execute the pytest suite inside the running container to verify functionality:

```bash
docker-compose run --rm api pytest -v
```

### CLI Usage
You can run the CLI tool from your local machine (requires Python installed) or enter the container to run it.

Option A: Running Locally (Recommended)
#### 1. Install Dependencies:
```bash
pip install -r requirements.txt
```

#### 2. Commands:
- Create a server
```bash
python cli/main.py create "srv-node-01" "192.168.1.50" --state active
```
- List all servers
```bash
python cli/main.py list
```
- Get a single server
```bash
# Replace 1 with the actual ID
python cli/main.py get 1
```
- Update a server
```bash
# Change state to offline
python cli/main.py update 1 --state offline
# Change IP address
python cli/main.py update 1 --ip "192.168.1.11"
```
- Delete a server
```bash
python cli/main.py delete 1
```
Empty file added app/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os
import asyncpg
from typing import List, Optional, Any

DATABASE_URL = os.getenv("DATABASE_URL", "postgres://postgres:postgres@localhost:5432/postgres")

class Database:
def __init__(self):
self.pool = None

async def connect(self):
self.pool = await asyncpg.create_pool(DATABASE_URL)
await self.init_db()

async def close(self):
await self.pool.close()

async def init_db(self):
query = """
CREATE TABLE IF NOT EXISTS servers (
id SERIAL PRIMARY KEY,
hostname VARCHAR(255) UNIQUE NOT NULL,
ip_address VARCHAR(45) NOT NULL,
state VARCHAR(20) NOT NULL CHECK (state IN ('active', 'offline', 'retired'))
);
"""
async with self.pool.acquire() as connection:
await connection.execute(query)

async def fetch_all(self, query: str, *args) -> List[dict]:
async with self.pool.acquire() as connection:
rows = await connection.fetch(query, *args)
return [dict(row) for row in rows]

async def fetch_one(self, query: str, *args) -> Optional[dict]:
async with self.pool.acquire() as connection:
row = await connection.fetchrow(query, *args)
return dict(row) if row else None

async def execute(self, query: str, *args) -> Any:
async with self.pool.acquire() as connection:
return await connection.fetchval(query, *args)

db = Database()
Loading