mirror of
https://github.com/moby/moby.git
synced 2026-01-11 18:51:37 +00:00
Improve validation for empty name; while the daemon already handled empty
strings, it didn't account for the "canonical" name with "/" prefix, for
which it would produce an obscure error:
Error response from daemon: Error when allocating new name: Invalid container name (/ ), only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed
Before this change:
curl -XPOST --unix-socket /var/run/docker.sock 'http://localhost/v1.51/containers/old/rename?name='
{"message":"Neither old nor new names may be empty"}
curl -XPOST --unix-socket /var/run/docker.sock 'http://localhost/v1.51/containers/old/rename?name=/'
{"message":"Error when allocating new name: Invalid container name (/), only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed"}
curl -XPOST --unix-socket /var/run/docker.sock 'http://localhost/v1.51/containers/old/rename?name=/hello'
# OK
A check was added in the client as well for situations where an older daemon
is used; the same code currently was implemented in the CLI.
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
40 lines
1.3 KiB
Go
40 lines
1.3 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/containerd/errdefs"
|
|
)
|
|
|
|
// ContainerRenameOptions represents the options for renaming a container.
|
|
type ContainerRenameOptions struct {
|
|
NewName string
|
|
}
|
|
|
|
// ContainerRenameResult represents the result of a container rename operation.
|
|
type ContainerRenameResult struct {
|
|
// This struct can be expanded in the future if needed
|
|
}
|
|
|
|
// ContainerRename changes the name of a given container.
|
|
func (cli *Client) ContainerRename(ctx context.Context, containerID string, options ContainerRenameOptions) (ContainerRenameResult, error) {
|
|
containerID, err := trimID("container", containerID)
|
|
if err != nil {
|
|
return ContainerRenameResult{}, err
|
|
}
|
|
options.NewName = strings.TrimSpace(options.NewName)
|
|
if options.NewName == "" || strings.TrimPrefix(options.NewName, "/") == "" {
|
|
// daemons before v29.0 did not handle the canonical name ("/") well
|
|
// let's be nice and validate it here before sending
|
|
return ContainerRenameResult{}, errdefs.ErrInvalidArgument.WithMessage("new name cannot be blank")
|
|
}
|
|
|
|
query := url.Values{}
|
|
query.Set("name", options.NewName)
|
|
resp, err := cli.post(ctx, "/containers/"+containerID+"/rename", query, nil, nil)
|
|
defer ensureReaderClosed(resp)
|
|
return ContainerRenameResult{}, err
|
|
}
|