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