lifetime.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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) fullDuplexLifecycle(r plugin_entities.PluginFullDuplexLifetime, launched_chan chan error) {
  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. // remove lifetime state after plugin if it has been stopped
  27. defer r.TriggerStop()
  28. // try to init environment until succeed
  29. for {
  30. log.Info("init environment for plugin %s", configuration.Identity())
  31. if err := r.InitEnvironment(); err != nil {
  32. log.Error("init environment failed: %s, retry in 30s", err.Error())
  33. time.Sleep(30 * time.Second)
  34. continue
  35. }
  36. break
  37. }
  38. // notify launched
  39. if launched_chan != nil {
  40. close(launched_chan)
  41. }
  42. // init environment successfully
  43. // once succeed, we consider the plugin is installed successfully
  44. for !r.Stopped() {
  45. // start plugin
  46. if err := r.StartPlugin(); err != nil {
  47. if r.Stopped() {
  48. // plugin has been stopped, exit
  49. break
  50. }
  51. }
  52. // wait for plugin to stop normally
  53. c, err := r.Wait()
  54. if err == nil {
  55. <-c
  56. }
  57. // restart plugin in 5s
  58. time.Sleep(5 * time.Second)
  59. // add restart times
  60. r.AddRestarts()
  61. }
  62. }