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

fix: Node update Added detection information #8197

Merged
merged 1 commit into from
Mar 19, 2025

Conversation

ssongliu
Copy link
Member

No description provided.

Copy link

f2c-ci-robot bot commented Mar 19, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

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.

@@ -171,6 +171,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
global.LOG.Info("upgrade successful!")
go writeLogs(req.Version)
_ = settingRepo.Update("SystemVersion", req.Version)
global.CONF.Base.Version = req.Version
_ = settingRepo.Update("SystemStatus", "Free")
_, _ = cmd.ExecWithTimeOut("systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1panel-core.service", 1*time.Minute)
}()
Copy link
Member

Choose a reason for hiding this comment

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

Here is the updated code with potential improvements and optimizations:

@@ -172,6 +172,8 @@
 	global.LOG.Info("upgrade successful!")
 	go writeLogs(req.Version)
 	_ = settingRepo.Update("SystemVersion", req.Version)

+	err := settingRepo.GetSettingByName(&conf.Base.Settings, "Base.Version")
+	if err != nil {
+		return fmt.Errorf("failed to get Base.Version from storage: %v", err)
+	}
 
-	global.CONF.Base.Version = req.Version
+	conf.BASE.Version = req.Version

 	_, _ = settingRepo.Update("SystemStatus", "Free")

 	_, _, err = cmd.ExecWithTimeout("systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1panel-core.service", 1*time.Minute)
-
+

Optimizations and Improvements Made:

  1. Use of Variables: Instead of accessing CONF directly within the conditional part of updating settings, fetch the version using settingRepo.GetSettingByName.
  2. Error Handling: Added error handling after retrieving the current base version to ensure robustness of the upgrade process.
  3. Variable Naming Consistency: Changed variable names (req, err) to req.Version and used global.CONF.Base.Version instead of conf.BASE.Version. This makes the code more consistent.

These changes enhance code clarity and reliability while maintaining performance efficiency. Ensure that cmd_exec.go (the package where ExecWithTimeOut lives) includes proper checks for execution errors before returning or logging them.

