How to use invokeService method of plugin Package

Best Gauge code snippet using plugin.invokeService

worker.go

Source:worker.go Github

copy

Full Screen

1//////////////////////////////////////////////////////////////////////2//3// G006169494//5// Paul McKerley6//7// CS675 Spring 2020 -- Lab28//9// Worker registers with driver and receives requests to do work.10//11//////////////////////////////////////////////////////////////////////12package main13import (14 "cs675-spring20-labs/lab2/serverless"15 "fmt"16 "log"17 "net"18 "net/rpc"19 "os"20 "plugin"21 "strconv"22 "sync"23)24// Worker holds the state for a server waiting for:25// 1) RegisterService,26// 2) InvokeService,27// 3) Shutdown RPCs.28type Worker struct {29 sync.Mutex30 address string // address of this worker process31 masterAddr string // address of the driver process32 nThreads int // misc. statistics (usage not required)33 nRPC int // number of RPC requests to serve before the worker exists34 nTasks int // misc. statistics (usage not required)35 concurrent int // misc. statistics (usage not required)36 l net.Listener37 shutdown chan struct{}38}39// Service struct maintains the state of a plugin Service.40type Service struct {41 pluginDir string42 name string43 interf serverless.Interface44}45// serviceMap is a global map that keeps track of all registered plugin Services.46// You should insert the newly registered service into this map.47var serviceMap = make(map[string]*Service)48// newService initializes a new plugin Service.49func newService(serviceName string) *Service {50 return &Service{51 pluginDir: serverless.PluginDir,52 name: serviceName,53 interf: nil,54 }55}56// Finds and opens the plugin.57func (svc *Service) openPlugin() error {58 plug, err := plugin.Open(svc.pluginDir + "/" + svc.name + ".so")59 if err != nil {60 serverless.Debug("Failed to open plugin %s: %v\n", svc.name, err)61 return err62 }63 serverless.Debug("Opened plugin %s\n", svc.name)64 symInterface, err := plug.Lookup("Interface")65 if err != nil {66 serverless.Debug("Error looking up symbol 'Interface' in %s: %v\n", svc.name, err)67 return err68 }69 serverless.Debug("Successfully looked up Interface %s\n", svc.name)70 var interf serverless.Interface71 interf, ok := symInterface.(serverless.Interface)72 if !ok {73 serverless.Debug("Unable to load Interface from %s.\n", svc.name)74 return fmt.Errorf("Unable to load type %s", svc.name)75 }76 svc.interf = interf77 return nil78}79// RegisterService is caled by the driver to plugin a new service that has already been80// compiled into a .so static object library.81func (wk *Worker) RegisterService(args *serverless.ServiceRegisterArgs, _ *struct{}) error {82 serverless.Debug("Register called for %s\n", args.ServiceName)83 service := newService(args.ServiceName)84 err := service.openPlugin()85 if err != nil {86 return err87 }88 serviceMap[args.ServiceName] = service89 serverless.Debug("Successfully registered new service %s\n", args.ServiceName)90 return nil91}92// InvokeService is called by the driver (schedule) when a new task93// is being scheduled on this worker.94func (wk *Worker) InvokeService(args serverless.RPCArgs, _ *struct{}) error {95 serverless.Debug("worker InvokeService: %s\n", args.Name)96 svc, ok := serviceMap[args.Name]97 if !ok {98 msg := fmt.Sprintf("Unknown service in call to InvokeService: %s\n", args.Name)99 serverless.Debug(msg)100 return fmt.Errorf(msg)101 }102 svc.interf.DoService(args.Args)103 return nil104}105// Shutdown is called by the driver when all work has been completed.106// No response needed.107func (wk *Worker) Shutdown(_ *struct{}, _ *struct{}) error {108 serverless.Debug("Worker shutdown %s\n", wk.address)109 close(wk.shutdown)110 wk.l.Close()111 return nil112}113// Tell the driver I exist and ready to work:114// register is the internal function that calls the RPC method of Driver.Register115// at the remote driver to register the worker itself.116func (wk *Worker) register(driver string) {117 args := new(serverless.WorkerRegisterArgs)118 args.WorkerAddr = wk.address119 ok := serverless.Call(driver, "Driver.Register", args, new(struct{}))120 if ok == true {121 fmt.Printf("Successfully registered worker %s\n", wk.address)122 } else {123 fmt.Printf("Failed to register worker %s\n", wk.address)124 }125}126// startRPCServer sets up a connection with the driver, registers its address,127// and waits for any of the following two events:128// 1) plugin Services to be registered,129// 2) tasks to be scheduled.130func (wk *Worker) startRPCServer() {131 rpcs := rpc.NewServer()132 rpcs.Register(wk)133 l, err := net.Listen("tcp", wk.address)134 if err != nil {135 log.Fatal("Worker: worker listen error: ", err)136 }137 wk.l = l138 defer wk.l.Close()139 wk.register(wk.masterAddr)140 // DON'T MODIFY CODE BELOW141 serverless.Debug("Worker: %v To start the RPC server...\n", wk.address)142loop:143 for {144 select {145 case <-wk.shutdown:146 break loop147 default:148 }149 wk.Lock()150 if wk.nRPC == 0 {151 wk.Unlock()152 break153 }154 wk.Unlock()155 conn, err := wk.l.Accept()156 if err == nil {157 wk.Lock()158 wk.nRPC--159 wk.Unlock()160 go rpcs.ServeConn(conn)161 wk.Lock()162 wk.nTasks++163 wk.Unlock()164 } else {165 break166 }167 }168 serverless.Debug("Worker: %v RPC server exist\n", wk.address)169}170// The main entrance of worker.go171func main() {172 wk := new(Worker)173 wk.address = os.Args[1] // the 1st cmd-line argument: worker hostname and ip addr174 wk.masterAddr = os.Args[2] // the 2nd cmd-line argument: driver hostname and ip addr175 nRPC, err := strconv.Atoi(os.Args[3]) // the 3rd cmd-line argument: number of RPC requests176 if err != nil {177 log.Fatal("strconv.Atoi failed")178 }179 wk.nRPC = nRPC180 wk.shutdown = make(chan struct{})181 wk.nTasks = 0182 wk.startRPCServer()183}...

