diff --git a/.gitignore b/.gitignore index df28da4..078c693 100644 --- a/.gitignore +++ b/.gitignore @@ -62,12 +62,6 @@ htmlcov/ coverage.xml *.cover -# dotenv environment files -.env.local -.env.* -.env -!.env.example - # Ignore generated files and backups *.orig *.rej @@ -82,3 +76,15 @@ public/ # Ignore personal notes or drafts private-notes/ drafts/ + +# Docker +.docker-env +.docker-cache +docker-compose.override.yml + +# Environment variables +.env.local +.env.* +.env +!.env.example +docker/environments/databases/.env diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b28b29e --- /dev/null +++ b/Makefile @@ -0,0 +1,48 @@ +.PHONY: build run-snippet help db-start db-stop db-run-snippet + +help: + @echo "Tech Notes Hub Docker Environment" + @echo "=================================" + @echo "" + @echo "Usage:" + @echo " make build Build all Docker environments" + @echo " make run-snippet FILE=path Run a specific code snippet" + @echo " make db-start DB=type Start a specific database (mysql, postgres, mongodb, redis, sqlite)" + @echo " make db-stop DB=type Stop a specific database" + @echo " make db-run-snippet DB=type FILE=path Run a code snippet with database connection" + @echo " make help Show this help message" + +build: + docker-compose build + +run-snippet: + @if [ -z "$(FILE)" ]; then \ + echo "Error: Please specify a file path. Example: make run-snippet FILE=snippets/algorithms/graph-traversal/graph_traversal.py"; \ + exit 1; \ + fi + ./docker/run-snippet.sh $(FILE) + +db-start: + @if [ -z "$(DB)" ]; then \ + echo "Error: Please specify a database type. Example: make db-start DB=mysql"; \ + exit 1; \ + fi + docker-compose -f docker/environments/databases/docker-compose.yml up -d $(DB) + +db-stop: + @if [ -z "$(DB)" ]; then \ + echo "Error: Please specify a database type. Example: make db-stop DB=mysql"; \ + exit 1; \ + fi + docker-compose -f docker/environments/databases/docker-compose.yml stop $(DB) + +db-run-snippet: + @if [ -z "$(DB)" ]; then \ + echo "Error: Please specify a database type. Example: make db-run-snippet DB=mysql FILE=path/to/file.py"; \ + exit 1; \ + fi + @if [ -z "$(FILE)" ]; then \ + echo "Error: Please specify a file path. Example: make db-run-snippet DB=mysql FILE=path/to/file.py"; \ + exit 1; \ + fi + ./docker/run-db-snippet.sh $(DB) $(FILE) diff --git a/README.md b/README.md index 3a87c67..97b5e37 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,16 @@ Simply browse the folders or use GitHub's search feature to find the topic or pa **For a complete table of contents with all available notes and resources, check out the [SUMMARY.md](SUMMARY.md) file.** +### 🐳 Docker Environments + +This repository includes Docker configurations for running code snippets in various programming languages. To run a code snippet: + +```bash +./docker/run-snippet.sh snippets/path/to/your/snippet.py +``` + +For more information on Docker usage, see the [Docker README](docker/README.md). + ## 🤝 Contribution Contributions are highly welcome! If you want to: diff --git a/README_vi.md b/README_vi.md index 1ff2b93..2663314 100644 --- a/README_vi.md +++ b/README_vi.md @@ -54,6 +54,16 @@ Mỗi ghi chú đều độc lập, bao gồm lý thuyết và mã ví dụ th **Để xem danh mục đầy đủ với tất cả các ghi chú và tài nguyên có sẵn, hãy xem file [SUMMARY.md](SUMMARY.md).** +### 🐳 Môi Trường Docker + +Kho lưu trữ này bao gồm cấu hình Docker để chạy đoạn mã trong nhiều ngôn ngữ lập trình khác nhau. Để chạy một đoạn mã: + +```bash +./docker/run-snippet.sh snippets/path/to/your/snippet.py +``` + +Để biết thêm thông tin về cách sử dụng Docker, hãy xem [Docker README](docker/README_vi.md). + ## 🤝 Đóng góp Mọi đóng góp đều rất hoan nghênh! Nếu bạn muốn: diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..51e758a --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,112 @@ +version: '1.0' + +services: + # Python environment + python: + build: + context: . + dockerfile: docker/environments/python/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["--version"] + + # JavaScript/Node.js environment + javascript: + build: + context: . + dockerfile: docker/environments/javascript/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["--version"] + + # Java environment + java: + build: + context: . + dockerfile: docker/environments/java/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["/bin/bash", "-c", "java -version"] + + # C/C++ environment + cpp: + build: + context: . + dockerfile: docker/environments/cpp/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["/bin/bash", "-c", "g++ --version"] + + # Go environment + go: + build: + context: . + dockerfile: docker/environments/go/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["version"] + + # Rust environment + rust: + build: + context: . + dockerfile: docker/environments/rust/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["/bin/bash", "-c", "rustc --version"] + + # PHP environment + php: + build: + context: . + dockerfile: docker/environments/php/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["--version"] + + # C# environment + csharp: + build: + context: . + dockerfile: docker/environments/csharp/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["/bin/bash", "-c", "dotnet --version"] + + # Ruby environment + ruby: + build: + context: . + dockerfile: docker/environments/ruby/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["--version"] + + # Shell environment for Linux and DevOps scripts + shell: + build: + context: . + dockerfile: docker/environments/shell/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["-c", "echo 'Shell environment ready'"] + + # Databricks/PySpark environment + databricks: + build: + context: . + dockerfile: docker/environments/databricks/Dockerfile + volumes: + - ./snippets:/app/snippets + working_dir: /app + command: ["--version"] diff --git a/docker/DATABASE_GUIDE.md b/docker/DATABASE_GUIDE.md new file mode 100644 index 0000000..cd26fd0 --- /dev/null +++ b/docker/DATABASE_GUIDE.md @@ -0,0 +1,158 @@ +# Database Usage Guide with Docker + +This guide helps you run code snippets with connections to databases in Docker environments. + +## Supported Databases + +- **MySQL** (8.0) +- **PostgreSQL** (15) +- **MongoDB** (6) +- **Redis** (7) +- **SQLite** (3.x) + +## How to Use + +### 1. Start a Specific Database + +```bash +# Using Docker Compose directly +docker-compose -f docker/environments/databases/docker-compose.yml up -d mysql + +# Or using the Makefile +make db-start DB=mysql +``` + +Valid values for DB are: `mysql`, `postgres`, `mongodb`, `redis`, `sqlite` + +### 2. Run a Code Snippet with Database Connection + +```bash +# Using the script directly +./docker/run-db-snippet.sh mysql snippets/databases/mysql_example.py + +# Or using the Makefile +make db-run-snippet DB=mysql FILE=snippets/databases/mysql_example.py +``` + +### 3. Stop a Database When Not in Use + +```bash +# Using Docker Compose directly +docker-compose -f docker/environments/databases/docker-compose.yml stop mysql + +# Or using the Makefile +make db-stop DB=mysql +``` + +## Database Connection Information + +When running a code snippet with a database, the following environment variables will be automatically passed to the container: + +- `DB_HOST`: Database hostname +- `DB_PORT`: Database port +- `DB_USER`: Username for connection +- `DB_PASS`: Password for connection +- `DB_NAME`: Database name +- `DB_CONN_STR`: Full connection string + +### Default Connection Strings + +- **MySQL**: `mysql://user:password@tech-notes-mysql:3306/tech_notes` +- **PostgreSQL**: `postgresql://user:password@tech-notes-postgres:5432/tech_notes` +- **MongoDB**: `mongodb://user:password@tech-notes-mongodb:27017/tech_notes` +- **Redis**: `redis://tech-notes-redis:6379` +- **SQLite**: `sqlite:///data/tech_notes.db` + +### Environment Variables Configuration + +To change the default connection information, you can create a `.env` file in the `docker/environments/databases/` directory: + +1. Copy the `.env.example` file to `.env`: + ```bash + cp docker/environments/databases/.env.example docker/environments/databases/.env + ``` + +2. Edit the `.env` file to change the connection information (usernames, passwords, database names, etc.) + +3. When running the `run-db-snippet.sh` command or `make db-run-snippet`, the environment variables from the `.env` file will be automatically used. + +Note: The `.env` file has been added to `.gitignore` to prevent it from being tracked by Git, ensuring sensitive information is not pushed to the repository. + +## Example Connection Code + +### Python with MySQL + +```python +import os +import mysql.connector + +# Get connection info from environment variables +db_host = os.environ.get('DB_HOST', 'localhost') +db_port = os.environ.get('DB_PORT', '3306') +db_user = os.environ.get('DB_USER', 'user') +db_pass = os.environ.get('DB_PASS', 'password') +db_name = os.environ.get('DB_NAME', 'tech_notes') + +# Connect to the database +conn = mysql.connector.connect( + host=db_host, + port=db_port, + user=db_user, + password=db_pass, + database=db_name +) + +cursor = conn.cursor() +cursor.execute("SELECT * FROM users") +users = cursor.fetchall() + +for user in users: + print(user) + +conn.close() +``` + +### JavaScript with MongoDB + +```javascript +const { MongoClient } = require('mongodb'); + +// Get connection string from environment variable +const uri = process.env.DB_CONN_STR || 'mongodb://user:password@localhost:27017/tech_notes'; + +async function main() { + const client = new MongoClient(uri); + + try { + await client.connect(); + const database = client.db('tech_notes'); + const users = database.collection('users'); + + const query = {}; + const cursor = users.find(query); + + if ((await cursor.count()) === 0) { + console.log("No documents found!"); + } + + await cursor.forEach(user => { + console.log(user); + }); + + } finally { + await client.close(); + } +} + +main().catch(console.error); +``` + +## Sample Data + +Each database has been configured with the following sample data: + +- `users` table/collection with 3 users +- `posts` table/collection with 4 posts linked to users + +You can see the details of the sample data in the init files in the respective directory of each database. + diff --git a/docker/DATABASE_GUIDE_vi.md b/docker/DATABASE_GUIDE_vi.md new file mode 100644 index 0000000..7c1f513 --- /dev/null +++ b/docker/DATABASE_GUIDE_vi.md @@ -0,0 +1,157 @@ +# Hướng Dẫn Sử Dụng Database với Docker + +Hướng dẫn này giúp bạn chạy code snippets có kết nối tới các database trong môi trường Docker. + +## Các Database Được Hỗ Trợ + +- **MySQL** (8.0) +- **PostgreSQL** (15) +- **MongoDB** (6) +- **Redis** (7) +- **SQLite** (3.x) + +## Cách Sử Dụng + +### 1. Khởi động một Database cụ thể + +```bash +# Sử dụng Docker Compose trực tiếp +docker-compose -f docker/environments/databases/docker-compose.yml up -d mysql + +# Hoặc sử dụng Makefile +make db-start DB=mysql +``` + +Các giá trị hợp lệ cho DB là: `mysql`, `postgres`, `mongodb`, `redis`, `sqlite` + +### 2. Chạy Code Snippet với kết nối Database + +```bash +# Sử dụng script trực tiếp +./docker/run-db-snippet.sh mysql snippets/databases/mysql_example.py + +# Hoặc sử dụng Makefile +make db-run-snippet DB=mysql FILE=snippets/databases/mysql_example.py +``` + +### 3. Tắt Database khi không sử dụng + +```bash +# Sử dụng Docker Compose trực tiếp +docker-compose -f docker/environments/databases/docker-compose.yml stop mysql + +# Hoặc sử dụng Makefile +make db-stop DB=mysql +``` + +## Thông Tin Kết Nối Database + +Khi chạy code snippet với database, các biến môi trường sau sẽ được tự động truyền vào container: + +- `DB_HOST`: Hostname của database +- `DB_PORT`: Port của database +- `DB_USER`: Username để kết nối +- `DB_PASS`: Password để kết nối +- `DB_NAME`: Tên database +- `DB_CONN_STR`: Connection string đầy đủ + +### Các Connection String Mặc Định + +- **MySQL**: `mysql://user:password@tech-notes-mysql:3306/tech_notes` +- **PostgreSQL**: `postgresql://user:password@tech-notes-postgres:5432/tech_notes` +- **MongoDB**: `mongodb://user:password@tech-notes-mongodb:27017/tech_notes` +- **Redis**: `redis://tech-notes-redis:6379` +- **SQLite**: `sqlite:///data/tech_notes.db` + +### Cấu Hình Biến Môi Trường + +Để thay đổi các thông tin kết nối mặc định, bạn có thể tạo một file `.env` trong thư mục `docker/environments/databases/`: + +1. Sao chép file `.env.example` thành `.env`: + ```bash + cp docker/environments/databases/.env.example docker/environments/databases/.env + ``` + +2. Chỉnh sửa file `.env` để thay đổi các thông tin kết nối (tên người dùng, mật khẩu, tên database, v.v.) + +3. Khi chạy lệnh `run-db-snippet.sh` hoặc `make db-run-snippet`, các biến môi trường từ file `.env` sẽ được tự động sử dụng. + +Lưu ý: File `.env` đã được thêm vào `.gitignore` để không theo dõi bởi Git, đảm bảo thông tin nhạy cảm không bị đưa lên repository. + +## Ví Dụ Code Kết Nối + +### Python với MySQL + +```python +import os +import mysql.connector + +# Lấy thông tin kết nối từ biến môi trường +db_host = os.environ.get('DB_HOST', 'localhost') +db_port = os.environ.get('DB_PORT', '3306') +db_user = os.environ.get('DB_USER', 'user') +db_pass = os.environ.get('DB_PASS', 'password') +db_name = os.environ.get('DB_NAME', 'tech_notes') + +# Kết nối tới database +conn = mysql.connector.connect( + host=db_host, + port=db_port, + user=db_user, + password=db_pass, + database=db_name +) + +cursor = conn.cursor() +cursor.execute("SELECT * FROM users") +users = cursor.fetchall() + +for user in users: + print(user) + +conn.close() +``` + +### JavaScript với MongoDB + +```javascript +const { MongoClient } = require('mongodb'); + +// Lấy connection string từ biến môi trường +const uri = process.env.DB_CONN_STR || 'mongodb://user:password@localhost:27017/tech_notes'; + +async function main() { + const client = new MongoClient(uri); + + try { + await client.connect(); + const database = client.db('tech_notes'); + const users = database.collection('users'); + + const query = {}; + const cursor = users.find(query); + + if ((await cursor.count()) === 0) { + console.log("No documents found!"); + } + + await cursor.forEach(user => { + console.log(user); + }); + + } finally { + await client.close(); + } +} + +main().catch(console.error); +``` + +## Dữ Liệu Mẫu + +Mỗi database đã được cấu hình với dữ liệu mẫu sau: + +- Bảng/Collection `users` với 3 người dùng +- Bảng/Collection `posts` với 4 bài viết liên kết với người dùng + +Bạn có thể xem chi tiết dữ liệu mẫu trong các file init trong thư mục tương ứng của mỗi database. diff --git a/docker/QUICK_START.md b/docker/QUICK_START.md new file mode 100644 index 0000000..c2e9a5e --- /dev/null +++ b/docker/QUICK_START.md @@ -0,0 +1,61 @@ +# Docker Quick Start Guide + +This guide will help you get started with running code snippets in Docker environments. + +## Prerequisites + +1. Docker installed on your machine +2. Docker Compose installed on your machine + +## Getting Started + +### 1. Build the Docker Environments + +First, build all the Docker environments: + +```bash +# Using Docker Compose directly +docker-compose build + +# Or using the Makefile +make build +``` + +### 2. Run a Code Snippet + +You can run any code snippet from the repository using the provided script: + +```bash +# Using the script directly +./docker/run-snippet.sh snippets/algorithms/graph-traversal/graph_traversal.py + +# Or using the Makefile +make run-snippet FILE=snippets/algorithms/graph-traversal/graph_traversal.py +``` + +The script automatically detects the file extension and uses the appropriate Docker container for the language. + +### 3. Running Different Languages + +The setup supports multiple programming languages: + +- **Python**: `.py` files +- **JavaScript**: `.js` files +- **Java**: `.java` files +- **C/C++**: `.c` and `.cpp` files +- **Go**: `.go` files +- **Rust**: `.rs` files +- **PHP**: `.php` files +- **C#**: `.cs` files +- **Ruby**: `.rb` files + +### 4. Troubleshooting + +If you encounter any issues: + +1. Make sure Docker and Docker Compose are installed and running +2. Verify that the Docker daemon is running +3. Check the file path provided to the run-snippet script +4. Ensure the file extension is supported + +For more detailed information, see the [Docker README](README.md). diff --git a/docker/QUICK_START_vi.md b/docker/QUICK_START_vi.md new file mode 100644 index 0000000..cf05b0e --- /dev/null +++ b/docker/QUICK_START_vi.md @@ -0,0 +1,61 @@ +# Hướng Dẫn Nhanh Docker + +Hướng dẫn này sẽ giúp bạn bắt đầu chạy các đoạn mã trong môi trường Docker. + +## Yêu Cầu Tiên Quyết + +1. Docker đã được cài đặt trên máy của bạn +2. Docker Compose đã được cài đặt trên máy của bạn + +## Bắt Đầu + +### 1. Xây Dựng Môi Trường Docker + +Đầu tiên, xây dựng tất cả các môi trường Docker: + +```bash +# Sử dụng Docker Compose trực tiếp +docker-compose build + +# Hoặc sử dụng Makefile +make build +``` + +### 2. Chạy Một Đoạn Mã + +Bạn có thể chạy bất kỳ đoạn mã nào từ kho lưu trữ bằng script được cung cấp: + +```bash +# Sử dụng script trực tiếp +./docker/run-snippet.sh snippets/algorithms/graph-traversal/graph_traversal.py + +# Hoặc sử dụng Makefile +make run-snippet FILE=snippets/algorithms/graph-traversal/graph_traversal.py +``` + +Script tự động phát hiện phần mở rộng tệp và sử dụng container Docker thích hợp cho ngôn ngữ đó. + +### 3. Chạy Các Ngôn Ngữ Khác Nhau + +Thiết lập hỗ trợ nhiều ngôn ngữ lập trình: + +- **Python**: Tệp `.py` +- **JavaScript**: Tệp `.js` +- **Java**: Tệp `.java` +- **C/C++**: Tệp `.c` và `.cpp` +- **Go**: Tệp `.go` +- **Rust**: Tệp `.rs` +- **PHP**: Tệp `.php` +- **C#**: Tệp `.cs` +- **Ruby**: Tệp `.rb` + +### 4. Xử Lý Sự Cố + +Nếu bạn gặp bất kỳ vấn đề nào: + +1. Đảm bảo Docker và Docker Compose đã được cài đặt và đang chạy +2. Xác minh rằng Docker daemon đang chạy +3. Kiểm tra đường dẫn tệp được cung cấp cho script run-snippet +4. Đảm bảo phần mở rộng tệp được hỗ trợ + +Để biết thông tin chi tiết hơn, hãy xem [Docker README](README_vi.md). diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..737bd7f --- /dev/null +++ b/docker/README.md @@ -0,0 +1,110 @@ +# Docker Environment for Tech Notes Hub + +This directory contains Docker configurations for running code snippets in various programming languages and environments. + +## Directory Structure + +- `environments/` - Contains Dockerfiles and setup scripts for each language + - `python/` - Python environment + - `javascript/` - JavaScript/Node.js environment + - `java/` - Java environment + - `cpp/` - C/C++ environment + - `go/` - Go environment + - `rust/` - Rust environment + - `php/` - PHP environment + - `csharp/` - C# environment + - `ruby/` - Ruby environment + - `databases/` - Database environments + - `mysql/` - MySQL environment + - `postgresql/` - PostgreSQL environment + - `mongodb/` - MongoDB environment + - `redis/` - Redis environment + - `sqlite/` - SQLite environment + - `shell/` - Shell environment for Linux scripts and DevOps + - `databricks/` - Databricks/PySpark environment for data processing + +## Usage + +### Running a Snippet + +Use the provided `run-snippet.sh` script to run a code snippet in the appropriate Docker environment: + +```bash +./docker/run-snippet.sh snippets/algorithms/graph-traversal/graph_traversal.py +``` + +The script automatically detects the file extension and uses the appropriate Docker container. + +### Running a Snippet with Database Connection + +Use the provided `run-db-snippet.sh` script to run a code snippet with a database connection: + +```bash +./docker/run-db-snippet.sh mysql snippets/databases/mysql_example.py +``` + +The script starts the specified database, connects it to your code environment, and runs the code with the appropriate connection parameters. + +For more information on using databases, see the [Database Guide](DATABASE_GUIDE.md). + +### Building All Environments + +To build all Docker environments without running them: + +```bash +docker-compose build +``` + +### Running a Specific Environment + +To run a specific environment: + +```bash +docker-compose run --rm python snippets/path/to/your/script.py +docker-compose run --rm javascript snippets/path/to/your/script.js +docker-compose run --rm java snippets/path/to/your/script.java +# etc. +``` + +### Database Operations + +To start a specific database: + +```bash +docker-compose -f docker/environments/databases/docker-compose.yml up -d mysql +# Or using the Makefile +make db-start DB=mysql +``` + +To stop a database: + +```bash +docker-compose -f docker/environments/databases/docker-compose.yml stop mysql +# Or using the Makefile +make db-stop DB=mysql +``` + +### Database Environment Variables + +The database configurations use environment variables for sensitive information. A `.env.example` file is provided in the `docker/environments/databases/` directory as a template. + +To use custom database credentials: + +1. Copy the example file to create a `.env` file: + ```bash + cp docker/environments/databases/.env.example docker/environments/databases/.env + ``` + +2. Edit the `.env` file to set your own credentials. + +3. The `.env` file is included in `.gitignore` to ensure sensitive data isn't committed to the repository. + +## Adding New Languages + +To add support for a new language: + +1. Create a new directory in `environments/` for your language +2. Add a `Dockerfile` for the language +3. If needed, add an `entrypoint.sh` script for handling compilation/execution +4. Update the `docker-compose.yml` file to include your new service +5. Update the `run-snippet.sh` script to recognize the new file extension diff --git a/docker/README_vi.md b/docker/README_vi.md new file mode 100644 index 0000000..97afd17 --- /dev/null +++ b/docker/README_vi.md @@ -0,0 +1,110 @@ +# Môi Trường Docker cho Tech Notes Hub + +Thư mục này chứa các cấu hình Docker để chạy các đoạn mã trong nhiều ngôn ngữ lập trình và môi trường khác nhau. + +## Cấu Trúc Thư Mục + +- `environments/` - Chứa Dockerfiles và scripts cài đặt cho mỗi ngôn ngữ + - `python/` - Môi trường Python + - `javascript/` - Môi trường JavaScript/Node.js + - `java/` - Môi trường Java + - `cpp/` - Môi trường C/C++ + - `go/` - Môi trường Go + - `rust/` - Môi trường Rust + - `php/` - Môi trường PHP + - `csharp/` - Môi trường C# + - `ruby/` - Môi trường Ruby + - `databases/` - Môi trường Cơ sở dữ liệu + - `mysql/` - Môi trường MySQL + - `postgresql/` - Môi trường PostgreSQL + - `mongodb/` - Môi trường MongoDB + - `redis/` - Môi trường Redis + - `sqlite/` - Môi trường SQLite + - `shell/` - Môi trường Shell cho scripts Linux và DevOps + - `databricks/` - Môi trường Databricks/PySpark cho xử lý dữ liệu + +## Cách Sử Dụng + +### Chạy Một Đoạn Mã + +Sử dụng script `run-snippet.sh` được cung cấp để chạy một đoạn mã trong môi trường Docker phù hợp: + +```bash +./docker/run-snippet.sh snippets/algorithms/graph-traversal/graph_traversal.py +``` + +Script tự động phát hiện phần mở rộng tệp và sử dụng container Docker thích hợp. + +### Chạy Đoạn Mã với Kết Nối Cơ Sở Dữ Liệu + +Sử dụng script `run-db-snippet.sh` được cung cấp để chạy một đoạn mã với kết nối cơ sở dữ liệu: + +```bash +./docker/run-db-snippet.sh mysql snippets/databases/mysql_example.py +``` + +Script sẽ khởi động cơ sở dữ liệu được chỉ định, kết nối nó với môi trường mã của bạn, và chạy mã với các tham số kết nối thích hợp. + +Để biết thêm thông tin về việc sử dụng cơ sở dữ liệu, xem [Hướng Dẫn Cơ Sở Dữ Liệu](DATABASE_GUIDE_vi.md). + +### Xây Dựng Tất Cả Các Môi Trường + +Để xây dựng tất cả các môi trường Docker mà không chạy chúng: + +```bash +docker-compose build +``` + +### Chạy Một Môi Trường Cụ Thể + +Để chạy một môi trường cụ thể: + +```bash +docker-compose run --rm python snippets/path/to/your/script.py +docker-compose run --rm javascript snippets/path/to/your/script.js +docker-compose run --rm java snippets/path/to/your/script.java +# v.v. +``` + +### Thao Tác Cơ Sở Dữ Liệu + +Để khởi động một cơ sở dữ liệu cụ thể: + +```bash +docker-compose -f docker/environments/databases/docker-compose.yml up -d mysql +# Hoặc sử dụng Makefile +make db-start DB=mysql +``` + +Để dừng một cơ sở dữ liệu: + +```bash +docker-compose -f docker/environments/databases/docker-compose.yml stop mysql +# Hoặc sử dụng Makefile +make db-stop DB=mysql +``` + +### Biến Môi Trường Cơ Sở Dữ Liệu + +Cấu hình cơ sở dữ liệu sử dụng biến môi trường cho thông tin nhạy cảm. Một file `.env.example` được cung cấp trong thư mục `docker/environments/databases/` làm mẫu. + +Để sử dụng thông tin đăng nhập cơ sở dữ liệu tùy chỉnh: + +1. Sao chép file mẫu để tạo file `.env`: + ```bash + cp docker/environments/databases/.env.example docker/environments/databases/.env + ``` + +2. Chỉnh sửa file `.env` để đặt thông tin đăng nhập của riêng bạn. + +3. File `.env` được bao gồm trong `.gitignore` để đảm bảo dữ liệu nhạy cảm không được commit vào repository. + +## Thêm Ngôn Ngữ Mới + +Để thêm hỗ trợ cho một ngôn ngữ mới: + +1. Tạo một thư mục mới trong `environments/` cho ngôn ngữ của bạn +2. Thêm một `Dockerfile` cho ngôn ngữ đó +3. Nếu cần, thêm một script `entrypoint.sh` để xử lý biên dịch/thực thi +4. Cập nhật tệp `docker-compose.yml` để bao gồm dịch vụ mới của bạn +5. Cập nhật script `run-snippet.sh` để nhận diện phần mở rộng tệp mới diff --git a/docker/environments/cpp/Dockerfile b/docker/environments/cpp/Dockerfile new file mode 100644 index 0000000..53d1451 --- /dev/null +++ b/docker/environments/cpp/Dockerfile @@ -0,0 +1,17 @@ +FROM gcc:12 + +WORKDIR /app + +# Install necessary development tools +RUN apt-get update && apt-get install -y \ + cmake \ + make \ + gdb \ + valgrind \ + && rm -rf /var/lib/apt/lists/* + +# Set up compilation and execution command +COPY docker/environments/cpp/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker/environments/cpp/entrypoint.sh b/docker/environments/cpp/entrypoint.sh new file mode 100644 index 0000000..6dd5edc --- /dev/null +++ b/docker/environments/cpp/entrypoint.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e + +FILE=$1 +FILENAME=$(basename "$FILE") +EXTENSION="${FILENAME##*.}" +OUTPUT_NAME="${FILENAME%.*}" + +echo "Compiling $FILENAME..." +if [ "$EXTENSION" == "c" ]; then + gcc -o "$OUTPUT_NAME" "$FILE" -lm +elif [ "$EXTENSION" == "cpp" ]; then + g++ -o "$OUTPUT_NAME" "$FILE" -std=c++17 +else + echo "Unsupported file extension: $EXTENSION" + exit 1 +fi + +echo "Running $OUTPUT_NAME..." +./"$OUTPUT_NAME" diff --git a/docker/environments/csharp/Dockerfile b/docker/environments/csharp/Dockerfile new file mode 100644 index 0000000..f845454 --- /dev/null +++ b/docker/environments/csharp/Dockerfile @@ -0,0 +1,17 @@ +FROM mcr.microsoft.com/dotnet/sdk:7.0 + +WORKDIR /app + +# Install necessary .NET tools +RUN dotnet tool install -g dotnet-format && \ + dotnet tool install -g dotnet-trace && \ + dotnet tool install -g dotnet-counters + +# Add .NET tools to PATH +ENV PATH="$PATH:/root/.dotnet/tools" + +# Set up compilation and execution command +COPY docker/environments/csharp/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker/environments/csharp/entrypoint.sh b/docker/environments/csharp/entrypoint.sh new file mode 100644 index 0000000..c280f81 --- /dev/null +++ b/docker/environments/csharp/entrypoint.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e + +FILE=$1 +FILENAME=$(basename "$FILE") +OUTPUT_NAME="${FILENAME%.*}" + +echo "Compiling $FILENAME..." +csc /out:"$OUTPUT_NAME.exe" "$FILE" + +echo "Running $OUTPUT_NAME.exe..." +mono "$OUTPUT_NAME.exe" diff --git a/docker/environments/databases/.env.example b/docker/environments/databases/.env.example new file mode 100644 index 0000000..88d2bbb --- /dev/null +++ b/docker/environments/databases/.env.example @@ -0,0 +1,39 @@ +# MySQL Configuration +MYSQL_ROOT_PASSWORD=rootpassword +MYSQL_DATABASE=tech_notes +MYSQL_USER=user +MYSQL_PASSWORD=password +MYSQL_PORT_EXPOSE=3306 +MYSQL_PORT=3306 + +# PostgreSQL Configuration +POSTGRES_USER=user +POSTGRES_PASSWORD=password +POSTGRES_DB=tech_notes +POSTGRES_PORT_EXPOSE=5432 +POSTGRES_PORT=5432 + +# MongoDB Configuration +MONGO_INITDB_ROOT_USERNAME=root +MONGO_INITDB_ROOT_PASSWORD=rootpassword +MONGO_INITDB_DATABASE=tech_notes +MONGO_USER=user +MONGO_PASSWORD=password +MONGO_PORT_EXPOSE=27017 +MONGO_PORT=27017 + +# Redis Configuration +REDIS_PASSWORD=your_secure_password +REDIS_PORT_EXPOSE=6379 +REDIS_PORT=6379 +REDIS_PASSWORD=your_secure_password + +# SQLite Configuration +# SQLite does not require credentials + +# MongoDB +MONGODB_PORT_EXPOSE=27017 +MONGODB_PORT=27017 +MONGODB_DATABASE=tech_notes +MONGODB_USER=root +MONGODB_PASSWORD=your_secure_password \ No newline at end of file diff --git a/docker/environments/databases/docker-compose.yml b/docker/environments/databases/docker-compose.yml new file mode 100644 index 0000000..4b5a42e --- /dev/null +++ b/docker/environments/databases/docker-compose.yml @@ -0,0 +1,76 @@ +version: '1.0' + +services: + # MySQL + mysql: + image: mysql:8.0 + container_name: tech-notes-mysql + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword} + MYSQL_DATABASE: ${MYSQL_DATABASE:-tech_notes} + MYSQL_USER: ${MYSQL_USER:-user} + MYSQL_PASSWORD: ${MYSQL_PASSWORD:-password} + ports: + - "${MYSQL_PORT_EXPOSE:-3306}:${MYSQL_PORT:-3306}" + volumes: + - mysql_data:/var/lib/mysql + - ./mysql/init:/docker-entrypoint-initdb.d + restart: unless-stopped + command: --default-authentication-plugin=mysql_native_password + + # PostgreSQL + postgres: + image: postgres:15 + container_name: tech-notes-postgres + environment: + POSTGRES_USER: ${POSTGRES_USER:-user} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-password} + POSTGRES_DB: ${POSTGRES_DB:-tech_notes} + ports: + - "${POSTGRES_PORT_EXPOSE:-5432}:${POSTGRES_PORT:-5432}" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./postgresql/init:/docker-entrypoint-initdb.d + restart: unless-stopped + + # MongoDB + mongodb: + image: mongo:6 + container_name: tech-notes-mongodb + environment: + MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME:-root} + MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD:-rootpassword} + MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE:-tech_notes} + ports: + - "${MONGO_PORT_EXPOSE:-27017}:${MONGO_PORT:-27017}" + volumes: + - mongodb_data:/data/db + - ./mongodb/init:/docker-entrypoint-initdb.d + restart: unless-stopped + + # Redis + redis: + image: redis:7 + container_name: tech-notes-redis + ports: + - "${REDIS_PORT_EXPOSE:-6379}:${REDIS_PORT:-6379}" + volumes: + - redis_data:/data + - ./redis/redis.conf:/usr/local/etc/redis/redis.conf + command: redis-server /usr/local/etc/redis/redis.conf + restart: unless-stopped + + # SQLite + sqlite: + build: ./sqlite + container_name: tech-notes-sqlite + volumes: + - sqlite_data:/data + restart: unless-stopped + +volumes: + mysql_data: + postgres_data: + mongodb_data: + redis_data: + sqlite_data: diff --git a/docker/environments/databases/mongodb/docker-compose.yml b/docker/environments/databases/mongodb/docker-compose.yml new file mode 100644 index 0000000..7ffb944 --- /dev/null +++ b/docker/environments/databases/mongodb/docker-compose.yml @@ -0,0 +1,19 @@ +version: '1.0' + +services: + mongodb: + image: mongo:6 + container_name: tech-notes-mongodb + environment: + MONGO_INITDB_ROOT_USERNAME: ${MONGODB_USER:-root} + MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_PASSWORD:-rootpassword} + MONGO_INITDB_DATABASE: ${MONGODB_DATABASE:-tech_notes} + ports: + - "${MONGODB_PORT_EXPOSE:-27017}:${MONGODB_PORT:-27017}" + volumes: + - mongodb_data:/data/db + - ./init:/docker-entrypoint-initdb.d + restart: unless-stopped + +volumes: + mongodb_data: diff --git a/docker/environments/databases/mongodb/init/01-sample-data.js b/docker/environments/databases/mongodb/init/01-sample-data.js new file mode 100644 index 0000000..fbbf409 --- /dev/null +++ b/docker/environments/databases/mongodb/init/01-sample-data.js @@ -0,0 +1,70 @@ +// Create a user for the database +db.createUser({ + user: 'user', + pwd: 'password', + roles: [ + { + role: 'readWrite', + db: 'tech_notes' + } + ] +}); + +// Switch to the tech_notes database +db = db.getSiblingDB('tech_notes'); + +// Create collections +db.createCollection('users'); +db.createCollection('posts'); + +// Insert sample data into users collection +db.users.insertMany([ + { + username: 'user1', + email: 'user1@example.com', + created_at: new Date() + }, + { + username: 'user2', + email: 'user2@example.com', + created_at: new Date() + }, + { + username: 'user3', + email: 'user3@example.com', + created_at: new Date() + } +]); + +// Get the user IDs +const user1 = db.users.findOne({ username: 'user1' }); +const user2 = db.users.findOne({ username: 'user2' }); +const user3 = db.users.findOne({ username: 'user3' }); + +// Insert sample data into posts collection +db.posts.insertMany([ + { + title: 'First Post', + content: 'This is the content of the first post', + user_id: user1._id, + created_at: new Date() + }, + { + title: 'Second Post', + content: 'This is the content of the second post', + user_id: user1._id, + created_at: new Date() + }, + { + title: 'Hello World', + content: 'Hello world post content', + user_id: user2._id, + created_at: new Date() + }, + { + title: 'Database Demo', + content: 'This is a demonstration of MongoDB database', + user_id: user3._id, + created_at: new Date() + } +]); diff --git a/docker/environments/databases/mysql/docker-compose.yml b/docker/environments/databases/mysql/docker-compose.yml new file mode 100644 index 0000000..515b79e --- /dev/null +++ b/docker/environments/databases/mysql/docker-compose.yml @@ -0,0 +1,21 @@ +version: '1.0' + +services: + mysql: + image: mysql:8.0 + container_name: tech-notes-mysql + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword} + MYSQL_DATABASE: ${MYSQL_DATABASE:-tech_notes} + MYSQL_USER: ${MYSQL_USER:-user} + MYSQL_PASSWORD: ${MYSQL_PASSWORD:-password} + ports: + - "${MYSQL_PORT_EXPOSE:-3306}:${MYSQL_PORT:-3306}" + volumes: + - mysql_data:/var/lib/mysql + - ./init:/docker-entrypoint-initdb.d + restart: unless-stopped + command: --default-authentication-plugin=mysql_native_password + +volumes: + mysql_data: diff --git a/docker/environments/databases/mysql/init/01-sample-data.sql b/docker/environments/databases/mysql/init/01-sample-data.sql new file mode 100644 index 0000000..24c06f5 --- /dev/null +++ b/docker/environments/databases/mysql/init/01-sample-data.sql @@ -0,0 +1,28 @@ +-- Create sample tables +CREATE TABLE IF NOT EXISTS users ( + id INT AUTO_INCREMENT PRIMARY KEY, + username VARCHAR(50) NOT NULL UNIQUE, + email VARCHAR(100) NOT NULL UNIQUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS posts ( + id INT AUTO_INCREMENT PRIMARY KEY, + title VARCHAR(255) NOT NULL, + content TEXT, + user_id INT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) +); + +-- Insert sample data +INSERT INTO users (username, email) VALUES + ('user1', 'user1@example.com'), + ('user2', 'user2@example.com'), + ('user3', 'user3@example.com'); + +INSERT INTO posts (title, content, user_id) VALUES + ('First Post', 'This is the content of the first post', 1), + ('Second Post', 'This is the content of the second post', 1), + ('Hello World', 'Hello world post content', 2), + ('Database Demo', 'This is a demonstration of MySQL database', 3); diff --git a/docker/environments/databases/postgresql/docker-compose.yml b/docker/environments/databases/postgresql/docker-compose.yml new file mode 100644 index 0000000..ee7e7f2 --- /dev/null +++ b/docker/environments/databases/postgresql/docker-compose.yml @@ -0,0 +1,19 @@ +version: '1.0' + +services: + postgres: + image: postgres:15 + container_name: tech-notes-postgres + environment: + POSTGRES_USER: ${POSTGRES_USER:-user} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-password} + POSTGRES_DB: ${POSTGRES_DB:-tech_notes} + ports: + - "${POSTGRES_PORT_EXPOSE:-5432}:${POSTGRES_PORT:-5432}" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init:/docker-entrypoint-initdb.d + restart: unless-stopped + +volumes: + postgres_data: diff --git a/docker/environments/databases/postgresql/init/01-sample-data.sql b/docker/environments/databases/postgresql/init/01-sample-data.sql new file mode 100644 index 0000000..3531b8b --- /dev/null +++ b/docker/environments/databases/postgresql/init/01-sample-data.sql @@ -0,0 +1,28 @@ +-- Create sample tables +CREATE TABLE IF NOT EXISTS users ( + id SERIAL PRIMARY KEY, + username VARCHAR(50) NOT NULL UNIQUE, + email VARCHAR(100) NOT NULL UNIQUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS posts ( + id SERIAL PRIMARY KEY, + title VARCHAR(255) NOT NULL, + content TEXT, + user_id INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) +); + +-- Insert sample data +INSERT INTO users (username, email) VALUES + ('user1', 'user1@example.com'), + ('user2', 'user2@example.com'), + ('user3', 'user3@example.com'); + +INSERT INTO posts (title, content, user_id) VALUES + ('First Post', 'This is the content of the first post', 1), + ('Second Post', 'This is the content of the second post', 1), + ('Hello World', 'Hello world post content', 2), + ('Database Demo', 'This is a demonstration of PostgreSQL database', 3); diff --git a/docker/environments/databases/redis/docker-compose.yml b/docker/environments/databases/redis/docker-compose.yml new file mode 100644 index 0000000..13505af --- /dev/null +++ b/docker/environments/databases/redis/docker-compose.yml @@ -0,0 +1,16 @@ +version: '1.0' + +services: + redis: + image: redis:7 + container_name: tech-notes-redis + ports: + - "${REDIS_PORT_EXPOSE:-6379}:${REDIS_PORT:-6379}" + volumes: + - redis_data:/data + - ./redis.conf:/usr/local/etc/redis/redis.conf + command: redis-server /usr/local/etc/redis/redis.conf + restart: unless-stopped + +volumes: + redis_data: diff --git a/docker/environments/databases/redis/redis.conf b/docker/environments/databases/redis/redis.conf new file mode 100644 index 0000000..57c1035 --- /dev/null +++ b/docker/environments/databases/redis/redis.conf @@ -0,0 +1,51 @@ +# Redis configuration file + +# Basic configuration +bind 0.0.0.0 +protected-mode yes +port ${REDIS_PORT:-6379} +tcp-backlog 511 +timeout 0 +tcp-keepalive 300 + +# General configuration +daemonize no +supervised no +pidfile /var/run/redis_${REDIS_PORT:-6379}.pid +loglevel notice +logfile "" +databases 16 + +# Snapshotting +save 900 1 +save 300 10 +save 60 10000 +stop-writes-on-bgsave-error yes +rdbcompression yes +rdbchecksum yes +dbfilename dump.rdb +dir /data + +# Security (no password by default for easy access) +# Comment this to disable password +requirepass ${REDIS_PASSWORD:-your_secure_password} + +# Memory management +maxmemory 256mb +maxmemory-policy allkeys-lru + +# Append only mode +appendonly yes +appendfilename "appendonly.aof" +appendfsync everysec +no-appendfsync-on-rewrite no +auto-aof-rewrite-percentage 100 +auto-aof-rewrite-min-size 64mb +aof-load-truncated yes + +# Lua scripting +lua-time-limit 5000 + +# Slow log +slowlog-log-slower-than 10000 +slowlog-max-len 128 diff --git a/docker/environments/databases/sqlite/Dockerfile b/docker/environments/databases/sqlite/Dockerfile new file mode 100644 index 0000000..0ede5ed --- /dev/null +++ b/docker/environments/databases/sqlite/Dockerfile @@ -0,0 +1,20 @@ +FROM alpine:3.17 + +# Install SQLite and required tools +RUN apk add --no-cache sqlite sqlite-dev sqlite-libs bash + +# Create data directory +RUN mkdir -p /data + +# Set working directory +WORKDIR /data + +# Copy init script +COPY init.sh /init.sh +COPY init.sql /init.sql + +# Make the script executable +RUN chmod +x /init.sh + +# Run init script on startup +ENTRYPOINT ["/init.sh"] diff --git a/docker/environments/databases/sqlite/docker-compose.yml b/docker/environments/databases/sqlite/docker-compose.yml new file mode 100644 index 0000000..fa0c955 --- /dev/null +++ b/docker/environments/databases/sqlite/docker-compose.yml @@ -0,0 +1,12 @@ +version: '1.0' + +services: + sqlite: + build: . + container_name: tech-notes-sqlite + volumes: + - sqlite_data:/data + restart: unless-stopped + +volumes: + sqlite_data: diff --git a/docker/environments/databases/sqlite/init.sh b/docker/environments/databases/sqlite/init.sh new file mode 100644 index 0000000..151ab06 --- /dev/null +++ b/docker/environments/databases/sqlite/init.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Create the database if it doesn't exist +if [ ! -f /data/tech_notes.db ]; then + echo "Creating new SQLite database..." + sqlite3 /data/tech_notes.db < /init.sql + echo "Database created and initialized." +else + echo "Database already exists." +fi + +# Keep container running +echo "SQLite container is ready. Database is at /data/tech_notes.db" +echo "Use 'docker exec -it tech-notes-sqlite sqlite3 /data/tech_notes.db' to access the database." +tail -f /dev/null diff --git a/docker/environments/databases/sqlite/init.sql b/docker/environments/databases/sqlite/init.sql new file mode 100644 index 0000000..78dd428 --- /dev/null +++ b/docker/environments/databases/sqlite/init.sql @@ -0,0 +1,28 @@ +-- Create sample tables +CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + email TEXT NOT NULL UNIQUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + content TEXT, + user_id INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) +); + +-- Insert sample data +INSERT INTO users (username, email) VALUES + ('user1', 'user1@example.com'), + ('user2', 'user2@example.com'), + ('user3', 'user3@example.com'); + +INSERT INTO posts (title, content, user_id) VALUES + ('First Post', 'This is the content of the first post', 1), + ('Second Post', 'This is the content of the second post', 1), + ('Hello World', 'Hello world post content', 2), + ('Database Demo', 'This is a demonstration of SQLite database', 3); diff --git a/docker/environments/databricks/Dockerfile b/docker/environments/databricks/Dockerfile new file mode 100644 index 0000000..b4f168c --- /dev/null +++ b/docker/environments/databricks/Dockerfile @@ -0,0 +1,36 @@ +FROM python:3.9-slim + +# Install Java +RUN apt-get update && \ + apt-get install -y openjdk-11-jdk && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +# Set Java home +ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 + +# Install PySpark and Databricks libraries +RUN pip install --no-cache-dir \ + pyspark==3.3.0 \ + delta-spark==2.1.0 \ + databricks-connect==10.4.* \ + matplotlib \ + pandas \ + numpy \ + scikit-learn + +# Install additional libraries for databricks +RUN pip install --no-cache-dir \ + mlflow \ + koalas \ + plotly \ + databricks-cli + +# Set up working directory +WORKDIR /app + +# Create PySpark configuration directory +RUN mkdir -p /root/.databricks-connect + +# Set entrypoint to Python +ENTRYPOINT ["python"] diff --git a/docker/environments/go/Dockerfile b/docker/environments/go/Dockerfile new file mode 100644 index 0000000..826ea4d --- /dev/null +++ b/docker/environments/go/Dockerfile @@ -0,0 +1,11 @@ +FROM golang:1.21-alpine + +WORKDIR /app + +# Install necessary Go packages +RUN go install github.com/stretchr/testify@latest && \ + go install github.com/golang/mock/mockgen@latest && \ + go install golang.org/x/tools/cmd/goimports@latest + +# Set up command to run Go scripts +ENTRYPOINT ["go", "run"] diff --git a/docker/environments/java/Dockerfile b/docker/environments/java/Dockerfile new file mode 100644 index 0000000..c26955f --- /dev/null +++ b/docker/environments/java/Dockerfile @@ -0,0 +1,15 @@ +FROM openjdk:17-slim + +WORKDIR /app + +# Install build tools +RUN apt-get update && apt-get install -y \ + maven \ + gradle \ + && rm -rf /var/lib/apt/lists/* + +# Set up compilation and execution command +COPY docker/environments/java/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker/environments/java/entrypoint.sh b/docker/environments/java/entrypoint.sh new file mode 100644 index 0000000..8266ec3 --- /dev/null +++ b/docker/environments/java/entrypoint.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e + +FILE=$1 +FILENAME=$(basename "$FILE") +CLASSNAME="${FILENAME%.*}" + +echo "Compiling $FILENAME..." +javac "$FILE" + +echo "Running $CLASSNAME..." +java -cp "$(dirname "$FILE")" "$CLASSNAME" diff --git a/docker/environments/javascript/Dockerfile b/docker/environments/javascript/Dockerfile new file mode 100644 index 0000000..65a40d5 --- /dev/null +++ b/docker/environments/javascript/Dockerfile @@ -0,0 +1,13 @@ +FROM node:18-slim + +WORKDIR /app + +# Install necessary Node.js packages +RUN npm install -g \ + jest \ + mocha \ + chai \ + eslint + +# Set up command to run JavaScript scripts +ENTRYPOINT ["node"] diff --git a/docker/environments/php/Dockerfile b/docker/environments/php/Dockerfile new file mode 100644 index 0000000..d1c4abe --- /dev/null +++ b/docker/environments/php/Dockerfile @@ -0,0 +1,23 @@ +FROM php:8.2-cli + +WORKDIR /app + +# Install necessary PHP extensions and tools +RUN apt-get update && apt-get install -y \ + libzip-dev \ + unzip \ + git \ + && docker-php-ext-install zip \ + && php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \ + && php composer-setup.php --install-dir=/usr/local/bin --filename=composer \ + && php -r "unlink('composer-setup.php');" \ + && rm -rf /var/lib/apt/lists/* + +# Install PHPUnit and other common packages +RUN composer global require phpunit/phpunit + +# Add composer's vendor bin to PATH +ENV PATH="/root/.composer/vendor/bin:${PATH}" + +# Set up command to run PHP scripts +ENTRYPOINT ["php"] diff --git a/docker/environments/python/Dockerfile b/docker/environments/python/Dockerfile new file mode 100644 index 0000000..81f51f3 --- /dev/null +++ b/docker/environments/python/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.11-slim + +WORKDIR /app + +# Install necessary Python packages +RUN pip install --no-cache-dir \ + pytest \ + numpy \ + pandas \ + matplotlib \ + scipy \ + scikit-learn + +# Set up command to run Python scripts +ENTRYPOINT ["python"] diff --git a/docker/environments/ruby/Dockerfile b/docker/environments/ruby/Dockerfile new file mode 100644 index 0000000..79f6f31 --- /dev/null +++ b/docker/environments/ruby/Dockerfile @@ -0,0 +1,14 @@ +FROM ruby:3.2-slim + +WORKDIR /app + +# Install necessary Ruby gems +RUN gem install \ + rspec \ + rubocop \ + pry \ + sinatra \ + rails + +# Set up command to run Ruby scripts +ENTRYPOINT ["ruby"] diff --git a/docker/environments/rust/Dockerfile b/docker/environments/rust/Dockerfile new file mode 100644 index 0000000..dbe73e0 --- /dev/null +++ b/docker/environments/rust/Dockerfile @@ -0,0 +1,13 @@ +FROM rust:1.75-slim + +WORKDIR /app + +# Install necessary Rust tools +RUN rustup component add rustfmt clippy && \ + cargo install cargo-watch cargo-expand + +# Set up command to run Rust scripts +COPY docker/environments/rust/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker/environments/rust/entrypoint.sh b/docker/environments/rust/entrypoint.sh new file mode 100644 index 0000000..f2f726b --- /dev/null +++ b/docker/environments/rust/entrypoint.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +FILE=$1 +FILENAME=$(basename "$FILE") + +echo "Running $FILENAME with rustc..." +rustc -o temp_executable "$FILE" && ./temp_executable +rm -f temp_executable diff --git a/docker/environments/shell/Dockerfile b/docker/environments/shell/Dockerfile new file mode 100644 index 0000000..37593d8 --- /dev/null +++ b/docker/environments/shell/Dockerfile @@ -0,0 +1,28 @@ +FROM ubuntu:22.04 + +# Install essential tools and utilities +RUN apt-get update && apt-get install -y \ + bash \ + bc \ + curl \ + git \ + iputils-ping \ + iproute2 \ + net-tools \ + nodejs \ + npm \ + openssh-client \ + procps \ + systemd \ + vim \ + wget \ + && rm -rf /var/lib/apt/lists/* + +# Set up working directory +WORKDIR /app + +# Set bash as the default shell +SHELL ["/bin/bash", "-c"] + +# Set entrypoint to bash shell +ENTRYPOINT ["/bin/bash"] diff --git a/docker/redis/redis.conf b/docker/redis/redis.conf new file mode 100644 index 0000000..e474859 --- /dev/null +++ b/docker/redis/redis.conf @@ -0,0 +1,4 @@ +# Security (no password by default for easy access) +# uncomment and change to set password +# requirepass yourpassword +requirepass ${REDIS_PASSWORD} diff --git a/docker/run-db-snippet.sh b/docker/run-db-snippet.sh new file mode 100755 index 0000000..35f67f4 --- /dev/null +++ b/docker/run-db-snippet.sh @@ -0,0 +1,141 @@ +#!/bin/bash +set -e + +if [ $# -lt 2 ]; then + echo "Usage: $0 " + echo "Database types: mysql, postgres, mongodb, redis, sqlite" + exit 1 +fi + +DB_TYPE="$1" +SNIPPET_PATH="$2" +EXTENSION="${SNIPPET_PATH##*.}" + +# Load environment variables from .env file if it exists +ENV_FILE="docker/environments/databases/.env" +if [ -f "$ENV_FILE" ]; then + echo "Loading environment variables from $ENV_FILE" + export $(grep -v '^#' "$ENV_FILE" | xargs) +else + echo "No .env file found at $ENV_FILE, using default values" +fi + +# Start the selected database +function start_database() { + echo "Starting $DB_TYPE database..." + docker-compose -f docker/environments/databases/docker-compose.yml up -d "$DB_TYPE" + + # Give some time for the database to start + sleep 5 + + echo "$DB_TYPE database is ready." +} + +# Map file extensions to Docker services +case "$EXTENSION" in + py) + SERVICE="python" + ;; + js) + SERVICE="javascript" + ;; + java) + SERVICE="java" + ;; + c|cpp) + SERVICE="cpp" + ;; + go) + SERVICE="go" + ;; + rs) + SERVICE="rust" + ;; + php) + SERVICE="php" + ;; + cs) + SERVICE="csharp" + ;; + rb) + SERVICE="ruby" + ;; + *) + echo "Unsupported file extension: $EXTENSION" + exit 1 + ;; +esac + +# Get the database connection details +case "$DB_TYPE" in + mysql) + DB_HOST="tech-notes-mysql" + DB_PORT="3306" + DB_USER="${MYSQL_USER:-user}" + DB_PASS="${MYSQL_PASSWORD:-password}" + DB_NAME="${MYSQL_DATABASE:-tech_notes}" + DB_CONN_STR="mysql://$DB_USER:$DB_PASS@$DB_HOST:$DB_PORT/$DB_NAME" + ;; + postgres) + DB_HOST="tech-notes-postgres" + DB_PORT="5432" + DB_USER="${POSTGRES_USER:-user}" + DB_PASS="${POSTGRES_PASSWORD:-password}" + DB_NAME="${POSTGRES_DB:-tech_notes}" + DB_CONN_STR="postgresql://$DB_USER:$DB_PASS@$DB_HOST:$DB_PORT/$DB_NAME" + ;; + mongodb) + DB_HOST="tech-notes-mongodb" + DB_PORT="27017" + DB_USER="${MONGO_USER:-user}" + DB_PASS="${MONGO_PASSWORD:-password}" + DB_NAME="${MONGO_INITDB_DATABASE:-tech_notes}" + DB_CONN_STR="mongodb://$DB_USER:$DB_PASS@$DB_HOST:$DB_PORT/$DB_NAME" + ;; + redis) + DB_HOST="tech-notes-redis" + DB_PORT="6379" + DB_PASS="${REDIS_PASSWORD:-}" + if [ -n "$DB_PASS" ]; then + DB_CONN_STR="redis://:$DB_PASS@$DB_HOST:$DB_PORT" + else + DB_CONN_STR="redis://$DB_HOST:$DB_PORT" + fi + ;; + sqlite) + DB_CONN_STR="sqlite:///data/tech_notes.db" + ;; + *) + echo "Unsupported database type: $DB_TYPE" + exit 1 + ;; +esac + +# Start the database +start_database + +# Get absolute path from relative path +ABSOLUTE_PATH=$(realpath "$SNIPPET_PATH") +# Get the path relative to the project root +RELATIVE_PATH=$(realpath --relative-to="$(pwd)" "$ABSOLUTE_PATH") + +# Create a custom docker network if it doesn't exist +if ! docker network inspect tech-notes-network >/dev/null 2>&1; then + echo "Creating docker network: tech-notes-network" + docker network create tech-notes-network + + # Add the database container to the network + echo "Adding $DB_TYPE database to the network" + docker network connect tech-notes-network "tech-notes-$DB_TYPE" +fi + +echo "Running $RELATIVE_PATH in $SERVICE environment with $DB_TYPE database..." +docker-compose run --rm \ + --network tech-notes-network \ + -e DB_HOST="$DB_HOST" \ + -e DB_PORT="$DB_PORT" \ + -e DB_USER="$DB_USER" \ + -e DB_PASS="$DB_PASS" \ + -e DB_NAME="$DB_NAME" \ + -e DB_CONN_STR="$DB_CONN_STR" \ + "$SERVICE" "/app/$RELATIVE_PATH" diff --git a/docker/run-snippet.sh b/docker/run-snippet.sh new file mode 100755 index 0000000..913c8d5 --- /dev/null +++ b/docker/run-snippet.sh @@ -0,0 +1,69 @@ +#!/bin/bash +set -e + +if [ $# -lt 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SNIPPET_PATH="$1" +EXTENSION="${SNIPPET_PATH##*.}" + +# Map file extensions to Docker services +case "$EXTENSION" in + py) + SERVICE="python" + ;; + js) + SERVICE="javascript" + ;; + java) + SERVICE="java" + ;; + c|cpp) + SERVICE="cpp" + ;; + go) + SERVICE="go" + ;; + rs) + SERVICE="rust" + ;; + php) + SERVICE="php" + ;; + cs) + SERVICE="csharp" + ;; + rb) + SERVICE="ruby" + ;; + sh) + SERVICE="shell" + ;; + ipynb) + SERVICE="databricks" + ;; + *) + echo "Unsupported file extension: $EXTENSION" + exit 1 + ;; +esac + +# Get absolute path from relative path +ABSOLUTE_PATH=$(realpath "$SNIPPET_PATH") +# Get the path relative to the project root +RELATIVE_PATH=$(realpath --relative-to="$(pwd)" "$ABSOLUTE_PATH") + +# Special handling for shell scripts +if [ "$EXTENSION" == "sh" ]; then + echo "Running $RELATIVE_PATH in $SERVICE environment..." + # Make the script executable in the container and run it + docker-compose run --rm "$SERVICE" -c "chmod +x /app/$RELATIVE_PATH && /app/$RELATIVE_PATH" +elif [ "$EXTENSION" == "ipynb" ]; then + echo "Running Jupyter notebook $RELATIVE_PATH in $SERVICE environment..." + docker-compose run --rm "$SERVICE" -m jupyter nbconvert --execute --to notebook --inplace "/app/$RELATIVE_PATH" +else + echo "Running $RELATIVE_PATH in $SERVICE environment..." + docker-compose run --rm "$SERVICE" "/app/$RELATIVE_PATH" +fi diff --git a/snippets/databases/.env.example b/snippets/databases/.env.example index 46b59e9..ef9053e 100644 --- a/snippets/databases/.env.example +++ b/snippets/databases/.env.example @@ -29,4 +29,4 @@ DAPPER_CONNECTION_STRING=Data Source=:memory: # SQLite: sqlite:///path/to/database.db # PostgreSQL: postgresql://user:password@localhost/dbname # MySQL: mysql://user:password@localhost/dbname -SQLALCHEMY_DATABASE_URL=sqlite:///:memory: \ No newline at end of file +SQLALCHEMY_DATABASE_URL=sqlite:///:memory: