blob: ab0146fdda0e82e23db7cb3532ee7e4bad1401dd [file] [log] [blame]
Scott Bakera1e53fa2020-04-01 11:13:34 -07001/*
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 */
16package commands
17
18import (
19 "encoding/json"
20 "errors"
21 "fmt"
22 "github.com/Shopify/sarama"
23 "github.com/fullstorydev/grpcurl"
24 "github.com/golang/protobuf/ptypes/any"
25 flags "github.com/jessevdk/go-flags"
26 "github.com/jhump/protoreflect/desc"
27 "github.com/jhump/protoreflect/dynamic"
28 "github.com/opencord/voltctl/pkg/filter"
29 "github.com/opencord/voltctl/pkg/format"
30 "github.com/opencord/voltctl/pkg/model"
31 "log"
32 "os"
33 "os/signal"
34 "strings"
35 "time"
36)
37
38/*
39 * The "message listen" command supports two types of output:
40 * 1) A summary output where a row is displayed for each message received. For the summary
41 * format, DEFAULT_MESSAGE_FORMAT contains the default list of columns that will be
42 * display and can be overridden at runtime.
43 * 2) A body output where the full grpcurl or json body is output for each message received.
44 *
45 * These two modes are switched by using the "-b" / "--body" flag.
46 *
47 * The summary mode has the potential to aggregate data together from multiple parts of the
48 * message. For example, it currently aggregates the InterAdapterHeader contents together with
49 * the InterContainerHeader contents.
50 *
51 * Similar to "event listen", the "message listen" command operates in a streaming mode, rather
52 * than collecting a list of results and then emitting them at program exit. This is done to
53 * facilitate options such as "-F" / "--follow" where the program is intended to operate
54 * continuously. This means that automatically calculating column widths is not practical, and
55 * a set of Fixed widths (MessageHeaderDefaultWidths) are predefined.
56 *
57 * As there are multiple kafka topics that can be listened to, specifying a topic is a
58 * mandatory positional argument for the `message listen` command. Common topics include:
59 * * openolt
60 * * brcm_openonu_adapter
61 * * rwcore
62 * * core-pair-1
63 */
64
65const (
66 DEFAULT_MESSAGE_FORMAT = "table{{.Id}}\t{{.Type}}\t{{.FromTopic}}\t{{.ToTopic}}\t{{.KeyTopic}}\t{{.InterAdapterType}}"
67)
68
69type MessageListenOpts struct {
70 Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
71 // nolint: staticcheck
72 OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
73 Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"`
74 Follow bool `short:"F" long:"follow" description:"Continue to consume until CTRL-C is pressed"`
75 ShowBody bool `short:"b" long:"show-body" description:"Show body of messages rather than only a header summary"`
76 Count int `short:"c" long:"count" default:"-1" value-name:"LIMIT" description:"Limit the count of messages that will be printed"`
77 Now bool `short:"n" long:"now" description:"Stop printing messages when current time is reached"`
78 Timeout int `short:"t" long:"idle" default:"900" value-name:"SECONDS" description:"Timeout if no message received within specified seconds"`
79 Since string `short:"s" long:"since" default:"" value-name:"TIMESTAMP" description:"Do not show entries before timestamp"`
80
81 Args struct {
82 Topic string
83 } `positional-args:"yes" required:"yes"`
84}
85
86type MessageOpts struct {
87 MessageListen MessageListenOpts `command:"listen"`
88}
89
90var interAdapterOpts = MessageOpts{}
91
92/* MessageHeader is a set of fields extracted
93 * from voltha.MessageHeader as well as useful other
94 * places such as InterAdapterHeader. These are fields that
95 * will be summarized in list mode and/or can be filtered
96 * on.
97 */
98type MessageHeader struct {
99 Id string `json:"id"`
100 Type string `json:"type"`
101 FromTopic string `json:"from_topic"`
102 ToTopic string `json:"to_topic"`
103 KeyTopic string `json:"key_topic"`
104 Timestamp time.Time `json:"timestamp"`
105 InterAdapterType string `json:"inter_adapter_type"` // interadapter header
106 ToDeviceId string `json:"to_device_id"` // interadapter header
107 ProxyDeviceId string `json:"proxy_device_id"` //interadapter header
108}
109
110/* Fixed widths because we output in a continuous streaming
111 * mode rather than a table-based dump at the end.
112 */
113type MessageHeaderWidths struct {
114 Id int
115 Type int
116 FromTopic int
117 ToTopic int
118 KeyTopic int
119 InterAdapterType int
120 ToDeviceId int
121 ProxyDeviceId int
122 Timestamp int
123}
124
125var DefaultMessageWidths MessageHeaderWidths = MessageHeaderWidths{
126 Id: 32,
127 Type: 10,
128 FromTopic: 16,
129 ToTopic: 16,
130 KeyTopic: 10,
131 Timestamp: 10,
132 InterAdapterType: 14,
133 ToDeviceId: 10,
134 ProxyDeviceId: 10,
135}
136
137func RegisterMessageCommands(parent *flags.Parser) {
138 if _, err := parent.AddCommand("message", "message commands", "Commands for observing messages between components", &interAdapterOpts); err != nil {
139 Error.Fatalf("Unable to register message commands with voltctl command parser: %s", err.Error())
140 }
141}
142
143// Find the any.Any field named by "fieldName" in the dynamic Message m.
144// Create a new dynamic message using the bytes from the Any
145// Return the new dynamic message and the type name
146func DeserializeAny(icFile *desc.FileDescriptor, m *dynamic.Message, fieldName string) (*dynamic.Message, string, error) {
147 f, err := m.TryGetFieldByName(fieldName)
148 if err != nil {
149 return nil, "", err
150 }
151 a := f.(*any.Any)
152 embeddedType := strings.SplitN(a.TypeUrl, "/", 2)[1] // example type.googleapis.com/voltha.InterContainerRequestBody
153 embeddedBytes := a.Value
154
155 md := icFile.FindMessage(embeddedType)
156
157 embeddedM := dynamic.NewMessage(md)
158 err = embeddedM.Unmarshal(embeddedBytes)
159 if err != nil {
160 return nil, "", err
161 }
162
163 return embeddedM, embeddedType, nil
164}
165
166// Extract the header, as well as a few other items that might be of interest
167func DecodeInterContainerHeader(icFile *desc.FileDescriptor, md *desc.MessageDescriptor, b []byte, ts time.Time, f grpcurl.Formatter) (*MessageHeader, error) {
168 m := dynamic.NewMessage(md)
169 if err := m.Unmarshal(b); err != nil {
170 return nil, err
171 }
172
173 headerIntf, err := m.TryGetFieldByName("header")
174 if err != nil {
175 return nil, err
176 }
177
178 header := headerIntf.(*dynamic.Message)
179
180 idIntf, err := header.TryGetFieldByName("id")
181 if err != nil {
182 return nil, err
183 }
184 id := idIntf.(string)
185
186 typeIntf, err := header.TryGetFieldByName("type")
187 if err != nil {
188 return nil, err
189 }
190 msgType := typeIntf.(int32)
191
192 fromTopicIntf, err := header.TryGetFieldByName("from_topic")
193 if err != nil {
194 return nil, err
195 }
196 fromTopic := fromTopicIntf.(string)
197
198 toTopicIntf, err := header.TryGetFieldByName("to_topic")
199 if err != nil {
200 return nil, err
201 }
202 toTopic := toTopicIntf.(string)
203
204 keyTopicIntf, err := header.TryGetFieldByName("key_topic")
205 if err != nil {
206 return nil, err
207 }
208 keyTopic := keyTopicIntf.(string)
209
210 timestampIntf, err := header.TryGetFieldByName("timestamp")
211 if err != nil {
212 return nil, err
213 }
214 timestamp, err := DecodeTimestamp(timestampIntf)
215 if err != nil {
216 return nil, err
217 }
218
219 // Pull some additional data out of the InterAdapterHeader, if it
220 // is embedded inside the InterContainerMessage
221
222 var iaMessageTypeStr string
223 var toDeviceId string
224 var proxyDeviceId string
225 body, bodyKind, err := DeserializeAny(icFile, m, "body")
226 if err != nil {
227 return nil, err
228 }
229 switch bodyKind {
230 case "voltha.InterContainerRequestBody":
231 argListIntf, err := body.TryGetFieldByName("args")
232 if err != nil {
233 return nil, err
234 }
235 argList := argListIntf.([]interface{})
236 for _, argIntf := range argList {
237 arg := argIntf.(*dynamic.Message)
238 keyIntf, err := arg.TryGetFieldByName("key")
239 if err != nil {
240 return nil, err
241 }
242 key := keyIntf.(string)
243 if key == "msg" {
244 argBody, argBodyKind, err := DeserializeAny(icFile, arg, "value")
245 if err != nil {
246 return nil, err
247 }
248 switch argBodyKind {
249 case "voltha.InterAdapterMessage":
250 iaHeaderIntf, err := argBody.TryGetFieldByName("header")
251 if err != nil {
252 return nil, err
253 }
254 iaHeader := iaHeaderIntf.(*dynamic.Message)
255 iaMessageTypeIntf, err := iaHeader.TryGetFieldByName("type")
256 if err != nil {
257 return nil, err
258 }
259 iaMessageType := iaMessageTypeIntf.(int32)
260 iaMessageTypeStr = model.GetEnumString(iaHeader, "type", iaMessageType)
261
262 toDeviceIdIntf, err := iaHeader.TryGetFieldByName("to_device_id")
263 if err != nil {
264 return nil, err
265 }
266 toDeviceId = toDeviceIdIntf.(string)
267
268 proxyDeviceIdIntf, err := iaHeader.TryGetFieldByName("proxy_device_id")
269 if err != nil {
270 return nil, err
271 }
272 proxyDeviceId = proxyDeviceIdIntf.(string)
273 }
274 }
275 }
276 }
277
278 icHeader := MessageHeader{Id: id,
279 Type: model.GetEnumString(header, "type", msgType),
280 FromTopic: fromTopic,
281 ToTopic: toTopic,
282 KeyTopic: keyTopic,
283 Timestamp: timestamp,
284 InterAdapterType: iaMessageTypeStr,
285 ProxyDeviceId: proxyDeviceId,
286 ToDeviceId: toDeviceId,
287 }
288
289 return &icHeader, nil
290}
291
292// Print the full message, either in JSON or in GRPCURL-human-readable format,
293// depending on which grpcurl formatter is passed in.
294func PrintInterContainerMessage(f grpcurl.Formatter, md *desc.MessageDescriptor, b []byte) error {
295 m := dynamic.NewMessage(md)
296 err := m.Unmarshal(b)
297 if err != nil {
298 return err
299 }
300 s, err := f(m)
301 if err != nil {
302 return err
303 }
304 fmt.Println(s)
305 return nil
306}
307
308// Print just the enriched InterContainerHeader. This is either in JSON format, or in
309// table format.
310func PrintInterContainerHeader(outputAs string, outputFormat string, hdr *MessageHeader) error {
311 if outputAs == "json" {
312 asJson, err := json.Marshal(hdr)
313 if err != nil {
314 return fmt.Errorf("Error marshalling JSON: %v", err)
315 } else {
316 fmt.Printf("%s\n", asJson)
317 }
318 } else {
319 f := format.Format(outputFormat)
320 output, err := f.ExecuteFixedWidth(DefaultMessageWidths, false, *hdr)
321 if err != nil {
322 return err
323 }
324 fmt.Printf("%s\n", output)
325 }
326 return nil
327}
328
329// Get the FileDescriptor that has the InterContainer protos
330func GetInterContainerDescriptorFile() (*desc.FileDescriptor, error) {
331 descriptor, err := GetDescriptorSource()
332 if err != nil {
333 return nil, err
334 }
335
336 // get the symbol for voltha.InterContainerMessage
337 iaSymbol, err := descriptor.FindSymbol("voltha.InterContainerMessage")
338 if err != nil {
339 return nil, err
340 }
341
342 icFile := iaSymbol.GetFile()
343 return icFile, nil
344}
345
346// Start output, print any column headers or other start characters
347func (options *MessageListenOpts) StartOutput(outputFormat string) error {
348 if options.OutputAs == "json" {
349 fmt.Println("[")
350 } else if (options.OutputAs == "table") && !options.ShowBody {
351 f := format.Format(outputFormat)
352 output, err := f.ExecuteFixedWidth(DefaultMessageWidths, true, nil)
353 if err != nil {
354 return err
355 }
356 fmt.Println(output)
357 }
358 return nil
359}
360
361// Finish output, print any column footers or other end characters
362func (options *MessageListenOpts) FinishOutput() {
363 if options.OutputAs == "json" {
364 fmt.Println("]")
365 }
366}
367
368func (options *MessageListenOpts) Execute(args []string) error {
369 ProcessGlobalOptions()
370 if GlobalConfig.Kafka == "" {
371 return errors.New("Kafka address is not specified")
372 }
373
374 icFile, err := GetInterContainerDescriptorFile()
375 if err != nil {
376 return err
377 }
378
379 icMessage := icFile.FindMessage("voltha.InterContainerMessage")
380
381 config := sarama.NewConfig()
382 config.ClientID = "go-kafka-consumer"
383 config.Consumer.Return.Errors = true
384 config.Version = sarama.V1_0_0_0
385 brokers := []string{GlobalConfig.Kafka}
386
387 client, err := sarama.NewClient(brokers, config)
388 if err != nil {
389 return err
390 }
391
392 defer func() {
393 if err := client.Close(); err != nil {
394 panic(err)
395 }
396 }()
397
398 consumer, consumerErrors, highwaterMarks, err := startInterContainerConsumer([]string{options.Args.Topic}, client)
399 if err != nil {
400 return err
401 }
402
403 highwater := highwaterMarks[options.Args.Topic]
404
405 signals := make(chan os.Signal, 1)
406 signal.Notify(signals, os.Interrupt)
407
408 // Count how many message processed
409 consumeCount := 0
410
411 // Count how many messages were printed
412 count := 0
413
414 var grpcurlFormatter grpcurl.Formatter
415 // need a descriptor source, any method will do
416 descriptor, _, err := GetMethod("device-list")
417 if err != nil {
418 return err
419 }
420
421 jsonFormatter := grpcurl.NewJSONFormatter(false, grpcurl.AnyResolverFromDescriptorSource(descriptor))
422 if options.ShowBody {
423 if options.OutputAs == "json" {
424 grpcurlFormatter = jsonFormatter
425 } else {
426 grpcurlFormatter = grpcurl.NewTextFormatter(false)
427 }
428 }
429
430 var headerFilter *filter.Filter
431 if options.Filter != "" {
432 headerFilterVal, err := filter.Parse(options.Filter)
433 if err != nil {
434 return fmt.Errorf("Failed to parse filter: %v", err)
435 }
436 headerFilter = &headerFilterVal
437 }
438
439 outputFormat := CharReplacer.Replace(options.Format)
440 if outputFormat == "" {
441 outputFormat = GetCommandOptionWithDefault("intercontainer-listen", "format", DEFAULT_MESSAGE_FORMAT)
442 }
443
444 err = options.StartOutput(outputFormat)
445 if err != nil {
446 return err
447 }
448
449 var since *time.Time
450 if options.Since != "" {
451 since, err = ParseSince(options.Since)
452 if err != nil {
453 return err
454 }
455 }
456
457 // Get signnal for finish
458 doneCh := make(chan struct{})
459 go func() {
460 tStart := time.Now()
461 Loop:
462 for {
463 // Initialize the idle timeout timer
464 timeoutTimer := time.NewTimer(time.Duration(options.Timeout) * time.Second)
465 select {
466 case msg := <-consumer:
467 consumeCount++
468 hdr, err := DecodeInterContainerHeader(icFile, icMessage, msg.Value, msg.Timestamp, jsonFormatter)
469 if err != nil {
470 log.Printf("Error decoding header %v\n", err)
471 continue
472 }
473 if headerFilter != nil && !headerFilter.Evaluate(*hdr) {
474 // skip printing message
475 } else if since != nil && hdr.Timestamp.Before(*since) {
476 // it's too old
477 } else {
478 // comma separated between this message and predecessor
479 if count > 0 {
480 if options.OutputAs == "json" {
481 fmt.Println(",")
482 }
483 }
484
485 // Print it
486 if options.ShowBody {
487 if err := PrintInterContainerMessage(grpcurlFormatter, icMessage, msg.Value); err != nil {
488 log.Printf("%v\n", err)
489 }
490 } else {
491 if err := PrintInterContainerHeader(options.OutputAs, outputFormat, hdr); err != nil {
492 log.Printf("%v\n", err)
493 }
494 }
495
496 // Check to see if we've hit the "count" threshold the user specified
497 count++
498 if (options.Count > 0) && (count >= options.Count) {
499 log.Println("Count reached")
500 doneCh <- struct{}{}
501 break Loop
502 }
503
504 // Check to see if we've hit the "now" threshold the user specified
505 if (options.Now) && (!hdr.Timestamp.Before(tStart)) {
506 log.Println("Now timestamp reached")
507 doneCh <- struct{}{}
508 break Loop
509 }
510 }
511
512 // If we're not in follow mode, see if we hit the highwater mark
513 if !options.Follow && !options.Now && (msg.Offset >= highwater) {
514 log.Println("High water reached")
515 doneCh <- struct{}{}
516 break Loop
517 }
518
519 // Reset the timeout timer
520 if !timeoutTimer.Stop() {
521 <-timeoutTimer.C
522 }
523 case consumerError := <-consumerErrors:
524 log.Printf("Received consumerError topic=%v, partition=%v, err=%v\n", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err)
525 doneCh <- struct{}{}
526 case <-signals:
527 doneCh <- struct{}{}
528 case <-timeoutTimer.C:
529 log.Printf("Idle timeout\n")
530 doneCh <- struct{}{}
531 }
532 }
533 }()
534
535 <-doneCh
536
537 options.FinishOutput()
538
539 log.Printf("Consumed %d messages. Printed %d messages", consumeCount, count)
540
541 return nil
542}
543
544// Consume message from Sarama and send them out on a channel.
545// Supports multiple topics.
546// Taken from Sarama example consumer.
547func startInterContainerConsumer(topics []string, client sarama.Client) (chan *sarama.ConsumerMessage, chan *sarama.ConsumerError, map[string]int64, error) {
548 master, err := sarama.NewConsumerFromClient(client)
549 if err != nil {
550 return nil, nil, nil, err
551 }
552
553 consumers := make(chan *sarama.ConsumerMessage)
554 errors := make(chan *sarama.ConsumerError)
555 highwater := make(map[string]int64)
556 for _, topic := range topics {
557 if strings.Contains(topic, "__consumer_offsets") {
558 continue
559 }
560 partitions, _ := master.Partitions(topic)
561
562 // TODO: Add support for multiple partitions
563 if len(partitions) > 1 {
564 log.Printf("WARNING: %d partitions on topic %s but we only listen to the first one\n", len(partitions), topic)
565 }
566
567 hw, err := client.GetOffset("openolt", partitions[0], sarama.OffsetNewest)
568 if err != nil {
569 return nil, nil, nil, fmt.Errorf("Error in consume() getting highwater: Topic %v Partitions: %v", topic, partitions)
570 }
571 highwater[topic] = hw
572
573 consumer, err := master.ConsumePartition(topic, partitions[0], sarama.OffsetOldest)
574 if nil != err {
575 return nil, nil, nil, fmt.Errorf("Error in consume(): Topic %v Partitions: %v", topic, partitions)
576 }
577 log.Println(" Start consuming topic ", topic)
578 go func(topic string, consumer sarama.PartitionConsumer) {
579 for {
580 select {
581 case consumerError := <-consumer.Errors():
582 errors <- consumerError
583
584 case msg := <-consumer.Messages():
585 consumers <- msg
586 }
587 }
588 }(topic, consumer)
589 }
590
591 return consumers, errors, highwater, nil
592}