Commit 70960a5e authored by Kubernetes Submit Queue's avatar Kubernetes Submit Queue Committed by GitHub

Merge pull request #53128 from dixudx/godeps_fix_grpc_data_race

Automatic merge from submit-queue. If you want to cherry-pick this change to another branch, please follow the instructions <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/cherry-picks.md">here</a>. update gRPC to pick up data race fix **What this PR does / why we need it**: **Which issue this PR fixes** *(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close that issue when PR gets merged)*: fixes #53124 **Special notes for your reviewer**: **Release note**: ```release-note update gRPC to v1.6.0 to pick up data race fix grpc/grpc-go#1316 ```
parents ba66fcb6 99e9ec12
...@@ -2932,73 +2932,78 @@ ...@@ -2932,73 +2932,78 @@
}, },
{ {
"ImportPath": "google.golang.org/grpc", "ImportPath": "google.golang.org/grpc",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/codes", "ImportPath": "google.golang.org/grpc/codes",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
},
{
"ImportPath": "google.golang.org/grpc/connectivity",
"Comment": "v1.5.2",
"Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/credentials", "ImportPath": "google.golang.org/grpc/credentials",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1", "ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclog", "ImportPath": "google.golang.org/grpc/grpclog",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/internal", "ImportPath": "google.golang.org/grpc/internal",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/keepalive", "ImportPath": "google.golang.org/grpc/keepalive",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/metadata", "ImportPath": "google.golang.org/grpc/metadata",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/naming", "ImportPath": "google.golang.org/grpc/naming",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/peer", "ImportPath": "google.golang.org/grpc/peer",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/stats", "ImportPath": "google.golang.org/grpc/stats",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/status", "ImportPath": "google.golang.org/grpc/status",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/tap", "ImportPath": "google.golang.org/grpc/tap",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/transport", "ImportPath": "google.golang.org/grpc/transport",
"Comment": "v1.3.0", "Comment": "v1.5.2",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "gopkg.in/gcfg.v1", "ImportPath": "gopkg.in/gcfg.v1",
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -448,59 +448,63 @@ ...@@ -448,59 +448,63 @@
}, },
{ {
"ImportPath": "google.golang.org/grpc", "ImportPath": "google.golang.org/grpc",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/codes", "ImportPath": "google.golang.org/grpc/codes",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
},
{
"ImportPath": "google.golang.org/grpc/connectivity",
"Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/credentials", "ImportPath": "google.golang.org/grpc/credentials",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1", "ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclog", "ImportPath": "google.golang.org/grpc/grpclog",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/internal", "ImportPath": "google.golang.org/grpc/internal",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/keepalive", "ImportPath": "google.golang.org/grpc/keepalive",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/metadata", "ImportPath": "google.golang.org/grpc/metadata",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/naming", "ImportPath": "google.golang.org/grpc/naming",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/peer", "ImportPath": "google.golang.org/grpc/peer",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/stats", "ImportPath": "google.golang.org/grpc/stats",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/status", "ImportPath": "google.golang.org/grpc/status",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/tap", "ImportPath": "google.golang.org/grpc/tap",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/transport", "ImportPath": "google.golang.org/grpc/transport",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "gopkg.in/inf.v0", "ImportPath": "gopkg.in/inf.v0",
......
...@@ -696,59 +696,64 @@ ...@@ -696,59 +696,64 @@
}, },
{ {
"ImportPath": "google.golang.org/grpc", "ImportPath": "google.golang.org/grpc",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/codes", "ImportPath": "google.golang.org/grpc/codes",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
},
{
"ImportPath": "google.golang.org/grpc/connectivity",
"Comment": "v1.5.2",
"Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/credentials", "ImportPath": "google.golang.org/grpc/credentials",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1", "ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclog", "ImportPath": "google.golang.org/grpc/grpclog",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/internal", "ImportPath": "google.golang.org/grpc/internal",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/keepalive", "ImportPath": "google.golang.org/grpc/keepalive",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/metadata", "ImportPath": "google.golang.org/grpc/metadata",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/naming", "ImportPath": "google.golang.org/grpc/naming",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/peer", "ImportPath": "google.golang.org/grpc/peer",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/stats", "ImportPath": "google.golang.org/grpc/stats",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/status", "ImportPath": "google.golang.org/grpc/status",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/tap", "ImportPath": "google.golang.org/grpc/tap",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/transport", "ImportPath": "google.golang.org/grpc/transport",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "gopkg.in/inf.v0", "ImportPath": "gopkg.in/inf.v0",
......
...@@ -424,59 +424,64 @@ ...@@ -424,59 +424,64 @@
}, },
{ {
"ImportPath": "google.golang.org/grpc", "ImportPath": "google.golang.org/grpc",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/codes", "ImportPath": "google.golang.org/grpc/codes",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
},
{
"ImportPath": "google.golang.org/grpc/connectivity",
"Comment": "v1.5.2",
"Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/credentials", "ImportPath": "google.golang.org/grpc/credentials",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1", "ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclog", "ImportPath": "google.golang.org/grpc/grpclog",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/internal", "ImportPath": "google.golang.org/grpc/internal",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/keepalive", "ImportPath": "google.golang.org/grpc/keepalive",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/metadata", "ImportPath": "google.golang.org/grpc/metadata",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/naming", "ImportPath": "google.golang.org/grpc/naming",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/peer", "ImportPath": "google.golang.org/grpc/peer",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/stats", "ImportPath": "google.golang.org/grpc/stats",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/status", "ImportPath": "google.golang.org/grpc/status",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/tap", "ImportPath": "google.golang.org/grpc/tap",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/transport", "ImportPath": "google.golang.org/grpc/transport",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "gopkg.in/inf.v0", "ImportPath": "gopkg.in/inf.v0",
......
...@@ -408,59 +408,64 @@ ...@@ -408,59 +408,64 @@
}, },
{ {
"ImportPath": "google.golang.org/grpc", "ImportPath": "google.golang.org/grpc",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/codes", "ImportPath": "google.golang.org/grpc/codes",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
},
{
"ImportPath": "google.golang.org/grpc/connectivity",
"Comment": "v1.5.2",
"Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/credentials", "ImportPath": "google.golang.org/grpc/credentials",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1", "ImportPath": "google.golang.org/grpc/grpclb/grpc_lb_v1",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/grpclog", "ImportPath": "google.golang.org/grpc/grpclog",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/internal", "ImportPath": "google.golang.org/grpc/internal",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/keepalive", "ImportPath": "google.golang.org/grpc/keepalive",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/metadata", "ImportPath": "google.golang.org/grpc/metadata",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/naming", "ImportPath": "google.golang.org/grpc/naming",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/peer", "ImportPath": "google.golang.org/grpc/peer",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/stats", "ImportPath": "google.golang.org/grpc/stats",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/status", "ImportPath": "google.golang.org/grpc/status",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/tap", "ImportPath": "google.golang.org/grpc/tap",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "google.golang.org/grpc/transport", "ImportPath": "google.golang.org/grpc/transport",
"Rev": "d2e1b51f33ff8c5e4a15560ff049d200e83726c5" "Rev": "b3ddf786825de56a4178401b7e174ee332173b66"
}, },
{ {
"ImportPath": "gopkg.in/inf.v0", "ImportPath": "gopkg.in/inf.v0",
......
language: go language: go
go: go:
- 1.6.3 - 1.6.x
- 1.7 - 1.7.x
- 1.8 - 1.8.x
go_import_path: google.golang.org/grpc go_import_path: google.golang.org/grpc
before_install: before_install:
- go get github.com/golang/lint/golint - if [[ $TRAVIS_GO_VERSION = 1.8* ]]; then go get -u github.com/golang/lint/golint honnef.co/go/tools/cmd/staticcheck; fi
- go get -u golang.org/x/tools/cmd/goimports github.com/axw/gocov/gocov github.com/mattn/goveralls golang.org/x/tools/cmd/cover - go get -u golang.org/x/tools/cmd/goimports github.com/axw/gocov/gocov github.com/mattn/goveralls golang.org/x/tools/cmd/cover
script: script:
- '! gofmt -s -d -l . 2>&1 | read' - '! gofmt -s -d -l . 2>&1 | read'
- '! goimports -l . | read' - '! goimports -l . | read'
- '! golint ./... | grep -vE "(_mock|_string|\.pb)\.go:"' - 'if [[ $TRAVIS_GO_VERSION = 1.8* ]]; then ! golint ./... | grep -vE "(_mock|_string|\.pb)\.go:"; fi'
- '! go tool vet -all . 2>&1 | grep -vE "constant [0-9]+ not a string in call to Errorf" | grep -vF .pb.go:' # https://github.com/golang/protobuf/issues/214 - 'if [[ $TRAVIS_GO_VERSION = 1.8* ]]; then ! go tool vet -all . 2>&1 | grep -vF .pb.go:; fi' # https://github.com/golang/protobuf/issues/214
- make test testrace - make test testrace
- 'if [[ $TRAVIS_GO_VERSION = 1.8* ]]; then staticcheck -ignore google.golang.org/grpc/transport/transport_test.go:SA2002 ./...; fi' # TODO(menghanl): fix these
...@@ -27,6 +27,7 @@ go_library( ...@@ -27,6 +27,7 @@ go_library(
"//vendor/golang.org/x/net/http2:go_default_library", "//vendor/golang.org/x/net/http2:go_default_library",
"//vendor/golang.org/x/net/trace:go_default_library", "//vendor/golang.org/x/net/trace:go_default_library",
"//vendor/google.golang.org/grpc/codes:go_default_library", "//vendor/google.golang.org/grpc/codes:go_default_library",
"//vendor/google.golang.org/grpc/connectivity:go_default_library",
"//vendor/google.golang.org/grpc/credentials:go_default_library", "//vendor/google.golang.org/grpc/credentials:go_default_library",
"//vendor/google.golang.org/grpc/grpclb/grpc_lb_v1:go_default_library", "//vendor/google.golang.org/grpc/grpclb/grpc_lb_v1:go_default_library",
"//vendor/google.golang.org/grpc/grpclog:go_default_library", "//vendor/google.golang.org/grpc/grpclog:go_default_library",
...@@ -54,6 +55,7 @@ filegroup( ...@@ -54,6 +55,7 @@ filegroup(
srcs = [ srcs = [
":package-srcs", ":package-srcs",
"//vendor/google.golang.org/grpc/codes:all-srcs", "//vendor/google.golang.org/grpc/codes:all-srcs",
"//vendor/google.golang.org/grpc/connectivity:all-srcs",
"//vendor/google.golang.org/grpc/credentials:all-srcs", "//vendor/google.golang.org/grpc/credentials:all-srcs",
"//vendor/google.golang.org/grpc/grpclb/grpc_lb_v1:all-srcs", "//vendor/google.golang.org/grpc/grpclb/grpc_lb_v1:all-srcs",
"//vendor/google.golang.org/grpc/grpclog:all-srcs", "//vendor/google.golang.org/grpc/grpclog:all-srcs",
......
# How to contribute # How to contribute
We definitely welcome patches and contribution to grpc! Here are some guidelines We definitely welcome your patches and contributions to gRPC!
and information about how to do so.
## Sending patches If you are new to github, please start by reading [Pull Request howto](https://help.github.com/articles/about-pull-requests/)
### Getting started
1. Check out the code:
$ go get google.golang.org/grpc
$ cd $GOPATH/src/google.golang.org/grpc
1. Create a fork of the grpc-go repository.
1. Add your fork as a remote:
$ git remote add fork git@github.com:$YOURGITHUBUSERNAME/grpc-go.git
1. Make changes, commit them.
1. Run the test suite:
$ make test
1. Push your changes to your fork:
$ git push fork ...
1. Open a pull request.
## Legal requirements ## Legal requirements
In order to protect both you and ourselves, you will need to sign the In order to protect both you and ourselves, you will need to sign the
[Contributor License Agreement](https://cla.developers.google.com/clas). [Contributor License Agreement](https://cla.developers.google.com/clas).
## Filing Issues ## Guidelines for Pull Requests
When filing an issue, make sure to answer these five questions: How to get your contributions merged smoothly and quickly.
1. What version of Go are you using (`go version`)? - Create **small PRs** that are narrowly focused on **addressing a single concern**. We often times receive PRs that are trying to fix several things at a time, but only one fix is considered acceptable, nothing gets merged and both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy.
2. What operating system and processor architecture are you using?
3. What did you do? - For speculative changes, consider opening an issue and discussing it first. If you are suggesting a behavioral or API change, consider starting with a [gRFC proposal](https://github.com/grpc/proposal).
4. What did you expect to see?
5. What did you see instead? - Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists.
### Contributing code - Don't fix code style and formatting unless you are already changing that line to address an issue. PRs with irrelevant changes won't be merged. If you do want to fix formatting or style, do that in a separate PR.
Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.
- Unless your PR is trivial, you should expect there will be reviewer comments that you'll need to address before merging. We expect you to be reasonably responsive to those comments, otherwise the PR will be closed after 2-3 weeks of inactivity.
- Maintain **clean commit history** and use **meaningful commit messages**. PRs with messy commit history are difficult to review and won't be merged. Use `rebase -i upstream/master` to curate your commit history and/or to bring in latest changes from master (but avoid rebasing in the middle of a code review).
- Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change).
- **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on.
- Exceptions to the rules can be made if there's a compelling reason for doing so.
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the gRPC project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of gRPC, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of gRPC. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of gRPC or any code incorporated within this
implementation of gRPC constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of gRPC
shall terminate as of the date such litigation is filed.
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc) [![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc)
The Go implementation of [gRPC](http://www.grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start](http://www.grpc.io/docs/) guide. The Go implementation of [gRPC](https://grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start: Go](https://grpc.io/docs/quickstart/go.html) guide.
Installation Installation
------------ ------------
...@@ -26,9 +26,13 @@ Documentation ...@@ -26,9 +26,13 @@ Documentation
------------- -------------
See [API documentation](https://godoc.org/google.golang.org/grpc) for package and API descriptions and find examples in the [examples directory](examples/). See [API documentation](https://godoc.org/google.golang.org/grpc) for package and API descriptions and find examples in the [examples directory](examples/).
Performance
-----------
See the current benchmarks for some of the languages supported in [this dashboard](https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5652536396611584&widget=490377658&container=1286539696).
Status Status
------ ------
GA General Availability [Google Cloud Platform Launch Stages](https://cloud.google.com/terms/launch-stages).
FAQ FAQ
--- ---
......
/*
*
* Copyright 2017 gRPC authors.
*
* 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
*
* http://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.
*
*/
package grpc package grpc
import ( import (
......
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -35,6 +20,7 @@ package grpc ...@@ -35,6 +20,7 @@ package grpc
import ( import (
"fmt" "fmt"
"net"
"sync" "sync"
"golang.org/x/net/context" "golang.org/x/net/context"
...@@ -60,6 +46,10 @@ type BalancerConfig struct { ...@@ -60,6 +46,10 @@ type BalancerConfig struct {
// use to dial to a remote load balancer server. The Balancer implementations // use to dial to a remote load balancer server. The Balancer implementations
// can ignore this if it does not need to talk to another party securely. // can ignore this if it does not need to talk to another party securely.
DialCreds credentials.TransportCredentials DialCreds credentials.TransportCredentials
// Dialer is the custom dialer the Balancer implementation can use to dial
// to a remote load balancer server. The Balancer implementations
// can ignore this if it doesn't need to talk to remote balancer.
Dialer func(context.Context, string) (net.Conn, error)
} }
// BalancerGetOptions configures a Get call. // BalancerGetOptions configures a Get call.
...@@ -167,7 +157,7 @@ type roundRobin struct { ...@@ -167,7 +157,7 @@ type roundRobin struct {
func (rr *roundRobin) watchAddrUpdates() error { func (rr *roundRobin) watchAddrUpdates() error {
updates, err := rr.w.Next() updates, err := rr.w.Next()
if err != nil { if err != nil {
grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err) grpclog.Warningf("grpc: the naming watcher stops working due to %v.", err)
return err return err
} }
rr.mu.Lock() rr.mu.Lock()
...@@ -183,7 +173,7 @@ func (rr *roundRobin) watchAddrUpdates() error { ...@@ -183,7 +173,7 @@ func (rr *roundRobin) watchAddrUpdates() error {
for _, v := range rr.addrs { for _, v := range rr.addrs {
if addr == v.addr { if addr == v.addr {
exist = true exist = true
grpclog.Println("grpc: The name resolver wanted to add an existing address: ", addr) grpclog.Infoln("grpc: The name resolver wanted to add an existing address: ", addr)
break break
} }
} }
...@@ -200,7 +190,7 @@ func (rr *roundRobin) watchAddrUpdates() error { ...@@ -200,7 +190,7 @@ func (rr *roundRobin) watchAddrUpdates() error {
} }
} }
default: default:
grpclog.Println("Unknown update.Op ", update.Op) grpclog.Errorln("Unknown update.Op ", update.Op)
} }
} }
// Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified. // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified.
...@@ -211,6 +201,10 @@ func (rr *roundRobin) watchAddrUpdates() error { ...@@ -211,6 +201,10 @@ func (rr *roundRobin) watchAddrUpdates() error {
if rr.done { if rr.done {
return ErrClientConnClosing return ErrClientConnClosing
} }
select {
case <-rr.addrCh:
default:
}
rr.addrCh <- open rr.addrCh <- open
return nil return nil
} }
...@@ -233,7 +227,7 @@ func (rr *roundRobin) Start(target string, config BalancerConfig) error { ...@@ -233,7 +227,7 @@ func (rr *roundRobin) Start(target string, config BalancerConfig) error {
return err return err
} }
rr.w = w rr.w = w
rr.addrCh = make(chan []Address) rr.addrCh = make(chan []Address, 1)
go func() { go func() {
for { for {
if err := rr.watchAddrUpdates(); err != nil { if err := rr.watchAddrUpdates(); err != nil {
...@@ -385,6 +379,9 @@ func (rr *roundRobin) Notify() <-chan []Address { ...@@ -385,6 +379,9 @@ func (rr *roundRobin) Notify() <-chan []Address {
func (rr *roundRobin) Close() error { func (rr *roundRobin) Close() error {
rr.mu.Lock() rr.mu.Lock()
defer rr.mu.Unlock() defer rr.mu.Unlock()
if rr.done {
return errBalancerClosed
}
rr.done = true rr.done = true
if rr.w != nil { if rr.w != nil {
rr.w.Close() rr.w.Close()
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -73,7 +58,10 @@ func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTran ...@@ -73,7 +58,10 @@ func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTran
} }
} }
for { for {
if err = recv(p, dopts.codec, stream, dopts.dc, reply, dopts.maxMsgSize, inPayload); err != nil { if c.maxReceiveMessageSize == nil {
return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)")
}
if err = recv(p, dopts.codec, stream, dopts.dc, reply, *c.maxReceiveMessageSize, inPayload); err != nil {
if err == io.EOF { if err == io.EOF {
break break
} }
...@@ -86,14 +74,11 @@ func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTran ...@@ -86,14 +74,11 @@ func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTran
dopts.copts.StatsHandler.HandleRPC(ctx, inPayload) dopts.copts.StatsHandler.HandleRPC(ctx, inPayload)
} }
c.trailerMD = stream.Trailer() c.trailerMD = stream.Trailer()
if peer, ok := peer.FromContext(stream.Context()); ok {
c.peer = peer
}
return nil return nil
} }
// sendRequest writes out various information of an RPC such as Context and Message. // sendRequest writes out various information of an RPC such as Context and Message.
func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, callHdr *transport.CallHdr, stream *transport.Stream, t transport.ClientTransport, args interface{}, opts *transport.Options) (err error) { func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, c *callInfo, callHdr *transport.CallHdr, stream *transport.Stream, t transport.ClientTransport, args interface{}, opts *transport.Options) (err error) {
defer func() { defer func() {
if err != nil { if err != nil {
// If err is connection error, t will be closed, no need to close stream here. // If err is connection error, t will be closed, no need to close stream here.
...@@ -116,7 +101,13 @@ func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, ...@@ -116,7 +101,13 @@ func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor,
} }
outBuf, err := encode(dopts.codec, args, compressor, cbuf, outPayload) outBuf, err := encode(dopts.codec, args, compressor, cbuf, outPayload)
if err != nil { if err != nil {
return Errorf(codes.Internal, "grpc: %v", err) return err
}
if c.maxSendMessageSize == nil {
return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)")
}
if len(outBuf) > *c.maxSendMessageSize {
return Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(outBuf), *c.maxSendMessageSize)
} }
err = t.Write(stream, outBuf, opts) err = t.Write(stream, outBuf, opts)
if err == nil && outPayload != nil { if err == nil && outPayload != nil {
...@@ -145,14 +136,18 @@ func Invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli ...@@ -145,14 +136,18 @@ func Invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli
func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) { func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {
c := defaultCallInfo c := defaultCallInfo
if mc, ok := cc.getMethodConfig(method); ok { mc := cc.GetMethodConfig(method)
c.failFast = !mc.WaitForReady if mc.WaitForReady != nil {
if mc.Timeout > 0 { c.failFast = !*mc.WaitForReady
var cancel context.CancelFunc }
ctx, cancel = context.WithTimeout(ctx, mc.Timeout)
defer cancel() if mc.Timeout != nil && *mc.Timeout >= 0 {
} var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
defer cancel()
} }
opts = append(cc.dopts.callOptions, opts...)
for _, o := range opts { for _, o := range opts {
if err := o.before(&c); err != nil { if err := o.before(&c); err != nil {
return toRPCErr(err) return toRPCErr(err)
...@@ -163,6 +158,10 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli ...@@ -163,6 +158,10 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli
o.after(&c) o.after(&c)
} }
}() }()
c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
if EnableTracing { if EnableTracing {
c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
defer c.traceInfo.tr.Finish() defer c.traceInfo.tr.Finish()
...@@ -182,24 +181,22 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli ...@@ -182,24 +181,22 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli
ctx = newContextWithRPCInfo(ctx) ctx = newContextWithRPCInfo(ctx)
sh := cc.dopts.copts.StatsHandler sh := cc.dopts.copts.StatsHandler
if sh != nil { if sh != nil {
ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method}) ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
begin := &stats.Begin{ begin := &stats.Begin{
Client: true, Client: true,
BeginTime: time.Now(), BeginTime: time.Now(),
FailFast: c.failFast, FailFast: c.failFast,
} }
sh.HandleRPC(ctx, begin) sh.HandleRPC(ctx, begin)
} defer func() {
defer func() {
if sh != nil {
end := &stats.End{ end := &stats.End{
Client: true, Client: true,
EndTime: time.Now(), EndTime: time.Now(),
Error: e, Error: e,
} }
sh.HandleRPC(ctx, end) sh.HandleRPC(ctx, end)
} }()
}() }
topts := &transport.Options{ topts := &transport.Options{
Last: true, Last: true,
Delay: false, Delay: false,
...@@ -221,6 +218,9 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli ...@@ -221,6 +218,9 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli
if cc.dopts.cp != nil { if cc.dopts.cp != nil {
callHdr.SendCompress = cc.dopts.cp.Type() callHdr.SendCompress = cc.dopts.cp.Type()
} }
if c.creds != nil {
callHdr.Creds = c.creds
}
gopts := BalancerGetOptions{ gopts := BalancerGetOptions{
BlockingWait: !c.failFast, BlockingWait: !c.failFast,
...@@ -259,7 +259,10 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli ...@@ -259,7 +259,10 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli
} }
return toRPCErr(err) return toRPCErr(err)
} }
err = sendRequest(ctx, cc.dopts, cc.dopts.cp, callHdr, stream, t, args, topts) if peer, ok := peer.FromContext(stream.Context()); ok {
c.peer = peer
}
err = sendRequest(ctx, cc.dopts, cc.dopts.cp, &c, callHdr, stream, t, args, topts)
if err != nil { if err != nil {
if put != nil { if put != nil {
updateRPCInfoInContext(ctx, rpcInfo{ updateRPCInfoInContext(ctx, rpcInfo{
......
/* /*
*
* Copyright 2014, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2014 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ * 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.
*
*/
package grpc package grpc
...@@ -96,6 +81,7 @@ func (p protoCodec) Marshal(v interface{}) ([]byte, error) { ...@@ -96,6 +81,7 @@ func (p protoCodec) Marshal(v interface{}) ([]byte, error) {
func (p protoCodec) Unmarshal(data []byte, v interface{}) error { func (p protoCodec) Unmarshal(data []byte, v interface{}) error {
cb := protoBufferPool.Get().(*cachedProtoBuffer) cb := protoBufferPool.Get().(*cachedProtoBuffer)
cb.SetBuf(data) cb.SetBuf(data)
v.(proto.Message).Reset()
err := cb.Unmarshal(v.(proto.Message)) err := cb.Unmarshal(v.(proto.Message))
cb.SetBuf(nil) cb.SetBuf(nil)
protoBufferPool.Put(cb) protoBufferPool.Put(cb)
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -44,7 +29,7 @@ const ( ...@@ -44,7 +29,7 @@ const (
// OK is returned on success. // OK is returned on success.
OK Code = 0 OK Code = 0
// Canceled indicates the operation was cancelled (typically by the caller). // Canceled indicates the operation was canceled (typically by the caller).
Canceled Code = 1 Canceled Code = 1
// Unknown error. An example of where this error may be returned is // Unknown error. An example of where this error may be returned is
......
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = ["connectivity.go"],
importpath = "google.golang.org/grpc/connectivity",
visibility = ["//visibility:public"],
deps = [
"//vendor/golang.org/x/net/context:go_default_library",
"//vendor/google.golang.org/grpc/grpclog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
/*
*
* Copyright 2017 gRPC authors.
*
* 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
*
* http://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.
*
*/
// Package connectivity defines connectivity semantics.
// For details, see https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md.
// All APIs in this package are experimental.
package connectivity
import (
"golang.org/x/net/context"
"google.golang.org/grpc/grpclog"
)
// State indicates the state of connectivity.
// It can be the state of a ClientConn or SubConn.
type State int
func (s State) String() string {
switch s {
case Idle:
return "IDLE"
case Connecting:
return "CONNECTING"
case Ready:
return "READY"
case TransientFailure:
return "TRANSIENT_FAILURE"
case Shutdown:
return "SHUTDOWN"
default:
grpclog.Errorf("unknown connectivity state: %d", s)
return "Invalid-State"
}
}
const (
// Idle indicates the ClientConn is idle.
Idle State = iota
// Connecting indicates the ClienConn is connecting.
Connecting
// Ready indicates the ClientConn is ready for work.
Ready
// TransientFailure indicates the ClientConn has seen a failure but expects to recover.
TransientFailure
// Shutdown indicates the ClientConn has started shutting down.
Shutdown
)
// Reporter reports the connectivity states.
type Reporter interface {
// CurrentState returns the current state of the reporter.
CurrentState() State
// WaitForStateChange blocks until the reporter's state is different from the given state,
// and returns true.
// It returns false if <-ctx.Done() can proceed (ctx got timeout or got canceled).
WaitForStateChange(context.Context, State) bool
}
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -196,14 +181,14 @@ func NewTLS(c *tls.Config) TransportCredentials { ...@@ -196,14 +181,14 @@ func NewTLS(c *tls.Config) TransportCredentials {
return tc return tc
} }
// NewClientTLSFromCert constructs a TLS from the input certificate for client. // NewClientTLSFromCert constructs TLS credentials from the input certificate for client.
// serverNameOverride is for testing only. If set to a non empty string, // serverNameOverride is for testing only. If set to a non empty string,
// it will override the virtual host name of authority (e.g. :authority header field) in requests. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
} }
// NewClientTLSFromFile constructs a TLS from the input certificate file for client. // NewClientTLSFromFile constructs TLS credentials from the input certificate file for client.
// serverNameOverride is for testing only. If set to a non empty string, // serverNameOverride is for testing only. If set to a non empty string,
// it will override the virtual host name of authority (e.g. :authority header field) in requests. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
...@@ -218,12 +203,12 @@ func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredent ...@@ -218,12 +203,12 @@ func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredent
return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
} }
// NewServerTLSFromCert constructs a TLS from the input certificate for server. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
} }
// NewServerTLSFromFile constructs a TLS from the input certificate file and key // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
// file for server. // file for server.
func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile) cert, err := tls.LoadX509KeyPair(certFile, keyFile)
......
...@@ -3,34 +3,19 @@ ...@@ -3,34 +3,19 @@
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
...@@ -2,34 +2,19 @@ ...@@ -2,34 +2,19 @@
/* /*
* *
* Copyright 2017, Google Inc. * Copyright 2017 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
...@@ -2,34 +2,19 @@ ...@@ -2,34 +2,19 @@
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
Package grpc implements an RPC system called gRPC. Package grpc implements an RPC system called gRPC.
See www.grpc.io for more information about gRPC. See grpc.io for more information about gRPC.
*/ */
package grpc package grpc
// +build go1.6,!go1.7 // +build go1.6,!go1.7
/* /*
* Copyright 2016, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2016 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * Unless required by applicable law or agreed to in writing, software
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * distributed under the License is distributed on an "AS IS" BASIS,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * See the License for the specific language governing permissions and
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * limitations under the License.
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -36,10 +22,15 @@ package grpc ...@@ -36,10 +22,15 @@ package grpc
import ( import (
"fmt" "fmt"
"io"
"net" "net"
"net/http" "net/http"
"os"
"golang.org/x/net/context" "golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/transport"
) )
// dialContext connects to the address on the named network. // dialContext connects to the address on the named network.
...@@ -54,3 +45,54 @@ func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) erro ...@@ -54,3 +45,54 @@ func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) erro
} }
return nil return nil
} }
// toRPCErr converts an error into an error from the status package.
func toRPCErr(err error) error {
if _, ok := status.FromError(err); ok {
return err
}
switch e := err.(type) {
case transport.StreamError:
return status.Error(e.Code, e.Desc)
case transport.ConnectionError:
return status.Error(codes.Unavailable, e.Desc)
default:
switch err {
case context.DeadlineExceeded:
return status.Error(codes.DeadlineExceeded, err.Error())
case context.Canceled:
return status.Error(codes.Canceled, err.Error())
case ErrClientConnClosing:
return status.Error(codes.FailedPrecondition, err.Error())
}
}
return status.Error(codes.Unknown, err.Error())
}
// convertCode converts a standard Go error into its canonical code. Note that
// this is only used to translate the error returned by the server applications.
func convertCode(err error) codes.Code {
switch err {
case nil:
return codes.OK
case io.EOF:
return codes.OutOfRange
case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
return codes.FailedPrecondition
case os.ErrInvalid:
return codes.InvalidArgument
case context.Canceled:
return codes.Canceled
case context.DeadlineExceeded:
return codes.DeadlineExceeded
}
switch {
case os.IsExist(err):
return codes.AlreadyExists
case os.IsNotExist(err):
return codes.NotFound
case os.IsPermission(err):
return codes.PermissionDenied
}
return codes.Unknown
}
// +build go1.7 // +build go1.7
/* /*
* Copyright 2016, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2016 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * Unless required by applicable law or agreed to in writing, software
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * distributed under the License is distributed on an "AS IS" BASIS,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * See the License for the specific language governing permissions and
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * limitations under the License.
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
package grpc package grpc
import ( import (
"context"
"io"
"net" "net"
"net/http" "net/http"
"os"
"golang.org/x/net/context" netctx "golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/transport"
) )
// dialContext connects to the address on the named network. // dialContext connects to the address on the named network.
...@@ -53,3 +45,54 @@ func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) erro ...@@ -53,3 +45,54 @@ func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) erro
} }
return nil return nil
} }
// toRPCErr converts an error into an error from the status package.
func toRPCErr(err error) error {
if _, ok := status.FromError(err); ok {
return err
}
switch e := err.(type) {
case transport.StreamError:
return status.Error(e.Code, e.Desc)
case transport.ConnectionError:
return status.Error(codes.Unavailable, e.Desc)
default:
switch err {
case context.DeadlineExceeded, netctx.DeadlineExceeded:
return status.Error(codes.DeadlineExceeded, err.Error())
case context.Canceled, netctx.Canceled:
return status.Error(codes.Canceled, err.Error())
case ErrClientConnClosing:
return status.Error(codes.FailedPrecondition, err.Error())
}
}
return status.Error(codes.Unknown, err.Error())
}
// convertCode converts a standard Go error into its canonical code. Note that
// this is only used to translate the error returned by the server applications.
func convertCode(err error) codes.Code {
switch err {
case nil:
return codes.OK
case io.EOF:
return codes.OutOfRange
case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
return codes.FailedPrecondition
case os.ErrInvalid:
return codes.InvalidArgument
case context.Canceled, netctx.Canceled:
return codes.Canceled
case context.DeadlineExceeded, netctx.DeadlineExceeded:
return codes.DeadlineExceeded
}
switch {
case os.IsExist(err):
return codes.AlreadyExists
case os.IsNotExist(err):
return codes.NotFound
case os.IsPermission(err):
return codes.PermissionDenied
}
return codes.Unknown
}
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -96,8 +81,8 @@ const ( ...@@ -96,8 +81,8 @@ const (
GRPCLB GRPCLB
) )
// AddrMetadataGRPCLB contains the information the name resolution for grpclb should provide. The // AddrMetadataGRPCLB contains the information the name resolver for grpclb should provide. The
// name resolver used by grpclb balancer is required to provide this type of metadata in // name resolver used by the grpclb balancer is required to provide this type of metadata in
// its address updates. // its address updates.
type AddrMetadataGRPCLB struct { type AddrMetadataGRPCLB struct {
// AddrType is the type of server (grpc load balancer or backend). // AddrType is the type of server (grpc load balancer or backend).
...@@ -152,6 +137,7 @@ type balancer struct { ...@@ -152,6 +137,7 @@ type balancer struct {
func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerInfo) error { func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerInfo) error {
updates, err := w.Next() updates, err := w.Next()
if err != nil { if err != nil {
grpclog.Warningf("grpclb: failed to get next addr update from watcher: %v", err)
return err return err
} }
b.mu.Lock() b.mu.Lock()
...@@ -176,13 +162,13 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn ...@@ -176,13 +162,13 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn
md, ok := update.Metadata.(*AddrMetadataGRPCLB) md, ok := update.Metadata.(*AddrMetadataGRPCLB)
if !ok { if !ok {
// TODO: Revisit the handling here and may introduce some fallback mechanism. // TODO: Revisit the handling here and may introduce some fallback mechanism.
grpclog.Printf("The name resolution contains unexpected metadata %v", update.Metadata) grpclog.Errorf("The name resolution contains unexpected metadata %v", update.Metadata)
continue continue
} }
switch md.AddrType { switch md.AddrType {
case Backend: case Backend:
// TODO: Revisit the handling here and may introduce some fallback mechanism. // TODO: Revisit the handling here and may introduce some fallback mechanism.
grpclog.Printf("The name resolution does not give grpclb addresses") grpclog.Errorf("The name resolution does not give grpclb addresses")
continue continue
case GRPCLB: case GRPCLB:
b.rbs = append(b.rbs, remoteBalancerInfo{ b.rbs = append(b.rbs, remoteBalancerInfo{
...@@ -190,7 +176,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn ...@@ -190,7 +176,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn
name: md.ServerName, name: md.ServerName,
}) })
default: default:
grpclog.Printf("Received unknow address type %d", md.AddrType) grpclog.Errorf("Received unknow address type %d", md.AddrType)
continue continue
} }
case naming.Delete: case naming.Delete:
...@@ -202,7 +188,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn ...@@ -202,7 +188,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn
} }
} }
default: default:
grpclog.Println("Unknown update.Op ", update.Op) grpclog.Errorf("Unknown update.Op %v", update.Op)
} }
} }
// TODO: Fall back to the basic round-robin load balancing if the resulting address is // TODO: Fall back to the basic round-robin load balancing if the resulting address is
...@@ -249,8 +235,15 @@ func (b *balancer) processServerList(l *lbpb.ServerList, seq int) { ...@@ -249,8 +235,15 @@ func (b *balancer) processServerList(l *lbpb.ServerList, seq int) {
) )
for _, s := range servers { for _, s := range servers {
md := metadata.Pairs("lb-token", s.LoadBalanceToken) md := metadata.Pairs("lb-token", s.LoadBalanceToken)
ip := net.IP(s.IpAddress)
ipStr := ip.String()
if ip.To4() == nil {
// Add square brackets to ipv6 addresses, otherwise net.Dial() and
// net.SplitHostPort() will return too many colons error.
ipStr = fmt.Sprintf("[%s]", ipStr)
}
addr := Address{ addr := Address{
Addr: fmt.Sprintf("%s:%d", net.IP(s.IpAddress), s.Port), Addr: fmt.Sprintf("%s:%d", ipStr, s.Port),
Metadata: &md, Metadata: &md,
} }
sl = append(sl, &grpclbAddrInfo{ sl = append(sl, &grpclbAddrInfo{
...@@ -306,6 +299,7 @@ func (b *balancer) sendLoadReport(s *balanceLoadClientStream, interval time.Dura ...@@ -306,6 +299,7 @@ func (b *balancer) sendLoadReport(s *balanceLoadClientStream, interval time.Dura
ClientStats: &stats, ClientStats: &stats,
}, },
}); err != nil { }); err != nil {
grpclog.Errorf("grpclb: failed to send load report: %v", err)
return return
} }
} }
...@@ -316,7 +310,7 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b ...@@ -316,7 +310,7 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b
defer cancel() defer cancel()
stream, err := lbc.BalanceLoad(ctx) stream, err := lbc.BalanceLoad(ctx)
if err != nil { if err != nil {
grpclog.Printf("Failed to perform RPC to the remote balancer %v", err) grpclog.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err)
return return
} }
b.mu.Lock() b.mu.Lock()
...@@ -333,23 +327,25 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b ...@@ -333,23 +327,25 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b
}, },
} }
if err := stream.Send(initReq); err != nil { if err := stream.Send(initReq); err != nil {
grpclog.Errorf("grpclb: failed to send init request: %v", err)
// TODO: backoff on retry? // TODO: backoff on retry?
return true return true
} }
reply, err := stream.Recv() reply, err := stream.Recv()
if err != nil { if err != nil {
grpclog.Errorf("grpclb: failed to recv init response: %v", err)
// TODO: backoff on retry? // TODO: backoff on retry?
return true return true
} }
initResp := reply.GetInitialResponse() initResp := reply.GetInitialResponse()
if initResp == nil { if initResp == nil {
grpclog.Println("Failed to receive the initial response from the remote balancer.") grpclog.Errorf("grpclb: reply from remote balancer did not include initial response.")
return return
} }
// TODO: Support delegation. // TODO: Support delegation.
if initResp.LoadBalancerDelegate != "" { if initResp.LoadBalancerDelegate != "" {
// delegation // delegation
grpclog.Println("TODO: Delegation is not supported yet.") grpclog.Errorf("TODO: Delegation is not supported yet.")
return return
} }
streamDone := make(chan struct{}) streamDone := make(chan struct{})
...@@ -364,6 +360,7 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b ...@@ -364,6 +360,7 @@ func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry b
for { for {
reply, err := stream.Recv() reply, err := stream.Recv()
if err != nil { if err != nil {
grpclog.Errorf("grpclb: failed to recv server list: %v", err)
break break
} }
b.mu.Lock() b.mu.Lock()
...@@ -397,6 +394,7 @@ func (b *balancer) Start(target string, config BalancerConfig) error { ...@@ -397,6 +394,7 @@ func (b *balancer) Start(target string, config BalancerConfig) error {
w, err := b.r.Resolve(target) w, err := b.r.Resolve(target)
if err != nil { if err != nil {
b.mu.Unlock() b.mu.Unlock()
grpclog.Errorf("grpclb: failed to resolve address: %v, err: %v", target, err)
return err return err
} }
b.w = w b.w = w
...@@ -406,7 +404,7 @@ func (b *balancer) Start(target string, config BalancerConfig) error { ...@@ -406,7 +404,7 @@ func (b *balancer) Start(target string, config BalancerConfig) error {
go func() { go func() {
for { for {
if err := b.watchAddrUpdates(w, balancerAddrsCh); err != nil { if err := b.watchAddrUpdates(w, balancerAddrsCh); err != nil {
grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err) grpclog.Warningf("grpclb: the naming watcher stops working due to %v.\n", err)
close(balancerAddrsCh) close(balancerAddrsCh)
return return
} }
...@@ -490,22 +488,29 @@ func (b *balancer) Start(target string, config BalancerConfig) error { ...@@ -490,22 +488,29 @@ func (b *balancer) Start(target string, config BalancerConfig) error {
cc.Close() cc.Close()
} }
// Talk to the remote load balancer to get the server list. // Talk to the remote load balancer to get the server list.
var err error var (
creds := config.DialCreds err error
ccError = make(chan struct{}) dopts []DialOption
if creds == nil { )
cc, err = Dial(rb.addr, WithInsecure()) if creds := config.DialCreds; creds != nil {
} else {
if rb.name != "" { if rb.name != "" {
if err := creds.OverrideServerName(rb.name); err != nil { if err := creds.OverrideServerName(rb.name); err != nil {
grpclog.Printf("Failed to override the server name in the credentials: %v", err) grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v", err)
continue continue
} }
} }
cc, err = Dial(rb.addr, WithTransportCredentials(creds)) dopts = append(dopts, WithTransportCredentials(creds))
} else {
dopts = append(dopts, WithInsecure())
} }
if dialer := config.Dialer; dialer != nil {
// WithDialer takes a different type of function, so we instead use a special DialOption here.
dopts = append(dopts, func(o *dialOptions) { o.copts.Dialer = dialer })
}
ccError = make(chan struct{})
cc, err = Dial(rb.addr, dopts...)
if err != nil { if err != nil {
grpclog.Printf("Failed to setup a connection to the remote balancer %v: %v", rb.addr, err) grpclog.Warningf("grpclb: failed to setup a connection to the remote balancer %v: %v", rb.addr, err)
close(ccError) close(ccError)
continue continue
} }
...@@ -732,6 +737,9 @@ func (b *balancer) Notify() <-chan []Address { ...@@ -732,6 +737,9 @@ func (b *balancer) Notify() <-chan []Address {
func (b *balancer) Close() error { func (b *balancer) Close() error {
b.mu.Lock() b.mu.Lock()
defer b.mu.Unlock() defer b.mu.Unlock()
if b.done {
return errBalancerClosed
}
b.done = true b.done = true
if b.expTimer != nil { if b.expTimer != nil {
b.expTimer.Stop() b.expTimer.Stop()
......
// Copyright 2016, Google Inc. // Copyright 2016 gRPC authors.
// All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without // Licensed under the Apache License, Version 2.0 (the "License");
// modification, are permitted provided that the following conditions are // you may not use this file except in compliance with the License.
// met: // You may obtain a copy of the License at
// //
// * Redistributions of source code must retain the above copyright // http://www.apache.org/licenses/LICENSE-2.0
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // Unless required by applicable law or agreed to in writing, software
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // distributed under the License is distributed on an "AS IS" BASIS,
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // See the License for the specific language governing permissions and
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // limitations under the License.
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3"; syntax = "proto3";
......
...@@ -2,7 +2,11 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library") ...@@ -2,7 +2,11 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library( go_library(
name = "go_default_library", name = "go_default_library",
srcs = ["logger.go"], srcs = [
"grpclog.go",
"logger.go",
"loggerv2.go",
],
importpath = "google.golang.org/grpc/grpclog", importpath = "google.golang.org/grpc/grpclog",
visibility = ["//visibility:public"], visibility = ["//visibility:public"],
) )
......
/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// Package grpclog defines logging for grpc.
//
// All logs in transport package only go to verbose level 2.
// All logs in other packages in grpc are logged in spite of the verbosity level.
//
// In the default logger,
// severity level can be set by environment variable GRPC_GO_LOG_SEVERITY_LEVEL,
// verbosity level can be set by GRPC_GO_LOG_VERBOSITY_LEVEL.
package grpclog
import "os"
var logger = newLoggerV2()
// V reports whether verbosity level l is at least the requested verbose level.
func V(l int) bool {
return logger.V(l)
}
// Info logs to the INFO log.
func Info(args ...interface{}) {
logger.Info(args...)
}
// Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf.
func Infof(format string, args ...interface{}) {
logger.Infof(format, args...)
}
// Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println.
func Infoln(args ...interface{}) {
logger.Infoln(args...)
}
// Warning logs to the WARNING log.
func Warning(args ...interface{}) {
logger.Warning(args...)
}
// Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf.
func Warningf(format string, args ...interface{}) {
logger.Warningf(format, args...)
}
// Warningln logs to the WARNING log. Arguments are handled in the manner of fmt.Println.
func Warningln(args ...interface{}) {
logger.Warningln(args...)
}
// Error logs to the ERROR log.
func Error(args ...interface{}) {
logger.Error(args...)
}
// Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf.
func Errorf(format string, args ...interface{}) {
logger.Errorf(format, args...)
}
// Errorln logs to the ERROR log. Arguments are handled in the manner of fmt.Println.
func Errorln(args ...interface{}) {
logger.Errorln(args...)
}
// Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Print.
// It calls os.Exit() with exit code 1.
func Fatal(args ...interface{}) {
logger.Fatal(args...)
os.Exit(1)
}
// Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf.
// It calles os.Exit() with exit code 1.
func Fatalf(format string, args ...interface{}) {
logger.Fatalf(format, args...)
os.Exit(1)
}
// Fatalln logs to the FATAL log. Arguments are handled in the manner of fmt.Println.
// It calle os.Exit()) with exit code 1.
func Fatalln(args ...interface{}) {
logger.Fatalln(args...)
os.Exit(1)
}
// Print prints to the logger. Arguments are handled in the manner of fmt.Print.
// Deprecated: use Info.
func Print(args ...interface{}) {
logger.Info(args...)
}
// Printf prints to the logger. Arguments are handled in the manner of fmt.Printf.
// Deprecated: use Infof.
func Printf(format string, args ...interface{}) {
logger.Infof(format, args...)
}
// Println prints to the logger. Arguments are handled in the manner of fmt.Println.
// Deprecated: use Infoln.
func Println(args ...interface{}) {
logger.Infoln(args...)
}
/* /*
* *
* Copyright 2015, Google Inc. * Copyright 2015 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
/*
Package grpclog defines logging for grpc.
*/
package grpclog package grpclog
import (
"log"
"os"
)
// Use golang's standard logger by default.
// Access is not mutex-protected: do not modify except in init()
// functions.
var logger Logger = log.New(os.Stderr, "", log.LstdFlags)
// Logger mimics golang's standard Logger as an interface. // Logger mimics golang's standard Logger as an interface.
// Deprecated: use LoggerV2.
type Logger interface { type Logger interface {
Fatal(args ...interface{}) Fatal(args ...interface{})
Fatalf(format string, args ...interface{}) Fatalf(format string, args ...interface{})
...@@ -58,36 +31,53 @@ type Logger interface { ...@@ -58,36 +31,53 @@ type Logger interface {
// SetLogger sets the logger that is used in grpc. Call only from // SetLogger sets the logger that is used in grpc. Call only from
// init() functions. // init() functions.
// Deprecated: use SetLoggerV2.
func SetLogger(l Logger) { func SetLogger(l Logger) {
logger = l logger = &loggerWrapper{Logger: l}
}
// loggerWrapper wraps Logger into a LoggerV2.
type loggerWrapper struct {
Logger
}
func (g *loggerWrapper) Info(args ...interface{}) {
g.Logger.Print(args...)
}
func (g *loggerWrapper) Infoln(args ...interface{}) {
g.Logger.Println(args...)
}
func (g *loggerWrapper) Infof(format string, args ...interface{}) {
g.Logger.Printf(format, args...)
}
func (g *loggerWrapper) Warning(args ...interface{}) {
g.Logger.Print(args...)
} }
// Fatal is equivalent to Print() followed by a call to os.Exit() with a non-zero exit code. func (g *loggerWrapper) Warningln(args ...interface{}) {
func Fatal(args ...interface{}) { g.Logger.Println(args...)
logger.Fatal(args...)
} }
// Fatalf is equivalent to Printf() followed by a call to os.Exit() with a non-zero exit code. func (g *loggerWrapper) Warningf(format string, args ...interface{}) {
func Fatalf(format string, args ...interface{}) { g.Logger.Printf(format, args...)
logger.Fatalf(format, args...)
} }
// Fatalln is equivalent to Println() followed by a call to os.Exit()) with a non-zero exit code. func (g *loggerWrapper) Error(args ...interface{}) {
func Fatalln(args ...interface{}) { g.Logger.Print(args...)
logger.Fatalln(args...)
} }
// Print prints to the logger. Arguments are handled in the manner of fmt.Print. func (g *loggerWrapper) Errorln(args ...interface{}) {
func Print(args ...interface{}) { g.Logger.Println(args...)
logger.Print(args...)
} }
// Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. func (g *loggerWrapper) Errorf(format string, args ...interface{}) {
func Printf(format string, args ...interface{}) { g.Logger.Printf(format, args...)
logger.Printf(format, args...)
} }
// Println prints to the logger. Arguments are handled in the manner of fmt.Println. func (g *loggerWrapper) V(l int) bool {
func Println(args ...interface{}) { // Returns true for all verbose level.
logger.Println(args...) return true
} }
/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package grpclog
import (
"io"
"io/ioutil"
"log"
"os"
"strconv"
)
// LoggerV2 does underlying logging work for grpclog.
type LoggerV2 interface {
// Info logs to INFO log. Arguments are handled in the manner of fmt.Print.
Info(args ...interface{})
// Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.
Infoln(args ...interface{})
// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
Infof(format string, args ...interface{})
// Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print.
Warning(args ...interface{})
// Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.
Warningln(args ...interface{})
// Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
Warningf(format string, args ...interface{})
// Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.
Error(args ...interface{})
// Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
Errorln(args ...interface{})
// Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
Errorf(format string, args ...interface{})
// Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print.
// This function should call os.Exit() with a non-zero exit code.
Fatal(args ...interface{})
// Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
// This function should call os.Exit() with a non-zero exit code.
Fatalln(args ...interface{})
// Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
// This function should call os.Exit() with a non-zero exit code.
Fatalf(format string, args ...interface{})
// V reports whether verbosity level l is at least the requested verbose level.
V(l int) bool
}
// SetLoggerV2 sets logger that is used in grpc to a V2 logger.
// Not mutex-protected, should be called before any gRPC functions.
func SetLoggerV2(l LoggerV2) {
logger = l
}
const (
// infoLog indicates Info severity.
infoLog int = iota
// warningLog indicates Warning severity.
warningLog
// errorLog indicates Error severity.
errorLog
// fatalLog indicates Fatal severity.
fatalLog
)
// severityName contains the string representation of each severity.
var severityName = []string{
infoLog: "INFO",
warningLog: "WARNING",
errorLog: "ERROR",
fatalLog: "FATAL",
}
// loggerT is the default logger used by grpclog.
type loggerT struct {
m []*log.Logger
v int
}
// NewLoggerV2 creates a loggerV2 with the provided writers.
// Fatal logs will be written to errorW, warningW, infoW, followed by exit(1).
// Error logs will be written to errorW, warningW and infoW.
// Warning logs will be written to warningW and infoW.
// Info logs will be written to infoW.
func NewLoggerV2(infoW, warningW, errorW io.Writer) LoggerV2 {
return NewLoggerV2WithVerbosity(infoW, warningW, errorW, 0)
}
// NewLoggerV2WithVerbosity creates a loggerV2 with the provided writers and
// verbosity level.
func NewLoggerV2WithVerbosity(infoW, warningW, errorW io.Writer, v int) LoggerV2 {
var m []*log.Logger
m = append(m, log.New(infoW, severityName[infoLog]+": ", log.LstdFlags))
m = append(m, log.New(io.MultiWriter(infoW, warningW), severityName[warningLog]+": ", log.LstdFlags))
ew := io.MultiWriter(infoW, warningW, errorW) // ew will be used for error and fatal.
m = append(m, log.New(ew, severityName[errorLog]+": ", log.LstdFlags))
m = append(m, log.New(ew, severityName[fatalLog]+": ", log.LstdFlags))
return &loggerT{m: m, v: v}
}
// newLoggerV2 creates a loggerV2 to be used as default logger.
// All logs are written to stderr.
func newLoggerV2() LoggerV2 {
errorW := ioutil.Discard
warningW := ioutil.Discard
infoW := ioutil.Discard
logLevel := os.Getenv("GRPC_GO_LOG_SEVERITY_LEVEL")
switch logLevel {
case "", "ERROR", "error": // If env is unset, set level to ERROR.
errorW = os.Stderr
case "WARNING", "warning":
warningW = os.Stderr
case "INFO", "info":
infoW = os.Stderr
}
var v int
vLevel := os.Getenv("GRPC_GO_LOG_VERBOSITY_LEVEL")
if vl, err := strconv.Atoi(vLevel); err == nil {
v = vl
}
return NewLoggerV2WithVerbosity(infoW, warningW, errorW, v)
}
func (g *loggerT) Info(args ...interface{}) {
g.m[infoLog].Print(args...)
}
func (g *loggerT) Infoln(args ...interface{}) {
g.m[infoLog].Println(args...)
}
func (g *loggerT) Infof(format string, args ...interface{}) {
g.m[infoLog].Printf(format, args...)
}
func (g *loggerT) Warning(args ...interface{}) {
g.m[warningLog].Print(args...)
}
func (g *loggerT) Warningln(args ...interface{}) {
g.m[warningLog].Println(args...)
}
func (g *loggerT) Warningf(format string, args ...interface{}) {
g.m[warningLog].Printf(format, args...)
}
func (g *loggerT) Error(args ...interface{}) {
g.m[errorLog].Print(args...)
}
func (g *loggerT) Errorln(args ...interface{}) {
g.m[errorLog].Println(args...)
}
func (g *loggerT) Errorf(format string, args ...interface{}) {
g.m[errorLog].Printf(format, args...)
}
func (g *loggerT) Fatal(args ...interface{}) {
g.m[fatalLog].Fatal(args...)
}
func (g *loggerT) Fatalln(args ...interface{}) {
g.m[fatalLog].Fatalln(args...)
}
func (g *loggerT) Fatalf(format string, args ...interface{}) {
g.m[fatalLog].Fatalf(format, args...)
}
func (g *loggerT) V(l int) bool {
return l <= g.v
}
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -42,15 +27,15 @@ type UnaryInvoker func(ctx context.Context, method string, req, reply interface{ ...@@ -42,15 +27,15 @@ type UnaryInvoker func(ctx context.Context, method string, req, reply interface{
// UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC // UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC
// and it is the responsibility of the interceptor to call it. // and it is the responsibility of the interceptor to call it.
// This is the EXPERIMENTAL API. // This is an EXPERIMENTAL API.
type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
// Streamer is called by StreamClientInterceptor to create a ClientStream. // Streamer is called by StreamClientInterceptor to create a ClientStream.
type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
// StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O // StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O
// operations. streamer is the handlder to create a ClientStream and it is the responsibility of the interceptor to call it. // operations. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it.
// This is the EXPERIMENTAL API. // This is an EXPERIMENTAL API.
type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)
// UnaryServerInfo consists of various information about a unary RPC on // UnaryServerInfo consists of various information about a unary RPC on
......
/* /*
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
* *
* Copyright 2017, Google Inc. * Copyright 2017 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -39,8 +24,8 @@ import ( ...@@ -39,8 +24,8 @@ import (
) )
// ClientParameters is used to set keepalive parameters on the client-side. // ClientParameters is used to set keepalive parameters on the client-side.
// These configure how the client will actively probe to notice when a connection broken // These configure how the client will actively probe to notice when a connection is broken
// and to cause activity so intermediaries are aware the connection is still in use. // and send pings so intermediaries will be aware of the liveness of the connection.
// Make sure these parameters are set in coordination with the keepalive policy on the server, // Make sure these parameters are set in coordination with the keepalive policy on the server,
// as incompatible settings can result in closing of connection. // as incompatible settings can result in closing of connection.
type ClientParameters struct { type ClientParameters struct {
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
// Package metadata define the structure of the metadata supported by gRPC library. // Package metadata define the structure of the metadata supported by gRPC library.
// Please refer to http://www.grpc.io/docs/guides/wire.html for more information about custom-metadata. // Please refer to https://grpc.io/docs/guides/wire.html for more information about custom-metadata.
package metadata package metadata
import ( import (
...@@ -51,8 +36,14 @@ func DecodeKeyValue(k, v string) (string, string, error) { ...@@ -51,8 +36,14 @@ func DecodeKeyValue(k, v string) (string, string, error) {
// two convenience functions New and Pairs to generate MD. // two convenience functions New and Pairs to generate MD.
type MD map[string][]string type MD map[string][]string
// New creates a MD from given key-value map. // New creates an MD from a given key-value map.
// Keys are automatically converted to lowercase. //
// Only the following ASCII characters are allowed in keys:
// - digits: 0-9
// - uppercase letters: A-Z (normalized to lower)
// - lowercase letters: a-z
// - special characters: -_.
// Uppercase letters are automatically converted to lowercase.
func New(m map[string]string) MD { func New(m map[string]string) MD {
md := MD{} md := MD{}
for k, val := range m { for k, val := range m {
...@@ -64,7 +55,13 @@ func New(m map[string]string) MD { ...@@ -64,7 +55,13 @@ func New(m map[string]string) MD {
// Pairs returns an MD formed by the mapping of key, value ... // Pairs returns an MD formed by the mapping of key, value ...
// Pairs panics if len(kv) is odd. // Pairs panics if len(kv) is odd.
// Keys are automatically converted to lowercase. //
// Only the following ASCII characters are allowed in keys:
// - digits: 0-9
// - uppercase letters: A-Z (normalized to lower)
// - lowercase letters: a-z
// - special characters: -_.
// Uppercase letters are automatically converted to lowercase.
func Pairs(kv ...string) MD { func Pairs(kv ...string) MD {
if len(kv)%2 == 1 { if len(kv)%2 == 1 {
panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv))) panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv)))
...@@ -91,9 +88,9 @@ func (md MD) Copy() MD { ...@@ -91,9 +88,9 @@ func (md MD) Copy() MD {
return Join(md) return Join(md)
} }
// Join joins any number of MDs into a single MD. // Join joins any number of mds into a single MD.
// The order of values for each key is determined by the order in which // The order of values for each key is determined by the order in which
// the MDs containing those values are presented to Join. // the mds containing those values are presented to Join.
func Join(mds ...MD) MD { func Join(mds ...MD) MD {
out := MD{} out := MD{}
for _, md := range mds { for _, md := range mds {
...@@ -127,17 +124,17 @@ func FromContext(ctx context.Context) (md MD, ok bool) { ...@@ -127,17 +124,17 @@ func FromContext(ctx context.Context) (md MD, ok bool) {
return FromIncomingContext(ctx) return FromIncomingContext(ctx)
} }
// FromIncomingContext returns the incoming MD in ctx if it exists. The // FromIncomingContext returns the incoming metadata in ctx if it exists. The
// returned md should be immutable, writing to it may cause races. // returned MD should not be modified. Writing to it may cause races.
// Modification should be made to the copies of the returned md. // Modification should be made to copies of the returned MD.
func FromIncomingContext(ctx context.Context) (md MD, ok bool) { func FromIncomingContext(ctx context.Context) (md MD, ok bool) {
md, ok = ctx.Value(mdIncomingKey{}).(MD) md, ok = ctx.Value(mdIncomingKey{}).(MD)
return return
} }
// FromOutgoingContext returns the outgoing MD in ctx if it exists. The // FromOutgoingContext returns the outgoing metadata in ctx if it exists. The
// returned md should be immutable, writing to it may cause races. // returned MD should not be modified. Writing to it may cause races.
// Modification should be made to the copies of the returned md. // Modification should be made to the copies of the returned MD.
func FromOutgoingContext(ctx context.Context) (md MD, ok bool) { func FromOutgoingContext(ctx context.Context) (md MD, ok bool) {
md, ok = ctx.Value(mdOutgoingKey{}).(MD) md, ok = ctx.Value(mdOutgoingKey{}).(MD)
return return
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -42,7 +27,8 @@ import ( ...@@ -42,7 +27,8 @@ import (
"google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials"
) )
// Peer contains the information of the peer for an RPC. // Peer contains the information of the peer for an RPC, such as the address
// and authentication information.
type Peer struct { type Peer struct {
// Addr is the peer address. // Addr is the peer address.
Addr net.Addr Addr net.Addr
......
/* /*
* *
* Copyright 2017, Google Inc. * Copyright 2017 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -45,19 +30,22 @@ type ConnTagInfo struct { ...@@ -45,19 +30,22 @@ type ConnTagInfo struct {
RemoteAddr net.Addr RemoteAddr net.Addr
// LocalAddr is the local address of the corresponding connection. // LocalAddr is the local address of the corresponding connection.
LocalAddr net.Addr LocalAddr net.Addr
// TODO add QOS related fields.
} }
// RPCTagInfo defines the relevant information needed by RPC context tagger. // RPCTagInfo defines the relevant information needed by RPC context tagger.
type RPCTagInfo struct { type RPCTagInfo struct {
// FullMethodName is the RPC method in the format of /package.service/method. // FullMethodName is the RPC method in the format of /package.service/method.
FullMethodName string FullMethodName string
// FailFast indicates if this RPC is failfast.
// This field is only valid on client side, it's always false on server side.
FailFast bool
} }
// Handler defines the interface for the related stats handling (e.g., RPCs, connections). // Handler defines the interface for the related stats handling (e.g., RPCs, connections).
type Handler interface { type Handler interface {
// TagRPC can attach some information to the given context. // TagRPC can attach some information to the given context.
// The returned context is used in the rest lifetime of the RPC. // The context used for the rest lifetime of the RPC will be derived from
// the returned context.
TagRPC(context.Context, *RPCTagInfo) context.Context TagRPC(context.Context, *RPCTagInfo) context.Context
// HandleRPC processes the RPC stats. // HandleRPC processes the RPC stats.
HandleRPC(context.Context, RPCStats) HandleRPC(context.Context, RPCStats)
......
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -49,7 +34,7 @@ type RPCStats interface { ...@@ -49,7 +34,7 @@ type RPCStats interface {
} }
// Begin contains stats when an RPC begins. // Begin contains stats when an RPC begins.
// FailFast are only valid if Client is true. // FailFast is only valid if this Begin is from client side.
type Begin struct { type Begin struct {
// Client is true if this Begin is from client side. // Client is true if this Begin is from client side.
Client bool Client bool
...@@ -59,7 +44,7 @@ type Begin struct { ...@@ -59,7 +44,7 @@ type Begin struct {
FailFast bool FailFast bool
} }
// IsClient indicates if this is from client side. // IsClient indicates if the stats information is from client side.
func (s *Begin) IsClient() bool { return s.Client } func (s *Begin) IsClient() bool { return s.Client }
func (s *Begin) isRPCStats() {} func (s *Begin) isRPCStats() {}
...@@ -80,19 +65,19 @@ type InPayload struct { ...@@ -80,19 +65,19 @@ type InPayload struct {
RecvTime time.Time RecvTime time.Time
} }
// IsClient indicates if this is from client side. // IsClient indicates if the stats information is from client side.
func (s *InPayload) IsClient() bool { return s.Client } func (s *InPayload) IsClient() bool { return s.Client }
func (s *InPayload) isRPCStats() {} func (s *InPayload) isRPCStats() {}
// InHeader contains stats when a header is received. // InHeader contains stats when a header is received.
// FullMethod, addresses and Compression are only valid if Client is false.
type InHeader struct { type InHeader struct {
// Client is true if this InHeader is from client side. // Client is true if this InHeader is from client side.
Client bool Client bool
// WireLength is the wire length of header. // WireLength is the wire length of header.
WireLength int WireLength int
// The following fields are valid only if Client is false.
// FullMethod is the full RPC method string, i.e., /package.service/method. // FullMethod is the full RPC method string, i.e., /package.service/method.
FullMethod string FullMethod string
// RemoteAddr is the remote address of the corresponding connection. // RemoteAddr is the remote address of the corresponding connection.
...@@ -103,7 +88,7 @@ type InHeader struct { ...@@ -103,7 +88,7 @@ type InHeader struct {
Compression string Compression string
} }
// IsClient indicates if this is from client side. // IsClient indicates if the stats information is from client side.
func (s *InHeader) IsClient() bool { return s.Client } func (s *InHeader) IsClient() bool { return s.Client }
func (s *InHeader) isRPCStats() {} func (s *InHeader) isRPCStats() {}
...@@ -116,7 +101,7 @@ type InTrailer struct { ...@@ -116,7 +101,7 @@ type InTrailer struct {
WireLength int WireLength int
} }
// IsClient indicates if this is from client side. // IsClient indicates if the stats information is from client side.
func (s *InTrailer) IsClient() bool { return s.Client } func (s *InTrailer) IsClient() bool { return s.Client }
func (s *InTrailer) isRPCStats() {} func (s *InTrailer) isRPCStats() {}
...@@ -137,19 +122,19 @@ type OutPayload struct { ...@@ -137,19 +122,19 @@ type OutPayload struct {
SentTime time.Time SentTime time.Time
} }
// IsClient indicates if this is from client side. // IsClient indicates if this stats information is from client side.
func (s *OutPayload) IsClient() bool { return s.Client } func (s *OutPayload) IsClient() bool { return s.Client }
func (s *OutPayload) isRPCStats() {} func (s *OutPayload) isRPCStats() {}
// OutHeader contains stats when a header is sent. // OutHeader contains stats when a header is sent.
// FullMethod, addresses and Compression are only valid if Client is true.
type OutHeader struct { type OutHeader struct {
// Client is true if this OutHeader is from client side. // Client is true if this OutHeader is from client side.
Client bool Client bool
// WireLength is the wire length of header. // WireLength is the wire length of header.
WireLength int WireLength int
// The following fields are valid only if Client is true.
// FullMethod is the full RPC method string, i.e., /package.service/method. // FullMethod is the full RPC method string, i.e., /package.service/method.
FullMethod string FullMethod string
// RemoteAddr is the remote address of the corresponding connection. // RemoteAddr is the remote address of the corresponding connection.
...@@ -160,7 +145,7 @@ type OutHeader struct { ...@@ -160,7 +145,7 @@ type OutHeader struct {
Compression string Compression string
} }
// IsClient indicates if this is from client side. // IsClient indicates if this stats information is from client side.
func (s *OutHeader) IsClient() bool { return s.Client } func (s *OutHeader) IsClient() bool { return s.Client }
func (s *OutHeader) isRPCStats() {} func (s *OutHeader) isRPCStats() {}
...@@ -173,7 +158,7 @@ type OutTrailer struct { ...@@ -173,7 +158,7 @@ type OutTrailer struct {
WireLength int WireLength int
} }
// IsClient indicates if this is from client side. // IsClient indicates if this stats information is from client side.
func (s *OutTrailer) IsClient() bool { return s.Client } func (s *OutTrailer) IsClient() bool { return s.Client }
func (s *OutTrailer) isRPCStats() {} func (s *OutTrailer) isRPCStats() {}
......
/* /*
* *
* Copyright 2017, Google Inc. * Copyright 2017 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
* *
* Copyright 2016, Google Inc. * Copyright 2016 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
/* /*
* *
* Copyright 2015, Google Inc. * Copyright 2015 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
......
...@@ -3,6 +3,7 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library") ...@@ -3,6 +3,7 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library( go_library(
name = "go_default_library", name = "go_default_library",
srcs = [ srcs = [
"bdp_estimator.go",
"control.go", "control.go",
"go16.go", "go16.go",
"go17.go", "go17.go",
...@@ -10,6 +11,7 @@ go_library( ...@@ -10,6 +11,7 @@ go_library(
"http2_client.go", "http2_client.go",
"http2_server.go", "http2_server.go",
"http_util.go", "http_util.go",
"log.go",
"transport.go", "transport.go",
], ],
importpath = "google.golang.org/grpc/transport", importpath = "google.golang.org/grpc/transport",
......
package transport
import (
"sync"
"time"
)
const (
// bdpLimit is the maximum value the flow control windows
// will be increased to.
bdpLimit = (1 << 20) * 4
// alpha is a constant factor used to keep a moving average
// of RTTs.
alpha = 0.9
// If the current bdp sample is greater than or equal to
// our beta * our estimated bdp and the current bandwidth
// sample is the maximum bandwidth observed so far, we
// increase our bbp estimate by a factor of gamma.
beta = 0.66
// To put our bdp to be smaller than or equal to twice the real BDP,
// we should multiply our current sample with 4/3, however to round things out
// we use 2 as the multiplication factor.
gamma = 2
)
var (
// Adding arbitrary data to ping so that its ack can be
// identified.
// Easter-egg: what does the ping message say?
bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}}
)
type bdpEstimator struct {
// sentAt is the time when the ping was sent.
sentAt time.Time
mu sync.Mutex
// bdp is the current bdp estimate.
bdp uint32
// sample is the number of bytes received in one measurement cycle.
sample uint32
// bwMax is the maximum bandwidth noted so far (bytes/sec).
bwMax float64
// bool to keep track of the begining of a new measurement cycle.
isSent bool
// Callback to update the window sizes.
updateFlowControl func(n uint32)
// sampleCount is the number of samples taken so far.
sampleCount uint64
// round trip time (seconds)
rtt float64
}
// timesnap registers the time bdp ping was sent out so that
// network rtt can be calculated when its ack is recieved.
// It is called (by controller) when the bdpPing is
// being written on the wire.
func (b *bdpEstimator) timesnap(d [8]byte) {
if bdpPing.data != d {
return
}
b.sentAt = time.Now()
}
// add adds bytes to the current sample for calculating bdp.
// It returns true only if a ping must be sent. This can be used
// by the caller (handleData) to make decision about batching
// a window update with it.
func (b *bdpEstimator) add(n uint32) bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.bdp == bdpLimit {
return false
}
if !b.isSent {
b.isSent = true
b.sample = n
b.sentAt = time.Time{}
b.sampleCount++
return true
}
b.sample += n
return false
}
// calculate is called when an ack for a bdp ping is received.
// Here we calculate the current bdp and bandwidth sample and
// decide if the flow control windows should go up.
func (b *bdpEstimator) calculate(d [8]byte) {
// Check if the ping acked for was the bdp ping.
if bdpPing.data != d {
return
}
b.mu.Lock()
rttSample := time.Since(b.sentAt).Seconds()
if b.sampleCount < 10 {
// Bootstrap rtt with an average of first 10 rtt samples.
b.rtt += (rttSample - b.rtt) / float64(b.sampleCount)
} else {
// Heed to the recent past more.
b.rtt += (rttSample - b.rtt) * float64(alpha)
}
b.isSent = false
// The number of bytes accumalated so far in the sample is smaller
// than or equal to 1.5 times the real BDP on a saturated connection.
bwCurrent := float64(b.sample) / (b.rtt * float64(1.5))
if bwCurrent > b.bwMax {
b.bwMax = bwCurrent
}
// If the current sample (which is smaller than or equal to the 1.5 times the real BDP) is
// greater than or equal to 2/3rd our perceived bdp AND this is the maximum bandwidth seen so far, we
// should update our perception of the network BDP.
if float64(b.sample) >= beta*float64(b.bdp) && bwCurrent == b.bwMax && b.bdp != bdpLimit {
sampleFloat := float64(b.sample)
b.bdp = uint32(gamma * sampleFloat)
if b.bdp > bdpLimit {
b.bdp = bdpLimit
}
bdp := b.bdp
b.mu.Unlock()
b.updateFlowControl(bdp)
return
}
b.mu.Unlock()
}
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -46,8 +31,7 @@ const ( ...@@ -46,8 +31,7 @@ const (
// The default value of flow control window size in HTTP2 spec. // The default value of flow control window size in HTTP2 spec.
defaultWindowSize = 65535 defaultWindowSize = 65535
// The initial window size for flow control. // The initial window size for flow control.
initialWindowSize = defaultWindowSize // for an RPC initialWindowSize = defaultWindowSize // for an RPC
initialConnWindowSize = defaultWindowSize * 16 // for a connection
infinity = time.Duration(math.MaxInt64) infinity = time.Duration(math.MaxInt64)
defaultClientKeepaliveTime = infinity defaultClientKeepaliveTime = infinity
defaultClientKeepaliveTimeout = time.Duration(20 * time.Second) defaultClientKeepaliveTimeout = time.Duration(20 * time.Second)
...@@ -58,6 +42,8 @@ const ( ...@@ -58,6 +42,8 @@ const (
defaultServerKeepaliveTime = time.Duration(2 * time.Hour) defaultServerKeepaliveTime = time.Duration(2 * time.Hour)
defaultServerKeepaliveTimeout = time.Duration(20 * time.Second) defaultServerKeepaliveTimeout = time.Duration(20 * time.Second)
defaultKeepalivePolicyMinTime = time.Duration(5 * time.Minute) defaultKeepalivePolicyMinTime = time.Duration(5 * time.Minute)
// max window limit set by HTTP2 Specs.
maxWindowSize = math.MaxInt32
) )
// The following defines various control items which could flow through // The following defines various control items which could flow through
...@@ -66,6 +52,7 @@ const ( ...@@ -66,6 +52,7 @@ const (
type windowUpdate struct { type windowUpdate struct {
streamID uint32 streamID uint32
increment uint32 increment uint32
flush bool
} }
func (*windowUpdate) item() {} func (*windowUpdate) item() {}
...@@ -87,6 +74,8 @@ func (*resetStream) item() {} ...@@ -87,6 +74,8 @@ func (*resetStream) item() {}
type goAway struct { type goAway struct {
code http2.ErrCode code http2.ErrCode
debugData []byte debugData []byte
headsUp bool
closeConn bool
} }
func (*goAway) item() {} func (*goAway) item() {}
...@@ -157,16 +146,59 @@ func (qb *quotaPool) acquire() <-chan int { ...@@ -157,16 +146,59 @@ func (qb *quotaPool) acquire() <-chan int {
// inFlow deals with inbound flow control // inFlow deals with inbound flow control
type inFlow struct { type inFlow struct {
mu sync.Mutex
// The inbound flow control limit for pending data. // The inbound flow control limit for pending data.
limit uint32 limit uint32
mu sync.Mutex
// pendingData is the overall data which have been received but not been // pendingData is the overall data which have been received but not been
// consumed by applications. // consumed by applications.
pendingData uint32 pendingData uint32
// The amount of data the application has consumed but grpc has not sent // The amount of data the application has consumed but grpc has not sent
// window update for them. Used to reduce window update frequency. // window update for them. Used to reduce window update frequency.
pendingUpdate uint32 pendingUpdate uint32
// delta is the extra window update given by receiver when an application
// is reading data bigger in size than the inFlow limit.
delta uint32
}
// newLimit updates the inflow window to a new value n.
// It assumes that n is always greater than the old limit.
func (f *inFlow) newLimit(n uint32) uint32 {
f.mu.Lock()
defer f.mu.Unlock()
d := n - f.limit
f.limit = n
return d
}
func (f *inFlow) maybeAdjust(n uint32) uint32 {
if n > uint32(math.MaxInt32) {
n = uint32(math.MaxInt32)
}
f.mu.Lock()
defer f.mu.Unlock()
// estSenderQuota is the receiver's view of the maximum number of bytes the sender
// can send without a window update.
estSenderQuota := int32(f.limit - (f.pendingData + f.pendingUpdate))
// estUntransmittedData is the maximum number of bytes the sends might not have put
// on the wire yet. A value of 0 or less means that we have already received all or
// more bytes than the application is requesting to read.
estUntransmittedData := int32(n - f.pendingData) // Casting into int32 since it could be negative.
// This implies that unless we send a window update, the sender won't be able to send all the bytes
// for this message. Therefore we must send an update over the limit since there's an active read
// request from the application.
if estUntransmittedData > estSenderQuota {
// Sender's window shouldn't go more than 2^31 - 1 as speecified in the HTTP spec.
if f.limit+n > maxWindowSize {
f.delta = maxWindowSize - f.limit
} else {
// Send a window update for the whole message and not just the difference between
// estUntransmittedData and estSenderQuota. This will be helpful in case the message
// is padded; We will fallback on the current available window(at least a 1/4th of the limit).
f.delta = n
}
return f.delta
}
return 0
} }
// onData is invoked when some data frame is received. It updates pendingData. // onData is invoked when some data frame is received. It updates pendingData.
...@@ -174,7 +206,7 @@ func (f *inFlow) onData(n uint32) error { ...@@ -174,7 +206,7 @@ func (f *inFlow) onData(n uint32) error {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
f.pendingData += n f.pendingData += n
if f.pendingData+f.pendingUpdate > f.limit { if f.pendingData+f.pendingUpdate > f.limit+f.delta {
return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", f.pendingData+f.pendingUpdate, f.limit) return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", f.pendingData+f.pendingUpdate, f.limit)
} }
return nil return nil
...@@ -189,6 +221,13 @@ func (f *inFlow) onRead(n uint32) uint32 { ...@@ -189,6 +221,13 @@ func (f *inFlow) onRead(n uint32) uint32 {
return 0 return 0
} }
f.pendingData -= n f.pendingData -= n
if n > f.delta {
n -= f.delta
f.delta = 0
} else {
f.delta -= n
n = 0
}
f.pendingUpdate += n f.pendingUpdate += n
if f.pendingUpdate >= f.limit/4 { if f.pendingUpdate >= f.limit/4 {
wu := f.pendingUpdate wu := f.pendingUpdate
...@@ -198,10 +237,10 @@ func (f *inFlow) onRead(n uint32) uint32 { ...@@ -198,10 +237,10 @@ func (f *inFlow) onRead(n uint32) uint32 {
return 0 return 0
} }
func (f *inFlow) resetPendingData() uint32 { func (f *inFlow) resetPendingUpdate() uint32 {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
n := f.pendingData n := f.pendingUpdate
f.pendingData = 0 f.pendingUpdate = 0
return n return n
} }
// +build go1.6,!go1.7 // +build go1.6,!go1.7
/* /*
* Copyright 2016, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2016 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * Unless required by applicable law or agreed to in writing, software
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * distributed under the License is distributed on an "AS IS" BASIS,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * See the License for the specific language governing permissions and
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * limitations under the License.
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -37,6 +23,8 @@ package transport ...@@ -37,6 +23,8 @@ package transport
import ( import (
"net" "net"
"google.golang.org/grpc/codes"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
...@@ -44,3 +32,14 @@ import ( ...@@ -44,3 +32,14 @@ import (
func dialContext(ctx context.Context, network, address string) (net.Conn, error) { func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address)
} }
// ContextErr converts the error from context package into a StreamError.
func ContextErr(err error) StreamError {
switch err {
case context.DeadlineExceeded:
return streamErrorf(codes.DeadlineExceeded, "%v", err)
case context.Canceled:
return streamErrorf(codes.Canceled, "%v", err)
}
return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err)
}
// +build go1.7 // +build go1.7
/* /*
* Copyright 2016, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2016 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * Unless required by applicable law or agreed to in writing, software
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * distributed under the License is distributed on an "AS IS" BASIS,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * See the License for the specific language governing permissions and
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * limitations under the License.
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
package transport package transport
import ( import (
"context"
"net" "net"
"golang.org/x/net/context" "google.golang.org/grpc/codes"
netctx "golang.org/x/net/context"
) )
// dialContext connects to the address on the named network. // dialContext connects to the address on the named network.
func dialContext(ctx context.Context, network, address string) (net.Conn, error) { func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, address) return (&net.Dialer{}).DialContext(ctx, network, address)
} }
// ContextErr converts the error from context package into a StreamError.
func ContextErr(err error) StreamError {
switch err {
case context.DeadlineExceeded, netctx.DeadlineExceeded:
return streamErrorf(codes.DeadlineExceeded, "%v", err)
case context.Canceled, netctx.Canceled:
return streamErrorf(codes.Canceled, "%v", err)
}
return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err)
}
/* /*
* Copyright 2016, Google Inc.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Copyright 2016 gRPC authors.
* modification, are permitted provided that the following conditions are
* met:
* *
* * Redistributions of source code must retain the above copyright * Licensed under the Apache License, Version 2.0 (the "License");
* notice, this list of conditions and the following disclaimer. * you may not use this file except in compliance with the License.
* * Redistributions in binary form must reproduce the above * You may obtain a copy of the License at
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * http://www.apache.org/licenses/LICENSE-2.0
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * Unless required by applicable law or agreed to in writing, software
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * distributed under the License is distributed on an "AS IS" BASIS,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * See the License for the specific language governing permissions and
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * limitations under the License.
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -102,15 +88,6 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTr ...@@ -102,15 +88,6 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTr
continue continue
} }
for _, v := range vv { for _, v := range vv {
if k == "user-agent" {
// user-agent is special. Copying logic of http_util.go.
if i := strings.LastIndex(v, " "); i == -1 {
// There is no application user agent string being set
continue
} else {
v = v[:i]
}
}
v, err := decodeMetadataHeader(k, v) v, err := decodeMetadataHeader(k, v)
if err != nil { if err != nil {
return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err) return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err)
...@@ -179,11 +156,18 @@ func (a strAddr) String() string { return string(a) } ...@@ -179,11 +156,18 @@ func (a strAddr) String() string { return string(a) }
// do runs fn in the ServeHTTP goroutine. // do runs fn in the ServeHTTP goroutine.
func (ht *serverHandlerTransport) do(fn func()) error { func (ht *serverHandlerTransport) do(fn func()) error {
// Avoid a panic writing to closed channel. Imperfect but maybe good enough.
select { select {
case ht.writes <- fn:
return nil
case <-ht.closedCh: case <-ht.closedCh:
return ErrConnClosing return ErrConnClosing
default:
select {
case ht.writes <- fn:
return nil
case <-ht.closedCh:
return ErrConnClosing
}
} }
} }
...@@ -309,13 +293,13 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace ...@@ -309,13 +293,13 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace
req := ht.req req := ht.req
s := &Stream{ s := &Stream{
id: 0, // irrelevant id: 0, // irrelevant
windowHandler: func(int) {}, // nothing requestRead: func(int) {},
cancel: cancel, cancel: cancel,
buf: newRecvBuffer(), buf: newRecvBuffer(),
st: ht, st: ht,
method: req.URL.Path, method: req.URL.Path,
recvCompress: req.Header.Get("grpc-encoding"), recvCompress: req.Header.Get("grpc-encoding"),
} }
pr := &peer.Peer{ pr := &peer.Peer{
Addr: ht.RemoteAddr(), Addr: ht.RemoteAddr(),
...@@ -326,7 +310,10 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace ...@@ -326,7 +310,10 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace
ctx = metadata.NewIncomingContext(ctx, ht.headerMD) ctx = metadata.NewIncomingContext(ctx, ht.headerMD)
ctx = peer.NewContext(ctx, pr) ctx = peer.NewContext(ctx, pr)
s.ctx = newContextWithStream(ctx, s) s.ctx = newContextWithStream(ctx, s)
s.dec = &recvBufferReader{ctx: s.ctx, recv: s.buf} s.trReader = &transportReader{
reader: &recvBufferReader{ctx: s.ctx, recv: s.buf},
windowHandler: func(int) {},
}
// readerDone is closed when the Body.Read-ing goroutine exits. // readerDone is closed when the Body.Read-ing goroutine exits.
readerDone := make(chan struct{}) readerDone := make(chan struct{})
...@@ -338,11 +325,11 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace ...@@ -338,11 +325,11 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace
for buf := make([]byte, readSize); ; { for buf := make([]byte, readSize); ; {
n, err := req.Body.Read(buf) n, err := req.Body.Read(buf)
if n > 0 { if n > 0 {
s.buf.put(&recvMsg{data: buf[:n:n]}) s.buf.put(recvMsg{data: buf[:n:n]})
buf = buf[n:] buf = buf[n:]
} }
if err != nil { if err != nil {
s.buf.put(&recvMsg{err: mapRecvMsgError(err)}) s.buf.put(recvMsg{err: mapRecvMsgError(err)})
return return
} }
if len(buf) == 0 { if len(buf) == 0 {
......
/* /*
* *
* Copyright 2014, Google Inc. * Copyright 2014 gRPC authors.
* All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Licensed under the Apache License, Version 2.0 (the "License");
* modification, are permitted provided that the following conditions are * you may not use this file except in compliance with the License.
* met: * You may obtain a copy of the License at
* *
* * Redistributions of source code must retain the above copyright * http://www.apache.org/licenses/LICENSE-2.0
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * Unless required by applicable law or agreed to in writing, software
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * distributed under the License is distributed on an "AS IS" BASIS,
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * See the License for the specific language governing permissions and
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * limitations under the License.
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
...@@ -40,6 +25,7 @@ import ( ...@@ -40,6 +25,7 @@ import (
"fmt" "fmt"
"io" "io"
"net" "net"
"net/http"
"strconv" "strconv"
"strings" "strings"
"sync/atomic" "sync/atomic"
...@@ -50,7 +36,6 @@ import ( ...@@ -50,7 +36,6 @@ import (
"golang.org/x/net/http2/hpack" "golang.org/x/net/http2/hpack"
spb "google.golang.org/genproto/googleapis/rpc/status" spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
) )
...@@ -88,6 +73,24 @@ var ( ...@@ -88,6 +73,24 @@ var (
codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm, codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm,
codes.PermissionDenied: http2.ErrCodeInadequateSecurity, codes.PermissionDenied: http2.ErrCodeInadequateSecurity,
} }
httpStatusConvTab = map[int]codes.Code{
// 400 Bad Request - INTERNAL.
http.StatusBadRequest: codes.Internal,
// 401 Unauthorized - UNAUTHENTICATED.
http.StatusUnauthorized: codes.Unauthenticated,
// 403 Forbidden - PERMISSION_DENIED.
http.StatusForbidden: codes.PermissionDenied,
// 404 Not Found - UNIMPLEMENTED.
http.StatusNotFound: codes.Unimplemented,
// 429 Too Many Requests - UNAVAILABLE.
http.StatusTooManyRequests: codes.Unavailable,
// 502 Bad Gateway - UNAVAILABLE.
http.StatusBadGateway: codes.Unavailable,
// 503 Service Unavailable - UNAVAILABLE.
http.StatusServiceUnavailable: codes.Unavailable,
// 504 Gateway timeout - UNAVAILABLE.
http.StatusGatewayTimeout: codes.Unavailable,
}
) )
// Records the states during HPACK decoding. Must be reset once the // Records the states during HPACK decoding. Must be reset once the
...@@ -100,8 +103,9 @@ type decodeState struct { ...@@ -100,8 +103,9 @@ type decodeState struct {
statusGen *status.Status statusGen *status.Status
// rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not
// intended for direct access outside of parsing. // intended for direct access outside of parsing.
rawStatusCode int32 rawStatusCode *int
rawStatusMsg string rawStatusMsg string
httpStatus *int
// Server side only fields. // Server side only fields.
timeoutSet bool timeoutSet bool
timeout time.Duration timeout time.Duration
...@@ -159,7 +163,7 @@ func validContentType(t string) bool { ...@@ -159,7 +163,7 @@ func validContentType(t string) bool {
func (d *decodeState) status() *status.Status { func (d *decodeState) status() *status.Status {
if d.statusGen == nil { if d.statusGen == nil {
// No status-details were provided; generate status using code/msg. // No status-details were provided; generate status using code/msg.
d.statusGen = status.New(codes.Code(d.rawStatusCode), d.rawStatusMsg) d.statusGen = status.New(codes.Code(int32(*(d.rawStatusCode))), d.rawStatusMsg)
} }
return d.statusGen return d.statusGen
} }
...@@ -193,6 +197,44 @@ func decodeMetadataHeader(k, v string) (string, error) { ...@@ -193,6 +197,44 @@ func decodeMetadataHeader(k, v string) (string, error) {
return v, nil return v, nil
} }
func (d *decodeState) decodeResponseHeader(frame *http2.MetaHeadersFrame) error {
for _, hf := range frame.Fields {
if err := d.processHeaderField(hf); err != nil {
return err
}
}
// If grpc status exists, no need to check further.
if d.rawStatusCode != nil || d.statusGen != nil {
return nil
}
// If grpc status doesn't exist and http status doesn't exist,
// then it's a malformed header.
if d.httpStatus == nil {
return streamErrorf(codes.Internal, "malformed header: doesn't contain status(gRPC or HTTP)")
}
if *(d.httpStatus) != http.StatusOK {
code, ok := httpStatusConvTab[*(d.httpStatus)]
if !ok {
code = codes.Unknown
}
return streamErrorf(code, http.StatusText(*(d.httpStatus)))
}
// gRPC status doesn't exist and http status is OK.
// Set rawStatusCode to be unknown and return nil error.
// So that, if the stream has ended this Unknown status
// will be propogated to the user.
// Otherwise, it will be ignored. In which case, status from
// a later trailer, that has StreamEnded flag set, is propogated.
code := int(codes.Unknown)
d.rawStatusCode = &code
return nil
}
func (d *decodeState) processHeaderField(f hpack.HeaderField) error { func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
switch f.Name { switch f.Name {
case "content-type": case "content-type":
...@@ -206,7 +248,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error { ...@@ -206,7 +248,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
if err != nil { if err != nil {
return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err) return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err)
} }
d.rawStatusCode = int32(code) d.rawStatusCode = &code
case "grpc-message": case "grpc-message":
d.rawStatusMsg = decodeGrpcMessage(f.Value) d.rawStatusMsg = decodeGrpcMessage(f.Value)
case "grpc-status-details-bin": case "grpc-status-details-bin":
...@@ -227,6 +269,12 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error { ...@@ -227,6 +269,12 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
} }
case ":path": case ":path":
d.method = f.Value d.method = f.Value
case ":status":
code, err := strconv.Atoi(f.Value)
if err != nil {
return streamErrorf(codes.Internal, "transport: malformed http-status: %v", err)
}
d.httpStatus = &code
default: default:
if !isReservedHeader(f.Name) || isWhitelistedPseudoHeader(f.Name) { if !isReservedHeader(f.Name) || isWhitelistedPseudoHeader(f.Name) {
if d.mdata == nil { if d.mdata == nil {
...@@ -234,7 +282,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error { ...@@ -234,7 +282,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
} }
v, err := decodeMetadataHeader(f.Name, f.Value) v, err := decodeMetadataHeader(f.Name, f.Value)
if err != nil { if err != nil {
grpclog.Printf("Failed to decode (%q, %q): %v", f.Name, f.Value, err) errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err)
return nil return nil
} }
d.mdata[f.Name] = append(d.mdata[f.Name], v) d.mdata[f.Name] = append(d.mdata[f.Name], v)
......
/*
*
* Copyright 2017 gRPC authors.
*
* 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
*
* http://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.
*
*/
// This file contains wrappers for grpclog functions.
// The transport package only logs to verbose level 2 by default.
package transport
import "google.golang.org/grpc/grpclog"
const logLevel = 2
func infof(format string, args ...interface{}) {
if grpclog.V(logLevel) {
grpclog.Infof(format, args...)
}
}
func warningf(format string, args ...interface{}) {
if grpclog.V(logLevel) {
grpclog.Warningf(format, args...)
}
}
func errorf(format string, args ...interface{}) {
if grpclog.V(logLevel) {
grpclog.Errorf(format, args...)
}
}
func fatalf(format string, args ...interface{}) {
if grpclog.V(logLevel) {
grpclog.Fatalf(format, args...)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment