/
vsock.go
95 lines (86 loc) · 1.92 KB
/
vsock.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
package watch
import (
"fmt"
"math"
"math/rand"
"sync"
virtv1 "kubevirt.io/api/core/v1"
"kubevirt.io/kubevirt/pkg/controller"
)
type randCIDFunc func() uint32
type nextCIDFunc func(uint32) uint32
type cidsMap struct {
mu sync.Mutex
cids map[string]uint32
reverse map[uint32]string
randCID randCIDFunc
nextCID nextCIDFunc
}
func newCIDsMap() *cidsMap {
return &cidsMap{
cids: make(map[string]uint32),
reverse: make(map[uint32]string),
randCID: func() uint32 {
cid := rand.Uint32()
if cid < 3 {
// The guest CID will start from 3
cid += 3
}
return cid
},
nextCID: func(cur uint32) uint32 {
if cur == math.MaxUint32 {
return 3
}
return cur + 1
},
}
}
// Sync loads the allocated CIDs from VMIs.
func (m *cidsMap) Sync(vmis []*virtv1.VirtualMachineInstance) {
m.mu.Lock()
defer m.mu.Unlock()
for _, vmi := range vmis {
if vmi.Status.VSOCKCID == nil {
continue
}
key := controller.VirtualMachineInstanceKey(vmi)
m.cids[key] = *vmi.Status.VSOCKCID
m.reverse[*vmi.Status.VSOCKCID] = key
}
}
// Allocate select a new CID and set it to the status of the given VMI.
func (m *cidsMap) Allocate(vmi *virtv1.VirtualMachineInstance) error {
m.mu.Lock()
defer m.mu.Unlock()
key := controller.VirtualMachineInstanceKey(vmi)
if cid, exist := m.cids[key]; exist {
vmi.Status.VSOCKCID = &cid
return nil
}
start := m.randCID()
assigned := start
for {
if _, exist := m.reverse[assigned]; !exist {
break
}
assigned = m.nextCID(assigned)
if assigned == start {
// Run out of CIDs. Practically this shouldn't happen.
return fmt.Errorf("CIDs exhausted")
}
}
m.cids[key] = assigned
m.reverse[assigned] = key
vmi.Status.VSOCKCID = &assigned
return nil
}
// Remove cleans the CID for given VMI.
func (m *cidsMap) Remove(key string) {
m.mu.Lock()
defer m.mu.Unlock()
if cid, exist := m.cids[key]; exist {
delete(m.reverse, cid)
delete(m.cids, key)
}
}