blob: 0d9e2fb86ccbe880296620d97b60a447388db9a2 [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)
Neha Sharma19ca2bf2020-05-11 15:34:17 +0000260 iaMessageTypeStr, err = model.GetEnumString(iaHeader, "type", iaMessageType)
261 if err != nil {
262 return nil, err
263 }
Scott Bakera1e53fa2020-04-01 11:13:34 -0700264
265 toDeviceIdIntf, err := iaHeader.TryGetFieldByName("to_device_id")
266 if err != nil {
267 return nil, err
268 }
269 toDeviceId = toDeviceIdIntf.(string)
270
271 proxyDeviceIdIntf, err := iaHeader.TryGetFieldByName("proxy_device_id")
272 if err != nil {
273 return nil, err
274 }
275 proxyDeviceId = proxyDeviceIdIntf.(string)
276 }
277 }
278 }
279 }
Neha Sharma19ca2bf2020-05-11 15:34:17 +0000280 messageHeaderType, err := model.GetEnumString(header, "type", msgType)
281 if err != nil {
282 return nil, err
283 }
Scott Bakera1e53fa2020-04-01 11:13:34 -0700284
285 icHeader := MessageHeader{Id: id,
Neha Sharma19ca2bf2020-05-11 15:34:17 +0000286 Type: messageHeaderType,
Scott Bakera1e53fa2020-04-01 11:13:34 -0700287 FromTopic: fromTopic,
288 ToTopic: toTopic,
289 KeyTopic: keyTopic,
290 Timestamp: timestamp,
291 InterAdapterType: iaMessageTypeStr,
292 ProxyDeviceId: proxyDeviceId,
293 ToDeviceId: toDeviceId,
294 }
295
296 return &icHeader, nil
297}
298
299// Print the full message, either in JSON or in GRPCURL-human-readable format,
300// depending on which grpcurl formatter is passed in.
301func PrintInterContainerMessage(f grpcurl.Formatter, md *desc.MessageDescriptor, b []byte) error {
302 m := dynamic.NewMessage(md)
303 err := m.Unmarshal(b)
304 if err != nil {
305 return err
306 }
307 s, err := f(m)
308 if err != nil {
309 return err
310 }
311 fmt.Println(s)
312 return nil
313}
314
315// Print just the enriched InterContainerHeader. This is either in JSON format, or in
316// table format.
317func PrintInterContainerHeader(outputAs string, outputFormat string, hdr *MessageHeader) error {
318 if outputAs == "json" {
319 asJson, err := json.Marshal(hdr)
320 if err != nil {
321 return fmt.Errorf("Error marshalling JSON: %v", err)
322 } else {
323 fmt.Printf("%s\n", asJson)
324 }
325 } else {
326 f := format.Format(outputFormat)
327 output, err := f.ExecuteFixedWidth(DefaultMessageWidths, false, *hdr)
328 if err != nil {
329 return err
330 }
331 fmt.Printf("%s\n", output)
332 }
333 return nil
334}
335
336// Get the FileDescriptor that has the InterContainer protos
337func GetInterContainerDescriptorFile() (*desc.FileDescriptor, error) {
338 descriptor, err := GetDescriptorSource()
339 if err != nil {
340 return nil, err
341 }
342
343 // get the symbol for voltha.InterContainerMessage
344 iaSymbol, err := descriptor.FindSymbol("voltha.InterContainerMessage")
345 if err != nil {
346 return nil, err
347 }
348
349 icFile := iaSymbol.GetFile()
350 return icFile, nil
351}
352
353// Start output, print any column headers or other start characters
354func (options *MessageListenOpts) StartOutput(outputFormat string) error {
355 if options.OutputAs == "json" {
356 fmt.Println("[")
357 } else if (options.OutputAs == "table") && !options.ShowBody {
358 f := format.Format(outputFormat)
359 output, err := f.ExecuteFixedWidth(DefaultMessageWidths, true, nil)
360 if err != nil {
361 return err
362 }
363 fmt.Println(output)
364 }
365 return nil
366}
367
368// Finish output, print any column footers or other end characters
369func (options *MessageListenOpts) FinishOutput() {
370 if options.OutputAs == "json" {
371 fmt.Println("]")
372 }
373}
374
375func (options *MessageListenOpts) Execute(args []string) error {
376 ProcessGlobalOptions()
377 if GlobalConfig.Kafka == "" {
378 return errors.New("Kafka address is not specified")
379 }
380
381 icFile, err := GetInterContainerDescriptorFile()
382 if err != nil {
383 return err
384 }
385
386 icMessage := icFile.FindMessage("voltha.InterContainerMessage")
387
388 config := sarama.NewConfig()
389 config.ClientID = "go-kafka-consumer"
390 config.Consumer.Return.Errors = true
391 config.Version = sarama.V1_0_0_0
392 brokers := []string{GlobalConfig.Kafka}
393
394 client, err := sarama.NewClient(brokers, config)
395 if err != nil {
396 return err
397 }
398
399 defer func() {
400 if err := client.Close(); err != nil {
401 panic(err)
402 }
403 }()
404
405 consumer, consumerErrors, highwaterMarks, err := startInterContainerConsumer([]string{options.Args.Topic}, client)
406 if err != nil {
407 return err
408 }
409
410 highwater := highwaterMarks[options.Args.Topic]
411
412 signals := make(chan os.Signal, 1)
413 signal.Notify(signals, os.Interrupt)
414
415 // Count how many message processed
416 consumeCount := 0
417
418 // Count how many messages were printed
419 count := 0
420
421 var grpcurlFormatter grpcurl.Formatter
422 // need a descriptor source, any method will do
423 descriptor, _, err := GetMethod("device-list")
424 if err != nil {
425 return err
426 }
427
428 jsonFormatter := grpcurl.NewJSONFormatter(false, grpcurl.AnyResolverFromDescriptorSource(descriptor))
429 if options.ShowBody {
430 if options.OutputAs == "json" {
431 grpcurlFormatter = jsonFormatter
432 } else {
433 grpcurlFormatter = grpcurl.NewTextFormatter(false)
434 }
435 }
436
437 var headerFilter *filter.Filter
438 if options.Filter != "" {
439 headerFilterVal, err := filter.Parse(options.Filter)
440 if err != nil {
441 return fmt.Errorf("Failed to parse filter: %v", err)
442 }
443 headerFilter = &headerFilterVal
444 }
445
446 outputFormat := CharReplacer.Replace(options.Format)
447 if outputFormat == "" {
448 outputFormat = GetCommandOptionWithDefault("intercontainer-listen", "format", DEFAULT_MESSAGE_FORMAT)
449 }
450
451 err = options.StartOutput(outputFormat)
452 if err != nil {
453 return err
454 }
455
456 var since *time.Time
457 if options.Since != "" {
458 since, err = ParseSince(options.Since)
459 if err != nil {
460 return err
461 }
462 }
463
464 // Get signnal for finish
465 doneCh := make(chan struct{})
466 go func() {
467 tStart := time.Now()
468 Loop:
469 for {
470 // Initialize the idle timeout timer
471 timeoutTimer := time.NewTimer(time.Duration(options.Timeout) * time.Second)
472 select {
473 case msg := <-consumer:
474 consumeCount++
475 hdr, err := DecodeInterContainerHeader(icFile, icMessage, msg.Value, msg.Timestamp, jsonFormatter)
476 if err != nil {
477 log.Printf("Error decoding header %v\n", err)
478 continue
479 }
480 if headerFilter != nil && !headerFilter.Evaluate(*hdr) {
481 // skip printing message
482 } else if since != nil && hdr.Timestamp.Before(*since) {
483 // it's too old
484 } else {
485 // comma separated between this message and predecessor
486 if count > 0 {
487 if options.OutputAs == "json" {
488 fmt.Println(",")
489 }
490 }
491
492 // Print it
493 if options.ShowBody {
494 if err := PrintInterContainerMessage(grpcurlFormatter, icMessage, msg.Value); err != nil {
495 log.Printf("%v\n", err)
496 }
497 } else {
498 if err := PrintInterContainerHeader(options.OutputAs, outputFormat, hdr); err != nil {
499 log.Printf("%v\n", err)
500 }
501 }
502
503 // Check to see if we've hit the "count" threshold the user specified
504 count++
505 if (options.Count > 0) && (count >= options.Count) {
506 log.Println("Count reached")
507 doneCh <- struct{}{}
508 break Loop
509 }
510
511 // Check to see if we've hit the "now" threshold the user specified
512 if (options.Now) && (!hdr.Timestamp.Before(tStart)) {
513 log.Println("Now timestamp reached")
514 doneCh <- struct{}{}
515 break Loop
516 }
517 }
518
519 // If we're not in follow mode, see if we hit the highwater mark
520 if !options.Follow && !options.Now && (msg.Offset >= highwater) {
521 log.Println("High water reached")
522 doneCh <- struct{}{}
523 break Loop
524 }
525
526 // Reset the timeout timer
527 if !timeoutTimer.Stop() {
528 <-timeoutTimer.C
529 }
530 case consumerError := <-consumerErrors:
531 log.Printf("Received consumerError topic=%v, partition=%v, err=%v\n", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err)
532 doneCh <- struct{}{}
533 case <-signals:
534 doneCh <- struct{}{}
535 case <-timeoutTimer.C:
536 log.Printf("Idle timeout\n")
537 doneCh <- struct{}{}
538 }
539 }
540 }()
541
542 <-doneCh
543
544 options.FinishOutput()
545
546 log.Printf("Consumed %d messages. Printed %d messages", consumeCount, count)
547
548 return nil
549}
550
551// Consume message from Sarama and send them out on a channel.
552// Supports multiple topics.
553// Taken from Sarama example consumer.
554func startInterContainerConsumer(topics []string, client sarama.Client) (chan *sarama.ConsumerMessage, chan *sarama.ConsumerError, map[string]int64, error) {
555 master, err := sarama.NewConsumerFromClient(client)
556 if err != nil {
557 return nil, nil, nil, err
558 }
559
560 consumers := make(chan *sarama.ConsumerMessage)
561 errors := make(chan *sarama.ConsumerError)
562 highwater := make(map[string]int64)
563 for _, topic := range topics {
564 if strings.Contains(topic, "__consumer_offsets") {
565 continue
566 }
567 partitions, _ := master.Partitions(topic)
568
569 // TODO: Add support for multiple partitions
570 if len(partitions) > 1 {
571 log.Printf("WARNING: %d partitions on topic %s but we only listen to the first one\n", len(partitions), topic)
572 }
573
574 hw, err := client.GetOffset("openolt", partitions[0], sarama.OffsetNewest)
575 if err != nil {
576 return nil, nil, nil, fmt.Errorf("Error in consume() getting highwater: Topic %v Partitions: %v", topic, partitions)
577 }
578 highwater[topic] = hw
579
580 consumer, err := master.ConsumePartition(topic, partitions[0], sarama.OffsetOldest)
581 if nil != err {
582 return nil, nil, nil, fmt.Errorf("Error in consume(): Topic %v Partitions: %v", topic, partitions)
583 }
584 log.Println(" Start consuming topic ", topic)
585 go func(topic string, consumer sarama.PartitionConsumer) {
586 for {
587 select {
588 case consumerError := <-consumer.Errors():
589 errors <- consumerError
590
591 case msg := <-consumer.Messages():
592 consumers <- msg
593 }
594 }
595 }(topic, consumer)
596 }
597
598 return consumers, errors, highwater, nil
599}