Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 支持 metrics #310

Closed

Conversation

qdsordinarydream
Copy link
Contributor

@qdsordinarydream qdsordinarydream commented May 11, 2024

新增 metrics 链路指标监控

Summary by CodeRabbit

  • New Features

    • Introduced Prometheus metrics across various components to enhance monitoring capabilities, including tracking namespace versions, latest checks, and onchange events.
    • Added new fields AppId and Cluster to change events for better context in configurations.
  • Enhancements

    • Improved initialization of metrics to precede configuration setups in the StartWithConfig function.
    • Enhanced metric tracking in configuration synchronization and notification components.
  • Documentation

    • Updated comments for better clarity and consistency in component configurations and startup processes.

Copy link

coderabbitai bot commented May 11, 2024

Walkthrough

The recent updates across multiple Go files introduce enhanced metrics tracking capabilities using Prometheus, alongside some structural changes to data handling and function parameters. These modifications aim to improve monitoring, version tracking, and event handling in the application's configuration and notification components.

Changes

Files Summary
client.go, component/notify/..., component/remote/async.go, storage/repository.go Introduced or enhanced use of Prometheus metrics for better tracking and monitoring.
component/metrics/metrics.go, extension/metrics.go Added new metrics functionalities and initialization processes.
storage/change_event.go Structural changes to data handling, addition of new fields, and modification in function parameters.

🐇💻 A Poem by CodeRabbit
O hark! The metrics dance anew,
In lines of code, beneath the blue.
Gauges spin, counters fly,
In Apollo's realm, where data lie.
With each push and pull, we see,
A code-rabbit's joy, in git commit glee! 🎉🐾


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

mergify bot commented May 11, 2024

感谢您提出Pull Request,我会尽快Review。我会在1-2日内进行查看或者回复,如果遇到节假日可能会处理较慢,敬请谅解。

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 9660dd0 and eb38b4e.
Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
Files selected for processing (7)
  • client.go (1 hunks)
  • component/metrics/metrics.go (1 hunks)
  • component/notify/componet_notify.go (4 hunks)
  • component/remote/async.go (2 hunks)
  • extension/metrics.go (1 hunks)
  • storage/change_event.go (4 hunks)
  • storage/repository.go (3 hunks)
Additional comments not posted (7)
component/metrics/metrics.go (2)

8-13: Ensure that the labels used in NamespaceVersionGauge are accurate and meaningful for the intended metrics.

Verification successful

The verification process has confirmed that the labels used in NamespaceVersionGauge are both accurate and meaningful for the intended metrics. The labels "appid", "req_cluster", "use_cluster", "namespace", "ip", and "version" are appropriately used in the codebase, with "req_cluster" and "use_cluster" representing different aspects of cluster configuration, which justifies their separate usage. This aligns well with the intended functionality of tracking namespace versions in different clusters and configurations.

  • appid is correctly used to identify the application.
  • req_cluster and use_cluster effectively differentiate between the requested cluster and the cluster actually used, which is crucial for accurate metrics in a distributed environment.
  • namespace, ip, and version are straightforward and directly relate to their respective metrics.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the labels used in NamespaceVersionGauge are accurate and meaningful.

# Test: Search for the usage of NamespaceVersionGauge. Expect: Labels should match the context where they are used.
rg --type go $'NamespaceVersionGauge.WithLabelValues'

Length of output: 458



Script:

#!/bin/bash
# Description: Verify the purpose of 'req_cluster' and 'use_cluster' in the context of NamespaceVersionGauge.

# Test: Search for definitions or comments related to 'appConfig.Cluster' and 'apolloConfig.Cluster' to understand their roles.
rg --type go -C 3 'appConfig.Cluster|apolloConfig.Cluster'

Length of output: 4415


15-20: Ensure that the labels used in LatestCheckGauge are accurate and meaningful for the intended metrics.

Verification successful

The labels used in LatestCheckGauge are confirmed to be accurate and meaningful for the intended metrics. The function utils.GetInternal(), which corresponds to the "ip" label, is specifically designed to retrieve an internal IP address, aligning perfectly with its usage in the metric. This verification addresses the concern raised in the review comment.

  • File: component/metrics/metrics.go
  • Label Usage Verification: component/notify/componet_notify.go
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the labels used in LatestCheckGauge are accurate and meaningful.

# Test: Search for the usage of LatestCheckGauge. Expect: Labels should match the context where they are used.
rg --type go $'LatestCheckGauge.WithLabelValues'

