github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/container/rename.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package container 18 19 import ( 20 "context" 21 "fmt" 22 "runtime" 23 24 "github.com/containerd/containerd" 25 "github.com/containerd/nerdctl/v2/pkg/api/types" 26 "github.com/containerd/nerdctl/v2/pkg/clientutil" 27 "github.com/containerd/nerdctl/v2/pkg/dnsutil/hostsstore" 28 "github.com/containerd/nerdctl/v2/pkg/idutil/containerwalker" 29 "github.com/containerd/nerdctl/v2/pkg/labels" 30 "github.com/containerd/nerdctl/v2/pkg/namestore" 31 ) 32 33 // Rename change container name to a new name 34 // containerID is container name, short ID, or long ID 35 func Rename(ctx context.Context, client *containerd.Client, containerID, newContainerName string, 36 options types.ContainerRenameOptions) error { 37 dataStore, err := clientutil.DataStore(options.GOptions.DataRoot, options.GOptions.Address) 38 if err != nil { 39 return err 40 } 41 namest, err := namestore.New(dataStore, options.GOptions.Namespace) 42 if err != nil { 43 return err 44 } 45 hostst, err := hostsstore.NewStore(dataStore) 46 if err != nil { 47 return err 48 } 49 walker := &containerwalker.ContainerWalker{ 50 Client: client, 51 OnFound: func(ctx context.Context, found containerwalker.Found) error { 52 if found.MatchCount > 1 { 53 return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req) 54 } 55 return renameContainer(ctx, found.Container, newContainerName, 56 options.GOptions.Namespace, namest, hostst) 57 }, 58 } 59 60 if n, err := walker.Walk(ctx, containerID); err != nil { 61 return err 62 } else if n == 0 { 63 return fmt.Errorf("no such container %s", containerID) 64 } 65 return nil 66 } 67 68 func renameContainer(ctx context.Context, container containerd.Container, newName, ns string, 69 namst namestore.NameStore, hostst hostsstore.Store) error { 70 l, err := container.Labels(ctx) 71 if err != nil { 72 return err 73 } 74 name := l[labels.Name] 75 if err := namst.Rename(name, container.ID(), newName); err != nil { 76 return err 77 } 78 if runtime.GOOS == "linux" { 79 if err := hostst.Update(ns, container.ID(), newName); err != nil { 80 return err 81 } 82 } 83 labels := map[string]string{ 84 labels.Name: newName, 85 } 86 if _, err = container.SetLabels(ctx, labels); err != nil { 87 return err 88 } 89 return nil 90 }