1/*
2Copyright 2019 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package containermap
18
19import (
20	"fmt"
21)
22
23// ContainerMap maps (containerID)->(*v1.Pod, *v1.Container)
24type ContainerMap map[string]struct {
25	podUID        string
26	containerName string
27}
28
29// NewContainerMap creates a new ContainerMap struct
30func NewContainerMap() ContainerMap {
31	return make(ContainerMap)
32}
33
34// Add adds a mapping of (containerID)->(podUID, containerName) to the ContainerMap
35func (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
43func (cm ContainerMap) RemoveByContainerID(containerID string) {
44	delete(cm, containerID)
45}
46
47// RemoveByContainerRef removes a mapping of (containerID)->(podUID, containerName) from the ContainerMap
48func (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
56func (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
66func (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