You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2022/11/01 12:02:34 UTC

[plc4x] 01/02: feat(plc4xanalyzer): exposed cli options to the ui

This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 00d418f0e6af3146fb001c611ad1b105905b7930
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Tue Nov 1 12:56:59 2022 +0100

    feat(plc4xanalyzer): exposed cli options to the ui
---
 .../plc4xpcapanalyzer/config/AnalyzeConfig.go      |   2 +-
 .../tools/plc4xpcapanalyzer/config/BacnetConfig.go |   4 +-
 .../tools/plc4xpcapanalyzer/config/CBusConfig.go   |   4 +-
 .../plc4xpcapanalyzer/config/ExtractConfig.go      |   2 +-
 .../tools/plc4xpcapanalyzer/config/PcapConfig.go   |   2 +-
 .../internal/analyzer/analyzer.go                  |  21 +--
 .../internal/extractor/extractor.go                |  21 +--
 plc4go/tools/plc4xpcapanalyzer/ui/commands.go      | 192 ++++++++++++++-------
 plc4go/tools/plc4xpcapanalyzer/ui/config.go        |  31 +++-
 9 files changed, 188 insertions(+), 91 deletions(-)

diff --git a/plc4go/tools/plc4xpcapanalyzer/config/AnalyzeConfig.go b/plc4go/tools/plc4xpcapanalyzer/config/AnalyzeConfig.go
index 602521fbf..1c6f25377 100644
--- a/plc4go/tools/plc4xpcapanalyzer/config/AnalyzeConfig.go
+++ b/plc4go/tools/plc4xpcapanalyzer/config/AnalyzeConfig.go
@@ -20,7 +20,7 @@
 package config
 
 type AnalyzeConfig struct {
-	*PcapConfig
+	*PcapConfig                                          `json:"-"`
 	NoFilter, OnlyParse, NoBytesCompare, NoCustomMapping bool
 }
 
diff --git a/plc4go/tools/plc4xpcapanalyzer/config/BacnetConfig.go b/plc4go/tools/plc4xpcapanalyzer/config/BacnetConfig.go
index de370e415..b662daf91 100644
--- a/plc4go/tools/plc4xpcapanalyzer/config/BacnetConfig.go
+++ b/plc4go/tools/plc4xpcapanalyzer/config/BacnetConfig.go
@@ -20,8 +20,8 @@
 package config
 
 type BacnetConfig struct {
-	*AnalyzeConfig
-	BacnetFilter string
+	*AnalyzeConfig `json:"-"`
+	BacnetFilter   string
 }
 
 var BacnetConfigInstance = BacnetConfig{}
