-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathettus_plugin.go
331 lines (299 loc) · 8.67 KB
/
ettus_plugin.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
// Copyright 2020 Gradiant
// Author: Carlos Giraldo([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
"log"
"github.com/golang/glog"
"golang.org/x/net/context"
"google.golang.org/grpc"
pluginapi "k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1"
)
const (
EttusVendorID = "2500"
EttusNiVendorID = "3923"
B200ProductID = "0020"
B200MiniProductID = "0021"
B205MiniProductID = "0022"
B200NiProductID = "7813"
B210NiProductID = "7814"
)
const (
SysfsDevices = "/sys/bus/usb/devices"
VendorFile = "idVendor"
ProductFile = "idProduct"
DeviceFile = "device"
)
const (
socketName string = "ettusUSRP"
resourceName string = "ettus.com/usrp"
)
type ettusDevice struct {
vid string
pid string
name string
busNum string
devNum string
device pluginapi.Device
}
// etttusManager manages ettus devices
type ettusManager struct {
devices map[string]*ettusDevice
}
func NewEttusManager() (*ettusManager, error) {
return &ettusManager{
devices: make(map[string]*ettusDevice),
}, nil
}
func GetFileContent(file string) (string, error) {
if buf, err := ioutil.ReadFile(file); err != nil {
return "", fmt.Errorf("Can't read file %s", file)
} else {
ret := strings.Trim(string(buf), "\n")
return ret, nil
}
}
func (ettus *ettusManager) discoverEttusResources() (bool, error) {
found := false
ettus.devices = make(map[string]*ettusDevice)
glog.Info("discoverEttusResources")
usbFiles, err := ioutil.ReadDir(SysfsDevices)
if err != nil {
return false, fmt.Errorf("Can't read folder %s", SysfsDevices)
}
for _, usbFile := range usbFiles {
usbID := usbFile.Name()
if strings.Contains(usbID, ":") {
continue
}
fname := path.Join(SysfsDevices, usbID, VendorFile)
vendorID, err := GetFileContent(fname)
if err != nil {
return false, err
}
fname = path.Join(SysfsDevices, usbID, ProductFile)
productID, err := GetFileContent(fname)
if err != nil {
return false, err
}
productName := "Undefined"
if strings.EqualFold(vendorID, EttusVendorID) {
switch productID {
case B200ProductID:
productName = "B200"
case B200MiniProductID:
productName = "B200Mini"
case B205MiniProductID:
productName = "B205Mini"
default:
continue
}
} else if strings.EqualFold(vendorID, EttusNiVendorID) {
switch productID {
case B200NiProductID:
productName = "B200"
case B210NiProductID:
productName = "B210"
default:
continue
}
} else {
continue
}
fname = path.Join(SysfsDevices, usbID, "busnum")
busnum, err := GetFileContent(fname)
if err != nil {
return false, err
}
fname = path.Join(SysfsDevices, usbID, "devnum")
devnum, err := GetFileContent(fname)
if err != nil {
return false, err
}
fname = path.Join(SysfsDevices, usbID, "serial")
serial, err := GetFileContent(fname)
if err != nil {
return false, err
}
healthy := pluginapi.Healthy
dev := ettusDevice{
vid: vendorID,
pid: productID,
name: productName,
busNum: fmt.Sprintf("%03s", busnum),
devNum: fmt.Sprintf("%03s", devnum),
device: pluginapi.Device{
ID: serial,
Health: healthy},
}
ettus.devices[serial] = &dev
found = true
}
log.Printf("Devices: %v \n", ettus.devices)
return found, nil
}
func (ettus *ettusManager) DownloadUhdImages() error {
var out bytes.Buffer
var stderr bytes.Buffer
log.Println("Downloading uhd_images. Be patient")
cmd := exec.Command("uhd_images_downloader")
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
log.Println("Error: CMD uhd_images_downloader: " + fmt.Sprint(err) + ": " + stderr.String())
}
return err
}
func (ettus *ettusManager) Init() error {
glog.Info("Init ettus Manager\n")
err := ettus.DownloadUhdImages()
return err
}
func Register(kubeletEndpoint string, pluginEndpoint, socketName string) error {
conn, err := grpc.Dial(kubeletEndpoint, grpc.WithInsecure(),
grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("unix", addr, timeout)
}))
defer conn.Close()
if err != nil {
return fmt.Errorf("device-plugin: cannot connect to kubelet service: %v", err)
}
client := pluginapi.NewRegistrationClient(conn)
reqt := &pluginapi.RegisterRequest{
Version: pluginapi.Version,
Endpoint: pluginEndpoint,
ResourceName: resourceName,
}
_, err = client.Register(context.Background(), reqt)
if err != nil {
return fmt.Errorf("device-plugin: cannot register to kubelet service: %v", err)
}
return nil
}
// Implements DevicePlugin service functions
func (ettus *ettusManager) ListAndWatch(emtpy *pluginapi.Empty, stream pluginapi.DevicePlugin_ListAndWatchServer) error {
glog.Info("device-plugin: ListAndWatch start\n")
for {
ettus.discoverEttusResources()
resp := new(pluginapi.ListAndWatchResponse)
for _, dev := range ettus.devices {
glog.Info("dev ", dev)
resp.Devices = append(resp.Devices, &dev.device)
}
glog.Info("resp.Devices ", resp.Devices)
if err := stream.Send(resp); err != nil {
glog.Errorf("Failed to send response to kubelet: %v\n", err)
}
time.Sleep(5 * time.Second)
}
return nil
}
func (ettus *ettusManager) Allocate(ctx context.Context, rqt *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {
glog.Info("Allocate")
resp := new(pluginapi.AllocateResponse)
for _, containerRqt := range rqt.ContainerRequests {
containerResp := new(pluginapi.ContainerAllocateResponse)
resp.ContainerResponses = append(resp.ContainerResponses, containerResp)
for _, id := range containerRqt.DevicesIDs {
if dev, ok := ettus.devices[id]; ok {
devPath := path.Join("/dev/bus/usb/", dev.busNum, dev.devNum)
containerResp.Devices = append(containerResp.Devices, &pluginapi.DeviceSpec{
HostPath: devPath,
ContainerPath: devPath,
Permissions: "mrw",
})
containerResp.Mounts = append(containerResp.Mounts, &pluginapi.Mount{
HostPath: "/usr/share/uhd/",
ContainerPath: "/usr/share/uhd/",
ReadOnly: true,
})
}
glog.Info("Allocated interface ", id)
}
}
return resp, nil
}
func (ettus *ettusManager) GetPreferredAllocation(ctx context.Context, rqt *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error) {
return new(pluginapi.PreferredAllocationResponse), nil
}
func (ettus *ettusManager) PreStartContainer(ctx context.Context, rqt *pluginapi.PreStartContainerRequest) (*pluginapi.PreStartContainerResponse, error) {
return nil, fmt.Errorf("PreStartContainer() should not be called")
}
func (ettus *ettusManager) GetDevicePluginOptions(ctx context.Context, empty *pluginapi.Empty) (*pluginapi.DevicePluginOptions, error) {
log.Println("GetDevicePluginOptions: return empty options")
return new(pluginapi.DevicePluginOptions), nil
}
func main() {
flag.Parse()
log.Printf("Starting main \n")
flag.Lookup("logtostderr").Value.Set("true")
ettus, err := NewEttusManager()
if err != nil {
glog.Fatal(err)
os.Exit(1)
}
for {
found, err := ettus.discoverEttusResources()
if err != nil {
glog.Fatal(err)
os.Exit(1)
}
if found {
break
}
glog.Warning("No Ettus are present\n")
time.Sleep(5 * time.Second)
}
err = ettus.Init()
if err != nil {
glog.Errorf("Error downloading uhd images")
}
pluginEndpoint := fmt.Sprintf("%s-%d.sock", socketName, time.Now().Unix())
var wg sync.WaitGroup
wg.Add(1)
// Starts device plugin service.
go func() {
defer wg.Done()
log.Printf("DevicePluginPath %s, pluginEndpoint %s\n", pluginapi.DevicePluginPath, pluginEndpoint)
log.Printf("device-plugin start server at: %s\n", path.Join(pluginapi.DevicePluginPath, pluginEndpoint))
lis, err := net.Listen("unix", path.Join(pluginapi.DevicePluginPath, pluginEndpoint))
if err != nil {
glog.Fatal(err)
return
}
grpcServer := grpc.NewServer()
pluginapi.RegisterDevicePluginServer(grpcServer, ettus)
grpcServer.Serve(lis)
}()
time.Sleep(5 * time.Second)
// Registers with Kubelet.
err = Register(pluginapi.KubeletSocket, pluginEndpoint, resourceName)
if err != nil {
glog.Fatal(err)
}
log.Printf("device-plugin registered\n")
wg.Wait()
}