Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [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 ( |
| 19 | "encoding/json" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "github.com/Shopify/sarama" |
| 23 | "github.com/fullstorydev/grpcurl" |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 24 | "github.com/golang/protobuf/ptypes" |
| 25 | "github.com/golang/protobuf/ptypes/timestamp" |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 26 | flags "github.com/jessevdk/go-flags" |
| 27 | "github.com/jhump/protoreflect/desc" |
| 28 | "github.com/jhump/protoreflect/dynamic" |
| 29 | "github.com/opencord/voltctl/pkg/filter" |
| 30 | "github.com/opencord/voltctl/pkg/format" |
| 31 | "github.com/opencord/voltctl/pkg/model" |
| 32 | "log" |
| 33 | "os" |
| 34 | "os/signal" |
| 35 | "strings" |
| 36 | "time" |
| 37 | ) |
| 38 | |
| 39 | const ( |
| 40 | DEFAULT_EVENT_FORMAT = "table{{.Category}}\t{{.SubCategory}}\t{{.Type}}\t{{.Timestamp}}\t{{.Device_ids}}\t{{.Titles}}" |
| 41 | ) |
| 42 | |
| 43 | type EventListenOpts struct { |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 44 | Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"` |
| 45 | // nolint: staticcheck |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 46 | OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"` |
| 47 | Filter string `short:"f" long:"filter" default:"" value-name:"FILTER" description:"Only display results that match filter"` |
| 48 | Follow bool `short:"F" long:"follow" description:"Continue to consume until CTRL-C is pressed"` |
| 49 | ShowBody bool `short:"b" long:"show-body" description:"Show body of events rather than only a header summary"` |
| 50 | Count int `short:"c" long:"count" default:"-1" value-name:"LIMIT" description:"Limit the count of messages that will be printed"` |
| 51 | Now bool `short:"n" long:"now" description:"Stop printing events when current time is reached"` |
| 52 | Timeout int `short:"t" long:"idle" default:"900" value-name:"SECONDS" description:"Timeout if no message received within specified seconds"` |
Scott Baker | f05e60a | 2020-02-02 21:53:57 -0800 | [diff] [blame] | 53 | Since string `short:"s" long:"since" default:"" value-name:"TIMESTAMP" description:"Do not show entries before timestamp"` |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 54 | } |
| 55 | |
| 56 | type EventOpts struct { |
| 57 | EventListen EventListenOpts `command:"listen"` |
| 58 | } |
| 59 | |
| 60 | var eventOpts = EventOpts{} |
| 61 | |
| 62 | type EventHeader struct { |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 63 | Category string `json:"category"` |
| 64 | SubCategory string `json:"sub_category"` |
| 65 | Type string `json:"type"` |
| 66 | Raised_ts time.Time `json:"raised_ts"` |
| 67 | Reported_ts time.Time `json:"reported_ts"` |
| 68 | Device_ids []string `json:"device_ids"` // Opportunistically collected list of device_ids |
| 69 | Titles []string `json:"titles"` // Opportunistically collected list of titles |
| 70 | Timestamp time.Time `json:"timestamp"` // Timestamp from Kafka |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 71 | } |
| 72 | |
| 73 | type EventHeaderWidths struct { |
| 74 | Category int |
| 75 | SubCategory int |
| 76 | Type int |
| 77 | Raised_ts int |
| 78 | Reported_ts int |
| 79 | Device_ids int |
| 80 | Titles int |
| 81 | Timestamp int |
| 82 | } |
| 83 | |
| 84 | var DefaultWidths EventHeaderWidths = EventHeaderWidths{ |
| 85 | Category: 13, |
| 86 | SubCategory: 3, |
| 87 | Type: 12, |
| 88 | Raised_ts: 10, |
| 89 | Reported_ts: 10, |
| 90 | Device_ids: 40, |
| 91 | Titles: 40, |
| 92 | Timestamp: 10, |
| 93 | } |
| 94 | |
| 95 | func RegisterEventCommands(parent *flags.Parser) { |
| 96 | _, err := parent.AddCommand("event", "event commands", "Commands for observing events", &eventOpts) |
| 97 | if err != nil { |
| 98 | Error.Fatalf("Unable to register event commands with voltctl command parser: %s", err.Error()) |
| 99 | } |
| 100 | } |
| 101 | |
Scott Baker | f05e60a | 2020-02-02 21:53:57 -0800 | [diff] [blame] | 102 | func ParseSince(s string) (*time.Time, error) { |
| 103 | if strings.EqualFold(s, "now") { |
| 104 | since := time.Now() |
| 105 | return &since, nil |
| 106 | } |
| 107 | |
| 108 | rfc3339Time, err := time.Parse(time.RFC3339, s) |
| 109 | if err == nil { |
| 110 | return &rfc3339Time, nil |
| 111 | } |
| 112 | |
| 113 | duration, err := time.ParseDuration(s) |
| 114 | if err == nil { |
| 115 | since := time.Now().Add(-duration) |
| 116 | return &since, nil |
| 117 | } |
| 118 | |
| 119 | return nil, fmt.Errorf("Unable to parse time specification `%s`. Please use either `now`, a duration, or an RFC3339-compliant string", s) |
| 120 | } |
| 121 | |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 122 | // Convert a timestamp field in an event to a time.Time |
| 123 | func DecodeTimestamp(tsIntf interface{}) (time.Time, error) { |
| 124 | ts, okay := tsIntf.(*timestamp.Timestamp) |
| 125 | if okay { |
| 126 | // Voltha-Protos 3.2.3 and above |
| 127 | result, err := ptypes.Timestamp(ts) |
| 128 | return result, err |
| 129 | } |
| 130 | tsFloat, okay := tsIntf.(float32) |
| 131 | if okay { |
| 132 | // Voltha-Protos 3.2.2 and below |
| 133 | return time.Unix(int64(tsFloat), 0), nil |
| 134 | } |
Scott Baker | a1e53fa | 2020-04-01 11:13:34 -0700 | [diff] [blame^] | 135 | tsInt64, okay := tsIntf.(int64) |
| 136 | if okay { |
| 137 | if tsInt64 > 10000000000000 { |
| 138 | // sometimes it's in nanoseconds |
| 139 | return time.Unix(tsInt64/1000000000, tsInt64%1000000000), nil |
| 140 | } else { |
| 141 | // sometimes it's in seconds |
| 142 | return time.Unix(tsInt64/1000, 0), nil |
| 143 | } |
| 144 | } |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 145 | return time.Time{}, errors.New("Failed to decode timestamp") |
| 146 | } |
| 147 | |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 148 | // Extract the header, as well as a few other items that might be of interest |
| 149 | func DecodeHeader(md *desc.MessageDescriptor, b []byte, ts time.Time) (*EventHeader, error) { |
| 150 | m := dynamic.NewMessage(md) |
| 151 | err := m.Unmarshal(b) |
| 152 | if err != nil { |
| 153 | return nil, err |
| 154 | } |
| 155 | |
| 156 | headerIntf, err := m.TryGetFieldByName("header") |
| 157 | if err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | |
| 161 | header := headerIntf.(*dynamic.Message) |
| 162 | |
| 163 | catIntf, err := header.TryGetFieldByName("category") |
| 164 | if err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | cat := catIntf.(int32) |
| 168 | |
| 169 | subCatIntf, err := header.TryGetFieldByName("sub_category") |
| 170 | if err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | subCat := subCatIntf.(int32) |
| 174 | |
| 175 | typeIntf, err := header.TryGetFieldByName("type") |
| 176 | if err != nil { |
| 177 | return nil, err |
| 178 | } |
| 179 | evType := typeIntf.(int32) |
| 180 | |
| 181 | raisedIntf, err := header.TryGetFieldByName("raised_ts") |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 185 | raised, err := DecodeTimestamp(raisedIntf) |
| 186 | if err != nil { |
| 187 | return nil, err |
| 188 | } |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 189 | |
| 190 | reportedIntf, err := header.TryGetFieldByName("reported_ts") |
| 191 | if err != nil { |
| 192 | return nil, err |
| 193 | } |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 194 | reported, err := DecodeTimestamp(reportedIntf) |
| 195 | if err != nil { |
| 196 | return nil, err |
| 197 | } |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 198 | |
| 199 | // Opportunistically try to extract the device_id and title from a kpi_event2 |
| 200 | // note that there might actually be multiple_slice data, so there could |
| 201 | // be multiple device_id, multiple title, etc. |
| 202 | device_ids := make(map[string]interface{}) |
| 203 | titles := make(map[string]interface{}) |
| 204 | |
| 205 | kpiIntf, err := m.TryGetFieldByName("kpi_event2") |
| 206 | if err == nil { |
| 207 | kpi, ok := kpiIntf.(*dynamic.Message) |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 208 | if ok && kpi != nil { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 209 | sliceListIntf, err := kpi.TryGetFieldByName("slice_data") |
| 210 | if err == nil { |
| 211 | sliceIntf, ok := sliceListIntf.([]interface{}) |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 212 | if ok && len(sliceIntf) > 0 { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 213 | slice, ok := sliceIntf[0].(*dynamic.Message) |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 214 | if ok && slice != nil { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 215 | metadataIntf, err := slice.TryGetFieldByName("metadata") |
| 216 | if err == nil { |
| 217 | metadata, ok := metadataIntf.(*dynamic.Message) |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 218 | if ok && metadata != nil { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 219 | deviceIdIntf, err := metadataIntf.(*dynamic.Message).TryGetFieldByName("device_id") |
| 220 | if err == nil { |
| 221 | device_ids[deviceIdIntf.(string)] = slice |
| 222 | } |
| 223 | titleIntf, err := metadataIntf.(*dynamic.Message).TryGetFieldByName("title") |
| 224 | if err == nil { |
| 225 | titles[titleIntf.(string)] = slice |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // Opportunistically try to pull a resource_id and title from a DeviceEvent |
| 236 | // There can only be one resource_id and title from a DeviceEvent, so it's easier |
| 237 | // than dealing with KPI_EVENT2. |
| 238 | deviceEventIntf, err := m.TryGetFieldByName("device_event") |
| 239 | if err == nil { |
| 240 | deviceEvent, ok := deviceEventIntf.(*dynamic.Message) |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 241 | if ok && deviceEvent != nil { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 242 | deviceEventNameIntf, err := deviceEvent.TryGetFieldByName("device_event_name") |
| 243 | if err == nil { |
| 244 | deviceEventName, ok := deviceEventNameIntf.(string) |
| 245 | if ok { |
| 246 | titles[deviceEventName] = deviceEvent |
| 247 | } |
| 248 | } |
| 249 | resourceIdIntf, err := deviceEvent.TryGetFieldByName("resource_id") |
| 250 | if err == nil { |
| 251 | resourceId, ok := resourceIdIntf.(string) |
| 252 | if ok { |
| 253 | device_ids[resourceId] = deviceEvent |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | device_id_keys := make([]string, len(device_ids)) |
| 260 | i := 0 |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 261 | for k := range device_ids { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 262 | device_id_keys[i] = k |
| 263 | i++ |
| 264 | } |
| 265 | |
| 266 | title_keys := make([]string, len(titles)) |
| 267 | i = 0 |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 268 | for k := range titles { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 269 | title_keys[i] = k |
| 270 | i++ |
| 271 | } |
| 272 | |
| 273 | evHeader := EventHeader{Category: model.GetEnumString(header, "category", cat), |
| 274 | SubCategory: model.GetEnumString(header, "sub_category", subCat), |
| 275 | Type: model.GetEnumString(header, "type", evType), |
| 276 | Raised_ts: raised, |
| 277 | Reported_ts: reported, |
| 278 | Device_ids: device_id_keys, |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 279 | Timestamp: ts, |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 280 | Titles: title_keys} |
| 281 | |
| 282 | return &evHeader, nil |
| 283 | } |
| 284 | |
| 285 | // Print the full message, either in JSON or in GRPCURL-human-readable format, |
| 286 | // depending on which grpcurl formatter is passed in. |
| 287 | func PrintMessage(f grpcurl.Formatter, md *desc.MessageDescriptor, b []byte) error { |
| 288 | m := dynamic.NewMessage(md) |
| 289 | err := m.Unmarshal(b) |
| 290 | if err != nil { |
| 291 | return err |
| 292 | } |
| 293 | s, err := f(m) |
| 294 | if err != nil { |
| 295 | return err |
| 296 | } |
| 297 | fmt.Println(s) |
| 298 | return nil |
| 299 | } |
| 300 | |
| 301 | // Print just the enriched EventHeader. This is either in JSON format, or in |
| 302 | // table format. |
| 303 | func PrintEventHeader(outputAs string, outputFormat string, hdr *EventHeader) error { |
| 304 | if outputAs == "json" { |
| 305 | asJson, err := json.Marshal(hdr) |
| 306 | if err != nil { |
| 307 | return fmt.Errorf("Error marshalling JSON: %v", err) |
| 308 | } else { |
| 309 | fmt.Printf("%s\n", asJson) |
| 310 | } |
| 311 | } else { |
| 312 | f := format.Format(outputFormat) |
| 313 | output, err := f.ExecuteFixedWidth(DefaultWidths, false, *hdr) |
| 314 | if err != nil { |
| 315 | return err |
| 316 | } |
| 317 | fmt.Printf("%s\n", output) |
| 318 | } |
| 319 | return nil |
| 320 | } |
| 321 | |
| 322 | func GetEventMessageDesc() (*desc.MessageDescriptor, error) { |
| 323 | // This is a very long-winded way to get a message descriptor |
| 324 | |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 325 | descriptor, err := GetDescriptorSource() |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 326 | if err != nil { |
| 327 | return nil, err |
| 328 | } |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 329 | |
| 330 | // get the symbol for voltha.events |
| 331 | eventSymbol, err := descriptor.FindSymbol("voltha.Event") |
| 332 | if err != nil { |
| 333 | return nil, err |
| 334 | } |
| 335 | |
| 336 | /* |
| 337 | * EventSymbol is a Descriptor, but not a MessageDescrptior, |
| 338 | * so we can't look at it's fields yet. Go back to the file, |
| 339 | * call FindMessage to get the Message, then ... |
| 340 | */ |
| 341 | |
| 342 | eventFile := eventSymbol.GetFile() |
| 343 | eventMessage := eventFile.FindMessage("voltha.Event") |
| 344 | |
| 345 | return eventMessage, nil |
| 346 | } |
| 347 | |
| 348 | // Start output, print any column headers or other start characters |
| 349 | func (options *EventListenOpts) StartOutput(outputFormat string) error { |
| 350 | if options.OutputAs == "json" { |
| 351 | fmt.Println("[") |
| 352 | } else if (options.OutputAs == "table") && !options.ShowBody { |
| 353 | f := format.Format(outputFormat) |
| 354 | output, err := f.ExecuteFixedWidth(DefaultWidths, true, nil) |
| 355 | if err != nil { |
| 356 | return err |
| 357 | } |
| 358 | fmt.Println(output) |
| 359 | } |
| 360 | return nil |
| 361 | } |
| 362 | |
| 363 | // Finish output, print any column footers or other end characters |
| 364 | func (options *EventListenOpts) FinishOutput() { |
| 365 | if options.OutputAs == "json" { |
| 366 | fmt.Println("]") |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | func (options *EventListenOpts) Execute(args []string) error { |
| 371 | ProcessGlobalOptions() |
| 372 | if GlobalConfig.Kafka == "" { |
| 373 | return errors.New("Kafka address is not specified") |
| 374 | } |
| 375 | |
| 376 | eventMessage, err := GetEventMessageDesc() |
| 377 | if err != nil { |
| 378 | return err |
| 379 | } |
| 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 := startConsumer([]string{"voltha.events"}, client) |
| 399 | if err != nil { |
| 400 | return err |
| 401 | } |
| 402 | |
| 403 | highwater := highwaterMarks["voltha.events"] |
| 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 | |
| 416 | if options.ShowBody { |
| 417 | if options.OutputAs == "json" { |
| 418 | // need a descriptor source, any method will do |
David K. Bainbridge | 4bbad14 | 2020-03-11 11:55:39 -0700 | [diff] [blame] | 419 | descriptor, _, err := GetMethod("device-list") |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 420 | if err != nil { |
| 421 | return err |
| 422 | } |
| 423 | grpcurlFormatter = grpcurl.NewJSONFormatter(false, grpcurl.AnyResolverFromDescriptorSource(descriptor)) |
| 424 | } else { |
| 425 | grpcurlFormatter = grpcurl.NewTextFormatter(false) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | var headerFilter *filter.Filter |
| 430 | if options.Filter != "" { |
| 431 | headerFilterVal, err := filter.Parse(options.Filter) |
| 432 | if err != nil { |
| 433 | return fmt.Errorf("Failed to parse filter: %v", err) |
| 434 | } |
| 435 | headerFilter = &headerFilterVal |
| 436 | } |
| 437 | |
| 438 | outputFormat := CharReplacer.Replace(options.Format) |
| 439 | if outputFormat == "" { |
| 440 | outputFormat = GetCommandOptionWithDefault("events-listen", "format", DEFAULT_EVENT_FORMAT) |
| 441 | } |
| 442 | |
| 443 | err = options.StartOutput(outputFormat) |
| 444 | if err != nil { |
| 445 | return err |
| 446 | } |
| 447 | |
Scott Baker | f05e60a | 2020-02-02 21:53:57 -0800 | [diff] [blame] | 448 | var since *time.Time |
| 449 | if options.Since != "" { |
| 450 | since, err = ParseSince(options.Since) |
| 451 | if err != nil { |
| 452 | return err |
| 453 | } |
| 454 | } |
| 455 | |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 456 | // Get signnal for finish |
| 457 | doneCh := make(chan struct{}) |
| 458 | go func() { |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 459 | tStart := time.Now() |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 460 | Loop: |
| 461 | for { |
| 462 | // Initialize the idle timeout timer |
| 463 | timeoutTimer := time.NewTimer(time.Duration(options.Timeout) * time.Second) |
| 464 | select { |
| 465 | case msg := <-consumer: |
| 466 | consumeCount++ |
| 467 | hdr, err := DecodeHeader(eventMessage, msg.Value, msg.Timestamp) |
| 468 | if err != nil { |
| 469 | log.Printf("Error decoding header %v\n", err) |
| 470 | continue |
| 471 | } |
| 472 | if headerFilter != nil && !headerFilter.Evaluate(*hdr) { |
| 473 | // skip printing message |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 474 | } else if since != nil && hdr.Timestamp.Before(*since) { |
Scott Baker | f05e60a | 2020-02-02 21:53:57 -0800 | [diff] [blame] | 475 | // it's too old |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 476 | } else { |
| 477 | // comma separated between this message and predecessor |
| 478 | if count > 0 { |
| 479 | if options.OutputAs == "json" { |
| 480 | fmt.Println(",") |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | // Print it |
| 485 | if options.ShowBody { |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 486 | if err := PrintMessage(grpcurlFormatter, eventMessage, msg.Value); err != nil { |
| 487 | log.Printf("%v\n", err) |
| 488 | } |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 489 | } else { |
David K. Bainbridge | 2b62761 | 2020-02-18 14:50:13 -0800 | [diff] [blame] | 490 | if err := PrintEventHeader(options.OutputAs, outputFormat, hdr); err != nil { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 491 | log.Printf("%v\n", err) |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | // Check to see if we've hit the "count" threshold the user specified |
| 496 | count++ |
| 497 | if (options.Count > 0) && (count >= options.Count) { |
| 498 | log.Println("Count reached") |
| 499 | doneCh <- struct{}{} |
| 500 | break Loop |
| 501 | } |
| 502 | |
| 503 | // Check to see if we've hit the "now" threshold the user specified |
Scott Baker | 2fe436a | 2020-02-10 17:21:47 -0800 | [diff] [blame] | 504 | if (options.Now) && (!hdr.Timestamp.Before(tStart)) { |
Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 505 | log.Println("Now timestamp reached") |
| 506 | doneCh <- struct{}{} |
| 507 | break Loop |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | // If we're not in follow mode, see if we hit the highwater mark |
| 512 | if !options.Follow && !options.Now && (msg.Offset >= highwater) { |
| 513 | log.Println("High water reached") |
| 514 | doneCh <- struct{}{} |
| 515 | break Loop |
| 516 | } |
| 517 | |
| 518 | // Reset the timeout timer |
| 519 | if !timeoutTimer.Stop() { |
| 520 | <-timeoutTimer.C |
| 521 | } |
| 522 | case consumerError := <-consumerErrors: |
| 523 | log.Printf("Received consumerError topic=%v, partition=%v, err=%v\n", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err) |
| 524 | doneCh <- struct{}{} |
| 525 | case <-signals: |
| 526 | doneCh <- struct{}{} |
| 527 | case <-timeoutTimer.C: |
| 528 | log.Printf("Idle timeout\n") |
| 529 | doneCh <- struct{}{} |
| 530 | } |
| 531 | } |
| 532 | }() |
| 533 | |
| 534 | <-doneCh |
| 535 | |
| 536 | options.FinishOutput() |
| 537 | |
| 538 | log.Printf("Consumed %d messages. Printed %d messages", consumeCount, count) |
| 539 | |
| 540 | return nil |
| 541 | } |
| 542 | |
| 543 | // Consume message from Sarama and send them out on a channel. |
| 544 | // Supports multiple topics. |
| 545 | // Taken from Sarama example consumer. |
| 546 | func startConsumer(topics []string, client sarama.Client) (chan *sarama.ConsumerMessage, chan *sarama.ConsumerError, map[string]int64, error) { |
| 547 | master, err := sarama.NewConsumerFromClient(client) |
| 548 | if err != nil { |
| 549 | return nil, nil, nil, err |
| 550 | } |
| 551 | |
| 552 | consumers := make(chan *sarama.ConsumerMessage) |
| 553 | errors := make(chan *sarama.ConsumerError) |
| 554 | highwater := make(map[string]int64) |
| 555 | for _, topic := range topics { |
| 556 | if strings.Contains(topic, "__consumer_offsets") { |
| 557 | continue |
| 558 | } |
| 559 | partitions, _ := master.Partitions(topic) |
| 560 | |
| 561 | // TODO: Add support for multiple partitions |
| 562 | if len(partitions) > 1 { |
| 563 | log.Printf("WARNING: %d partitions on topic %s but we only listen to the first one\n", len(partitions), topic) |
| 564 | } |
| 565 | |
| 566 | hw, err := client.GetOffset("voltha.events", partitions[0], sarama.OffsetNewest) |
| 567 | if err != nil { |
| 568 | return nil, nil, nil, fmt.Errorf("Error in consume() getting highwater: Topic %v Partitions: %v", topic, partitions) |
| 569 | } |
| 570 | highwater[topic] = hw |
| 571 | |
| 572 | consumer, err := master.ConsumePartition(topic, partitions[0], sarama.OffsetOldest) |
| 573 | if nil != err { |
| 574 | return nil, nil, nil, fmt.Errorf("Error in consume(): Topic %v Partitions: %v", topic, partitions) |
| 575 | } |
| 576 | log.Println(" Start consuming topic ", topic) |
| 577 | go func(topic string, consumer sarama.PartitionConsumer) { |
| 578 | for { |
| 579 | select { |
| 580 | case consumerError := <-consumer.Errors(): |
| 581 | errors <- consumerError |
| 582 | |
| 583 | case msg := <-consumer.Messages(): |
| 584 | consumers <- msg |
| 585 | } |
| 586 | } |
| 587 | }(topic, consumer) |
| 588 | } |
| 589 | |
| 590 | return consumers, errors, highwater, nil |
| 591 | } |