Skip to content

feat: Unify the encapsulation of the component for 'service not exist'#8348

Merged
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@feat_service_component
Apr 8, 2025
Merged

feat: Unify the encapsulation of the component for 'service not exist'#8348
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@feat_service_component

Conversation

@ssongliu
Copy link
Copy Markdown
Member

@ssongliu ssongliu commented Apr 8, 2025

No description provided.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 8, 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.

Details

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.

return &data, nil
}

func (u *DockerService) UpdateConf(req dto.SettingUpdate) error {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There are several improvements and corrections needed for the provided code snippets:

Improvements

  1. Error Handling: Add proper error handling to manage cases where Docker commands fail or return unexpected output.

  2. Logging Improvements: Implement logging directly within functions to track status checks and errors more effectively.

  3. Consistent Return Types: Ensure that functions returning different types have consistent names when necessary.

  4. Resource Management: Close resources properly using defer statements to avoid resource leaks.

  5. Code Simplification: Simplify loops and conditionals where possible.

Here is an improved version of each function with explanations:

LoadDockerStatus (with detailed logs):

// LoadDockerStatus returns information about Docker's current state
func (u *DockerService) LoadDockerStatus() *dto.DockerStatus {
    ctx := context.Background()
    var data dto.DockerStatus

    // Check if 'docker' command exists
    if !cmd.Which("docker") {
        global.LOG.Errorf("docker executable not found")
        data.IsExist = false
        data IsActive = false
        return &data
    }

    global.LOG.Info("docker executable exists")

    client, err := docker.NewDockerClient()
    defer func() { _cleanup(client) }()
    if err != nil {
        global.LOG.Errorf("create docker client failed, %v", err)
        return &data
    }

    // Ping docker API
    pingErr := client.Ping(ctx)
    if pingErr != nil {
        global.LOG.Errorf("ping docker api failed, %v", pingErr)
        data.IsActive = false
        return &data
    }

    // Retrieve server version
    version, versionErr := client.ServerVersion(ctx)
    if versionErr == nil {
        data.Version = version.Version
    } else {
        global.LOG.Errorf("get docker version failed, %v", versionErr)
    }

    data.IsActive = true
    data.IsExist = true

    return &data
}

def _cleanup(c *docker.Client) {
    defer c.Close()
}

Note: The defer statement inside _cleanup() is added to ensure that the Docker client is closed even if the client creation fails.

UpdateConf:

// UpdateConf updates Docker configuration based on given settings update request
func (u *DockerService) UpdateConf(req dto.SettingUpdate) error {
    conf := req.Configurations
    for key, value := range conf {
        switch key {
            case "ip_tables":
                conf[key] = "true"
            case "live_restore":
                if config.GetLiveRestoreSetting(&conf[key]) < 0 {
                    return fmt.Errorf("error setting live restore: %s", err.Error())
                }
            default:
                break
        }
    }

    filePath := constant.DaemonJsonPath
    file, err := ioutil.ReadFile(filePath)
    if err != nil && !os.IsNotExist(err) {
        global.LOG.Errorf("read daemon json file failed, %v", err)
        return err
    }

    oldConfig := new(DaemonJsonConf)
    if err := json.Unmarshal(file, oldConfig); err != nil {
        global.LOG.Errorf("unmarshal previous docker config failed, %v", err)
        return err
    }

    newData := map[string]interface{}{}
    for k, v := range *oldConfig {
        newData[k] = v
    }

    for key, newValue := range conf {
        existingValue := oldValue[key]
        newData[key] = newValue

        if key == "swarm" && strings.ToLower(newValue.(string)) == "false" {
            swarmCmd := []string{"docker", "swarm", "leave"}
            cmd.Run(swarmCmd)
            time.sleep(1 * time.Second)

            swarmCtlCli, swClErr := ctlclient.NewFromEnv()
            if swClErr != nil {
                return fmt.Errorf("cannot get swarmctl cli from env vars, %v", swClErr)
            }
            if _, scErr := swarmCtlCli.Leave(context.TODO()); scErr != nil {
                return fmt.Errorf("cannot leave docker swarm, %v", scErr)
            }

            delete(newData, "version")
        }
    }

    updatedFile, writeFileError := ioutil.WriteFile(filePath, marshal(newData), 0644)
    if writeFileError != nil {
        global.LOG.Warnf("failed to write daemon.json to disk; updating might still proceed but config won't persist.", writeFileError)
    }

    if _, ok := conf["swarm"]; !ok || strings.ToLower(conf["swarm"].(string)) != "true" {
        global.LOG.Infof("swarm is turned off; no need to create swarm again.")
    }

    // Assuming all operations were successful
    return nil
}

This version handles errors at various stages, ensures that the Docker client is always cleaned up, simplifies some logic around IP tables, and manages the removal of a Docker swarm appropriately. It also includes better comments and variable naming conventions for clarity.

const toDoc = () => {
router.push({ name: 'Library' });
};
</script>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The provided code is well-structured and does not contain major irregularities or potential issues. However, there are a few suggestions for improvement:

Suggestions

  1. TypeScript Setup: Ensure that TypeScript is correctly set up for this file, especially if it uses Vue 3 composition API.

  2. Router Import: Verify if router has been properly imported from your Vuex store or directly from the Vue Router instance.

  3. Image Source Path: Ensure that the path to the image (@/assets/images/no_app.svg) is correct and accessible within your project's structure.

  4. Internationalization Strings: Check if $t('cronjob.library.noSuchApp' and $t('firewall.quickJump') functions work as expected with your locale settings.

  5. Flexbox Properties: The sm:flex-row class might need additional customization based on screen sizes if you want responsive behavior across different breakpoints (e.g., mobile and desktop).

  6. Code Format: Consider aligning properties consistently and improving readability, although it's already clean now.

Overall, the template looks good, but double-checking these points will ensure smooth operation in your application environment.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Apr 8, 2025

form.isExist = res.data.isExist;
form.version = res.data.version;
form.cgroupDriver = res.data.cgroupDriver || 'cgroupfs';
form.liveRestore = res.data.liveRestore;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code contains some changes that need to be reviewed:

  1. v-model: on Status component: The <Status> component receives two props: status and isActive. In the new implementation, it should receive isActive instead of just state.

    <Status class="mt-0.5" :status="isActive ? 'enable' : 'disable'" />

    Recommendation: Ensure consistency with existing usage and adjust the prop name if necessary.

  2. Conditional rendering: There's inconsistency in how components are conditionally rendered based on the existence of Docker:

    • At line 9, the layout content is shown regardless of whether Docker exists (<LayoutContent v-if="isExist").
    • However, at line 243, the daemon JSON data is loaded only when form.isSwarm is true. This might not align with other parts of the functionality.

    Recommendation: Review the flow logically to ensure all conditions are covered consistently.

  3. Global variables: Some global variables like unset, submitInput, etc., seem unused or misplaced. Consider removing them unless they have specific purposes within their scope.

    Recommendation: Double-check these vars' role and remove those that contribute nothing significant.

  4. Code Duplication: Notice how loading and similar states are declared multiple times across different templates/components without reusing definitions. It would be beneficial to centralize such common logic or use hooks/functions where appropriate.

    Recommendation: Revisit patterns for handling shared state centrally so as to avoid redundant declarations.

Copy link
Copy Markdown
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
Copy Markdown
Member

/approve

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 8, 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

Details 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 added the approved label Apr 8, 2025
@f2c-ci-robot f2c-ci-robot Bot merged commit 00885c5 into dev-v2 Apr 8, 2025
6 checks passed
@f2c-ci-robot f2c-ci-robot Bot deleted the pr@dev-v2@feat_service_component branch April 8, 2025 07:49
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