Getting Unimplemented desc = unknown service error gRPC - go

In one of my services that happens to be my loadbalancer, I am getting the following error when calling the server method in one of my deployed services:
rpc error: code = Unimplemented desc = unknown service
fooService.FooService
I have a few other services set up with gRPC and they work fine. It just seems to be this one and I am wondering if that is because it is the loadbalancer?
func GetResult(w http.ResponseWriter, r *http.Request) {
conn, errOne := grpc.Dial("redis-gateway:10006", grpc.WithInsecure())
defer conn.Close()
rClient := rs.NewRedisGatewayClient(conn)
result , errTwo := rClient.GetData(context.Background(), &rs.KeyRequest{Key: "trump", Value: "trumpVal"}, grpc.WithInsecure())
fmt.Fprintf(w, "print result: %s \n", result) //prints nil
fmt.Fprintf(w, "print error one: %v \n", errOne) // prints nil
fmt.Fprintf(w, "print error two: %s \n", errTwo) // prints error
}
The error says there is no service called fooService.FooService which is true because the dns name for the service I am calling is called foo-service. However it is the exact same setup for my other services that use gRPC and work fine. Also my proto files are correctly configured so that is not an issue.
server I am calling:
func main() {
lis, err := net.Listen("tcp", ":10006")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
newServer := &RedisGatewayServer{}
rs.RegisterRedisGatewayServer(grpcServer, newServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
The function I am trying to access from client:
func (s *RedisGatewayServer) GetData(ctx context.Context, in *rs.KeyRequest)(*rs.KeyRequest, error) {
return in, nil
}
My docker and yaml files are all correct also with the right naming and ports.

I had this exact problem, and it was because of a very simple mistake: I had put the call to the service registration after the server start. The code looked like this:
err = s.Serve(listener)
if err != nil {
log.Fatalf("[x] serve: %v", err)
}
primepb.RegisterPrimeServiceServer(s, &server{})
Obviously, the registration should have been called before the server was ran:
primepb.RegisterPrimeServiceServer(s, &server{})
err = s.Serve(listener)
if err != nil {
log.Fatalf("[x] serve: %v", err)
}

thanks #dolan's for the comment, it solved the problem.
Basically we have to make sure, the method value should be same in both server and client (you can even copy the method name from the pb.go file generated from server side)
func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error {
this invoke function will be there inside all the methods which you have implemented in gRPC service.

for me, my client was connecting to the wrong server port.
My server listens to localhost:50052
My client connects to localhost:50051
and hence I see this error.

I had the same problem - I was able to perform rpc call from Postman to the service whereas apigateway was able to connect to the service but on method call It gave error code 12 unknown service and the reason was in my proto files client was under package X whereas server was under package Y.
Quite silly but yeah making the package for both proto under apigateway and service solved my problem.

There are many scenarios in which this can happen. The underlying issue seems to be the same - the GRPC server is reachable but cannot service client requests.
The two scenarios I faced that are not documented in previous answers are:
1. Client and server are not running the same contract version
A breaking change introduced in the contract can cause this error.
In my case, the server was running the older version of the contract while the client was running the latest one.
A breaking change meant that the server could not resolve the service my client was asking for thus returning the unimplemented error.
2. The client is connecting to the wrong GRPC server
The client reached the incorrect server that doesn't implement the contract.
Consider this scenario if you're running multiple different GRPC services. You might be mistakingly dialing the wrong one.

Related

Using google PubSub with a Cloud Run gRPC service

I have a Cloud Run gRPC service and I want it to listen to PubSub topic.
The only way to do it from the official documentations is to use a trigger but this only works with REST server that accept http requests.
I couldn't find any good example on the web of how to use pubsub with cloud run grpc services.
My service is built with Go following the official grpc instructions
main.go:
func main() {
ctx := context.Background()
pubSubClient, err := pubsub.NewClient(ctx, 'project-id')
if err != nil {
log.Fatal(err)
}
pubSubSubscription := pubSubClient.Subscription("subscription-id")
go func(sub *pubsub.Subscription) {
err := sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
defer m.Ack()
log.Printf("sub.Receiv called %+v", m)
})
if err != nil {
// handle error
}
}(pubSubSubscription)
....
lis, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s, _ := server.New(ctx, ...)
grpcServer := grpc.NewServer()
grpcpkg.RegisterReportServiceServer(grpcServer, s)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
This will work as long as there is at least one instance up and listening. But if there is no instances active, and a new pubsub message publishes, cloud run won't "wake up" the insane because it's autoscaling is utilized based on http requests.
The only way to make the above code work is by setting min-instance 1 in cloud run, but this can be not efficient for a lot of use cases (i.e the service is not active at night)
Is there any work around for this?
Is there any way to trigger a grpc cloud run service from a pubsub message?
The sub.Receive method you are attempting to use on the client library is meant for Pull message delivery and not Push delivery. You can read about how these two delivery types compare to make a choice.
If you wish to receive messages as incoming requests, you must use Push delivery and can follow the the Cloud Run Pubsub usage guide. Note that Cloud Pub/Sub only delivers messages as HTTPS POST requests with the specified JSON payload. To handle these requests from a gRPC server, you can use the gRPC Gateway plugin to generate a reverse proxy that exposes an HTTP API.
Once your Cloud Run instance is accepting HTTP traffic using the reverse proxy, it will be autoscaled with incoming requests, so you won't need to keep 1 instance always running. Note that this may mean that message processing latency is upto 10s on a cold start.

GO GCP SDK auth code to connect gcp project

Im using the following code which works as expected, I use from the cli gcloud auth application-default login and enter my credentials and I was able to run the code successfully from my macbook.
Now I need to run this code in my CI and we need to use different approach , what should be the approach to get the client_secret
and client_id or service account / some ENV variable, what is the way for doing it via GO code?
import "google.golang.org/api/compute/v1"
project := "my-project"
region := "my-region"
ctx := context.Background()
c, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
if err != nil {
log.Fatal(err)
}
computeService, err := compute.New(c)
if err != nil {
log.Fatal(err)
}
req := computeService.Routers.List(project, region)
if err := req.Pages(ctx, func(page *compute.RouterList) error {
for _, router := range page.Items {
// process each `router` resource:
fmt.Printf("%#v\n", router)
// NAT Gateways are found in router.nats
}
return nil
}); err != nil {
log.Fatal(err)
}
Since you're using Jenkins you probably want to start with how to create a service account. It guides you on creating a service account and exporting a key to be set as a var in another CI/CD system.
Then refer to the docs from the client library on how to create a new client with source credential.
e.g.
client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json"))
If you provided no source, it would attempt to read the credentials locally and act as the service account running the operation (not applicable in your use case).
Many CIs support the export of specific env vars. Or your script / conf can do it too.
But if you want to run in a CI why you need such configuration? Integration tests?
Some services can be used locally for unit/smoke testing. Like pubsub, there is a way to run a fake/local pubsub to perform some tests.
Or perhaps I did not understand your question, in this case can you provide an example?

When deploying GCP cloud function with go client I receive: "Error 400: Precondition check failed., failedPrecondition"

I'm trying to deploy a Google Cloud Function using the go client package by google.
(https://pkg.go.dev/google.golang.org/api/cloudfunctions/v1?tab=doc#pkg-overview)
I have broken it down into the snippet I think is most relevant:
import (
"context"
log "github.com/sirupsen/logrus"
functions "google.golang.org/api/cloudfunctions/v1"
)
func main() {
ctx := context.Background()
CloudFunctionService, err := functions.NewService(ctx)
if err != nil {
log.Printf("Error at functions.NewService(ctx): \"%v\"\n", err)
}
FunctionSpec := functions.CloudFunction{
EntryPoint: "DeployThisFunctionEntryPoint",
EventTrigger: &functions.EventTrigger{
EventType: "google.pubsub.topic.publish",
Resource: "projects/mytestproject/topics/cloud-builds",
},
Name: "DeployThisFunction",
Runtime: "go111",
SourceRepository: &functions.SourceRepository{Url: "https://source.developers.google.com/projects/mytestproject/repos/deploythisfunction/moveable-aliases/master/paths//"},
}
CloudFunctionDeploymentService := functions.NewProjectsLocationsFunctionsService(CloudFunctionService)
createCall := CloudFunctionDeploymentService.Create("projects/mytestproject/locations/us-central1", &FunctionSpec)
resp, err := createCall.Context(ctx).Do()
if err != nil {
log.Printf("Error at createCall.Context(ctx).Do(): \"%v\"\n", err)
}
log.Printf("response createCall.Context(ctx).Do(): \"%v\"\n", resp)
}
However, no matter how I format it or try. I always get the following message:
googleapi: Error 400: Precondition check failed., failedPrecondition
Through the google api explorer I ran the request with their authentication and json scheme and I received the same error.
https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions/create
Response:
{
"error": {
"code": 400,
"message": "Precondition check failed.",
"status": "FAILED_PRECONDITION"
}
}
I cannot figure out what is going wrong. I have started my own project and am the administrator. When running another part of the go client with GCP for instance creating storage, IAM user, serviceaccounts, database I can make it work and create these resources.
If anyone has encountered this problem I would appreciate some help.
The eventType should match pattern : providers/*/eventTypes/*.*. .
For exmple:providers/cloud.pubsub/eventTypes/topic.publish
Also SourceRepository url should be https://source.developers.google.com/projects/*/repos/*/revisions/*/paths/
and you have https://source.developers.google.com/projects/mytestproject/repos/deploythisfunction/moveable-aliases/master/paths//
The error message says that is an issue with the way you configure FunctionSpec, I suspect EventTrigger or SourceRepository fields.
Edit
The code: 400 is a bad request, client error, in this case formatting issue, and the first thing to check is each cloud function fileds

GRPC: when get a new client?

I am using grpc in my project, if i have a grpc service call helloService, should i use GetNewHelloServiceClient to get a new client in every function? Or just get once in start program?
// for example:
c.GET("/hello", SayHello)
func SayHello() {
c := pb.GetNewHelloServiceClient()
res, err := c.SayHello(context.Background(), &request)
if err != nil {
return
}
fmt.print(res.Hello)
}
Create a gRPC client just once.
Lots of networking concepts in go are designed for reuse: http clients, http transports, sql.DB connection pools etc. They are all go-routine safe & should only be created once but reused many times.

Couchbase GoLang client can't find bucket

I have a TCP server that tries to connect to a Couchbase database using the go-couchbase client library but I get an error saying that the bucket that I'm trying to access, named "events", doesn't exist.
When I use the official Couchbase client library for Go everything works fine.
The difference that I noticed between these two clients is the concept of "pool". I have set this pool to be "default".
What could lead to this Go client not seeing my bucket?
cb, err := couchbase.Connect("http://address:port")
if err != nil {
log.Fatalf("Error connecting: %v", err)
}
cbPool, err := cb.GetPool("default")
if err != nil {
log.Fatalf("Error getting pool: %v", err)
}
cbBucket, err := cbPool.GetBucketWithAuth("events", "username", "password")
if err != nil {
log.Fatalf("Error getting bucket: %v", err)
}
I'm assuming you're getting some kind of an authentication error. The API is a little bit confusing. GetBucketWithAuth should be called like this:
GetBucketWithAuth("events", "events", "password")
The reason is that the client wants the bucket user name and the bucket password. The bucket username is the same as the bucket name.
With that said I would highly recommend that you use gocb and not go-couchbase. gocb is the official Couchbase go client and go-couchbase is only used internally inside Couchbase. In fact many of the components that use go-couchbase will start using gocb instead since this library is much easier to use and is better organized.
https://github.com/couchbase/gocb

Resources