setup.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package python
  2. import (
  3. _ "embed"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "github.com/langgenius/dify-sandbox/internal/core/runner"
  8. python_dependencies "github.com/langgenius/dify-sandbox/internal/core/runner/python/dependencies"
  9. "github.com/langgenius/dify-sandbox/internal/core/runner/types"
  10. "github.com/langgenius/dify-sandbox/internal/utils/log"
  11. )
  12. //go:embed python.so
  13. var python_lib []byte
  14. func init() {
  15. log.Info("initializing python runner environment...")
  16. // remove /tmp/sandbox-python
  17. os.RemoveAll("/tmp/sandbox-python")
  18. os.Remove("/tmp/sandbox-python")
  19. err := os.MkdirAll("/tmp/sandbox-python", 0755)
  20. if err != nil {
  21. log.Panic("failed to create /tmp/sandbox-python")
  22. }
  23. err = os.WriteFile("/tmp/sandbox-python/python.so", python_lib, 0755)
  24. if err != nil {
  25. log.Panic("failed to write /tmp/sandbox-python/python.so")
  26. }
  27. log.Info("python runner environment initialized")
  28. }
  29. func InstallDependencies(requirements string) error {
  30. if requirements == "" {
  31. return nil
  32. }
  33. runner := runner.TempDirRunner{}
  34. return runner.WithTempDir([]string{}, func(root_path string) error {
  35. defer os.Remove(root_path)
  36. defer os.RemoveAll(root_path)
  37. // create a requirements file
  38. err := os.WriteFile(path.Join(root_path, "requirements.txt"), []byte(requirements), 0644)
  39. if err != nil {
  40. log.Panic("failed to create requirements.txt")
  41. }
  42. // install dependencies
  43. cmd := exec.Command("pip3", "install", "-r", "requirements.txt")
  44. reader, err := cmd.StdoutPipe()
  45. if err != nil {
  46. log.Panic("failed to get stdout pipe of pip3")
  47. }
  48. defer reader.Close()
  49. err = cmd.Start()
  50. if err != nil {
  51. log.Panic("failed to start pip3")
  52. }
  53. defer cmd.Wait()
  54. for {
  55. buf := make([]byte, 1024)
  56. n, err := reader.Read(buf)
  57. if err != nil {
  58. break
  59. }
  60. log.Info(string(buf[:n]))
  61. }
  62. return nil
  63. })
  64. }
  65. func ListDependencies() []types.Dependency {
  66. return python_dependencies.ListDependencies()
  67. }