Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions sample/grpc-ping/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

FROM golang AS builder
ARG SAMPLE
ARG BUILDTAG

# Get the dependencies from GitHub
RUN go get google.golang.org/grpc

WORKDIR /go/src/github.com/knative/serving
ADD . /go/src/github.com/knative/serving

RUN CGO_ENABLED=0 go build -tags=${BUILDTAG} ./sample/${SAMPLE}

FROM gcr.io/distroless/base
ARG SAMPLE

EXPOSE 8080
COPY --from=builder /go/src/github.com/knative/serving/${SAMPLE} /sample

ENTRYPOINT ["/sample"]
51 changes: 51 additions & 0 deletions sample/grpc-ping/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# gRPC Ping

A simple gRPC server written in Go that you can use for testing.

This sample is dependent on [this issue](https://github.com/knative/serving/issues/1047) to be complete.

## Prerequisites

1. [Install Knative](https://github.com/knative/install/blob/master/README.md)
1. Install [docker](https://www.docker.com/)

## Build and run the gRPC server

Build and run the gRPC server. This command will build the server and use `kubectl` to apply the configuration.

```
REPO="gcr.io/<your-project-here>"

# Build and publish the container, run from the root directory.
docker build \
--build-arg SAMPLE=grpc-ping \
--build-arg BUILDTAG=grpcping \
--tag "${REPO}/sample/grpc-ping" \
--file=sample/grpc-ping/Dockerfile .
docker push "${REPO}/sample/grpc-ping"

# Replace the image reference with our published image.
perl -pi -e "s@github.com/knative/serving/sample/grpc-ping@${REPO}/sample/grpc-ping@g" sample/grpc-ping/*.yaml

# Deploy the Knative sample
kubectl apply -f sample/grpc-ping/sample.yaml

```

## Use the client to stream messages to the gRPC server

1. Fetch the created ingress hostname and IP.

```
# Put the Ingress Host name into an environment variable.
export SERVICE_HOST=`kubectl get route grpc-ping -o jsonpath="{.status.domain}"`

# Put the Ingress IP into an environment variable.
export SERVICE_IP=`kubectl get ingress grpc-ping-ela-ingress -o jsonpath="{.status.loadBalancer.ingress[*]['ip']}"`
```

1. Use the client to send message streams to the gRPC server

```
go run -tags=grpcping sample/grpc-ping/client/client.go -server_addr="$SERVICE_IP:80" -server_host_override="$SERVICE_HOST"
```
87 changes: 87 additions & 0 deletions sample/grpc-ping/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// +build grpcping

package main

import (
"flag"
"fmt"
"io"
"log"
"time"

pb "github.com/knative/serving/sample/grpc-ping/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
)

var (
serverAddr = flag.String("server_addr", "127.0.0.1:8080", "The server address in the format of host:port")
serverHostOverride = flag.String("server_host_override", "grpc.knative.dev", "")
insecure = flag.Bool("insecure", false, "Set to true to skip SSL validation")
)

func main() {
flag.Parse()

opts := []grpc.DialOption{grpc.WithAuthority(*serverHostOverride)}
if *insecure {
opts = append(opts, grpc.WithInsecure())
}
grpc.With

conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewPingServiceClient(conn)

ping(client, "hello")
pingStream(client, "hello")
}

func pingStream(client pb.PingServiceClient, msg string) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, err := client.PingStream(ctx)
if err != nil {
log.Fatalf("%v.(_) = _, %v", client, err)
}

waitc := make(chan struct{})
go func() {
for {
in, err := stream.Recv()
if err == io.EOF {
// read done.
close(waitc)
return
}
if err != nil {
log.Fatalf("Failed to receive a response : %v", err)
}
log.Printf("Got %s", in.GetMsg())
}
}()

i := 0
for i < 20 {
if err := stream.Send(&pb.Request{Msg: fmt.Sprintf("%s-%d", msg, i)}); err != nil {
log.Fatalf("Failed to send a ping: %v", err)
}
i++
}
stream.CloseSend()
<-waitc

}

func ping(client pb.PingServiceClient, msg string) {
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
rep, err := client.Ping(ctx, &pb.Request{Msg: msg})
if err != nil {
log.Fatalf("%v.Ping failed %v: ", client, err)
}
log.Printf("Ping got %v\n", rep.GetMsg())
}
66 changes: 66 additions & 0 deletions sample/grpc-ping/grpc-ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// +build grpcping

package main

import (
"fmt"
"io"
"log"
"net"
"time"

ping "github.com/knative/serving/sample/grpc-ping/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
)

var port = 8080

type pingServer struct {
}

func (p *pingServer) Ping(ctx context.Context, req *ping.Request) (*ping.Response, error) {
return &ping.Response{Msg: fmt.Sprintf("%s - pong", req.Msg)}, nil
}

func (p *pingServer) PingStream(stream ping.PingService_PingStreamServer) error {
for {
req, err := stream.Recv()

if err == io.EOF {
fmt.Println("Client disconnected")
return nil
}

if err != nil {
fmt.Println("Failed to receive ping")
return err
}

fmt.Printf("Replying to ping %s at %s\n", req.Msg, time.Now())

err = stream.Send(&ping.Response{
Msg: fmt.Sprintf("pong %s", time.Now()),
})

if err != nil {
fmt.Printf("Failed to send pong %s\n", err)
return err
}
}
}

func main() {
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}

pingServer := &pingServer{}

// The grpcServer is currently configured to serve h2c traffic by default.
// To configure credentials or encyrption, see: https://grpc.io/docs/guides/auth.html#go
grpcServer := grpc.NewServer()
ping.RegisterPingServiceServer(grpcServer, pingServer)
grpcServer.Serve(lis)
}
Loading