# Legacy System Migration Example

Migrate legacy infrastructure to Provisioning platform with zero downtime.

## Migration Strategy

```text
Phase 1: Assessment
├─ Inventory legacy resources
├─ Map dependencies
├─ Identify critical services
└─ Plan migration sequence

Phase 2: Parallel Setup
├─ Deploy Provisioning infrastructure
├─ Configure replication
├─ Test failover procedures
└─ Train team

Phase 3: Gradual Cutover
├─ Route 10% traffic to new infrastructure
├─ Monitor and validate
├─ Increase routing percentage (10→25→50→75→90→100%)
├─ Each stage: 24 hours minimum
└─ Maintain rollback capability

Phase 4: Cleanup
├─ Decommission legacy infrastructure
├─ Archive configurations
├─ Update documentation
└─ Close support tickets
```

## Phase 1: Assessment

### Inventory Existing Infrastructure

```nushell
def assess-legacy-infrastructure [] {
    print "Assessing legacy infrastructure..."

    # 1. Document compute resources
    let compute = (
        provisioning inventory compute \
            --location "data-center-1" \
            --include-detailed-specs
    )

    print $"Found ($compute | length) compute resources"
    $compute | each { | resource |
        print $"  - ($resource.hostname): ($resource.cpu)C, ($resource.memory)GB, ($resource.os)"
    }

    # 2. Document storage and databases
    let storage = (
        provisioning inventory storage \
            --location "data-center-1"
    )

    let databases = (
        provisioning inventory databases \
            --location "data-center-1"
    )

    print $"Found ($storage | length) storage systems"
    print $"Found ($databases | length) databases"

    # 3. Map network topology
    let networks = (
        provisioning inventory networks \
            --location "data-center-1"
    )

    print ""
    print "Network topology:"
    $networks | each { | network |
        print $"  - ($network.name): ($network.cidr)"
        $network.subnets | each { | subnet |
            print $"    - ($subnet.name): ($subnet.cidr) [$subnet.hosts hosts]"
        }
    }

    # 4. Export configuration
    provisioning export legacy-config \
        --format nickel \
        --output legacy-infrastructure.ncl
}
```

### Dependency Mapping

```nushell
def map-service-dependencies [] {
    print "Mapping service dependencies..."

    let services = [
        "web-app",
        "api-backend",
        "database",
        "cache",
        "message-queue"
    ]

    let dependencies = (
        $services | each { | service |
            {
                service: $service,
                depends_on: (
                    provisioning dependencies analyze \
                        --service $service \
                        --location "data-center-1"
                )
            }
        }
    )

    print "Dependency Graph:"
    $dependencies | each { | dep |
        print $"($dep.service)"
        $dep.depends_on | each { | upstream |
            print $"  → requires: ($upstream)"
        }
    }

    export-mermaid-diagram --dependencies $dependencies
}
```

## Phase 2: Parallel Setup

### Deploy Mirror Infrastructure

```nushell
def deploy-mirror-infrastructure [--config: string] {
    print "Deploying mirror infrastructure in Provisioning..."

    # 1. Create workspace
    let workspace = (
        provisioning workspace create \
            --name "legacy-migration" \
            --template "multi-tier-app"
    )

    # 2. Deploy infrastructure from legacy-infrastructure.ncl
    provisioning infra apply \
        --config $config \
        --workspace $workspace.id \
        --auto-approve

    # 3. Verify all resources created
    let resources = (
        provisioning resource list \
            --workspace $workspace.id
    )

    print $"✓ Created ($resources | length) resources"

    # 4. Initialize databases
    provisioning database init \
        --workspace $workspace.id \
        --from-backup "legacy-full-backup.sql"

    print "✓ Databases initialized from legacy backup"
}
```

### Setup Replication

```nushell
def setup-replication [] {
    print "Setting up data replication..."

    # Database replication (continuous)
    provisioning replication create \
        --source "legacy-db.datacenter1" \
        --target "new-db.provisioning" \
        --replication-type "streaming" \
        --lag-threshold 1000ms

    # File synchronization (periodic)
    provisioning sync create \
        --source "/legacy/data" \
        --target "s3://provisioning-migration/data" \
        --schedule "every 5m" \
        --delete-orphaned-files false

    print "✓ Replication configured"

    # Monitor replication lag
    provisioning replication monitor \
        --source-target "legacy-db→new-db" \
        --alert-threshold 10000ms
}
```

## Phase 3: Gradual Cutover

### Traffic Shifting (Canary)

