# Gitea Task Service

## Overview

The Gitea task service provides a complete installation and configuration of [Gitea](https://gitea.io/), a lightweight, self-hosted Git service written in Go. Gitea provides a GitHub-like experience with repositories, issue tracking, pull requests, wikis, and CI/CD integration while being resource-efficient and easy to deploy.

## Features

### Core Git Features
- **Git Repository Hosting** - Complete Git server with web interface
- **Branch Management** - Advanced branching and merging capabilities
- **Repository Management** - Create, fork, clone, and manage repositories
- **File Management** - Web-based file editing and management
- **Git LFS Support** - Large file storage integration

### Collaboration Features
- **Issue Tracking** - Comprehensive issue management system
- **Pull Requests** - Code review workflow with approval systems
- **Code Review** - Line-by-line code review with comments
- **Wikis** - Repository and organization wikis
- **Project Boards** - Kanban-style project management

### User & Organization Management
- **User Authentication** - Local, LDAP, OAuth2, and SSO integration
- **Organizations** - Multi-user organization management
- **Teams & Permissions** - Granular access control and team management
- **SSH Key Management** - Multiple SSH key support per user
- **Two-Factor Authentication** - TOTP and WebAuthn support

### Advanced Features
- **CI/CD Integration** - Gitea Actions (GitHub Actions compatible)
- **Package Registry** - Built-in package management (Docker, NPM, etc.)
- **API Access** - Complete REST API for automation
- **Webhooks** - Extensive webhook system for integrations  
- **Mirror Repositories** - Git repository mirroring

### Administration Features
- **Web Administration** - Complete web-based admin interface
- **Database Support** - SQLite, PostgreSQL, MySQL, MSSQL support
- **Email Integration** - SMTP email notifications and registration
- **Backup & Restore** - Built-in backup and restoration tools
- **Monitoring** - Prometheus metrics and health endpoints

## Configuration

### Basic Configuration
```kcl
gitea: Gitea = {
    name: "gitea"
    version: "1.21.1"
    app_name: "Gitea: Git with a cup of tea"
    run_user: {
        name: "gitea"
        group: "gitea"
        home: "/home/gitea"
    }
    adm_user: {
        name: "admin"
        password: "admin123"
        email: "admin@company.com"
    }
    work_path: "/var/lib/gitea"
    etc_path: "/etc/gitea"
    config_path: "app.ini"
    run_path: "/usr/local/bin/gitea"
    protocol: "http"
    http_addr: "localhost"
    http_port: 3000
    root_url: "http://localhost:3000"
    domain: "localhost"
    db: {
        typ: "sqlite"
        name: "gitea"
        path: "/var/lib/gitea/gitea.db"
    }
    disable_registration: true
    require_signin_view: false
}
```

### Production Configuration with PostgreSQL
```kcl
gitea: Gitea = {
    name: "gitea"
    version: "1.21.1"
    app_name: "Company Git Service"
    run_user: {
        name: "gitea"
        group: "gitea"
        home: "/opt/gitea"
    }
    adm_user: {
        name: "admin"
        password: "secure_admin_password_123"
        email: "admin@company.com"
    }
    work_path: "/var/lib/gitea"
    etc_path: "/etc/gitea"
    config_path: "app.ini"
    run_path: "/usr/local/bin/gitea"
    protocol: "http"
    http_addr: "0.0.0.0"
    http_port: 3000
    root_url: "https://git.company.com"
    domain: "git.company.com"
    db: {
        typ: "postgres"
        host: "127.0.0.1:5432"
        name: "gitea"
        user: "gitea"
        password: "gitea_db_password"
        charset: "utf8"
        ssl_mode: "disable"
    }
    disable_registration: true
    require_signin_view: true
    webhook_allowed_hosts_list: "*.company.com,10.0.0.0/8"
}
```

### SSH and SSL Configuration
```kcl
gitea: Gitea_SSH_SSL = {
    name: "gitea"
    version: "1.21.1"
    app_name: "Secure Company Git"
    run_user: {
        name: "gitea"
        group: "gitea"
        home: "/opt/gitea"
    }
    adm_user: {
        name: "admin"
        password: "secure_admin_password_123"
        email: "admin@company.com"
    }
    work_path: "/var/lib/gitea"
    etc_path: "/etc/gitea"
    protocol: "https"
    http_addr: "0.0.0.0"
    http_port: 3000
    root_url: "https://git.company.com"
    domain: "git.company.com"
    ssh_domain: "git.company.com"
    ssh_port: 2022
    start_ssh_server: true
    builtin_ssh_server_user: "git"
    ssh_root_path: "/home/gitea/.ssh"
    certs_path: "/etc/ssl/gitea"
    cert_file: "/etc/ssl/gitea/fullchain.pem"
    key_file: "/etc/ssl/gitea/privkey.pem"
    db: {
        typ: "postgres"
        host: "127.0.0.1:5432"
        name: "gitea"
        user: "gitea"
        password: "gitea_db_password"
        charset: "utf8"
        ssl_mode: "require"
    }
    disable_registration: false
    require_signin_view: true
}
```

### CI/CD Integration Configuration
```kcl
gitea: Gitea = {
    name: "gitea"
    version: "1.21.1"
    # ... base configuration
    cdci_user: "gitea-runner"
    cdci_group: "gitea-runner"
    cdci_user_home: "/home/gitea-runner"
    cdci_key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC..."
    webhook_allowed_hosts_list: "localhost,127.0.0.1,*.company.com,10.0.0.0/8"
    actions: {
        enabled: true
        default_actions_url: "github"
        runner_registration_token: "auto-generate"
    }
    packages: {
        enabled: true
        docker_registry: {
            enabled: true
            base_path: "/var/lib/gitea/data/packages/docker"
        }
        npm_registry: {
            enabled: true
            base_path: "/var/lib/gitea/data/packages/npm"
        }
    }
}
```

### High-Availability Configuration
```kcl
gitea: Gitea = {
    name: "gitea"
    version: "1.21.1"
    # ... base configuration
    protocol: "https"
    http_addr: "0.0.0.0"
    http_port: 3000
    root_url: "https://git.company.com"
    domain: "git.company.com"
    db: {
        typ: "postgres"
        host: "postgres-cluster.company.com:5432"
        name: "gitea"
        user: "gitea"
        password: "gitea_cluster_password"
        charset: "utf8"
        ssl_mode: "require"
    }
    cache: {
        enabled: true
        adapter: "redis"
        interval: 60
        host: "redis-cluster.company.com:6379"
        password: "redis_password"
    }
    session: {
        provider: "redis"
        provider_config: "network=tcp,addr=redis-cluster.company.com:6379,password=redis_password,db=0,pool_size=100,idle_timeout=180"
    }
    storage: {
        serve_direct: true
        minio: {
            endpoint: "minio.company.com:9000"
            access_key_id: "gitea_access_key"
            secret_access_key: "gitea_secret_key"
            bucket: "gitea"
            location: "us-east-1"
            use_ssl: true
        }
    }
}
```

### Enterprise LDAP Configuration
```kcl
gitea: Gitea = {
    name: "gitea"
    version: "1.21.1"
    # ... base configuration
    authentication: {
        ldap: {
            enabled: true
            name: "Corporate LDAP"
            security_protocol: "ldaps"
            host: "ldap.company.com"
            port: 636
            bind_dn: "cn=gitea,ou=services,dc=company,dc=com"
            bind_password: "ldap_bind_password"
            user_base: "ou=users,dc=company,dc=com"
            user_filter: "(&(objectClass=person)(uid=%s))"
            admin_filter: "(memberOf=cn=gitea-admins,ou=groups,dc=company,dc=com)"
            username_attribute: "uid"
            firstname_attribute: "givenName"
            surname_attribute: "sn"
            email_attribute: "mail"
            public_ssh_key_attribute: "sshPublicKey"
        }
        oauth2: [
            {
                name: "Corporate SSO"
                provider: "openid-connect"
                client_id: "gitea-client-id"
                client_secret: "gitea-client-secret"
                auto_discovery_url: "https://sso.company.com/.well-known/openid_configuration"
                scopes: "openid profile email groups"
                group_claim_name: "groups"
                admin_group: "gitea-admins"
            }
        ]
    }
    disable_registration: true
    require_signin_view: true
}
```

## Usage

### Deploy Gitea
```bash
./core/nulib/provisioning taskserv create gitea --infra <infrastructure-name>
```

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

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

### Service Management
```bash
# Check Gitea status
systemctl status gitea

# Start/stop Gitea
systemctl start gitea
systemctl stop gitea
systemctl restart gitea

# View Gitea logs
journalctl -u gitea -f

# Check Gitea version
gitea --version
```

### Administrative Commands
```bash
# Create admin user
sudo -u gitea /usr/local/bin/gitea admin user create \
  --name admin \
  --password admin123 \
  --email admin@company.com \
  --admin \
  --config /etc/gitea/app.ini

# List users
sudo -u gitea /usr/local/bin/gitea admin user list \
  --config /etc/gitea/app.ini

# Change user password
sudo -u gitea /usr/local/bin/gitea admin user change-password \
  --username admin \
  --password new_password \
  --config /etc/gitea/app.ini

# Create organization
sudo -u gitea /usr/local/bin/gitea admin user create-org \
  --name company \
  --owner admin \
  --config /etc/gitea/app.ini
```

### Repository Management
```bash
# Migrate repository from GitHub
sudo -u gitea /usr/local/bin/gitea migrate \
  --git-service github \
  --auth-token github_token \
  --repo-owner company \
  --repo-name project \
  --config /etc/gitea/app.ini

# Generate Git hooks
sudo -u gitea /usr/local/bin/gitea admin regenerate hooks \
  --config /etc/gitea/app.ini

# Rebuild indexes
sudo -u gitea /usr/local/bin/gitea admin regenerate keys \
  --config /etc/gitea/app.ini
```

### Database Operations
```bash
# Database migration
sudo -u gitea /usr/local/bin/gitea migrate \
  --config /etc/gitea/app.ini

# Backup database
sudo -u gitea /usr/local/bin/gitea backup \
  --config /etc/gitea/app.ini \
  --file /backup/gitea-backup-$(date +%Y%m%d).zip

# Restore from backup
sudo -u gitea /usr/local/bin/gitea restore \
  --config /etc/gitea/app.ini \
  --from /backup/gitea-backup.zip
```

### Actions and CI/CD
```bash
# Register Actions runner
gitea-actions-runner register \
  --instance https://git.company.com \
  --token runner_registration_token \
  --name company-runner-1

# Start Actions runner
gitea-actions-runner daemon \
  --config /etc/gitea-runner/config.yaml

# Check runner status
gitea-actions-runner status
```

### Monitoring and Health
```bash
# Check application health
curl http://localhost:3000/api/healthz

# Get version information
curl http://localhost:3000/api/v1/version

# Monitor metrics (if enabled)
curl http://localhost:3000/metrics

# Check database connectivity
sudo -u gitea /usr/local/bin/gitea doctor check \
  --config /etc/gitea/app.ini
```

## Architecture

### System Architecture
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Users/Clients │────│   Gitea Server   │────│   Data Storage  │
│                 │    │                  │    │                 │
│ • Web Browser   │    │ • Web Interface  │    │ • Git Repos     │
│ • Git CLI       │────│ • Git Protocol   │────│ • Database      │
│ • IDE/Editor    │    │ • SSH Server     │    │ • File Storage  │
│ • CI/CD Tools   │    │ • API Server     │    │ • Cache         │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Component Architecture
```
┌─────────────────────────────────────────────────────────────┐
│                      Gitea Application                      │
├─────────────────────────────────────────────────────────────┤
│  Web Interface    │  Git Server       │  API Server        │
│                   │                   │                    │
│ • Repository View │ • Git Operations  │ • REST API         │
│ • Issue Tracker   │ • SSH Access      │ • Webhook System   │
│ • Pull Requests   │ • HTTP(S) Clone   │ • Authentication   │
│ • User Management │ • Push/Pull       │ • Authorization    │
├─────────────────────────────────────────────────────────────┤
│                    Storage Layer                           │
├─────────────────────────────────────────────────────────────┤
│  Database         │  File System      │  Cache Layer       │
│                   │                   │                    │
│ • SQLite/Postgres │ • Git Repositories│ • Redis (optional) │
│ • User Data       │ • LFS Storage     │ • Session Store    │
│ • Metadata        │ • Avatars/Assets  │ • Template Cache   │
└─────────────────────────────────────────────────────────────┘
```

### Network Ports
- **HTTP Port (3000)** - Web interface and Git HTTP operations
- **SSH Port (2022)** - Git SSH operations and built-in SSH server
- **Metrics Port (8080)** - Prometheus metrics (if enabled)

### File Structure
```
/var/lib/gitea/              # Main data directory
├── data/                    # Application data
│   ├── avatars/            # User avatars
│   ├── attachments/        # Issue attachments
│   ├── packages/           # Package registry
│   └── tmp/                # Temporary files
├── git/                    # Git repositories
│   ├── repositories/       # Repository storage
│   └── lfs/               # Git LFS objects
├── indexers/              # Search indexes
├── log/                   # Application logs
└── sessions/              # Session data

/etc/gitea/                 # Configuration
├── app.ini                # Main configuration
└── locale/               # Custom locale files

/home/gitea/.ssh/          # SSH configuration
├── authorized_keys       # SSH public keys
└── gitea.rsa            # Server SSH key
```

## Supported Operating Systems

- Ubuntu 20.04+ / Debian 11+
- CentOS 8+ / RHEL 8+ / Fedora 35+
- Amazon Linux 2+
- SUSE Linux Enterprise 15+
- Windows Server 2019+

## System Requirements

### Minimum Requirements
- **RAM**: 2GB (4GB+ recommended)
- **Storage**: 10GB (50GB+ for repositories)
- **CPU**: 2 cores (4+ cores recommended)
- **Database**: SQLite (included) or external database

### Production Requirements
- **RAM**: 4GB+ (8GB+ for large installations)
- **Storage**: 100GB+ SSD (depends on repository size)
- **CPU**: 4+ cores (8+ cores for high load)
- **Database**: PostgreSQL or MySQL cluster

### Network Requirements
- **HTTP/HTTPS**: Port 80/443 for web access
- **SSH**: Port 22 or custom port for Git operations
- **Database**: Network access to database server (if external)

## Troubleshooting

### Service Issues
```bash
# Check service status
systemctl status gitea

# View logs
journalctl -u gitea -f --no-pager

# Check configuration
sudo -u gitea /usr/local/bin/gitea doctor check --config /etc/gitea/app.ini

# Test database connection
sudo -u gitea /usr/local/bin/gitea doctor check --config /etc/gitea/app.ini --fix
```

### Database Issues
```bash
# Check database connectivity
sudo -u gitea /usr/local/bin/gitea doctor --config /etc/gitea/app.ini

# Rebuild database indexes
sudo -u gitea /usr/local/bin/gitea admin regenerate keys --config /etc/gitea/app.ini

# Fix database migrations
sudo -u gitea /usr/local/bin/gitea migrate --config /etc/gitea/app.ini

# Check database size
du -sh /var/lib/gitea/gitea.db
```

### Repository Issues
```bash
# Check repository integrity
sudo -u gitea git fsck --full /var/lib/gitea/git/repositories/user/repo.git

# Rebuild repository indexes
sudo -u gitea /usr/local/bin/gitea admin regenerate hooks --config /etc/gitea/app.ini

# Check repository permissions
ls -la /var/lib/gitea/git/repositories/

# Fix repository ownership
sudo chown -R gitea:gitea /var/lib/gitea/
```

### SSH Issues
```bash
# Check SSH configuration
sudo -u gitea ssh-keygen -t rsa -b 4096 -f /home/gitea/.ssh/gitea.rsa

# Test SSH connectivity
ssh -T git@git.company.com -p 2022

# Check authorized keys
sudo -u gitea cat /home/gitea/.ssh/authorized_keys

# Debug SSH connections
ssh -vvv git@git.company.com -p 2022
```

### Performance Issues
```bash
# Check system resources
htop
df -h /var/lib/gitea

# Monitor Gitea process
ps aux | grep gitea

# Check database performance
sudo -u gitea /usr/local/bin/gitea doctor check --config /etc/gitea/app.ini

# Check Git repository size
du -sh /var/lib/gitea/git/repositories/
```

## Security Considerations

### Authentication Security
- **Strong Passwords** - Enforce strong password policies
- **Two-Factor Authentication** - Enable 2FA for admin accounts
- **SSH Key Management** - Regular SSH key rotation
- **Session Security** - Secure session configuration

### Network Security
- **HTTPS/TLS** - Always use HTTPS in production
- **Firewall Rules** - Restrict access to necessary ports
- **Reverse Proxy** - Use nginx/Apache for SSL termination
- **Network Segmentation** - Isolate Gitea from other services

### Data Security
- **Database Security** - Secure database access and encryption
- **Repository Security** - Proper file permissions and access control
- **Backup Security** - Encrypt and secure backups
- **Secret Management** - Secure webhook and API secrets

### Access Control
- **RBAC** - Role-based access control
- **Organization Management** - Proper team and permission setup
- **Repository Permissions** - Granular repository access control
- **Admin Access** - Limit administrative access

## Performance Optimization

### Database Optimization
- **Connection Pooling** - Configure database connection pools
- **Query Optimization** - Regular database maintenance
- **Index Optimization** - Optimize database indexes
- **Database Caching** - Enable query result caching

### Storage Optimization
- **SSD Storage** - Use SSD for better I/O performance
- **Git LFS** - Use Git LFS for large files
- **Repository Cleanup** - Regular git garbage collection
- **File System** - Optimize file system for many small files

### Application Optimization
- **Memory Settings** - Configure appropriate memory limits
- **Cache Configuration** - Enable and configure caching
- **Connection Limits** - Set appropriate connection limits
- **Asset Optimization** - Enable static asset caching

### Network Optimization
- **CDN Integration** - Use CDN for static assets
- **Compression** - Enable HTTP compression
- **Keep-Alive** - Configure HTTP keep-alive
- **Reverse Proxy** - Use reverse proxy for load balancing

## Integration Examples

### Nginx Reverse Proxy
```nginx
server {
    listen 80;
    server_name git.company.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name git.company.com;
    
    ssl_certificate /etc/ssl/gitea/fullchain.pem;
    ssl_certificate_key /etc/ssl/gitea/privkey.pem;
    
    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}
```

### Docker Compose Integration
```yaml
version: '3.8'
services:
  gitea:
    image: gitea/gitea:1.21.1
    container_name: gitea
    environment:
      - USER_UID=1000
      - USER_GID=1000
      - GITEA__database__DB_TYPE=postgres
      - GITEA__database__HOST=db:5432
      - GITEA__database__NAME=gitea
      - GITEA__database__USER=gitea
      - GITEA__database__PASSWD=gitea
    restart: always
    volumes:
      - gitea:/data
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    ports:
      - "3000:3000"
      - "2022:22"
    depends_on:
      - db

  db:
    image: postgres:14
    restart: always
    environment:
      - POSTGRES_USER=gitea
      - POSTGRES_PASSWORD=gitea
      - POSTGRES_DB=gitea
    volumes:
      - postgres:/var/lib/postgresql/data

volumes:
  gitea:
  postgres:
```

## Resources

- **Official Documentation**: [docs.gitea.io](https://docs.gitea.io/)
- **GitHub Repository**: [go-gitea/gitea](https://github.com/go-gitea/gitea)
- **Community Forum**: [discourse.gitea.io](https://discourse.gitea.io/)
- **API Documentation**: [docs.gitea.io/en-us/api-usage](https://docs.gitea.io/en-us/api-usage/)
- **Actions Documentation**: [docs.gitea.io/en-us/usage/actions](https://docs.gitea.io/en-us/usage/actions/)