How to use walkFileDescriptors method of grpc Package

Best K6 code snippet using grpc.walkFileDescriptors

client.go

Source:client.go Github

copy

Full Screen

...56 }57 fdset := &descriptorpb.FileDescriptorSet{}58 seen := make(map[string]struct{})59 for _, fd := range fds {60 fdset.File = append(fdset.File, walkFileDescriptors(seen, fd)...)61 }62 return c.convertToMethodInfo(fdset)63}64// Connect is a block dial to the gRPC server at the given address (host:port)65func (c *Client) Connect(addr string, params map[string]interface{}) (bool, error) {66 state := c.vu.State()67 if state == nil {68 return false, common.NewInitContextError("connecting to a gRPC server in the init context is not supported")69 }70 p, err := c.parseConnectParams(params)71 if err != nil {72 return false, err73 }74 opts := grpcext.DefaultOptions(c.vu)75 var tcred credentials.TransportCredentials76 if !p.IsPlaintext {77 tlsCfg := state.TLSConfig.Clone()78 tlsCfg.NextProtos = []string{"h2"}79 // TODO(rogchap): Would be good to add support for custom RootCAs (self signed)80 tcred = credentials.NewTLS(tlsCfg)81 } else {82 tcred = insecure.NewCredentials()83 }84 opts = append(opts, grpc.WithTransportCredentials(tcred))85 if ua := state.Options.UserAgent; ua.Valid {86 opts = append(opts, grpc.WithUserAgent(ua.ValueOrZero()))87 }88 ctx, cancel := context.WithTimeout(c.vu.Context(), p.Timeout)89 defer cancel()90 c.addr = addr91 c.conn, err = grpcext.Dial(ctx, addr, opts...)92 if err != nil {93 return false, err94 }95 if !p.UseReflectionProtocol {96 return true, nil97 }98 fdset, err := c.conn.Reflect(ctx)99 if err != nil {100 return false, err101 }102 _, err = c.convertToMethodInfo(fdset)103 if err != nil {104 return false, fmt.Errorf("can't convert method info: %w", err)105 }106 return true, err107}108// Invoke creates and calls a unary RPC by fully qualified method name109func (c *Client) Invoke(110 method string,111 req goja.Value,112 params map[string]interface{},113) (*grpcext.Response, error) {114 state := c.vu.State()115 if state == nil {116 return nil, common.NewInitContextError("invoking RPC methods in the init context is not supported")117 }118 if c.conn == nil {119 return nil, errors.New("no gRPC connection, you must call connect first")120 }121 if method == "" {122 return nil, errors.New("method to invoke cannot be empty")123 }124 if method[0] != '/' {125 method = "/" + method126 }127 methodDesc := c.mds[method]128 if methodDesc == nil {129 return nil, fmt.Errorf("method %q not found in file descriptors", method)130 }131 p, err := c.parseParams(params)132 if err != nil {133 return nil, err134 }135 b, err := req.ToObject(c.vu.Runtime()).MarshalJSON()136 if err != nil {137 return nil, fmt.Errorf("unable to serialise request object: %w", err)138 }139 md := metadata.New(nil)140 for param, strval := range p.Metadata {141 md.Append(param, strval)142 }143 ctx, cancel := context.WithTimeout(c.vu.Context(), p.Timeout)144 defer cancel()145 tags := state.CloneTags()146 for k, v := range p.Tags {147 tags[k] = v148 }149 if state.Options.SystemTags.Has(metrics.TagURL) {150 tags["url"] = fmt.Sprintf("%s%s", c.addr, method)151 }152 parts := strings.Split(method[1:], "/")153 if state.Options.SystemTags.Has(metrics.TagService) {154 tags["service"] = parts[0]155 }156 if state.Options.SystemTags.Has(metrics.TagMethod) {157 tags["method"] = parts[1]158 }159 // Only set the name system tag if the user didn't explicitly set it beforehand160 if _, ok := tags["name"]; !ok && state.Options.SystemTags.Has(metrics.TagName) {161 tags["name"] = method162 }163 reqmsg := grpcext.Request{164 MethodDescriptor: methodDesc,165 Message: b,166 Tags: tags,167 }168 return c.conn.Invoke(ctx, method, md, reqmsg)169}170// Close will close the client gRPC connection171func (c *Client) Close() error {172 if c.conn == nil {173 return nil174 }175 err := c.conn.Close()176 c.conn = nil177 return err178}179// MethodInfo holds information on any parsed method descriptors that can be used by the goja VM180type MethodInfo struct {181 Package string182 Service string183 FullMethod string184 grpc.MethodInfo `json:"-" js:"-"`185}186func (c *Client) convertToMethodInfo(fdset *descriptorpb.FileDescriptorSet) ([]MethodInfo, error) {187 files, err := protodesc.NewFiles(fdset)188 if err != nil {189 return nil, err190 }191 var rtn []MethodInfo192 if c.mds == nil {193 // This allows us to call load() multiple times, without overwriting the194 // previously loaded definitions.195 c.mds = make(map[string]protoreflect.MethodDescriptor)196 }197 appendMethodInfo := func(198 fd protoreflect.FileDescriptor,199 sd protoreflect.ServiceDescriptor,200 md protoreflect.MethodDescriptor,201 ) {202 name := fmt.Sprintf("/%s/%s", sd.FullName(), md.Name())203 c.mds[name] = md204 rtn = append(rtn, MethodInfo{205 MethodInfo: grpc.MethodInfo{206 Name: string(md.Name()),207 IsClientStream: md.IsStreamingClient(),208 IsServerStream: md.IsStreamingServer(),209 },210 Package: string(fd.Package()),211 Service: string(sd.Name()),212 FullMethod: name,213 })214 }215 files.RangeFiles(func(fd protoreflect.FileDescriptor) bool {216 sds := fd.Services()217 for i := 0; i < sds.Len(); i++ {218 sd := sds.Get(i)219 mds := sd.Methods()220 for j := 0; j < mds.Len(); j++ {221 md := mds.Get(j)222 appendMethodInfo(fd, sd, md)223 }224 }225 return true226 })227 return rtn, nil228}229type params struct {230 Metadata map[string]string231 Tags map[string]string232 Timeout time.Duration233}234func (c *Client) parseParams(raw map[string]interface{}) (params, error) {235 p := params{236 Timeout: 1 * time.Minute,237 }238 for k, v := range raw {239 switch k {240 case "headers":241 c.vu.State().Logger.Warn("The headers property is deprecated, replace it with the metadata property, please.")242 fallthrough243 case "metadata":244 p.Metadata = make(map[string]string)245 rawHeaders, ok := v.(map[string]interface{})246 if !ok {247 return p, errors.New("metadata must be an object with key-value pairs")248 }249 for hk, kv := range rawHeaders {250 // TODO(rogchap): Should we manage a string slice?251 strval, ok := kv.(string)252 if !ok {253 return p, fmt.Errorf("metadata %q value must be a string", hk)254 }255 p.Metadata[hk] = strval256 }257 case "tags":258 p.Tags = make(map[string]string)259 rawTags, ok := v.(map[string]interface{})260 if !ok {261 return p, errors.New("tags must be an object with key-value pairs")262 }263 for tk, tv := range rawTags {264 strVal, ok := tv.(string)265 if !ok {266 return p, fmt.Errorf("tag %q value must be a string", tk)267 }268 p.Tags[tk] = strVal269 }270 case "timeout":271 var err error272 p.Timeout, err = types.GetDurationValue(v)273 if err != nil {274 return p, fmt.Errorf("invalid timeout value: %w", err)275 }276 default:277 return p, fmt.Errorf("unknown param: %q", k)278 }279 }280 return p, nil281}282type connectParams struct {283 IsPlaintext bool284 UseReflectionProtocol bool285 Timeout time.Duration286}287func (c *Client) parseConnectParams(raw map[string]interface{}) (connectParams, error) {288 params := connectParams{289 IsPlaintext: false,290 UseReflectionProtocol: false,291 Timeout: time.Minute,292 }293 for k, v := range raw {294 switch k {295 case "plaintext":296 var ok bool297 params.IsPlaintext, ok = v.(bool)298 if !ok {299 return params, fmt.Errorf("invalid plaintext value: '%#v', it needs to be boolean", v)300 }301 case "timeout":302 var err error303 params.Timeout, err = types.GetDurationValue(v)304 if err != nil {305 return params, fmt.Errorf("invalid timeout value: %w", err)306 }307 case "reflect":308 var ok bool309 params.UseReflectionProtocol, ok = v.(bool)310 if !ok {311 return params, fmt.Errorf("invalid reflect value: '%#v', it needs to be boolean", v)312 }313 default:314 return params, fmt.Errorf("unknown connect param: %q", k)315 }316 }317 return params, nil318}319func walkFileDescriptors(seen map[string]struct{}, fd *desc.FileDescriptor) []*descriptorpb.FileDescriptorProto {320 fds := []*descriptorpb.FileDescriptorProto{}321 if _, ok := seen[fd.GetName()]; ok {322 return fds323 }324 seen[fd.GetName()] = struct{}{}325 fds = append(fds, fd.AsFileDescriptorProto())326 for _, dep := range fd.GetDependencies() {327 deps := walkFileDescriptors(seen, dep)328 fds = append(fds, deps...)329 }330 return fds331}...