Length of output: 242



Script:

#!/bin/bash
# Description: Verify the function `utils.GetInternal()` to ensure it returns an IP address or an equivalent identifier.

# Test: Search for the implementation of `utils.GetInternal()` to understand its functionality.
ast-grep --lang go --pattern $'func GetInternal() {
  $$$
}'

Length of output: 61



Script:

#!/bin/bash
# Description: Broaden the search for any occurrence of `GetInternal` to catch any definition, usage, or alias.

# Test: Search across all Go files for `GetInternal` to understand its context and definition.
rg --type go 'GetInternal'

Length of output: 1211

component/notify/componet_notify.go (1)

65-68: Ensure that the labels used in LatestCheckGauge are correctly applied and that the metric accurately reflects the intended measurement.

storage/change_event.go (1)

Line range hint 42-98: Ensure that the new fields AppId and Cluster in the event structures are correctly utilized throughout the system, especially in metrics and logging.

Verification successful

The review comment concerning the utilization of the new fields AppId and Cluster in metrics and logging has been verified. The fields are actively used in metrics, as evidenced by their inclusion in various metric labels. Although no explicit logging statements were found, the usage in metrics typically fulfills a similar role in monitoring and debugging, which might be considered sufficient depending on the system's architecture and requirements.

  • Metrics usage found in:
    • metrics.OnchangeGauge.WithLabelValues(event.AppId, event.Cluster, event.Namespace, utils.GetInternal()).Set(float64(event.NotificationID))
    • metrics.NamespaceVersionGauge.WithLabelValues(apolloConfig.AppID, appConfig.Cluster, apolloConfig.Cluster, notifyConfig.NamespaceName, utils.GetInternal(), version).Set(1)
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of new fields `AppId` and `Cluster`.

# Test: Search for the usage of `AppId` and `Cluster`. Expect: Fields should be correctly utilized in metrics and logging.
rg --type go $'AppId|Cluster'

Length of output: 3416

component/remote/async.go (1)

88-95: Ensure that the version tracking logic correctly handles the transition between old and new versions, and that metrics are accurately recorded.

Verification successful

The version tracking logic in the code correctly handles the transition between old and new versions by setting the metric value for the old version to 0 and for the new version to 1. Additionally, the metrics are accurately recorded with appropriate labels, ensuring that the transitions are well-documented and traceable. Based on this analysis:

  • The handling of version transitions in component/remote/async.go is implemented as expected.
  • The metrics recording uses consistent labels and correctly reflects the version changes.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the version tracking logic and the accuracy of metrics recording.

# Test: Search for the usage of `NamespaceVersionGauge`. Expect: Logic should correctly handle version transitions and metrics should be accurately recorded.
rg --type go $'NamespaceVersionGauge.WithLabelValues'

Length of output: 458

client.go (1)

111-113: Ensure that the metrics initialization at the start of the StartWithConfig function is correctly placed to capture all necessary data.

Metrics initialization is correctly placed at the start of the function to ensure all subsequent operations are monitored.

storage/repository.go (1)

622-622: Ensure that the metrics recording in the pushChangeEvent function correctly reflects the onchange events.

Verification successful

The verification process has confirmed that the OnchangeGauge metric is used within the pushChangeEvent function in storage/repository.go. The context provided by the script output shows that the metric is set right before triggering the OnChange listener, which aligns with the intended purpose of recording onchange events. The parameters used (event.AppId, event.Cluster, event.Namespace, and utils.GetInternal()) and the setting of the gauge to float64(event.NotificationID) are appropriate for reflecting the details of the onchange event.

Given this information, the implementation of the metrics recording in the pushChangeEvent function correctly reflects the onchange events as intended in the original review comment.

Metrics Recording in pushChangeEvent Function is Correct

  • The usage of OnchangeGauge in the pushChangeEvent function is correctly implemented to reflect onchange events.
  • The metric is set with appropriate event details and is triggered in the correct function context.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the accuracy of metrics recording in onchange events.

# Test: Search for the usage of `OnchangeGauge`. Expect: Metrics should correctly reflect onchange events.
rg --type go $'OnchangeGauge.WithLabelValues'

Length of output: 207



Script:

#!/bin/bash
# Verify that the `OnchangeGauge` is only used in the `pushChangeEvent` function and check its context.
rg --type go -C 5 "OnchangeGauge.WithLabelValues"

Length of output: 714

