github.com/noxiouz/docker@v0.7.3-0.20160629055221-3d231c78e8c5/daemon/rename.go (about) 1 package daemon 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/Sirupsen/logrus" 8 "github.com/docker/libnetwork" 9 ) 10 11 // ContainerRename changes the name of a container, using the oldName 12 // to find the container. An error is returned if newName is already 13 // reserved. 14 func (daemon *Daemon) ContainerRename(oldName, newName string) error { 15 var ( 16 sid string 17 sb libnetwork.Sandbox 18 ) 19 20 if oldName == "" || newName == "" { 21 return fmt.Errorf("Neither old nor new names may be empty") 22 } 23 24 if newName[0] != '/' { 25 newName = "/" + newName 26 } 27 28 container, err := daemon.GetContainer(oldName) 29 if err != nil { 30 return err 31 } 32 33 oldName = container.Name 34 oldIsAnonymousEndpoint := container.NetworkSettings.IsAnonymousEndpoint 35 36 if oldName == newName { 37 return fmt.Errorf("Renaming a container with the same name as its current name") 38 } 39 40 container.Lock() 41 defer container.Unlock() 42 43 if newName, err = daemon.reserveName(container.ID, newName); err != nil { 44 return fmt.Errorf("Error when allocating new name: %v", err) 45 } 46 47 container.Name = newName 48 container.NetworkSettings.IsAnonymousEndpoint = false 49 50 defer func() { 51 if err != nil { 52 container.Name = oldName 53 container.NetworkSettings.IsAnonymousEndpoint = oldIsAnonymousEndpoint 54 daemon.reserveName(container.ID, oldName) 55 daemon.releaseName(newName) 56 } 57 }() 58 59 daemon.releaseName(oldName) 60 if err = container.ToDisk(); err != nil { 61 return err 62 } 63 64 attributes := map[string]string{ 65 "oldName": oldName, 66 } 67 68 if !container.Running { 69 daemon.LogContainerEventWithAttributes(container, "rename", attributes) 70 return nil 71 } 72 73 defer func() { 74 if err != nil { 75 container.Name = oldName 76 container.NetworkSettings.IsAnonymousEndpoint = oldIsAnonymousEndpoint 77 if e := container.ToDisk(); e != nil { 78 logrus.Errorf("%s: Failed in writing to Disk on rename failure: %v", container.ID, e) 79 } 80 } 81 }() 82 83 sid = container.NetworkSettings.SandboxID 84 if daemon.netController != nil { 85 sb, err = daemon.netController.SandboxByID(sid) 86 if err != nil { 87 return err 88 } 89 90 err = sb.Rename(strings.TrimPrefix(container.Name, "/")) 91 if err != nil { 92 return err 93 } 94 } 95 96 daemon.LogContainerEventWithAttributes(container, "rename", attributes) 97 return nil 98 }