Full Screen

Full Screen

proto.go

Source:proto.go Github

copy

Full Screen

...29 fd, err := client.FileContainingSymbol(srv)30 if err != nil {31 return nil, err32 }33 fdset.File = append(fdset.File, walkFileDescriptors(seen, fd)...)34 }35 return protodesc.NewFiles(fdset)36}37func protoFilesFromDisk(importPaths, filenames []string) (*protoregistry.Files, error) {38 if len(filenames) == 0 {39 return nil, errors.New("app: no *.proto files found")40 }41 f, err := protoparse.ResolveFilenames(importPaths, filenames...)42 if err != nil {43 return nil, err44 }45 parser := protoparse.Parser{46 ImportPaths: importPaths,47 InferImportPaths: len(importPaths) == 0,48 }49 fds, err := parser.ParseFiles(f...)50 if err != nil {51 return nil, err52 }53 fdset := &descriptorpb.FileDescriptorSet{}54 seen := make(map[string]struct{})55 for _, fd := range fds {56 fdset.File = append(fdset.File, walkFileDescriptors(seen, fd)...)57 }58 return protodesc.NewFiles(fdset)59}60func walkFileDescriptors(seen map[string]struct{}, fd *desc.FileDescriptor) []*descriptorpb.FileDescriptorProto {61 fds := []*descriptorpb.FileDescriptorProto{}62 if _, ok := seen[fd.GetName()]; ok {63 return fds64 }65 seen[fd.GetName()] = struct{}{}66 fds = append(fds, fd.AsFileDescriptorProto())67 for _, dep := range fd.GetDependencies() {68 deps := walkFileDescriptors(seen, dep)69 fds = append(fds, deps...)70 }71 return fds72}...

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2type server struct{}3func (s *server) Check(ctx context.Context, in *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {4 return &grpc_health_v1.HealthCheckResponse{Status: grpc_health_v1.HealthCheckResponse_SERVING}, nil5}6func (s *server) Watch(in *grpc_health_v1.HealthCheckRequest, stream grpc_health_v1.Health_WatchServer) error {7}8func main() {9 lis, err := net.Listen("tcp", ":50051")10 if err != nil {11 grpclog.Fatalf("failed to listen: %v", err)12 }13 s := grpc.NewServer()14 grpc_health_v1.RegisterHealthServer(s, &server{})15 reflection.Register(s)16 if err := s.Serve(lis); err != nil {17 grpclog.Fatalf("failed to serve: %v", err)18 }19}20import (21type server struct{}22func (s *server) Check(ctx context.Context, in *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {23 return &grpc_health_v1.HealthCheckResponse{Status: grpc_health_v1.HealthCheckResponse_SERVING}, nil24}25func (s *server) Watch(in *grpc_health_v1.HealthCheckRequest, stream grpc_health_v1.Health_WatchServer) error {26}27func main() {28 lis, err := net.Listen("tcp", ":50051")29 if err != nil {30 grpclog.Fatalf("failed to listen: %v", err)31 }32 s := grpc.NewServer()33 grpc_health_v1.RegisterHealthServer(s, &server{})34 reflection.Register(s)

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())4 if err != nil {5 log.Fatalf("did not connect: %v", err)6 }7 defer conn.Close()8 fds, err := walkFileDescriptors(conn)9 if err != nil {10 log.Fatalf("walkFileDescriptors failed: %v", err)11 }12 for _, fd := range fds {13 fmt.Println(fd)14 }15}16func walkFileDescriptors(conn *grpc.ClientConn) ([]uintptr, error) {17 c, ok := conn.(*grpc.ClientConn)18 if !ok {19 return nil, fmt.Errorf("failed to get underlying connection")20 }21 cc, ok := c.Conn.(*grpc.ClientConn)22 if !ok {23 return nil, fmt.Errorf("failed to get underlying connection")24 }25 fd := int(cc.GetState().Conn.(*net.TCPConn).Fd())26 fds, err := walk(fd)27 if err != nil {28 }29}30func walk(fd int) ([]uintptr, error) {31 fi, err := os.NewFile(uintptr(fd), "").Stat()32 if err != nil {33 }34 if fi.Mode()&os.ModeSocket != 0 {35 return []uintptr{uintptr(fd)}, nil36 }37 if fi.Mode().IsDir() {38 f, err := os.Open(fmt.Sprintf("/proc/self/fd/%d", fd))39 if err != nil {40 }41 defer f.Close()42 names, err := f.Readdirnames(-1)43 if err != nil {44 }45 for _, name := range names {46 fd, err := strconv.Atoi(name)47 if err != nil {48 }49 fds, err = walk(fd)50 if err != nil {51 }52 }

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2type server struct{}3func (s *server) WalkFileDescriptors(req *WalkFileDescriptorsRequest, stream WalkFileDescriptors_WalkFileDescriptorsServer) error {4 fmt.Println("WalkFileDescriptors was invoked with %v\n", req)5}6func main() {7 fmt.Println("Hello World")8 lis, err := net.Listen("tcp", "

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())4 if err != nil {5 log.Fatalf("did not connect: %v", err)6 }7 defer conn.Close()8 c := pb.NewGreeterClient(conn)9 if len(os.Args) > 1 {10 }11 ctx, cancel := context.WithTimeout(context.Background(), time.Second)12 defer cancel()13 r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})14 if err != nil {15 log.Fatalf("could not greet: %v", err)16 }17 log.Printf("Greeting: %s", r.Message)18}19import (20func main() {21 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())22 if err != nil {23 log.Fatalf("did not connect: %v", err)24 }25 defer conn.Close()26 c := pb.NewGreeterClient(conn)27 if len(os.Args) > 1 {28 }29 ctx, cancel := context.WithTimeout(context.Background(), time.Second)30 defer cancel()31 r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})32 if err != nil {33 log.Fatalf("could not greet: %v", err)34 }35 log.Printf("Greeting: %s", r.Message)36}

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1func main() {2 opts = append(opts, grpc.MaxConcurrentStreams(1000000))3 opts = append(opts, grpc.MaxMsgSize(1024*1024*1024))4 opts = append(opts, grpc.InitialWindowSize(1024*1024*1024))5 opts = append(opts, grpc.InitialConnWindowSize(1024*1024*1024))6 opts = append(opts, grpc.WriteBufferSize(1024*1024*1024))7 opts = append(opts, grpc.ReadBufferSize(1024*1024*1024))8 s := grpc.NewServer(opts...)9 reflection.Register(s)10 if err := s.Serve(lis); err != nil {11 log.Fatalf("failed to serve: %v", err)12 }13}14func main() {15 opts = append(opts, grpc.MaxConcurrentStreams(1000000))16 opts = append(opts, grpc.MaxMsgSize(1024*1024*1024))17 opts = append(opts, grpc.InitialWindowSize(1024*1024*1024))18 opts = append(opts, grpc.InitialConnWindowSize(1024*1024*1024))19 opts = append(opts, grpc.WriteBufferSize(1024*1024*1024))20 opts = append(opts, grpc.ReadBufferSize(1024*1024*1024))21 s := grpc.NewServer(opts...)22 reflection.Register(s)23 if err := s.Serve(lis); err != nil {24 log.Fatalf("failed to serve: %v", err)25 }26}27func main() {28 opts = append(opts, grpc.MaxConcurrentStreams(1000000))29 opts = append(opts, grpc.MaxMsgSize(1024*1024

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 pid := syscall.Getpid()4 fmt.Println("Pid of the process: ", pid)5 profile := pprof.Lookup("goroutine")6 profile.WriteTo(os.Stdout, 1)7}

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1func (s *Server) walkFileDescriptors() []string {2 grpc.WalkFileDescriptors(func(fd uintptr) bool {3 fds = append(fds, fmt.Sprintf("%d", fd))4 })5}6func (s *Server) walkFileDescriptors() []string {7 grpc.WalkFileDescriptors(func(fd uintptr) bool {8 fds = append(fds, fmt.Sprintf("%d", fd))9 })10}11func (s *Server) walkFileDescriptors() []string {12 grpc.WalkFileDescriptors(func(fd uintptr) bool {13 fds = append(fds, fmt.Sprintf("%d", fd))14 })15}16func (s *Server) walkFileDescriptors() []string {17 grpc.WalkFileDescriptors(func(fd uintptr) bool {18 fds = append(fds, fmt.Sprintf("%d", fd))19 })20}21func (s *Server) walkFileDescriptors() []string {22 grpc.WalkFileDescriptors(func(fd uintptr) bool {23 fds = append(fds, fmt.Sprintf("%d", fd))24 })25}26func (s *Server) walkFileDescriptors() []string {27 grpc.WalkFileDescriptors(func(fd uintptr) bool {28 fds = append(fds, fmt.Sprintf("%d", fd))29 })30}

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) != 2 {4 fmt.Println("Usage: %s <socket path>", os.Args[0])5 os.Exit(1)6 }7 conn, err := grpc.Dial(os.Args[1], grpc.WithInsecure())8 if err != nil {9 fmt.Println("Error creating connection: %v", err)10 os.Exit(1)11 }12 defer conn.Close()13 fds, err := grpc.FD(conn)14 if err != nil {15 fmt.Println("Error getting file descriptors: %v", err)16 os.Exit(1)17 }18 fmt.Println("File descriptors:")19 for _, fd := range fds {20 fmt.Printf("\t%v\n", fd.Name())21 }22}

Full Screen

Full Screen

walkFileDescriptors

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 lis, err := net.Listen("tcp", "localhost:50051")4 if err != nil {5 grpclog.Fatalf("failed to listen: %v", err)6 }7 s := grpc.NewServer()8 RegisterHelloWorldServer(s, &server{})9 walkFileDescriptors(s)10 if err := s.Serve(lis); err != nil {11 grpclog.Fatalf("failed to serve: %v", err)12 }13}14func walkFileDescriptors(s *grpc.Server) {15 t := s.GetTransport()16 fdset, err := t.FileDescriptorSet()17 if err != nil {18 log.Fatal(err)19 }20 fdsetString := proto.MarshalTextString(fdset)21 fmt.Println("File descriptor set string is: ", fdsetString)22 fdsetLength := len(fdsetString)23 fmt.Println("File descriptor set length is: ", fdsetLength)24 fdsetBytes := []byte(fdsetString)25 fmt.Println("File descriptor set bytes are: ", fdsetBytes)26 fmt.Println("File descriptor set slice is: ", fdsetSlice)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful