Loading
Loading
Ampere A1 هو معالج ARM عالي الأداء تقدمه Oracle مجاناً بـ 4 OCPUs و24 GB RAM.
ARM VMs تكون Out of Capacity أحياناً. الحل: جرّب مناطق مختلفة أو أوقات مختلفة.
ssh -i private_key ubuntu@IP_ADDRESS
import subprocess
import os
from dataclasses import dataclass, field
from typing import List, Dict, Optional
# ─── VM Configuration ──────────────────────────────────────
@dataclass
class ARMVMConfig:
name: str
ocpus: float
memory_gb: float
os_image: str = "Canonical-Ubuntu-22.04-aarch64"
boot_gb: int = 50
region: str = "us-ashburn-1"
shape: str = "VM.Standard.A1.Flex"
def validate(self) -> Dict:
"""تحقق من حدود Always Free"""
errors = []
if self.ocpus > 4:
errors.append(f"OCPUs {self.ocpus} > 4 (حد Always Free)")
if self.memory_gb > 24:
errors.append(f"RAM {self.memory_gb}GB > 24GB (حد Always Free)")
if self.boot_gb > 200:
errors.append(f"Boot {self.boot_gb}GB > 200GB")
return {"valid": len(errors) == 0, "errors": errors}
# ─── محاكاة OCI Compute ────────────────────────────────────
class OCICompute:
def __init__(self):
self._instances: Dict[str, Dict] = {}
self._capacity_regions = ["us-ashburn-1", "eu-frankfurt-1"]
def launch(self, cfg: ARMVMConfig, ssh_pub_key: str) -> Dict:
result = cfg.validate()
if not result["valid"]:
return {"success": False, "error": result["errors"]}
if cfg.region not in self._capacity_regions:
return {"success": False, "error": f"Out of Capacity في {cfg.region} — جرّب منطقة أخرى"}
inst = {
"name": cfg.name,
"shape": cfg.shape,
"ocpus": cfg.ocpus,
"memory_gb": cfg.memory_gb,
"region": cfg.region,
"state": "PROVISIONING",
"public_ip": f"152.67.{hash(cfg.name)%200+1}.{hash(cfg.name)%254+1}",
"os": cfg.os_image,
}
self._instances[cfg.name] = inst
return {"success": True, "instance": inst}
def wait_running(self, name: str) -> str:
if name in self._instances:
self._instances[name]["state"] = "RUNNING"
return "RUNNING"
class FirewallManager:
"""إدارة Security List / NSG"""
def __init__(self):
self.rules: List[Dict] = []
def open_port(self, port: int, protocol: str = "TCP", source: str = "0.0.0.0/0"):
self.rules.append({"port": port, "proto": protocol, "source": source})
print(f" 🔓 Port {port}/{protocol} ← {source}")
def open_ssh(self):
self.open_port(22, "TCP", "YOUR_IP/32") # SSH من IP محدد فقط
def show(self):
print(f"\n قواعد Firewall ({len(self.rules)}):")
for r in self.rules:
print(f" • Port {r['port']}/{r['proto']} ← {r['source']}")
# ─── إعداد Setup Script ────────────────────────────────────
SETUP_SCRIPT = """#!/bin/bash
# إعداد VM ARM لتشغيل AI API
# تحديث النظام
sudo apt update && sudo apt upgrade -y
# Python 3.11 + pip
sudo apt install -y python3.11 python3-pip python3.11-venv
# إنشاء بيئة افتراضية
python3.11 -m venv /opt/ai-env
source /opt/ai-env/bin/activate
# تثبيت المكتبات
pip install fastapi uvicorn anthropic python-dotenv
# Nginx كـ Reverse Proxy
sudo apt install -y nginx certbot python3-certbot-nginx
echo "✅ الإعداد مكتمل!"
"""
# ─── تشغيل المحاكاة ────────────────────────────────────────
print("🔴 إنشاء VM ARM مجانية على Oracle Cloud:")
print("=" * 55)
compute = OCICompute()
firewall = FirewallManager()
# إنشاء VM
print("\n1️⃣ إنشاء VM ARM (2 OCPU + 12 GB RAM):")
cfg = ARMVMConfig(name="ai-server-01", ocpus=2, memory_gb=12)
result = compute.launch(cfg, "ssh-rsa AAAAB3NzaC1yc2E...")
if result["success"]:
inst = result["instance"]
print(f" ✅ VM بدأ الإنشاء: {inst['name']}")
print(f" Region : {inst['region']}")
cpu_s = f"{inst['ocpus']} OCPUs"
ram_s = f"{inst['memory_gb']} GB"
print(f" Compute: {cpu_s} / {ram_s}")
state = compute.wait_running(inst["name"])
print(f" State : {state}")
print(f" IP : {inst['public_ip']}")
else:
print(f" ❌ {result['error']}")
# Firewall
print(f"\n2️⃣ إعداد Security Rules:")
firewall.open_ssh()
firewall.open_port(80, "TCP", "0.0.0.0/0") # HTTP
firewall.open_port(443, "TCP", "0.0.0.0/0") # HTTPS
firewall.open_port(8080, "TCP", "0.0.0.0/0") # FastAPI
firewall.show()
# Setup Script
print(f"\n3️⃣ Setup Script:")
print(f" # انسخ الـ Script إلى الـ VM:")
if result["success"]:
ip = result["instance"]["public_ip"]
print(f" $ scp setup.sh ubuntu@{ip}:~/")
print(f" $ ssh ubuntu@{ip} 'bash setup.sh'")
print()
for line in SETUP_SCRIPT.strip().split("\n")[:8]:
print(f" {line}")
print(f" ...")
# Validate Free Tier Limits
print(f"\n4️⃣ التحقق من حدود Always Free:")
test_cases = [
ARMVMConfig("vm1", ocpus=2, memory_gb=12),
ARMVMConfig("vm2", ocpus=3, memory_gb=18),
ARMVMConfig("vm3", ocpus=5, memory_gb=30), # تجاوز الحد
]
for tc in test_cases:
v = tc.validate()
icon = "✅" if v["valid"] else "❌"
cpu_s = f"{tc.ocpus} OCPUs"
ram_s = f"{tc.memory_gb} GB"
print(f" {icon} {tc.name}: {cpu_s} + {ram_s}")
if not v["valid"]:
for e in v["errors"]:
print(f" ⚠️ {e}")
print(f"\n✅ VM ARM جاهزة للاستخدام!")