Full Screen

Full Screen

schedule.go

Source:schedule.go Github

copy

Full Screen

...34 // Make, for example, serviceName "wc", and phase "Map", into35 // a valid service, like, for example, "wcm_service".36 pluginName := ServiceName(serviceName, phase)37 // The jobChan is a queue of jobs to be exected. Allows failed jobs to38 // be requeued by invokeService when they fail39 var nTasks int40 var jobChan chan *MapReduceArgs41 Debug("Driver: Creating jobs\n")42 if phase == mapPhase {43 nTasks = len(drv.inFiles)44 jobChan = make(chan *MapReduceArgs, nTasks)45 for i, fileName := range drv.inFiles {46 arg := new(MapReduceArgs)47 arg.TaskNum = i48 arg.JobName = serviceName49 arg.InFile = fileName50 arg.NReduce = drv.nReduce51 arg.SampleKeys = drv.sampleKeys52 jobChan <- arg53 }54 } else {55 nTasks = drv.nReduce56 jobChan = make(chan *MapReduceArgs, nTasks)57 for i := 0; i < nTasks; i++ {58 arg := new(MapReduceArgs)59 arg.TaskNum = i60 arg.JobName = serviceName61 arg.NReduce = drv.nReduce62 arg.NOthers = len(drv.inFiles)63 arg.SampleKeys = drv.sampleKeys64 jobChan <- arg65 }66 }67 Debug("Driver: Creating jobs\n")68 // readyChan is a bounded buffer that is used to notify the69 // scheduler of workers that are *TRULY* ready for executing the70 // service tasks.71 readyChan := make(chan string, nTasks)72 // Complete chan allow main thread to know73 // when all workers have finished.74 completeChan := make(chan bool, nTasks)75 // invokeService is a goroutine that is used to call the RPC76 // method of Worker.InvokeService at the worker side.77 invokeService := func(worker string, args *MapReduceArgs) {78 var buf bytes.Buffer79 enc := gob.NewEncoder(&buf)80 err := enc.Encode(args)81 checkError(err)82 rpc_args := new(RPCArgs)83 rpc_args.Name = pluginName84 rpc_args.Args = buf.Bytes()85 success := Call(worker, "Worker.InvokeService", rpc_args, new(struct{}))86 // If success, then put the worker back in the queue, and report the task done.87 if success {88 // Notify the scheduler that this worker is back to ready state.89 readyChan <- worker90 // Notify scheduler that this task is complete.91 completeChan <- true92 } else {93 // Job failed, so put job back in queue to be executed94 jobChan <- args95 log.Printf("Schedule: task failed to execute by %v: %v\n", worker, args.TaskNum)96 }97 }98 // Get new workers, or ones ready for99 // more work, and assign tasks to them.100 runner := func() {101 Debug("Driver: Job runner waiting for jobs\n")102 // wait for a job103 for arg := range jobChan {104 Debug("Driver: Job runner got job\n")105 var worker string106 // assign107 select {108 case worker = <-registerChan:109 go invokeService(worker, arg)110 case worker = <-readyChan:111 go invokeService(worker, arg)112 }113 }114 }115 Debug("Driver: starting runner\n")116 go runner()117 // Wait for all tasks to complete before returning118 Debug("Driver: Waiting for tasks to be complete\n")119 for i := 0; i < nTasks; i++ {120 <-completeChan121 }122 // Work done: finish the task scheduling123 Debug("Driver: Task scheduling done\n")124}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

