### Install Dependencies and Start Development Server (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md This snippet demonstrates how to install project dependencies using npm and start the development server for the web dashboard. Ensure Node.js 18+ and npm are installed. ```bash cd services/web-dashboard npm install npm start ``` -------------------------------- ### Clone and Set Up Project with Docker Compose Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Clones the Android Container Platform repository and sets up the development environment using Docker Compose. This is a quick setup for development purposes. ```bash git clone https://github.com/your-org/android-container-platform.git cd android-container-platform make setup make dev ``` -------------------------------- ### Clone Repository and Setup Development Environment Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md This snippet demonstrates how to clone the project repository and set up the development environment using make commands. It requires Git and assumes the user has a Linux host with Docker and Docker Compose installed. ```bash git clone https://github.com/your-org/android-container-platform.git cd android-container-platform make setup make dev curl http://localhost:3000/health ``` -------------------------------- ### ELK Stack Deployment using Helm Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This bash script demonstrates deploying the Elastic ELK stack (Elasticsearch, Kibana, Filebeat) using Helm charts. It adds the Elastic Helm repository and installs each component into the 'logging' namespace. This requires Helm to be installed and configured. ```bash helm repo add elastic https://helm.elastic.co helm install elasticsearch elastic/elasticsearch -n logging --create-namespace helm install kibana elastic/kibana -n logging helm install filebeat elastic/filebeat -n logging ``` -------------------------------- ### Kubernetes PostgreSQL Deployment and Initialization Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Deploys a PostgreSQL database instance within a Kubernetes cluster and initializes it. This involves applying the PostgreSQL manifest, waiting for the pod to be ready, and then executing the initialization script. Requires kubectl. ```bash kubectl apply -f k8s/postgres.yaml kubectl wait --for=condition=ready pod -l app=postgres -n android-platform --timeout=300s kubectl exec -it deployment/postgres -n android-platform -- \ psql -U acp_user -d android_platform -f /docker-entrypoint-initdb.d/init.sql ``` -------------------------------- ### npm Scripts for Development and Build Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Lists the available npm scripts for managing the development workflow. This includes starting the development server, building the production bundle, running tests, linting code with ESLint, and formatting code with Prettier. ```bash npm start # Start development server npm run build # Build production bundle npm test # Run test suite npm run lint # Run ESLint npm run lint:fix # Fix ESLint issues npm run format # Format code with Prettier ``` -------------------------------- ### Kubernetes Namespace and RBAC Setup Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Sets up a dedicated namespace for the Android Container Platform and configures Role-Based Access Control (RBAC) within Kubernetes. This ensures proper isolation and permissions for the deployed services. Requires kubectl. ```bash kubectl create namespace android-platform kubectl label namespace android-platform name=android-platform kubectl apply -f k8s/rbac.yaml ``` -------------------------------- ### Deploy Monitoring Stack with kubectl Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Applies the Kubernetes manifest for the monitoring stack. This command is used to deploy monitoring tools such as Prometheus and Grafana to the cluster. It requires a 'monitoring.yaml' file in the 'k8s' directory. ```bash kubectl apply -f k8s/monitoring.yaml ``` -------------------------------- ### Production Docker Compose Configuration and Deployment Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Configures and deploys the Android Container Platform using Docker Compose for production. This involves creating a production-specific compose file, setting environment variables, and starting the services. Requires Docker Compose v2.0+. ```yaml # docker-compose.prod.yml version: '3.8' services: postgres: environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data restart: unless-stopped deploy: resources: limits: cpus: '2.0' memory: 4G reservations: cpus: '1.0' memory: 2G redis: restart: unless-stopped deploy: resources: limits: cpus: '0.5' memory: 1G api-gateway: environment: JWT_SECRET: ${JWT_SECRET} DATABASE_URL: ${DATABASE_URL} restart: unless-stopped deploy: replicas: 3 resources: limits: cpus: '1.0' memory: 1G ``` ```bash # Create .env file cat > .env << EOF POSTGRES_PASSWORD=$(openssl rand -base64 32) JWT_SECRET=$(openssl rand -base64 32) DATABASE_URL=postgresql://acp_user:${POSTGRES_PASSWORD}@postgres:5432/android_platform ENVIRONMENT=production EOF docker-compose -f docker-compose.prod.yml up -d docker-compose -f docker-compose.prod.yml ps curl http://localhost:3000/health ``` -------------------------------- ### Start Route Simulation API Reference Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Initiates a route simulation on a specified Android instance. It takes a list of waypoints (latitude, longitude pairs) and a speed profile for different modes of transport (e.g., walking, driving). This allows testing navigation and route-dependent features. ```json { "waypoints": [ [40.7128, -74.0060], [40.7589, -73.9851], [40.7614, -73.9776] ], "speed_profile": { "walking": 5.0, "driving": 50.0 } } ``` -------------------------------- ### Authentication Response Example Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Example response after a successful authentication request, providing the JWT access token and token type. This token must be included in the `Authorization` header for subsequent authenticated API calls. ```json { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "token_type": "bearer" } ``` -------------------------------- ### Full System Restore Sequence (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This sequence of commands outlines the steps for a full system restore in a Kubernetes environment. It involves reapplying persistent volume definitions, then reapplying the application's Kubernetes manifests, and finally running integrity and performance tests to verify the restoration. This is a critical part of the disaster recovery plan. ```bash # Restore persistent volumes kubectl apply -f backup/persistent-volumes.yaml # Restore application state kubectl apply -f k8s/ # Verify restoration ./scripts/test-integrity.sh ./scripts/test-performance.sh ``` -------------------------------- ### Prometheus Custom Recording Rules Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This YAML file defines custom recording rules for Prometheus to precompute aggregated metrics. These rules calculate rates for instance creation/failures, API request duration percentiles, and resource utilization. The rules depend on existing metrics exposed by the platform services. ```yaml # monitoring/recording_rules.yml groups: - name: android_platform_recording_rules interval: 30s rules: - record: android_platform:instance_creation_rate expr: rate(android_instances_created_total[5m]) - record: android_platform:instance_failure_rate expr: rate(android_instances_failed_total[5m]) - record: android_platform:api_request_duration_p99 expr: histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) - record: android_platform:resource_utilization expr: | ( android_platform:total_cpu_usage / android_platform:total_cpu_limit ) * 100 ``` -------------------------------- ### Kubernetes Redis Deployment and Verification Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Deploys a Redis cache instance within a Kubernetes cluster and verifies its readiness. This ensures that the cache service is available for the application. Requires kubectl. ```bash kubectl apply -f k8s/redis.yaml kubectl wait --for=condition=ready pod -l app=redis -n android-platform --timeout=120s ``` -------------------------------- ### Grafana Dashboard for Platform Overview Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This JSON defines a Grafana dashboard for visualizing the 'Android Platform Overview'. It includes panels for 'Active Instances' using a stat panel and 'API Request Rate' using a graph panel. The dashboard relies on Prometheus as a data source and specific metrics like `android_instances_active_total` and `http_requests_total`. ```json { "dashboard": { "title": "Android Platform Overview", "panels": [ { "title": "Active Instances", "type": "stat", "targets": [ { "expr": "android_instances_active_total", "legendFormat": "Active Instances" } ] }, { "title": "API Request Rate", "type": "graph", "targets": [ { "expr": "rate(http_requests_total[5m])", "legendFormat": "{{method}} {{endpoint}}" } ] } ] } } ``` -------------------------------- ### Kubernetes Application Services Deployment and Verification Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Deploys the core application services for the Android Container Platform in Kubernetes and verifies their deployment status and health. Includes steps for checking pods, services, and performing a health check via port-forwarding. Requires kubectl. ```bash kubectl apply -f k8s/services.yaml kubectl get pods -n android-platform -w kubectl get services -n android-platform # Port forward for testing kubectl port-forward svc/api-gateway 3000:80 -n android-platform curl http://localhost:3000/health ``` -------------------------------- ### Install External Secrets Operator Helm Chart Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Installs the External Secrets Operator using Helm. This operator synchronizes secrets from external secret management systems (like Vault, AWS Secrets Manager, etc.) into Kubernetes secrets. It adds the necessary Helm repository and performs the installation in the 'external-secrets-system' namespace. ```bash helm repo add external-secrets https://charts.external-secrets.io helm install external-secrets external-secrets/external-secrets -n external-secrets-system --create-namespace ``` -------------------------------- ### PostgreSQL Primary Region Configuration (YAML) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes custom resource defines a PostgreSQL cluster configured for replication in the primary region. It specifies 3 instances and sets PostgreSQL parameters like `wal_level`, `max_wal_senders`, and `max_replication_slots` to support replication. This setup is a prerequisite for multi-region database replication. ```yaml # Primary region apiVersion: postgresql.cnpg.io/v1 kind: Cluster metadata: name: postgres-primary spec: instances: 3 primaryUpdateStrategy: unsupervised postgresql: parameters: wal_level: replica max_wal_senders: 10 max_replication_slots: 10 ``` -------------------------------- ### Database Restoration with pg_restore (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This command demonstrates how to restore a PostgreSQL database from a compressed backup file using `pg_restore`. It executes `pg_restore` within a specified Kubernetes deployment (`postgres` in the `android-platform` namespace), targeting the `android_platform` database and using a backup file located at `/backup/latest_backup.sql.gz`. This is part of the disaster recovery process. ```bash # Restore from backup kubectl exec -it deployment/postgres -n android-platform -- \ pg_restore -h localhost -U acp_user -d android_platform /backup/latest_backup.sql.gz ``` -------------------------------- ### Container Resource Limits and Requests Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines resource allocation for a container, specifying limits and requests for CPU, memory, and ephemeral storage. This ensures predictable performance and prevents resource exhaustion. It requests 100m CPU and 256Mi memory, while limiting to 1000m CPU and 2Gi memory. ```yaml resources: limits: cpu: 1000m memory: 2Gi ephemeral-storage: 1Gi requests: cpu: 100m memory: 256Mi ephemeral-storage: 100Mi ``` -------------------------------- ### Kubernetes Resource Limits Configuration Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Defines resource requests and limits for containers within Kubernetes pods. This includes specifying memory and CPU requirements for both starting up (requests) and maximum allowed usage (limits). Proper resource management is crucial for stability and performance. ```yaml resources: requests: memory: "512Mi" cpu: "250m" limits: memory: "2Gi" cpu: "1000m" ``` -------------------------------- ### Kubernetes ConfigMap for Production Environment Variables Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines a Kubernetes ConfigMap named 'platform-config' for the 'android-platform' namespace. It holds comprehensive environment variables for database, Redis, service URLs, security settings, platform limits, monitoring, and feature flags. ```yaml # k8s/configmap-prod.yaml apiVersion: v1 kind: ConfigMap metadata: name: platform-config namespace: android-platform data: # Database Configuration DATABASE_URL: "postgresql://acp_user:$(POSTGRES_PASSWORD)@postgres:5432/android_platform" DATABASE_POOL_SIZE: "20" DATABASE_MAX_OVERFLOW: "30" # Redis Configuration REDIS_URL: "redis://redis:6379/0" REDIS_POOL_SIZE: "10" # Service URLs IDENTITY_SERVICE_URL: "http://identity-manager:8001" LOCATION_SERVICE_URL: "http://location-manager:8002" NETWORK_SERVICE_URL: "http://network-manager:8003" LIFECYCLE_SERVICE_URL: "http://lifecycle-manager:8004" # Security Configuration JWT_EXPIRATION_HOURS: "24" RATE_LIMIT_PER_HOUR: "1000" BCRYPT_ROUNDS: "12" # Platform Limits MAX_INSTANCES_PER_USER: "10" DEFAULT_INSTANCE_MEMORY: "4G" DEFAULT_INSTANCE_CPU: "2.0" # Monitoring METRICS_ENABLED: "true" LOG_LEVEL: "INFO" # Feature Flags ENABLE_DEVICE_SPOOFING: "true" ENABLE_LOCATION_INJECTION: "true" ENABLE_NETWORK_ISOLATION: "true" ``` -------------------------------- ### Backup Retention Script (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md A bash script designed to clean up old PostgreSQL backup files. It identifies `.sql.gz` files in the `/backup` directory that are older than a specified number of days (defaulting to 30) and deletes them. The script also logs its execution time and the number of days for cleanup to `/var/log/backup-cleanup.log`. ```bash #!/bin/bash # cleanup-old-backups.sh BACKUP_DIR="/backup" RETENTION_DAYS=30 find $BACKUP_DIR -name "android_platform_*.sql.gz" -mtime +$RETENTION_DAYS -delete # Log backup status echo "$(date): Cleaned up backups older than $RETENTION_DAYS days" >> /var/log/backup-cleanup.log ``` -------------------------------- ### Kubernetes Secrets and ConfigMap Deployment Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Deploys necessary secrets (like database and JWT passwords) and configuration maps for the Android Container Platform in Kubernetes. This allows for secure management of sensitive information and application settings. Requires kubectl. ```bash # Update secrets first kubectl create secret generic platform-secrets \ --from-literal=postgres-password=$(openssl rand -base64 32) \ --from-literal=jwt-secret=$(openssl rand -base64 32) \ -n android-platform kubectl apply -f k8s/configmap.yaml ``` -------------------------------- ### Configure Node Auto-Scaling with ConfigMap Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This ConfigMap configures the cluster-autoscaler settings, specifying minimum and maximum node counts, and delays for scale-down operations. It requires Kubernetes to be running and the cluster-autoscaler to be deployed in the 'kube-system' namespace. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: cluster-autoscaler-status namespace: kube-system data: cluster-autoscaler: | nodes.max: 50 nodes.min: 5 scale-down-delay-after-add: 10m scale-down-unneeded-time: 10m ``` -------------------------------- ### Kubernetes Ingress Configuration for API Gateway Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines a Kubernetes Ingress resource named 'platform-ingress' for the 'android-platform' namespace. It configures Nginx as the ingress controller and uses the 'platform-tls' secret for TLS termination for the 'api.android-platform.com' host, routing traffic to the 'api-gateway' service. ```yaml # k8s/ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: platform-ingress namespace: android-platform annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod spec: tls: - hosts: - api.android-platform.com secretName: platform-tls rules: - host: api.android-platform.com http: paths: - path: / pathType: Prefix backend: service: name: api-gateway port: number: 80 ``` -------------------------------- ### Container Security Context for Non-Root Execution Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Specifies security settings for a container. It enforces running as a non-root user (UID 1000), a specific group (GID 2000), drops all Linux capabilities, and makes the root filesystem read-only. This enhances container security by limiting potential impact. ```yaml securityContext: runAsNonRoot: true runAsUser: 1000 fsGroup: 2000 capabilities: drop: - ALL readOnlyRootFilesystem: true ``` -------------------------------- ### Generate TLS Certificates and Kubernetes Secret Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Generates self-signed TLS certificates for testing purposes using OpenSSL and creates a Kubernetes TLS secret named 'platform-tls'. This secret is used by Ingress resources to secure communication. The certificates are valid for 365 days. ```bash # Self-signed for testing openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -keyout tls.key -out tls.crt \ -subj "/CN=android-platform.local" kubectl create secret tls platform-tls \ --cert=tls.crt --key=tls.key \ -n android-platform ``` -------------------------------- ### Automated PostgreSQL Backups with CronJob (YAML) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes CronJob automates daily PostgreSQL backups. It uses a `postgres:13` image to run `pg_dump`, compresses the output with gzip, and stores it in a persistent volume. The backup process runs daily at 2 AM and requires a persistent volume claim named `backup-pvc` and a secret named `platform-secrets` for the PostgreSQL password. ```yaml apiVersion: batch/v1 kind: CronJob metadata: name: postgres-backup namespace: android-platform spec: schedule: "0 2 * * *" # Daily at 2 AM jobTemplate: spec: template: spec: containers: - name: postgres-backup image: postgres:13 command: - /bin/bash - -c - | pg_dump -h postgres -U acp_user android_platform | \ gzip > /backup/android_platform_$(date +%Y%m%d_%H%M%S).sql.gz volumeMounts: - name: backup-storage mountPath: /backup env: - name: PGPASSWORD valueFrom: secretKeyRef: name: platform-secrets key: postgres-password volumes: - name: backup-storage persistentVolumeClaim: claimName: backup-pvc restartPolicy: OnFailure ``` -------------------------------- ### Implement Multi-Zone Pod Deployment with Affinity Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This YAML snippet demonstrates how to configure pod anti-affinity to ensure pods are spread across different availability zones. It uses Kubernetes affinity and topology keys to achieve a more resilient deployment. This configuration is applied within a pod's specification. ```yaml # Ensure pods are spread across zones spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - api-gateway topologyKey: topology.kubernetes.io/zone ``` -------------------------------- ### Prometheus Configuration for Android Platform Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This YAML configuration sets up Prometheus to scrape metrics from various services within the 'android-platform' Kubernetes namespace. It includes configurations for the API gateway, PostgreSQL, Redis, and container metrics via cAdvisor. Dependencies include Kubernetes service discovery and Prometheus's ability to scrape metrics endpoints. ```yaml # monitoring/prometheus-prod.yml global: scrape_interval: 15s evaluation_interval: 15s external_labels: cluster: 'android-platform-prod' replica: '1' rule_files: - "alert_rules.yml" - "recording_rules.yml" alerting: alertmanagers: - static_configs: - targets: - alertmanager:9093 scrape_configs: # Application metrics - job_name: 'api-gateway' kubernetes_sd_configs: - role: endpoints namespaces: names: ['android-platform'] relabel_configs: - source_labels: [__meta_kubernetes_service_name] action: keep regex: api-gateway # Database metrics - job_name: 'postgres' static_configs: - targets: ['postgres-exporter:9187'] # Redis metrics - job_name: 'redis' static_configs: - targets: ['redis-exporter:9121'] # Container metrics - job_name: 'cadvisor' kubernetes_sd_configs: - role: node relabel_configs: - target_label: __address__ replacement: kubernetes.default.svc:443 - source_labels: [__meta_kubernetes_node_name] regex: (.+) target_label: __metrics_path__ replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor ``` -------------------------------- ### Kubernetes Pod Security Policy Configuration Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines a Kubernetes PodSecurityPolicy named 'platform-psp'. It enforces security best practices by disallowing privileged containers, privilege escalation, and requiring specific volume types, non-root users, and dropping all capabilities. This policy aims to enhance the security posture of pods. ```yaml # k8s/pod-security-policy.yaml apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: platform-psp spec: privileged: false allowPrivilegeEscalation: false requiredDropCapabilities: - ALL volumes: - 'configMap' - 'emptyDir' - 'projected' - 'secret' - 'downwardAPI' - 'persistentVolumeClaim' runAsUser: rule: 'MustRunAsNonRoot' seLinux: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' ``` -------------------------------- ### Access Grafana Service via Port Forwarding Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Establishes a port-forwarding connection to the Grafana service. This allows local access to the Grafana dashboard for monitoring. The command forwards local port 3001 to the Grafana service's port 80 within the 'android-platform' namespace. Default credentials are admin/admin. ```bash kubectl port-forward svc/grafana 3001:80 -n android-platform # Open http://localhost:3001 (admin/admin) ``` -------------------------------- ### Kubernetes Network Policy for Ingress and Egress Traffic Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines a Kubernetes NetworkPolicy named 'platform-network-policy' for the 'android-platform' namespace. It restricts ingress traffic to specific ports from pods within the same namespace and allows egress traffic to DNS (port 53) and to pods within the 'android-platform' namespace. ```yaml # k8s/network-policy.yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: platform-network-policy namespace: android-platform spec: podSelector: {} policyTypes: - Ingress - Egress ingress: - from: - namespaceSelector: matchLabels: name: android-platform ports: - protocol: TCP port: 8001 - protocol: TCP port: 8002 - protocol: TCP port: 8003 - protocol: TCP port: 8004 egress: - to: [] ports: - protocol: TCP port: 53 - protocol: UDP port: 53 - to: - namespaceSelector: matchLabels: name: android-platform ``` -------------------------------- ### Configure External Secrets Operator for HashiCorp Vault Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md Defines a SecretStore resource for the External Secrets Operator to connect to a HashiCorp Vault instance. It specifies the Vault server URL, API path, version, and authentication method using Kubernetes service accounts. This allows Kubernetes to fetch secrets from Vault. ```yaml apiVersion: external-secrets.io/v1beta1 kind: SecretStore metadata: name: vault-backend namespace: android-platform spec: provider: vault: server: "https://vault.company.com" path: "secret" version: "v2" auth: kubernetes: mountPath: "kubernetes" role: "android-platform" ``` -------------------------------- ### Fluent Bit Log Aggregation Configuration Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes ConfigMap defines the configuration for Fluent Bit, a lightweight log processor. It's configured to tail container logs from '/var/log/containers/*android-platform*.log', parse them using the 'cri' parser, tag them as 'android.*', and output them to an Elasticsearch instance running on 'elasticsearch:9200' with the index name 'android-platform'. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: fluent-bit-config data: fluent-bit.conf: | [SERVICE] Flush 1 Log_Level info Daemon off Parsers_File parsers.conf [INPUT] Name tail Path /var/log/containers/*android-platform*.log Parser cri Tag android.* Refresh_Interval 5 [OUTPUT] Name es Match * Host elasticsearch Port 9200 Index android-platform ``` -------------------------------- ### Horizontal Pod Autoscaler Configuration (YAML) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes Horizontal Pod Autoscaler (HPA) configuration automatically adjusts the number of replicas for the `api-gateway` deployment in the `android-platform` namespace. It scales based on CPU utilization (targeting 70%) and memory utilization (targeting 80%), with defined scaling policies for both scale-up and scale-down events, including stabilization windows. ```yaml apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: api-gateway-hpa namespace: android-platform spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: api-gateway minReplicas: 3 maxReplicas: 20 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 - type: Resource resource: name: memory target: type: Utilization averageUtilization: 80 behavior: scaleUp: stabilizationWindowSeconds: 60 policies: - type: Percent value: 100 periodSeconds: 15 scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 50 periodSeconds: 60 ``` -------------------------------- ### Vertical Pod Autoscaler Configuration (YAML) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes Vertical Pod Autoscaler (VPA) configuration automatically adjusts the CPU and memory requests/limits for the `lifecycle-manager` container within the `lifecycle-manager` deployment in the `android-platform` namespace. The `updateMode` is set to "Auto", allowing the VPA to manage resource settings within defined minimum and maximum allowed values. ```yaml apiVersion: autoscaling.k8s.io/v1 kind: VerticalPodAutoscaler metadata: name: lifecycle-manager-vpa namespace: android-platform spec: targetRef: apiVersion: apps/v1 kind: Deployment name: lifecycle-manager updatePolicy: updateMode: "Auto" resourcePolicy: containerPolicies: - containerName: lifecycle-manager maxAllowed: cpu: 4 memory: 8Gi minAllowed: cpu: 100m memory: 256Mi ``` -------------------------------- ### Cross-Region Backup Sync with AWS CLI (YAML) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/DEPLOYMENT.md This Kubernetes CronJob is configured to perform daily backups to an AWS S3 bucket in a different region. It uses the `amazon/aws-cli` image to execute `aws s3 sync` command, transferring files from the local `/backup` directory to the specified S3 bucket (`s3://android-platform-backups-us-west-2/`). The backup sync runs daily at 6 AM. ```yaml apiVersion: batch/v1 kind: CronJob metadata: name: cross-region-backup spec: schedule: "0 6 * * *" # Daily at 6 AM jobTemplate: spec: template: spec: containers: - name: backup-sync image: amazon/aws-cli command: - aws - s3 - sync - /backup - s3://android-platform-backups-us-west-2/ ``` -------------------------------- ### Create an Android Instance via API Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Creates a new Android instance with specified configuration. Requires an authentication token and details like Android version, device model, and resource limits. Returns information about the created instance. ```bash curl -X POST http://localhost:3000/instances \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "android_version": "13", "device_manufacturer": "Google", "device_model": "Pixel 7", "cpu_limit": 2.0, "memory_limit": "4G" }' ``` -------------------------------- ### Create Instance API Reference Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Defines the payload for creating an Android instance via the API. It includes detailed configuration options for Android version, device specifics, resource allocation, network settings, and location precision. This endpoint is central to provisioning new instances. ```json { "android_version": "13", "device_manufacturer": "Google", "device_model": "Pixel 7", "cpu_limit": 2.0, "memory_limit": "4G", "storage_size": "8G", "network_config": { "proxy_type": "residential", "country": "US" }, "location_config": { "latitude": 40.7128, "longitude": -74.0060 } } ``` -------------------------------- ### Kubernetes Production Deployment Steps Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Deploys the Android container platform on a Kubernetes cluster. This involves applying YAML manifests for namespaces, configurations, databases, services, and monitoring. It is essential for setting up a production environment. ```bash # Create namespace kubectl apply -f k8s/namespace.yaml # Deploy configuration kubectl apply -f k8s/configmap.yaml # Deploy databases kubectl apply -f k8s/postgres.yaml kubectl apply -f k8s/redis.yaml # Deploy services kubectl apply -f k8s/services.yaml # Deploy monitoring kubectl apply -f k8s/monitoring.yaml ``` -------------------------------- ### Troubleshooting Build Failures Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Outlines steps to resolve build failures. This includes clearing the node_modules and package-lock.json files, reinstalling dependencies, and attempting to build the production bundle again. ```bash # Clear cache and reinstall rm -rf node_modules package-lock.json npm install npm run build ``` -------------------------------- ### Troubleshooting Map Loading Issues Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Provides guidance for resolving issues with map loading. It suggests checking the map provider configuration and API key environment variables if applicable. ```bash # Check map provider configuration echo $REACT_APP_MAP_PROVIDER # For providers requiring API keys echo $REACT_APP_MAP_API_KEY ``` -------------------------------- ### Configure Instance Network API Reference Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Sets up network configuration for an Android instance, including proxy type, country, city, and DNS servers. This enables testing applications under various network conditions and geographical locations. ```json { "proxy_type": "residential", "country": "US", "city": "New York", "dns_servers": ["8.8.8.8", "1.1.1.1"] } ``` -------------------------------- ### Monitor System Resources (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Real-time monitoring of system CPU and I/O usage. Essential for identifying performance bottlenecks at the host level. ```bash htop iotop ``` -------------------------------- ### Build Docker Image for Web Dashboard (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md This command builds a Docker image for the web dashboard application. It tags the image as 'android-dashboard' and uses the Dockerfile in the current directory. ```bash docker build -t android-dashboard . ``` -------------------------------- ### Instance Management API Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Provides endpoints for creating, managing, and deleting Android container instances. ```APIDOC ## POST /instances ### Description Creates a new Android container instance with specified configuration. ### Method POST ### Endpoint /instances ### Parameters #### Request Body - **android_version** (string) - Required - The Android version for the instance. - **device_manufacturer** (string) - Required - The manufacturer of the virtual device. - **device_model** (string) - Required - The model of the virtual device. - **cpu_limit** (number) - Required - The CPU limit for the instance. - **memory_limit** (string) - Required - The memory limit for the instance (e.g., "4G"). - **storage_size** (string) - Optional - The storage size for the instance (e.g., "8G"). - **network_config** (object) - Optional - Network configuration for the instance. - **proxy_type** (string) - Optional - The type of proxy to use (e.g., "residential"). - **country** (string) - Optional - The country code for the proxy. - **location_config** (object) - Optional - Initial location configuration for the instance. - **latitude** (number) - Optional - The latitude coordinate. - **longitude** (number) - Optional - The longitude coordinate. ### Request Example ```json { "android_version": "13", "device_manufacturer": "Google", "device_model": "Pixel 7", "cpu_limit": 2.0, "memory_limit": "4G", "storage_size": "8G", "network_config": { "proxy_type": "residential", "country": "US" }, "location_config": { "latitude": 40.7128, "longitude": -74.0060 } } ``` ## GET /instances ### Description Retrieves a list of Android container instances, with optional filtering by status and pagination. ### Method GET ### Endpoint /instances ### Parameters #### Query Parameters - **status** (string) - Optional - Filter instances by their status (e.g., "running"). - **limit** (integer) - Optional - The maximum number of instances to return. ### Response #### Success Response (200) (Response structure for listing instances would typically be an array of instance objects, but is not detailed in the provided text.) ## POST /instances/{instance_id}/start ### Description Starts a specific Android container instance. ### Method POST ### Endpoint /instances/{instance_id}/start ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to start. ## POST /instances/{instance_id}/stop ### Description Stops a specific Android container instance. ### Method POST ### Endpoint /instances/{instance_id}/stop ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to stop. ## POST /instances/{instance_id}/restart ### Description Restarts a specific Android container instance. ### Method POST ### Endpoint /instances/{instance_id}/restart ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to restart. ## DELETE /instances/{instance_id} ### Description Deletes a specific Android container instance. ### Method DELETE ### Endpoint /instances/{instance_id} ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to delete. ``` -------------------------------- ### Network Configuration API Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Allows configuring and testing network settings for Android instances. ```APIDOC ## POST /instances/{instance_id}/network ### Description Configures the network settings for a specific Android instance, including proxy and DNS settings. ### Method POST ### Endpoint /instances/{instance_id}/network ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to configure. #### Request Body - **proxy_type** (string) - Optional - The type of proxy to use (e.g., "residential"). - **country** (string) - Optional - The country code for the proxy. - **city** (string) - Optional - The city for the proxy. - **dns_servers** (array) - Optional - An array of DNS server IP addresses. ### Request Example ```json { "proxy_type": "residential", "country": "US", "city": "New York", "dns_servers": ["8.8.8.8", "1.1.1.1"] } ``` ## POST /instances/{instance_id}/network/test ### Description Tests the network connectivity of a specific Android instance. ### Method POST ### Endpoint /instances/{instance_id}/network/test ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to test. ### Response #### Success Response (200) (Response structure for network test is not detailed in the provided text.) ``` -------------------------------- ### List Network Namespaces (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Displays all available network namespaces on the system. Useful for debugging network isolation issues. ```bash ip netns list ``` -------------------------------- ### List Proxies (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Retrieves a list of configured proxies from the platform. Used for validating proxy settings and detecting potential issues. ```bash curl -X GET http://localhost:3000/proxy/list \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Troubleshooting API Connection Issues Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Provides commands to troubleshoot API connection failures. It includes checking the API URL configuration via echo and testing API connectivity using curl. ```bash # Check API URL configuration echo $REACT_APP_API_URL # Test API connectivity curl http://localhost:3000/api/health ``` -------------------------------- ### Retrieve Android Instance Logs (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Fetches logs for a specific Android instance via an API call. Requires an authorization token. ```bash curl -X GET http://localhost:3000/instances/INSTANCE_ID/logs \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Test Instance Network Connectivity (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Initiates a network test for a specific instance via an API call. Requires an authorization token. ```bash curl -X POST http://localhost:3000/instances/INSTANCE_ID/network/test \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Run Web Dashboard Docker Container (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md This command runs a Docker container from the 'android-dashboard' image. It maps port 80, sets environment variables for API and WebSocket URLs, and runs the container in the background. ```bash docker run -p 80:80 \ -e REACT_APP_API_URL=http://your-api-server:3000 \ -e REACT_APP_WS_URL=http://your-api-server:3000 \ android-dashboard ``` -------------------------------- ### Verify KVM Support (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Checks if Kernel-based Virtual Machine (KVM) is supported on the host system. Required for running Android emulators efficiently. ```bash kvm-ok ``` -------------------------------- ### Inspect Android Container (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Provides detailed low-level information about a Docker container running an Android instance. Helps in debugging container configurations. ```bash docker inspect android-INSTANCE_ID ``` -------------------------------- ### Nginx Configuration for Production Deployment Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Describes the Nginx configuration for the production environment, focusing on its role as a reverse proxy, WebSocket support, static asset caching, security headers (CORS, CSP), Gzip compression, and rate limiting for API abuse protection. ```text Reverse Proxy - API requests routed to backend WebSocket Support - Real-time connections handled properly Static Asset Caching - Optimized delivery of JS/CSS/images Security Headers - CORS, CSP, and other security measures Gzip Compression - Reduced bandwidth usage Rate Limiting - API abuse protection ``` -------------------------------- ### Verify Kubernetes Deployment Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Verifies the successful deployment of the Android container platform on Kubernetes by checking the status of pods and services within the designated namespace. Helps in troubleshooting deployment issues. ```bash kubectl get pods -n android-platform kubectl get services -n android-platform ``` -------------------------------- ### Monitor Container Resources (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Displays real-time resource utilization (CPU, memory, network, I/O) for running Docker containers. ```bash docker stats ``` -------------------------------- ### Verify Docker Disk Usage (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Shows the disk space used by Docker images, containers, and volumes. Useful for managing storage and identifying potential issues. ```bash docker system df ``` -------------------------------- ### Monitor an Android Instance via API Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Retrieves the status and details of a specific Android instance. Requires the instance ID and an authentication token. Useful for checking instance health and configuration. ```bash curl -X GET http://localhost:3000/instances/INSTANCE_ID \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Authenticate to Android Container Platform API Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Authenticates with the platform to obtain a JWT token. Requires username and password, and returns an access token for subsequent requests. This is the first step for most API interactions. ```bash curl -X POST http://localhost:3000/auth/login \ -H "Content-Type: application/json" \ -d '{"username":"admin","password":"admin123"}' ``` -------------------------------- ### Check Available Memory (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Displays the system's available memory in a human-readable format. Helps in identifying memory constraints. ```bash free -h ``` -------------------------------- ### Show Network Namespace IP Addresses (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Displays the IP addresses configured within a specific network namespace. Helps in verifying network connectivity for instances. ```bash ip netns exec netns-INSTANCE_ID ip addr show ``` -------------------------------- ### Enabling Debug Mode Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Shows how to enable debug logging for the application by setting the REACT_APP_ENABLE_DEBUG environment variable to true. ```bash REACT_APP_ENABLE_DEBUG=true ``` -------------------------------- ### Environment Variables for Web Dashboard Configuration (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md These environment variables are used to configure the web dashboard, specifying the API endpoint, WebSocket URL, and map provider details. They are typically set in a .env file or directly during container runtime. ```bash # API Configuration REACT_APP_API_URL=http://localhost:3000 REACT_APP_WS_URL=http://localhost:3000 # Map Configuration REACT_APP_MAP_PROVIDER=openstreetmap REACT_APP_MAP_API_KEY=your_api_key_here ``` -------------------------------- ### Check Service Logs (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Retrieves logs for a specific service using docker-compose or kubectl. Useful for diagnosing startup or runtime errors. ```bash docker-compose logs service-name kubectl logs -f deployment/service-name -n android-platform ``` -------------------------------- ### Troubleshooting WebSocket Connection Issues Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/services/web-dashboard/README.md Offers commands to diagnose WebSocket connection problems. It involves checking the WebSocket URL and verifying the WebSocket endpoint using wscat. ```bash # Check WebSocket URL echo $REACT_APP_WS_URL # Verify WebSocket endpoint wscat -c ws://localhost:3000/socket.io/ ``` -------------------------------- ### Retrieve Platform Metrics (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Fetches performance metrics exposed by the platform, typically in Prometheus format. Useful for detailed performance analysis. ```bash curl http://localhost:9090/metrics ``` -------------------------------- ### View Android Container Logs (Bash) Source: https://github.com/muhammadbilal005/android-container-platform/blob/master/docs/README.md Retrieves the standard output and error logs from a Docker container running an Android instance. ```bash docker logs android-INSTANCE_ID ```