File size: 9,346 Bytes
fd357f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/bin/bash

# 30-Minute Server Migration Plan for DTO Framework
# Emergency migration protocol for rapid server transitions
# Prometheus - Head of Data Migration & Transfer Operations

set -euo pipefail

# Load .env file
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DTO_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
ENV_FILE="$DTO_ROOT/.env"

if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | xargs)
    echo "βœ… Loaded .env file from $ENV_FILE"
else
    echo "❌ .env file not found at $ENV_FILE"
    exit 1
fi

# Configuration
MIGRATION_LOG="/tmp/migration_$(date +%Y%m%d_%H%M%S).log"
BACKUP_DIR="/tmp/migration_backup_$(date +%Y%m%d_%H%M%S)"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$MIGRATION_LOG"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" | tee -a "$MIGRATION_LOG" >&2
}

warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "$MIGRATION_LOG"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1" | tee -a "$MIGRATION_LOG"
}

# Phase 1: Pre-Migration Preparation (Minutes 0-5)
pre_migration_prep() {
    log "=== PHASE 1: Pre-Migration Preparation ==="
    
    # Create backup directory
    mkdir -p "$BACKUP_DIR"
    
    # Verify Hugging Face authentication
    log "Verifying Hugging Face authentication"
    python3 -c "
from huggingface_hub import HfApi
try:
    api = HfApi(token='$HF_TOKEN')
    user = api.whoami()
    print(f'βœ… Authenticated as: {user[\"name\"]}')
    print(f'βœ… Organization: {user.get(\"orgs\", [{}])[0].get(\"name\", \"Personal\")}')
except Exception as e:
    print(f'❌ Authentication failed: {e}')
    exit(1)
" | tee -a "$MIGRATION_LOG"
    
    # Check repository access
    log "Checking repository access"
    for repo in "$HF_REPO_MODELS" "$HF_REPO_DATASETS" "$HF_REPO_ARTIFACTS"; do
        python3 -c "
from huggingface_hub import HfApi, RepositoryNotFoundError

try:
    api = HfApi(token='$HF_TOKEN')
    info = api.repo_info('$repo')
    print(f'βœ… Repository accessible: $repo ({info.size} bytes)')
except RepositoryNotFoundError:
    print(f'⚠️  Repository not found: $repo (will create)')
except Exception as e:
    print(f'❌ Error accessing $repo: {e}')
    exit(1)
" | tee -a "$MIGRATION_LOG"
    done
    
    # Create inventory of critical files
    log "Creating inventory of critical files"
    find /data/adaptai/aiml/02_models -type f -name "*.safetensors" -o -name "*.pt" -o -name "*.bin" | head -20 > "$BACKUP_DIR/critical_models.txt"
    find /data/adaptai/aiml/03_training -type f -name "*.parquet" -o -name "*.jsonl" -o -name "*.csv" | head -20 > "$BACKUP_DIR/critical_datasets.txt"
    
    log "Pre-migration preparation completed"
}

# Phase 2: Rapid Upload (Minutes 5-20)
rapid_upload() {
    log "=== PHASE 2: Rapid Upload to HF/Xet ==="
    
    # Upload models (highest priority)
    log "Uploading critical models..."
    python3 -c "
import os
from integrations.huggingface_client import HuggingFaceClient

client = HuggingFaceClient()
if not client.is_authenticated():
    print('❌ Not authenticated')
    exit(1)

# Upload most critical model files first
critical_files = []
for root, dirs, files in os.walk('/data/adaptai/aiml/02_models'):
    for file in files:
        if file.endswith(('.safetensors', '.pt', '.bin')):
            full_path = os.path.join(root, file)
            critical_files.append(full_path)
            if len(critical_files) >= 50:  # Limit for rapid upload
                break
    if len(critical_files) >= 50:
        break

for file_path in critical_files:
    rel_path = os.path.relpath(file_path, '/data/adaptai/aiml/02_models')
    print(f'πŸš€ UPLOADING: {rel_path}')
    success = client.upload_artifact(file_path, rel_path, '$HF_REPO_MODELS')
    if not success:
        print(f'❌ FAILED: {rel_path}')
        exit(1)

print('βœ… Critical models uploaded successfully')
" | tee -a "$MIGRATION_LOG"
    
    # Upload datasets
    log "Uploading critical datasets..."
    python3 -c "
import os
from integrations.huggingface_client import HuggingFaceClient

client = HuggingFaceClient()

# Upload critical dataset files
for root, dirs, files in os.walk('/data/adaptai/aiml/03_training'):
    for file in files:
        if file.endswith(('.parquet', '.jsonl')):
            full_path = os.path.join(root, file)
            rel_path = os.path.relpath(full_path, '/data/adaptai/aiml/03_training')
            print(f'πŸš€ UPLOADING: {rel_path}')
            success = client.upload_artifact(full_path, rel_path, '$HF_REPO_DATASETS')
            if not success:
                print(f'❌ FAILED: {rel_path}')
                exit(1)
            if len([f for f in os.listdir('/data/adaptai/aiml/03_training') if f.endswith(('.parquet', '.jsonl'))]) <= 10:
                break  # Stop after first 10 files for rapid migration

print('βœ… Critical datasets uploaded successfully')
" | tee -a "$MIGRATION_LOG"
    
    log "Rapid upload phase completed"
}

