Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019-present Ciena Corporation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package commands |
| 17 | |
| 18 | import ( |
Scott Baker | d69e422 | 2019-08-21 16:46:05 -0700 | [diff] [blame] | 19 | "fmt" |
Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 20 | "github.com/golang/protobuf/proto" |
| 21 | "github.com/jhump/protoreflect/desc" |
| 22 | "github.com/jhump/protoreflect/dynamic" |
| 23 | "google.golang.org/grpc/metadata" |
| 24 | "google.golang.org/grpc/status" |
| 25 | "io" |
| 26 | ) |
| 27 | |
| 28 | type RpcEventHandler struct { |
| 29 | Response proto.Message |
| 30 | Status *status.Status |
| 31 | Data []byte |
| 32 | Fields map[string]map[string]interface{} |
| 33 | } |
| 34 | |
| 35 | func (h *RpcEventHandler) OnResolveMethod(*desc.MethodDescriptor) { |
| 36 | } |
| 37 | |
| 38 | func (h *RpcEventHandler) OnSendHeaders(metadata.MD) { |
| 39 | } |
| 40 | |
| 41 | func (h *RpcEventHandler) OnReceiveHeaders(metadata.MD) { |
| 42 | } |
| 43 | |
| 44 | func (h *RpcEventHandler) OnReceiveResponse(m proto.Message) { |
| 45 | h.Response = m |
| 46 | } |
| 47 | |
| 48 | func (h *RpcEventHandler) OnReceiveTrailers(s *status.Status, m metadata.MD) { |
| 49 | h.Status = s |
| 50 | } |
| 51 | |
| 52 | func (h *RpcEventHandler) GetParams(msg proto.Message) error { |
| 53 | dmsg, err := dynamic.AsDynamicMessage(msg) |
| 54 | if err != nil { |
| 55 | return err |
| 56 | } |
| 57 | |
| 58 | if h.Fields == nil || len(h.Fields) == 0 { |
| 59 | return io.EOF |
| 60 | } |
| 61 | |
| 62 | fields, ok := h.Fields[dmsg.XXX_MessageName()] |
| 63 | if !ok { |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | for k, v := range fields { |
Scott Baker | d69e422 | 2019-08-21 16:46:05 -0700 | [diff] [blame] | 68 | err := dmsg.TrySetFieldByName(k, v) |
| 69 | if err != nil { |
| 70 | fmt.Printf("Failed to set field %s in proto %s, err %v\n", k, dmsg.XXX_MessageName(), err) |
| 71 | panic("GetParams failure") |
| 72 | } |
Zack Williams | e940c7a | 2019-08-21 14:25:39 -0700 | [diff] [blame] | 73 | } |
| 74 | delete(h.Fields, dmsg.XXX_MessageName()) |
| 75 | |
| 76 | return nil |
| 77 | } |