Conversation
Signed-off-by: Daniel Li <2067089451@qq.com>
|
@aAAaqwq: The label(s) DetailsIn response to this:
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
Welcome @aAAaqwq! It looks like this is your first PR to kubeedge/mappers-go 🎉 |
There was a problem hiding this comment.
Summary of Changes
Hello @aAAaqwq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request delivers a complete solution for integrating Modbus temperature sensors into the KubeEdge ecosystem. It encompasses the core mapper logic, a flexible driver for Modbus communication, and extensive options for data handling, including persistence to various databases and publishing to external systems. The changes aim to optimize KubeEdge's device management capabilities for practical industrial use cases.
Highlights
- New Temperature Sensor Mapper: Introduced a new KubeEdge mapper specifically designed for Modbus-based temperature sensors, enabling comprehensive device management at the edge.
- Modbus Protocol Support: Implemented robust support for both Modbus TCP and RTU communication modes, allowing flexible integration with various industrial temperature sensors.
- Extensive Data Persistence Options: Added capabilities to push collected temperature data to multiple database types, including InfluxDB2, MySQL, Redis, and TDengine, providing diverse storage solutions.
- Flexible Data Publishing Methods: Enabled various methods for publishing device data, such as HTTP, MQTT, and OpenTelemetry, facilitating integration with different monitoring and analytics platforms.
- Comprehensive Deployment Resources: Provided detailed Kubernetes Custom Resource Definitions (CRDs) for device models and instances, along with Dockerfiles, Makefiles, and Kubernetes YAMLs for streamlined build, deployment, and testing.
- Modbus Simulator for Development: Included a basic Modbus TCP simulator to aid in local development and testing of the mapper without requiring physical hardware.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request adds a new temperature sensor mapper with extensive support for various data storage and publishing methods. The overall contribution is significant, but there are several critical issues across the new files that need to be addressed before merging.
The review has identified critical security vulnerabilities (SQL injection), race conditions from using global variables, and correctness bugs that will cause panics at runtime. Additionally, there are significant performance and image size issues in the Dockerfiles and client implementations. I've provided detailed comments and suggestions for each issue below.
Key areas for improvement:
- Security: Address the SQL injection vulnerabilities in the
tdengineclient by using prepared statements. - Correctness: Fix several bugs that will lead to panics, such as improper error handling in the HTTP client, unsafe type assertions in the OTel handler, and incorrect data parsing in the Redis client. The core driver logic in
GetDeviceDatashould be refactored to return structured data instead of a formatted string. - Concurrency: Refactor database clients (
mysql,redis,tdengine) to avoid using global variables, which can lead to race conditions and make the code difficult to maintain and test. - Performance & Best Practices: The Dockerfiles, particularly
Dockerfile_stream, need significant optimization to reduce image size and build time. The MQTT and HTTP clients should be refactored to reuse connections instead of creating new ones for each request.
Please review the detailed comments on each file. Addressing these points will greatly improve the quality, security, and robustness of the new mapper.
| deviceData := "TimeStamp: " + strconv.FormatInt(data.TimeStamp, 10) + " PropertyName: " + data.PropertyName + " data: " + data.Value | ||
| // Add data to ordered set. If the ordered set does not exist, it will be created. | ||
| _, err := RedisCli.ZAdd(ctx, data.DeviceName, &redis.Z{ | ||
| Score: float64(data.TimeStamp), | ||
| Member: deviceData, |
There was a problem hiding this comment.
The data is being stored in Redis as a concatenated, unstructured string. This makes it very difficult and brittle to parse later. It's much better to store structured data, like a JSON string, which can be easily marshalled and unmarshalled.
Furthermore, GetDataByDeviceID attempts to unmarshal this string as JSON, which will fail and cause a runtime error. This is a critical bug.
deviceData, err := json.Marshal(data)
if err != nil {
return err
}
// Add data to ordered set. If the ordered set does not exist, it will be created.
_, err = RedisCli.ZAdd(ctx, data.DeviceName, &redis.Z{
Score: float64(data.TimeStamp),
Member: deviceData,
}).Result()| insertSQL := fmt.Sprintf("INSERT INTO %s USING %s TAGS ('%s') VALUES('%v','%s', '%s', '%s', '%s');", | ||
| legalTag, legalTable, legalTag, datatime, tableName, data.PropertyName, data.Value, data.Type) | ||
|
|
||
| rows, _ := DB.Query(stableName) |
There was a problem hiding this comment.
| return fmt.Errorf("get device data fail: %v", err) | ||
| } | ||
|
|
||
| o.ObserveFloat64(gauge, data.(float64)) |
There was a problem hiding this comment.
This line performs a hard type assertion data.(float64). However, the GetDeviceData function in the driver returns a formatted string (e.g., "The data read from the device,Type:float32 Value:25.5"), not a float64. This will cause a runtime panic.
The driver's GetDeviceData method needs to be refactored to return the raw, normalized data value. After that, the value should be correctly converted here before being observed.
| if token := client.Connect(); token.Wait() && token.Error() != nil { | ||
| fmt.Println(token.Error()) | ||
| os.Exit(1) | ||
| } |
There was a problem hiding this comment.
Calling os.Exit(1) on an MQTT connection failure is too drastic. It will terminate the entire mapper process if the MQTT broker is temporarily unavailable. The error should be logged, and the connection should be retried, possibly with a backoff strategy.
| if token := client.Connect(); token.Wait() && token.Error() != nil { | |
| fmt.Println(token.Error()) | |
| os.Exit(1) | |
| } | |
| if token := client.Connect(); token.Wait() && token.Error() != nil { | |
| klog.Errorf("Failed to connect to MQTT broker: %v", token.Error()) | |
| return | |
| } |
| @@ -0,0 +1,157 @@ | |||
| package tdengine | |||
| // go modbus_simulator.InitModbusSimulator(":5502") | ||
|
|
||
| klog.InitFlags(nil) | ||
| defer klog.Flush() | ||
|
|
||
| if c, err = config.Parse(); err != nil { | ||
| klog.Fatal(err) | ||
| } | ||
| // klog.Infof("config: %+v", c) | ||
|
|
||
|
|
||
| klog.Infoln("Mapper will register to edgecore") | ||
| deviceList, deviceModelList, err := grpcclient.RegisterMapper(true) | ||
| if err != nil { | ||
| klog.Fatal(err) | ||
| } | ||
| klog.Infoln("Mapper register finished") | ||
|
|
||
| panel := device.NewDevPanel() | ||
| err = panel.DevInit(deviceList, deviceModelList) | ||
| if err != nil && !errors.Is(err, device.ErrEmptyData) { | ||
| klog.Fatal(err) | ||
| } | ||
| // if errors.Is(err, device.ErrEmptyData) { | ||
| // klog.Infoln("devInit finished,but no device data") | ||
| // }else{ | ||
| // klog.Infoln("devInit finished") | ||
| // } |
|
|
||
| ### 1. Clone the repository to local | ||
| ``` | ||
| git clone https://github.com/aAAaqwq/temperature-sensor-mapper |
There was a problem hiding this comment.
| # name: mysecret | ||
| # key: token | ||
| image: temperature-mapper:v1.0 | ||
| imagePullPolicy: Always |
There was a problem hiding this comment.
|
Thanks for your contribution; however, the mapper is for a specific type of connection, like Modbus, Bluetooth, not for a special device. Maybe move your contriubtion to https://github.com/kubeedge/examples is better? |
This mapper is built based on the modbus protocol and can be renamed to modbus-mapper. In example repo, we will use this modbus mapper to manage the simulated temperature device. |
|
|
||
| ## Prerequisites | ||
|
|
||
| - KubeEdge environment (v1.12.0 or higher) |
There was a problem hiding this comment.
Is this mapper generated based on mapper-framework v1.21? If so, I suggest changing the version number here to v1.21 or higher.
| - Go 1.22.0 or higher | ||
| - Modbus Simulator | ||
|
|
||
| ## Quick Start |
There was a problem hiding this comment.
Mappers-go should only contain the built-in mapper plugin, so the Quick Start only needs to describe how to deploy this mapper. You can add a sentence at the end: If you want to fully experience the mapper management of simulated temperature devices, you can refer to the example repo
What type of PR is this?
/kind feat
What this PR does / why we need it:
To resolve issue #6315 :Optimize KubeEdge Device Management Practical Case Studies.
Which issue(s) this PR fixes:
Fixes #6315
Special notes for your reviewer:
Does this PR introduce a user-facing change?: