161 lines
5.2 KiB
Python
Executable File
161 lines
5.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Create Gitea PR from AI suggestions using existing gitea_integration module
|
|
"""
|
|
import json
|
|
import yaml
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
from gitea_integration import GiteaIntegration
|
|
|
|
def get_latest_pr_file():
|
|
"""Find the most recent PR file from AI suggestions"""
|
|
pr_dir = Path('/shared/ai-gitops/pending_prs')
|
|
pr_files = sorted(pr_dir.glob('*.json'), key=lambda x: x.stat().st_mtime, reverse=True)
|
|
|
|
if pr_files:
|
|
return pr_files[0]
|
|
return None
|
|
|
|
def main():
|
|
"""Create PR from latest AI suggestions"""
|
|
print("="*60)
|
|
print(" CREATE GITEA PR FROM AI SUGGESTIONS")
|
|
print("="*60)
|
|
|
|
# Load config
|
|
with open('/home/netops/orchestrator/config.yaml', 'r') as f:
|
|
config = yaml.safe_load(f)
|
|
|
|
# Initialize Gitea integration
|
|
gitea = GiteaIntegration(config['gitea'])
|
|
|
|
# Get latest PR file
|
|
pr_file = get_latest_pr_file()
|
|
if not pr_file:
|
|
print("❌ No pending PR files found")
|
|
print(" Run: python3 run_pipeline.py --skip-netflow")
|
|
return
|
|
|
|
print(f"📄 Found PR file: {pr_file.name}")
|
|
|
|
# Load PR data
|
|
with open(pr_file, 'r') as f:
|
|
pr_data = json.load(f)
|
|
|
|
# Extract details
|
|
suggestions = pr_data.get('suggestions', '')
|
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
|
|
# Show preview
|
|
print("\n📋 PR Preview:")
|
|
print(f" Title: {pr_data.get('title', 'AI Network Optimization')}")
|
|
print(f" Model: {pr_data.get('model', 'llama2:13b')}")
|
|
print(f" Feedback aware: {pr_data.get('feedback_aware', False)}")
|
|
print(f" Config lines: {len(suggestions.split(chr(10)))}")
|
|
|
|
# Show first few lines of suggestions
|
|
print("\n📝 First few suggestions:")
|
|
for line in suggestions.split('\n')[:5]:
|
|
if line.strip():
|
|
print(f" {line}")
|
|
print(" ...")
|
|
|
|
# Confirm creation
|
|
print(f"\n❓ Create PR from these AI suggestions? (y/n): ", end="")
|
|
if input().lower() != 'y':
|
|
print("❌ Cancelled")
|
|
return
|
|
|
|
# Create PR title and description
|
|
pr_title = f"AI Network Optimization - {timestamp}"
|
|
pr_description = f"""## 🤖 AI-Generated Network Configuration
|
|
|
|
**Generated:** {timestamp}
|
|
**Model:** {pr_data.get('model', 'llama2:13b')}
|
|
**Feedback Learning:** {'✅ Applied' if pr_data.get('feedback_aware') else '❌ Not applied'}
|
|
|
|
### 📊 Security Compliance Check:
|
|
- ✅ No source-address any
|
|
- ✅ No destination-address any
|
|
- ✅ No application any
|
|
- ✅ Logging enabled
|
|
- ✅ Address-sets defined
|
|
|
|
### 📋 Configuration Summary:
|
|
This AI-generated configuration includes:
|
|
- Address-set definitions for network segmentation
|
|
- Security policies with specific source/destination
|
|
- Logging enabled for audit compliance
|
|
- No any/any/any rules (security best practice)
|
|
|
|
### 🔍 Changes Overview:
|
|
Total configuration lines: {len(suggestions.split(chr(10)))}
|
|
|
|
### 📝 Full Configuration:
|
|
```junos
|
|
{suggestions}
|
|
```
|
|
|
|
### ✅ Review Checklist:
|
|
- [ ] Verify address-sets match network architecture
|
|
- [ ] Confirm zone assignments are correct
|
|
- [ ] Check application definitions
|
|
- [ ] Validate logging configuration
|
|
- [ ] Test in lab environment first
|
|
|
|
---
|
|
*Generated by AI Network Automation System*
|
|
*Feedback learning from {pr_data.get('feedback_count', 5)} previous reviews*
|
|
"""
|
|
|
|
# Create the PR
|
|
print("\n📤 Creating PR in Gitea...")
|
|
try:
|
|
pr_info = gitea.create_pr_with_config(
|
|
srx_config=suggestions,
|
|
title=pr_title,
|
|
description=pr_description
|
|
)
|
|
|
|
if pr_info:
|
|
print(f"\n✅ SUCCESS! Created PR #{pr_info['number']}")
|
|
print(f" Title: {pr_info.get('title')}")
|
|
print(f" URL: {pr_info.get('url', config['gitea']['url'] + '/' + config['gitea']['repo'] + '/pulls/' + str(pr_info['number']))}")
|
|
print(f"\n📋 Next steps:")
|
|
print(f" 1. Review PR at: {pr_info.get('url', 'Gitea URL')}")
|
|
print(f" 2. Test configuration in lab")
|
|
print(f" 3. Approve or provide feedback")
|
|
print(f" 4. If approved, run: python3 deploy_approved.py")
|
|
|
|
# Save PR tracking info
|
|
tracking_file = Path('/shared/ai-gitops/pr_tracking') / f"pr_{pr_info['number']}_created.json"
|
|
tracking_file.parent.mkdir(exist_ok=True)
|
|
with open(tracking_file, 'w') as f:
|
|
json.dump({
|
|
'pr_number': pr_info['number'],
|
|
'created_at': datetime.now().isoformat(),
|
|
'pr_file': str(pr_file),
|
|
'title': pr_title,
|
|
'model': pr_data.get('model'),
|
|
'feedback_aware': pr_data.get('feedback_aware')
|
|
}, f, indent=2)
|
|
|
|
return True
|
|
else:
|
|
print("❌ Failed to create PR")
|
|
print(" Check logs for details")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error creating PR: {e}")
|
|
|
|
# Try to get more details
|
|
import traceback
|
|
print("\n🔍 Debug information:")
|
|
print(traceback.format_exc())
|
|
return False
|
|
|
|
if __name__ == "__main__":
|
|
main()
|