1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00
moby--moby/daemon/rename.go
Arnaud Porterie 70c5e96cb8 Merge pull request #19604 from Microsoft/jjh/testrename
Windows CI: Fix TestRename*
2016-01-26 19:03:31 -08:00

85 lines
1.7 KiB
Go

package daemon
import (
"strings"
"github.com/Sirupsen/logrus"
derr "github.com/docker/docker/errors"
"github.com/docker/libnetwork"
)
// ContainerRename changes the name of a container, using the oldName
// to find the container. An error is returned if newName is already
// reserved.
func (daemon *Daemon) ContainerRename(oldName, newName string) error {
var (
sid string
sb libnetwork.Sandbox
)
if oldName == "" || newName == "" {
return derr.ErrorCodeEmptyRename
}
container, err := daemon.GetContainer(oldName)
if err != nil {
return err
}
oldName = container.Name
container.Lock()
defer container.Unlock()
if newName, err = daemon.reserveName(container.ID, newName); err != nil {
return derr.ErrorCodeRenameTaken.WithArgs(err)
}
container.Name = newName
defer func() {
if err != nil {
container.Name = oldName
daemon.reserveName(container.ID, oldName)
daemon.releaseName(newName)
}
}()
daemon.releaseName(oldName)
if err = container.ToDisk(); err != nil {
return err
}
attributes := map[string]string{
"oldName": oldName,
}
if !container.Running {
daemon.LogContainerEventWithAttributes(container, "rename", attributes)
return nil
}
defer func() {
if err != nil {
container.Name = oldName
if e := container.ToDisk(); e != nil {
logrus.Errorf("%s: Failed in writing to Disk on rename failure: %v", container.ID, e)
}
}
}()
sid = container.NetworkSettings.SandboxID
if daemon.netController != nil {
sb, err = daemon.netController.SandboxByID(sid)
if err != nil {
return err
}
err = sb.Rename(strings.TrimPrefix(container.Name, "/"))
if err != nil {
return err
}
}
daemon.LogContainerEventWithAttributes(container, "rename", attributes)
return nil
}