code.vegaprotocol.io/vega@v0.79.0/blockexplorer/api/grpc-ui.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package api 17 18 import ( 19 "context" 20 "fmt" 21 "net" 22 "net/http" 23 24 "code.vegaprotocol.io/vega/logging" 25 26 "github.com/fullstorydev/grpcui/standalone" 27 "google.golang.org/grpc" 28 "google.golang.org/grpc/credentials/insecure" 29 ) 30 31 type GRPCUIHandler struct { 32 GRPCUIConfig 33 handler http.Handler 34 log *logging.Logger 35 dialer grpcDialer 36 conn *grpc.ClientConn 37 } 38 39 type grpcDialer interface { 40 net.Listener 41 DialGRPC(context.Context, ...grpc.DialOption) (*grpc.ClientConn, error) 42 } 43 44 func NewGRPCUIHandler(log *logging.Logger, dialer grpcDialer, config GRPCUIConfig) *GRPCUIHandler { 45 log = log.Named(grpcUINamedLogger) 46 return &GRPCUIHandler{ 47 GRPCUIConfig: config, 48 log: log, 49 handler: NewNotStartedHandler("grpc-ui"), 50 dialer: dialer, 51 } 52 } 53 54 func (g *GRPCUIHandler) Name() string { 55 return "grpc-ui" 56 } 57 58 func (g *GRPCUIHandler) Start(ctx context.Context) error { 59 defaultCallOptions := []grpc.CallOption{ 60 grpc.MaxCallRecvMsgSize(int(g.MaxPayloadSize)), 61 } 62 63 dialOpts := []grpc.DialOption{ 64 grpc.WithDefaultCallOptions(defaultCallOptions...), 65 grpc.WithTransportCredentials(insecure.NewCredentials()), 66 grpc.WithBlock(), 67 } 68 conn, err := g.dialer.DialGRPC(ctx, dialOpts...) 69 if err != nil { 70 return fmt.Errorf("failed to create client to local grpc server: %w", err) 71 } 72 g.conn = conn 73 74 g.log.Info("Starting gRPC UI", logging.String("target", conn.Target())) 75 76 handler, err := standalone.HandlerViaReflection(ctx, conn, "vega data node") 77 if err != nil { 78 return fmt.Errorf("failed to create grpc-ui server:%w", err) 79 } 80 g.handler = handler 81 return nil 82 } 83 84 func (g *GRPCUIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 85 g.handler.ServeHTTP(w, r) 86 } 87 88 func (g *GRPCUIHandler) Stop() { 89 if g.conn != nil { 90 g.log.Info("Stopping gRPC UI", logging.String("target", g.conn.Target())) 91 _ = g.conn.Close() 92 } 93 }