server.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package server
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. "github.com/langgenius/dify-sandbox/internal/controller"
  7. "github.com/langgenius/dify-sandbox/internal/core/runner/python"
  8. "github.com/langgenius/dify-sandbox/internal/static"
  9. "github.com/langgenius/dify-sandbox/internal/utils/log"
  10. )
  11. func initConfig() {
  12. // auto migrate database
  13. err := static.InitConfig("conf/config.yaml")
  14. if err != nil {
  15. log.Panic("failed to init config: %v", err)
  16. }
  17. log.Info("config init success")
  18. err = static.SetupRunnerDependencies()
  19. if err != nil {
  20. log.Error("failed to setup runner dependencies: %v", err)
  21. }
  22. log.Info("runner dependencies init success")
  23. }
  24. func initServer() {
  25. config := static.GetDifySandboxGlobalConfigurations()
  26. if !config.App.Debug {
  27. gin.SetMode(gin.ReleaseMode)
  28. }
  29. r := gin.Default()
  30. controller.Setup(r)
  31. r.Run(fmt.Sprintf(":%d", config.App.Port))
  32. }
  33. func initDependencies() {
  34. log.Info("installing python dependencies...")
  35. dependenices := static.GetRunnerDependencies()
  36. err := python.InstallDependencies(dependenices.PythonRequirements)
  37. if err != nil {
  38. log.Panic("failed to install python dependencies: %v", err)
  39. }
  40. log.Info("python dependencies installed")
  41. log.Info("initializing python dependencies sandbox...")
  42. err = python.PreparePythonDependenciesEnv()
  43. if err != nil {
  44. log.Panic("failed to initialize python dependencies sandbox: %v", err)
  45. }
  46. log.Info("python dependencies sandbox initialized")
  47. // start a ticker to update python dependencies every 30 minutes to keep the sandbox up-to-date
  48. go func() {
  49. ticker := time.NewTicker(30 * time.Minute)
  50. for range ticker.C {
  51. log.Info("updating python dependencies...")
  52. err := python.InstallDependencies(dependenices.PythonRequirements)
  53. if err != nil {
  54. log.Error("failed to update python dependencies: %v", err)
  55. }
  56. log.Info("python dependencies updated")
  57. }
  58. }()
  59. }
  60. func Run() {
  61. initConfig()
  62. initDependencies()
  63. initServer()
  64. }