Golang grpc: how to determine when the server has started listening? - go

So I have the following:
type Node struct {
Table map[string]string
thing.UnimplementedGreeterServer
address string
}
func (n *Node) Start() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
thing.RegisterGreeterServer(s, n)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
In my main function I'll spin up mulitple nodes like so:
func main() {
n :=Node{Table: map[string]string{}}
go n.Start()
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
}
The problem is, because I'm spinning up the node concurrently, there's a chance the dial up connection might not work because the node might not have been setup yet.
Ideally, I'd like a done channel that tells me when the grpc server has actually started listening. How do I accomplish this?
This is essntially the same problem as How to add hook on golang grpc server start? which doesn't have an answer

s.Serve(listener) blocks, so you can't achieve your purpose by having a done chan, instead you have to implement the healthcheck and readiness for your service, and check those before performing any request by the client.
The server should implement the following proto:
syntax = "proto3";
package grpc.health.v1;
message HealthCheckRequest {
string service = 1;
}
message HealthCheckResponse {
enum ServingStatus {
UNKNOWN = 0;
SERVING = 1;
NOT_SERVING = 2;
SERVICE_UNKNOWN = 3; // Used only by the Watch method.
}
ServingStatus status = 1;
}
service Health {
rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse);
}
For example, the envoy proxy grpc_health_check works with the above proto.
Read GRPC Health Checking Protocol for more information.

The server can be Dialed as soon as net.Listen returns a nil error. Dial will block until the server calls Accept (which will happen somewhere in s.Serve in this case).
Either move creation of the listener into the caller and pass it as an argument:
func (n *Node) Start(lis net.Listener) {
s := grpc.NewServer()
thing.RegisterGreeterServer(s, n)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
n := Node{Table: map[string]string{}}
go n.Start(lis)
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
}
Or signal that the listener is up after Listen returns:
func (n *Node) Start(up chan struct{}) {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
if up != nil {
close(up)
}
s := grpc.NewServer()
thing.RegisterGreeterServer(s, n)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func main() {
n := Node{Table: map[string]string{}}
up := make(chan struct{})
go n.Start(up)
<-up
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
}

For all those who are still looking for an answer to this, here is another simple way to do it. Start the server in a child routine. Here is a code snippet:
// Start the server in a child routine
go func() {
if err := s.Serve(listener); err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}()
fmt.Println("Server succesfully started on port :50051")
In my case I am using MongoDB as well, so when you run it, you get:
grpc-go-mongodb-cobra>go run server/main.go
Starting server on port :50051...
Connecting to MongoDB...
Connected to MongoDB
Server succesfully started on port :50051
I have also written a Blog post on this, with working code in GitHub. Here is the link: https://softwaredevelopercentral.blogspot.com/2021/03/golang-grpc-microservice.html

Related

how to gomock a server streaming grpc method?

I tried using the following code but the client hangs and never receives from the mock server.
I thought this part: Do(rs.EXPECT().Send(&proto.Response{Result: "steve"})would make the mock server response to the client, it never worked out.
For a server-streaming grpc mock, a typical approach like:
mockServer.EXPECT().FetchResponse(&proto.Request{Id: 123}, rs).Times(1).Return(...)
doesn't work, the return value is expected to be an error, not a streaming message.
Could someone with a kind heart please explain how this problem should be handled properly?
Code
func Test_Streaming(t *testing.T) {
// create listiner
lis, err := net.Listen("tcp", ":50005")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// create grpc server
s := grpc.NewServer()
c := gomock.NewController(t)
mockServer := mock_proto.NewMockStreamServiceServer(c)
proto.RegisterStreamServiceServer(s, mockServer)
go func() {
log.Println("start server")
// and start...
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
rs := mock_proto.NewMockStreamService_FetchResponseServer(c)
mockServer.EXPECT().FetchResponse(&proto.Request{Id: 123}, rs).Times(1).Do(rs.EXPECT().Send(&proto.Response{Result: "steve"}))
// client call FetchResponse
ClientConnect()
}

SSH proxy, bad packet length

Implementing an ssh proxy in Go, errors out with bad packet length, these are the errors with ssh in debug mode:
debug1: SSH2_MSG_KEXINIT sent
Bad packet length 1231976033.
ssh_dispatch_run_fatal: Connection to ::1 port 8080: message authentication code incorrect
Code:
func handleSSH(conn net.Conn, r *bufio.Reader, protocol string) {
target, err := url.Parse("ssh://localhost:3333")
if err != nil {
fmt.Println("Error parsing target", err)
conn.Close()
return
}
targetConn, err := net.Dial("tcp", target.Host)
if err != nil {
fmt.Println("error dialing SSH target:", err)
conn.Close()
return
}
defer targetConn.Close()
var wg sync.WaitGroup
wg.Add(2)
go func() {
_, err := io.Copy(targetConn, conn)
if err != nil {
fmt.Println("error copying data to target:", err)
}
wg.Done()
}()
go func() {
_, err := io.Copy(conn, targetConn)
if err != nil {
fmt.Println("error copying data from target:", err)
}
wg.Done()
}()
wg.Wait()
conn.Close()
}
// EDIT
func connection(conn net.Conn) {
r := bufio.NewReader(conn)
protocol, err := r.ReadString('\n')
if err != nil {
fmt.Println("Error reading first line", err)
conn.Close()
return
}
if protocol[0:3] == "SSH" {
handleSSH(conn, r, protocol)
}
}
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
go connection(conn)
}
}
EDIT: added code for relevant information on how the connection is initiated and reproduce the error.
My best guess is the ssh negotiation process is being interrupted, and things goes out of sync.
The code is reading the first line from the client and checks the kind of protocol in order to call the appropriate handler:
protocol, err := r.ReadString('\n')
...
if protocol[0:3] == "SSH" {
handleSSH(conn, r, protocol)
}
}
But the code fails to forward the already read bytes to the connected server. These bytes are in protocol and are given to handleSSH. But it fails to send these bytes to the connected server once the connection is established. Instead it only copies new data between client and server.
This means the server does not get the first line from the client. It therefore likely complains about a protocol error with something like Invalid SSH identification string. which gets forwarded to the client and misinterpreted as valid data from an SSH connection.

