lifetime.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package plugin_manager
  2. import (
  3. "time"
  4. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  5. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  6. )
  7. func (p *PluginManager) AddPluginRegisterHandler(handler func(r plugin_entities.PluginLifetime) error) {
  8. p.pluginRegisters = append(p.pluginRegisters, handler)
  9. }
  10. func (p *PluginManager) fullDuplexLifetime(r plugin_entities.PluginFullDuplexLifetime) {
  11. configuration := r.Configuration()
  12. log.Info("new plugin logged in: %s", configuration.Identity())
  13. defer log.Info("plugin %s has exited", configuration.Identity())
  14. // cleanup plugin runtime state and working directory
  15. defer r.Cleanup()
  16. // stop plugin when the plugin reaches the end of its lifetime
  17. defer r.Stop()
  18. // register plugin
  19. for _, reg := range p.pluginRegisters {
  20. err := reg(r)
  21. if err != nil {
  22. log.Error("add plugin to cluster failed: %s", err.Error())
  23. return
  24. }
  25. }
  26. start_failed_times := 0
  27. // remove lifetime state after plugin if it has been stopped
  28. defer r.TriggerStop()
  29. // try at most 3 times to init environment
  30. for i := 0; i < 3; i++ {
  31. if err := r.InitEnvironment(); err != nil {
  32. log.Error("init environment failed: %s, retry in 30s", err.Error())
  33. if start_failed_times == 3 {
  34. log.Error(
  35. "init environment failed 3 times, plugin %s has been stopped",
  36. configuration.Identity(),
  37. )
  38. return
  39. }
  40. time.Sleep(30 * time.Second)
  41. start_failed_times++
  42. continue
  43. }
  44. }
  45. // TODO: launched will only be triggered when calling StartPlugin
  46. // init environment successfully
  47. // once succeed, we consider the plugin is installed successfully
  48. for !r.Stopped() {
  49. // start plugin
  50. if err := r.StartPlugin(); err != nil {
  51. if r.Stopped() {
  52. // plugin has been stopped, exit
  53. break
  54. }
  55. }
  56. // wait for plugin to stop normally
  57. c, err := r.Wait()
  58. if err == nil {
  59. <-c
  60. }
  61. // restart plugin in 5s
  62. time.Sleep(5 * time.Second)
  63. // add restart times
  64. r.AddRestarts()
  65. }
  66. }