container_map.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package containermap
  14. import (
  15. "fmt"
  16. )
  17. // ContainerMap maps (containerID)->(*v1.Pod, *v1.Container)
  18. type ContainerMap map[string]struct {
  19. podUID string
  20. containerName string
  21. }
  22. // NewContainerMap creates a new ContainerMap struct
  23. func NewContainerMap() ContainerMap {
  24. return make(ContainerMap)
  25. }
  26. // Add adds a mapping of (containerID)->(podUID, containerName) to the ContainerMap
  27. func (cm ContainerMap) Add(podUID, containerName, containerID string) {
  28. cm[containerID] = struct {
  29. podUID string
  30. containerName string
  31. }{podUID, containerName}
  32. }
  33. // RemoveByContainerID removes a mapping of (containerID)->(podUID, containerName) from the ContainerMap
  34. func (cm ContainerMap) RemoveByContainerID(containerID string) {
  35. delete(cm, containerID)
  36. }
  37. // RemoveByContainerRef removes a mapping of (containerID)->(podUID, containerName) from the ContainerMap
  38. func (cm ContainerMap) RemoveByContainerRef(podUID, containerName string) {
  39. containerID, err := cm.GetContainerID(podUID, containerName)
  40. if err == nil {
  41. cm.RemoveByContainerID(containerID)
  42. }
  43. }
  44. // GetContainerID retrieves a ContainerID from the ContainerMap
  45. func (cm ContainerMap) GetContainerID(podUID, containerName string) (string, error) {
  46. for key, val := range cm {
  47. if val.podUID == podUID && val.containerName == containerName {
  48. return key, nil
  49. }
  50. }
  51. return "", fmt.Errorf("container %s not in ContainerMap for pod %s", containerName, podUID)
  52. }
  53. // GetContainerRef retrieves a (podUID, containerName) pair from the ContainerMap
  54. func (cm ContainerMap) GetContainerRef(containerID string) (string, string, error) {
  55. if _, exists := cm[containerID]; !exists {
  56. return "", "", fmt.Errorf("containerID %s not in ContainerMap", containerID)
  57. }
  58. return cm[containerID].podUID, cm[containerID].containerName, nil
  59. }