github.com/awesome-flow/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/util/plugin/plugin.go (about) 1 package plugin 2 3 import ( 4 "fmt" 5 "os" 6 "path" 7 goplugin "plugin" 8 ) 9 10 type Symbol interface{} 11 12 type Plugin interface { 13 Load() error 14 Lookup(string) (Symbol, error) 15 } 16 17 type GoPlugin struct { 18 path string 19 name string 20 plug *goplugin.Plugin 21 } 22 23 var _ Plugin = (*GoPlugin)(nil) 24 25 func NewGoPlugin(path, name string) *GoPlugin { 26 return &GoPlugin{ 27 path: path, 28 name: name, 29 } 30 } 31 32 func (g *GoPlugin) Load() error { 33 fullpath := path.Join(g.path, g.name, g.name+".so") 34 if _, err := os.Stat(fullpath); err != nil { 35 if os.IsNotExist(err) { 36 return fmt.Errorf("failed to load plugin .so library from %s", fullpath) 37 } 38 return err 39 } 40 p, err := goplugin.Open(fullpath) 41 if err != nil { 42 return err 43 } 44 g.plug = p 45 46 return nil 47 } 48 49 func (g *GoPlugin) Lookup(symName string) (Symbol, error) { 50 return g.plug.Lookup(symName) 51 } 52 53 type Loader func(path, name string) (Plugin, error) 54 55 func GoPluginLoader(path, name string) (Plugin, error) { 56 p := NewGoPlugin(path, name) 57 if err := p.Load(); err != nil { 58 return nil, err 59 } 60 61 return p, nil 62 }