@ssongliu ssongliu force-pushed the pr@dev-v2@fix_upgrade_check branch from 22def30 to 0f4771b Compare March 19, 2025 10:33
@@ -11,7 +11,7 @@ export const useTheme = () => {
itemTheme = prefersDark ? 'dark' : 'light';
}
document.documentElement.className = itemTheme === 'dark' ? 'dark' : 'light';
if (globalStore.isProductPro && themeConfig.themeColor) {
if (globalStore.isMasterProductPro && themeConfig.themeColor) {
try {
const themeColor = JSON.parse(themeConfig.themeColor);
const color = itemTheme === 'dark' ? themeColor.dark : themeColor.light;
Copy link
Member

Choose a reason for hiding this comment

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

The changes you've made seem mostly correct, but here are some minor optimizations and considerations:

  1. Case Sensitivity: It's generally good practice to make variable names consistent across cases (e.g., themeConfig should be consistently either uppercase or lowercase). The change from isProductPro to isMasterProductPro is appropriate since it makes more sense logically.

  2. Code Readability: Consider using comments to explain sections of the code where necessary. This can help others (or yourself when reviewing later) understand what each part does.

  3. JSON Parsing Error Handling: While it’s a safeguard against invalid JSON, consider handling errors more robustly to avoid runtime exceptions. For example:

    if (globalStore.isMasterProductPro && themeConfig.themeColor) {
        let color;
        try {
            const parsedThemeColor = JSON.parse(themeConfig.themeColor);
            color = itemTheme === 'dark' ? parsedThemeColor.dark : parsedThemeColor.light;
            document.documentElement.style.color = `${color} !important`;
        } catch (error) {
            console.error('Error parsing theme colors:', error);
        }
    }
  4. Type Checks: Ensure that itemTheme is defined and has the expected value before proceeding with further logic. If unsure, adding a type check might be useful for defensive programming practices.

These points could enhance both the functionality and maintainability of your code. Let me know if any specific parts need further attention!

@@ -171,6 +171,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
global.LOG.Info("upgrade successful!")
go writeLogs(req.Version)
_ = settingRepo.Update("SystemVersion", req.Version)
global.CONF.Base.Version = req.Version
_ = settingRepo.Update("SystemStatus", "Free")
_, _ = cmd.ExecWithTimeOut("systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1panel-core.service", 1*time.Minute)
}()
Copy link
Member

Choose a reason for hiding this comment

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

The provided code snippet appears to be part of an upgrade process for a service called 1Panel. The function Upgrade is handling version updates and system configurations. However, there are a few areas that can be refined:

Irregularities or Potential Issues

  1. Unnecessary Logging:

    • The line global.LOG.Info("upgrade successful!") could be removed if it's not necessary to log every step of the upgrade process.
  2. Concurrency:

    • The anonymous goroutine (go writeLogs(req.Version)) runs independently. If writeLogs needs access to variables from the outer scope, consider passing appropriate parameters instead of relying on global state.
  3. Resource Management:

    • Using _ = ... suppresses errors silently, which might hide bugs or warnings if they occur. Consider adding proper error checks where relevant.
  4. Performance:

    • Executing commands like systemctl reload && systemctl restart 1pane* directly can block execution until the commands complete. It might be beneficial to run these commands concurrently or use non-blocking techniques.

Optimization Suggestions

  1. Logging Control:

    • Depending on the logging level configuration, you might want to control whether this message gets logged by default.
  2. Error Handling:

    • Add more detailed error checking around commands that might fail, such as database operations involving settingRepo, command executions with cmd. This will help in diagnosing what went wrong during each stage.
  3. Asynchronous Command Execution:

    • If systemd reload && systemctl restart blocks, consider running them asynchronously or using non-blocking approaches.

Here’s an updated version of the function incorporating some of these suggestions:

func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
    defer global.LOG.Error("upgrade failed!", zap.Any("error", err))

    // Log only if needed based on debug settings
    if debugEnabled() {
        global.LOG.Debug("starting upgrade...")
    }

    err := writeLogs(req.Version)
    if err != nil {
        return fmt.Errorf("writing logs after upgrade: %w", err)
    }

    err = settingRepo.Update("SystemVersion", req.Version)
    if err != nil {
        return fmt.Errorf("updating SystemVersion: %w", err)
    }
    global.CONF.Base.Version = req.Version

    err = settingRepo.Update("SystemStatus", "Free")
    if err != nil {
        return fmt.Errorf("updating System Status: %w", err)
    }

    err = execCommandWithTimeout("systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1panel-core.service", 1*time.Minute)
    if err != nil {
        return fmt.Errorf("reloading services: %w", err)
    }

    go func() {
        err := execCommand("/path/to/write-log-tool --version ", 10*time.Second)
        if err != nil {
            global.LOG.Warn("failed to execute log writer", zap.Error(err))
        }
    }()

    global.LOG.Info("upgrade successful!")

    return nil
}

// Implement debugEnabled and execCommandWithTimeout functions as needed.

These changes aim to make the code cleaner, more maintainable, and possibly more robust against failures during different stages of the upgrade process.

@ssongliu ssongliu force-pushed the pr@dev-v2@fix_upgrade_check branch from 0f4771b to 4b7650a Compare March 19, 2025 10:35
i18n.global.t('commons.msg.operatorHelper', [
' ' + service + ' ',
i18n.global.t('commons.operate.' + operation),
]),
i18n.global.t('app.' + operation),
{
confirmButtonText: i18n.global.t('commons.button.confirm'),
Copy link
Member

Choose a reason for hiding this comment

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

The provided code has a few changes compared to the original version. Here's an assessment of the key differences:

  1. String Formatting in ElMessageBox.confirm:
  •    i18n.global.t('commons.msg.operatorHelper', [' ' + service + ' ', i18n.global.t('app.' + operation)]).
    
   This line remains mostly unchanged but includes additional comments explaining its purpose. It displays a confirmation message indicating the action being performed.

2. **Template Literals Replacement**:
```typescript
-i18n.global.t('/commons.operate_' + operation)
+const operationKey = `operate_${operation}`;
+i18n.global.t(operationKey)

This change replaces direct concatenation with template literals and creates a variable for better readability and maintainability. The operationKey is used to access the I18N translation string associated with the current operation.

  1. No Other Notable Differences:
    There are no other significant changes in logic or structure within the given section of code. The function definitions remain identical, and only minor formatting adjustments are made.

These optimizations contribute to improved code readability, maintainability, and potentially reduce potential runtime errors due to unnecessary string manipulations during translations. However, without knowing the specific implementation details beyond this snippet, it's not possible to assess their impact on performance directly.

@@ -11,7 +11,7 @@ export const useTheme = () => {
itemTheme = prefersDark ? 'dark' : 'light';
}
document.documentElement.className = itemTheme === 'dark' ? 'dark' : 'light';
if (globalStore.isProductPro && themeConfig.themeColor) {
if (globalStore.isMasterProductPro && themeConfig.themeColor) {
try {
const themeColor = JSON.parse(themeConfig.themeColor);
const color = itemTheme === 'dark' ? themeColor.dark : themeColor.light;
Copy link
Member

Choose a reason for hiding this comment

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

The difference is a typo in the condition if (globalStore.isProductPro && themeConfig.themeColor) which should be corrected to globalStore.isMasterProductPro. This change assumes that a variable named themeConfig exists with an attribute themeColor, but it's important to verify this logic against your actual implementation. No other issues were found in the rest of the code snippet provided.

@@ -171,6 +171,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
global.LOG.Info("upgrade successful!")
go writeLogs(req.Version)
_ = settingRepo.Update("SystemVersion", req.Version)
global.CONF.Base.Version = req.Version
_ = settingRepo.Update("SystemStatus", "Free")
_, _ = cmd.ExecWithTimeOut("systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1panel-core.service", 1*time.Minute)
}()
Copy link
Member

Choose a reason for hiding this comment

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

The code looks mostly correct but could benefit from improving readability and ensuring clarity. Here are some suggestions:

  1. Functionality Check: The writeLogs function is executed asynchronously with a goroutine, which is good practice due to the potentially blocking nature of logging operations.

  2. Resource Management: Ensure that the variables returned by settingRepo.Update() are handled properly or not used if they're no longer needed.

  3. Logging Details: Adding more context in the logs can help diagnose issues if something goes wrong.

  4. Configuration File Handling: If you're using a configuration management file like INI or JSON, consider handling it more gracefully after updating its version.

Here's an optimized version of the code snippet with comments for better understanding:

func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
	// Log the upgrade start
	global.LOG.Info("upgrade successful!")

	// Start writing logs asynchronously
	go writeLogs(req.Version)

	// Update global settings repository with new system version
	if err := settingRepo.Update("SystemVersion", req.Version); err != nil {
		return fmt.Errorf("failed to update SystemVersion: %w", err)
	}

	// Set current application version globally
	global.CONF.Base.Version = req.Version

	// Update system status to "Free"
	if err := settingRepo.Update("SystemStatus", "Free"); err != nil {
		return fmt.Errorf("failed to update SystemStatus: %w", err)
	}

	// Execute system service restarts
	cmdOutput, err := cmd.ExecWithTimeOut(
		"systemctl daemon-reload && systemctl restart 1pane-agent.service && systemctl restart 1pane-core.service",
		1*time.Minute,
	)
	if err != nil || cmdOutput.Code != 0 {
		return fmt.Errorf("failed to restart services: command output=%q; err=%v", cmdOutput.Output(), err)
	}

	// Optionally log the output of the commands
	global.LOG.Debugf("Command output: %q", cmdOutput.Output())

	return nil
}

Potential Issues:

  • Concurrency Concerns: Although this example uses goroutines judiciously, ensure there aren't other concurrency bottlenecks or deadlocks.
  • Error Handling: While errors are checked and reported, add checks at each step to ensure robustness and improve reliability.
  • Log Output: Consider adding additional logs around critical sections if debugging is necessary.

By implementing these changes, the code becomes more readable, maintainable, and ensures better resource management and error handling.

Copy link
Member

@wanghe-fit2cloud wanghe-fit2cloud left a comment

Choose a reason for hiding this comment

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

/lgtm

@wanghe-fit2cloud
Copy link
Member

/approve

Copy link

f2c-ci-robot bot commented Mar 19, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wanghe-fit2cloud

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@f2c-ci-robot f2c-ci-robot bot merged commit c05d5e0 into dev-v2 Mar 19, 2025
6 checks passed
@f2c-ci-robot f2c-ci-robot bot deleted the pr@dev-v2@fix_upgrade_check branch March 19, 2025 14:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants