gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/profiling/cmd/remote.go (about) 1 /* 2 * 3 * Copyright 2019 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package main 20 21 import ( 22 "context" 23 "encoding/gob" 24 "fmt" 25 "os" 26 "time" 27 28 grpc "gitee.com/ks-custle/core-gm/grpc" 29 ppb "gitee.com/ks-custle/core-gm/grpc/profiling/proto" 30 ) 31 32 func setEnabled(ctx context.Context, c ppb.ProfilingClient, enabled bool) error { 33 _, err := c.Enable(ctx, &ppb.EnableRequest{Enabled: enabled}) 34 if err != nil { 35 logger.Infof("error calling Enable: %v\n", err) 36 return err 37 } 38 39 logger.Infof("successfully set enabled = %v", enabled) 40 return nil 41 } 42 43 func retrieveSnapshot(ctx context.Context, c ppb.ProfilingClient, f string) error { 44 logger.Infof("getting stream stats") 45 resp, err := c.GetStreamStats(ctx, &ppb.GetStreamStatsRequest{}) 46 if err != nil { 47 logger.Errorf("error calling GetStreamStats: %v\n", err) 48 return err 49 } 50 s := &snapshot{StreamStats: resp.StreamStats} 51 52 logger.Infof("creating snapshot file %s", f) 53 file, err := os.Create(f) 54 if err != nil { 55 logger.Errorf("cannot create %s: %v", f, err) 56 return err 57 } 58 defer file.Close() 59 60 logger.Infof("encoding data and writing to snapshot file %s", f) 61 encoder := gob.NewEncoder(file) 62 err = encoder.Encode(s) 63 if err != nil { 64 logger.Infof("error encoding: %v", err) 65 return err 66 } 67 68 logger.Infof("successfully wrote profiling snapshot to %s", f) 69 return nil 70 } 71 72 func remoteCommand() error { 73 ctx := context.Background() 74 if *flagTimeout > 0 { 75 var cancel func() 76 ctx, cancel = context.WithTimeout(context.Background(), time.Duration(*flagTimeout)*time.Second) 77 defer cancel() 78 } 79 80 logger.Infof("dialing %s", *flagAddress) 81 cc, err := grpc.Dial(*flagAddress, grpc.WithInsecure()) 82 if err != nil { 83 logger.Errorf("cannot dial %s: %v", *flagAddress, err) 84 return err 85 } 86 defer cc.Close() 87 88 c := ppb.NewProfilingClient(cc) 89 90 if *flagEnableProfiling || *flagDisableProfiling { 91 return setEnabled(ctx, c, *flagEnableProfiling) 92 } else if *flagRetrieveSnapshot { 93 return retrieveSnapshot(ctx, c, *flagSnapshot) 94 } else { 95 return fmt.Errorf("what should I do with the remote target?") 96 } 97 }