diff --git a/plc4go/tools/plc4xpcapanalyzer/config/CBusConfig.go b/plc4go/tools/plc4xpcapanalyzer/config/CBusConfig.go
index f9d1b3e5c..42bbd4a47 100644
--- a/plc4go/tools/plc4xpcapanalyzer/config/CBusConfig.go
+++ b/plc4go/tools/plc4xpcapanalyzer/config/CBusConfig.go
@@ -20,8 +20,8 @@
 package config
 
 type CBusConfig struct {
-	*AnalyzeConfig
-	CBusFilter string
+	*AnalyzeConfig `json:"-"`
+	CBusFilter     string
 
 	Connect bool
 	Smart   bool
diff --git a/plc4go/tools/plc4xpcapanalyzer/config/ExtractConfig.go b/plc4go/tools/plc4xpcapanalyzer/config/ExtractConfig.go
index 7ea1a3cde..6f101aa99 100644
--- a/plc4go/tools/plc4xpcapanalyzer/config/ExtractConfig.go
+++ b/plc4go/tools/plc4xpcapanalyzer/config/ExtractConfig.go
@@ -27,7 +27,7 @@ const (
 )
 
 type ExtractConfig struct {
-	*PcapConfig
+	*PcapConfig               `json:"-"`
 	ShowDirectionalIndicators bool
 	ExtractType               ExtractType
 }
diff --git a/plc4go/tools/plc4xpcapanalyzer/config/PcapConfig.go b/plc4go/tools/plc4xpcapanalyzer/config/PcapConfig.go
index 41e54765e..c399c633e 100644
--- a/plc4go/tools/plc4xpcapanalyzer/config/PcapConfig.go
+++ b/plc4go/tools/plc4xpcapanalyzer/config/PcapConfig.go
@@ -20,7 +20,7 @@
 package config
 
 type PcapConfig struct {
-	*RootConfig
+	*RootConfig        `json:"-"`
 	Filter             string
 	Client             string
 	StartPackageNumber uint
diff --git a/plc4go/tools/plc4xpcapanalyzer/internal/analyzer/analyzer.go b/plc4go/tools/plc4xpcapanalyzer/internal/analyzer/analyzer.go
index d931ee5cb..da7e3552a 100644
--- a/plc4go/tools/plc4xpcapanalyzer/internal/analyzer/analyzer.go
+++ b/plc4go/tools/plc4xpcapanalyzer/internal/analyzer/analyzer.go
@@ -51,16 +51,7 @@ func AnalyzeWithOutput(pcapFile, protocolType string, stdout, stderr io.Writer)
 }
 
 func AnalyzeWithOutputAndCallback(ctx context.Context, pcapFile, protocolType string, stdout, stderr io.Writer, messageCallback func(parsed spi.Message)) error {
-	log.Info().Msgf("Analyzing pcap file '%s' with protocolType '%s' and filter '%s' now", pcapFile, protocolType, config.AnalyzeConfigInstance.Filter)
-
-	handle, numberOfPackage, timestampToIndexMap, err := pcaphandler.GetIndexedPcapHandle(pcapFile, config.AnalyzeConfigInstance.Filter)
-	if err != nil {
-		return errors.Wrap(err, "Error getting handle")
-	}
-	log.Info().Msgf("Starting to analyze %d packages", numberOfPackage)
-	defer handle.Close()
-	log.Debug().Interface("handle", handle).Int("numberOfPackage", numberOfPackage).Msg("got handle")
-	source := pcaphandler.GetPacketSource(handle)
+	var filterExpression = config.AnalyzeConfigInstance.Filter
 	var mapPackets = func(in chan gopacket.Packet, packetInformationCreator func(packet gopacket.Packet) common.PacketInformation) chan gopacket.Packet {
 		return in
 	}
@@ -88,6 +79,16 @@ func AnalyzeWithOutputAndCallback(ctx context.Context, pcapFile, protocolType st
 	default:
 		return errors.Errorf("Unsupported protocol type %s", protocolType)
 	}
+
+	log.Info().Msgf("Analyzing pcap file '%s' with protocolType '%s' and filter '%s' now", pcapFile, protocolType, filterExpression)
+	handle, numberOfPackage, timestampToIndexMap, err := pcaphandler.GetIndexedPcapHandle(pcapFile, filterExpression)
+	if err != nil {
+		return errors.Wrap(err, "Error getting handle")
+	}
+	log.Info().Msgf("Starting to analyze %d packages", numberOfPackage)
+	defer handle.Close()
+	log.Debug().Interface("handle", handle).Int("numberOfPackage", numberOfPackage).Msg("got handle")
+	source := pcaphandler.GetPacketSource(handle)
 	bar := progressbar.NewOptions(numberOfPackage, progressbar.OptionSetWriter(ansi.NewAnsiStderr()),
 		progressbar.OptionSetVisibility(!config.RootConfigInstance.HideProgressBar),
 		progressbar.OptionEnableColorCodes(true),
diff --git a/plc4go/tools/plc4xpcapanalyzer/internal/extractor/extractor.go b/plc4go/tools/plc4xpcapanalyzer/internal/extractor/extractor.go
index f18719fde..03464ff1d 100644
--- a/plc4go/tools/plc4xpcapanalyzer/internal/extractor/extractor.go
+++ b/plc4go/tools/plc4xpcapanalyzer/internal/extractor/extractor.go
@@ -40,16 +40,6 @@ func Extract(pcapFile, protocolType string) error {
 }
 
 func ExtractWithOutput(ctx context.Context, pcapFile, protocolType string, stdout, stderr io.Writer) error {
-	log.Info().Msgf("Analyzing pcap file '%s' with protocolType '%s' and filter '%s' now", pcapFile, protocolType, config.ExtractConfigInstance.Filter)
-
-	handle, numberOfPackage, timestampToIndexMap, err := pcaphandler.GetIndexedPcapHandle(pcapFile, config.ExtractConfigInstance.Filter)
-	if err != nil {
-		return errors.Wrap(err, "Error getting handle")
-	}
-	log.Info().Msgf("Starting to analyze %d packages", numberOfPackage)
-	defer handle.Close()
-	log.Debug().Interface("handle", handle).Int("numberOfPackage", numberOfPackage).Msg("got handle")
-	source := pcaphandler.GetPacketSource(handle)
 	var printPayload = func(packetInformation common.PacketInformation, item []byte) {
 		_, _ = fmt.Fprintf(stdout, "%x\n", item)
 	}
@@ -91,6 +81,17 @@ func ExtractWithOutput(ctx context.Context, pcapFile, protocolType string, stdou
 			}
 		}
 	}
+	filterExpression := config.ExtractConfigInstance.Filter
+	log.Info().Msgf("Analyzing pcap file '%s' with protocolType '%s' and filter '%s' now", pcapFile, protocolType, filterExpression)
+
+	handle, numberOfPackage, timestampToIndexMap, err := pcaphandler.GetIndexedPcapHandle(pcapFile, filterExpression)
+	if err != nil {
+		return errors.Wrap(err, "Error getting handle")
+	}
+	log.Info().Msgf("Starting to analyze %d packages", numberOfPackage)
+	defer handle.Close()
+	log.Debug().Interface("handle", handle).Int("numberOfPackage", numberOfPackage).Msg("got handle")
+	source := pcaphandler.GetPacketSource(handle)
 	bar := progressbar.NewOptions(numberOfPackage, progressbar.OptionSetWriter(ansi.NewAnsiStderr()),
 		progressbar.OptionSetVisibility(!config.RootConfigInstance.HideProgressBar),
 		progressbar.OptionEnableColorCodes(true),
diff --git a/plc4go/tools/plc4xpcapanalyzer/ui/commands.go b/plc4go/tools/plc4xpcapanalyzer/ui/commands.go
index 2ceb2b1da..272d923c8 100644
--- a/plc4go/tools/plc4xpcapanalyzer/ui/commands.go
+++ b/plc4go/tools/plc4xpcapanalyzer/ui/commands.go
@@ -33,6 +33,7 @@ import (
 	"github.com/rs/zerolog/log"
 	"os"
 	"path"
+	"reflect"
 	"strings"
 	"time"
 )
@@ -287,62 +288,154 @@ var rootCommand = Command{
 			},
 		},
 		{
-			Name:        "plc4x-conf",
-			Description: "plc4x related settings",
+			Name:        "conf",
+			Description: "Various settings for plc4xpcapanalyzer",
 			subCommands: []Command{
 				{
-					Name:        "TraceTransactionManagerWorkers",
-					Description: "print information about transaction manager workers",
+					Name:        "list",
+					Description: "list config values with their current settings",
+					action: func(_ context.Context, _ Command, _ string) error {
+						allCliConfigsValue := reflect.ValueOf(allCliConfigsInstances)
+						for i := 0; i < allCliConfigsValue.NumField(); i++ {
+							allConfigField := allCliConfigsValue.Field(i)
+							allConfigFieldType := allCliConfigsValue.Type().Field(i)
+							_, _ = fmt.Fprintf(commandOutput, "%s:\n", allConfigFieldType.Name)
+							configInstanceReflectValue := reflect.ValueOf(allConfigField.Interface())
+							if configInstanceReflectValue.Kind() == reflect.Ptr {
+								configInstanceReflectValue = configInstanceReflectValue.Elem()
+							}
+							for j := 0; j < configInstanceReflectValue.NumField(); j++ {
+								configField := configInstanceReflectValue.Field(j)
+								configFieldType := configInstanceReflectValue.Type().Field(j)
+								if configFieldType.Tag.Get("json") == "-" {
+									// Ignore those
+									continue
+								}
+								_, _ = fmt.Fprintf(commandOutput, "  %s: %s\t= %v\n", configFieldType.Name, configFieldType.Type, configField.Interface())
+							}
+						}
+						return nil
+					},
+				},
+				{
+					Name:        "set",
+					Description: "sets a config value",
+					subCommands: func() []Command {
+						var configCommand []Command
+						allCliConfigsValue := reflect.ValueOf(allCliConfigsInstances)
+						for i := 0; i < allCliConfigsValue.NumField(); i++ {
+							allConfigField := allCliConfigsValue.Field(i)
+							allConfigFieldType := allCliConfigsValue.Type().Field(i)
+							configCommand = append(configCommand, Command{
+								Name:        allConfigFieldType.Name,
+								Description: fmt.Sprintf("Setting for %s", allConfigFieldType.Name),
+								subCommands: func() []Command {
+									var configElementCommands []Command
+									configInstanceReflectValue := reflect.ValueOf(allConfigField.Interface())
+									if configInstanceReflectValue.Kind() == reflect.Ptr {
+										configInstanceReflectValue = configInstanceReflectValue.Elem()
+									}
+									for i := 0; i < configInstanceReflectValue.NumField(); i++ {
+										field := configInstanceReflectValue.Field(i)
+										fieldOfType := configInstanceReflectValue.Type().Field(i)
+										if fieldOfType.Tag.Get("json") == "-" {
+											// Ignore those
+											continue
+										}
+										configElementCommands = append(configElementCommands, Command{
+											Name:        fieldOfType.Name,
+											Description: fmt.Sprintf("Sets value for %s", fieldOfType.Name),
+											action: func(_ context.Context, _ Command, argument string) error {
+												field.SetString(argument)
+												return nil
+											},
+										})
+									}
+									return configElementCommands
+								}(),
+							})
+						}
+						return configCommand
+					}(),
+				},
+				{
+					Name:        "plc4xpcapanalyzer-debug",
+					Description: "Prints out debug information of the pcap analyzer itself",
 					subCommands: []Command{
 						{
 							Name:        "on",
-							Description: "trace on",
+							Description: "debug on",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceTransactionManagerWorkers = true
+								plc4xpcapanalyzerLog = zerolog.New(zerolog.ConsoleWriter{Out: tview.ANSIWriter(consoleOutput)})
 								return nil
 							},
 						},
 						{
 							Name:        "off",
-							Description: "trace off",
+							Description: "debug off",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceTransactionManagerWorkers = false
+								plc4xpcapanalyzerLog = zerolog.Nop()
 								return nil
 							},
 						},
 					},
 				},
 				{
-					Name:        "TraceTransactionManagerTransactions",
-					Description: "print information about transaction manager transactions",
+					Name:        "auto-register",
+					Description: "autoregister driver at startup",
 					subCommands: []Command{
 						{
-							Name:        "on",
-							Description: "trace on",
-							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceTransactionManagerTransactions = true
+							Name: "list",
+							action: func(_ context.Context, currentCommand Command, argument string) error {
+								_, _ = fmt.Fprintf(commandOutput, "Auto-register enabled drivers:\n  %s\n", strings.Join(config.AutoRegisterDrivers, "\n  "))
 								return nil
 							},
 						},
 						{
-							Name:        "off",
-							Description: "trace off",
-							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceTransactionManagerTransactions = false
-								return nil
+							Name: "enable",
+							action: func(_ context.Context, _ Command, argument string) error {
+								return enableAutoRegister(argument)
+							},
+							parameterSuggestions: func(currentText string) (entries []string) {
+								for _, protocol := range protocolList {
+									if strings.HasPrefix(protocol, currentText) {
+										entries = append(entries, protocol)
+									}
+								}
+								return
+							},
+						},
+						{
+							Name: "disable",
+							action: func(_ context.Context, _ Command, argument string) error {
+								return disableAutoRegister(argument)
+							},
+							parameterSuggestions: func(currentText string) (entries []string) {
+								for _, protocol := range protocolList {
+									if strings.HasPrefix(protocol, currentText) {
+										entries = append(entries, protocol)
+									}
+								}
+								return
 							},
 						},
 					},
 				},
+			},
+		},
+		{
+			Name:        "plc4x-conf",
+			Description: "plc4x related settings",
+			subCommands: []Command{
 				{
-					Name:        "TraceDefaultMessageCodecWorker",
-					Description: "print information about message codec workers",
+					Name:        "TraceTransactionManagerWorkers",
+					Description: "print information about transaction manager workers",
 					subCommands: []Command{
 						{
 							Name:        "on",
 							Description: "trace on",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceDefaultMessageCodecWorker = true
+								plc4x_config.TraceTransactionManagerWorkers = true
 								return nil
 							},
 						},
@@ -350,71 +443,52 @@ var rootCommand = Command{
 							Name:        "off",
 							Description: "trace off",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4x_config.TraceDefaultMessageCodecWorker = false
+								plc4x_config.TraceTransactionManagerWorkers = false
 								return nil
 							},
 						},
 					},
 				},
 				{
-					Name:        "plc4xpcapanalyzer-debug",
-					Description: "Prints out debug information of the pcap analyzer itself",
+					Name:        "TraceTransactionManagerTransactions",
+					Description: "print information about transaction manager transactions",
 					subCommands: []Command{
 						{
 							Name:        "on",
-							Description: "debug on",
+							Description: "trace on",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4xpcapanalyzerLog = zerolog.New(zerolog.ConsoleWriter{Out: tview.ANSIWriter(consoleOutput)})
+								plc4x_config.TraceTransactionManagerTransactions = true
 								return nil
 							},
 						},
 						{
 							Name:        "off",
-							Description: "debug off",
+							Description: "trace off",
 							action: func(_ context.Context, _ Command, _ string) error {
-								plc4xpcapanalyzerLog = zerolog.Nop()
+								plc4x_config.TraceTransactionManagerTransactions = false
 								return nil
 							},
 						},
 					},
 				},
 				{
-					Name:        "auto-register",
-					Description: "autoregister driver at startup",
+					Name:        "TraceDefaultMessageCodecWorker",
+					Description: "print information about message codec workers",
 					subCommands: []Command{
 						{
-							Name: "list",
-							action: func(_ context.Context, currentCommand Command, argument string) error {
-								_, _ = fmt.Fprintf(commandOutput, "Auto-register enabled drivers:\n  %s\n", strings.Join(config.AutoRegisterDrivers, "\n  "))
+							Name:        "on",
+							Description: "trace on",
+							action: func(_ context.Context, _ Command, _ string) error {
+								plc4x_config.TraceDefaultMessageCodecWorker = true
 								return nil
 							},
 						},
 						{
-							Name: "enable",
-							action: func(_ context.Context, _ Command, argument string) error {
-								return enableAutoRegister(argument)
-							},
-							parameterSuggestions: func(currentText string) (entries []string) {
-								for _, protocol := range protocolList {
-									if strings.HasPrefix(protocol, currentText) {
-										entries = append(entries, protocol)
-									}
-								}
-								return
-							},
-						},
-						{
-							Name: "disable",
-							action: func(_ context.Context, _ Command, argument string) error {
-								return disableAutoRegister(argument)
-							},
-							parameterSuggestions: func(currentText string) (entries []string) {
-								for _, protocol := range protocolList {
-									if strings.HasPrefix(protocol, currentText) {
-										entries = append(entries, protocol)
-									}
-								}
-								return
+							Name:        "off",
+							Description: "trace off",
+							action: func(_ context.Context, _ Command, _ string) error {
+								plc4x_config.TraceDefaultMessageCodecWorker = false
+								return nil
 							},
 						},
 					},
diff --git a/plc4go/tools/plc4xpcapanalyzer/ui/config.go b/plc4go/tools/plc4xpcapanalyzer/ui/config.go
index f856ef362..61f3bc3ff 100644
--- a/plc4go/tools/plc4xpcapanalyzer/ui/config.go
+++ b/plc4go/tools/plc4xpcapanalyzer/ui/config.go
@@ -20,6 +20,7 @@
 package ui
 
 import (
+	cliConfig "github.com/apache/plc4x/plc4go/tools/plc4xpcapanalyzer/config"
 	"github.com/pkg/errors"
 	"github.com/rs/zerolog"
 	"github.com/rs/zerolog/log"
@@ -34,6 +35,7 @@ var configFile string
 var config = Config{
 	MaxConsoleLines: 500,
 	MaxOutputLines:  500,
+	CliConfigs:      allCliConfigsInstances,
 }
 
 type Config struct {
@@ -42,11 +44,30 @@ type Config struct {
 		Last10Files    []string `yaml:"last_hosts"`
 		Last10Commands []string `yaml:"last_commands"`
 	}
-	AutoRegisterDrivers []string  `yaml:"auto_register_driver"`
-	LastUpdated         time.Time `yaml:"last_updated"`
-	LogLevel            string    `yaml:"log_level"`
-	MaxConsoleLines     int       `yaml:"max_console_lines"`
-	MaxOutputLines      int       `yaml:"max_output_lines"`
+	AutoRegisterDrivers []string      `yaml:"auto_register_driver"`
+	LastUpdated         time.Time     `yaml:"last_updated"`
+	LogLevel            string        `yaml:"log_level"`
+	MaxConsoleLines     int           `yaml:"max_console_lines"`
+	MaxOutputLines      int           `yaml:"max_output_lines"`
+	CliConfigs          allCliConfigs `yaml:"cli_configs"`
+}
+
+type allCliConfigs struct {
+	RootConfig    *cliConfig.RootConfig
+	AnalyzeConfig *cliConfig.AnalyzeConfig
+	ExtractConfig *cliConfig.ExtractConfig
+	BacnetConfig  *cliConfig.BacnetConfig
+	CBusConfig    *cliConfig.CBusConfig
+	PcapConfig    *cliConfig.PcapConfig
+}
+
+var allCliConfigsInstances = allCliConfigs{
+	&cliConfig.RootConfigInstance,
+	&cliConfig.AnalyzeConfigInstance,
+	&cliConfig.ExtractConfigInstance,
+	&cliConfig.BacnetConfigInstance,
+	&cliConfig.CBusConfigInstance,
+	&cliConfig.PcapConfigInstance,
 }
 
 func init() {