github.com/uppal0016/docker_new@v0.0.0-20240123060250-1c98be13ac2c/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 container, err := daemon.GetContainer(oldName) 25 if err != nil { 26 return err 27 } 28 29 oldName = container.Name 30 31 container.Lock() 32 defer container.Unlock() 33 if newName, err = daemon.reserveName(container.ID, newName); err != nil { 34 return fmt.Errorf("Error when allocating new name: %v", err) 35 } 36 37 container.Name = newName 38 39 defer func() { 40 if err != nil { 41 container.Name = oldName 42 daemon.reserveName(container.ID, oldName) 43 daemon.releaseName(newName) 44 } 45 }() 46 47 daemon.releaseName(oldName) 48 if err = container.ToDisk(); err != nil { 49 return err 50 } 51 52 attributes := map[string]string{ 53 "oldName": oldName, 54 } 55 56 if !container.Running { 57 daemon.LogContainerEventWithAttributes(container, "rename", attributes) 58 return nil 59 } 60 61 defer func() { 62 if err != nil { 63 container.Name = oldName 64 if e := container.ToDisk(); e != nil { 65 logrus.Errorf("%s: Failed in writing to Disk on rename failure: %v", container.ID, e) 66 } 67 } 68 }() 69 70 sid = container.NetworkSettings.SandboxID 71 if daemon.netController != nil { 72 sb, err = daemon.netController.SandboxByID(sid) 73 if err != nil { 74 return err 75 } 76 77 err = sb.Rename(strings.TrimPrefix(container.Name, "/")) 78 if err != nil { 79 return err 80 } 81 } 82 83 daemon.LogContainerEventWithAttributes(container, "rename", attributes) 84 return nil 85 }