跳到主要内容

第二十课

PR #162

Add a PodCache that is responsible for caching pod information

// PodCache contains both a cache of container information, as well as the mechanism for keeping
// that cache up to date.
type PodCache struct {
containerInfo client.ContainerInfo
pods registry.PodRegistry
podInfo map[string]interface{}
period time.Duration
podLock sync.Mutex
}

func NewPodCache(info client.ContainerInfo, pods registry.PodRegistry, period time.Duration) *PodCache {
return &PodCache{
containerInfo: info,
pods: pods,
podInfo: map[string]interface{}{},
period: period,
}
}

// Implements the ContainerInfo interface
// The returned value should be treated as read-only
func (p *PodCache) GetContainerInfo(host, id string) (interface{}, error) {
p.podLock.Lock()
defer p.podLock.Unlock()
value, ok := p.podInfo[id]
if !ok {
return nil, fmt.Errorf("Couldn't find any information for %s", id)
} else {
return value, nil
}
}

回顾

提示

题目:在已有的 PodCache 结构体中,实现一个新的方法,名为 GetPodsInfo(),该方法将返回一个包含所有 Pod 信息的切片([]interface{}),并返回一个错误信息(error)。如果没有找到任何 Pod 信息,返回一个空切片和一个描述性错误。请注意,您需要使用互斥锁(podLock)来确保并发访问安全。

// 在这里实现 GetPodsInfo 方法
func (p *PodCache) GetPodsInfo() ([]interface{}, error) {
// ...
}

要求:

  • 实现 GetPodsInfo() 方法,返回一个包含所有 Pod 信息的切片([]interface{})。
  • 如果没有找到任何 Pod 信息,返回一个空切片和一个描述性错误。
  • 使用互斥锁(podLock)确保并发访问安全。