github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/resource/cobalt/cobalt.go (about) 1 package cobalt 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/projecteru2/core/log" 8 "github.com/projecteru2/core/resource/plugins" 9 "github.com/projecteru2/core/resource/plugins/binary" 10 "github.com/projecteru2/core/resource/plugins/cpumem" 11 "github.com/projecteru2/core/resource/plugins/goplugin" 12 "github.com/projecteru2/core/types" 13 "github.com/projecteru2/core/utils" 14 ) 15 16 // Manager manager plugins 17 type Manager struct { 18 config types.Config 19 plugins []plugins.Plugin 20 } 21 22 // New creates a plugin manager 23 func New(config types.Config) (*Manager, error) { 24 m := &Manager{ 25 config: config, 26 plugins: []plugins.Plugin{}, 27 } 28 29 return m, nil 30 } 31 32 // LoadPlugins . 33 func (m *Manager) LoadPlugins(ctx context.Context, t *testing.T) error { 34 logger := log.WithFunc("resource.cobalt.LoadPlugins") 35 // Load internal 36 cm, err := cpumem.NewPlugin(ctx, m.config, t) 37 if err != nil { 38 return err 39 } 40 m.AddPlugins(cm) 41 42 if m.config.ResourcePlugin.Dir == "" { 43 return nil 44 } 45 46 cache := map[string]struct{}{} 47 for _, plugin := range m.plugins { 48 cache[plugin.Name()] = struct{}{} 49 } 50 51 sharedLibFiles, err := utils.ListAllSharedLibFiles(m.config.ResourcePlugin.Dir) 52 if err != nil { 53 logger.Errorf(ctx, err, "failed to list all share lib files dir: %+v", m.config.ResourcePlugin.Dir) 54 return err 55 } 56 57 for _, file := range sharedLibFiles { 58 logger.Infof(ctx, "load go plugin: %+v", file) 59 b, err := goplugin.NewPlugin(ctx, file, m.config) 60 if err != nil { 61 return err 62 } 63 if _, ok := cache[b.Name()]; ok { 64 continue 65 } 66 cache[b.Name()] = struct{}{} 67 m.AddPlugins(b) 68 } 69 70 pluginFiles, err := utils.ListAllExecutableFiles(m.config.ResourcePlugin.Dir) 71 if err != nil { 72 logger.Errorf(ctx, err, "failed to list all executable files dir: %+v", m.config.ResourcePlugin.Dir) 73 return err 74 } 75 for _, file := range pluginFiles { 76 logger.Infof(ctx, "load binary plugin: %+v", file) 77 b, err := binary.NewPlugin(ctx, file, m.config) 78 if err != nil { 79 return err 80 } 81 if _, ok := cache[b.Name()]; ok { 82 continue 83 } 84 cache[b.Name()] = struct{}{} 85 m.AddPlugins(b) 86 } 87 return nil 88 } 89 90 // AddPlugins adds a plugin (for test and debug) 91 func (m *Manager) AddPlugins(plugins ...plugins.Plugin) { 92 m.plugins = append(m.plugins, plugins...) 93 } 94 95 // GetPlugins is used for mock 96 func (m Manager) GetPlugins() []plugins.Plugin { 97 return m.plugins 98 }