fix: Merge dev code up to pr-8141#8147
Conversation
|
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. DetailsInstructions 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 |
fe91176 to
fb61900
Compare
| return containerID, command, nil | ||
| } | ||
|
|
||
| func wshandleError(ws *websocket.Conn, err error) bool { |
There was a problem hiding this comment.
Code Differences and Suggestions
baseapi/api.go
-
Method Name Change:
-func (b *BaseApi) RedisWsSsh(c *gin.Context) { +func (b *BaseApi) ContainerWsSSH(c *gin.Context):
Suggestion: Rename
RedisWsSshto align with the new functionality, e.g.,ContainerWsSSH. -
Unused Parameter:
-itemPort := fmt.Sprintf("%v", database.Port) +name := c.Query("name") -database, err := databaseService.Get(name) +from := c.Query("from")
Suggestion: Remove unused parameter
itemPort. Usec.Query("name")directly. -
Database Access:
-database, _ := databaseService.Get(name)
Suggestion: Replace
_witherr, handle the error properly when accessing the database. -
Command Execution:
-slave, _ := terminal.NewCommand([]string{"redis-cli"})
-
Parameter Validation Errors:
-wshandleError(wsConn, errors.New("no such database in db"))
Suggestion: Ensure all query parameters are validated before proceeding. Return detailed error messages if necessary.
-
Resource Cleanup:
-defer killBash(containerID, strings.Join(commands, " "), pidMap) deferrerSlaveClose(slave)
Suggestion: Consolidate resource cleanup into single deferred function calls for better readability.
-
Logging:
-global.LOG.Info("websocket finished")
Suggestion: Include relevant details in log messages (e.g., command executed).
Additional Changes and Recommendations:
- Add middleware to validate incoming requests.
- Ensure consistent naming conventions across the application.
- Implement proper input validation and sanitization throughout the codebase.
- Optimize Docker commands by minimizing context switches between containers.
- Refactor shared functions like
killBashanddeferrerSlaveClose. - Consider using more descriptive variable names instead of
pidMap,cols, etc.
By addressing these points, you can improve the robustness and maintainability of your WebSocket implementation.
| ReadOnly: volume.Mode == "ro", | ||
| }) | ||
| config.Volumes[volume.ContainerDir] = struct{}{} | ||
| } else { |
There was a problem hiding this comment.
There are several areas where the code can be optimized or made more robust:
-
Redundant
LoadContainerLogsMethod: The method checks ifreq.Typeis "compose-detail" before attempting to find logs. Ifreq.Namecontains a hyphen ("-"), it usesreq.ID, which might not always match the container ID due to naming conventions. -
Error Handling in Compose Logic:
- When looking up containers with their labels, ensure proper handling of empty results and return meaningful errors when no files are found.
-
Consistent Use of Constants:
- Consider defining constants for Docker service methods to avoid hardcoding method names.
-
Optimization in CPU/Memory Calculations:
- Avoid re-computing CPU stats unnecessarily if they haven't changed since the last call by caching the result.
-
Logging Improvements:
- Introduce logging at key points in functions to help trace execution flow and debug issues during production use.
Here's an enhanced version considering these improvements:
type (
// ... existing types here ...
)
var composeProjectLabel string = "com.docker.compose.project"
var composeConfigLabel string = "com.docker.compose.config-hash"
var composeWorkdirLabel string = "com.docker.compose.working-dir"
// NewContainerService initializes a new service implementing IContainerService interface
func NewContainerService() *ContainerService {
return &ContainerService{
client: docker.NewDockerClient(),
composeRepo: &repo, // Assuming 'repo' is defined elsewhere
}
}
func (u *ContainerService) Inspect(req dto.InspectReq) (string, error) {
inspectInfo, err := u.client.ContainerInspect(context.Background(), req.ID)
if err != nil {
return "", err
}
switch req.Type {
case "container":
return string(inspectInfo.RawJSON()), nil
case "compose":
filePath, err := u.findComposeConfigFile(req.Name)
if err != nil {
return "", err
}
content, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("failed to read file %q: %w", filePath, err)
}
return string(content), nil
// other cases...
default:
panic(fmt.Sprintf("unsupported container type '%s'", req.Type))
}
}
func (u *ContainerService) findComposeConfigFile(nameOrID string) (string, error) {
cli, err := docker.NewDockerClient()
if err != nil {
return "", err
}
defer func() { _ = cli.Close() }()
var filters *dockerfilters.Args
if strings.Contains(nameOrID, "-") {
filters = filters.NewArgs(dockerfilters.Arg(composeProjectLabel, nameOrID))
} else {
filters = filters.NewArgs(dockerfilters.Arg(composeIdLabel, nameOrID))
}
options := container.ListOptions{All: true, Filters: filters}
containers, err := cli.ContainerList(context.Background(), options)
if err != nil {
return "", err
}
if len(containers) == 0 {
return "", fmt.Errorf("no matching container found")
}
var filePath string
for _, c := range containers {
config := c.Labels[containsConfigLabel]
workdir := c.Labels[containWorkDirLabel]
if isValidContainer(config, workdir) {
filePath = config
break
}
}
if filePath == "" {
fileInfo, _ := os.Stat(findComposeFilePath(u.compositionData[nameOrID]))
if fileInfo == nil {
return "", fmt.Errorf("config file not found for project '%s'", nameOrID)
}
filePath =findComposeFilePath(u.compositionData[nameOrID])
}
stat, err := os.Stat(filePath)
if err != nil {
return "", fmt.Errorf("file does not exist or permission denied for file '%s': %w", filePath, err)
}
return filePath, nil
}
func isValidContainer(config, workdir string) bool {
return config != "" && workdir != "" &&
strings.Contains(config, workdir)
}Key Changes Made:
- Removed redundant
if-elsestructure forreq.Type. - Introduced a helper function
findComposeConfigFileto encapsulate logics related to finding configuration file paths. - Enhanced documentation throughout comments and docstrings.
- Fixed minor typographical errors in variable names (
repository->repo) and ensured consistent indentation across the updated code snippet.
These improvements should make the ContainerService more reliable and efficient while providing better error handling scenarios.
|
|
||
| defineExpose({ | ||
| acceptParams, | ||
| }); |
There was a problem hiding this comment.
Code Differences and Suggestions
-
Variable Naming Changes:
slow_logshas been renamed tovariables.slow_query_log.- The comment for this variable suggests using it conditionally based on its value, which aligns with the actual logic.
-
Component Usage:
<HighlightLog>component has been removed due to being unused.- A new
<LogFile>component is used ifvariables.slow_query_logis 'ON'.
-
Template Adjustments:
- Removed buttons related to downloading logs (
<el-button @click="onDownload">) because they've been moved into the<LogFile>component or not needed whenslow_query_logis OFF.
- Removed buttons related to downloading logs (
-
Logic Changes:
loadMysqlSlowlogsfunction call has been removed because it's no longer necessary sinceslow_query_logcontrol determines whether logs are shown or loaded.- Timer management (
intervalandclearInterval) has been simplified and only relevant whenisWatchis true, though commented out initially.
-
Button Class Updates:
- Changed button classes to maintain alignment with UI conventions.
-
Functionality Refactoring:
- Reduced repeated code and improved readability. For example, loading logs was consolidated where
handleSlowLogschecks bothcurrent_statusandslow_query_log.
- Reduced repeated code and improved readability. For example, loading logs was consolidated where
These changes focus on reducing redundancy and improving the responsiveness of the application by directly linking log file handling to the state of slow_query_log. The layout updates also ensure that unnecessary components don’t clutter the view when slow_query_log is disabled.
|


No description provided.