How to use plugins method of plugin Package

Best Gauge code snippet using plugin.plugins

loader.go

Source:loader.go Github

copy

Full Screen

...17 logging "github.com/ipfs/go-log"18 opentracing "github.com/opentracing/opentracing-go"19)20var preloadPlugins []plugin.Plugin21// Preload adds one or more plugins to the preload list. This should _only_ be called during init.22func Preload(plugins ...plugin.Plugin) {23 preloadPlugins = append(preloadPlugins, plugins...)24}25var log = logging.Logger("plugin/loader")26var loadPluginFunc = func(string) ([]plugin.Plugin, error) {27 return nil, fmt.Errorf("unsupported platform %s", runtime.GOOS)28}29type loaderState int30const (31 loaderLoading loaderState = iota32 loaderInitializing33 loaderInitialized34 loaderInjecting35 loaderInjected36 loaderStarting37 loaderStarted38 loaderClosing39 loaderClosed40 loaderFailed41)42func (ls loaderState) String() string {43 switch ls {44 case loaderLoading:45 return "Loading"46 case loaderInitializing:47 return "Initializing"48 case loaderInitialized:49 return "Initialized"50 case loaderInjecting:51 return "Injecting"52 case loaderInjected:53 return "Injected"54 case loaderStarting:55 return "Starting"56 case loaderStarted:57 return "Started"58 case loaderClosing:59 return "Closing"60 case loaderClosed:61 return "Closed"62 case loaderFailed:63 return "Failed"64 default:65 return "Unknown"66 }67}68// PluginLoader keeps track of loaded plugins.69//70// To use:71// 1. Load any desired plugins with Load and LoadDirectory. Preloaded plugins72// will automatically be loaded.73// 2. Call Initialize to run all initialization logic.74// 3. Call Inject to register the plugins.75// 4. Optionally call Start to start plugins.76// 5. Call Close to close all plugins.77type PluginLoader struct {78 state loaderState79 plugins map[string]plugin.Plugin80 started []plugin.Plugin81 config config.Plugins82 repo string83}84// NewPluginLoader creates new plugin loader85func NewPluginLoader(repo string) (*PluginLoader, error) {86 loader := &PluginLoader{plugins: make(map[string]plugin.Plugin, len(preloadPlugins)), repo: repo}87 if repo != "" {88 cfg, err := cserialize.Load(filepath.Join(repo, config.DefaultConfigFile))89 switch err {90 case cserialize.ErrNotInitialized:91 case nil:92 loader.config = cfg.Plugins93 default:94 return nil, err95 }96 }97 for _, v := range preloadPlugins {98 if err := loader.Load(v); err != nil {99 return nil, err100 }101 }102 if err := loader.LoadDirectory(filepath.Join(repo, "plugins")); err != nil {103 return nil, err104 }105 return loader, nil106}107func (loader *PluginLoader) assertState(state loaderState) error {108 if loader.state != state {109 return fmt.Errorf("loader state must be %s, was %s", state, loader.state)110 }111 return nil112}113func (loader *PluginLoader) transition(from, to loaderState) error {114 if err := loader.assertState(from); err != nil {115 return err116 }117 loader.state = to118 return nil119}120// Load loads a plugin into the plugin loader.121func (loader *PluginLoader) Load(pl plugin.Plugin) error {122 if err := loader.assertState(loaderLoading); err != nil {123 return err124 }125 name := pl.Name()126 if ppl, ok := loader.plugins[name]; ok {127 // plugin is already loaded128 return fmt.Errorf(129 "plugin: %s, is duplicated in version: %s, "+130 "while trying to load dynamically: %s",131 name, ppl.Version(), pl.Version())132 }133 if loader.config.Plugins[name].Disabled {134 log.Infof("not loading disabled plugin %s", name)135 return nil136 }137 loader.plugins[name] = pl138 return nil139}140// LoadDirectory loads a directory of plugins into the plugin loader.141func (loader *PluginLoader) LoadDirectory(pluginDir string) error {142 if err := loader.assertState(loaderLoading); err != nil {143 return err144 }145 newPls, err := loadDynamicPlugins(pluginDir)146 if err != nil {147 return err148 }149 for _, pl := range newPls {150 if err := loader.Load(pl); err != nil {151 return err152 }153 }154 return nil155}156func loadDynamicPlugins(pluginDir string) ([]plugin.Plugin, error) {157 _, err := os.Stat(pluginDir)158 if os.IsNotExist(err) {159 return nil, nil160 }161 if err != nil {162 return nil, err163 }164 var plugins []plugin.Plugin165 err = filepath.Walk(pluginDir, func(fi string, info os.FileInfo, err error) error {166 if err != nil {167 return err168 }169 if info.IsDir() {170 if fi != pluginDir {171 log.Warnf("found directory inside plugins directory: %s", fi)172 }173 return nil174 }175 if info.Mode().Perm()&0111 == 0 {176 // file is not executable let's not load it177 // this is to prevent loading plugins from for example non-executable178 // mounts, some /tmp mounts are marked as such for security179 log.Errorf("non-executable file in plugins directory: %s", fi)180 return nil181 }182 if newPlugins, err := loadPluginFunc(fi); err == nil {183 plugins = append(plugins, newPlugins...)184 } else {185 return fmt.Errorf("loading plugin %s: %s", fi, err)186 }187 return nil188 })189 return plugins, err190}191// Initialize initializes all loaded plugins192func (loader *PluginLoader) Initialize() error {193 if err := loader.transition(loaderLoading, loaderInitializing); err != nil {194 return err195 }196 for name, p := range loader.plugins {197 err := p.Init(&plugin.Environment{198 Repo: loader.repo,199 Config: loader.config.Plugins[name].Config,200 })201 if err != nil {202 loader.state = loaderFailed203 return err204 }205 }206 return loader.transition(loaderInitializing, loaderInitialized)207}208// Inject hooks all the plugins into the appropriate subsystems.209func (loader *PluginLoader) Inject() error {210 if err := loader.transition(loaderInitialized, loaderInjecting); err != nil {211 return err212 }213 for _, pl := range loader.plugins {214 if pl, ok := pl.(plugin.PluginIPLD); ok {215 err := injectIPLDPlugin(pl)216 if err != nil {217 loader.state = loaderFailed218 return err219 }220 }221 if pl, ok := pl.(plugin.PluginTracer); ok {222 err := injectTracerPlugin(pl)223 if err != nil {224 loader.state = loaderFailed225 return err226 }227 }228 if pl, ok := pl.(plugin.PluginDatastore); ok {229 err := injectDatastorePlugin(pl)230 if err != nil {231 loader.state = loaderFailed232 return err233 }234 }235 }236 return loader.transition(loaderInjecting, loaderInjected)237}238// Start starts all long-running plugins.239func (loader *PluginLoader) Start(node *core.IpfsNode) error {240 if err := loader.transition(loaderInjected, loaderStarting); err != nil {241 return err242 }243 iface, err := coreapi.NewCoreAPI(node)244 if err != nil {245 return err246 }247 for _, pl := range loader.plugins {248 if pl, ok := pl.(plugin.PluginDaemon); ok {249 err := pl.Start(iface)250 if err != nil {251 _ = loader.Close()252 return err253 }254 loader.started = append(loader.started, pl)255 }256 if pl, ok := pl.(plugin.PluginDaemonInternal); ok {257 err := pl.Start(node)258 if err != nil {259 _ = loader.Close()260 return err261 }262 loader.started = append(loader.started, pl)263 }264 }265 return loader.transition(loaderStarting, loaderStarted)266}267// StopDaemon stops all long-running plugins.268func (loader *PluginLoader) Close() error {269 switch loader.state {270 case loaderClosing, loaderFailed, loaderClosed:271 // nothing to do.272 return nil273 }274 loader.state = loaderClosing275 var errs []string276 started := loader.started277 loader.started = nil278 for _, pl := range started {279 if closer, ok := pl.(io.Closer); ok {280 err := closer.Close()281 if err != nil {...

