Пример #1
0
func InitMsgSvrClient() error {
	var err error
	MsgSvrClient, err = rpc.Dial(Conf.MsgSvr.Network, Conf.MsgSvr.Addr)
	if err != nil {
		return err
	}

	// rpc Ping
	go func() {
		for {
			reply := 0
			if err := MsgSvrClient.Call("MessageRPC.Ping", 0, &reply); err != nil {
				Log.Error("rpc.Call(\"MessageRPC.Ping\") failed (%v)", err)
				rpcTmp, err := rpc.Dial("tcp", Conf.Addr)
				if err != nil {
					Log.Error("rpc.Dial(\"tcp\", %s) failed (%v)", Conf.Addr, err)
					time.Sleep(time.Duration(Conf.MsgSvr.Retry) * time.Second)
					Log.Warn("rpc reconnect \"%s\" after %d second", Conf.Addr, Conf.MsgSvr.Retry)
				} else {
					Log.Info("rpc client reconnect \"%s\" ok", Conf.Addr)
					MsgSvrClient = rpcTmp
				}

				continue
			}

			// every one second send a heartbeat ping
			Log.Debug("rpc ping ok")
			time.Sleep(time.Duration(Conf.MsgSvr.Heartbeat) * time.Second)
		}
	}()

	return nil
}
Пример #2
0
func (m *mGocode) Call() (interface{}, string) {
	e := ""
	res := M{}
	c, err := rpc.Dial("tcp", mGocodeAddr)
	if err != nil {
		if serveErr := mGocodeServe(m); serveErr != nil {
			return res, "Error starting gocode server: " + serveErr.Error()
		}

		for i := 0; err != nil && i < 5; i += 1 {
			time.Sleep(20 * time.Millisecond)
			c, err = rpc.Dial("tcp", mGocodeAddr)
		}

		if err != nil {
			return res, "Error connecting to gocode server: " + err.Error()
		}
	}
	defer c.Close()

	switch m.cmd {
	case "set":
		for k, v := range m.Set {
			mGocodeCmdSet(c, k, v)
		}
		res, e = mGocodeCmdSet(c, "\x00", "\x00")
	case "complete":
		pos := 0
		if m.Complete.Src == "" {
			// this is here for testing, the client should always send the src
			s, _ := ioutil.ReadFile(m.Complete.Fn)
			m.Complete.Src = string(s)
		}

		for i, _ := range m.Complete.Src {
			pos += 1
			if pos >= m.Complete.Pos {
				pos = i
				break
			}
		}
		res, e = mGocodeCmdComplete(c, m.Complete.Fn, []byte(m.Complete.Src), pos)
	default:
		panic("Unsupported command: gocode: " + m.cmd)
	}

	return res, e
}
Пример #3
0
Файл: web.go Проект: aart/poc
func getTransportOrder(w http.ResponseWriter, r *http.Request) {

	u := r.URL
	q := u.Query()
	in := q.Get("id")

	client, err := rpc.Dial("tcp", "localhost:42586")
	if err != nil {
		log.Fatal(err)
	}

	var out pack.TransportOrder

	err = client.Call("Listener.GetTransportOrderById", in, &out)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("web layer - getTransportOrder: ", out)

	b, err := json.MarshalIndent(out, "", "   ")
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w, string(b))

}
Пример #4
0
func TestEcho(t *testing.T) {
	routerAddr := "127.0.0.1:14817"

	r, _ := New("id", routerAddr, "")
	err := r.Start()
	if err != nil {
		t.Fatal("router start:", err)
	}
	defer r.Stop()

	time.Sleep(time.Millisecond * 50)

	client, err := rpc.Dial("tcp", ":14817")
	if err != nil {
		t.Fatal("dialing:", err)
	}

	reply := new(Reply)
	err = client.Call("RouterRPC.Echo", "hello router!", reply)
	if err != nil {
		t.Fatal("router rpc:", err)
	}

	assert.Equal(t, reply.Value, "hello router!")
}
Пример #5
0
func (lt *localRPCTransport) getClient(id proto.RaftNodeID) (*rpc.Client, error) {
	lt.mu.Lock()
	defer lt.mu.Unlock()

	select {
	case <-lt.closed:
		return nil, util.Errorf("transport is closed")
	default:
	}

	client, ok := lt.clients[id]
	if ok {
		return client, nil
	}

	listener, ok := lt.listeners[id]
	if !ok {
		return nil, util.Errorf("unknown peer %v", id)
	}
	address := listener.Addr().String()

	// If this wasn't test code we wouldn't want to call Dial while holding the lock.
	client, err := rpc.Dial("tcp", address)
	if err != nil {
		return nil, err
	}
	lt.clients[id] = client
	return client, err
}
Пример #6
0
func TestRunFailure(t *testing.T) {
	// Create a queue & start the resource
	q := Queue{authToken: "FailureTest"}
	l := startRPCOnce("tcp", addr, &q)
	defer l.Close()

	// Add the failure tool
	tool := new(simpleFailerTooler)
	tool.SetUUID(uuid.New())
	q.tools = append(q.tools, tool)

	// Build the RPC client
	client, err := rpc.Dial("tcp", addr)
	if err != nil {
		t.Fatal("Error dailing RPC servers.", err)
	}

	// Build the job to send to the simpleFailureTask
	params := map[string]string{"failFunc": "Run"}
	job := common.NewJob(tool.UUID(), "Failure Test", "GoTestSuite", params)

	// Try and create the job... we should get a failure
	call := common.RPCCall{Auth: "FailureTest", Job: job}
	err = client.Call("Queue.AddTask", call, nil)
	if err == nil {
		t.Fatal("Failure task's error was not returned.")
	}
}
Пример #7
0
// jujuCMain uses JUJU_CONTEXT_ID and JUJU_AGENT_SOCKET to ask a running unit agent
// to execute a Command on our behalf. Individual commands should be exposed
// by symlinking the command name to this executable.
func jujuCMain(commandName string, args []string) (code int, err error) {
	code = 1
	contextId, err := getenv("JUJU_CONTEXT_ID")
	if err != nil {
		return
	}
	dir, err := getwd()
	if err != nil {
		return
	}
	req := jujuc.Request{
		ContextId:   contextId,
		Dir:         dir,
		CommandName: commandName,
		Args:        args[1:],
	}
	socketPath, err := getenv("JUJU_AGENT_SOCKET")
	if err != nil {
		return
	}
	client, err := rpc.Dial("unix", socketPath)
	if err != nil {
		return
	}
	defer client.Close()
	var resp jujuc.Response
	err = client.Call("Jujuc.Main", req, &resp)
	if err != nil {
		return
	}
	os.Stdout.Write(resp.Stdout)
	os.Stderr.Write(resp.Stderr)
	return resp.Code, nil
}
Пример #8
0
func TestProvisionerRPC(t *testing.T) {
	assert := asserts.NewTestingAsserts(t, true)

	// Create the interface to test
	p := new(testProvisioner)

	// Start the server
	server := rpc.NewServer()
	RegisterProvisioner(server, p)
	address := serveSingleConn(server)

	// Create the client over RPC and run some methods to verify it works
	client, err := rpc.Dial("tcp", address)
	assert.Nil(err, "should be able to connect")

	// Test Prepare
	config := 42
	pClient := Provisioner(client)
	pClient.Prepare(config)
	assert.True(p.prepareCalled, "prepare should be called")
	assert.Equal(p.prepareConfigs, []interface{}{42}, "prepare should be called with right arg")

	// Test Provision
	ui := &testUi{}
	comm := new(packer.MockCommunicator)
	pClient.Provision(ui, comm)
	assert.True(p.provCalled, "provision should be called")

	p.provUi.Say("foo")
	assert.True(ui.sayCalled, "say should be called")
}
Пример #9
0
func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s server:port\n", os.Args[0])
		os.Exit(1)
	}

	service := os.Args[1]

	client, err := rpc.Dial("tcp", service)
	if err != nil {
		log.Fatal("Dialing:", err)
	}

	args := Args{17, 8}
	var reply int

	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error", err)
	}
	fmt.Printf("Arith: %d * %d = %d\n", args.A, args.B, reply)

	var quot Quotient
	err = client.Call("Arith.Divide", args, &quot)
	if err != nil {
		log.Fatal("arith error", err)
	}
	fmt.Printf("Arith: %d / %d = %d, remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)

}
Пример #10
0
func (self *Application) ExecClient() (result bool) {
	if flag.NArg() == 0 {
		ShowApplicationUsage()
		return false
	}

	rpcClient, err := rpc.Dial(GetServiceSocket(self.tcpPort))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Cannot open RPC connection: %v\n", err)
		return false
	}

	switch flag.Arg(0) {
	case "close":
		ClientCloseService(rpcClient)
	case "reload":
		ClientReloadService(rpcClient)
	case "scan":
		if flag.NArg() != 2 {
			ShowApplicationUsage()
			return false
		}
		inputPath, err := filepath.Abs(flag.Arg(1))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Cannot get full path from '%s'\n", flag.Arg(1))
			return false
		}
		result := ClientScanEmotions(rpcClient, inputPath)
		fmt.Fprintf(os.Stdout, "Text has %d words, %.2f%% positive and %.2f%% negative\n", result.WordCount, result.PercentPositive, result.PercentNegative)
	default:
		ShowApplicationUsage()
		return false
	}
	return true
}
Пример #11
0
func GetTradeProfile() {
	var InputFromUser int
	InputFromUser = 0
	fmt.Println(InputFromUser)
	c, err := rpc.Dial("tcp", "127.0.0.1:9999")

	if err != nil {
		fmt.Println(err)
		return
	}

	if InputFromUser == 2 {
		Sr1.TradeId = 1
		fmt.Println("Second function here")
		err = c.Call("Server.GetTradeProfile", Sr1, &Sresp)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println("Trade ID: ", Sresp.TradeId, " and Remaining amount: ", Sresp.UnvestedAmount)

		for index := 0; index < len(Sresp.NumberOfStocks); index++ {
			if Sresp.Name[index] != "" {
				fmt.Println("Name of Stock", Sresp.Name[index], " Number of Stocks", Sresp.NumberOfStocks[index], " Value of Stock", Sresp.ProfitLoss[index], Sresp.StockValue[index])
			}
		}

		fmt.Println("Current total value ", Sresp.CurrentMarketValue)
	}

}
Пример #12
0
func Test_Proto_Binary_Large_Timeout(t *testing.T) {
	t.Skip()
	srv := &binaryTestServer{&baseTestServer{}}
	port, err := srv.listen()
	assert.NoError(t, err)
	srv.start()
	defer srv.Stop()

	client, err := rpc.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
	assert.NoError(t, err)
	defer client.Close()

	var res, res1 TestMessage
	req := TestMessage{
		"12345678910",
		[]byte(strings.Repeat("0", 1024*1024)),
	}
	err = client.Call("ServiceFixture.Ping", &req, &res)
	assert.NoError(t, err)
	assert.Equal(t, req, res)

	time.Sleep(time.Second)
	err = client.Call("ServiceFixture.Ping", &req, &res1)
	assert.NoError(t, err)
	assert.Equal(t, req, res1)
}
Пример #13
0
func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ", os.Args[0], "server:port")
		os.Exit(1)
	}
	service := os.Args[1]

	client, err := rpc.Dial("tcp", service)
	if err != nil {
		log.Fatal("dialing:", err)
	}
	// Synchronous call
	args := Args{17, 8}
	var reply int
	err = client.Call("Math.Multiply", args, &reply)
	if err != nil {
		log.Fatal("Math error:", err)
	}
	fmt.Printf("Math: %d*%d=%d\n", args.A, args.B, reply)

	var quot Quotient
	err = client.Call("Math.Divide", args, &quot)
	if err != nil {
		log.Fatal("Math error:", err)
	}
	fmt.Printf("Math: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)

}
Пример #14
0
func Benchmark_Proto_Binary_Large(b *testing.B) {
	b.Skip()
	srv := &binaryTestServer{&baseTestServer{}}
	port, err := srv.listen()
	assert.NoError(b, err)
	srv.start()
	defer srv.Stop()

	client, err := rpc.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
	assert.NoError(b, err)
	defer client.Close()

	b.Log(port)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StartTimer()
		var res TestMessage
		req := TestMessage{
			"12345678910",
			[]byte(strings.Repeat("0", 1024*1024)),
		}
		err = client.Call("ServiceFixture.Ping", &req, &res)
		b.StopTimer()
		assert.NoError(b, err)
		assert.Equal(b, req, res)
		b.SetBytes(int64(len(req.Data) * 2))
	}
}
Пример #15
0
func isLeader(rpc_port int) bool {
	client, err := rpc.Dial("tcp", "localhost"+":"+strconv.Itoa(rpc_port))

	reply := -1
	if err != nil {

		return false
	} else {

		I := 10

		errr := client.Call("RaftRPC.Phase", &I, &reply)
		if errr != nil {

			//fmt.Println("\nError comes")
			return false
		}
		client.Close()
	}
	//fmt.Printf("\n")
	//fmt.Printf("Rk="+strconv.Itoa(reply))
	if reply == 1 {
		//fmt.Printf("\nReturning true")
		return true
	}
	return false
}
Пример #16
0
func main() {
	client, err := rpc.Dial("tcp", "localhost:42586")
	//client, err := rpc.Dial("tcp", "moore.ucsd.edu:42586")
	if err != nil {
		log.Fatal(err)
	}

	in := bufio.NewReader(os.Stdin)
	//in := bufio.NewReader("hello")
	for {

		fmt.Println("hi, please input so that I can send: ")
		line, _, err := in.ReadLine()
		if err != nil {
			log.Fatal(err)
		}
		var reply bool
		fmt.Println("hi")
		err = client.Call("Listener.GetLine", line, &reply)
		fmt.Println("GetLine: ", reply)
		if err != nil {
			log.Fatal(err)
		}
	}
}
Пример #17
0
func do_client() int {
	addr := *g_disp_addr
	sock := "tcp"

	// client
	client, err := rpc.Dial(sock, addr)
	if err != nil {
		client, err = try_to_connect(sock, addr)
		if err != nil {
			fmt.Printf("%s\n", err.Error())
			return 1
		}
	}
	defer client.Close()

	if flag.NArg() > 0 {
		switch flag.Arg(0) {
		case "close":
			cmd_close(client)
		case "status":
			cmd_status(client)
		}
	}
	return 0
}
Пример #18
0
// command: run.
func run(cmd, proc string) error {
	client, err := rpc.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", *port))
	if err != nil {
		return err
	}
	defer client.Close()
	var ret string
	switch cmd {
	case "start":
		return client.Call("Goreman.Start", proc, &ret)
	case "stop":
		return client.Call("Goreman.Stop", proc, &ret)
	case "restart":
		return client.Call("Goreman.Restart", proc, &ret)
	case "list":
		err := client.Call("Goreman.List", "", &ret)
		fmt.Print(ret)
		return err
	case "dump":
		err := client.Call("Goreman.Dump", "", &ret)
		fmt.Print(ret)
		return err
	}
	return errors.New("Unknown command")
}
Пример #19
0
func (cliConnection *cliConnection) callCliCommand(silently bool, args ...string) ([]string, error) {
	client, err := rpc.Dial("tcp", "127.0.0.1:"+cliConnection.cliServerPort)
	if err != nil {
		return []string{}, err
	}
	defer client.Close()

	var success bool

	client.Call("CliRpcCmd.DisableTerminalOutput", silently, &success)
	err = client.Call("CliRpcCmd.CallCoreCommand", args, &success)

	var cmdOutput []string
	outputErr := client.Call("CliRpcCmd.GetOutputAndReset", success, &cmdOutput)

	if err != nil {
		return cmdOutput, err
	} else if !success {
		return cmdOutput, errors.New("Error executing cli core command")
	}

	if outputErr != nil {
		return cmdOutput, errors.New("something completely unexpected happened")
	}
	return cmdOutput, nil
}
Пример #20
0
func (p *postProcessor) PostProcess(ui packer.Ui, a packer.Artifact) (packer.Artifact, bool, error) {
	server := rpc.NewServer()
	RegisterArtifact(server, a)
	RegisterUi(server, ui)

	var response PostProcessorProcessResponse
	if err := p.client.Call("PostProcessor.PostProcess", serveSingleConn(server), &response); err != nil {
		return nil, false, err
	}

	if response.Err != nil {
		return nil, false, response.Err
	}

	if response.RPCAddress == "" {
		return nil, false, nil
	}

	client, err := rpc.Dial("tcp", response.RPCAddress)
	if err != nil {
		return nil, false, err
	}

	return Artifact(client), response.Keep, nil
}
Пример #21
0
func TestArtifactRPC(t *testing.T) {
	// Create the interface to test
	a := new(testArtifact)

	// Start the server
	server := rpc.NewServer()
	RegisterArtifact(server, a)
	address := serveSingleConn(server)

	// Create the client over RPC and run some methods to verify it works
	client, err := rpc.Dial("tcp", address)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	aClient := Artifact(client)

	// Test
	if aClient.BuilderId() != "bid" {
		t.Fatalf("bad: %s", aClient.BuilderId())
	}

	if !reflect.DeepEqual(aClient.Files(), []string{"a", "b"}) {
		t.Fatalf("bad: %#v", aClient.Files())
	}

	if aClient.Id() != "id" {
		t.Fatalf("bad: %s", aClient.Id())
	}

	if aClient.String() != "string" {
		t.Fatalf("bad: %s", aClient.String())
	}
}
Пример #22
0
func (p *PostProcessorServer) PostProcess(address string, reply *PostProcessorProcessResponse) error {
	client, err := rpc.Dial("tcp", address)
	if err != nil {
		return err
	}

	responseAddress := ""

	artifact, keep, err := p.p.PostProcess(&Ui{client}, Artifact(client))
	if err == nil && artifact != nil {
		server := rpc.NewServer()
		RegisterArtifact(server, artifact)
		responseAddress = serveSingleConn(server)
	}

	if err != nil {
		err = NewBasicError(err)
	}

	*reply = PostProcessorProcessResponse{
		Err:        err,
		Keep:       keep,
		RPCAddress: responseAddress,
	}

	return nil
}
Пример #23
0
Файл: rpc.go Проект: yubo/gotty
func Call(serviceMethod string, args interface{}, reply interface{}) error {
	client, err := rpc.Dial("unix", GlobalOpt.UnixSocket)
	if err != nil {
		return err
	}
	return client.Call(serviceMethod, args, reply)
}
Пример #24
0
func (s *ServerSuite) Call(c *C, req jujuc.Request) (resp jujuc.Response, err error) {
	client, err := rpc.Dial("unix", s.sockPath)
	c.Assert(err, IsNil)
	defer client.Close()
	err = client.Call("Jujuc.Main", req, &resp)
	return resp, err
}
Пример #25
0
// Main server loop.
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	checkArgs()

	kvAddr := os.Args[1]
	myID = os.Args[2]

	verbosePrintOnOff = true

	// Connect to the KV-service via RPC.
	var err error
	kvService, err = rpc.Dial("tcp", kvAddr)
	checkError(err)

	lastNum = 1
	leaderNum = 1
	registerNum = 1
	myIDNum = 1
	activeNodeKey = 1

	currentNodeKey = make(map[string]int)
	currentNodeNum = make(map[string]int)
	activeNodes = []string{}

	checkForLeader()

}
Пример #26
0
func main() {
	client, err := rpc.Dial("tcp", "127.0.0.1:60000")
	if err != nil {
		fmt.Printf("dialing:%v\n", err)
		return
	}

	var args = "hello rpc"
	var reply string
	err = client.Call("RPC.Ping", args, &reply)
	if err != nil {
		fmt.Printf("RPC.Ping error:%v\n", err)
	} else {
		fmt.Printf("RPC.Ping: %v %v\n", args, reply)
	}

	//err = client.Go("DefaultAuther.Auth", 1, &reply, nil).Done
	//if err != nil {
	//	fmt.Printf("RPC.Auth error:%v\n", err)
	//} else {
	//	fmt.Printf("RPC.Auth: %v %v\n", args, reply)
	//}

	// ping
	tickJob(client)
}
Пример #27
0
func NewRpcClient(addr string) (c *RpcClient, err error) {
	var cli *rpc.Client
	if cli, err = rpc.Dial("tcp", addr); err != nil {
		return
	}
	return &RpcClient{cli}, nil
}
Пример #28
0
// testRPCClient returns an RPCClient connected to an RPC server that
// serves only this connection.
func testRPCClient(t *testing.T) (*RPCClient, *Agent) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	agent := testAgent()
	server := rpc.NewServer()
	if err := registerEndpoint(server, agent); err != nil {
		l.Close()
		t.Fatalf("err: %s", err)
	}

	go func() {
		conn, err := l.Accept()
		l.Close()
		if err != nil {
			t.Fatalf("err: %s", err)
		}
		defer conn.Close()
		server.ServeConn(conn)
	}()

	rpcClient, err := rpc.Dial("tcp", l.Addr().String())
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	return &RPCClient{Client: rpcClient}, agent
}
Пример #29
0
func NewServer() (*Server, error) {
	// connect dao server
dao:
	daocli, err := rpc.Dial("tcp", cfg.DaoAddr())
	if err != nil {
		log.Warningf("dao server connect fail(err=%+v), try again...", err.Error())
		time.Sleep(1 * time.Second)
		goto dao
	}

	ctrl := make(chan string, 10)
game:
	cli, err := fw.NewClient(cfg.GameAddr(), &gameCliModel{}, ctrl)
	if err != nil {
		log.Error(err.Error())
		log.Warningf("game server connect fail(err=%+v), try again...", err.Error())
		time.Sleep(1 * time.Second)
		goto game
	}
	go cli.Loop()

	// daemon routine (to be done), with "ctrl"
	// ......
	////////////////////

	// new server
	serverInst = &Server{
		dao:       daocli,
		gameCli:   cli,
		gameCtrl:  ctrl,
		connIdAcc: 0,
		agents:    make(map[int]*fw.Agent, 1000),
	}
	return serverInst, nil
}
Пример #30
0
// NewClient makes a Client that uses h and dials address.
func NewClient(c Configuration, address string) (Client, error) {
	var client, err = rpc.Dial("tcp", address)
	if err != nil {
		return Client{}, err
	}
	return Client{Client: client, Configuration: c, Name: "Marketing"}, nil // Default receiver name is "Marketing".
}