k8s.io/kubernetes@v1.29.3/pkg/kubelet/cm/containermap/container_map.go (about) 1 /* 2 Copyright 2019 The Kubernetes 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 containermap 18 19 import ( 20 "fmt" 21 ) 22 23 // ContainerMap maps (containerID)->(*v1.Pod, *v1.Container) 24 type ContainerMap map[string]struct { 25 podUID string 26 containerName string 27 } 28 29 // NewContainerMap creates a new ContainerMap struct 30 func NewContainerMap() ContainerMap { 31 return make(ContainerMap) 32 } 33 34 // Add adds a mapping of (containerID)->(podUID, containerName) to the ContainerMap 35 func (cm ContainerMap) Add(podUID, containerName, containerID string) { 36 cm[containerID] = struct { 37 podUID string 38 containerName string 39 }{podUID, containerName} 40 } 41 42 // RemoveByContainerID removes a mapping of (containerID)->(podUID, containerName) from the ContainerMap 43 func (cm ContainerMap) RemoveByContainerID(containerID string) { 44 delete(cm, containerID) 45 } 46 47 // RemoveByContainerRef removes a mapping of (containerID)->(podUID, containerName) from the ContainerMap 48 func (cm ContainerMap) RemoveByContainerRef(podUID, containerName string) { 49 containerID, err := cm.GetContainerID(podUID, containerName) 50 if err == nil { 51 cm.RemoveByContainerID(containerID) 52 } 53 } 54 55 // GetContainerID retrieves a ContainerID from the ContainerMap 56 func (cm ContainerMap) GetContainerID(podUID, containerName string) (string, error) { 57 for key, val := range cm { 58 if val.podUID == podUID && val.containerName == containerName { 59 return key, nil 60 } 61 } 62 return "", fmt.Errorf("container %s not in ContainerMap for pod %s", containerName, podUID) 63 } 64 65 // GetContainerRef retrieves a (podUID, containerName) pair from the ContainerMap 66 func (cm ContainerMap) GetContainerRef(containerID string) (string, string, error) { 67 if _, exists := cm[containerID]; !exists { 68 return "", "", fmt.Errorf("containerID %s not in ContainerMap", containerID) 69 } 70 return cm[containerID].podUID, cm[containerID].containerName, nil 71 } 72 73 // Visit invoke visitor function to walks all of the entries in the container map 74 func (cm ContainerMap) Visit(visitor func(podUID, containerName, containerID string)) { 75 for k, v := range cm { 76 visitor(v.podUID, v.containerName, k) 77 } 78 }