# Coder Task Service

## Overview

The Coder task service provides a complete installation and configuration of [Coder](https://coder.com/), a self-hosted remote development platform that provides secure, high-performance development environments accessible from anywhere. Coder enables teams to standardize development environments while maintaining the flexibility of individual workspaces.

## Features

### Core Capabilities
- **Remote Development Environments** - Secure, standardized dev environments
- **Web-based IDE Access** - Browser-based development with VS Code
- **Template Management** - Standardized workspace templates for teams
- **Resource Provisioning** - Automatic provisioning of compute resources
- **SSH Access** - Direct SSH access to development environments

### Database Support
- **SQLite** (default) - Simple, file-based database for small deployments
- **PostgreSQL** - Production-ready database for larger installations
- **Connection Pooling** - Optimized database connections

### Authentication & Security
- **OAuth Integration** - GitHub, Google, OpenID Connect support
- **TLS/SSL Support** - HTTPS with custom certificates
- **Wildcard Domains** - Support for workspace subdomains
- **RBAC** - Role-based access control for users and workspaces

### Management Features
- **Systemd Integration** - Full service management and monitoring
- **Admin User Creation** - Automated first admin user setup
- **Resource Monitoring** - Workspace resource usage tracking
- **Audit Logging** - Comprehensive activity logging

## Configuration

### Basic Configuration
```kcl
coder: CoderServer = {
    name: "coder-dev"
    version: "2.8.0"
    run_user: {
        name: "coder"
        home: "/home/coder"
    }
    access_url: "http://coder.example.com:7080"
    http_address: "0.0.0.0:7080"
    database: {
        typ: "sqlite"
        path: "/var/lib/coder/coder.db"
    }
}
```

### Production Configuration
```kcl
coder: CoderServer = {
    name: "coder-prod"
    version: "2.8.0"
    run_user: {
        name: "coder"
        group: "coder"
        home: "/home/coder"
    }
    work_path: "/var/lib/coder"
    config_path: "/etc/coder"
    access_url: "https://coder.company.com"
    wildcard_access_url: "*.coder.company.com"
    http_address: "0.0.0.0:7080"
    database: {
        typ: "postgresql"
        host: "postgres.company.com"
        port: 5432
        database: "coder"
        username: "coder_user"
        password: "secure_password"
        ssl_mode: "require"
    }
    tls: {
        enabled: true
        cert_file: "/etc/ssl/certs/coder.crt"
        key_file: "/etc/ssl/private/coder.key"
        address: "0.0.0.0:443"
    }
    oauth: {
        enabled: true
        provider: "github"
        client_id: "github_client_id"
        client_secret: "github_client_secret"
    }
    log_level: "info"
    telemetry_enabled: false
    secure_auth_cookie: true
    max_session_token_lifetime: "720h"
}
```

### OpenID Connect Configuration
```kcl
coder: CoderServer = {
    # ... other configuration
    oauth: {
        enabled: true
        provider: "oidc"
        client_id: "coder-client"
        client_secret: "oidc_client_secret"
        issuer_url: "https://auth.company.com/realms/company"
        scopes: ["openid", "profile", "email", "groups"]
    }
}
```

## Usage

### Deploy Coder Server
```bash
./core/nulib/provisioning taskserv create coder --infra <infrastructure-name>
```

### List Available Task Services
```bash
./core/nulib/provisioning taskserv list
```

### SSH to Coder Server
```bash
./core/nulib/provisioning server ssh <coder-server>
```

### Service Management
```bash
# Check Coder server status
systemctl status coder

# Start/stop Coder server
systemctl start coder
systemctl stop coder
systemctl restart coder

# View Coder logs
journalctl -u coder -f

# Check Coder configuration
sudo -u coder coder server --help
```

### Access Web Interface
1. **Open browser** to configured access URL
2. **Complete setup wizard** (first time)
3. **Create admin user** (automatically done by taskserv)
4. **Create workspace templates**
5. **Provision development environments**

### CLI Usage
```bash
# Install Coder CLI
curl -fsSL https://coder.com/install.sh | sh

# Login to Coder instance
coder login https://coder.example.com

# List available templates
coder templates list

# Create workspace from template
coder create my-workspace --template=docker

# SSH into workspace
coder ssh my-workspace

# Port forward from workspace
coder port-forward my-workspace --tcp 3000:3000

# Show workspace status
coder list
```

## Architecture

### System Architecture
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Users/Teams   │────│   Coder Server   │────│   Workspaces    │
│                 │    │                  │    │                 │
│ • Web Browser   │    │ • Authentication │    │ • Docker        │
│ • VS Code       │────│ • Templates      │────│ • Kubernetes    │
│ • SSH Client    │    │ • Provisioning   │    │ • VMs           │
│ • Coder CLI     │    │ • Monitoring     │    │ • Cloud VMs     │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Network Ports
- **HTTP/HTTPS (7080/443)** - Web interface and API
- **Workspace Access** - Dynamic ports for workspace connections
- **DERP (3478)** - Relay server for workspace connectivity

### File Structure
```
/var/lib/coder/             # Main working directory
├── coder.db               # SQLite database (if used)
├── templates/             # Workspace templates
├── workspaces/           # Workspace data
└── logs/                 # Application logs

/etc/coder/               # Configuration directory
├── coder.yaml            # Main configuration
└── templates/            # Template definitions

/home/coder/              # Service user home
├── .config/              # User configuration
└── templates/            # User templates
```

## Supported Operating Systems

- Ubuntu 20.04+ / Debian 11+
- CentOS 8+ / RHEL 8+ / Fedora 35+

## System Requirements

### Minimum Requirements (Coder Server)
- **RAM**: 2GB (4GB recommended)
- **Storage**: 20GB (varies with workspace count)
- **CPU**: 2 cores (4 cores recommended)
- **Network**: Internet access for workspace provisioning

### Production Requirements
- **RAM**: 8GB+ (depends on concurrent workspaces)
- **Storage**: 100GB+ SSD
- **CPU**: 4+ cores
- **Database**: External PostgreSQL recommended
- **Load Balancer**: For high availability

### Network Requirements
- **Outbound**: HTTPS (443) for template downloads and updates
- **Inbound**: HTTP/HTTPS on configured ports
- **Workspace Connectivity**: Various ports for workspace access

## Templates

### Docker Template Example
```hcl
terraform {
  required_providers {
    coder = {
      source  = "coder/coder"
    }
    docker = {
      source  = "kreuzwerker/docker"
    }
  }
}

data "coder_workspace" "me" {}

data "coder_parameter" "image" {
  name        = "image"
  type        = "string"
  description = "Docker image"
  default     = "codercom/enterprise-base:ubuntu"
}

resource "docker_image" "main" {
  name = data.coder_parameter.image.value
}

resource "docker_container" "workspace" {
  count = data.coder_workspace.me.start_count
  image = docker_image.main.name
  name  = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}"
  
  env = ["CODER=true"]
  
  host {
    host = "host.docker.internal"
    ip   = "host-gateway"
  }
}

resource "coder_agent" "main" {
  count = data.coder_workspace.me.start_count
  arch  = "amd64"
  os    = "linux"
  
  startup_script = <<-EOT
    #!/bin/bash
    # Install development tools
    sudo apt-get update && sudo apt-get install -y git curl wget
  EOT
}
```

### Kubernetes Template Example
```hcl
terraform {
  required_providers {
    coder = {
      source = "coder/coder"
    }
    kubernetes = {
      source = "hashicorp/kubernetes"
    }
  }
}

resource "kubernetes_pod" "main" {
  count = data.coder_workspace.me.start_count
  
  metadata {
    name      = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}"
    namespace = "coder-workspaces"
  }
  
  spec {
    container {
      name  = "dev"
      image = "codercom/enterprise-base:ubuntu"
      
      resources {
        requests = {
          "cpu"    = "250m"
          "memory" = "512Mi"
        }
        limits = {
          "cpu"    = "2"
          "memory" = "4Gi"
        }
      }
    }
  }
}
```

## Troubleshooting

### Service Issues
```bash
# Check Coder server status
systemctl status coder

# View recent logs
journalctl -u coder -n 100

# Check configuration
sudo -u coder coder server validate

# Test database connection
sudo -u coder coder server postgres-builtin-url
```

### Database Issues
```bash
# SQLite issues
ls -la /var/lib/coder/coder.db
sudo -u coder sqlite3 /var/lib/coder/coder.db ".tables"

# PostgreSQL connection test
sudo -u coder psql -h <host> -U <user> -d <database> -c "SELECT version();"
```

### Authentication Issues
```bash
# Check OAuth configuration
sudo -u coder coder server --help | grep oauth

# Test OIDC discovery
curl https://auth.provider.com/.well-known/openid-configuration

# Reset admin user (if needed)
sudo -u coder coder users create --username admin --password newpassword
```

### Workspace Issues
```bash
# List workspaces
coder list

# Check workspace logs
coder logs workspace-name

# Debug workspace connectivity
coder ping workspace-name

# Force workspace rebuild
coder stop workspace-name
coder delete workspace-name --force
coder create workspace-name --template template-name
```

### Network Connectivity
```bash
# Check if Coder is listening
netstat -tlnp | grep :7080

# Test external access
curl -I http://localhost:7080/healthz

# Check workspace connectivity
coder port-forward workspace-name --tcp 2222:22
ssh -p 2222 coder@localhost
```

## Security Considerations

### Server Security
- **TLS/SSL** - Always use HTTPS in production
- **Firewall Rules** - Limit access to necessary ports
- **Regular Updates** - Keep Coder server updated
- **Database Security** - Use encrypted connections for external databases

### Authentication Security
- **OAuth/OIDC** - Use external identity providers
- **Session Management** - Configure appropriate session timeouts
- **Multi-Factor Authentication** - Enable through identity provider
- **RBAC** - Implement proper role-based access controls

### Workspace Security
- **Template Review** - Audit workspace templates regularly
- **Resource Limits** - Set appropriate CPU/memory limits
- **Network Isolation** - Isolate workspaces when possible
- **Data Protection** - Encrypt workspace storage

## Performance Optimization

### Server Performance
- **Database Tuning** - Optimize PostgreSQL settings for Coder
- **Resource Allocation** - Allocate sufficient CPU/memory
- **Storage Performance** - Use SSD storage for database and workspaces
- **Load Balancing** - Use multiple Coder instances for high availability

### Workspace Performance
- **Template Optimization** - Create efficient workspace templates
- **Resource Right-sizing** - Set appropriate resource limits
- **Image Optimization** - Use minimal, optimized container images
- **Startup Scripts** - Minimize startup script execution time

## Backup and Recovery

### Backup Procedure
```bash
# Stop Coder service
systemctl stop coder

# Backup database (SQLite)
cp /var/lib/coder/coder.db /backup/coder-db-$(date +%Y%m%d).db

# Backup database (PostgreSQL)
pg_dump -h host -U user database > /backup/coder-db-$(date +%Y%m%d).sql

# Backup configuration
tar -czf /backup/coder-config-$(date +%Y%m%d).tar.gz /etc/coder/

# Restart service
systemctl start coder
```

### Recovery Procedure
1. **Stop Coder service**
2. **Restore database** from backup
3. **Restore configuration** files
4. **Update database schema** if needed: `coder server migrate`
5. **Start Coder service**
6. **Verify functionality**

## Integration Examples

### CI/CD Integration
```yaml
# GitHub Actions example
name: Deploy to Coder
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Setup Coder CLI
        run: curl -fsSL https://coder.com/install.sh | sh
        
      - name: Login to Coder
        run: coder login ${{ secrets.CODER_URL }} --token ${{ secrets.CODER_TOKEN }}
        
      - name: Update template
        run: coder templates push my-template --directory ./template/
```

### Monitoring Integration
```bash
# Prometheus metrics endpoint
curl http://localhost:7080/api/v2/metrics

# Health check endpoint
curl http://localhost:7080/healthz

# Custom monitoring script
#!/bin/bash
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:7080/healthz)
if [ $STATUS -ne 200 ]; then
    echo "Coder is down: HTTP $STATUS"
    # Send alert
fi
```

## Resources

- **Official Documentation**: [coder.com/docs](https://coder.com/docs)
- **GitHub Repository**: [coder/coder](https://github.com/coder/coder)
- **Community**: [coder.com/community](https://coder.com/community)
- **Templates**: [github.com/coder/coder/tree/main/examples/templates](https://github.com/coder/coder/tree/main/examples/templates)