```nushell
def cutover-gradual [] {
    let stages = [
        { percentage: 5, duration_hours: 24 },
        { percentage: 10, duration_hours: 24 },
        { percentage: 25, duration_hours: 24 },
        { percentage: 50, duration_hours: 24 },
        { percentage: 75, duration_hours: 24 },
        { percentage: 100, duration_hours: 12 }
    ]

    $stages | each { | stage |
        print ""
        print $"Stage: ($stage.percentage)% traffic to new infrastructure"
        print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

        # 1. Update load balancer weights
        provisioning lb update-weights \
            --legacy-target 0 \
            --new-target 1 \
            --legacy-percentage ($100 - $stage.percentage) \
            --new-percentage $stage.percentage

        print $"✓ Updated traffic: ($stage.percentage)% → new infrastructure"

        # 2. Monitor metrics
        let start_time = (date now)
        let end_time = (date now | date add $"($stage.duration_hours)h")

        while (date now) < $end_time {
            let metrics = (
                provisioning metrics get \
                    --window 5m
            )

            let error_rate = $metrics.error_rate
            let latency_p99 = $metrics.latency_p99

            if $error_rate > 1.0 {
                print "⚠️  High error rate detected ($error_rate)%"
                print "Rolling back traffic shift..."

                provisioning lb rollback-weights

                print "✗ Rollback complete, aborting cutover"
                return 1
            }

            if $latency_p99 > 500 {
                print "⚠️  High latency detected ($latency_p99)ms"
            }

            print $"✓ Stage ($stage.percentage)%: Error rate ($error_rate)%, Latency P99 ($latency_p99)ms"
            sleep 5m
        }

        print $"✓ Stage ($stage.percentage)% completed successfully"
    }

    print ""
    print "✓ Cutover complete - 100% traffic on new infrastructure"
}
```

### Health Checks and Validation

```nushell
def validate-cutover-health [] {
    print "Validating new infrastructure health..."

    let checks = [
        {
            name: "api-endpoints",
            test: { endpoint: "/health", expected_status: 200 }
        },
        {
            name: "database-connectivity",
            test: { query: "SELECT 1", expected_result: "1" }
        },
        {
            name: "cache-functionality",
            test: { command: "SET key value", expected_result: "OK" }
        },
        {
            name: "message-queue-latency",
            test: { metric: "queue_latency_ms", threshold: 100 }
        }
    ]

    $checks | each { | check |
        let result = (
            provisioning test execute \
                --test-name $check.name \
                --config $check.test
        )

        if $result.status == "passed" {
            print $"✓ ($check.name): PASSED"
        } else {
            print $"✗ ($check.name): FAILED"
            return 1
        }
    }

    print ""
    print "✓ All health checks passed"
}
```

## Phase 4: Cleanup

### Decommission Legacy Infrastructure

```nushell
def decommission-legacy [] {
    print "Decommissioning legacy infrastructure..."

    # 1. Final data backup
    let final_backup = (
        provisioning backup create \
            --source "legacy-infrastructure" \
            --encryption hybrid \
            --retention-years 7
    )

    print $"✓ Final backup created: ($final_backup.id)"

    # 2. Archive configurations
    provisioning archive create \
        --source "legacy-configs" \
        --destination "s3://archive/legacy-2025-01" \
        --include ["*.conf", "*.yaml", "*.xml", "*.ini"]

    print "✓ Configurations archived"

    # 3. Shutdown services (in reverse dependency order)
    let shutdown_sequence = [
        "web-app",
        "api-backend",
        "message-queue",
        "cache",
        "database"
    ]

    $shutdown_sequence | each { | service |
        print $"Shutting down ($service)..."
        provisioning service shutdown --name $service

        # Verify shutdown
        sleep 30s
        let status = (provisioning service status --name $service)
        print $"  Status: ($status.status)"
    }

    # 4. Deallocate resources
    provisioning resource deallocate \
        --location "data-center-1" \
        --confirm

    print "✓ Resources deallocated"

    # 5. Update DNS to remove legacy references
    provisioning dns cleanup --location "data-center-1"

    print "✓ Decommissioning complete"
}
```

## Rollback Plan

If issues occur at any stage:

```nushell
def rollback-migration [] {
    print "⚠️  Rolling back migration..."

    # 1. Revert all traffic to legacy infrastructure
    provisioning lb update-weights \
        --legacy-target 1 \
        --new-target 0

    # 2. Stop replication
    provisioning replication stop \
        --source "legacy-db" \
        --target "new-db"

    # 3. Verify legacy infrastructure
    provisioning health check --location "data-center-1"

    # 4. Notify team
    provisioning notification send \
        --channel "slack" \
        --message "Migration rolled back - investigating issues"

    print "✓ Rollback complete - all traffic returned to legacy infrastructure"
}
```

## Migration Timeline

```text
Week 1: Assessment and Planning
├─ Day 1: Inventory legacy infrastructure
├─ Day 2-3: Map dependencies and criticality
├─ Day 4-5: Plan migration sequence
└─ Day 6-7: Training and preparation

Week 2-3: Parallel Setup and Replication
├─ Deploy new infrastructure
├─ Initialize databases
├─ Setup replication
└─ Perform failover drills

Week 4-5: Gradual Cutover (5% increments)
├─ 5% traffic shift (24h monitoring)
├─ 10% traffic shift (24h monitoring)
├─ 25% traffic shift (24h monitoring)
├─ 50% traffic shift (24h monitoring)
├─ 75% traffic shift (24h monitoring)
└─ 100% traffic shift (12h monitoring)

Week 6: Cleanup
├─ Final backups
├─ Decommission legacy
├─ Update documentation
└─ Close migration project
```

## See Also

- [Disaster Recovery Guide](../guides/disaster-recovery.md)
- [Blue-Green Deployments](../operations/deployment-strategies.md)
- [Monitoring and Alerting](../operations/monitoring.md)
