# CoreDNS Task Service

## Overview

The CoreDNS task service provides a complete installation and configuration of [CoreDNS](https://coredns.io/), a DNS server written in Go that chains plugins. CoreDNS is the default DNS server for Kubernetes and can also serve as a general-purpose authoritative or recursive DNS server with advanced features like service discovery, load balancing, and integration with various backends.

## Features

### Core DNS Capabilities
- **Authoritative DNS** - Serve DNS records for your domains
- **Recursive DNS** - Forward queries to upstream DNS servers
- **Zone File Support** - Traditional DNS zone file management
- **Dynamic Records** - Real-time DNS record updates
- **Service Discovery** - Integration with service discovery systems

### Plugin Architecture
- **Modular Design** - Extensible plugin-based architecture
- **Built-in Plugins** - Comprehensive set of built-in plugins
- **Custom Plugins** - Support for custom plugin development
- **Plugin Chaining** - Chain multiple plugins for complex DNS scenarios
- **Hot Reload** - Configuration changes without service restart

### Advanced Features
- **Load Balancing** - Multiple DNS resolution strategies
- **Health Checking** - Monitor upstream server health
- **Metrics & Monitoring** - Prometheus metrics integration
- **Logging** - Structured logging with multiple output formats
- **TLS/DoT Support** - DNS over TLS for secure queries

### Integration Capabilities
- **Kubernetes Integration** - Native Kubernetes service discovery
- **Etcd Backend** - Store DNS records in etcd
- **Cloud DNS** - Integration with cloud DNS providers
- **External Data** - Integration with external databases and APIs
- **DNSSEC Support** - DNS Security Extensions

## Configuration

### Basic Configuration
```kcl
coredns: COREDNS = {
    name: "coredns"
    version: "1.11.1"
    hostname: "dns-server"
    etc_corefile: "/etc/coredns/Corefile"
    nameservers: [
        {ns_ip: "8.8.8.8"},
        {ns_ip: "8.8.4.4"}
    ]
    domains_search: "cluster.local"
    entries: [
        {
            domain: "."
            port: 53
            forward: {
                source: "."
                forward_ip: "8.8.8.8"
            }
            use_log: true
            use_errors: true
            use_cache: true
        }
    ]
}
```

### Production DNS Server
```kcl
coredns: COREDNS = {
    name: "coredns"
    version: "1.11.1"
    hostname: "production-dns"
    etc_corefile: "/etc/coredns/Corefile"
    nameservers: [
        {ns_ip: "1.1.1.1"},
        {ns_ip: "1.0.0.1"},
        {ns_ip: "8.8.8.8"}
    ]
    domains_search: "company.com cluster.local"
    entries: [
        {
            domain: "company.com"
            port: 53
            file: "/etc/coredns/company.com.db"
            records: [
                {
                    name: "www"
                    ttl: 300
                    rectype: "A"
                    target_ip: "203.0.113.10"
                    comment: "Main website"
                },
                {
                    name: "api"
                    ttl: 300
                    rectype: "A"
                    target_ip: "203.0.113.20"
                    comment: "API server"
                },
                {
                    name: "mail"
                    ttl: 300
                    rectype: "MX"
                    value: "10 mail.company.com"
                    comment: "Mail server"
                }
            ]
            use_log: true
            use_errors: true
            use_cache: true
        },
        {
            domain: "."
            port: 53
            forward: {
                source: "."
                forward_ip: "1.1.1.1"
            }
            use_log: true
            use_errors: true
            use_cache: true
        }
    ]
}
```

### Kubernetes DNS Configuration
```kcl
coredns: COREDNS = {
    name: "coredns"
    version: "1.11.1"
    hostname: "k8s-dns"
    etc_corefile: "/etc/coredns/Corefile"
    nameservers: [
        {ns_ip: "8.8.8.8"},
        {ns_ip: "8.8.4.4"}
    ]
    domains_search: "cluster.local svc.cluster.local"
    entries: [
        {
            domain: "cluster.local"
            port: 53
            use_log: true
            use_errors: true
            use_cache: true
            etcd_cluster_name: "kubernetes"
        },
        {
            domain: "in-addr.arpa"
            port: 53
            use_log: true
            use_errors: true
            use_cache: true
        },
        {
            domain: "ip6.arpa"
            port: 53
            use_log: true
            use_errors: true
            use_cache: true
        },
        {
            domain: "."
            port: 53
            forward: {
                source: "."
                forward_ip: "8.8.8.8"
            }
            use_log: true
            use_errors: true
            use_cache: true
        }
    ]
}
```

### Multi-Zone Configuration
```kcl
coredns: COREDNS = {
    name: "coredns"
    version: "1.11.1"
    hostname: "multi-zone-dns"
    etc_corefile: "/etc/coredns/Corefile"
    nameservers: [
        {ns_ip: "1.1.1.1"},
        {ns_ip: "8.8.8.8"}
    ]
    domains_search: "internal.company.com external.company.com"
    entries: [
        {
            domain: "internal.company.com"
            port: 53
            file: "/etc/coredns/internal.db"
            records: [
                {
                    name: "db1"
                    ttl: 300
                    rectype: "A"
                    target_ip: "10.0.1.100"
                },
                {
                    name: "app1"
                    ttl: 300
                    rectype: "A"
                    target_ip: "10.0.1.200"
                },
                {
                    name: "load-balancer"
                    ttl: 60
                    rectype: "A"
                    target_ip: "10.0.1.10"
                }
            ]
            use_log: true
            use_errors: true
            use_cache: true
        },
        {
            domain: "external.company.com"
            port: 53
            file: "/etc/coredns/external.db"
            records: [
                {
                    name: "www"
                    ttl: 3600
                    rectype: "CNAME"
                    value: "cdn.cloudflare.com"
                },
                {
                    name: "blog"
                    ttl: 300
                    rectype: "A"
                    target_ip: "203.0.113.50"
                }
            ]
            use_log: true
            use_errors: true
            use_cache: true
        }
    ]
}
```

### High-Availability Configuration
```kcl
coredns: COREDNS = {
    name: "coredns"
    version: "1.11.1"
    hostname: "ha-dns-primary"
    etc_corefile: "/etc/coredns/Corefile"
    nameservers: [
        {ns_ip: "1.1.1.1"},
        {ns_ip: "1.0.0.1"},
        {ns_ip: "8.8.8.8"},
        {ns_ip: "8.8.4.4"}
    ]
    domains_search: "company.com"
    entries: [
        {
            domain: "company.com"
            port: 53
            file: "/etc/coredns/company.com.db"
            records: [
                {
                    name: "@"
                    ttl: 300
                    rectype: "SOA"
                    value: "ns1.company.com. admin.company.com. 2024010101 3600 1800 604800 86400"
                },
                {
                    name: "@"
                    ttl: 300
                    rectype: "NS"
                    value: "ns1.company.com."
                },
                {
                    name: "@"
                    ttl: 300
                    rectype: "NS"
                    value: "ns2.company.com."
                },
                {
                    name: "ns1"
                    ttl: 300
                    rectype: "A"
                    target_ip: "203.0.113.10"
                },
                {
                    name: "ns2"
                    ttl: 300
                    rectype: "A"
                    target_ip: "203.0.113.11"
                }
            ]
            use_log: true
            use_errors: true
            use_cache: true
        }
    ]
}
```

## Usage

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

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

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

### Service Management
```bash
# Check CoreDNS status
systemctl status coredns

# Start/stop CoreDNS
systemctl start coredns
systemctl stop coredns
systemctl restart coredns

# View CoreDNS logs
journalctl -u coredns -f

# Check CoreDNS version
coredns -version
```

### DNS Testing
```bash
# Test DNS resolution
dig @localhost google.com
nslookup google.com localhost

# Test specific record types
dig @localhost company.com MX
dig @localhost company.com NS
dig @localhost company.com SOA

# Test reverse DNS
dig @localhost -x 8.8.8.8

# Performance testing
drill @localhost google.com
```

### Configuration Management
```bash
# Validate Corefile syntax
coredns -conf /etc/coredns/Corefile -dry

# Check loaded plugins
coredns -plugins

# Reload configuration (if enabled)
systemctl reload coredns

# View current configuration
cat /etc/coredns/Corefile
```

### Zone File Management
```bash
# Check zone file syntax
named-checkzone company.com /etc/coredns/company.com.db

# View zone records
cat /etc/coredns/company.com.db

# Update zone file
sudo vi /etc/coredns/company.com.db
sudo systemctl reload coredns
```

### Monitoring and Debugging
```bash
# Check DNS metrics (if Prometheus plugin enabled)
curl http://localhost:9153/metrics

# Debug DNS queries
tail -f /var/log/coredns/query.log

# Check plugin status
coredns -conf /etc/coredns/Corefile -plugins

# Network troubleshooting
netstat -tlnp | grep :53
ss -tulpn | grep :53
```

## Architecture

### System Architecture
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   DNS Clients   │────│   CoreDNS        │────│   Backends      │
│                 │    │                  │    │                 │
│ • Applications  │    │ • Plugin Chain   │    │ • Zone Files    │
│ • Services      │────│ • Query Router   │────│ • Etcd          │
│ • Resolvers     │    │ • Cache Layer    │    │ • External DNS  │
│ • Load Balancer │    │ • Health Checks  │    │ • Databases     │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Plugin Chain Architecture
```
┌─────────────────────────────────────────────────────────────┐
│                      DNS Query Flow                        │
├─────────────────────────────────────────────────────────────┤
│  Input Plugin      │  Processing Plugins │  Output Plugin   │
│                    │                     │                  │
│ • bind             │ • cache             │ • forward        │
│ • health           │ • rewrite           │ • file           │
│ • ready            │ • template          │ • auto           │
│ • prometheus       │ • loadbalance       │ • etcd           │
│ • log              │ • dnssec            │ • kubernetes     │
├─────────────────────────────────────────────────────────────┤
│                    Error Handling                          │
│                                                             │
│ • errors           • whoami            • debug             │
│ • trace            • chaos             • reload            │
└─────────────────────────────────────────────────────────────┘
```

### File Structure
```
/etc/coredns/              # Configuration directory
├── Corefile               # Main configuration file
├── company.com.db         # Zone files
├── internal.db            # Internal zone file
└── external.db            # External zone file

/var/lib/coredns/          # Data directory
├── cache/                 # DNS cache data
├── zones/                 # Dynamic zone data
└── logs/                  # Log files

/var/log/coredns/          # Log directory
├── query.log              # Query logs
├── error.log              # Error logs
└── access.log             # Access logs
```

## Supported Operating Systems

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

## System Requirements

### Minimum Requirements
- **RAM**: 512MB (1GB+ recommended)
- **Storage**: 5GB (10GB+ for extensive logging)
- **CPU**: 1 core (2+ cores recommended)
- **Network**: UDP/TCP port 53 access

### Production Requirements
- **RAM**: 2GB+ (depends on cache size and query volume)
- **Storage**: 20GB+ SSD
- **CPU**: 2+ cores
- **Network**: High bandwidth, low latency

### Network Requirements
- **Port 53** - DNS queries (UDP/TCP)
- **Port 9153** - Metrics endpoint (optional)
- **Port 8080** - Health check endpoint (optional)
- **Firewall** - Allow inbound DNS traffic

## Troubleshooting

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

# View detailed logs
journalctl -u coredns --no-pager -l

# Check configuration syntax
coredns -conf /etc/coredns/Corefile -dry

# Test plugin loading
coredns -conf /etc/coredns/Corefile -plugins
```

### DNS Resolution Issues
```bash
# Test local resolution
dig @127.0.0.1 google.com

# Check upstream connectivity
dig @8.8.8.8 google.com

# Test specific zones
dig @localhost company.com SOA

# Debug query path
dig @localhost +trace google.com
```

### Performance Issues
```bash
# Check resource usage
top -p $(pgrep coredns)
ps aux | grep coredns

# Monitor DNS queries
tail -f /var/log/coredns/query.log

# Check cache hit ratio
curl http://localhost:9153/metrics | grep coredns_cache

# Network performance
iftop -i eth0 -f "port 53"
```

### Configuration Issues
```bash
# Validate Corefile
coredns -conf /etc/coredns/Corefile -dry

# Check zone file syntax
named-checkzone company.com /etc/coredns/company.com.db

# Test configuration reload
sudo systemctl reload coredns

# Check file permissions
ls -la /etc/coredns/
```

### Network Connectivity
```bash
# Check port binding
netstat -tlnp | grep :53
ss -tulpn | grep coredns

# Test external connectivity
telnet 8.8.8.8 53

# Check firewall rules
sudo iptables -L | grep 53
sudo ufw status | grep 53
```

## Security Considerations

### DNS Security
- **DNSSEC Support** - Enable DNS Security Extensions
- **Query Filtering** - Filter malicious or unwanted domains
- **Rate Limiting** - Prevent DNS amplification attacks
- **Access Control** - Restrict query sources when appropriate

### Network Security
- **Firewall Rules** - Limit DNS port access to necessary sources
- **TLS Encryption** - Use DNS over TLS for sensitive environments
- **Monitoring** - Monitor for unusual query patterns
- **Logging** - Comprehensive query and error logging

### Operational Security
- **Regular Updates** - Keep CoreDNS updated to latest version
- **Configuration Validation** - Validate configuration changes
- **Backup** - Regular backup of zone files and configuration
- **Access Control** - Limit administrative access

### Zone Security
- **Zone Transfer** - Secure zone transfer configuration
- **Dynamic Updates** - Secure dynamic DNS updates
- **Key Management** - Proper DNSSEC key management
- **Audit Trail** - Maintain audit logs for zone changes

## Performance Optimization

### Query Performance
- **Cache Configuration** - Optimize cache size and TTL values
- **Upstream Selection** - Choose fast, reliable upstream servers
- **Load Balancing** - Distribute queries across multiple upstreams
- **Query Optimization** - Minimize query response times

### System Performance
- **Memory Allocation** - Allocate sufficient memory for cache
- **CPU Optimization** - Use appropriate number of worker threads
- **Storage Performance** - Use fast storage for zone files
- **Network Optimization** - Optimize network buffer sizes

### Monitoring Optimization
- **Selective Logging** - Log only necessary information
- **Metric Collection** - Monitor key performance indicators
- **Alert Configuration** - Set up appropriate alerting thresholds
- **Resource Monitoring** - Monitor system resource usage

## Integration Examples

### Prometheus Monitoring
```yaml
# Corefile configuration for metrics
. {
    prometheus localhost:9153
    errors
    log
    cache 30
    forward . 8.8.8.8 8.8.4.4
}
```

### Kubernetes Service Discovery
```yaml
# Kubernetes CoreDNS configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        errors
        health {
            lameduck 5s
        }
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {
            pods insecure
            fallthrough in-addr.arpa ip6.arpa
            ttl 30
        }
        prometheus :9153
        forward . /etc/resolv.conf
        cache 30
        loop
        reload
        loadbalance
    }
```

### Etcd Backend Integration
```yaml
# Corefile with etcd backend
example.com {
    etcd {
        stubzones
        path /coredns
        endpoint http://localhost:2379
    }
    cache 160
    loadbalance
    prometheus
    errors
    log
}
```

## Resources

- **Official Documentation**: [coredns.io](https://coredns.io/)
- **GitHub Repository**: [coredns/coredns](https://github.com/coredns/coredns)
- **Plugin Documentation**: [coredns.io/plugins](https://coredns.io/plugins/)
- **Community**: [coredns.slack.com](https://coredns.slack.com)
- **CNCF Project**: [cncf.io/projects/coredns](https://www.cncf.io/projects/coredns/)