Comment on lines +22 to +27
// OnchangeGauge 触发 onchange 监控, 值为版本
OnchangeGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "onchange",
Subsystem: "sdk",
Namespace: "apollo",
}, []string{"appid", "use_cluster", "namespace", "ip"})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The verification process has revealed a potential issue with the label usage in OnchangeGauge:

  • The label "ip" is correctly used to represent IP addresses, aligning with the output of utils.GetInternal().
  • However, the label "use_cluster" might be misleading as it is used with event.Cluster, which appears to be a cluster identifier rather than indicating a boolean state or usage pattern as the label might suggest.

It would be beneficial to review and possibly revise the label "use_cluster" to ensure it accurately reflects its intended purpose.

Analysis chain

Ensure that the labels used in OnchangeGauge are accurate and meaningful for the intended metrics.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the labels used in OnchangeGauge are accurate and meaningful.

# Test: Search for the usage of OnchangeGauge. Expect: Labels should match the context where they are used.
rg --type go $'OnchangeGauge.WithLabelValues'

Length of output: 207



Script:

#!/bin/bash
# Description: Further investigate the usage of labels in OnchangeGauge.

# Test 1: Check the return type and value of `utils.GetInternal()` to see if it matches the expected IP address format.
rg --type go -A 5 'func GetInternal()'

# Test 2: Search for documentation or comments that clarify the intended use of `event.Cluster` to see if it matches the "use_cluster" label.
rg --type go -C 3 'event.Cluster'

Length of output: 796

Comment on lines +30 to +38
var m = make(map[string]string)

func GetVersionByNamespace(appid, cluster, namespace string) string {
return m[appid+cluster+namespace]
}

func SetVersionByNamespace(appid, cluster, namespace, version string) {
m[appid+cluster+namespace] = version
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using a more robust key structure for the version map to avoid potential key collisions.

- m[appid+cluster+namespace] = version
+ m[appid + "|" + cluster + "|" + namespace] = version

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
var m = make(map[string]string)
func GetVersionByNamespace(appid, cluster, namespace string) string {
return m[appid+cluster+namespace]
}
func SetVersionByNamespace(appid, cluster, namespace, version string) {
m[appid+cluster+namespace] = version
}
var m = make(map[string]string)
func GetVersionByNamespace(appid, cluster, namespace string) string {
return m[appid+cluster+namespace]
}
func SetVersionByNamespace(appid, cluster, namespace, version string) {
m[appid + "|" + cluster + "|" + namespace] = version
}

Comment on lines +25 to +28
// SetMetricsRegister 甚至 metrics register
func SetMetricsRegister(register *prometheus.Registry) {
globalMetrics = register
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typographical error in the comment of SetMetricsRegister. It should be "set" instead of "甚至".

- // SetMetricsRegister 甚至 metrics register
+ // SetMetricsRegister set metrics register

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// SetMetricsRegister 甚至 metrics register
func SetMetricsRegister(register *prometheus.Registry) {
globalMetrics = register
}
// SetMetricsRegister set metrics register
func SetMetricsRegister(register *prometheus.Registry) {
globalMetrics = register
}

Comment on lines +39 to +51
if err := register.Register(metrics.NamespaceVersionGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}

// 最近更新内容监控
if err := register.Register(metrics.LatestCheckGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}

// onchange 监控
if err := register.Register(metrics.OnchangeGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure error handling is consistent and correct in the registration of metrics. Currently, the error message always refers to namespace_version which might be incorrect for other metrics.

- log.Errorf("register namespace_version metrics fail, error: %v", err)
+ log.Errorf("register %s metrics fail, error: %v", metricName, err)

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if err := register.Register(metrics.NamespaceVersionGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}
// 最近更新内容监控
if err := register.Register(metrics.LatestCheckGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}
// onchange 监控
if err := register.Register(metrics.OnchangeGauge); err != nil {
log.Errorf("register namespace_version metrics fail, error: %v", err)
}
if err := register.Register(metrics.NamespaceVersionGauge); err != nil {
log.Errorf("register %s metrics fail, error: %v", "namespace_version", err)
}
// 最近更新内容监控
if err := register.Register(metrics.LatestCheckGauge); err != nil {
log.Errorf("register %s metrics fail, error: %v", "latest_check", err)
}
// onchange 监控
if err := register.Register(metrics.OnchangeGauge); err != nil {
log.Errorf("register %s metrics fail, error: %v", "onchange", err)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant