Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

setup_all.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. #!/usr/bin/env python3
  2. import socket
  3. import subprocess
  4. import sys
  5. import time
  6. from pathlib import Path
  7. from common import Logger, ProgressLogger
  8. def run_script(script_name: str, description: str) -> bool:
  9. """Run a Python script and return success status."""
  10. script_path = Path(__file__).parent / "setup" / script_name
  11. if not script_path.exists():
  12. print(f"❌ Script not found: {script_path}")
  13. return False
  14. print(f"\n{'=' * 60}")
  15. print(f"🚀 {description}")
  16. print(f" Running: {script_name}")
  17. print(f"{'=' * 60}")
  18. try:
  19. result = subprocess.run(
  20. [sys.executable, str(script_path)],
  21. capture_output=True,
  22. text=True,
  23. check=False,
  24. )
  25. # Print output
  26. if result.stdout:
  27. print(result.stdout)
  28. if result.stderr:
  29. print(result.stderr, file=sys.stderr)
  30. if result.returncode != 0:
  31. print(f"❌ Script failed with exit code: {result.returncode}")
  32. return False
  33. print(f"✅ {script_name} completed successfully")
  34. return True
  35. except Exception as e:
  36. print(f"❌ Error running {script_name}: {e}")
  37. return False
  38. def check_port(host: str, port: int, service_name: str) -> bool:
  39. """Check if a service is running on the specified port."""
  40. try:
  41. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  42. sock.settimeout(2)
  43. result = sock.connect_ex((host, port))
  44. sock.close()
  45. if result == 0:
  46. Logger().success(f"{service_name} is running on port {port}")
  47. return True
  48. else:
  49. Logger().error(f"{service_name} is not accessible on port {port}")
  50. return False
  51. except Exception as e:
  52. Logger().error(f"Error checking {service_name}: {e}")
  53. return False
  54. def main() -> None:
  55. """Run all setup scripts in order."""
  56. log = Logger("Setup")
  57. log.box("Dify Stress Test Setup - Full Installation")
  58. # Check if required services are running
  59. log.step("Checking required services...")
  60. log.separator()
  61. dify_running = check_port("localhost", 5001, "Dify API server")
  62. if not dify_running:
  63. log.info("To start Dify API server:")
  64. log.list_item("Run: ./dev/start-api")
  65. mock_running = check_port("localhost", 5004, "Mock OpenAI server")
  66. if not mock_running:
  67. log.info("To start Mock OpenAI server:")
  68. log.list_item("Run: python scripts/stress-test/setup/mock_openai_server.py")
  69. if not dify_running or not mock_running:
  70. print("\n⚠️ Both services must be running before proceeding.")
  71. retry = input("\nWould you like to check again? (yes/no): ")
  72. if retry.lower() in ["yes", "y"]:
  73. return main() # Recursively call main to check again
  74. else:
  75. print("❌ Setup cancelled. Please start the required services and try again.")
  76. sys.exit(1)
  77. log.success("All required services are running!")
  78. input("\nPress Enter to continue with setup...")
  79. # Define setup steps
  80. setup_steps = [
  81. ("setup_admin.py", "Creating admin account"),
  82. ("login_admin.py", "Logging in and getting access token"),
  83. ("install_openai_plugin.py", "Installing OpenAI plugin"),
  84. ("configure_openai_plugin.py", "Configuring OpenAI plugin with mock server"),
  85. ("import_workflow_app.py", "Importing workflow application"),
  86. ("create_api_key.py", "Creating API key for the app"),
  87. ("publish_workflow.py", "Publishing the workflow"),
  88. ]
  89. # Create progress logger
  90. progress = ProgressLogger(len(setup_steps), log)
  91. failed_step = None
  92. for script, description in setup_steps:
  93. progress.next_step(description)
  94. success = run_script(script, description)
  95. if not success:
  96. failed_step = script
  97. break
  98. # Small delay between steps
  99. time.sleep(1)
  100. log.separator()
  101. if failed_step:
  102. log.error(f"Setup failed at: {failed_step}")
  103. log.separator()
  104. log.info("Troubleshooting:")
  105. log.list_item("Check if the Dify API server is running (./dev/start-api)")
  106. log.list_item("Check if the mock OpenAI server is running (port 5004)")
  107. log.list_item("Review the error messages above")
  108. log.list_item("Run cleanup.py and try again")
  109. sys.exit(1)
  110. else:
  111. progress.complete()
  112. log.separator()
  113. log.success("Setup completed successfully!")
  114. log.info("Next steps:")
  115. log.list_item("Test the workflow:")
  116. log.info(
  117. ' python scripts/stress-test/setup/run_workflow.py "Your question here"',
  118. indent=4,
  119. )
  120. log.list_item("To clean up and start over:")
  121. log.info(" python scripts/stress-test/cleanup.py", indent=4)
  122. # Optionally run a test
  123. log.separator()
  124. test_input = input("Would you like to run a test workflow now? (yes/no): ")
  125. if test_input.lower() in ["yes", "y"]:
  126. log.step("Running test workflow...")
  127. run_script("run_workflow.py", "Testing workflow with default question")
  128. if __name__ == "__main__":
  129. main()