lifetime.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // init environment successfully
  46. // once succeed, we consider the plugin is installed successfully
  47. for !r.Stopped() {
  48. // start plugin
  49. if err := r.StartPlugin(); err != nil {
  50. if r.Stopped() {
  51. // plugin has been stopped, exit
  52. break
  53. }
  54. }
  55. // wait for plugin to stop normally
  56. c, err := r.Wait()
  57. if err == nil {
  58. <-c
  59. }
  60. // restart plugin in 5s
  61. time.Sleep(5 * time.Second)
  62. // add restart times
  63. r.AddRestarts()
  64. }
  65. }