setup.go 1.6 KB

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