Skip to content
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

Support HTTP-style error codes from GRPC errors #40

Merged
merged 5 commits into from
May 31, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion httpgrpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ To rebuild generated protobuf code, run:

protoc -I ./ --go_out=plugins=grpc:./ ./httpgrpc.proto

Follow the instructions here to get a working protoc: https://github.com/golang/protobuf
Follow the instructions here to get a working protoc: https://github.com/golang/protobuf
184 changes: 5 additions & 179 deletions httpgrpc/httpgrpc.go
Original file line number Diff line number Diff line change
@@ -1,175 +1,17 @@
package httpgrpc

import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"

log "github.com/Sirupsen/logrus"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/mwitkow/go-grpc-middleware"
"github.com/opentracing/opentracing-go"
"github.com/sercand/kuberesolver"
"golang.org/x/net/context"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc"
"google.golang.org/grpc/status"

"github.com/weaveworks/common/middleware"
)

// Server implements HTTPServer. HTTPServer is a generated interface that gRPC
// servers must implement.
type Server struct {
handler http.Handler
}

// NewServer makes a new Server.
func NewServer(handler http.Handler) *Server {
return &Server{
handler: handler,
}
}

// Handle implements HTTPServer.
func (s Server) Handle(ctx context.Context, r *HTTPRequest) (*HTTPResponse, error) {
req, err := http.NewRequest(r.Method, r.Url, ioutil.NopCloser(bytes.NewReader(r.Body)))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
toHeader(r.Headers, req.Header)
req.RequestURI = r.Url
recorder := httptest.NewRecorder()
s.handler.ServeHTTP(recorder, req)
resp := &HTTPResponse{
Code: int32(recorder.Code),
Headers: fromHeader(recorder.Header()),
Body: recorder.Body.Bytes(),
}
if recorder.Code/100 == 5 {
return nil, errorFromHTTPResponse(resp)
}
return resp, err
}

// Client is a http.Handler that forwards the request over gRPC.
type Client struct {
mtx sync.RWMutex
service string
namespace string
port string
client HTTPClient
conn *grpc.ClientConn
}

// ParseURL deals with direct:// style URLs, as well as kubernetes:// urls.
// For backwards compatibility it treats URLs without schems as kubernetes://.
func ParseURL(unparsed string) (string, []grpc.DialOption, error) {
parsed, err := url.Parse(unparsed)
if err != nil {
return "", nil, err
}

scheme, host := parsed.Scheme, parsed.Host
if !strings.Contains(unparsed, "://") {
scheme, host = "kubernetes", unparsed
}

switch scheme {
case "direct":
return host, nil, err

case "kubernetes":
host, port, err := net.SplitHostPort(host)
if err != nil {
return "", nil, err
}
parts := strings.SplitN(host, ".", 2)
service, namespace := parts[0], "default"
if len(parts) == 2 {
namespace = parts[1]
}
balancer := kuberesolver.NewWithNamespace(namespace)
address := fmt.Sprintf("kubernetes://%s:%s", service, port)
dialOptions := []grpc.DialOption{balancer.DialOption()}
return address, dialOptions, nil

default:
return "", nil, fmt.Errorf("unrecognised scheme: %s", parsed.Scheme)
}
}

// NewClient makes a new Client, given a kubernetes service address.
func NewClient(address string) (*Client, error) {
address, dialOptions, err := ParseURL(address)
if err != nil {
return nil, err
}

dialOptions = append(
dialOptions,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()),
middleware.ClientUserHeaderInterceptor,
)),
)

conn, err := grpc.Dial(address, dialOptions...)
if err != nil {
return nil, err
}

return &Client{
client: NewHTTPClient(conn),
conn: conn,
}, nil
}

// ServeHTTP implements http.Handler
func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req := &HTTPRequest{
Method: r.Method,
Url: r.RequestURI,
Body: body,
Headers: fromHeader(r.Header),
}

resp, err := c.client.Handle(r.Context(), req)
if err != nil {
// Some errors will actually contain a valid resp, just need to unpack it
var ok bool
resp, ok = httpResponseFromError(err)

if !ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

toHeader(resp.Headers, w.Header())
w.WriteHeader(int(resp.Code))
if _, err := w.Write(resp.Body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

func errorFromHTTPResponse(resp *HTTPResponse) error {
// ErrorFromHTTPResponse converts an HTTP response into a grpc error
func ErrorFromHTTPResponse(resp *HTTPResponse) error {
a, err := ptypes.MarshalAny(resp)
if err != nil {
return err
Expand All @@ -182,10 +24,11 @@ func errorFromHTTPResponse(resp *HTTPResponse) error {
})
}

func httpResponseFromError(err error) (*HTTPResponse, bool) {
// HTTPResponseFromError converts a grpc error into an HTTP response
func HTTPResponseFromError(err error) (*HTTPResponse, bool) {
s, ok := status.FromError(err)
if !ok {
fmt.Println("not status")

This comment was marked as abuse.

fmt.Printf("not status, %v\n", err)
return nil, false
}

Expand All @@ -202,20 +45,3 @@ func httpResponseFromError(err error) (*HTTPResponse, bool) {

return &resp, true
}

func toHeader(hs []*Header, header http.Header) {
for _, h := range hs {
header[h.Key] = h.Values
}
}

func fromHeader(hs http.Header) []*Header {
result := make([]*Header, 0, len(hs))
for k, vs := range hs {
result = append(result, &Header{
Key: k,
Values: vs,
})
}
return result
}
5 changes: 2 additions & 3 deletions httpgrpc/httpgrpc.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading