diff --git a/ci/github-actions.yml b/.github/workflows/ci.yml similarity index 88% rename from ci/github-actions.yml rename to .github/workflows/ci.yml index 50d543d..e0a366f 100644 --- a/ci/github-actions.yml +++ b/.github/workflows/ci.yml @@ -76,11 +76,11 @@ jobs: docker stop test-${{ matrix.app.name }} docker rm test-${{ matrix.app.name }} - # Security scanning + # Security scanning - Runs in parallel security-scan: name: Security Scan runs-on: ubuntu-latest - needs: build-apps + needs: validate # Only needs code checkout/validation steps: - name: Checkout code uses: actions/checkout@v4 @@ -101,11 +101,28 @@ jobs: format: "sarif" output: "trivy-python-results.sarif" + # Validate Kubernetes Manifests + lint-k8s: + name: Lint Kubernetes + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install kubeconform + run: | + wget https://github.com/yannh/kubeconform/releases/download/v0.6.3/kubeconform-linux-amd64.tar.gz + tar xf kubeconform-linux-amd64.tar.gz + sudo mv kubeconform /usr/local/bin/ + + - name: Validate Manifests + run: kubeconform -summary -output text k8s/ + # Integration test integration-test: name: Integration Tests runs-on: ubuntu-latest - needs: build-apps + needs: [build-apps, security-scan, lint-k8s] steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/.github/workflows/gitops.yml b/.github/workflows/gitops.yml new file mode 100644 index 0000000..9962cf6 --- /dev/null +++ b/.github/workflows/gitops.yml @@ -0,0 +1,26 @@ +name: GitOps Sync Simulation + +on: + push: + paths: + - "k8s/**" + branches: + - main + +jobs: + sync-check: + name: Simulate GitOps Sync + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Minikube (Simulation) + uses: medyagh/setup-minikube@master + + - name: Calculate Diff + run: | + echo "Simulating ArgoCD/Flux sync..." + echo "Comparing git state vs cluster state..." + kubectl diff -f k8s/ || true + echo "Changes detected above would be applied automatically in a real GitOps setup." diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..1c7d686 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,431 @@ +# Migration Guide: Docker Compose β†’ Kubernetes + +Panduan migrasi CloudLab dari Docker Compose ke Kubernetes. + +## πŸ“Š Comparison Overview + +| Aspect | Docker Compose | Kubernetes | +|--------|---------------|------------| +| **Orchestration** | Single host | Multi-node cluster | +| **Scaling** | Manual (`docker-compose scale`) | Auto-scaling (HPA) | +| **High Availability** | Limited | Built-in (replicas, self-healing) | +| **Load Balancing** | Basic | Advanced (Services, Ingress) | +| **Storage** | Docker volumes | PersistentVolumes | +| **Networking** | Bridge network | Service mesh, Network Policies | +| **Configuration** | Environment variables | ConfigMaps, Secrets | +| **Deployment** | `docker-compose up` | `kubectl apply` | +| **Monitoring** | Manual setup | Native integration | + +## πŸ”„ Mapping Components + +### Services β†’ Deployments + Services + +**Docker Compose:** +```yaml +services: + nodejs-app: + build: ./apps/demo-apps/nodejs-app + ports: + - "3001:3001" + environment: + - NODE_ENV=production +``` + +**Kubernetes:** +```yaml +# Deployment +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nodejs-app +spec: + replicas: 3 # HA dengan multiple replicas + template: + spec: + containers: + - name: nodejs-app + image: cloudlab-nodejs-app:latest + env: + - name: NODE_ENV + value: production +--- +# Service +apiVersion: v1 +kind: Service +metadata: + name: nodejs-app +spec: + selector: + app: nodejs-app + ports: + - port: 3001 + targetPort: 3001 +``` + +### Networks β†’ Services & Network Policies + +**Docker Compose:** +```yaml +networks: + cloudlab-network: + driver: bridge +``` + +**Kubernetes:** +- Services provide DNS-based service discovery +- Network Policies untuk traffic control (optional) +- Pods dapat communicate via service names + +### Volumes β†’ PersistentVolumeClaims + +**Docker Compose:** +```yaml +volumes: + prometheus-data: + driver: local +``` + +**Kubernetes:** +```yaml +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: prometheus-storage +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 10Gi +``` + +### Depends_on β†’ Init Containers / Readiness Probes + +**Docker Compose:** +```yaml +depends_on: + - prometheus +``` + +**Kubernetes:** +- Readiness probes ensure service is ready +- Init containers untuk startup dependencies +- Service discovery handles availability + +## πŸ“ Migration Steps + +### Phase 1: Preparation + +1. **Audit Current Setup** + ```bash + # List running services + docker-compose ps + + # Check resource usage + docker stats + + # Export configurations + docker-compose config > docker-compose-backup.yml + ``` + +2. **Build and Tag Images** + ```bash + # Build images dengan versioning + cd apps/demo-apps/nodejs-app + docker build -t cloudlab-nodejs-app:1.0.0 . + docker tag cloudlab-nodejs-app:1.0.0 cloudlab-nodejs-app:latest + + cd ../python-app + docker build -t cloudlab-python-app:1.0.0 . + docker tag cloudlab-python-app:1.0.0 cloudlab-python-app:latest + ``` + +3. **Backup Data** + ```bash + # Backup Grafana data + docker cp cloudlab-grafana:/var/lib/grafana ./backup/grafana + + # Backup Prometheus data + docker cp cloudlab-prometheus:/prometheus ./backup/prometheus + ``` + +### Phase 2: Setup Kubernetes + +1. **Choose Cluster Type** + - Local: Minikube or Kind + - Cloud: GKE, EKS, or AKS + - On-premise: kubeadm or k3s + +2. **Install Required Tools** + ```bash + # kubectl + curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" + sudo install kubectl /usr/local/bin/ + + # Minikube (untuk local) + curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 + sudo install minikube-linux-amd64 /usr/local/bin/minikube + ``` + +3. **Start Cluster** + ```bash + # Minikube + minikube start --cpus=4 --memory=8192 + minikube addons enable ingress + minikube addons enable metrics-server + ``` + +### Phase 3: Deploy to Kubernetes + +1. **Prepare Images** + ```bash + # For Minikube + minikube image load cloudlab-nodejs-app:latest + minikube image load cloudlab-python-app:latest + + # For other clusters, push to registry + # docker push your-registry/cloudlab-nodejs-app:latest + ``` + +2. **Generate SSL Certificates** + ```bash + # Generate self-signed cert + openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout /tmp/tls.key -out /tmp/tls.crt \ + -subj "/C=ID/ST=Jakarta/L=Jakarta/O=CloudLab/OU=Dev/CN=cloudlab.local" + + # Update secret + TLS_CRT=$(cat /tmp/tls.crt | base64 -w 0) + TLS_KEY=$(cat /tmp/tls.key | base64 -w 0) + sed -i "s|tls.crt:.*|tls.crt: $TLS_CRT|" k8s/base/secrets/ssl-certs.yaml + sed -i "s|tls.key:.*|tls.key: $TLS_KEY|" k8s/base/secrets/ssl-certs.yaml + ``` + +3. **Deploy Resources** + ```bash + # Deploy dengan kustomize + kubectl apply -k k8s/ + + # Wait for rollout + kubectl rollout status deployment/nodejs-app -n cloudlab-apps + kubectl rollout status deployment/python-app -n cloudlab-apps + kubectl rollout status deployment/grafana -n cloudlab-monitoring + kubectl rollout status statefulset/prometheus -n cloudlab-monitoring + ``` + +4. **Verify Deployment** + ```bash + # Check pods + kubectl get pods -n cloudlab-apps + kubectl get pods -n cloudlab-monitoring + + # Check services + kubectl get svc -n cloudlab-apps + kubectl get svc -n cloudlab-monitoring + + # Check ingress + kubectl get ingress -A + ``` + +### Phase 4: Data Migration + +1. **Restore Grafana Data** + ```bash + # Copy backup ke pod + kubectl cp ./backup/grafana grafana-:/var/lib/grafana -n cloudlab-monitoring + + # Restart Grafana + kubectl rollout restart deployment/grafana -n cloudlab-monitoring + ``` + +2. **Restore Prometheus Data** + ```bash + # Copy backup ke pod + kubectl cp ./backup/prometheus prometheus-0:/prometheus -n cloudlab-monitoring + + # Restart Prometheus + kubectl rollout restart statefulset/prometheus -n cloudlab-monitoring + ``` + +### Phase 5: Testing + +1. **Functional Testing** + ```bash + # Port forward untuk testing + kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps & + kubectl port-forward svc/python-app 5000:5000 -n cloudlab-apps & + kubectl port-forward svc/grafana 3000:3000 -n cloudlab-monitoring & + + # Test endpoints + curl http://localhost:3001/health + curl http://localhost:5000/health + curl http://localhost:3000/api/health + ``` + +2. **Load Testing** + ```bash + # Generate load + kubectl run -it --rm load-generator --image=busybox -- /bin/sh + while true; do wget -q -O- http://nodejs-app.cloudlab-apps.svc.cluster.local:3001; done + + # Watch autoscaling + kubectl get hpa -n cloudlab-apps --watch + ``` + +3. **Monitoring Testing** + ```bash + # Check Prometheus targets + kubectl port-forward svc/prometheus 9090:9090 -n cloudlab-monitoring + # Open http://localhost:9090/targets + + # Check Grafana dashboards + # Open http://localhost:3000 + ``` + +### Phase 6: Cutover + +1. **Update DNS/Hosts** + ```bash + # Get Ingress IP + kubectl get ingress -n cloudlab-apps + + # Update /etc/hosts + echo "$(minikube ip) cloudlab.local grafana.cloudlab.local" | sudo tee -a /etc/hosts + ``` + +2. **Stop Docker Compose** + ```bash + # Stop services + docker-compose down + + # Keep volumes untuk backup + # docker-compose down -v # Only if you want to remove volumes + ``` + +3. **Verify Production Traffic** + ```bash + # Test via Ingress + curl https://cloudlab.local + curl https://grafana.cloudlab.local + ``` + +## πŸ”™ Rollback Procedure + +Jika ada masalah, rollback ke Docker Compose: + +```bash +# 1. Stop Kubernetes deployment +kubectl delete -k k8s/ + +# 2. Start Docker Compose +docker-compose up -d + +# 3. Verify services +docker-compose ps +``` + +## ⚠️ Common Issues + +### Issue 1: ImagePullBackOff + +**Problem:** Kubernetes tidak bisa pull image + +**Solution:** +```bash +# For Minikube, load image langsung +minikube image load cloudlab-nodejs-app:latest + +# For other clusters, push ke registry +docker tag cloudlab-nodejs-app:latest your-registry/cloudlab-nodejs-app:latest +docker push your-registry/cloudlab-nodejs-app:latest + +# Update kustomization.yaml dengan registry URL +``` + +### Issue 2: Pods Pending + +**Problem:** Pods stuck di Pending state + +**Solution:** +```bash +# Check node resources +kubectl top nodes + +# Check pod events +kubectl describe pod -n cloudlab-apps + +# Scale down jika resource tidak cukup +kubectl scale deployment nodejs-app --replicas=1 -n cloudlab-apps +``` + +### Issue 3: Ingress Not Working + +**Problem:** Tidak bisa access via Ingress + +**Solution:** +```bash +# Check Ingress controller +kubectl get pods -n ingress-nginx + +# For Minikube, enable ingress addon +minikube addons enable ingress + +# For Minikube, run tunnel +minikube tunnel +``` + +### Issue 4: PVC Pending + +**Problem:** PersistentVolumeClaim stuck di Pending + +**Solution:** +```bash +# Check storage class +kubectl get storageclass + +# For Minikube, enable storage provisioner +minikube addons enable storage-provisioner + +# Check PVC events +kubectl describe pvc grafana-storage -n cloudlab-monitoring +``` + +## πŸ“Š Performance Comparison + +### Resource Usage + +| Metric | Docker Compose | Kubernetes (3 replicas) | +|--------|---------------|------------------------| +| **Memory** | ~2GB | ~4GB | +| **CPU** | ~1 core | ~2 cores | +| **Startup Time** | ~30s | ~60s | +| **Scalability** | Manual | Auto (HPA) | + +### Benefits Gained + +βœ… **High Availability**: Multiple replicas dengan self-healing +βœ… **Auto-scaling**: HPA based on CPU/memory +βœ… **Rolling Updates**: Zero-downtime deployments +βœ… **Better Monitoring**: Native Prometheus integration +βœ… **Cloud Portability**: Deploy anywhere +βœ… **Production Ready**: Enterprise-grade orchestration + +## πŸ“š Next Steps + +1. **Setup CI/CD**: Update GitHub Actions untuk Kubernetes deployment +2. **Implement GitOps**: ArgoCD atau FluxCD untuk automated sync +3. **Add Monitoring**: Prometheus Operator, Grafana dashboards +4. **Security Hardening**: Network Policies, RBAC, Pod Security +5. **Backup Strategy**: Velero untuk cluster backup +6. **Service Mesh**: Istio atau Linkerd untuk advanced traffic management + +## πŸ”— References + +- [Kubernetes Documentation](https://kubernetes.io/docs/) +- [Docker Compose to Kubernetes](https://kubernetes.io/docs/tasks/configure-pod-container/translate-compose-kubernetes/) +- [Kompose Tool](https://kompose.io/) - Auto-convert Compose to K8s +- [Kustomize](https://kustomize.io/) + +--- + +**Migration Complete! Welcome to Kubernetes! πŸŽ‰** diff --git a/README.md b/README.md index 558e74a..9dcb3d7 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,17 @@ Comprehensive cloud laboratory environment dengan Docker containerization, rever ## πŸš€ Quick Start -### Prerequisites +CloudLab dapat di-deploy dengan dua cara: + +### Option 1: Docker Compose (Recommended untuk Development) + +#### Prerequisites - Docker Engine 20.10+ - Docker Compose 2.0+ - Git -### Installation +#### Installation 1. **Clone repository** ```bash @@ -93,49 +97,262 @@ curl http://localhost:9090/-/healthy curl http://localhost:3000/api/health ``` -## πŸ”§ Development +### Option 2: Kubernetes (Recommended untuk Production) + +#### Prerequisites + +- kubectl v1.28+ +- Kubernetes cluster (Minikube/Kind/GKE/EKS/AKS) +- Docker Engine 20.10+ +- Git + +#### Quick Deploy + +```bash +# 1. Clone repository +git clone +cd cloud-lab + +# 2. Run deployment script +./k8s/scripts/deploy.sh + +# 3. Access applications via port-forward +kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps +kubectl port-forward svc/grafana 3000:3000 -n cloudlab-monitoring +``` + +**οΏ½ Dokumentasi Lengkap:** +- [Kubernetes Deployment Guide](k8s/README.md) - Setup dan deployment detail +- [Migration Guide](MIGRATION.md) - Migrasi dari Docker Compose ke Kubernetes + +## πŸ“Š Service Endpoints + +### Docker Compose + +| Service | URL | Credentials | +|---------|-----|-------------| +| **Node.js App** | https://localhost/ | - | +| **Python API** | https://localhost/api | - | +| **Grafana** | http://localhost:3000 | admin / admin123 | +| **Prometheus** | http://localhost:9090 | - | +| **Nginx Status** | https://localhost/nginx_status | Internal only | + +### Kubernetes (via Port Forward) + +| Service | Command | URL | +|---------|---------|-----| +| **Node.js App** | `kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps` | http://localhost:3001 | +| **Python API** | `kubectl port-forward svc/python-app 5000:5000 -n cloudlab-apps` | http://localhost:5000 | +| **Grafana** | `kubectl port-forward svc/grafana 3000:3000 -n cloudlab-monitoring` | http://localhost:3000 | +| **Prometheus** | `kubectl port-forward svc/prometheus 9090:9090 -n cloudlab-monitoring` | http://localhost:9090 | + +### Health Checks (Docker Compose) + +```bash +# Node.js App +curl -k https://localhost/health + +# Python API +curl -k https://localhost/api/health + +# Prometheus +curl http://localhost:9090/-/healthy + +# Grafana +curl http://localhost:3000/api/health +``` + +### Health Checks (Kubernetes) + +```bash +# Check pod status +kubectl get pods -n cloudlab-apps +kubectl get pods -n cloudlab-monitoring + +# Test endpoints via port-forward +kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps & +curl http://localhost:3001/health + +kubectl port-forward svc/python-app 5000:5000 -n cloudlab-apps & +curl http://localhost:5000/health +``` + +## 🎯 Deployment Comparison + +| Feature | Docker Compose | Kubernetes | +|---------|---------------|------------| +| **Setup Complexity** | ⭐ Simple | ⭐⭐⭐ Advanced | +| **Scalability** | Manual | Auto (HPA) | +| **High Availability** | Limited | Built-in | +| **Production Ready** | Development | Production | +| **Resource Usage** | ~2GB RAM | ~4GB RAM | +| **Learning Curve** | Easy | Moderate | + +**Rekomendasi:** +- πŸ”§ **Development**: Gunakan Docker Compose untuk development lokal yang cepat +- πŸš€ **Production**: Gunakan Kubernetes untuk production deployment dengan HA dan auto-scaling + +## πŸ”§ Development (Docker Compose) ### Struktur Direktori +> **πŸ’‘ Catatan Penting:** Folder `apps/` dan `k8s/apps/` adalah **BERBEDA** dan **TIDAK duplikasi**! +> - `apps/` = Source code aplikasi (untuk build Docker images) +> - `k8s/apps/` = Kubernetes deployment configs (untuk deploy ke cluster) + ``` cloud-lab/ -β”œβ”€β”€ apps/ -β”‚ └── demo-apps/ -β”‚ β”œβ”€β”€ nodejs-app/ # Node.js Express application -β”‚ β”‚ β”œβ”€β”€ Dockerfile -β”‚ β”‚ β”œβ”€β”€ package.json -β”‚ β”‚ └── server.js -β”‚ └── python-app/ # Python Flask API -β”‚ β”œβ”€β”€ Dockerfile -β”‚ β”œβ”€β”€ requirements.txt -β”‚ └── app.py -β”œβ”€β”€ ci/ -β”‚ └── github-actions.yml # CI/CD pipeline -β”œβ”€β”€ monitoring/ -β”‚ β”œβ”€β”€ prometheus.yml # Prometheus config -β”‚ β”œβ”€β”€ alerts.yml # Alert rules +β”œβ”€β”€ apps/ # πŸ“¦ APPLICATION SOURCE CODE +β”‚ └── demo-apps/ # (Digunakan untuk build Docker images) +β”‚ β”œβ”€β”€ nodejs-app/ # Node.js Express application +β”‚ β”‚ β”œβ”€β”€ Dockerfile # ← Build instructions +β”‚ β”‚ β”œβ”€β”€ package.json # ← Dependencies +β”‚ β”‚ └── server.js # ← Application code +β”‚ └── python-app/ # Python Flask API +β”‚ β”œβ”€β”€ Dockerfile # ← Build instructions +β”‚ β”œβ”€β”€ requirements.txt # ← Dependencies +β”‚ └── app.py # ← Application code +β”‚ +β”œβ”€β”€ ci/ # πŸ”„ CI/CD PIPELINE +β”‚ β”œβ”€β”€ github-actions.yml # GitHub Actions workflow +β”‚ └── README.md # CI/CD documentation +β”‚ +β”œβ”€β”€ monitoring/ # πŸ“Š MONITORING (Docker Compose) +β”‚ β”œβ”€β”€ prometheus.yml # Prometheus config +β”‚ β”œβ”€β”€ alerts.yml # Alert rules β”‚ └── grafana/ -β”‚ β”œβ”€β”€ datasources.yml # Grafana datasources -β”‚ β”œβ”€β”€ dashboards.yml # Dashboard provisioning -β”‚ └── dashboards/ # Dashboard JSON files -β”œβ”€β”€ nginx/ -β”‚ β”œβ”€β”€ nginx.conf # Main Nginx config -β”‚ β”œβ”€β”€ ssl/ # SSL certificates -β”‚ └── conf.d/ # Additional configs -└── docker-compose.yml # Orchestration +β”‚ β”œβ”€β”€ datasources.yml # Grafana datasources +β”‚ β”œβ”€β”€ dashboards.yml # Dashboard provisioning +β”‚ └── dashboards/ # Dashboard JSON files +β”‚ +β”œβ”€β”€ nginx/ # 🌐 REVERSE PROXY (Docker Compose) +β”‚ β”œβ”€β”€ nginx.conf # Main Nginx config +β”‚ β”œβ”€β”€ ssl/ # SSL certificates +β”‚ └── conf.d/ # Additional configs +β”‚ +β”œβ”€β”€ k8s/ # ☸️ KUBERNETES MANIFESTS +β”‚ β”‚ # (Deployment configurations, BUKAN source code) +β”‚ β”œβ”€β”€ README.md # Kubernetes deployment guide +β”‚ β”œβ”€β”€ kustomization.yaml # Kustomize config +β”‚ β”œβ”€β”€ base/ # Base configurations +β”‚ β”‚ β”œβ”€β”€ namespace.yaml # Namespaces +β”‚ β”‚ β”œβ”€β”€ configmaps/ # ConfigMaps (Nginx, Prometheus) +β”‚ β”‚ └── secrets/ # Secrets (SSL, credentials) +β”‚ β”œβ”€β”€ apps/ # πŸš€ APPLICATION DEPLOYMENTS +β”‚ β”‚ β”œβ”€β”€ nodejs-app/ # (YAML configs, bukan source code!) +β”‚ β”‚ β”‚ β”œβ”€β”€ deployment.yaml # ← How to deploy +β”‚ β”‚ β”‚ β”œβ”€β”€ service.yaml # ← How to expose +β”‚ β”‚ β”‚ └── hpa.yaml # ← How to scale +β”‚ β”‚ └── python-app/ +β”‚ β”‚ β”œβ”€β”€ deployment.yaml +β”‚ β”‚ β”œβ”€β”€ service.yaml +β”‚ β”‚ └── hpa.yaml +β”‚ β”œβ”€β”€ monitoring/ # Monitoring stack for K8s +β”‚ β”‚ β”œβ”€β”€ prometheus/ # Prometheus StatefulSet +β”‚ β”‚ └── grafana/ # Grafana Deployment +β”‚ β”œβ”€β”€ ingress/ # Ingress configs +β”‚ β”‚ β”œβ”€β”€ ingress.yaml # Routing rules +β”‚ β”‚ └── cert-manager.yaml # SSL automation +β”‚ └── scripts/ # Helper scripts +β”‚ β”œβ”€β”€ deploy.sh # Automated deployment +β”‚ └── cleanup.sh # Cleanup script +β”‚ +β”œβ”€β”€ scripts/ # πŸ› οΈ UTILITY SCRIPTS (Docker Compose) +β”‚ β”œβ”€β”€ setup.sh +β”‚ └── cleanup.sh +β”‚ +β”œβ”€β”€ docker-compose.yml # 🐳 Docker Compose orchestration +β”œβ”€β”€ MIGRATION.md # πŸ“– Migration guide +└── README.md # This file +``` + +#### Penjelasan Struktur + +**Separation of Concerns:** + +| Directory | Purpose | Used By | Contains | +|-----------|---------|---------|----------| +| `apps/` | **Source code** untuk build images | Docker Compose & Kubernetes | Dockerfile, source code, dependencies | +| `k8s/apps/` | **Deployment configs** untuk K8s | Kubernetes only | YAML manifests (deployment, service, hpa) | +| `monitoring/` | Monitoring configs | Docker Compose only | Prometheus/Grafana configs | +| `k8s/monitoring/` | Monitoring configs | Kubernetes only | K8s manifests untuk Prometheus/Grafana | + +**Workflow:** +``` +1. Build: apps/demo-apps/nodejs-app/ β†’ docker build β†’ cloudlab-nodejs-app:latest +2. Deploy: k8s/apps/nodejs-app/ β†’ kubectl apply β†’ Running pods in cluster +``` + +**Analogi:** +- `apps/` = Dapur (tempat masak/build) +- `k8s/apps/` = Buku menu (cara sajikan/deploy) +``` + +### Melihat Logs (Docker Compose) + +```bash +# Semua services +docker-compose logs -f + +# Service tertentu +docker-compose logs -f nodejs-app +docker-compose logs -f python-app +docker-compose logs -f nginx +docker-compose logs -f prometheus +docker-compose logs -f grafana +``` + +## οΏ½πŸ”§ Operations (Kubernetes) + +### Melihat Logs + +```bash +# View logs +kubectl logs -f deployment/nodejs-app -n cloudlab-apps +kubectl logs -f deployment/python-app -n cloudlab-apps +kubectl logs -f statefulset/prometheus -n cloudlab-monitoring + +# Logs dari semua pods +kubectl logs -l app=nodejs-app -n cloudlab-apps --tail=100 +``` + +### Scaling + +```bash +# Manual scaling +kubectl scale deployment nodejs-app --replicas=5 -n cloudlab-apps + +# Check HPA status +kubectl get hpa -n cloudlab-apps +``` + +### Cleanup + +```bash +# Docker Compose +docker-compose down + +# Kubernetes +./k8s/scripts/cleanup.sh +# atau +kubectl delete -k k8s/ ``` ### Menambah Service Baru +**Docker Compose:** 1. Buat direktori aplikasi di `apps/` 2. Tambahkan service di `docker-compose.yml` 3. Konfigurasi reverse proxy di `nginx/nginx.conf` 4. Tambahkan scrape config di `monitoring/prometheus.yml` -5. **Tambahkan ke CI/CD pipeline** di `ci/github-actions.yml` (matrix strategy) -6. Rebuild dan restart: - ```bash - docker-compose up -d --build - ``` +5. Tambahkan ke CI/CD pipeline di `ci/github-actions.yml` (matrix strategy) +6. Rebuild: `docker-compose up -d --build` + +**Kubernetes:** +1. Buat direktori di `k8s/apps//` +2. Buat `deployment.yaml`, `service.yaml`, `hpa.yaml` +3. Update `k8s/kustomization.yaml` untuk include resources baru +4. Deploy: `kubectl apply -k k8s/` > **πŸ’‘ Tip:** Dengan matrix strategy di CI/CD, menambah aplikasi baru ke pipeline sangat mudah - cukup tambah 1 entry di matrix tanpa duplikasi kode. Lihat [`ci/README.md`](ci/README.md) untuk detail. diff --git a/apps/demo-apps/nodejs-app/Dockerfile b/apps/demo-apps/nodejs-app/Dockerfile index 22f410e..cf2de94 100644 --- a/apps/demo-apps/nodejs-app/Dockerfile +++ b/apps/demo-apps/nodejs-app/Dockerfile @@ -4,20 +4,23 @@ FROM node:18-alpine WORKDIR /app # Copy package files -COPY package*.json ./ +COPY --chown=node:node package*.json ./ # Install dependencies RUN npm ci --only=production # Copy application files -COPY . . +COPY --chown=node:node . . # Expose port EXPOSE 3001 # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ - CMD node -e "require('http').get('http://localhost:3001/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" + CMD ["node", "-e", "require('http').get('http://localhost:3001/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"] + +# Switch to non-root user +USER node # Start application CMD ["npm", "start"] diff --git a/apps/demo-apps/nodejs-app/package-lock.json b/apps/demo-apps/nodejs-app/package-lock.json new file mode 100644 index 0000000..c0a4209 --- /dev/null +++ b/apps/demo-apps/nodejs-app/package-lock.json @@ -0,0 +1,1265 @@ +{ + "name": "cloudlab-nodejs-app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "cloudlab-nodejs-app", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "cors": "^2.8.5", + "express": "^4.18.2", + "prom-client": "^15.1.0" + }, + "devDependencies": { + "nodemon": "^3.0.2" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bintrees": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz", + "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true, + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nodemon": { + "version": "3.1.11", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.11.tgz", + "integrity": "sha512-is96t8F/1//UHAjNPHpbsNY46ELPpftGUoSVNXwUfMk/qdjSylYrWSu1XavVTBOn526kFiOR733ATgNBCQyH0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prom-client": { + "version": "15.1.3", + "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz", + "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.0", + "tdigest": "^0.1.1" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tdigest": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz", + "integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==", + "license": "MIT", + "dependencies": { + "bintrees": "1.0.2" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/apps/demo-apps/nodejs-app/server.js b/apps/demo-apps/nodejs-app/server.js index 14900f5..7f57e76 100644 --- a/apps/demo-apps/nodejs-app/server.js +++ b/apps/demo-apps/nodejs-app/server.js @@ -28,6 +28,37 @@ const httpRequestTotal = new promClient.Counter({ registers: [register] }); +// -- Business Metrics -- +const activeSessions = new promClient.Gauge({ + name: 'active_sessions_total', + help: 'Number of active user sessions', + registers: [register] +}); + +const dbQueryDuration = new promClient.Histogram({ + name: 'db_query_duration_seconds', + help: 'Duration of database queries in seconds', + buckets: [0.1, 0.3, 0.5, 1, 3, 5], + registers: [register] +}); + +// Simulate metric changes +setInterval(() => { + // Randomly change active sessions + const fluctuation = Math.floor(Math.random() * 5) - 2; // -2 to +2 + let current = (global.currentSessions || 100) + fluctuation; + if (current < 0) current = 0; + global.currentSessions = current; + activeSessions.set(current); + + // Simulate occasional slow DB query + if (Math.random() > 0.8) { + dbQueryDuration.observe(Math.random() * 0.8); // Fast to medium + } else if (Math.random() > 0.95) { + dbQueryDuration.observe(0.5 + Math.random() * 1.5); // SLOW! + } +}, 5000); + // Middleware to track metrics app.use((req, res, next) => { const start = Date.now(); diff --git a/apps/demo-apps/python-app/Dockerfile b/apps/demo-apps/python-app/Dockerfile index f2da1d0..603890a 100644 --- a/apps/demo-apps/python-app/Dockerfile +++ b/apps/demo-apps/python-app/Dockerfile @@ -3,12 +3,15 @@ FROM python:3.11-slim # Set working directory WORKDIR /app +# Create a non-root user +RUN groupadd -r appuser && useradd -r -g appuser appuser + # Install dependencies COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy application files -COPY . . +COPY --chown=appuser:appuser . . # Expose port EXPOSE 5000 @@ -17,5 +20,8 @@ EXPOSE 5000 HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/health').read()" || exit 1 +# Switch to non-root user +USER appuser + # Start application with gunicorn CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "2", "--timeout", "60", "app:app"] diff --git a/apps/demo-apps/python-app/app.py b/apps/demo-apps/python-app/app.py index d741f02..6bbc089 100644 --- a/apps/demo-apps/python-app/app.py +++ b/apps/demo-apps/python-app/app.py @@ -12,12 +12,49 @@ ['method', 'endpoint', 'status_code'] ) -REQUEST_DURATION = Histogram( - 'http_request_duration_seconds', 'HTTP request duration in seconds', ['method', 'endpoint'] ) +# -- Business Metrics -- +from prometheus_client import Gauge +import random +import threading + +INVENTORY_STOCK = Gauge( + 'inventory_stock_count', + 'Current stock level of product', + ['product_id'] +) + +CHECKOUT_TIME = Histogram( + 'checkout_processing_seconds', + 'Time taken to process checkout', + buckets=(0.1, 0.5, 1.0, 2.0, 5.0) +) + +# Background simulation +def simulate_metrics(): + # Init stocks + stocks = {1: 50, 2: 200, 3: 15, 4: 5} + while True: + time.sleep(5) + # Update stock + for pid, count in stocks.items(): + # Randomly decrease stock, restock if low + change = random.randint(-2, 1) + stocks[pid] = max(0, stocks[pid] + change) + if stocks[pid] < 5: + if random.random() > 0.8: stocks[pid] += 20 # Restock + + INVENTORY_STOCK.labels(product_id=pid).set(stocks[pid]) + + # Simulate checkout latency + if random.random() > 0.7: + CHECKOUT_TIME.observe(random.uniform(0.1, 1.5)) + +threading.Thread(target=simulate_metrics, daemon=True).start() + # Middleware to track metrics @app.before_request def before_request(): diff --git a/docker-compose.yml b/docker-compose.yml index 7484b95..2bdf8c9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -version: '3.8' +version: "3.8" services: # Nginx Reverse Proxy @@ -13,13 +13,34 @@ services: - ./nginx/conf.d:/etc/nginx/conf.d:ro - ./nginx/ssl:/etc/nginx/ssl:ro depends_on: - - nodejs-app - - python-app - - grafana - - prometheus + nodejs-app: + condition: service_healthy + python-app: + condition: service_healthy + grafana: + condition: service_healthy + prometheus: + condition: service_healthy networks: - cloudlab-network restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 128M + healthcheck: + test: [ + "CMD", + "wget", + "--quiet", + "--tries=1", + "--spider", + "http://localhost:80/health", + ] # Assuming /health exists or root + interval: 30s + timeout: 10s + retries: 3 # Prometheus - Metrics Collection prometheus: @@ -32,14 +53,32 @@ services: - ./monitoring/alerts.yml:/etc/prometheus/alerts.yml:ro - prometheus-data:/prometheus command: - - '--config.file=/etc/prometheus/prometheus.yml' - - '--storage.tsdb.path=/prometheus' - - '--web.console.libraries=/usr/share/prometheus/console_libraries' - - '--web.console.templates=/usr/share/prometheus/consoles' - - '--web.enable-lifecycle' + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + - "--web.console.libraries=/usr/share/prometheus/console_libraries" + - "--web.console.templates=/usr/share/prometheus/consoles" + - "--web.enable-lifecycle" networks: - cloudlab-network restart: unless-stopped + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + healthcheck: + test: + [ + "CMD", + "wget", + "--quiet", + "--tries=1", + "--spider", + "http://localhost:9090/-/healthy", + ] + interval: 30s + timeout: 10s + retries: 3 # Grafana - Visualization grafana: @@ -58,10 +97,29 @@ services: - GF_USERS_ALLOW_SIGN_UP=false - GF_SERVER_ROOT_URL=http://localhost:3000 depends_on: - - prometheus + prometheus: + condition: service_healthy networks: - cloudlab-network restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + healthcheck: + test: + [ + "CMD", + "wget", + "--quiet", + "--tries=1", + "--spider", + "http://localhost:3000/api/health", + ] + interval: 30s + timeout: 10s + retries: 3 # Node.js Demo App nodejs-app: @@ -77,8 +135,21 @@ services: networks: - cloudlab-network restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3001/health"] + test: + [ + "CMD", + "wget", + "--quiet", + "--tries=1", + "--spider", + "http://localhost:3001/health", + ] interval: 30s timeout: 10s retries: 3 @@ -97,8 +168,21 @@ services: networks: - cloudlab-network restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:5000/health"] + test: + [ + "CMD", + "wget", + "--quiet", + "--tries=1", + "--spider", + "http://localhost:5000/health", + ] interval: 30s timeout: 10s retries: 3 diff --git a/k8s/FAQ.md b/k8s/FAQ.md new file mode 100644 index 0000000..5cb381f --- /dev/null +++ b/k8s/FAQ.md @@ -0,0 +1,295 @@ +# FAQ - Frequently Asked Questions + +## ❓ Pertanyaan Umum + +### 1. Mengapa ada folder `apps/` dan `k8s/apps/`? Apakah duplikasi? + +**TIDAK!** Ini bukan duplikasi. Mereka memiliki fungsi yang berbeda: + +| Folder | Fungsi | Berisi | Digunakan Untuk | +|--------|--------|--------|-----------------| +| `apps/` | Source code aplikasi | Dockerfile, source code, dependencies | Build Docker images | +| `k8s/apps/` | Deployment configuration | YAML manifests (deployment, service, hpa) | Deploy ke Kubernetes | + +**Analogi:** +- `apps/` = Dapur (tempat masak/build aplikasi) +- `k8s/apps/` = Buku menu (cara sajikan/deploy aplikasi) + +**Workflow:** +``` +apps/demo-apps/nodejs-app/ + β”œβ”€β”€ Dockerfile ─┐ + β”œβ”€β”€ package.json β”œβ”€β†’ docker build β†’ cloudlab-nodejs-app:latest + └── server.js β”€β”˜ + +k8s/apps/nodejs-app/ + β”œβ”€β”€ deployment.yaml ─┐ + β”œβ”€β”€ service.yaml β”œβ”€β†’ kubectl apply β†’ Running pods in cluster + └── hpa.yaml β”€β”˜ +``` + +### 2. Apakah saya perlu mengubah source code di `apps/` untuk Kubernetes? + +**TIDAK!** Source code di `apps/` tetap sama untuk Docker Compose dan Kubernetes. Yang berbeda hanya cara deployment-nya: +- Docker Compose: menggunakan `docker-compose.yml` +- Kubernetes: menggunakan manifests di `k8s/` + +### 3. Kenapa ada `monitoring/` dan `k8s/monitoring/`? + +Sama seperti `apps/`, ini juga separation of concerns: + +| Folder | Untuk | Berisi | +|--------|-------|--------| +| `monitoring/` | Docker Compose | Prometheus/Grafana configs untuk Docker Compose | +| `k8s/monitoring/` | Kubernetes | Kubernetes manifests untuk Prometheus/Grafana | + +### 4. Apakah saya bisa menggunakan Docker Compose dan Kubernetes bersamaan? + +**TIDAK direkomendasikan** untuk production. Pilih salah satu: +- **Development**: Docker Compose (lebih simple) +- **Production**: Kubernetes (lebih robust, scalable) + +Tapi untuk testing, Anda bisa run keduanya di environment berbeda. + +### 5. Bagaimana cara menambah aplikasi baru? + +**Untuk Docker Compose:** +1. Buat folder di `apps/demo-apps//` +2. Tambahkan Dockerfile dan source code +3. Update `docker-compose.yml` +4. Update `nginx/nginx.conf` untuk routing + +**Untuk Kubernetes:** +1. Buat folder di `apps/demo-apps//` (sama seperti di atas) +2. Buat folder di `k8s/apps//` +3. Buat `deployment.yaml`, `service.yaml`, `hpa.yaml` +4. Update `k8s/kustomization.yaml` +5. Update `k8s/ingress/ingress.yaml` untuk routing + +### 6. Mengapa image tidak bisa di-pull di Kubernetes? + +**Penyebab umum:** +- Image hanya ada di local Docker, belum di-load ke Minikube +- Image belum di-push ke container registry + +**Solusi:** + +**Untuk Minikube:** +```bash +minikube image load cloudlab-nodejs-app:latest +``` + +**Untuk cluster lain:** +```bash +# Push ke registry +docker tag cloudlab-nodejs-app:latest your-registry/cloudlab-nodejs-app:latest +docker push your-registry/cloudlab-nodejs-app:latest + +# Update kustomization.yaml +images: + - name: cloudlab-nodejs-app + newName: your-registry/cloudlab-nodejs-app + newTag: latest +``` + +### 7. Bagaimana cara update aplikasi yang sudah running? + +**Option 1: Rebuild image dan redeploy** +```bash +# 1. Rebuild image +cd apps/demo-apps/nodejs-app +docker build -t cloudlab-nodejs-app:v2 . + +# 2. Load ke Minikube (atau push ke registry) +minikube image load cloudlab-nodejs-app:v2 + +# 3. Update deployment +kubectl set image deployment/nodejs-app nodejs-app=cloudlab-nodejs-app:v2 -n cloudlab-apps + +# 4. Watch rollout +kubectl rollout status deployment/nodejs-app -n cloudlab-apps +``` + +**Option 2: Update code dan apply** +```bash +# 1. Edit source code di apps/ +# 2. Rebuild dan load image +# 3. Restart deployment +kubectl rollout restart deployment/nodejs-app -n cloudlab-apps +``` + +### 8. Pods stuck di "Pending" status, kenapa? + +**Penyebab umum:** +- Tidak cukup resources (CPU/memory) di cluster +- PersistentVolume tidak tersedia +- Node selector tidak match + +**Debugging:** +```bash +# Check pod events +kubectl describe pod -n cloudlab-apps + +# Check node resources +kubectl top nodes + +# Check PVC status +kubectl get pvc -n cloudlab-monitoring +``` + +**Solusi:** +- Scale down replicas jika resource terbatas +- Enable storage provisioner untuk Minikube +- Adjust resource requests/limits + +### 9. Bagaimana cara melihat logs dari semua pods? + +```bash +# Logs dari semua pods dengan label app=nodejs-app +kubectl logs -l app=nodejs-app -n cloudlab-apps --tail=100 -f + +# Atau gunakan stern (perlu install) +stern nodejs-app -n cloudlab-apps +``` + +### 10. Apakah HPA (autoscaling) langsung bekerja? + +**TIDAK otomatis.** HPA membutuhkan: +1. **Metrics Server** harus installed + ```bash + # Untuk Minikube + minikube addons enable metrics-server + + # Verify + kubectl top nodes + kubectl top pods -n cloudlab-apps + ``` + +2. **Load** yang cukup untuk trigger scaling + ```bash + # Generate load + kubectl run -it --rm load-generator --image=busybox -- /bin/sh + while true; do wget -q -O- http://nodejs-app.cloudlab-apps.svc.cluster.local:3001; done + + # Watch HPA + kubectl get hpa -n cloudlab-apps --watch + ``` + +### 11. SSL certificates tidak bekerja, kenapa? + +**Penyebab:** +- Secret `cloudlab-tls` masih menggunakan placeholder values + +**Solusi:** +```bash +# Generate self-signed certificate +openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout /tmp/tls.key -out /tmp/tls.crt \ + -subj "/C=ID/ST=Jakarta/L=Jakarta/O=CloudLab/OU=Dev/CN=cloudlab.local" + +# Encode dan update +TLS_CRT=$(cat /tmp/tls.crt | base64 -w 0) +TLS_KEY=$(cat /tmp/tls.key | base64 -w 0) +sed -i "s|tls.crt:.*|tls.crt: $TLS_CRT|" k8s/base/secrets/ssl-certs.yaml +sed -i "s|tls.key:.*|tls.key: $TLS_KEY|" k8s/base/secrets/ssl-certs.yaml + +# Reapply +kubectl delete secret cloudlab-tls -n cloudlab-apps +kubectl apply -f k8s/base/secrets/ssl-certs.yaml +``` + +**Untuk production:** +Install cert-manager dan gunakan Let's Encrypt: +```bash +kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml +kubectl apply -f k8s/ingress/cert-manager.yaml +``` + +### 12. Bagaimana cara cleanup semua resources? + +**Option 1: Menggunakan script** +```bash +./k8s/scripts/cleanup.sh +``` + +**Option 2: Manual** +```bash +# Delete via kustomization +kubectl delete -k k8s/ + +# Atau delete namespaces (cascade delete semua resources) +kubectl delete namespace cloudlab-apps +kubectl delete namespace cloudlab-monitoring +``` + +### 13. Apakah data Prometheus/Grafana hilang saat pod restart? + +**TIDAK**, karena menggunakan PersistentVolume. Data akan tetap ada selama PVC tidak dihapus. + +**Backup data:** +```bash +# Backup Grafana +kubectl cp grafana-:/var/lib/grafana ./backup/grafana -n cloudlab-monitoring + +# Backup Prometheus +kubectl cp prometheus-0:/prometheus ./backup/prometheus -n cloudlab-monitoring +``` + +### 14. Bagaimana cara access Grafana/Prometheus dari luar cluster? + +**Option 1: Port Forward (Development)** +```bash +kubectl port-forward svc/grafana 3000:3000 -n cloudlab-monitoring +# Access: http://localhost:3000 +``` + +**Option 2: Ingress (Production)** +```bash +# Sudah configured di k8s/ingress/ingress.yaml +# Access: https://grafana.cloudlab.local (setelah update /etc/hosts) +``` + +**Option 3: NodePort (Testing)** +```bash +# Edit service type +kubectl patch svc grafana -n cloudlab-monitoring -p '{"spec":{"type":"NodePort"}}' + +# Get NodePort +kubectl get svc grafana -n cloudlab-monitoring + +# Access via Minikube IP +minikube ip +# http://: +``` + +### 15. Dimana saya bisa belajar lebih lanjut tentang Kubernetes? + +**Official Resources:** +- [Kubernetes Documentation](https://kubernetes.io/docs/) +- [Kubernetes Tutorials](https://kubernetes.io/docs/tutorials/) +- [kubectl Cheat Sheet](https://kubernetes.io/docs/reference/kubectl/cheatsheet/) + +**Interactive Learning:** +- [Katacoda Kubernetes Scenarios](https://www.katacoda.com/courses/kubernetes) +- [Play with Kubernetes](https://labs.play-with-k8s.com/) + +**Books:** +- "Kubernetes Up & Running" by Kelsey Hightower +- "The Kubernetes Book" by Nigel Poulton + +**YouTube Channels:** +- TechWorld with Nana +- Just me and Opensource +- KodeKloud + +--- + +## πŸ†˜ Masih Ada Pertanyaan? + +Jika pertanyaan Anda tidak terjawab di sini: +1. Check [main README](../README.md) +2. Check [k8s/README.md](README.md) +3. Check [MIGRATION.md](../MIGRATION.md) +4. Buat issue di repository + +**Happy Learning! πŸš€** diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000..8543742 --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,520 @@ +# Kubernetes Deployment Guide + +Panduan lengkap untuk deploy CloudLab ke Kubernetes cluster. + +## πŸ“‹ Prerequisites + +### Required Tools +- **kubectl** v1.28+ - Kubernetes CLI +- **Docker** v20.10+ - Container runtime +- **Kubernetes cluster** - Salah satu dari: + - Minikube (local development) + - Kind (Kubernetes in Docker) + - GKE/EKS/AKS (cloud managed) + - kubeadm/k3s (self-managed) + +### Optional Tools +- **Helm** v3.0+ - Package manager +- **k9s** - Terminal UI untuk Kubernetes +- **kubectx/kubens** - Context dan namespace switching +- **kustomize** - Configuration management (built-in kubectl) + +## πŸ“ Understanding Directory Structure + +> **⚠️ PENTING:** Jangan bingung antara `apps/` dan `k8s/apps/` - mereka **BERBEDA**! + +``` +cloud-lab/ +β”œβ”€β”€ apps/ # πŸ“¦ SOURCE CODE (untuk build images) +β”‚ └── demo-apps/ +β”‚ β”œβ”€β”€ nodejs-app/ # ← Dockerfile, package.json, server.js +β”‚ └── python-app/ # ← Dockerfile, requirements.txt, app.py +β”‚ +└── k8s/ # ☸️ KUBERNETES CONFIGS (untuk deploy) + └── apps/ # πŸš€ DEPLOYMENT MANIFESTS + β”œβ”€β”€ nodejs-app/ # ← deployment.yaml, service.yaml, hpa.yaml + └── python-app/ # ← deployment.yaml, service.yaml, hpa.yaml +``` + +**Workflow:** +1. **Build** dari `apps/` β†’ Docker image +2. **Deploy** dengan `k8s/apps/` β†’ Running pods + +**Analogi:** +- `apps/` = Resep masakan (cara buat) +- `k8s/apps/` = Menu restoran (cara sajikan) + +Lihat [main README](../README.md#struktur-direktori) untuk penjelasan lengkap. + +## πŸš€ Quick Start + +### 1. Setup Kubernetes Cluster + +#### Option A: Minikube (Recommended untuk Development) + +```bash +# Install Minikube +curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 +sudo install minikube-linux-amd64 /usr/local/bin/minikube + +# Start cluster dengan resources yang cukup +minikube start --cpus=4 --memory=8192 --disk-size=20g + +# Enable addons +minikube addons enable ingress +minikube addons enable metrics-server +minikube addons enable storage-provisioner + +# Verify cluster +kubectl cluster-info +kubectl get nodes +``` + +#### Option B: Kind (Kubernetes in Docker) + +```bash +# Install Kind +curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.20.0/kind-linux-amd64 +chmod +x ./kind +sudo mv ./kind /usr/local/bin/kind + +# Create cluster dengan config +cat < -n cloudlab-apps + +# Execute command di pod +kubectl exec -it -n cloudlab-apps -- /bin/sh + +# Check events +kubectl get events -n cloudlab-apps --sort-by='.lastTimestamp' + +# Check resource usage +kubectl top nodes +kubectl top pods -n cloudlab-apps +``` + +## πŸ§ͺ Testing + +### Health Checks + +```bash +# Test health endpoints via port-forward +kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps & +curl http://localhost:3001/health + +kubectl port-forward svc/python-app 5000:5000 -n cloudlab-apps & +curl http://localhost:5000/health +``` + +### Load Testing + +```bash +# Generate load untuk test autoscaling +kubectl run -it --rm load-generator --image=busybox --restart=Never -- /bin/sh + +# Di dalam container +while true; do wget -q -O- http://nodejs-app.cloudlab-apps.svc.cluster.local:3001; done + +# Watch HPA di terminal lain +kubectl get hpa -n cloudlab-apps --watch +``` + +## πŸ”’ Security + +### Network Policies (Optional) + +```bash +# Apply network policies untuk isolasi +kubectl apply -f k8s/network-policies/ +``` + +### RBAC + +```bash +# Check service accounts +kubectl get serviceaccounts -n cloudlab-monitoring + +# Check roles +kubectl get clusterroles | grep prometheus +kubectl get clusterrolebindings | grep prometheus +``` + +### Secrets Management + +```bash +# View secrets (encoded) +kubectl get secrets -n cloudlab-apps +kubectl get secrets -n cloudlab-monitoring + +# Decode secret +kubectl get secret cloudlab-tls -n cloudlab-apps -o jsonpath='{.data.tls\.crt}' | base64 -d +``` + +## 🧹 Cleanup + +```bash +# Delete semua resources +kubectl delete -k k8s/ + +# Atau delete per namespace +kubectl delete namespace cloudlab-apps +kubectl delete namespace cloudlab-monitoring + +# Delete cluster (Minikube) +minikube delete + +# Delete cluster (Kind) +kind delete cluster +``` + +## πŸ› οΈ Troubleshooting + +### Pods tidak start + +```bash +# Check pod status +kubectl get pods -n cloudlab-apps + +# Describe pod untuk lihat events +kubectl describe pod -n cloudlab-apps + +# Check logs +kubectl logs -n cloudlab-apps + +# Common issues: +# - ImagePullBackOff: Image tidak ditemukan +# - CrashLoopBackOff: Container crash saat start +# - Pending: Tidak cukup resources +``` + +### Ingress tidak accessible + +```bash +# Check ingress controller +kubectl get pods -n ingress-nginx + +# Check ingress resource +kubectl describe ingress cloudlab-ingress -n cloudlab-apps + +# Check service endpoints +kubectl get endpoints -n cloudlab-apps + +# Untuk Minikube, pastikan tunnel running +minikube tunnel +``` + +### Prometheus tidak scrape metrics + +```bash +# Check Prometheus targets +kubectl port-forward svc/prometheus 9090:9090 -n cloudlab-monitoring +# Buka http://localhost:9090/targets + +# Check service discovery +kubectl get servicemonitors -n cloudlab-monitoring + +# Check pod annotations +kubectl get pod -n cloudlab-apps -o yaml | grep prometheus.io +``` + +### Storage issues + +```bash +# Check PVCs +kubectl get pvc -n cloudlab-monitoring + +# Check PVs +kubectl get pv + +# Describe PVC untuk lihat events +kubectl describe pvc grafana-storage -n cloudlab-monitoring + +# Untuk Minikube, pastikan storage provisioner enabled +minikube addons enable storage-provisioner +``` + +## πŸ“š Advanced Topics + +### Helm Deployment + +```bash +# Install dengan Helm (jika helm charts sudah dibuat) +helm install cloudlab ./helm/cloudlab -n cloudlab-apps --create-namespace + +# Upgrade +helm upgrade cloudlab ./helm/cloudlab -n cloudlab-apps + +# Rollback +helm rollback cloudlab -n cloudlab-apps +``` + +### GitOps dengan ArgoCD + +```bash +# Install ArgoCD +kubectl create namespace argocd +kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml + +# Create Application +kubectl apply -f argocd/application.yaml +``` + +### Service Mesh (Istio) + +```bash +# Install Istio +istioctl install --set profile=demo -y + +# Enable sidecar injection +kubectl label namespace cloudlab-apps istio-injection=enabled + +# Redeploy pods +kubectl rollout restart deployment -n cloudlab-apps +``` + +## πŸ”— Resources + +- [Kubernetes Documentation](https://kubernetes.io/docs/) +- [kubectl Cheat Sheet](https://kubernetes.io/docs/reference/kubectl/cheatsheet/) +- [Kustomize Documentation](https://kustomize.io/) +- [Helm Documentation](https://helm.sh/docs/) +- [Prometheus Operator](https://prometheus-operator.dev/) + +## ❓ FAQ + +Punya pertanyaan? Check [FAQ.md](FAQ.md) untuk jawaban pertanyaan umum seperti: +- Mengapa ada `apps/` dan `k8s/apps/`? +- Bagaimana cara update aplikasi? +- Troubleshooting pods yang pending +- Dan banyak lagi... + +## πŸ“ž Support + +Untuk issues atau pertanyaan, silakan buat issue di repository. + +--- + +**Happy Kubernetes Deployment! πŸš€** diff --git a/k8s/apps/nodejs-app/deployment.yaml b/k8s/apps/nodejs-app/deployment.yaml new file mode 100644 index 0000000..a4af2e7 --- /dev/null +++ b/k8s/apps/nodejs-app/deployment.yaml @@ -0,0 +1,70 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nodejs-app + namespace: cloudlab-apps + labels: + app: nodejs-app + tier: frontend +spec: + replicas: 3 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + selector: + matchLabels: + app: nodejs-app + template: + metadata: + labels: + app: nodejs-app + tier: frontend + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "3001" + prometheus.io/path: "/metrics" + spec: + securityContext: + runAsNonRoot: true + containers: + - name: nodejs-app + image: cloudlab-nodejs-app:latest + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 3001 + protocol: TCP + env: + - name: NODE_ENV + value: "production" + - name: PORT + value: "3001" + resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 500m + memory: 512Mi + livenessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 3 + readinessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: 10 + periodSeconds: 5 + timeoutSeconds: 3 + successThreshold: 1 + failureThreshold: 3 + restartPolicy: Always + terminationGracePeriodSeconds: 30 diff --git a/k8s/apps/nodejs-app/hpa.yaml b/k8s/apps/nodejs-app/hpa.yaml new file mode 100644 index 0000000..32ac51d --- /dev/null +++ b/k8s/apps/nodejs-app/hpa.yaml @@ -0,0 +1,44 @@ +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: nodejs-app-hpa + namespace: cloudlab-apps + labels: + app: nodejs-app +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: nodejs-app + minReplicas: 2 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + behavior: + scaleDown: + stabilizationWindowSeconds: 300 + policies: + - type: Percent + value: 50 + periodSeconds: 60 + scaleUp: + stabilizationWindowSeconds: 0 + policies: + - type: Percent + value: 100 + periodSeconds: 30 + - type: Pods + value: 2 + periodSeconds: 30 + selectPolicy: Max diff --git a/k8s/apps/nodejs-app/service.yaml b/k8s/apps/nodejs-app/service.yaml new file mode 100644 index 0000000..b46ecee --- /dev/null +++ b/k8s/apps/nodejs-app/service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + name: nodejs-app + namespace: cloudlab-apps + labels: + app: nodejs-app + tier: frontend +spec: + type: ClusterIP + selector: + app: nodejs-app + ports: + - name: http + port: 3001 + targetPort: http + protocol: TCP + sessionAffinity: None diff --git a/k8s/apps/python-app/deployment.yaml b/k8s/apps/python-app/deployment.yaml new file mode 100644 index 0000000..0be3eb6 --- /dev/null +++ b/k8s/apps/python-app/deployment.yaml @@ -0,0 +1,70 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: python-app + namespace: cloudlab-apps + labels: + app: python-app + tier: backend +spec: + replicas: 3 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + selector: + matchLabels: + app: python-app + template: + metadata: + labels: + app: python-app + tier: backend + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "5000" + prometheus.io/path: "/metrics" + spec: + securityContext: + runAsNonRoot: true + containers: + - name: python-app + image: cloudlab-python-app:latest + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 5000 + protocol: TCP + env: + - name: FLASK_ENV + value: "production" + - name: FLASK_APP + value: "app.py" + resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 500m + memory: 512Mi + livenessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 3 + readinessProbe: + httpGet: + path: /health + port: http + initialDelaySeconds: 10 + periodSeconds: 5 + timeoutSeconds: 3 + successThreshold: 1 + failureThreshold: 3 + restartPolicy: Always + terminationGracePeriodSeconds: 30 diff --git a/k8s/apps/python-app/hpa.yaml b/k8s/apps/python-app/hpa.yaml new file mode 100644 index 0000000..2b09d0b --- /dev/null +++ b/k8s/apps/python-app/hpa.yaml @@ -0,0 +1,44 @@ +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: python-app-hpa + namespace: cloudlab-apps + labels: + app: python-app +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: python-app + minReplicas: 2 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + behavior: + scaleDown: + stabilizationWindowSeconds: 300 + policies: + - type: Percent + value: 50 + periodSeconds: 60 + scaleUp: + stabilizationWindowSeconds: 0 + policies: + - type: Percent + value: 100 + periodSeconds: 30 + - type: Pods + value: 2 + periodSeconds: 30 + selectPolicy: Max diff --git a/k8s/apps/python-app/service.yaml b/k8s/apps/python-app/service.yaml new file mode 100644 index 0000000..81f395b --- /dev/null +++ b/k8s/apps/python-app/service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + name: python-app + namespace: cloudlab-apps + labels: + app: python-app + tier: backend +spec: + type: ClusterIP + selector: + app: python-app + ports: + - name: http + port: 5000 + targetPort: http + protocol: TCP + sessionAffinity: None diff --git a/k8s/base/configmaps/nginx-config.yaml b/k8s/base/configmaps/nginx-config.yaml new file mode 100644 index 0000000..46b8f45 --- /dev/null +++ b/k8s/base/configmaps/nginx-config.yaml @@ -0,0 +1,103 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: nginx-config + namespace: cloudlab-apps +data: + nginx.conf: | + user nginx; + worker_processes auto; + error_log /var/log/nginx/error.log warn; + pid /var/run/nginx.pid; + + events { + worker_connections 1024; + } + + http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 65; + types_hash_max_size 2048; + + # Security headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_proxied any; + gzip_comp_level 6; + gzip_types text/plain text/css text/xml text/javascript + application/json application/javascript application/xml+rss + application/rss+xml font/truetype font/opentype + application/vnd.ms-fontobject image/svg+xml; + + # Upstream untuk Node.js app + upstream nodejs_backend { + server nodejs-app:3001; + } + + # Upstream untuk Python app + upstream python_backend { + server python-app:5000; + } + + # HTTP server - redirect ke HTTPS + server { + listen 80; + server_name _; + return 301 https://$host$request_uri; + } + + # HTTPS server + server { + listen 443 ssl http2; + server_name _; + + ssl_certificate /etc/nginx/ssl/tls.crt; + ssl_certificate_key /etc/nginx/ssl/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers HIGH:!aNULL:!MD5; + ssl_prefer_server_ciphers on; + + # Node.js app - root path + location / { + proxy_pass http://nodejs_backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Python API + location /api { + proxy_pass http://python_backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Health check endpoint + location /nginx_status { + stub_status on; + access_log off; + allow 127.0.0.1; + allow 10.0.0.0/8; + deny all; + } + } + } diff --git a/k8s/base/configmaps/prometheus-config.yaml b/k8s/base/configmaps/prometheus-config.yaml new file mode 100644 index 0000000..c7a26d7 --- /dev/null +++ b/k8s/base/configmaps/prometheus-config.yaml @@ -0,0 +1,149 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: prometheus-config + namespace: cloudlab-monitoring +data: + prometheus.yml: | + global: + scrape_interval: 15s + evaluation_interval: 15s + external_labels: + cluster: 'cloudlab' + environment: 'production' + + # Alertmanager configuration + alerting: + alertmanagers: + - static_configs: + - targets: [] + # - alertmanager:9093 + + # Load rules once and periodically evaluate them + rule_files: + - /etc/prometheus/alerts.yml + + # Scrape configurations + scrape_configs: + # Prometheus self-monitoring + - job_name: 'prometheus' + static_configs: + - targets: ['localhost:9090'] + + # Kubernetes API server + - job_name: 'kubernetes-apiservers' + kubernetes_sd_configs: + - role: endpoints + scheme: https + tls_config: + ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token + relabel_configs: + - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name] + action: keep + regex: default;kubernetes;https + + # Kubernetes nodes + - job_name: 'kubernetes-nodes' + kubernetes_sd_configs: + - role: node + scheme: https + tls_config: + ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token + relabel_configs: + - action: labelmap + regex: __meta_kubernetes_node_label_(.+) + + # Kubernetes pods + - job_name: 'kubernetes-pods' + kubernetes_sd_configs: + - role: pod + relabel_configs: + - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] + action: keep + regex: true + - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path] + action: replace + target_label: __metrics_path__ + regex: (.+) + - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] + action: replace + regex: ([^:]+)(?::\d+)?;(\d+) + replacement: $1:$2 + target_label: __address__ + - action: labelmap + regex: __meta_kubernetes_pod_label_(.+) + - source_labels: [__meta_kubernetes_namespace] + action: replace + target_label: kubernetes_namespace + - source_labels: [__meta_kubernetes_pod_name] + action: replace + target_label: kubernetes_pod_name + + # Node.js application + - job_name: 'nodejs-app' + static_configs: + - targets: ['nodejs-app.cloudlab-apps.svc.cluster.local:3001'] + metrics_path: /metrics + + # Python application + - job_name: 'python-app' + static_configs: + - targets: ['python-app.cloudlab-apps.svc.cluster.local:5000'] + metrics_path: /metrics + + alerts.yml: | + groups: + - name: cloudlab_alerts + interval: 30s + rules: + # Service down alerts + - alert: ServiceDown + expr: up == 0 + for: 1m + labels: + severity: critical + annotations: + summary: "Service {{ $labels.job }} is down" + description: "{{ $labels.job }} has been down for more than 1 minute." + + # High CPU usage + - alert: HighCPUUsage + expr: rate(process_cpu_seconds_total[5m]) > 0.8 + for: 5m + labels: + severity: warning + annotations: + summary: "High CPU usage on {{ $labels.job }}" + description: "{{ $labels.job }} CPU usage is above 80% for 5 minutes." + + # High memory usage + - alert: HighMemoryUsage + expr: process_resident_memory_bytes / 1024 / 1024 > 500 + for: 5m + labels: + severity: warning + annotations: + summary: "High memory usage on {{ $labels.job }}" + description: "{{ $labels.job }} is using more than 500MB of memory." + + # HTTP error rate + - alert: HighErrorRate + expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.05 + for: 5m + labels: + severity: critical + annotations: + summary: "High error rate on {{ $labels.job }}" + description: "{{ $labels.job }} has error rate above 5% for 5 minutes." + + # Pod restart alerts + - alert: PodRestartingTooOften + expr: rate(kube_pod_container_status_restarts_total[15m]) > 0 + for: 5m + labels: + severity: warning + annotations: + summary: "Pod {{ $labels.pod }} is restarting frequently" + description: "Pod {{ $labels.pod }} in namespace {{ $labels.namespace }} has restarted {{ $value }} times in the last 15 minutes." diff --git a/k8s/base/namespace.yaml b/k8s/base/namespace.yaml new file mode 100644 index 0000000..ddf973c --- /dev/null +++ b/k8s/base/namespace.yaml @@ -0,0 +1,16 @@ +--- +apiVersion: v1 +kind: Namespace +metadata: + name: cloudlab-apps + labels: + name: cloudlab-apps + environment: production +--- +apiVersion: v1 +kind: Namespace +metadata: + name: cloudlab-monitoring + labels: + name: cloudlab-monitoring + environment: production diff --git a/k8s/base/secrets/ssl-certs.yaml b/k8s/base/secrets/ssl-certs.yaml new file mode 100644 index 0000000..aa05694 --- /dev/null +++ b/k8s/base/secrets/ssl-certs.yaml @@ -0,0 +1,35 @@ +--- +# NOTE: Untuk production, gunakan cert-manager untuk auto-generate certificates +# Atau gunakan existing certificates dengan command: +# kubectl create secret tls cloudlab-tls --cert=path/to/tls.crt --key=path/to/tls.key -n cloudlab-apps + +apiVersion: v1 +kind: Secret +metadata: + name: cloudlab-tls + namespace: cloudlab-apps +type: kubernetes.io/tls +data: + # Self-signed certificate untuk development + # Generate dengan: + # openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + # -keyout tls.key -out tls.crt \ + # -subj "/C=ID/ST=Jakarta/L=Jakarta/O=CloudLab/OU=Dev/CN=cloudlab.local" + # + # Kemudian encode ke base64: + # cat tls.crt | base64 -w 0 + # cat tls.key | base64 -w 0 + # + # PLACEHOLDER - Replace dengan actual certificates + tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCi0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K + tls.key: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K +--- +apiVersion: v1 +kind: Secret +metadata: + name: grafana-admin + namespace: cloudlab-monitoring +type: Opaque +stringData: + admin-user: admin + admin-password: admin123 diff --git a/k8s/ingress/cert-manager.yaml b/k8s/ingress/cert-manager.yaml new file mode 100644 index 0000000..aedac63 --- /dev/null +++ b/k8s/ingress/cert-manager.yaml @@ -0,0 +1,44 @@ +# Cert-Manager ClusterIssuer untuk Let's Encrypt +# Install cert-manager terlebih dahulu: +# kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml + +--- +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-staging +spec: + acme: + # Staging server untuk testing + server: https://acme-staging-v02.api.letsencrypt.org/directory + email: admin@cloudlab.local # Ganti dengan email yang valid + privateKeySecretRef: + name: letsencrypt-staging + solvers: + - http01: + ingress: + class: nginx +--- +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-prod +spec: + acme: + # Production server + server: https://acme-v02.api.letsencrypt.org/directory + email: admin@cloudlab.local # Ganti dengan email yang valid + privateKeySecretRef: + name: letsencrypt-prod + solvers: + - http01: + ingress: + class: nginx +--- +# Self-signed issuer untuk development +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: selfsigned-issuer +spec: + selfSigned: {} diff --git a/k8s/ingress/ingress.yaml b/k8s/ingress/ingress.yaml new file mode 100644 index 0000000..6846f38 --- /dev/null +++ b/k8s/ingress/ingress.yaml @@ -0,0 +1,96 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: cloudlab-ingress + namespace: cloudlab-apps + annotations: + nginx.ingress.kubernetes.io/rewrite-target: / + nginx.ingress.kubernetes.io/ssl-redirect: "true" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + cert-manager.io/cluster-issuer: "letsencrypt-prod" # Jika menggunakan cert-manager +spec: + ingressClassName: nginx + tls: + - hosts: + - cloudlab.local + - "*.cloudlab.local" + secretName: cloudlab-tls + rules: + # Main application + - host: cloudlab.local + http: + paths: + - path: /api + pathType: Prefix + backend: + service: + name: python-app + port: + number: 5000 + - path: / + pathType: Prefix + backend: + service: + name: nodejs-app + port: + number: 3001 + # Grafana subdomain + - host: grafana.cloudlab.local + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: grafana + port: + number: 3000 + # Prometheus subdomain (optional, untuk debugging) + - host: prometheus.cloudlab.local + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: prometheus + port: + number: 9090 +--- +# Ingress untuk monitoring namespace +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: monitoring-ingress + namespace: cloudlab-monitoring + annotations: + nginx.ingress.kubernetes.io/rewrite-target: / + nginx.ingress.kubernetes.io/ssl-redirect: "true" +spec: + ingressClassName: nginx + tls: + - hosts: + - grafana.cloudlab.local + - prometheus.cloudlab.local + secretName: cloudlab-tls + rules: + - host: grafana.cloudlab.local + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: grafana + port: + number: 3000 + - host: prometheus.cloudlab.local + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: prometheus + port: + number: 9090 diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml new file mode 100644 index 0000000..f3de1e1 --- /dev/null +++ b/k8s/kustomization.yaml @@ -0,0 +1,58 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +namespace: cloudlab-apps + +resources: + # Base resources + - base/namespace.yaml + - base/configmaps/nginx-config.yaml + - base/configmaps/prometheus-config.yaml + - base/secrets/ssl-certs.yaml + + # Applications + - apps/nodejs-app/deployment.yaml + - apps/nodejs-app/service.yaml + - apps/nodejs-app/hpa.yaml + - apps/python-app/deployment.yaml + - apps/python-app/service.yaml + - apps/python-app/hpa.yaml + + # Monitoring + - monitoring/prometheus/statefulset.yaml + - monitoring/prometheus/service.yaml + - monitoring/grafana/deployment.yaml + - monitoring/grafana/service.yaml + - monitoring/grafana/pvc.yaml + - monitoring/grafana/datasources.yaml + - monitoring/grafana/dashboards-config.yaml + - monitoring/grafana/dashboards.yaml + + # Ingress + - ingress/ingress.yaml + # - ingress/cert-manager.yaml # Uncomment jika cert-manager sudah installed + +# Common labels untuk semua resources +commonLabels: + app.kubernetes.io/name: cloudlab + app.kubernetes.io/managed-by: kustomize + +# Images - update dengan registry dan tag yang sesuai +images: + - name: cloudlab-nodejs-app + newName: cloudlab-nodejs-app + newTag: latest + - name: cloudlab-python-app + newName: cloudlab-python-app + newTag: latest +# ConfigMap generator (opsional) +# configMapGenerator: +# - name: app-config +# literals: +# - ENV=production + +# Secret generator (opsional) +# secretGenerator: +# - name: app-secrets +# literals: +# - API_KEY=your-api-key diff --git a/k8s/monitoring/grafana/dashboards-config.yaml b/k8s/monitoring/grafana/dashboards-config.yaml new file mode 100644 index 0000000..677cfb1 --- /dev/null +++ b/k8s/monitoring/grafana/dashboards-config.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: grafana-dashboards-config + namespace: cloudlab-monitoring +data: + dashboards.yml: | + apiVersion: 1 + providers: + - name: 'CloudLab Dashboards' + orgId: 1 + folder: 'CloudLab' + type: file + disableDeletion: false + updateIntervalSeconds: 10 + allowUiUpdates: true + options: + path: /var/lib/grafana/dashboards diff --git a/k8s/monitoring/grafana/dashboards.yaml b/k8s/monitoring/grafana/dashboards.yaml new file mode 100644 index 0000000..8c10fc4 --- /dev/null +++ b/k8s/monitoring/grafana/dashboards.yaml @@ -0,0 +1,21 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: grafana-dashboards + namespace: cloudlab-monitoring +data: + # NOTE: Dashboard JSON files dari monitoring/grafana/dashboards/ + # dapat di-copy ke sini atau di-mount dari external ConfigMap + # Untuk simplicity, user dapat import dashboards secara manual + # atau menggunakan Grafana sidecar untuk auto-load dari ConfigMaps + cloudlab-overview.json: | + { + "dashboard": { + "title": "CloudLab Overview", + "tags": ["cloudlab"], + "timezone": "browser", + "panels": [], + "schemaVersion": 16, + "version": 0 + } + } diff --git a/k8s/monitoring/grafana/datasources.yaml b/k8s/monitoring/grafana/datasources.yaml new file mode 100644 index 0000000..f7b60d2 --- /dev/null +++ b/k8s/monitoring/grafana/datasources.yaml @@ -0,0 +1,17 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: grafana-datasources + namespace: cloudlab-monitoring +data: + datasources.yml: | + apiVersion: 1 + datasources: + - name: Prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: true + jsonData: + timeInterval: 15s diff --git a/k8s/monitoring/grafana/deployment.yaml b/k8s/monitoring/grafana/deployment.yaml new file mode 100644 index 0000000..18fe3ad --- /dev/null +++ b/k8s/monitoring/grafana/deployment.yaml @@ -0,0 +1,82 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: grafana + namespace: cloudlab-monitoring + labels: + app: grafana +spec: + replicas: 1 + selector: + matchLabels: + app: grafana + template: + metadata: + labels: + app: grafana + spec: + containers: + - name: grafana + image: grafana/grafana:latest + ports: + - name: web + containerPort: 3000 + protocol: TCP + env: + - name: GF_SECURITY_ADMIN_USER + valueFrom: + secretKeyRef: + name: grafana-admin + key: admin-user + - name: GF_SECURITY_ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: grafana-admin + key: admin-password + - name: GF_USERS_ALLOW_SIGN_UP + value: "false" + - name: GF_SERVER_ROOT_URL + value: "http://localhost:3000" + - name: GF_INSTALL_PLUGINS + value: "" + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 500m + memory: 1Gi + volumeMounts: + - name: storage + mountPath: /var/lib/grafana + - name: datasources + mountPath: /etc/grafana/provisioning/datasources + - name: dashboards-config + mountPath: /etc/grafana/provisioning/dashboards + - name: dashboards + mountPath: /var/lib/grafana/dashboards + livenessProbe: + httpGet: + path: /api/health + port: web + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /api/health + port: web + initialDelaySeconds: 10 + periodSeconds: 5 + volumes: + - name: storage + persistentVolumeClaim: + claimName: grafana-storage + - name: datasources + configMap: + name: grafana-datasources + - name: dashboards-config + configMap: + name: grafana-dashboards-config + - name: dashboards + configMap: + name: grafana-dashboards diff --git a/k8s/monitoring/grafana/pvc.yaml b/k8s/monitoring/grafana/pvc.yaml new file mode 100644 index 0000000..1db0965 --- /dev/null +++ b/k8s/monitoring/grafana/pvc.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: grafana-storage + namespace: cloudlab-monitoring + labels: + app: grafana +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 5Gi diff --git a/k8s/monitoring/grafana/service.yaml b/k8s/monitoring/grafana/service.yaml new file mode 100644 index 0000000..ee26203 --- /dev/null +++ b/k8s/monitoring/grafana/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + name: grafana + namespace: cloudlab-monitoring + labels: + app: grafana +spec: + type: ClusterIP + selector: + app: grafana + ports: + - name: web + port: 3000 + targetPort: web + protocol: TCP diff --git a/k8s/monitoring/prometheus/service.yaml b/k8s/monitoring/prometheus/service.yaml new file mode 100644 index 0000000..cf25872 --- /dev/null +++ b/k8s/monitoring/prometheus/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + name: prometheus + namespace: cloudlab-monitoring + labels: + app: prometheus +spec: + type: ClusterIP + selector: + app: prometheus + ports: + - name: web + port: 9090 + targetPort: web + protocol: TCP diff --git a/k8s/monitoring/prometheus/statefulset.yaml b/k8s/monitoring/prometheus/statefulset.yaml new file mode 100644 index 0000000..529a36c --- /dev/null +++ b/k8s/monitoring/prometheus/statefulset.yaml @@ -0,0 +1,109 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: prometheus + namespace: cloudlab-monitoring + labels: + app: prometheus +spec: + serviceName: prometheus + replicas: 1 + selector: + matchLabels: + app: prometheus + template: + metadata: + labels: + app: prometheus + spec: + serviceAccountName: prometheus + containers: + - name: prometheus + image: prom/prometheus:latest + args: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + - "--web.console.libraries=/usr/share/prometheus/console_libraries" + - "--web.console.templates=/usr/share/prometheus/consoles" + - "--web.enable-lifecycle" + - "--storage.tsdb.retention.time=15d" + ports: + - name: web + containerPort: 9090 + protocol: TCP + resources: + requests: + cpu: 200m + memory: 512Mi + limits: + cpu: 1000m + memory: 2Gi + volumeMounts: + - name: config + mountPath: /etc/prometheus + - name: storage + mountPath: /prometheus + livenessProbe: + httpGet: + path: /-/healthy + port: web + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /-/ready + port: web + initialDelaySeconds: 5 + periodSeconds: 5 + volumes: + - name: config + configMap: + name: prometheus-config + volumeClaimTemplates: + - metadata: + name: storage + spec: + accessModes: ["ReadWriteOnce"] + resources: + requests: + storage: 10Gi +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: prometheus + namespace: cloudlab-monitoring +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: prometheus +rules: + - apiGroups: [""] + resources: + - nodes + - nodes/proxy + - services + - endpoints + - pods + verbs: ["get", "list", "watch"] + - apiGroups: + - extensions + resources: + - ingresses + verbs: ["get", "list", "watch"] + - nonResourceURLs: ["/metrics"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: prometheus +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: prometheus +subjects: + - kind: ServiceAccount + name: prometheus + namespace: cloudlab-monitoring diff --git a/k8s/scripts/cleanup.sh b/k8s/scripts/cleanup.sh new file mode 100755 index 0000000..ad4fef5 --- /dev/null +++ b/k8s/scripts/cleanup.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +# CloudLab Kubernetes Cleanup Script +# This script removes all CloudLab resources from Kubernetes + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Functions +print_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +print_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +cleanup_resources() { + print_info "Cleaning up CloudLab resources..." + + # Delete using kustomization + if [ -f "k8s/kustomization.yaml" ]; then + print_info "Deleting resources via kustomization..." + kubectl delete -k k8s/ --ignore-not-found=true + fi + + # Delete namespaces (this will cascade delete all resources) + print_info "Deleting namespaces..." + kubectl delete namespace cloudlab-apps --ignore-not-found=true + kubectl delete namespace cloudlab-monitoring --ignore-not-found=true + + print_info "Cleanup completed!" +} + +show_remaining() { + print_info "Checking for remaining resources..." + + # Check namespaces + if kubectl get namespace cloudlab-apps &> /dev/null; then + print_warn "Namespace cloudlab-apps still exists" + fi + + if kubectl get namespace cloudlab-monitoring &> /dev/null; then + print_warn "Namespace cloudlab-monitoring still exists" + fi + + # Check PVs + PVS=$(kubectl get pv -o json | jq -r '.items[] | select(.spec.claimRef.namespace | contains("cloudlab")) | .metadata.name' 2>/dev/null || echo "") + if [ -n "$PVS" ]; then + print_warn "Found PersistentVolumes that may need manual cleanup:" + echo "$PVS" + fi +} + +# Main execution +main() { + print_warn "This will delete ALL CloudLab resources from Kubernetes!" + print_warn "This action cannot be undone." + echo "" + + read -p "Are you sure you want to continue? (yes/no) " -r + echo + + if [[ $REPLY == "yes" ]]; then + cleanup_resources + + # Wait a bit for resources to be deleted + print_info "Waiting for resources to be deleted..." + sleep 5 + + show_remaining + print_info "Cleanup script completed!" + else + print_info "Cleanup cancelled." + fi +} + +# Run main +main diff --git a/k8s/scripts/deploy.sh b/k8s/scripts/deploy.sh new file mode 100755 index 0000000..d00b754 --- /dev/null +++ b/k8s/scripts/deploy.sh @@ -0,0 +1,203 @@ +#!/bin/bash + +# CloudLab Kubernetes Deployment Script +# This script automates the deployment of CloudLab to Kubernetes + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Functions +print_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +print_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +check_prerequisites() { + print_info "Checking prerequisites..." + + # Check kubectl + if ! command -v kubectl &> /dev/null; then + print_error "kubectl not found. Please install kubectl first." + exit 1 + fi + + # Check cluster connectivity + if ! kubectl cluster-info &> /dev/null; then + print_error "Cannot connect to Kubernetes cluster. Please check your kubeconfig." + exit 1 + fi + + print_info "Prerequisites check passed!" +} + +build_images() { + print_info "Building Docker images..." + + cd apps/demo-apps/nodejs-app + docker build -t cloudlab-nodejs-app:latest . + print_info "Built cloudlab-nodejs-app:latest" + + cd ../python-app + docker build -t cloudlab-python-app:latest . + print_info "Built cloudlab-python-app:latest" + + cd ../../.. +} + +load_images_minikube() { + print_info "Loading images to Minikube..." + + if command -v minikube &> /dev/null; then + minikube image load cloudlab-nodejs-app:latest + minikube image load cloudlab-python-app:latest + print_info "Images loaded to Minikube" + else + print_warn "Minikube not found, skipping image load" + fi +} + +generate_ssl_certs() { + print_info "Generating SSL certificates..." + + # Generate self-signed certificate + openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout /tmp/cloudlab-tls.key \ + -out /tmp/cloudlab-tls.crt \ + -subj "/C=ID/ST=Jakarta/L=Jakarta/O=CloudLab/OU=Dev/CN=cloudlab.local" \ + 2>/dev/null + + # Encode to base64 + TLS_CRT=$(cat /tmp/cloudlab-tls.crt | base64 -w 0) + TLS_KEY=$(cat /tmp/cloudlab-tls.key | base64 -w 0) + + # Update secret file + sed -i "s|tls.crt:.*|tls.crt: $TLS_CRT|" k8s/base/secrets/ssl-certs.yaml + sed -i "s|tls.key:.*|tls.key: $TLS_KEY|" k8s/base/secrets/ssl-certs.yaml + + # Cleanup + rm -f /tmp/cloudlab-tls.key /tmp/cloudlab-tls.crt + + print_info "SSL certificates generated and updated" +} + +deploy_kubernetes() { + print_info "Deploying to Kubernetes..." + + # Apply kustomization + kubectl apply -k k8s/ + + print_info "Kubernetes resources created" +} + +wait_for_rollout() { + print_info "Waiting for deployments to be ready..." + + # Wait for apps + kubectl rollout status deployment/nodejs-app -n cloudlab-apps --timeout=5m + kubectl rollout status deployment/python-app -n cloudlab-apps --timeout=5m + + # Wait for monitoring + kubectl rollout status deployment/grafana -n cloudlab-monitoring --timeout=5m + kubectl rollout status statefulset/prometheus -n cloudlab-monitoring --timeout=5m + + print_info "All deployments are ready!" +} + +show_status() { + print_info "Deployment Status:" + echo "" + + print_info "Pods in cloudlab-apps:" + kubectl get pods -n cloudlab-apps + echo "" + + print_info "Pods in cloudlab-monitoring:" + kubectl get pods -n cloudlab-monitoring + echo "" + + print_info "Services in cloudlab-apps:" + kubectl get svc -n cloudlab-apps + echo "" + + print_info "Services in cloudlab-monitoring:" + kubectl get svc -n cloudlab-monitoring + echo "" + + print_info "Ingress:" + kubectl get ingress -A + echo "" +} + +show_access_info() { + print_info "Access Information:" + echo "" + echo "Port Forwarding Commands:" + echo " kubectl port-forward svc/nodejs-app 3001:3001 -n cloudlab-apps" + echo " kubectl port-forward svc/python-app 5000:5000 -n cloudlab-apps" + echo " kubectl port-forward svc/grafana 3000:3000 -n cloudlab-monitoring" + echo " kubectl port-forward svc/prometheus 9090:9090 -n cloudlab-monitoring" + echo "" + + if command -v minikube &> /dev/null; then + MINIKUBE_IP=$(minikube ip 2>/dev/null || echo "N/A") + echo "Minikube IP: $MINIKUBE_IP" + echo "" + echo "Add to /etc/hosts:" + echo " $MINIKUBE_IP cloudlab.local grafana.cloudlab.local prometheus.cloudlab.local" + echo "" + echo "Then access:" + echo " https://cloudlab.local" + echo " https://grafana.cloudlab.local (admin/admin123)" + echo " https://prometheus.cloudlab.local" + fi +} + +# Main execution +main() { + print_info "Starting CloudLab Kubernetes Deployment" + echo "" + + check_prerequisites + + # Ask for confirmation + read -p "Do you want to build Docker images? (y/n) " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + build_images + load_images_minikube + fi + + # Generate SSL certs + read -p "Do you want to generate new SSL certificates? (y/n) " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + generate_ssl_certs + fi + + # Deploy + read -p "Do you want to deploy to Kubernetes? (y/n) " -n 1 -r + echo + if [[ $REPLY =~ ^[Yy]$ ]]; then + deploy_kubernetes + wait_for_rollout + show_status + show_access_info + fi + + print_info "Deployment script completed!" +} + +# Run main +main diff --git a/monitoring/alerts.yml b/monitoring/alerts.yml index c0f4cc2..614fcd4 100644 --- a/monitoring/alerts.yml +++ b/monitoring/alerts.yml @@ -41,3 +41,22 @@ groups: annotations: summary: "High error rate on {{ $labels.job }}" description: "{{ $labels.job }} has more than 5% error rate for 5 minutes." + + # -- Business Alerts -- + - alert: HighDBLatency + expr: rate(db_query_duration_seconds_sum[1m]) / rate(db_query_duration_seconds_count[1m]) > 0.5 + for: 1m + labels: + severity: warning + annotations: + summary: "Slow Database Queries" + description: "Average DB query duration is > 500ms" + + - alert: LowStockWarning + expr: inventory_stock_count < 5 + for: 1m + labels: + severity: critical + annotations: + summary: "Low Stock for Product {{ $labels.product_id }}" + description: "Inventory count is below 5 items!" diff --git a/monitoring/grafana/dashboards/business_dashboard.json b/monitoring/grafana/dashboards/business_dashboard.json new file mode 100644 index 0000000..25c4b76 --- /dev/null +++ b/monitoring/grafana/dashboards/business_dashboard.json @@ -0,0 +1,359 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": "-- Grafana --", + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": null, + "links": [], + "liveNow": false, + "panels": [ + { + "datasource": "Prometheus", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "expr": "active_sessions_total", + "interval": "", + "legendFormat": "", + "refId": "A" + } + ], + "title": "Active Sessions (Node.js)", + "type": "timeseries" + }, + { + "datasource": "Prometheus", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "expr": "inventory_stock_count", + "interval": "", + "legendFormat": "Product {{product_id}}", + "refId": "A" + } + ], + "title": "Product Stock Levels (Python)", + "type": "timeseries" + }, + { + "datasource": "Prometheus", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 8 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "expr": "rate(db_query_duration_seconds_sum[1m]) / rate(db_query_duration_seconds_count[1m])", + "interval": "", + "legendFormat": "Avg Latency", + "refId": "A" + } + ], + "title": "Simulated DB Latency", + "type": "timeseries" + }, + { + "datasource": "Prometheus", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 8 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "targets": [ + { + "expr": "histogram_quantile(0.95, rate(checkout_processing_seconds_bucket[5m]))", + "interval": "", + "legendFormat": "p95 checkout time", + "refId": "A" + } + ], + "title": "Checkout Processing Time (p95)", + "type": "timeseries" + } + ], + "refresh": "5s", + "schemaVersion": 27, + "style": "dark", + "tags": [], + "templating": { + "list": [] + }, + "time": { + "from": "now-15m", + "to": "now" + }, + "timepicker": {}, + "timezone": "", + "title": "CloudLab Business Dashboard", + "uid": "bus-metrics-01", + "version": 1 +} \ No newline at end of file diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100755 index 0000000..cd0bd89 --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e + +ACTION=$1 +ENV=$2 + +if [ -z "$ACTION" ]; then + echo "Usage: ./deploy.sh [apply|rollback] [env]" + exit 1 +fi + +echo "πŸš€ Starting deployment action: $ACTION..." + +if [ "$ACTION" == "apply" ]; then + echo "Applying manifests to cluster..." + # In real world: kubectl apply -f k8s/overlays/$ENV + kubectl apply -f k8s/apps/nodejs-app/ + kubectl apply -f k8s/apps/python-app/ + echo "βœ… Apply complete." +elif [ "$ACTION" == "rollback" ]; then + echo "Rolling back..." + kubectl rollout undo deployment/nodejs-app + kubectl rollout undo deployment/python-app + echo "βœ… Rollback complete." +else + echo "Unknown action: $ACTION" + exit 1 +fi