-
Notifications
You must be signed in to change notification settings - Fork 126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add grpc samples #65
Merged
Merged
Add grpc samples #65
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
FROM icr.io/codeengine/golang:latest AS stage | ||
|
||
WORKDIR /app/src | ||
|
||
COPY client/ ./client/ | ||
|
||
COPY ecommerce/ ./ecommerce/ | ||
|
||
COPY go.mod . | ||
|
||
COPY go.sum . | ||
|
||
RUN CGO_ENABLED=0 GOOS=linux go build -o client ./client | ||
|
||
FROM icr.io/codeengine/golang:latest | ||
|
||
WORKDIR /app/src | ||
|
||
COPY --from=stage /app/src/client/client . | ||
|
||
CMD [ "./client" ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
FROM icr.io/codeengine/golang:latest AS stage | ||
|
||
WORKDIR /app/src | ||
|
||
COPY server/ ./server/ | ||
|
||
COPY ecommerce/ ./ecommerce/ | ||
|
||
COPY go.mod . | ||
|
||
COPY go.sum . | ||
|
||
RUN CGO_ENABLED=0 GOOS=linux go build -o server ./server | ||
|
||
FROM icr.io/codeengine/golang:latest | ||
|
||
WORKDIR /app/src | ||
|
||
COPY --from=stage /app/src/server/server . | ||
|
||
CMD [ "./server" ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# gRPC Application | ||
|
||
A basic gRPC microservice architecture, involving a gRPC server and a | ||
client, that allow users to buy items from an online store. | ||
|
||
The ecommerce interface provided by the gRPC server, allows users to | ||
list and buy groceries via the public client/server application. | ||
|
||
The client/server application is deployed as a Code Engine application, | ||
with a public endpoint. While the gRPC server is deployed as a Code Engine | ||
application only exposed to the Code Engine project. | ||
|
||
See architecture diagram: | ||
|
||
![Alt text](images/grpc-architecture.png) | ||
|
||
## Source code | ||
|
||
Check the source code if you want to understand how this works. In general, | ||
we provided three directories: | ||
|
||
- `/ecommerce` directory hosts the protobuf files and declares the `grocery` | ||
interface for a set of remote procedures that can be called by clients. This directory | ||
can be regenerated upon changes to the `.proto` file, by calling the `./regenerate-grpc-code.sh`. | ||
- `/server` directory hosts the `grocery` interface implementation and creates a gRPC server. | ||
- `/client` directory defines an http server and calls the gRPC server via its different | ||
handlers. | ||
|
||
## Try it! | ||
|
||
You can try to deploy this microservice architecture in your Code Engine project. | ||
Once you have selected your Code Engine project, you only need to run: | ||
|
||
```sh | ||
./run | ||
``` | ||
|
||
If you want to clean-up resources from this sample app, do not forget to run: | ||
|
||
```sh | ||
./run clean | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
#!/bin/bash | ||
|
||
set -euo pipefail | ||
|
||
# Env Vars: | ||
# REGISTRY: name of the image registry/namespace to store the images | ||
# | ||
# NOTE: to run this you MUST set the REGISTRY environment variable to | ||
# your own image registry/namespace otherwise the `docker push` commands | ||
# will fail due to an auth failure. Which means, you also need to be logged | ||
# into that registry before you run it. | ||
|
||
export REGISTRY=${REGISTRY:-icr.io/codeengine} | ||
|
||
# Build the images | ||
docker build -f Dockerfile.client -t "${REGISTRY}"/grpc-client . --platform linux/amd64 | ||
docker build -f Dockerfile.server -t "${REGISTRY}"/grpc-server . --platform linux/amd64 | ||
|
||
# And push it | ||
docker push "${REGISTRY}"/grpc-client | ||
docker push "${REGISTRY}"/grpc-server |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"os" | ||
"strconv" | ||
"time" | ||
|
||
"github.com/gorilla/mux" | ||
ec "github.com/qu1queee/CodeEngine/grpc/ecommerce" | ||
"google.golang.org/grpc" | ||
"google.golang.org/grpc/credentials/insecure" | ||
) | ||
|
||
func indexHandler(w http.ResponseWriter, r *http.Request) { | ||
w.Header().Set("Content-Type", "application/json; charset=UFT-8") | ||
json.NewEncoder(w).Encode("server is running") | ||
} | ||
|
||
func GetGroceryHandler(groceryClient ec.GroceryClient) func(w http.ResponseWriter, r *http.Request) { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
GetHandler(w, r, groceryClient) | ||
} | ||
} | ||
|
||
func BuyGroceryHandler(groceryClient ec.GroceryClient) func(w http.ResponseWriter, r *http.Request) { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
BuyHandler(w, r, groceryClient) | ||
} | ||
} | ||
|
||
func Fail(w http.ResponseWriter, msg string, err error) { | ||
fmt.Printf("%s: %v\n", msg, err) | ||
w.WriteHeader(http.StatusBadRequest) | ||
w.Write([]byte(fmt.Sprintf("%s\n", msg))) | ||
} | ||
|
||
func GetHandler(w http.ResponseWriter, r *http.Request, groceryClient ec.GroceryClient) { | ||
|
||
// Contact the server and print out its response. | ||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1) | ||
defer cancel() | ||
|
||
vars := mux.Vars(r) | ||
|
||
categoryName := vars["category"] | ||
|
||
category := ec.Category{ | ||
Category: categoryName, | ||
} | ||
|
||
itemList, err := groceryClient.ListGrocery(ctx, &category) | ||
if err != nil { | ||
Fail(w, "failed to list groceries", err) | ||
return | ||
} | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
json.NewEncoder(w).Encode(itemList.Item) | ||
} | ||
|
||
func BuyHandler(w http.ResponseWriter, r *http.Request, groceryClient ec.GroceryClient) { | ||
vars := mux.Vars(r) | ||
|
||
itemName := vars["name"] | ||
pAmount := vars["amount"] | ||
categoryName := vars["category"] | ||
|
||
amount, err := strconv.ParseFloat(pAmount, 64) | ||
if err != nil { | ||
Fail(w, "invalid amount parameter", err) | ||
} | ||
|
||
category := ec.Category{ | ||
Category: categoryName, | ||
Itemname: itemName, | ||
} | ||
|
||
item, err := groceryClient.GetGrocery(context.Background(), &category) | ||
if err != nil { | ||
Fail(w, fmt.Sprintf("failed to get grocery item by name: %v", category.Itemname), err) | ||
return | ||
} | ||
|
||
paymentRequest := ec.PaymentRequest{ | ||
Amount: amount, | ||
Item: item, | ||
} | ||
|
||
paymentResponse, _ := groceryClient.BuyGrocery(context.Background(), &paymentRequest) | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
json.NewEncoder(w).Encode(paymentResponse) | ||
} | ||
|
||
func main() { | ||
localEndpoint := os.Getenv("LOCAL_ENDPOINT_WITH_PORT") | ||
|
||
fmt.Printf("using local endpoint: %s\n", localEndpoint) | ||
conn, err := grpc.Dial(localEndpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) | ||
if err != nil { | ||
log.Fatalf("failed to connect: %v", err) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't we and stop the app initialization at this point? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. log.Fatalf comes with an os.Exit(1) |
||
} | ||
|
||
defer conn.Close() | ||
|
||
c := ec.NewGroceryClient(conn) | ||
|
||
r := mux.NewRouter() | ||
r.HandleFunc("/", indexHandler).Methods("GET") | ||
r.HandleFunc("/listgroceries/{category}", GetGroceryHandler(c)) | ||
r.HandleFunc("/buygrocery/{category}/{name}/{amount:[0-9]+\\.[0-9]+}", BuyGroceryHandler(c)) | ||
fmt.Println("server app is running on :8080 .....") | ||
http.ListenAndServe(":8080", r) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there every a need to regenerate this directory (e.g. after user made some adjustments to play around)? If so, I suggest to add the command to re-generate the files.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done. Added a new script call `./regenerate-grpc-code.sh