1package main2import (3 "log"4 "net"5 "net/http"6 "os"7 "github.com/gin-gonic/gin"8 "github.com/mchmarny/gcputil/env"9 "go.opencensus.io/plugin/ochttp"10 "go.opencensus.io/trace"11 dapr "github.com/mchmarny/godapr/v1"12)13const (14 traceExporterNotSet = "trace-not-set"15)16var (17 logger = log.New(os.Stdout, "PROCESSOR == ", 0)18 // AppVersion will be overritten during build19 AppVersion = "v0.0.1-default"20 // service21 servicePort = env.MustGetEnvVar("PORT", "8081")22 // dapr23 daprClient Client24 // test client against local interace25 _ = Client(dapr.NewClient())26 stateStore = env.MustGetEnvVar("PROCESSOR_STATE_STORE_NAME", "tweet-store")27 eventTopic = env.MustGetEnvVar("PROCESSOR_PUBSUB_TOPIC_NAME", "processed")28 scoreService = env.MustGetEnvVar("PROCESSOR_SCORE_SERVICE_NAME", "sentimenter")29 scoreMethod = env.MustGetEnvVar("PROCESSOR_SCORE_METHOD_NAME", "score")30 exporterURL = env.MustGetEnvVar("TRACE_EXPORTER_URL", traceExporterNotSet)31)32func main() {33 gin.SetMode(gin.ReleaseMode)34 daprClient = dapr.NewClient()35 // router36 r := gin.New()37 r.Use(gin.Recovery())38 r.Use(Options)39 // simple routes40 r.GET("/", defaultHandler)41 r.POST("/tweets", tweetHandler)42 // server43 hostPort := net.JoinHostPort("0.0.0.0", servicePort)44 logger.Printf("Server (%s) starting: %s \n", AppVersion, hostPort)45 if err := http.ListenAndServe(hostPort, &ochttp.Handler{Handler: r}); err != nil {46 logger.Fatalf("server error: %v", err)47 }48}49// Options midleware50func Options(c *gin.Context) {51 if c.Request.Method != "OPTIONS" {52 c.Next()53 } else {54 c.Header("Access-Control-Allow-Origin", "*")55 c.Header("Access-Control-Allow-Methods", "POST,OPTIONS")56 c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")57 c.Header("Allow", "POST,OPTIONS")58 c.Header("Content-Type", "application/json")59 c.AbortWithStatus(http.StatusOK)60 }61}62// Client is the minim client support for testing63type Client interface {64 SaveState(ctx trace.SpanContext, store, key string, data interface{}) error65 InvokeService(ctx trace.SpanContext, service, method string, data interface{}) (out []byte, err error)66 Publish(ctx trace.SpanContext, topic string, data interface{}) error67}...

Full Screen

Full Screen

invokeService

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := plugin.NewClient(&plugin.ClientConfig{4 Cmd: exec.Command("C:\\Users\\admin\\Desktop\\go\\src\\plugin\\plugin.exe"),5 AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},6 })7 rpcClient, err := client.Client()8 if err != nil {9 panic(err)10 }11 raw, err := rpcClient.Dispense("greeter")12 if err != nil {13 panic(err)14 }15 greeter := raw.(Greeter)16 fmt.Println(greeter.Greet("Plugin"))17}18import (19type Greeter interface {20 Greet(string) string21}22type GreeterImpl struct{}23func (g *GreeterImpl) Greet(name string) string {24 return fmt.Sprintf("Hello, %s", name)25}26func (g *GreeterImpl) InvokeService() string {27}28type GreeterPlugin struct {29}30var Handshake = plugin.HandshakeConfig{31}32var pluginMap = map[string]plugin.Plugin{33 "greeter": &GreeterPlugin{Impl: &GreeterImpl{}},34}35func (p *GreeterPlugin) Server(*plugin.MuxBroker) (interface{}, error) {

Full Screen

Full Screen

invokeService

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := plugin.NewClient(&plugin.ClientConfig{4 Plugins: map[string]plugin.Plugin{5 "greeter": &GreeterPlugin{},6 },7 Cmd: exec.Command("sh", "-c", "go run 2.go"),8 AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},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.(Greeter)19 fmt.Println(greeter.Greet("World"))20}21import (22type GreeterImpl struct{}23func (g *GreeterImpl) Greet(name string) string {24 return fmt.Sprintf("Hello %s", name)25}26func main() {27 plugin.Serve(&plugin.ServeConfig{28 Plugins: map[string]plugin.Plugin{29 "greeter": &GreeterPlugin{Impl: &GreeterImpl{}},30 },31 })32}33import (34type HandshakeConfig struct {35}36type Plugin interface {37 PluginInfo() *PluginInfo38}39type PluginInfo struct {40}41type Greeter interface {42 Greet(name string) string43}44type GreeterPlugin struct {45}46func (g *GreeterPlugin) Server(*plugin.MuxBroker) (interface{}, error) {47}48func (g *GreeterPlugin) Client(b *plugin

Full Screen

Full Screen

invokeService

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 }7 sym, err := p.Lookup("InvokeService")8 if err != nil {9 panic(err)10 }11 invokeService := sym.(func(string) string)12 fmt.Println(invokeService("Hello"))13}

Full Screen

Full Screen

invokeService

Using AI Code Generation

copy

Full Screen

1import com.appcelerator.titanium.TiApplication;2import com.appcelerator.titanium.TiContext;3import com.appcelerator.titanium.TiModule;4import com.appcelerator.titanium.TiProxy;5import com.appcelerator.titanium.TiDict;6import com.appcelerator.titanium.TiCallback;7import com.appcelerator.titanium.TiBlob;8import com.appcelerator.titanium.TiList;9import com.appcelerator.titanium.TiFile;10import com.appcelerator.titanium.util.TiConvert;11import com.appcelerator.titanium.proxy.TiViewProxy;12import com.appcelerator.titanium.view.TiUIView;13import com.appcelerator.titanium.TiBaseActivity;14import java.lang.reflect.Method;15import java.lang.reflect.InvocationTargetException;16{17 private static final String LCAT = "PluginModule";18 private static final boolean DBG = TiConfig.LOGD;19 public PluginModule(TiContext tiContext)20 {21 super(tiContext);22 }23 public void invokeService(String className, String methodName, Object[] params, TiCallback callback)24 {25 {26 Class<?> c = Class.forName(className);27 Object obj = c.newInstance();28 Method m = c.getDeclaredMethod(methodName, new Class[] {Object[].class, TiCallback.class});29 m.invoke(obj, params, callback);30 }31 catch (Exception e)32 {33 e.printStackTrace();34 }35 }36}37import com.appcelerator.titanium.TiApplication;38import com.appcelerator.titanium.TiContext;39import com.appcelerator.titanium.TiModule;40import com.appcelerator.titanium.TiProxy;41import com.appcelerator.titanium.TiDict;42import com.appcelerator.titanium.TiCallback;43import com.appcelerator.titanium.TiBlob;44import com.appcelerator.titanium.TiList;45import com.appcelerator.titanium.TiFile;46import com.appcelerator.titanium.util.TiConvert;47import com.appcelerator.titanium.proxy.TiViewProxy;48import com.appcelerator.titanium.view.TiUIView;49import com.appcelerator.titan

Full Screen

Full Screen

invokeService

Using AI Code Generation

copy

Full Screen

1import com.vmware.vim25.mo.*;2import java.net.URL;3import java.net.MalformedURLException;4import java.rmi.RemoteException;5import com.vmware.vim25.*;6{

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