Full Screen

Full Screen

plugins.go

Source:plugins.go Github

copy

Full Screen

2import (3 "reflect"4 "strings"5)6// Message represents data accross plugins7type Message struct {8 Meta []byte // metadata9 Data []byte // actual data10}11// PluginReader is an interface for input plugins12type PluginReader interface {13 PluginRead() (msg *Message, err error)14}15// PluginWriter is an interface for output plugins16type PluginWriter interface {17 PluginWrite(msg *Message) (n int, err error)18}19// PluginReadWriter is an interface for plugins that support reading and writing20type PluginReadWriter interface {21 PluginReader22 PluginWriter23}24// InOutPlugins struct for holding references to plugins25type InOutPlugins struct {26 Inputs []PluginReader27 Outputs []PluginWriter28 All []interface{}29}30// extractLimitOptions detects if plugin get called with limiter support31// Returns address and limit32func extractLimitOptions(options string) (string, string) {33 split := strings.Split(options, "|")34 if len(split) > 1 {35 return split[0], split[1]36 }37 return split[0], ""38}39// Automatically detects type of plugin and initialize it40//41// See this article if curious about reflect stuff below: http://blog.burntsushi.net/type-parametric-functions-golang42func (plugins *InOutPlugins) registerPlugin(constructor interface{}, options ...interface{}) {43 var path, limit string44 vc := reflect.ValueOf(constructor)45 // Pre-processing options to make it work with reflect46 vo := []reflect.Value{}47 for _, oi := range options {48 vo = append(vo, reflect.ValueOf(oi))49 }50 if len(vo) > 0 {51 // Removing limit options from path52 path, limit = extractLimitOptions(vo[0].String())53 // Writing value back without limiter "|" options54 vo[0] = reflect.ValueOf(path)55 }56 // Calling our constructor with list of given options57 plugin := vc.Call(vo)[0].Interface()58 if limit != "" {59 plugin = NewLimiter(plugin, limit)60 }61 // Some of the output can be Readers as well because return responses62 if r, ok := plugin.(PluginReader); ok {63 plugins.Inputs = append(plugins.Inputs, r)64 }65 if w, ok := plugin.(PluginWriter); ok {66 plugins.Outputs = append(plugins.Outputs, w)67 }68 plugins.All = append(plugins.All, plugin)69}70// NewPlugins specify and initialize all available plugins71func NewPlugins() *InOutPlugins {72 plugins := new(InOutPlugins)73 for _, options := range Settings.InputDummy {74 plugins.registerPlugin(NewDummyInput, options)75 }76 for range Settings.OutputDummy {77 plugins.registerPlugin(NewDummyOutput)78 }79 if Settings.OutputStdout {80 plugins.registerPlugin(NewDummyOutput)81 }82 if Settings.OutputNull {83 plugins.registerPlugin(NewNullOutput)84 }85 for _, options := range Settings.InputRAW {86 plugins.registerPlugin(NewRAWInput, options, Settings.RAWInputConfig)87 }88 for _, options := range Settings.InputTCP {89 plugins.registerPlugin(NewTCPInput, options, &Settings.InputTCPConfig)90 }91 for _, options := range Settings.OutputTCP {92 plugins.registerPlugin(NewTCPOutput, options, &Settings.OutputTCPConfig)93 }94 for _, options := range Settings.InputFile {95 plugins.registerPlugin(NewFileInput, options, Settings.InputFileLoop)96 }97 for _, path := range Settings.OutputFile {98 if strings.HasPrefix(path, "s3://") {99 plugins.registerPlugin(NewS3Output, path, &Settings.OutputFileConfig)100 } else {101 plugins.registerPlugin(NewFileOutput, path, &Settings.OutputFileConfig)102 }103 }104 for _, options := range Settings.InputHTTP {105 plugins.registerPlugin(NewHTTPInput, options)106 }107 // If we explicitly set Host header http output should not rewrite it108 // Fix: https://github.com/buger/gor/issues/174109 for _, header := range Settings.ModifierConfig.Headers {110 if header.Name == "Host" {111 Settings.OutputHTTPConfig.OriginalHost = true112 break113 }114 }115 for _, options := range Settings.OutputHTTP {116 plugins.registerPlugin(NewHTTPOutput, options, &Settings.OutputHTTPConfig)117 }118 for _, options := range Settings.OutputBinary {119 plugins.registerPlugin(NewBinaryOutput, options, &Settings.OutputBinaryConfig)120 }121 if Settings.OutputKafkaConfig.Host != "" && Settings.OutputKafkaConfig.Topic != "" {122 plugins.registerPlugin(NewKafkaOutput, "", &Settings.OutputKafkaConfig, &Settings.KafkaTLSConfig)123 }124 if Settings.InputKafkaConfig.Host != "" && Settings.InputKafkaConfig.Topic != "" {125 plugins.registerPlugin(NewKafkaInput, "", &Settings.InputKafkaConfig, &Settings.KafkaTLSConfig)126 }127 return plugins128}...

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import "plugin"2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 panic(err)6 }7 f, err := p.Lookup("Hello")8 if err != nil {9 panic(err)10 }11 f.(func())()12}13import "fmt"14func Hello() {15 fmt.Println("Hello, world.")16}17func main() {18 Hello()19}20import "plugin"21func main() {22 p, err := plugin.Open("plugin.so")23 if err != nil {24 panic(err)25 }26 f, err := p.Lookup("Hello")27 if err != nil {28 panic(err)29 }30 f.(func())()31}32import "fmt"33func Hello() {34 fmt.Println("Hello, world.")35}36func main() {37 Hello()38}39import "plugin"40func main() {41 p, err := plugin.Open("plugin.so")42 if err != nil {43 panic(err)44 }45 f, err := p.Lookup("Hello")46 if err != nil {47 panic(err)48 }49 f.(func())()50}51import "fmt"52func Hello() {53 fmt.Println("Hello, world.")54}55func main() {56 Hello()57}58import "plugin"59func main() {60 p, err := plugin.Open("plugin.so")61 if err != nil {62 panic(err)63 }64 f, err := p.Lookup("Hello")65 if err != nil {66 panic(err)67 }68 f.(func())()69}70import "fmt"71func Hello() {72 fmt.Println("Hello, world.")73}74func main() {75 Hello()76}77import "plugin"78func main() {79 p, err := plugin.Open("plugin.so

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 fmt.Println(err)6 }7 sym, err := p.Lookup("Plugin")8 if err != nil {9 fmt.Println(err)10 }11 plugin, ok := sym.(func() string)12 if !ok {13 fmt.Println("unexpected type from module symbol")14 }

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.IOException;3import java.net.MalformedURLException;4import java.net.URL;5import java.net.URLClassLoader;6import java.util.ArrayList;7import java.util.List;8import java.util.logging.Level;9import java.util.logging.Logger;10import javax.swing.JFileChooser;11import javax.swing.filechooser.FileNameExtensionFilter;12public class Plugins extends javax.swing.JFrame {13 public Plugins() {14 initComponents();15 }16 public static void main(String args[]) {17 java.awt.EventQueue.invokeLater(new Runnable() {18 public void run() {19 new Plugins().setVisible(true);20 }21 });22 }23 @SuppressWarnings("unchecked")24 private void initComponents() {25 jLabel1 = new javax.swing.JLabel();26 jButton1 = new javax.swing.JButton();27 jLabel2 = new javax.swing.JLabel();28 jTextField1 = new javax.swing.JTextField();29 jButton2 = new javax.swing.JButton();30 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);31 jLabel1.setText("Select Plugin");32 jButton1.setText("Browse");33 jButton1.addActionListener(new java.awt.event.ActionListener() {34 public void actionPerformed(java.awt.event.ActionEvent evt) {35 jButton1ActionPerformed(evt);36 }37 });38 jLabel2.setText("Enter Class Name");39 jButton2.setText("Run");40 jButton2.addActionListener(new java.awt.event.ActionListener() {41 public void actionPerformed(java.awt.event.ActionEvent evt) {42 jButton2ActionPerformed(evt);43 }44 });45 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());46 getContentPane().setLayout(layout);47 layout.setHorizontalGroup(48 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)49 .addGroup(layout.createSequentialGroup()50 .addGap(31, 31, 31)51 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)52 .addComponent(jLabel1)53 .addComponent(jLabel2))54 .addGap(31, 31, 31)55 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)56 .addComponent(jButton2)57 .addComponent(jTextField1)58 .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))59 .addContainerGap(154, Short.MAX_VALUE))60 );61 layout.setVerticalGroup(62 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)63 .addGroup(layout.createSequentialGroup()64 .addGap(58, 58, 58)65 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)66 .addComponent(jLabel1)67 .addComponent(jButton1))68 .addGap(18, 18, 18)69 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 fmt.Println(err)6 }7 add, err := p.Lookup("Add")8 if err != nil {9 fmt.Println(err)10 }11 f := add.(func(int, int) int)12 fmt.Println(f(1, 2))13}14import "C"15func Add(a, b int) int {16}17func main() {}

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 panic(err)6 }

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1type interfaceName interface {2 methodName1(parameter list) returnType3 methodName2(parameter list) returnType4 methodNameN(parameter list) returnType5}6import "fmt"7type Shape interface {8 area() float649}10type Circle struct {11}12type Rectangle struct {13}14func (circle Circle) area() float64 {15}16func (rectangle Rectangle) area() float64 {17}18func getArea(shape Shape) float64 {19 return shape.area()20}21func main() {22 circle := Circle{x: 0, y: 0, radius: 5}23 rectangle := Rectangle{width: 10, height: 5}24 fmt.Printf("Circle area: %f25", getArea(circle))26 fmt.Printf("Rectangle area: %f27", getArea(rectangle))28}

Full Screen

Full Screen

plugins

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := plugin.NewClient(&plugin.ClientConfig{4 Plugins: map[string]plugin.Plugin{5 "greeter": &shared.GreeterPlugin{},6 },7 Cmd: plugin.Command{8 },9 })10 rpcClient, err := client.Client()11 if err != nil {12 panic(err)13 }14 raw, err := rpcClient.Dispense("greeter")15 if err != nil {16 panic(err)17 }18 greeter := raw.(shared.Greeter)19 fmt.Println(greeter.Greet())20}21import (22func main() {23 var pluginMap = map[string]plugin.Plugin{24 "greeter": &shared.GreeterPlugin{},25 }26 plugin.Serve(&plugin.ServeConfig{27 })28}29import (30var Handshake = plugin.HandshakeConfig{31}32type Greeter interface {33 Greet() string34}35type GreeterPlugin struct {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful