run.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Package local_runtime handles the local plugin runtime management
  2. package local_runtime
  3. import (
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "sync"
  9. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  10. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  11. "github.com/langgenius/dify-plugin-daemon/pkg/entities/constants"
  12. "github.com/langgenius/dify-plugin-daemon/pkg/entities/plugin_entities"
  13. )
  14. // gc performs garbage collection for the LocalPluginRuntime
  15. func (r *LocalPluginRuntime) gc() {
  16. if r.ioIdentity != "" {
  17. removeStdioHandler(r.ioIdentity)
  18. }
  19. if r.waitChan != nil {
  20. close(r.waitChan)
  21. r.waitChan = nil
  22. }
  23. }
  24. // Type returns the runtime type of the plugin
  25. func (r *LocalPluginRuntime) Type() plugin_entities.PluginRuntimeType {
  26. return plugin_entities.PLUGIN_RUNTIME_TYPE_LOCAL
  27. }
  28. // getCmd prepares the exec.Cmd for the plugin based on its language
  29. func (r *LocalPluginRuntime) getCmd() (*exec.Cmd, error) {
  30. if r.Config.Meta.Runner.Language == constants.Python {
  31. cmd := exec.Command(r.pythonInterpreterPath, "-m", r.Config.Meta.Runner.Entrypoint)
  32. cmd.Dir = r.State.WorkingPath
  33. if r.HttpsProxy != "" {
  34. cmd.Env = append(cmd.Env, fmt.Sprintf("HTTPS_PROXY=%s", r.HttpsProxy))
  35. }
  36. if r.HttpProxy != "" {
  37. cmd.Env = append(cmd.Env, fmt.Sprintf("HTTP_PROXY=%s", r.HttpProxy))
  38. }
  39. return cmd, nil
  40. }
  41. return nil, fmt.Errorf("unsupported language: %s", r.Config.Meta.Runner.Language)
  42. }
  43. // StartPlugin starts the plugin and manages its lifecycle
  44. func (r *LocalPluginRuntime) StartPlugin() error {
  45. defer log.Info("plugin %s stopped", r.Config.Identity())
  46. defer func() {
  47. r.waitChanLock.Lock()
  48. for _, c := range r.waitStoppedChan {
  49. select {
  50. case c <- true:
  51. default:
  52. }
  53. }
  54. r.waitChanLock.Unlock()
  55. }()
  56. if r.isNotFirstStart {
  57. r.SetRestarting()
  58. } else {
  59. r.SetLaunching()
  60. r.isNotFirstStart = true
  61. }
  62. // reset wait chan
  63. r.waitChan = make(chan bool)
  64. // reset wait launched chan
  65. // start plugin
  66. e, err := r.getCmd()
  67. if err != nil {
  68. return err
  69. }
  70. e.Dir = r.State.WorkingPath
  71. // add env INSTALL_METHOD=local
  72. e.Env = append(e.Env, "INSTALL_METHOD=local", "PATH="+os.Getenv("PATH"))
  73. // get writer
  74. stdin, err := e.StdinPipe()
  75. if err != nil {
  76. return fmt.Errorf("get stdin pipe failed: %s", err.Error())
  77. }
  78. defer stdin.Close()
  79. // get stdout
  80. stdout, err := e.StdoutPipe()
  81. if err != nil {
  82. return fmt.Errorf("get stdout pipe failed: %s", err.Error())
  83. }
  84. defer stdout.Close()
  85. // get stderr
  86. stderr, err := e.StderrPipe()
  87. if err != nil {
  88. return fmt.Errorf("get stderr pipe failed: %s", err.Error())
  89. }
  90. defer stderr.Close()
  91. if err := e.Start(); err != nil {
  92. return fmt.Errorf("start plugin failed: %s", err.Error())
  93. }
  94. var stdio *stdioHolder
  95. defer func() {
  96. // wait for plugin to exit
  97. originalErr := e.Wait()
  98. if originalErr != nil {
  99. // get stdio
  100. var err error
  101. if stdio != nil {
  102. stdioErr := stdio.Error()
  103. if stdioErr != nil {
  104. err = errors.Join(originalErr, stdioErr)
  105. } else {
  106. err = originalErr
  107. }
  108. } else {
  109. err = originalErr
  110. }
  111. if err != nil {
  112. log.Error("plugin %s exited with error: %s", r.Config.Identity(), err.Error())
  113. } else {
  114. log.Error("plugin %s exited with unknown error", r.Config.Identity())
  115. }
  116. }
  117. r.gc()
  118. }()
  119. // ensure the plugin process is killed after the plugin exits
  120. defer e.Process.Kill()
  121. log.Info("plugin %s started", r.Config.Identity())
  122. // setup stdio
  123. stdio = registerStdioHandler(r.Config.Identity(), stdin, stdout, stderr)
  124. r.ioIdentity = stdio.GetID()
  125. defer stdio.Stop()
  126. wg := sync.WaitGroup{}
  127. wg.Add(2)
  128. // listen to plugin stdout
  129. routine.Submit(map[string]string{
  130. "module": "plugin_manager",
  131. "type": "local",
  132. "function": "StartStdout",
  133. }, func() {
  134. defer wg.Done()
  135. stdio.StartStdout(func() {})
  136. })
  137. // listen to plugin stderr
  138. routine.Submit(map[string]string{
  139. "module": "plugin_manager",
  140. "type": "local",
  141. "function": "StartStderr",
  142. }, func() {
  143. defer wg.Done()
  144. stdio.StartStderr()
  145. })
  146. // send started event
  147. r.waitChanLock.Lock()
  148. for _, c := range r.waitStartedChan {
  149. select {
  150. case c <- true:
  151. default:
  152. }
  153. }
  154. r.waitChanLock.Unlock()
  155. // wait for plugin to exit
  156. err = stdio.Wait()
  157. if err != nil {
  158. return errors.Join(err, stdio.Error())
  159. }
  160. wg.Wait()
  161. // plugin has exited
  162. return nil
  163. }
  164. // Wait returns a channel that will be closed when the plugin stops
  165. func (r *LocalPluginRuntime) Wait() (<-chan bool, error) {
  166. if r.waitChan == nil {
  167. return nil, errors.New("plugin not started")
  168. }
  169. return r.waitChan, nil
  170. }
  171. // WaitStarted returns a channel that will receive true when the plugin starts
  172. func (r *LocalPluginRuntime) WaitStarted() <-chan bool {
  173. c := make(chan bool)
  174. r.waitChanLock.Lock()
  175. r.waitStartedChan = append(r.waitStartedChan, c)
  176. r.waitChanLock.Unlock()
  177. return c
  178. }
  179. // WaitStopped returns a channel that will receive true when the plugin stops
  180. func (r *LocalPluginRuntime) WaitStopped() <-chan bool {
  181. c := make(chan bool)
  182. r.waitChanLock.Lock()
  183. r.waitStoppedChan = append(r.waitStoppedChan, c)
  184. r.waitChanLock.Unlock()
  185. return c
  186. }
  187. // Stop stops the plugin
  188. func (r *LocalPluginRuntime) Stop() {
  189. // inherit from PluginRuntime
  190. r.PluginRuntime.Stop()
  191. // get stdio
  192. stdio := getStdioHandler(r.ioIdentity)
  193. if stdio != nil {
  194. stdio.Stop()
  195. }
  196. }