# Phase 3: Verification & Cleanup (Minutes 20-25)
verification_cleanup() {
    log "=== PHASE 3: Verification & Cleanup ==="
    
    # Verify uploads
    log "Verifying uploads..."
    python3 -c "
from huggingface_hub import HfApi

api = HfApi(token='$HF_TOKEN')

for repo in ['$HF_REPO_MODELS', '$HF_REPO_DATASETS']:
    try:
        info = api.repo_info(repo)
        print(f'βœ… {repo}: {len(info.siblings)} files, {info.size} bytes')
    except Exception as e:
        print(f'❌ Failed to verify {repo}: {e}')
        exit(1)
" | tee -a "$MIGRATION_LOG"
    
    # Create cleanup manifest
    log "Creating cleanup manifest..."
    find /data/adaptai/aiml/02_models -type f -name "*.safetensors" -o -name "*.pt" -o -name "*.bin" | head -50 > "$BACKUP_DIR/cleanup_manifest.txt"
    
    log "Verification completed - Ready for cleanup"
}

# Phase 4: Rapid Server Migration (Minutes 25-30)
rapid_migration() {
    log "=== PHASE 4: Rapid Server Migration ==="
    
    # Generate migration package
    log "Generating migration package..."
    MIGRATION_PACKAGE="/tmp/dto_migration_$TIMESTAMP.tar.gz"
    
    tar -czf "$MIGRATION_PACKAGE" \
        -C /data/adaptai/platform/dataops/dto \
        .env \
        integrations/ \
        scripts/ \
        dto_manifest.yaml \
        --exclude="*.pyc" --exclude="__pycache__"
    
    echo "βœ… Migration package created: $MIGRATION_PACKAGE ($(du -h $MIGRATION_PACKAGE | cut -f1))") | tee -a "$MIGRATION_LOG"
    
    # Create rapid setup script
    cat > "/tmp/rapid_setup.sh" << 'EOF'
#!/bin/bash
# Rapid DTO Framework Setup Script
# Extract and run on new server within 5 minutes

set -euo pipefail

# Extract migration package
tar -xzf $1 -C /tmp/dto_setup
cd /tmp/dto_setup

# Load environment
export $(grep -v '^#' .env | xargs)

# Install dependencies
pip install huggingface_hub hf-xet --upgrade

# Verify authentication
python3 -c "
from huggingface_hub import HfApi
try:
    api = HfApi(token='$HF_TOKEN')
    user = api.whoami()
    print(f'βœ… Authenticated as: {user[\"name\"]}')
except Exception as e:
    print(f'❌ Authentication failed: {e}')
    exit(1)
"

# Download critical assets
python3 -c "
from integrations.huggingface_client import HuggingFaceClient
client = HuggingFaceClient()

# Download most critical models
print('Downloading critical models...')
# Add specific file downloads here based on priority
"

echo "βœ… Rapid setup completed - DTO Framework ready"
EOF
    
    chmod +x "/tmp/rapid_setup.sh"
    
    log "Rapid migration preparation completed"
    log "Migration package: $MIGRATION_PACKAGE"
    log "Setup script: /tmp/rapid_setup.sh"
}

# Emergency cleanup function (use with caution)
emergency_cleanup() {
    log "=== EMERGENCY CLEANUP (IF SPACE CRITICAL) ==="
    warning "THIS WILL DELETE LOCAL COPIES AFTER UPLOAD VERIFICATION"
    
    # Only cleanup if we have successful uploads
    if [ -f "$BACKUP_DIR/cleanup_manifest.txt" ] && [ $(wc -l < "$BACKUP_DIR/cleanup_manifest.txt") -gt 0 ]; then
        log "Removing uploaded files..."
        while read -r file; do
            if [ -f "$file" ]; then
                rm -v "$file" | tee -a "$MIGRATION_LOG"
            fi
        done < "$BACKUP_DIR/cleanup_manifest.txt"
        
        log "Emergency cleanup completed"
        df -h /data | tee -a "$MIGRATION_LOG"
    else
        warning "No cleanup manifest found - skipping emergency cleanup"
    fi
}

# Main execution
main() {
    log "πŸš€ STARTING 30-MINUTE SERVER MIGRATION PLAN"
    log "Timestamp: $(date)"
    log "Migration log: $MIGRATION_LOG"
    log "Backup directory: $BACKUP_DIR"
    
    # Execute phases
    pre_migration_prep
    rapid_upload
    verification_cleanup
    rapid_migration
    
    # Only run emergency cleanup if explicitly requested
    if [ "${1:-}" = "--cleanup" ]; then
        emergency_cleanup
    fi
    
    log "βœ… 30-MINUTE MIGRATION PLAN COMPLETED SUCCESSFULLY"
    log "Next steps:"
    log "  1. Transfer migration package to new server"
    log "  2. Run: /tmp/rapid_setup.sh /path/to/migration_package.tar.gz"
    log "  3. Complete full uploads with upload_to_hf.sh"
    log "  4. Monitor new server deployment"
}

# Run main function
main "$@"