Beispiel #1
0
/////////////////////////////////
//MAIN
/////////////////////////////////
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
	var memprofile = flag.String("memprofile", "", "write memory profile to this file")
	var id *int = flag.Int("i", 0, "id [num]")
	var port1 *int = flag.Int("p1", 8000, "port1 [num]")
	var port2 *int = flag.Int("p2", 8001, "port2 [num]")
	var servers *string = flag.String("s", "", "servers [file]")
	var numClients *int = flag.Int("n", 0, "num clients [num]")
	var mode *string = flag.String("m", "", "mode [m for microblogging|f for file sharing]")
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	ss := ParseServerList(*servers)

	SetTotalClients(*numClients)

	s := NewServer(*port1, *port2, *id, ss, *mode == "f")

	if *memprofile != "" {
		f, err := os.Create(*memprofile)
		if err != nil {
			log.Fatal(err)
		}
		s.memProf = f
	}

	rpcServer1 := rpc.NewServer()
	rpcServer2 := rpc.NewServer()
	rpcServer1.Register(s)
	rpcServer2.Register(s)
	l1, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port1))
	if err != nil {
		log.Fatal("Cannot starting listening to the port: ", err)
	}
	l2, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port2))
	if err != nil {
		log.Fatal("Cannot starting listening to the port: ", err)
	}
	go rpcServer1.Accept(l1)
	go rpcServer2.Accept(l2)
	s.connectServers()
	fmt.Println("Starting server", *id)
	s.runHandlers()
	fmt.Println("Handler running", *id)

	Wait()
}
Beispiel #2
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
}
Beispiel #3
0
func TestSend(t *testing.T) {
	client, server := net.Pipe()
	go doServiceHandshake(server, true, t)

	cn, err := NewConnectionFromNetConn("TestRPCService", client)
	c := cn.(*Conn)

	s := rpc.NewServer()
	var ts TestRPCService
	s.Register(&ts)
	go s.ServeCodec(bsonrpc.NewServerCodec(server))

	var tp TestParam
	tp.Val1 = "Hello World"
	tp.Val2 = 10

	ri := &skynet.RequestInfo{}

	ts.TestMethod = func(in skynet.ServiceRPCIn, out *skynet.ServiceRPCOut) (err error) {
		out.Out, err = bson.Marshal(&tp)

		var t TestParam

		if err != nil {
			return
		}

		if in.ClientID != c.clientID {
			return errors.New("Failed to set ClientID on request")
		}

		if in.Method != "Foo" {
			return errors.New("Failed to set Method on request")
		}

		if *in.RequestInfo != *ri {
			return errors.New("Failed to set RequestInfo on request")
		}

		err = bson.Unmarshal(in.In, &t)
		if err != nil {
			return
		}

		if t.Val1 != tp.Val1 || tp.Val2 != tp.Val2 {
			return errors.New("Request failed to send proper data")
		}

		return
	}

	err = c.Send(ri, "Foo", tp, &tp)
	if err != nil {
		t.Error(err)
		return
	}

	c.Close()
	server.Close()
}
Beispiel #4
0
func NewServer(config *Config) (*Server, error) {
	s := &Server{
		config:     config,
		eventChLAN: make(chan serf.Event, 256),
		rpcServer:  rpc.NewServer(),
		shutdownCh: make(chan struct{}),
		ambari:     &Ambari{config.AmbariConfig},
	}

	// Get hosts
	hosts, err := NewHostsManager(config.HostsFile)
	if err != nil {
		return nil, err
	}
	s.hosts = hosts
	go s.updateHosts()

	// Setup serf
	serfLAN, err := s.setupSerf()
	if err != nil {
		s.Shutdown()
		return nil, err
	}
	s.serfLAN = serfLAN
	go s.serfEventHandler()

	// Setup RPC and start listening for requests
	if err := s.setupRPC(); err != nil {
		s.Shutdown()
		return nil, err
	}
	go s.listenRPC()

	return s, nil
}
Beispiel #5
0
func (c *ProducerServer) StartRpc() error {
	log.Printf("Start to start rpc! \n")
	server := rpc.NewServer()
	err := c.RegistFunctions(server)
	if err != nil {
		log.Printf("consumer regist failed! \n")
		return err
	}
	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
	log.Printf("Start to listen consumer rpc!%s \n", fmt.Sprintf("%s:%d", c.Address, c.RpcPort))
	l, e := net.Listen("tcp", fmt.Sprintf("%s:%d", c.Address, c.RpcPort))
	if e != nil {
		log.Printf("consumer listen failed err:%s! \n", e)
		return e
	}
	for {
		if c.IsShutDown {
			break
		}
		conn, err := l.Accept()
		if err != nil {
			log.Printf("accept err:%s \n", err)
			return err
		}
		go server.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
	return nil
}
Beispiel #6
0
// NewSuperServiceServer returns a new SuperService Server.
func NewSuperServiceServer(x SuperService) *rpc.Server {
	srv := rpc.NewServer()
	if err := srv.RegisterName("SuperService", x); err != nil {
		log.Fatal(err)
	}
	return srv
}
Beispiel #7
0
func BenchmarkNetrpcByteSlice(b *testing.B) {
	connC, connS := getTcpPipe(b)
	defer connC.Close()
	defer connS.Close()

	s := rpc.NewServer()
	if err := s.Register(&NetrpcService{}); err != nil {
		b.Fatalf("Error when registering rpc service: %s", err)
	}
	go s.ServeConn(connS)

	c := rpc.NewClient(connC)
	defer c.Close()

	req := []byte("byte slice byte slice aaa bbb ccc foobar")
	b.SetParallelism(250)
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		var resp []byte
		for i := 0; pb.Next(); i++ {
			if err := c.Call("NetrpcService.ByteSlice", req, &resp); err != nil {
				b.Fatalf("Unexpected error when calling NetrpcService.ByteSlice(%q): %s", req, err)
			}
			if !bytes.Equal(resp, req) {
				b.Fatalf("Unexpected response: %q. Expected %q", resp, req)
			}
		}
	})
}
Beispiel #8
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())
	}
}
Beispiel #9
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
}
Beispiel #10
0
func runServer(ch chan bool, done chan bool) {
	cert, err := tls.LoadX509KeyPair("../cert.pem", "../key.pem")
	if err != nil {
		log.Fatalf("While loading tls certs: %v", err)
		return
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	ln, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("When listening: %v", err)
		return
	}
	s := rpc.NewServer()
	if err := s.Register(&PostingList{}); err != nil {
		log.Fatalf("Error when registering rpc server: %v", err)
		return
	}

	ch <- true
	log.Debugln("Ready to accept new connection")
	conn, err := ln.Accept()
	if err != nil {
		log.Fatalf("cannot accept incoming tcp conn: %s", err)
		return
	}
	defer conn.Close()
	log.Debugln("Accepted a connection")
	go s.ServeConn(conn)
	<-done
}
Beispiel #11
0
func listenAndServeEchoService(network, addr string,
	serveConn func(srv *rpc.Server, conn io.ReadWriteCloser)) (net.Listener, error) {
	l, err := net.Listen(network, addr)
	if err != nil {
		fmt.Printf("failed to listen on %s: %s\n", addr, err)
		return nil, err
	}
	srv := rpc.NewServer()
	if err := srv.RegisterName("EchoService", new(Echo)); err != nil {
		return nil, err
	}
	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				log.Infof("accept: %v\n", err)
				break
			}
			serveConn(srv, conn)
		}
	}()

	if *onlyEchoServer {
		select {}
	}
	return l, nil
}
Beispiel #12
0
func main() {
	newServer := rpc.NewServer()
	newServer.Register(new(Arith))

	l, e := net.Listen("tcp", "127.0.0.1:1234")
	if e != nil {
		log.Fatalf("net.Listen tcp :0:%v", e)
	}

	go newServer.Accept(l)
	newServer.HandleHTTP("/foo", "/bar")
	time.Sleep(2 * time.Second)

	address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234")
	if err != nil {
		panic(err)
	}
	conn, _ := net.DialTCP("tcp", nil, address)
	defer conn.Close()

	client := rpc.NewClient(conn)
	defer client.Close()

	args := &Args{7, 8}
	reply := make([]string, 10)
	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error: ", err)
	}
	log.Println(reply)
}
Beispiel #13
0
func StartServer(hostname string, hd *hood.Hood) *Master {
	// call gob.Register on structures you want
	// Go's RPC library to marshall/unmarshall.
	// gob.Register()

	gopath := os.Getenv("GOPATH")
	if _, err := os.Stat(gopath + "/src/segments"); err != nil {
		if os.IsNotExist(err) {
			os.Mkdir(gopath+"/src/segments", 0777)
		} else {
			panic(err)
		}
	}

	master := new(Master)

	master.hd = hd
	master.events = make(chan (Event), MAX_EVENTS)
	master.minWorkers = 1

	rpcs := rpc.NewServer()
	rpcs.Register(master)

	// ignore the domain name: listen on all urls
	splitName := strings.Split(hostname, ":")
	l, e := net.Listen("tcp", ":"+splitName[1])
	if e != nil {
		log.Fatal("listen error: ", e)
	}
	master.l = l

	// Recovery procedure
	tx := master.hd.Begin()
	master.getNumAliveWorkers(tx)
	commitOrPanic(tx)
	master.restartPendingRdds()

	// start event loop
	go master.eventLoop()

	go func() {
		for {
			if conn, err := master.l.Accept(); err == nil {
				go rpcs.ServeConn(conn)
			} else {
				master.kill()
			}
		}
	}()

	// create a thread to call tick() periodically.
	go func() {
		for {
			master.tick()
			time.Sleep(TickInterval)
		}
	}()

	return master
}
Beispiel #14
0
//
// the application wants to create a paxos peer.
// the ports of all the paxos peers (including this one)
// are in peers[]. this servers port is peers[me].
//
func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {
	px := &Paxos{}
	px.peers = peers
	px.me = me

	// Your initialization code here.

	if rpcs != nil {
		// caller will create socket &c
		rpcs.Register(px)
	} else {
		rpcs = rpc.NewServer()
		rpcs.Register(px)

		// prepare to receive connections from clients.
		// change "unix" to "tcp" to use over a network.
		os.Remove(peers[me]) // only needed for "unix"
		l, e := net.Listen("unix", peers[me])
		if e != nil {
			log.Fatal("listen error: ", e)
		}
		px.l = l

		// please do not change any of the following code,
		// or do anything to subvert it.

		// create a thread to accept RPC connections
		go func() {
			for px.dead == false {
				conn, err := px.l.Accept()
				if err == nil && px.dead == false {
					if px.unreliable && (rand.Int63()%1000) < 100 {
						// discard the request.
						conn.Close()
					} else if px.unreliable && (rand.Int63()%1000) < 200 {
						// process the request but force discard of reply.
						c1 := conn.(*net.UnixConn)
						f, _ := c1.File()
						err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
						if err != nil {
							fmt.Printf("shutdown: %v\n", err)
						}
						px.rpcCount++
						go rpcs.ServeConn(conn)
					} else {
						px.rpcCount++
						go rpcs.ServeConn(conn)
					}
				} else if err == nil {
					conn.Close()
				}
				if err != nil && px.dead == false {
					fmt.Printf("Paxos(%v) accept: %v\n", me, err.Error())
				}
			}
		}()
	}

	return px
}
Beispiel #15
0
func main() {
	var err error

	clientApp := exec.Command("./client-example", "")

	rwc := new(ReadWriteCloser)

	rwc.WriteCloser, err = clientApp.StdinPipe()
	if err != nil {
		log.Fatal(err)
	}

	rwc.ReadCloser, err = clientApp.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}

	serv := rpc.NewServer()
	codec := jsonrpc.NewServerCodec(rwc)
	fmt.Println("Made RPC server")
	m := new(Adder)
	serv.Register(m)
	fmt.Println("Registered adder service")

	err = clientApp.Start()
	if err != nil {
		log.Fatal(err)
	}

	go serv.ServeCodec(codec)

	clientApp.Wait()

	fmt.Printf("Adder has been called %d times and is now: %d\n", no, *m)
}
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")
}
Beispiel #17
0
func CreateService(sd ServiceDelegate, c *skynet.ServiceConfig) (s *Service) {
	// This will set defaults
	initializeConfig(c)

	s = &Service{
		Config:         c,
		Delegate:       sd,
		Log:            c.Log,
		methods:        make(map[string]reflect.Value),
		connectionChan: make(chan *net.TCPConn),
		registeredChan: make(chan bool),
		doozerChan:     make(chan interface{}),
		slotsChan:      make(chan int),
	}

	c.Log.Item(ServiceCreated{
		ServiceConfig: s.Config,
	})
	// the main rpc server
	s.RPCServ = rpc.NewServer()
	rpcForwarder := NewServiceRPC(s.Delegate, c.Log)

	c.Log.Item(RegisteredMethods{rpcForwarder.MethodNames})

	s.RPCServ.RegisterName(s.Config.Name, rpcForwarder)

	return
}
Beispiel #18
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
}
Beispiel #19
0
func BenchmarkNetrpcInt(b *testing.B) {
	connC, connS := getTcpPipe(b)
	defer connC.Close()
	defer connS.Close()

	s := rpc.NewServer()
	if err := s.Register(&NetrpcService{}); err != nil {
		b.Fatalf("Error when registering rpc service: %s", err)
	}
	go s.ServeConn(connS)

	c := rpc.NewClient(connC)
	defer c.Close()

	b.SetParallelism(250)
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		var x int
		for i := 0; pb.Next(); i++ {
			if err := c.Call("NetrpcService.Int", i, &x); err != nil {
				b.Fatalf("Unexpected error when calling NetrpcService.Int(%d): %s", i, err)
			}
			if i != x {
				b.Fatalf("Unexpected response: %d. Expected %d", x, i)
			}
		}
	})
}
// Set up a connection with the master, register with the master,
// and wait for jobs from the master
func RunWorker(MasterAddress string, me string,
	MapFunc func(string) *list.List,
	ReduceFunc func(string, *list.List) string, nRPC int) {
	DPrintf("RunWorker %s\n", me)
	wk := new(Worker)
	wk.name = me
	wk.Map = MapFunc
	wk.Reduce = ReduceFunc
	wk.nRPC = nRPC
	rpcs := rpc.NewServer()
	rpcs.Register(wk)
	os.Remove(me) // only needed for "unix"
	l, e := net.Listen("unix", me)
	if e != nil {
		log.Fatal("RunWorker: worker ", me, " error: ", e)
	}
	wk.l = l
	Register(MasterAddress, me)

	// DON'T MODIFY CODE BELOW
	for wk.nRPC != 0 {
		conn, err := wk.l.Accept()
		if err == nil {
			wk.nRPC -= 1
			go rpcs.ServeConn(conn)
			wk.nJobs += 1
		} else {
			break
		}
	}
	wk.l.Close()
	DPrintf("RunWorker %s exit\n", me)
}
Beispiel #21
0
func (d *Daemon) init() error {
	d.quit = false
	ifs := []interface{}{
		&content.Session{},
		&clang.Clang{},
		&java.Java{},
		&cnet.Net{},
	}
	d.server = rpc.NewServer()

	for _, i := range ifs {
		if err := d.server.Register(i); err != nil {
			return err
		}
	}
	if proto == "unix" && rmFile {
		os.Remove(port)
	}
	var err error
	d.l, err = net.Listen(proto, port)
	if err != nil {
		return err
	}
	return nil
}
Beispiel #22
0
func Init(listenAddr string, supervisorPort uint16, cpuIncr, memIncr uint, resDuration time.Duration) error {
	var err error
	err = LoadEnvs()
	if err != nil {
		return err
	}
	CPUSharesIncrement = cpuIncr
	MemoryLimitIncrement = memIncr
	atlantis.Tracker.ResultDuration = resDuration
	// init rpc stuff here
	lAddr = listenAddr
	lPort = strings.Split(lAddr, ":")[1]
	supervisor.Init(fmt.Sprintf("%d", supervisorPort))
	manager.Init(lPort)
	manager := new(ManagerRPC)
	server = rpc.NewServer()
	server.Register(manager)
	config := &tls.Config{}
	config.InsecureSkipVerify = true
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.X509KeyPair(crypto.SERVER_CERT, crypto.SERVER_KEY)

	l, err = tls.Listen("tcp", lAddr, config)
	return err
}
Beispiel #23
0
//
// servers[] contains the ports of the set of
// servers that will cooperate via Paxos to
// form the fault-tolerant key/value service.
// me is the index of the current server in servers[].
//
func StartServer(servers []string, me int) *KVPaxos {
	// call gob.Register on structures you want
	// Go's RPC library to marshall/unmarshall.
	gob.Register(Op{})

	kv := new(KVPaxos)
	kv.me = me

	// initialization
	kv.kvData = make(map[string]string)
	kv.preReply = make(map[string]*Op)
	kv.seqChan = make(map[int]chan *Op)
	kv.maxInstanceID = -1

	rpcs := rpc.NewServer()
	rpcs.Register(kv)

	kv.px = paxos.Make(servers, me, rpcs)

	os.Remove(servers[me])
	l, e := net.Listen("unix", servers[me])
	if e != nil {
		log.Fatal("listen error: ", e)
	}
	kv.l = l

	// please do not change any of the following code,
	// or do anything to subvert it.

	go func() {
		for kv.dead == false {
			conn, err := kv.l.Accept()
			if err == nil && kv.dead == false {
				if kv.unreliable && (rand.Int63()%1000) < 100 {
					// discard the request.
					conn.Close()
				} else if kv.unreliable && (rand.Int63()%1000) < 200 {
					// process the request but force discard of reply.
					c1 := conn.(*net.UnixConn)
					f, _ := c1.File()
					err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
					if err != nil {
						fmt.Printf("shutdown: %v\n", err)
					}
					go rpcs.ServeConn(conn)
				} else {
					go rpcs.ServeConn(conn)
				}
			} else if err == nil {
				conn.Close()
			}
			if err != nil && kv.dead == false {
				fmt.Printf("KVPaxos(%v) accept: %v\n", me, err.Error())
				kv.kill()
			}
		}
	}()
	go kv.updateStatus()
	return kv
}
Beispiel #24
0
func (c *appClient) controlConnection() (bool, error) {
	headers := http.Header{}
	c.ProbeConfig.authorizeHeaders(headers)
	url := sanitize.URL("ws://", 0, "/api/control/ws")(c.target)
	conn, _, err := c.wsDialer.Dial(url, headers)
	if err != nil {
		return false, err
	}
	defer func() {
		conn.Close()
	}()

	codec := xfer.NewJSONWebsocketCodec(conn)
	server := rpc.NewServer()
	if err := server.RegisterName("control", c.control); err != nil {
		return false, err
	}

	// Will return false if we are exiting
	if !c.registerConn("control", conn) {
		return true, nil
	}
	defer c.closeConn("control")

	server.ServeCodec(codec)
	return false, nil
}
Beispiel #25
0
// handleConnection handles an incoming connection
func (p *Provider) handleConnection(conn net.Conn) {
	// Create an RPC server to handle inbound
	pe := &providerEndpoint{p: p}
	rpcServer := rpc.NewServer()
	rpcServer.RegisterName("Client", pe)
	rpcCodec := msgpackrpc.NewCodec(false, false, conn)

	defer func() {
		if !pe.hijacked() {
			conn.Close()
		}
	}()

	for !p.IsShutdown() {
		if err := rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				p.logger.Printf("[ERR] scada-client: RPC error: %v", err)
			}
			return
		}

		// Handle potential hijack in Client.Connect
		if pe.hijacked() {
			cb := pe.getHijack()
			cb(conn)
			return
		}
	}
}
func StartServer(vshost string, me string) *PBServer {
	pb := new(PBServer)
	pb.me = me
	pb.vs = viewservice.MakeClerk(me, vshost)
	// Your pb.* initializations here.
	pb.view = viewservice.View{}
	pb.content = make(map[string]string)
	pb.client = make(map[string]string)

	rpcs := rpc.NewServer()
	rpcs.Register(pb)

	os.Remove(pb.me)
	l, e := net.Listen("unix", pb.me)
	if e != nil {
		log.Fatal("listen error: ", e)
	}
	pb.l = l

	// please do not change any of the following code,
	// or do anything to subvert it.

	go func() {
		for pb.isdead() == false {
			conn, err := pb.l.Accept()
			if err == nil && pb.isdead() == false {
				if pb.isunreliable() && (rand.Int63()%1000) < 100 {
					// discard the request.
					conn.Close()
				} else if pb.isunreliable() && (rand.Int63()%1000) < 200 {
					// process the request but force discard of reply.
					c1 := conn.(*net.UnixConn)
					f, _ := c1.File()
					err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
					if err != nil {
						fmt.Printf("shutdown: %v\n", err)
					}
					go rpcs.ServeConn(conn)
				} else {
					go rpcs.ServeConn(conn)
				}
			} else if err == nil {
				conn.Close()
			}
			if err != nil && pb.isdead() == false {
				fmt.Printf("PBServer(%v) accept: %v\n", me, err.Error())
				pb.kill()
			}
		}
	}()

	go func() {
		for pb.isdead() == false {
			pb.tick()
			time.Sleep(viewservice.PingInterval)
		}
	}()

	return pb
}
Beispiel #27
0
func main() {
	list := new(Listener)
	buystock := new(Stock)
	list2 := new(Listenerx)

	server := rpc.NewServer()
	server.Register(list)
	server.Register(buystock)
	server.Register(list2)

	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
	listener, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	for {
		if conn, err := listener.Accept(); err != nil {
			log.Fatal("accept error: " + err.Error())
		} else {
			log.Printf("new connection established\n")
			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}

	}

}
Beispiel #28
0
// ServeConn runs a single connection.
//
// ServeConn blocks, serving the connection until the client hangs up.
func (s *Server) ServeConn(conn io.ReadWriteCloser) {
	// First create the yamux server to wrap this connection
	mux, err := yamux.Server(conn, nil)
	if err != nil {
		conn.Close()
		log.Printf("[ERR] plugin: %s", err)
		return
	}

	// Accept the control connection
	control, err := mux.Accept()
	if err != nil {
		mux.Close()
		log.Printf("[ERR] plugin: %s", err)
		return
	}

	// Create the broker and start it up
	broker := newMuxBroker(mux)
	go broker.Run()

	// Use the control connection to build the dispenser and serve the
	// connection.
	server := rpc.NewServer()
	server.RegisterName("Dispenser", &dispenseServer{
		ProviderFunc:    s.ProviderFunc,
		ProvisionerFunc: s.ProvisionerFunc,

		broker: broker,
	})
	server.ServeConn(control)
}
Beispiel #29
0
func (mr *MapReduce) StartRegistrationServer() {
	rpcs := rpc.NewServer()
	rpcs.Register(mr)
	os.Remove(mr.MasterAddress) // only needed for "unix"
	l, e := net.Listen("unix", mr.MasterAddress)
	if e != nil {
		log.Fatal("RegstrationServer", mr.MasterAddress, " error: ", e)
	}
	mr.l = l

	// now that we are listening on the master address, can fork off
	// accepting connections to another thread.
	go func() {
		for mr.alive {
			conn, err := mr.l.Accept()
			if err == nil {
				go func() {
					rpcs.ServeConn(conn)
					conn.Close()
				}()
			} else {
				DPrintf("RegistrationServer: accept error", err)
				break
			}
		}
		DPrintf("RegistrationServer: done\n")
	}()
}
Beispiel #30
0
// Create a new RPC server
func NewRpcServer(portNo uint16) (*rpc.Server, net.Listener) {
	server := rpc.NewServer()

	// Listens on a port
	l, e := net.Listen("tcp", fmt.Sprintf(":%d", portNo))
	if e != nil {
		log.Fatal("listen error:", e)
	}

	log.Infof("RPC Server is listening on %s\n", l.Addr())

	// run in background
	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				// if listener closed, just exit the groutine
				if strings.Contains(err.Error(), "use of closed network connection") {
					return
				}
				log.Fatal(err)
			}

			log.Infof("Server accepted connection to %s from %s\n", conn.LocalAddr(), conn.RemoteAddr())

			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

	return server, l
}