UDP server issues with multi ports connections

I have a UDP server that expose two ports, 8080 for normal data and 8082 for controll (keep alive signal). When I start the server one new instance of Server is created. It have a list of clients: a client is represented by a struct that contains two types of UDPConn, one for control and one for data. What is happening is when I run my Client.go I connect to server in both ports but, the server creates two clients instead of only one. Downward are part of my Server.go and Client.go. What can I do to create only one user for both connections?
Server.go
func main() {
server := NewLobby()
addressCntrl, err := net.ResolveUDPAddr(CONN_TYPE, CONN_CNTRL_PORT)
if err != nil {
log.Fatalf("Error resolving controller address: %s", err)
}
listenerCntrl, err := net.ListenUDP(CONN_TYPE, addressCntrl)
defer listenerCntrl.Close()
log.Printf("Listening controll on port %s", CONN_CNTRL_PORT)
addressData, err := net.ResolveUDPAddr(CONN_TYPE, CONN_DATA_PORT)
if err != nil {
log.Fatalf("Error Resolving data address: %s", err)
}
listenerData, err := net.ListenUDP(CONN_TYPE, addressData)
defer listenerData.Close()
log.Printf("Listening data on port %s", CONN_DATA_PORT)
for {
buffer = make([]byte, 1024)
listenerData.ReadFromUDP(buffer)
c := NewClient(*listenerData, *listenerCntrl)
server.Join(c)
}
}
NewServer (server.go)
func NewServer() *Server {
server := &Server{
clients: make([]*Client, 0),
chatRooms: make(map[string]*ChatRoom),
incoming: make(chan *Message),
join: make(chan *Client),
leave: make(chan *Client),
delete: make(chan *ChatRoom),
}
server.Listen()
return server
}
NewClient (server.go)
func NewClient(connData net.UDPConn, connCntrl net.UDPConn) *Client {
writerData := bufio.NewWriter(&connData)
readerData := bufio.NewReader(&connData)
writerCntrl := bufio.NewWriter(&connCntrl)
readerCntrl := bufio.NewReader(&connCntrl)
client := &Client{
name: CLIENT_NAME,
chatRoom: nil,
incoming: make(chan *Message),
outgoing: make(chan string),
connData: connData,
connCntrl: connCntrl,
readerData: readerData,
writerData: writerData,
readerCntrl: readerCntrl,
writerCntrl: writerCntrl,
}
log.Printf("New client connected")
client.Listen()
return client
}
Client.go
func main() {
server := NewServer()
addressCntrl, err := net.ResolveUDPAddr(CONN_TYPE, CONN_CNTRL_PORT)
if err != nil {
log.Fatalf("Error resolving controller address: %s", err)
}
listenerCntrl, err := net.ListenUDP(CONN_TYPE, addressCntrl)
defer listenerCntrl.Close()
log.Printf("Listening controll on port %s", CONN_CNTRL_PORT)
addressData, err := net.ResolveUDPAddr(CONN_TYPE, CONN_DATA_PORT)
if err != nil {
log.Fatalf("Error Resolving data address: %s", err)
}
listenerData, err := net.ListenUDP(CONN_TYPE, addressData)
defer listenerData.Close()
log.Printf("Listening data on port %s", CONN_DATA_PORT)
for {
buffer = make([]byte, 1024)
listenerData.ReadFromUDP(buffer)
c := NewClient(*listenerData, *listenerCntrl)
server.Join(c)
}
}
One example of output is bellow
Server output
2021/05/06 20:03:52 Listening controll on port :8082
2021/05/06 20:03:52 Listening data on port :8080
2021/05/06 20:03:56 New client connected
2021/05/06 20:03:58 New client connected
Client output
Welcome to the server! Type "/help" to get a list of commands.
Welcome to the server! Type "/help" to get a list of commands.
If needed my functions Read() and Write() of client is bellow.
Read (client.go)
func Read(connData net.UDPConn, connCntrl net.UDPConn) {
//Controller
go func() {
readerCntrl := bufio.NewReader(&connCntrl)
for {
str, _ := readerCntrl.ReadString('\n')
if strings.Compare(str, "timeout") == 0 {
os.Exit(1)
}
}
}()
//Data
reader := bufio.NewReader(&connData)
for {
str, err := reader.ReadString('\n')
if err != nil {
fmt.Printf(MSG_DISCONNECT)
wg.Done()
return
}
fmt.Print(str)
}
}
Write (client.go)
func Write(connData net.UDPConn, connCntrl net.UDPConn) {
//Controller
go func() {
writerCntrl := bufio.NewWriter(&connCntrl)
for range time.Tick(10 * time.Second) {
writerCntrl.WriteString("ka")
}
}()
//Data
reader := bufio.NewReader(os.Stdin)
writerData := bufio.NewWriter(&connData)
for {
input, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("Error reading input: %s", err)
}
_, err = writerData.WriteString(input)
if err != nil {
log.Fatalf("Error writing input to server: %s", err)
}
err = writerData.Flush()
if err != nil {
log.Fatalf("Error flushing the input: %s", err)
wg.Done()
}
}
}

