-
Notifications
You must be signed in to change notification settings - Fork 0
/
pod.go
358 lines (322 loc) · 9.67 KB
/
pod.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package nicmonitor
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/corigine/nic-monitor/pkg/nfp"
"github.com/corigine/nic-monitor/pkg/util"
"github.com/k8snetworkplumbingwg/sriovnet"
"github.com/vishvananda/netlink"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
internalapi "k8s.io/cri-api/pkg/apis"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/kubelet/cri/remote"
)
type vfRepInfo struct {
name string
vfindex int
pci string
}
type podInfo struct {
namespace string
vfReps []vfRepInfo
ifName string
nsPath string
}
var podRwlock sync.RWMutex
var podToVfIndexMap map[string]podInfo = make(map[string]podInfo)
var switchIdtoPci map[string]string = make(map[string]string)
var defaultTimeout = 2 * time.Second
var defaultRuntimeEndpoints = []string{"unix:///run/containerd/containerd.sock", "unix:///var/run/dockershim.sock", "unix:///run/crio/crio.sock", "unix:///var/run/cri-dockerd.sock"}
//var pciDeviceRegex = regexp.MustCompile(`^[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.\d{1}`)
// Regex that matches on VF representor port name
var vfPortRepRegex = regexp.MustCompile(`^(?:c\d+)?pf(\d+)vf(\d+)$`)
func parseIndexFromPhysPortName(portName string, regex *regexp.Regexp) (pfRepIndex, vfRepIndex int, err error) {
pfRepIndex = -1
vfRepIndex = -1
matches := regex.FindStringSubmatch(portName)
//nolint:gomnd
if len(matches) != 3 {
err = fmt.Errorf("failed to parse portName %s", portName)
} else {
pfRepIndex, err = strconv.Atoi(matches[1])
if err == nil {
vfRepIndex, err = strconv.Atoi(matches[2])
}
}
return pfRepIndex, vfRepIndex, err
}
func parsePortName(physPortName string) (pfRepIndex, vfRepIndex int, err error) {
// old kernel syntax of phys_port_name is vf index
physPortName = strings.TrimSpace(physPortName)
physPortNameInt, err := strconv.Atoi(physPortName)
if err == nil {
vfRepIndex = physPortNameInt
} else {
pfRepIndex, vfRepIndex, err = parseIndexFromPhysPortName(physPortName, vfPortRepRegex)
}
return pfRepIndex, vfRepIndex, err
}
func getSriovRepInfo(ifname string) *vfRepInfo {
var rep vfRepInfo
devicePortNameFile := filepath.Join(nfp.NetSysDir, ifname, nfp.NetdevPhysPortName)
physPortName, err := os.ReadFile(devicePortNameFile)
if err != nil {
return nil
}
rep.name = ifname
_, vfindex, err := parsePortName(strings.TrimSpace(string(physPortName)))
if err != nil {
klog.Errorf("Parese phy port name error for %s", ifname)
return nil
}
rep.vfindex = vfindex
swIDFile := filepath.Join(nfp.NetSysDir, ifname, "phys_switch_id")
physSwitchID, err := os.ReadFile(swIDFile)
if err != nil {
klog.Errorf("Can not get the switchid for %s", ifname)
return nil
}
pci, ok := switchIdtoPci[strings.TrimSpace(string(physSwitchID))]
if !ok {
klog.Errorf("Can not get pci for %s", ifname)
return nil
}
rep.pci = pci
return &rep
}
func getSriovInfo(sandboxId string, info *podInfo) bool {
var ifname string
if os.Getenv("CNI_VENDOR") == "FABRIC" {
ifname = strings.Replace(sandboxId, ":", "", -1)
} else {
ifname = fmt.Sprintf("%s_h", sandboxId[0:12])
}
info.ifName = ifname
devlink, err := netlink.LinkByName(ifname)
if err != nil {
klog.Errorf("Get dev %s netlink info error:%v", ifname, err)
return false
}
if devlink.Type() == "bond" {
slaveDevs := util.GetBondSlave(ifname)
for _, slave := range slaveDevs {
rep := getSriovRepInfo(slave)
if rep != nil {
info.vfReps = append(info.vfReps, *rep)
}
}
} else {
rep := getSriovRepInfo(ifname)
if rep != nil {
info.vfReps = append(info.vfReps, *rep)
}
}
if len(info.vfReps) != 0 {
return true
}
return false
}
func getPodInfo(containerId string) (map[string]interface{}, error) {
var rs internalapi.RuntimeService
var err error
for _, endPoint := range defaultRuntimeEndpoints {
rs, err = remote.NewRemoteRuntimeService(endPoint, defaultTimeout, nil)
if err != nil {
klog.Errorf("Connect using endpoint %q error:%v", endPoint, err)
continue
}
break
}
if rs == nil {
return nil, fmt.Errorf("Can not connect the the docker runtime service")
}
rep, err := rs.ContainerStatus(context.TODO(), containerId, true)
if err != nil {
return nil, fmt.Errorf("Can not get container %s from cri runtime:%v", containerId, err)
}
result := make(map[string]interface{})
if json.Unmarshal([]byte(rep.Info["info"]), &result) != nil {
return nil, fmt.Errorf("Can not get info for %s", containerId)
}
return result, nil
}
func getPodSandboxId(info map[string]interface{}) (string, error) {
sandboxId, ok := info["sandboxID"].(string)
if !ok {
return "", fmt.Errorf("Can not get sandboxID")
}
return sandboxId, nil
}
func getPodNs(info map[string]interface{}) (string, error) {
runtimeSpec, ok := info["runtimeSpec"].(map[string]interface{})
if !ok {
return "", fmt.Errorf("Can not get runtimeSpec")
}
linux, ok := runtimeSpec["linux"].(map[string]interface{})
if !ok {
return "", fmt.Errorf("Can not get linux info")
}
namespace, ok := linux["namespaces"].([]interface{})
if !ok {
return "", fmt.Errorf("Can not get namespaces")
}
for _, value := range namespace {
nsInfo := value.(map[string]interface{})
nsType, ok := nsInfo["type"]
if !ok {
continue
}
if nsType != "network" {
continue
}
nsPath, ok := nsInfo["path"].(string)
if !ok {
return "", fmt.Errorf("Can not get network namespace path")
}
return strings.TrimSpace(nsPath), nil
}
return "", fmt.Errorf("Can not find network namespace path")
}
func processPodUpdate(old, obj interface{}) {
defer utilruntime.HandleCrash()
if obj.(*v1.Pod).Status.Phase != v1.PodRunning ||
old.(*v1.Pod).Status.Phase == v1.PodRunning {
return
}
podRwlock.Lock()
defer podRwlock.Unlock()
info := podInfo{}
for _, cs := range obj.(*v1.Pod).Status.ContainerStatuses {
var ifname string
podinfo, err := getPodInfo(strings.Split(cs.ContainerID, "//")[1])
if err != nil {
klog.Errorf("Can not get the pod info for %s", obj.(*v1.Pod).Name, err)
}
if os.Getenv("CNI_VENDOR") == "FABRIC" {
var ok bool
info.nsPath, err = getPodNs(podinfo)
if err != nil {
klog.Errorf("Get pod %s ns error %v:", obj.(*v1.Pod).Name, err)
}
ifname, ok = obj.(*v1.Pod).Annotations["kubernetes.customized/fabric-mac"]
if !ok {
klog.Infof("Process pod %s update error: no kubernetes.customized/fabric-mac label", obj.(*v1.Pod).Name)
return
}
} else {
ifname, err = getPodSandboxId(podinfo)
if err != nil {
klog.Infof("Process pod %s update error: %v", obj.(*v1.Pod).Name, err)
continue
}
}
if getSriovInfo(ifname, &info) == true {
info.namespace = obj.(*v1.Pod).Namespace
podToVfIndexMap[obj.(*v1.Pod).Name] = info
klog.Infof("Process pod %s update %v", obj.(*v1.Pod).Name, info)
}
updatePodStateByNicState(info, obj.(*v1.Pod).Name)
}
}
func processPodAdd(obj interface{}) {
defer utilruntime.HandleCrash()
if obj.(*v1.Pod).Status.Phase != v1.PodRunning {
return
}
fmt.Println(obj.(*v1.Pod).Name)
podRwlock.Lock()
defer podRwlock.Unlock()
info := podInfo{}
for _, cs := range obj.(*v1.Pod).Status.ContainerStatuses {
var ifname string
podinfo, err := getPodInfo(strings.Split(cs.ContainerID, "//")[1])
if err != nil {
klog.Errorf("Can not get the pod info for %s", obj.(*v1.Pod).Name, err)
return
}
if os.Getenv("CNI_VENDOR") == "FABRIC" {
var ok bool
info.nsPath, err = getPodNs(podinfo)
if err != nil {
klog.Errorf("Get pod %s ns error %v:", obj.(*v1.Pod).Name, err)
}
ifname, ok = obj.(*v1.Pod).Annotations["kubernetes.customized/fabric-mac"]
if !ok {
klog.Infof("Process pod %s add error: no kubernetes.customized/fabric-mac label", obj.(*v1.Pod).Name)
return
}
} else {
ifname, err = getPodSandboxId(podinfo)
if err != nil {
klog.Infof("Process pod %s update error: %v", obj.(*v1.Pod).Name, err)
continue
}
}
if getSriovInfo(ifname, &info) == true {
info.namespace = obj.(*v1.Pod).Namespace
podToVfIndexMap[obj.(*v1.Pod).Name] = info
klog.Infof("Process pod %s add %v", obj.(*v1.Pod).Name, info)
}
updatePodStateByNicState(info, obj.(*v1.Pod).Name)
}
}
func processPodDelete(obj interface{}) {
podRwlock.Lock()
defer podRwlock.Unlock()
podName := obj.(*v1.Pod).Name
delete(podToVfIndexMap, podName)
klog.Infof("Process pod %s delete", podName)
}
func startUpdatePodInfoFromK8s(client *kubernetes.Clientset, stopCh chan struct{}) {
labelOptions := informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
opts.FieldSelector = fmt.Sprintf("spec.nodeName=%s", os.Getenv("NODE_NAME"))
})
sharedInformers := informers.NewSharedInformerFactoryWithOptions(client, 0, labelOptions)
informer := sharedInformers.Core().V1().Pods().Informer()
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: processPodAdd,
UpdateFunc: processPodUpdate,
DeleteFunc: processPodDelete,
})
informer.Run(stopCh)
}
func getSwitchIdByPci(pci string) (string, error) {
netDevs, _ := sriovnet.GetNetDevicesFromPci(pci)
for _, netDev := range netDevs {
swIDFile := filepath.Join(nfp.NetSysDir, netDev, "phys_switch_id")
physSwitchID, err := os.ReadFile(swIDFile)
if err != nil || len(physSwitchID) == 0 {
continue
}
return strings.TrimSpace(string(physSwitchID)), nil
}
return "nil", fmt.Errorf("nic not ready")
}
func init() {
/*Wait for all nfp card ready!!!*/
pciDevice := nfp.GetCorigineNicDevice()
for _, pci := range pciDevice {
for true {
physSwitchID, err := getSwitchIdByPci(pci)
if err != nil {
time.Sleep(1 * time.Second)
continue
}
switchIdtoPci[physSwitchID] = pci
break
}
}
}