diff --git a/cmd/common/config/flags.go b/cmd/common/config/flags.go index 524985d62..a6cddda2b 100644 --- a/cmd/common/config/flags.go +++ b/cmd/common/config/flags.go @@ -26,6 +26,7 @@ const ( KeyBasicAuthUsername = "basic-auth-username" // string KeyBasicAuthPassword = "basic-auth-password" // string KeyTimeout = "timeout" // time.Duration + KeyRequestTimeout = "request-timeout" // time.Duration ) // GlobalFlags are flags that apply to any command. @@ -47,6 +48,7 @@ func initGlobalFlags() { func initServerFlags() { ServerFlags.String(KeyServer, defaults.ServerAddress, "Address of a Hubble server. Ignored when --input-file is provided.") ServerFlags.Duration(KeyTimeout, defaults.DialTimeout, "Hubble server dialing timeout") + ServerFlags.Duration(KeyRequestTimeout, defaults.RequestTimeout, "Unary Request timeout. Only applies to non-streaming RPCs (ServerStatus, ListNodes, ListNamespaces).") ServerFlags.Bool( KeyTLS, false, diff --git a/cmd/common/conn/conn.go b/cmd/common/conn/conn.go index c0f94de07..e31b8513b 100644 --- a/cmd/common/conn/conn.go +++ b/cmd/common/conn/conn.go @@ -9,7 +9,9 @@ import ( "strings" "time" + "github.com/cilium/hubble/cmd/common/config" "github.com/cilium/hubble/pkg/defaults" + "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout" "github.com/spf13/viper" "google.golang.org/grpc" ) @@ -26,6 +28,7 @@ func init() { grpcOptionBlock, grpcOptionFailOnNonTempDialError, grpcOptionConnError, + grpcInterceptors, ) } @@ -41,6 +44,10 @@ func grpcOptionConnError(_ *viper.Viper) (grpc.DialOption, error) { return grpc.WithReturnConnectionError(), nil } +func grpcInterceptors(vp *viper.Viper) (grpc.DialOption, error) { + return grpc.WithUnaryInterceptor(timeout.UnaryClientInterceptor(vp.GetDuration(config.KeyRequestTimeout))), nil +} + var grpcDialOptions []grpc.DialOption // Init initializes common connection options. It MUST be called prior to any diff --git a/cmd/list/namespaces.go b/cmd/list/namespaces.go index ed3a7c5a3..db2524ea6 100644 --- a/cmd/list/namespaces.go +++ b/cmd/list/namespaces.go @@ -24,8 +24,7 @@ func newNamespacesCommand(vp *viper.Viper) *cobra.Command { Use: "namespaces", Short: "List namespaces with recent flows", RunE: func(cmd *cobra.Command, _ []string) error { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := cmd.Context() hubbleConn, err := conn.New(ctx, vp.GetString(config.KeyServer), vp.GetDuration(config.KeyTimeout)) if err != nil { return err diff --git a/cmd/list/node.go b/cmd/list/node.go index 67808400d..ece45081b 100644 --- a/cmd/list/node.go +++ b/cmd/list/node.go @@ -31,13 +31,13 @@ func newNodeCommand(vp *viper.Viper) *cobra.Command { Aliases: []string{"node"}, Short: "List Hubble nodes", RunE: func(cmd *cobra.Command, _ []string) error { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := cmd.Context() hubbleConn, err := conn.New(ctx, vp.GetString(config.KeyServer), vp.GetDuration(config.KeyTimeout)) if err != nil { return err } defer hubbleConn.Close() + return runListNodes(ctx, cmd, hubbleConn) }, } diff --git a/cmd/observe_help.txt b/cmd/observe_help.txt index 55da75d8e..ac6d7e2e1 100644 --- a/cmd/observe_help.txt +++ b/cmd/observe_help.txt @@ -133,6 +133,7 @@ Flow Format Flags: Server Flags: --basic-auth-password string Specify a password for basic auth --basic-auth-username string Specify a username for basic auth + --request-timeout duration Unary Request timeout. Only applies to non-streaming RPCs (ServerStatus, ListNodes, ListNamespaces). (default 12s) --server string Address of a Hubble server. Ignored when --input-file is provided. (default "localhost:4245") --timeout duration Hubble server dialing timeout (default 5s) --tls Specify that TLS must be used when establishing a connection to a Hubble server. diff --git a/cmd/status/status.go b/cmd/status/status.go index c6b8ee02f..151ff9b92 100644 --- a/cmd/status/status.go +++ b/cmd/status/status.go @@ -14,7 +14,6 @@ import ( "github.com/cilium/hubble/cmd/common/config" "github.com/cilium/hubble/cmd/common/conn" "github.com/cilium/hubble/cmd/common/template" - "github.com/cilium/hubble/pkg/defaults" "github.com/cilium/hubble/pkg/printer" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -35,14 +34,14 @@ func New(vp *viper.Viper) *cobra.Command { Long: `Display shows the status of the Hubble server. This is intended as a basic connectivity health check.`, RunE: func(cmd *cobra.Command, args []string) error { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := cmd.Context() hubbleConn, err := conn.New(ctx, vp.GetString(config.KeyServer), vp.GetDuration(config.KeyTimeout)) if err != nil { return err } defer hubbleConn.Close() - return runStatus(cmd.OutOrStdout(), hubbleConn) + + return runStatus(ctx, cmd.OutOrStdout(), hubbleConn) }, } @@ -74,9 +73,9 @@ connectivity health check.`, return statusCmd } -func runStatus(out io.Writer, conn *grpc.ClientConn) error { +func runStatus(ctx context.Context, out io.Writer, conn *grpc.ClientConn) error { // get the standard GRPC health check to see if the server is up - healthy, status, err := getHC(conn) + healthy, status, err := getHC(ctx, conn) if err != nil { return fmt.Errorf("failed getting status: %v", err) } @@ -88,7 +87,7 @@ func runStatus(out io.Writer, conn *grpc.ClientConn) error { } // if the server is up, lets try to get hubble specific status - ss, err := getStatus(conn) + ss, err := getStatus(ctx, conn) if err != nil { return fmt.Errorf("failed to get hubble server status: %v", err) } @@ -115,10 +114,7 @@ func runStatus(out io.Writer, conn *grpc.ClientConn) error { return p.Close() } -func getHC(conn *grpc.ClientConn) (healthy bool, status string, err error) { - ctx, cancel := context.WithTimeout(context.Background(), defaults.RequestTimeout) - defer cancel() - +func getHC(ctx context.Context, conn *grpc.ClientConn) (healthy bool, status string, err error) { req := &healthpb.HealthCheckRequest{Service: v1.ObserverServiceName} resp, err := healthpb.NewHealthClient(conn).Check(ctx, req) if err != nil { @@ -130,10 +126,7 @@ func getHC(conn *grpc.ClientConn) (healthy bool, status string, err error) { return true, "Ok", nil } -func getStatus(conn *grpc.ClientConn) (*observerpb.ServerStatusResponse, error) { - ctx, cancel := context.WithTimeout(context.Background(), defaults.RequestTimeout) - defer cancel() - +func getStatus(ctx context.Context, conn *grpc.ClientConn) (*observerpb.ServerStatusResponse, error) { req := &observerpb.ServerStatusRequest{} res, err := observerpb.NewObserverClient(conn).ServerStatus(ctx, req) if err != nil { diff --git a/go.mod b/go.mod index 5e864f339..e7b8ed9bf 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/cilium/cilium v1.15.0-pre.1.0.20231016085253-84f5b169c565 github.com/fatih/color v1.15.0 github.com/google/go-cmp v0.6.0 + github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1 github.com/spf13/cast v1.5.1 github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace diff --git a/go.sum b/go.sum index 3bdd1a3f6..bca7e48d8 100644 --- a/go.sum +++ b/go.sum @@ -280,6 +280,8 @@ github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1 h1:HcUWd006luQPljE73d5sk+/VgYPGUReEVz2y1/qylwY= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1/go.mod h1:w9Y7gY31krpLmrVU5ZPG9H7l9fZuRu5/3R3S3FMtVQ4= github.com/hashicorp/consul/api v1.25.1 h1:CqrdhYzc8XZuPnhIYZWH45toM0LB9ZeYr/gvpLVI3PE= github.com/hashicorp/consul/api v1.25.1/go.mod h1:iiLVwR/htV7mas/sy0O+XSuEnrdBUUydemjxcUrAt4g= github.com/hashicorp/consul/sdk v0.14.1 h1:ZiwE2bKb+zro68sWzZ1SgHF3kRMBZ94TwOCFRF4ylPs= diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT new file mode 100644 index 000000000..3b13627cd --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT @@ -0,0 +1,2 @@ +Copyright (c) The go-grpc-middleware Authors. +Licensed under the Apache License 2.0. diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/LICENSE b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/LICENSE new file mode 100644 index 000000000..b2b065037 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor 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, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/doc.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/doc.go new file mode 100644 index 000000000..4e0886800 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/doc.go @@ -0,0 +1,13 @@ +// Copyright (c) The go-grpc-middleware Authors. +// Licensed under the Apache License 2.0. + +/* +Package timeout is a middleware that responds with a timeout error after the given duration. + +`grpc_timeout` are interceptors that timeout for gRPC client calls. + +# Client Side Timeout Middleware + +Please see examples for simple examples of use. +*/ +package timeout diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/timeout.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/timeout.go new file mode 100644 index 000000000..a140424fb --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout/timeout.go @@ -0,0 +1,20 @@ +// Copyright (c) The go-grpc-middleware Authors. +// Licensed under the Apache License 2.0. + +package timeout + +import ( + "context" + "time" + + "google.golang.org/grpc" +) + +// UnaryClientInterceptor returns a new unary client interceptor that sets a timeout on the request context. +func UnaryClientInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + timedCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return invoker(timedCtx, method, req, reply, cc, opts...) + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7fbda5be2..549d2f84b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -324,6 +324,9 @@ github.com/google/gofuzz/bytesource # github.com/google/uuid v1.3.1 ## explicit github.com/google/uuid +# github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1 +## explicit; go 1.19 +github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout # github.com/hashicorp/consul/api v1.25.1 ## explicit; go 1.19 github.com/hashicorp/consul/api