Why can't I start two servers in the same Go project?

I am a new Go developer and I am trying to build a single project that has both a gRPC server and a Gin HTTP server. This is what my code roughly looks like:
package main
import (
"log"
"net"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
)
func main() {
startGRPCServer()
startHTTPServer()
}
func startGRPCServer() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatalf("could not attach listener to port: %v", err)
}
s := grpc.NewServer()
if err := s.Serve(listener); err != nil {
log.Fatalf("could not start grpc server: %v", err)
}
}
func startHTTPServer() {
g := gin.Default()
if err := g.Run(":8000"); err != nil {
log.Fatalf("could not start http server: %v", err)
}
}
When I run the code above, only the gRPC server starts. The startHTTPServer() function doesn't even get invoked. When I switch the order of the calls (move startHTTPServer() above startGRPCServer()), the startGRPCServer() function never gets called. Why does this happen? How can I fix this so that both functions get called and both servers run?
The startGRPCServer function blocks on running the grpc server. Run the GRPC server in a goroutine so that startGRPCServer returns.
func startGRPCServer() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatalf("could not attach listener to port: %v", err)
}
s := grpc.NewServer()
go func() {
if err := s.Serve(listener); err != nil {
log.Fatalf("could not start grpc server: %v", err)
}
}()
}

How to cache a TCP reverse proxy data transmission?

I've accomplished implementing TCP reverse proxy in GoLang. But unfortunately couldn't come up with implementing caching to a TCP reverse proxy. Is it possible to do so, if yes, is there any resource out there? Is caching possible on a TCP (Transport Layer of Network)?
Here's the simple TCP reverse proxy in Golang.
package main
import (
"io"
"log"
"net"
)
//Proxy struct
type Proxy struct {
laddr, raddr *net.TCPAddr
lconn, rconn io.ReadWriteCloser
errorSignal chan bool
}
// New Create a new Proxy instance.
func New(lconn *net.TCPConn, laddr, raddr *net.TCPAddr) *Proxy {
return &Proxy{
lconn: lconn,
laddr: laddr,
raddr: raddr,
errorSignal: make(chan bool),
}
}
//TCPAddressResolver resolves an address and returns to a struct having ip and port.
func TCPAddressResolver(addr string) (tcpAddress *net.TCPAddr, err error) {
tcpAddress, err = net.ResolveTCPAddr("tcp", addr)
return
}
func main() {
listenerAddress, err := TCPAddressResolver(":8080")
if err != nil {
log.Fatalf("Failed to resolve local address: %v", err)
}
remoteAddress, err := TCPAddressResolver(":3000")
if err != nil {
log.Fatalf("Failed to resolve remote address: %v", err)
}
listener, err := net.ListenTCP("tcp", listenerAddress)
if err != nil {
log.Fatalf("Failed to open local port to listen: %v", err)
}
log.Printf("Simple Proxy started on: %d and forwards to port %d", listenerAddress.Port, remoteAddress.Port)
for {
conn, err := listener.AcceptTCP()
if err != nil {
log.Fatalf("Failed to accept connection: %v", err)
continue
}
var p *Proxy
// HTTP is a stateless protocol thus a proxy needs to reinitiate the new next incoming call (conn)
// each time it finishes handling the previous one.
p = New(conn, listenerAddress, remoteAddress)
p.Start()
}
}
//Start initiates transmission of data to and from the remote to client side.
func (p *Proxy) Start() {
defer p.lconn.Close()
var err error
p.rconn, err = net.DialTCP("tcp", nil, p.raddr)
if err != nil {
log.Fatalf("Remote connection failure: %v", err)
}
defer p.rconn.Close()
go p.CopySrcDst(p.lconn, p.rconn)
go p.CopySrcDst(p.rconn, p.lconn)
//Wait for everything to close -- This one blocks the routine.
<-p.errorSignal
log.Printf("Closing Start routine \n")
}
func (p *Proxy) err(err error) {
if err != io.EOF {
log.Printf("Warning: %v: Setting error signal to true", err)
}
p.errorSignal <- true
}
//CopySrcDst copies data from src to dest
func (p *Proxy) CopySrcDst(src, dst io.ReadWriteCloser) {
buff := make([]byte, 1024)
for {
n, err := src.Read(buff)
if err != nil {
// Reading error.
p.err(err)
return
}
dataFromBuffer := buff[:n]
n, err = dst.Write(dataFromBuffer)
if err != nil {
// Writing error.
p.err(err)
return
}
}
}
You are asking how to save data read from an io.Reader. That's different from caching.
The easiest approach is to tee the reader into a buffer.
While you are at it, you might as well use io.Copy instead of the similar code in the question. The code in the question does not handle the case when read returns n > 0 and a non-nil error.
Use an error group to coordinate waiting for the goroutines and collecting error status.
var g errgroup.Group
var rbuf, lbuf bytes.Buffer
g.Go(func() error {
_, err := io.Copy(lconn, io.TeeReader(p.rconn, &rbuf))
return err
})
g.Go(func() error {
_, err := io.Copy(rconn, io.TeeReader(p.lconn, &lbuf))
return err
})
if err := g.Wait(); err != nil {
// handle error
}
// rbuf and lbuf have the contents of the two streams.
The name of the programming language is "Go", not "Golang" or "GoLang".

Resources