-
Notifications
You must be signed in to change notification settings - Fork 86
/
daemon_cache.go
102 lines (80 loc) · 2.19 KB
/
daemon_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package manager
import (
"sync"
"github.com/containerd/containerd/log"
"github.com/containerd/nydus-snapshotter/pkg/daemon"
)
// Daemon state cache to speed up access.
type DaemonCache struct {
mu sync.Mutex
idxByDaemonID map[string]*daemon.Daemon // index by ID
}
func newDaemonCache() *DaemonCache {
return &DaemonCache{
idxByDaemonID: make(map[string]*daemon.Daemon),
}
}
// Return nil if the daemon is never inserted or managed,
// otherwise returns the previously inserted daemon pointer.
// Allowing replace an existed daemon since some fields in Daemon can change after restarting nydusd.
func (s *DaemonCache) Add(daemon *daemon.Daemon) *daemon.Daemon {
s.mu.Lock()
defer s.mu.Unlock()
old := s.idxByDaemonID[daemon.ID()]
s.idxByDaemonID[daemon.ID()] = daemon
return old
}
func (s *DaemonCache) removeLocked(d *daemon.Daemon) *daemon.Daemon {
old := s.idxByDaemonID[d.ID()]
delete(s.idxByDaemonID, d.ID())
return old
}
func (s *DaemonCache) Remove(d *daemon.Daemon) *daemon.Daemon {
s.mu.Lock()
old := s.removeLocked(d)
s.mu.Unlock()
return old
}
func (s *DaemonCache) RemoveByDaemonID(id string) *daemon.Daemon {
return s.GetByDaemonID(id, func(d *daemon.Daemon) { s.removeLocked(d) })
}
// Also recover daemon runtime state here
func (s *DaemonCache) Update(d *daemon.Daemon) {
s.mu.Lock()
defer s.mu.Unlock()
log.L.Infof("Recovering daemon ID %s", d.ID())
s.idxByDaemonID[d.ID()] = d
}
func (s *DaemonCache) GetByDaemonID(id string, op func(d *daemon.Daemon)) *daemon.Daemon {
var daemon *daemon.Daemon
s.mu.Lock()
defer s.mu.Unlock()
daemon = s.idxByDaemonID[id]
if daemon != nil && op != nil {
op(daemon)
}
return daemon
}
func (s *DaemonCache) List() []*daemon.Daemon {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.idxByDaemonID) == 0 {
return nil
}
listed := make([]*daemon.Daemon, 0, len(s.idxByDaemonID))
for _, d := range s.idxByDaemonID {
listed = append(listed, d)
}
return listed
}
func (s *DaemonCache) Size() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.idxByDaemonID)
}