manager_test.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package devicemanager
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "reflect"
  20. "testing"
  21. "time"
  22. "github.com/stretchr/testify/assert"
  23. "github.com/stretchr/testify/require"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/api/resource"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/util/sets"
  28. "k8s.io/apimachinery/pkg/util/uuid"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. "k8s.io/client-go/tools/record"
  31. pluginapi "k8s.io/kubernetes/pkg/kubelet/apis/deviceplugin/v1beta1"
  32. watcherapi "k8s.io/kubernetes/pkg/kubelet/apis/pluginregistration/v1"
  33. "k8s.io/kubernetes/pkg/kubelet/checkpointmanager"
  34. "k8s.io/kubernetes/pkg/kubelet/config"
  35. "k8s.io/kubernetes/pkg/kubelet/lifecycle"
  36. "k8s.io/kubernetes/pkg/kubelet/pluginmanager"
  37. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  38. )
  39. const (
  40. testResourceName = "fake-domain/resource"
  41. )
  42. func tmpSocketDir() (socketDir, socketName, pluginSocketName string, err error) {
  43. socketDir, err = ioutil.TempDir("", "device_plugin")
  44. if err != nil {
  45. return
  46. }
  47. socketName = socketDir + "/server.sock"
  48. pluginSocketName = socketDir + "/device-plugin.sock"
  49. os.MkdirAll(socketDir, 0755)
  50. return
  51. }
  52. func TestNewManagerImpl(t *testing.T) {
  53. socketDir, socketName, _, err := tmpSocketDir()
  54. require.NoError(t, err)
  55. defer os.RemoveAll(socketDir)
  56. _, err = newManagerImpl(socketName)
  57. require.NoError(t, err)
  58. os.RemoveAll(socketDir)
  59. }
  60. func TestNewManagerImplStart(t *testing.T) {
  61. socketDir, socketName, pluginSocketName, err := tmpSocketDir()
  62. require.NoError(t, err)
  63. defer os.RemoveAll(socketDir)
  64. m, _, p := setup(t, []*pluginapi.Device{}, func(n string, d []pluginapi.Device) {}, socketName, pluginSocketName)
  65. cleanup(t, m, p)
  66. // Stop should tolerate being called more than once.
  67. cleanup(t, m, p)
  68. }
  69. func TestNewManagerImplStartProbeMode(t *testing.T) {
  70. socketDir, socketName, pluginSocketName, err := tmpSocketDir()
  71. require.NoError(t, err)
  72. defer os.RemoveAll(socketDir)
  73. m, _, p, _ := setupInProbeMode(t, []*pluginapi.Device{}, func(n string, d []pluginapi.Device) {}, socketName, pluginSocketName)
  74. cleanup(t, m, p)
  75. }
  76. // Tests that the device plugin manager correctly handles registration and re-registration by
  77. // making sure that after registration, devices are correctly updated and if a re-registration
  78. // happens, we will NOT delete devices; and no orphaned devices left.
  79. func TestDevicePluginReRegistration(t *testing.T) {
  80. socketDir, socketName, pluginSocketName, err := tmpSocketDir()
  81. require.NoError(t, err)
  82. defer os.RemoveAll(socketDir)
  83. devs := []*pluginapi.Device{
  84. {ID: "Dev1", Health: pluginapi.Healthy},
  85. {ID: "Dev2", Health: pluginapi.Healthy},
  86. }
  87. devsForRegistration := []*pluginapi.Device{
  88. {ID: "Dev3", Health: pluginapi.Healthy},
  89. }
  90. for _, preStartContainerFlag := range []bool{false, true} {
  91. m, ch, p1 := setup(t, devs, nil, socketName, pluginSocketName)
  92. p1.Register(socketName, testResourceName, "")
  93. select {
  94. case <-ch:
  95. case <-time.After(5 * time.Second):
  96. t.Fatalf("timeout while waiting for manager update")
  97. }
  98. capacity, allocatable, _ := m.GetCapacity()
  99. resourceCapacity, _ := capacity[v1.ResourceName(testResourceName)]
  100. resourceAllocatable, _ := allocatable[v1.ResourceName(testResourceName)]
  101. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  102. require.Equal(t, int64(2), resourceAllocatable.Value(), "Devices are not updated.")
  103. p2 := NewDevicePluginStub(devs, pluginSocketName+".new", testResourceName, preStartContainerFlag)
  104. err = p2.Start()
  105. require.NoError(t, err)
  106. p2.Register(socketName, testResourceName, "")
  107. select {
  108. case <-ch:
  109. case <-time.After(5 * time.Second):
  110. t.Fatalf("timeout while waiting for manager update")
  111. }
  112. capacity, allocatable, _ = m.GetCapacity()
  113. resourceCapacity, _ = capacity[v1.ResourceName(testResourceName)]
  114. resourceAllocatable, _ = allocatable[v1.ResourceName(testResourceName)]
  115. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  116. require.Equal(t, int64(2), resourceAllocatable.Value(), "Devices shouldn't change.")
  117. // Test the scenario that a plugin re-registers with different devices.
  118. p3 := NewDevicePluginStub(devsForRegistration, pluginSocketName+".third", testResourceName, preStartContainerFlag)
  119. err = p3.Start()
  120. require.NoError(t, err)
  121. p3.Register(socketName, testResourceName, "")
  122. select {
  123. case <-ch:
  124. case <-time.After(5 * time.Second):
  125. t.Fatalf("timeout while waiting for manager update")
  126. }
  127. capacity, allocatable, _ = m.GetCapacity()
  128. resourceCapacity, _ = capacity[v1.ResourceName(testResourceName)]
  129. resourceAllocatable, _ = allocatable[v1.ResourceName(testResourceName)]
  130. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  131. require.Equal(t, int64(1), resourceAllocatable.Value(), "Devices of plugin previously registered should be removed.")
  132. p2.Stop()
  133. p3.Stop()
  134. cleanup(t, m, p1)
  135. }
  136. }
  137. // Tests that the device plugin manager correctly handles registration and re-registration by
  138. // making sure that after registration, devices are correctly updated and if a re-registration
  139. // happens, we will NOT delete devices; and no orphaned devices left.
  140. // While testing above scenario, plugin discovery and registration will be done using
  141. // Kubelet probe based mechanism
  142. func TestDevicePluginReRegistrationProbeMode(t *testing.T) {
  143. socketDir, socketName, pluginSocketName, err := tmpSocketDir()
  144. require.NoError(t, err)
  145. defer os.RemoveAll(socketDir)
  146. devs := []*pluginapi.Device{
  147. {ID: "Dev1", Health: pluginapi.Healthy},
  148. {ID: "Dev2", Health: pluginapi.Healthy},
  149. }
  150. devsForRegistration := []*pluginapi.Device{
  151. {ID: "Dev3", Health: pluginapi.Healthy},
  152. }
  153. m, ch, p1, _ := setupInProbeMode(t, devs, nil, socketName, pluginSocketName)
  154. // Wait for the first callback to be issued.
  155. select {
  156. case <-ch:
  157. case <-time.After(5 * time.Second):
  158. t.FailNow()
  159. }
  160. capacity, allocatable, _ := m.GetCapacity()
  161. resourceCapacity, _ := capacity[v1.ResourceName(testResourceName)]
  162. resourceAllocatable, _ := allocatable[v1.ResourceName(testResourceName)]
  163. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  164. require.Equal(t, int64(2), resourceAllocatable.Value(), "Devices are not updated.")
  165. p2 := NewDevicePluginStub(devs, pluginSocketName+".new", testResourceName, false)
  166. err = p2.Start()
  167. require.NoError(t, err)
  168. // Wait for the second callback to be issued.
  169. select {
  170. case <-ch:
  171. case <-time.After(5 * time.Second):
  172. t.FailNow()
  173. }
  174. capacity, allocatable, _ = m.GetCapacity()
  175. resourceCapacity, _ = capacity[v1.ResourceName(testResourceName)]
  176. resourceAllocatable, _ = allocatable[v1.ResourceName(testResourceName)]
  177. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  178. require.Equal(t, int64(2), resourceAllocatable.Value(), "Devices are not updated.")
  179. // Test the scenario that a plugin re-registers with different devices.
  180. p3 := NewDevicePluginStub(devsForRegistration, pluginSocketName+".third", testResourceName, false)
  181. err = p3.Start()
  182. require.NoError(t, err)
  183. // Wait for the third callback to be issued.
  184. select {
  185. case <-ch:
  186. case <-time.After(5 * time.Second):
  187. t.FailNow()
  188. }
  189. capacity, allocatable, _ = m.GetCapacity()
  190. resourceCapacity, _ = capacity[v1.ResourceName(testResourceName)]
  191. resourceAllocatable, _ = allocatable[v1.ResourceName(testResourceName)]
  192. require.Equal(t, resourceCapacity.Value(), resourceAllocatable.Value(), "capacity should equal to allocatable")
  193. require.Equal(t, int64(1), resourceAllocatable.Value(), "Devices of previous registered should be removed")
  194. p2.Stop()
  195. p3.Stop()
  196. cleanup(t, m, p1)
  197. }
  198. func setupDeviceManager(t *testing.T, devs []*pluginapi.Device, callback monitorCallback, socketName string) (Manager, <-chan interface{}) {
  199. m, err := newManagerImpl(socketName)
  200. require.NoError(t, err)
  201. updateChan := make(chan interface{})
  202. if callback != nil {
  203. m.callback = callback
  204. }
  205. originalCallback := m.callback
  206. m.callback = func(resourceName string, devices []pluginapi.Device) {
  207. originalCallback(resourceName, devices)
  208. updateChan <- new(interface{})
  209. }
  210. activePods := func() []*v1.Pod {
  211. return []*v1.Pod{}
  212. }
  213. err = m.Start(activePods, &sourcesReadyStub{})
  214. require.NoError(t, err)
  215. return m, updateChan
  216. }
  217. func setupDevicePlugin(t *testing.T, devs []*pluginapi.Device, pluginSocketName string) *Stub {
  218. p := NewDevicePluginStub(devs, pluginSocketName, testResourceName, false)
  219. err := p.Start()
  220. require.NoError(t, err)
  221. return p
  222. }
  223. func setupPluginManager(t *testing.T, pluginSocketName string, m Manager) pluginmanager.PluginManager {
  224. pluginManager := pluginmanager.NewPluginManager(
  225. filepath.Dir(pluginSocketName), /* sockDir */
  226. "", /* deprecatedSockDir */
  227. &record.FakeRecorder{},
  228. )
  229. runPluginManager(pluginManager)
  230. pluginManager.AddHandler(watcherapi.DevicePlugin, m.GetWatcherHandler())
  231. return pluginManager
  232. }
  233. func runPluginManager(pluginManager pluginmanager.PluginManager) {
  234. sourcesReady := config.NewSourcesReady(func(_ sets.String) bool { return true })
  235. go pluginManager.Run(sourcesReady, wait.NeverStop)
  236. }
  237. func setup(t *testing.T, devs []*pluginapi.Device, callback monitorCallback, socketName string, pluginSocketName string) (Manager, <-chan interface{}, *Stub) {
  238. m, updateChan := setupDeviceManager(t, devs, callback, socketName)
  239. p := setupDevicePlugin(t, devs, pluginSocketName)
  240. return m, updateChan, p
  241. }
  242. func setupInProbeMode(t *testing.T, devs []*pluginapi.Device, callback monitorCallback, socketName string, pluginSocketName string) (Manager, <-chan interface{}, *Stub, pluginmanager.PluginManager) {
  243. m, updateChan := setupDeviceManager(t, devs, callback, socketName)
  244. pm := setupPluginManager(t, pluginSocketName, m)
  245. p := setupDevicePlugin(t, devs, pluginSocketName)
  246. return m, updateChan, p, pm
  247. }
  248. func cleanup(t *testing.T, m Manager, p *Stub) {
  249. p.Stop()
  250. m.Stop()
  251. }
  252. func TestUpdateCapacityAllocatable(t *testing.T) {
  253. socketDir, socketName, _, err := tmpSocketDir()
  254. require.NoError(t, err)
  255. defer os.RemoveAll(socketDir)
  256. testManager, err := newManagerImpl(socketName)
  257. as := assert.New(t)
  258. as.NotNil(testManager)
  259. as.Nil(err)
  260. devs := []pluginapi.Device{
  261. {ID: "Device1", Health: pluginapi.Healthy},
  262. {ID: "Device2", Health: pluginapi.Healthy},
  263. {ID: "Device3", Health: pluginapi.Unhealthy},
  264. }
  265. callback := testManager.genericDeviceUpdateCallback
  266. // Adds three devices for resource1, two healthy and one unhealthy.
  267. // Expects capacity for resource1 to be 2.
  268. resourceName1 := "domain1.com/resource1"
  269. e1 := &endpointImpl{}
  270. testManager.endpoints[resourceName1] = endpointInfo{e: e1, opts: nil}
  271. callback(resourceName1, devs)
  272. capacity, allocatable, removedResources := testManager.GetCapacity()
  273. resource1Capacity, ok := capacity[v1.ResourceName(resourceName1)]
  274. as.True(ok)
  275. resource1Allocatable, ok := allocatable[v1.ResourceName(resourceName1)]
  276. as.True(ok)
  277. as.Equal(int64(3), resource1Capacity.Value())
  278. as.Equal(int64(2), resource1Allocatable.Value())
  279. as.Equal(0, len(removedResources))
  280. // Deletes an unhealthy device should NOT change allocatable but change capacity.
  281. devs1 := devs[:len(devs)-1]
  282. callback(resourceName1, devs1)
  283. capacity, allocatable, removedResources = testManager.GetCapacity()
  284. resource1Capacity, ok = capacity[v1.ResourceName(resourceName1)]
  285. as.True(ok)
  286. resource1Allocatable, ok = allocatable[v1.ResourceName(resourceName1)]
  287. as.True(ok)
  288. as.Equal(int64(2), resource1Capacity.Value())
  289. as.Equal(int64(2), resource1Allocatable.Value())
  290. as.Equal(0, len(removedResources))
  291. // Updates a healthy device to unhealthy should reduce allocatable by 1.
  292. devs[1].Health = pluginapi.Unhealthy
  293. callback(resourceName1, devs)
  294. capacity, allocatable, removedResources = testManager.GetCapacity()
  295. resource1Capacity, ok = capacity[v1.ResourceName(resourceName1)]
  296. as.True(ok)
  297. resource1Allocatable, ok = allocatable[v1.ResourceName(resourceName1)]
  298. as.True(ok)
  299. as.Equal(int64(3), resource1Capacity.Value())
  300. as.Equal(int64(1), resource1Allocatable.Value())
  301. as.Equal(0, len(removedResources))
  302. // Deletes a healthy device should reduce capacity and allocatable by 1.
  303. devs2 := devs[1:]
  304. callback(resourceName1, devs2)
  305. capacity, allocatable, removedResources = testManager.GetCapacity()
  306. resource1Capacity, ok = capacity[v1.ResourceName(resourceName1)]
  307. as.True(ok)
  308. resource1Allocatable, ok = allocatable[v1.ResourceName(resourceName1)]
  309. as.True(ok)
  310. as.Equal(int64(0), resource1Allocatable.Value())
  311. as.Equal(int64(2), resource1Capacity.Value())
  312. as.Equal(0, len(removedResources))
  313. // Tests adding another resource.
  314. resourceName2 := "resource2"
  315. e2 := &endpointImpl{}
  316. testManager.endpoints[resourceName2] = endpointInfo{e: e2, opts: nil}
  317. callback(resourceName2, devs)
  318. capacity, allocatable, removedResources = testManager.GetCapacity()
  319. as.Equal(2, len(capacity))
  320. resource2Capacity, ok := capacity[v1.ResourceName(resourceName2)]
  321. as.True(ok)
  322. resource2Allocatable, ok := allocatable[v1.ResourceName(resourceName2)]
  323. as.True(ok)
  324. as.Equal(int64(3), resource2Capacity.Value())
  325. as.Equal(int64(1), resource2Allocatable.Value())
  326. as.Equal(0, len(removedResources))
  327. // Expires resourceName1 endpoint. Verifies testManager.GetCapacity() reports that resourceName1
  328. // is removed from capacity and it no longer exists in healthyDevices after the call.
  329. e1.setStopTime(time.Now().Add(-1*endpointStopGracePeriod - time.Duration(10)*time.Second))
  330. capacity, allocatable, removed := testManager.GetCapacity()
  331. as.Equal([]string{resourceName1}, removed)
  332. _, ok = capacity[v1.ResourceName(resourceName1)]
  333. as.False(ok)
  334. val, ok := capacity[v1.ResourceName(resourceName2)]
  335. as.True(ok)
  336. as.Equal(int64(3), val.Value())
  337. _, ok = testManager.healthyDevices[resourceName1]
  338. as.False(ok)
  339. _, ok = testManager.unhealthyDevices[resourceName1]
  340. as.False(ok)
  341. _, ok = testManager.endpoints[resourceName1]
  342. as.False(ok)
  343. as.Equal(1, len(testManager.endpoints))
  344. // Stops resourceName2 endpoint. Verifies its stopTime is set, allocate and
  345. // preStartContainer calls return errors.
  346. e2.stop()
  347. as.False(e2.stopTime.IsZero())
  348. _, err = e2.allocate([]string{"Device1"})
  349. reflect.DeepEqual(err, fmt.Errorf(errEndpointStopped, e2))
  350. _, err = e2.preStartContainer([]string{"Device1"})
  351. reflect.DeepEqual(err, fmt.Errorf(errEndpointStopped, e2))
  352. // Marks resourceName2 unhealthy and verifies its capacity/allocatable are
  353. // correctly updated.
  354. testManager.markResourceUnhealthy(resourceName2)
  355. capacity, allocatable, removed = testManager.GetCapacity()
  356. val, ok = capacity[v1.ResourceName(resourceName2)]
  357. as.True(ok)
  358. as.Equal(int64(3), val.Value())
  359. val, ok = allocatable[v1.ResourceName(resourceName2)]
  360. as.True(ok)
  361. as.Equal(int64(0), val.Value())
  362. as.Empty(removed)
  363. // Writes and re-reads checkpoints. Verifies we create a stopped endpoint
  364. // for resourceName2, its capacity is set to zero, and we still consider
  365. // it as a DevicePlugin resource. This makes sure any pod that was scheduled
  366. // during the time of propagating capacity change to the scheduler will be
  367. // properly rejected instead of being incorrectly started.
  368. err = testManager.writeCheckpoint()
  369. as.Nil(err)
  370. testManager.healthyDevices = make(map[string]sets.String)
  371. testManager.unhealthyDevices = make(map[string]sets.String)
  372. err = testManager.readCheckpoint()
  373. as.Nil(err)
  374. as.Equal(1, len(testManager.endpoints))
  375. _, ok = testManager.endpoints[resourceName2]
  376. as.True(ok)
  377. capacity, allocatable, removed = testManager.GetCapacity()
  378. val, ok = capacity[v1.ResourceName(resourceName2)]
  379. as.True(ok)
  380. as.Equal(int64(0), val.Value())
  381. as.Empty(removed)
  382. as.True(testManager.isDevicePluginResource(resourceName2))
  383. }
  384. func constructDevices(devices []string) sets.String {
  385. ret := sets.NewString()
  386. for _, dev := range devices {
  387. ret.Insert(dev)
  388. }
  389. return ret
  390. }
  391. func constructAllocResp(devices, mounts, envs map[string]string) *pluginapi.ContainerAllocateResponse {
  392. resp := &pluginapi.ContainerAllocateResponse{}
  393. for k, v := range devices {
  394. resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
  395. HostPath: k,
  396. ContainerPath: v,
  397. Permissions: "mrw",
  398. })
  399. }
  400. for k, v := range mounts {
  401. resp.Mounts = append(resp.Mounts, &pluginapi.Mount{
  402. ContainerPath: k,
  403. HostPath: v,
  404. ReadOnly: true,
  405. })
  406. }
  407. resp.Envs = make(map[string]string)
  408. for k, v := range envs {
  409. resp.Envs[k] = v
  410. }
  411. return resp
  412. }
  413. func TestCheckpoint(t *testing.T) {
  414. resourceName1 := "domain1.com/resource1"
  415. resourceName2 := "domain2.com/resource2"
  416. as := assert.New(t)
  417. tmpDir, err := ioutil.TempDir("", "checkpoint")
  418. as.Nil(err)
  419. ckm, err := checkpointmanager.NewCheckpointManager(tmpDir)
  420. as.Nil(err)
  421. testManager := &ManagerImpl{
  422. endpoints: make(map[string]endpointInfo),
  423. healthyDevices: make(map[string]sets.String),
  424. unhealthyDevices: make(map[string]sets.String),
  425. allocatedDevices: make(map[string]sets.String),
  426. podDevices: make(podDevices),
  427. checkpointManager: ckm,
  428. }
  429. testManager.podDevices.insert("pod1", "con1", resourceName1,
  430. constructDevices([]string{"dev1", "dev2"}),
  431. constructAllocResp(map[string]string{"/dev/r1dev1": "/dev/r1dev1", "/dev/r1dev2": "/dev/r1dev2"},
  432. map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))
  433. testManager.podDevices.insert("pod1", "con1", resourceName2,
  434. constructDevices([]string{"dev1", "dev2"}),
  435. constructAllocResp(map[string]string{"/dev/r2dev1": "/dev/r2dev1", "/dev/r2dev2": "/dev/r2dev2"},
  436. map[string]string{"/home/r2lib1": "/usr/r2lib1"},
  437. map[string]string{"r2devices": "dev1 dev2"}))
  438. testManager.podDevices.insert("pod1", "con2", resourceName1,
  439. constructDevices([]string{"dev3"}),
  440. constructAllocResp(map[string]string{"/dev/r1dev3": "/dev/r1dev3"},
  441. map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))
  442. testManager.podDevices.insert("pod2", "con1", resourceName1,
  443. constructDevices([]string{"dev4"}),
  444. constructAllocResp(map[string]string{"/dev/r1dev4": "/dev/r1dev4"},
  445. map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))
  446. testManager.healthyDevices[resourceName1] = sets.NewString()
  447. testManager.healthyDevices[resourceName1].Insert("dev1")
  448. testManager.healthyDevices[resourceName1].Insert("dev2")
  449. testManager.healthyDevices[resourceName1].Insert("dev3")
  450. testManager.healthyDevices[resourceName1].Insert("dev4")
  451. testManager.healthyDevices[resourceName1].Insert("dev5")
  452. testManager.healthyDevices[resourceName2] = sets.NewString()
  453. testManager.healthyDevices[resourceName2].Insert("dev1")
  454. testManager.healthyDevices[resourceName2].Insert("dev2")
  455. expectedPodDevices := testManager.podDevices
  456. expectedAllocatedDevices := testManager.podDevices.devices()
  457. expectedAllDevices := testManager.healthyDevices
  458. err = testManager.writeCheckpoint()
  459. as.Nil(err)
  460. testManager.podDevices = make(podDevices)
  461. err = testManager.readCheckpoint()
  462. as.Nil(err)
  463. as.Equal(len(expectedPodDevices), len(testManager.podDevices))
  464. for podUID, containerDevices := range expectedPodDevices {
  465. for conName, resources := range containerDevices {
  466. for resource := range resources {
  467. expDevices := expectedPodDevices.containerDevices(podUID, conName, resource)
  468. testDevices := testManager.podDevices.containerDevices(podUID, conName, resource)
  469. as.True(reflect.DeepEqual(expDevices, testDevices))
  470. opts1 := expectedPodDevices.deviceRunContainerOptions(podUID, conName)
  471. opts2 := testManager.podDevices.deviceRunContainerOptions(podUID, conName)
  472. as.Equal(len(opts1.Envs), len(opts2.Envs))
  473. as.Equal(len(opts1.Mounts), len(opts2.Mounts))
  474. as.Equal(len(opts1.Devices), len(opts2.Devices))
  475. }
  476. }
  477. }
  478. as.True(reflect.DeepEqual(expectedAllocatedDevices, testManager.allocatedDevices))
  479. as.True(reflect.DeepEqual(expectedAllDevices, testManager.healthyDevices))
  480. }
  481. type activePodsStub struct {
  482. activePods []*v1.Pod
  483. }
  484. func (a *activePodsStub) getActivePods() []*v1.Pod {
  485. return a.activePods
  486. }
  487. func (a *activePodsStub) updateActivePods(newPods []*v1.Pod) {
  488. a.activePods = newPods
  489. }
  490. type MockEndpoint struct {
  491. allocateFunc func(devs []string) (*pluginapi.AllocateResponse, error)
  492. initChan chan []string
  493. }
  494. func (m *MockEndpoint) stop() {}
  495. func (m *MockEndpoint) run() {}
  496. func (m *MockEndpoint) callback(resourceName string, devices []pluginapi.Device) {}
  497. func (m *MockEndpoint) preStartContainer(devs []string) (*pluginapi.PreStartContainerResponse, error) {
  498. m.initChan <- devs
  499. return &pluginapi.PreStartContainerResponse{}, nil
  500. }
  501. func (m *MockEndpoint) allocate(devs []string) (*pluginapi.AllocateResponse, error) {
  502. if m.allocateFunc != nil {
  503. return m.allocateFunc(devs)
  504. }
  505. return nil, nil
  506. }
  507. func (m *MockEndpoint) isStopped() bool { return false }
  508. func (m *MockEndpoint) stopGracePeriodExpired() bool { return false }
  509. func makePod(limits v1.ResourceList) *v1.Pod {
  510. return &v1.Pod{
  511. ObjectMeta: metav1.ObjectMeta{
  512. UID: uuid.NewUUID(),
  513. },
  514. Spec: v1.PodSpec{
  515. Containers: []v1.Container{
  516. {
  517. Resources: v1.ResourceRequirements{
  518. Limits: limits,
  519. },
  520. },
  521. },
  522. },
  523. }
  524. }
  525. func getTestManager(tmpDir string, activePods ActivePodsFunc, testRes []TestResource) (*ManagerImpl, error) {
  526. monitorCallback := func(resourceName string, devices []pluginapi.Device) {}
  527. ckm, err := checkpointmanager.NewCheckpointManager(tmpDir)
  528. if err != nil {
  529. return nil, err
  530. }
  531. testManager := &ManagerImpl{
  532. socketdir: tmpDir,
  533. callback: monitorCallback,
  534. healthyDevices: make(map[string]sets.String),
  535. unhealthyDevices: make(map[string]sets.String),
  536. allocatedDevices: make(map[string]sets.String),
  537. endpoints: make(map[string]endpointInfo),
  538. podDevices: make(podDevices),
  539. activePods: activePods,
  540. sourcesReady: &sourcesReadyStub{},
  541. checkpointManager: ckm,
  542. }
  543. for _, res := range testRes {
  544. testManager.healthyDevices[res.resourceName] = sets.NewString()
  545. for _, dev := range res.devs {
  546. testManager.healthyDevices[res.resourceName].Insert(dev)
  547. }
  548. if res.resourceName == "domain1.com/resource1" {
  549. testManager.endpoints[res.resourceName] = endpointInfo{
  550. e: &MockEndpoint{allocateFunc: allocateStubFunc()},
  551. opts: nil,
  552. }
  553. }
  554. if res.resourceName == "domain2.com/resource2" {
  555. testManager.endpoints[res.resourceName] = endpointInfo{
  556. e: &MockEndpoint{
  557. allocateFunc: func(devs []string) (*pluginapi.AllocateResponse, error) {
  558. resp := new(pluginapi.ContainerAllocateResponse)
  559. resp.Envs = make(map[string]string)
  560. for _, dev := range devs {
  561. switch dev {
  562. case "dev3":
  563. resp.Envs["key2"] = "val2"
  564. case "dev4":
  565. resp.Envs["key2"] = "val3"
  566. }
  567. }
  568. resps := new(pluginapi.AllocateResponse)
  569. resps.ContainerResponses = append(resps.ContainerResponses, resp)
  570. return resps, nil
  571. },
  572. },
  573. opts: nil,
  574. }
  575. }
  576. }
  577. return testManager, nil
  578. }
  579. func getTestNodeInfo(allocatable v1.ResourceList) *schedulernodeinfo.NodeInfo {
  580. cachedNode := &v1.Node{
  581. Status: v1.NodeStatus{
  582. Allocatable: allocatable,
  583. },
  584. }
  585. nodeInfo := &schedulernodeinfo.NodeInfo{}
  586. nodeInfo.SetNode(cachedNode)
  587. return nodeInfo
  588. }
  589. type TestResource struct {
  590. resourceName string
  591. resourceQuantity resource.Quantity
  592. devs []string
  593. }
  594. func TestPodContainerDeviceAllocation(t *testing.T) {
  595. res1 := TestResource{
  596. resourceName: "domain1.com/resource1",
  597. resourceQuantity: *resource.NewQuantity(int64(2), resource.DecimalSI),
  598. devs: []string{"dev1", "dev2"},
  599. }
  600. res2 := TestResource{
  601. resourceName: "domain2.com/resource2",
  602. resourceQuantity: *resource.NewQuantity(int64(1), resource.DecimalSI),
  603. devs: []string{"dev3", "dev4"},
  604. }
  605. testResources := make([]TestResource, 2)
  606. testResources = append(testResources, res1)
  607. testResources = append(testResources, res2)
  608. as := require.New(t)
  609. podsStub := activePodsStub{
  610. activePods: []*v1.Pod{},
  611. }
  612. tmpDir, err := ioutil.TempDir("", "checkpoint")
  613. as.Nil(err)
  614. defer os.RemoveAll(tmpDir)
  615. nodeInfo := getTestNodeInfo(v1.ResourceList{})
  616. testManager, err := getTestManager(tmpDir, podsStub.getActivePods, testResources)
  617. as.Nil(err)
  618. testPods := []*v1.Pod{
  619. makePod(v1.ResourceList{
  620. v1.ResourceName(res1.resourceName): res1.resourceQuantity,
  621. v1.ResourceName("cpu"): res1.resourceQuantity,
  622. v1.ResourceName(res2.resourceName): res2.resourceQuantity}),
  623. makePod(v1.ResourceList{
  624. v1.ResourceName(res1.resourceName): res2.resourceQuantity}),
  625. makePod(v1.ResourceList{
  626. v1.ResourceName(res2.resourceName): res2.resourceQuantity}),
  627. }
  628. testCases := []struct {
  629. description string
  630. testPod *v1.Pod
  631. expectedContainerOptsLen []int
  632. expectedAllocatedResName1 int
  633. expectedAllocatedResName2 int
  634. expErr error
  635. }{
  636. {
  637. description: "Successful allocation of two Res1 resources and one Res2 resource",
  638. testPod: testPods[0],
  639. expectedContainerOptsLen: []int{3, 2, 2},
  640. expectedAllocatedResName1: 2,
  641. expectedAllocatedResName2: 1,
  642. expErr: nil,
  643. },
  644. {
  645. description: "Requesting to create a pod without enough resources should fail",
  646. testPod: testPods[1],
  647. expectedContainerOptsLen: nil,
  648. expectedAllocatedResName1: 2,
  649. expectedAllocatedResName2: 1,
  650. expErr: fmt.Errorf("requested number of devices unavailable for domain1.com/resource1. Requested: 1, Available: 0"),
  651. },
  652. {
  653. description: "Successful allocation of all available Res1 resources and Res2 resources",
  654. testPod: testPods[2],
  655. expectedContainerOptsLen: []int{0, 0, 1},
  656. expectedAllocatedResName1: 2,
  657. expectedAllocatedResName2: 2,
  658. expErr: nil,
  659. },
  660. }
  661. activePods := []*v1.Pod{}
  662. for _, testCase := range testCases {
  663. pod := testCase.testPod
  664. activePods = append(activePods, pod)
  665. podsStub.updateActivePods(activePods)
  666. err := testManager.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: pod})
  667. if !reflect.DeepEqual(err, testCase.expErr) {
  668. t.Errorf("DevicePluginManager error (%v). expected error: %v but got: %v",
  669. testCase.description, testCase.expErr, err)
  670. }
  671. runContainerOpts, err := testManager.GetDeviceRunContainerOptions(pod, &pod.Spec.Containers[0])
  672. as.Nil(err)
  673. if testCase.expectedContainerOptsLen == nil {
  674. as.Nil(runContainerOpts)
  675. } else {
  676. as.Equal(len(runContainerOpts.Devices), testCase.expectedContainerOptsLen[0])
  677. as.Equal(len(runContainerOpts.Mounts), testCase.expectedContainerOptsLen[1])
  678. as.Equal(len(runContainerOpts.Envs), testCase.expectedContainerOptsLen[2])
  679. }
  680. as.Equal(testCase.expectedAllocatedResName1, testManager.allocatedDevices[res1.resourceName].Len())
  681. as.Equal(testCase.expectedAllocatedResName2, testManager.allocatedDevices[res2.resourceName].Len())
  682. }
  683. }
  684. func TestInitContainerDeviceAllocation(t *testing.T) {
  685. // Requesting to create a pod that requests resourceName1 in init containers and normal containers
  686. // should succeed with devices allocated to init containers reallocated to normal containers.
  687. res1 := TestResource{
  688. resourceName: "domain1.com/resource1",
  689. resourceQuantity: *resource.NewQuantity(int64(2), resource.DecimalSI),
  690. devs: []string{"dev1", "dev2"},
  691. }
  692. res2 := TestResource{
  693. resourceName: "domain2.com/resource2",
  694. resourceQuantity: *resource.NewQuantity(int64(1), resource.DecimalSI),
  695. devs: []string{"dev3", "dev4"},
  696. }
  697. testResources := make([]TestResource, 2)
  698. testResources = append(testResources, res1)
  699. testResources = append(testResources, res2)
  700. as := require.New(t)
  701. podsStub := activePodsStub{
  702. activePods: []*v1.Pod{},
  703. }
  704. nodeInfo := getTestNodeInfo(v1.ResourceList{})
  705. tmpDir, err := ioutil.TempDir("", "checkpoint")
  706. as.Nil(err)
  707. defer os.RemoveAll(tmpDir)
  708. testManager, err := getTestManager(tmpDir, podsStub.getActivePods, testResources)
  709. as.Nil(err)
  710. podWithPluginResourcesInInitContainers := &v1.Pod{
  711. ObjectMeta: metav1.ObjectMeta{
  712. UID: uuid.NewUUID(),
  713. },
  714. Spec: v1.PodSpec{
  715. InitContainers: []v1.Container{
  716. {
  717. Name: string(uuid.NewUUID()),
  718. Resources: v1.ResourceRequirements{
  719. Limits: v1.ResourceList{
  720. v1.ResourceName(res1.resourceName): res2.resourceQuantity,
  721. },
  722. },
  723. },
  724. {
  725. Name: string(uuid.NewUUID()),
  726. Resources: v1.ResourceRequirements{
  727. Limits: v1.ResourceList{
  728. v1.ResourceName(res1.resourceName): res1.resourceQuantity,
  729. },
  730. },
  731. },
  732. },
  733. Containers: []v1.Container{
  734. {
  735. Name: string(uuid.NewUUID()),
  736. Resources: v1.ResourceRequirements{
  737. Limits: v1.ResourceList{
  738. v1.ResourceName(res1.resourceName): res2.resourceQuantity,
  739. v1.ResourceName(res2.resourceName): res2.resourceQuantity,
  740. },
  741. },
  742. },
  743. {
  744. Name: string(uuid.NewUUID()),
  745. Resources: v1.ResourceRequirements{
  746. Limits: v1.ResourceList{
  747. v1.ResourceName(res1.resourceName): res2.resourceQuantity,
  748. v1.ResourceName(res2.resourceName): res2.resourceQuantity,
  749. },
  750. },
  751. },
  752. },
  753. },
  754. }
  755. podsStub.updateActivePods([]*v1.Pod{podWithPluginResourcesInInitContainers})
  756. err = testManager.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: podWithPluginResourcesInInitContainers})
  757. as.Nil(err)
  758. podUID := string(podWithPluginResourcesInInitContainers.UID)
  759. initCont1 := podWithPluginResourcesInInitContainers.Spec.InitContainers[0].Name
  760. initCont2 := podWithPluginResourcesInInitContainers.Spec.InitContainers[1].Name
  761. normalCont1 := podWithPluginResourcesInInitContainers.Spec.Containers[0].Name
  762. normalCont2 := podWithPluginResourcesInInitContainers.Spec.Containers[1].Name
  763. initCont1Devices := testManager.podDevices.containerDevices(podUID, initCont1, res1.resourceName)
  764. initCont2Devices := testManager.podDevices.containerDevices(podUID, initCont2, res1.resourceName)
  765. normalCont1Devices := testManager.podDevices.containerDevices(podUID, normalCont1, res1.resourceName)
  766. normalCont2Devices := testManager.podDevices.containerDevices(podUID, normalCont2, res1.resourceName)
  767. as.Equal(1, initCont1Devices.Len())
  768. as.Equal(2, initCont2Devices.Len())
  769. as.Equal(1, normalCont1Devices.Len())
  770. as.Equal(1, normalCont2Devices.Len())
  771. as.True(initCont2Devices.IsSuperset(initCont1Devices))
  772. as.True(initCont2Devices.IsSuperset(normalCont1Devices))
  773. as.True(initCont2Devices.IsSuperset(normalCont2Devices))
  774. as.Equal(0, normalCont1Devices.Intersection(normalCont2Devices).Len())
  775. }
  776. func TestSanitizeNodeAllocatable(t *testing.T) {
  777. resourceName1 := "domain1.com/resource1"
  778. devID1 := "dev1"
  779. resourceName2 := "domain2.com/resource2"
  780. devID2 := "dev2"
  781. as := assert.New(t)
  782. monitorCallback := func(resourceName string, devices []pluginapi.Device) {}
  783. tmpDir, err := ioutil.TempDir("", "checkpoint")
  784. as.Nil(err)
  785. ckm, err := checkpointmanager.NewCheckpointManager(tmpDir)
  786. as.Nil(err)
  787. testManager := &ManagerImpl{
  788. callback: monitorCallback,
  789. allocatedDevices: make(map[string]sets.String),
  790. healthyDevices: make(map[string]sets.String),
  791. podDevices: make(podDevices),
  792. checkpointManager: ckm,
  793. }
  794. // require one of resource1 and one of resource2
  795. testManager.allocatedDevices[resourceName1] = sets.NewString()
  796. testManager.allocatedDevices[resourceName1].Insert(devID1)
  797. testManager.allocatedDevices[resourceName2] = sets.NewString()
  798. testManager.allocatedDevices[resourceName2].Insert(devID2)
  799. cachedNode := &v1.Node{
  800. Status: v1.NodeStatus{
  801. Allocatable: v1.ResourceList{
  802. // has no resource1 and two of resource2
  803. v1.ResourceName(resourceName2): *resource.NewQuantity(int64(2), resource.DecimalSI),
  804. },
  805. },
  806. }
  807. nodeInfo := &schedulernodeinfo.NodeInfo{}
  808. nodeInfo.SetNode(cachedNode)
  809. testManager.sanitizeNodeAllocatable(nodeInfo)
  810. allocatableScalarResources := nodeInfo.AllocatableResource().ScalarResources
  811. // allocatable in nodeInfo is less than needed, should update
  812. as.Equal(1, int(allocatableScalarResources[v1.ResourceName(resourceName1)]))
  813. // allocatable in nodeInfo is more than needed, should skip updating
  814. as.Equal(2, int(allocatableScalarResources[v1.ResourceName(resourceName2)]))
  815. }
  816. func TestDevicePreStartContainer(t *testing.T) {
  817. // Ensures that if device manager is indicated to invoke `PreStartContainer` RPC
  818. // by device plugin, then device manager invokes PreStartContainer at endpoint interface.
  819. // Also verifies that final allocation of mounts, envs etc is same as expected.
  820. res1 := TestResource{
  821. resourceName: "domain1.com/resource1",
  822. resourceQuantity: *resource.NewQuantity(int64(2), resource.DecimalSI),
  823. devs: []string{"dev1", "dev2"},
  824. }
  825. as := require.New(t)
  826. podsStub := activePodsStub{
  827. activePods: []*v1.Pod{},
  828. }
  829. tmpDir, err := ioutil.TempDir("", "checkpoint")
  830. as.Nil(err)
  831. defer os.RemoveAll(tmpDir)
  832. nodeInfo := getTestNodeInfo(v1.ResourceList{})
  833. testManager, err := getTestManager(tmpDir, podsStub.getActivePods, []TestResource{res1})
  834. as.Nil(err)
  835. ch := make(chan []string, 1)
  836. testManager.endpoints[res1.resourceName] = endpointInfo{
  837. e: &MockEndpoint{
  838. initChan: ch,
  839. allocateFunc: allocateStubFunc(),
  840. },
  841. opts: &pluginapi.DevicePluginOptions{PreStartRequired: true},
  842. }
  843. pod := makePod(v1.ResourceList{
  844. v1.ResourceName(res1.resourceName): res1.resourceQuantity})
  845. activePods := []*v1.Pod{}
  846. activePods = append(activePods, pod)
  847. podsStub.updateActivePods(activePods)
  848. err = testManager.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: pod})
  849. as.Nil(err)
  850. runContainerOpts, err := testManager.GetDeviceRunContainerOptions(pod, &pod.Spec.Containers[0])
  851. as.Nil(err)
  852. var initializedDevs []string
  853. select {
  854. case <-time.After(time.Second):
  855. t.Fatalf("Timed out while waiting on channel for response from PreStartContainer RPC stub")
  856. case initializedDevs = <-ch:
  857. break
  858. }
  859. as.Contains(initializedDevs, "dev1")
  860. as.Contains(initializedDevs, "dev2")
  861. as.Equal(len(initializedDevs), len(res1.devs))
  862. expectedResps, err := allocateStubFunc()([]string{"dev1", "dev2"})
  863. as.Nil(err)
  864. as.Equal(1, len(expectedResps.ContainerResponses))
  865. expectedResp := expectedResps.ContainerResponses[0]
  866. as.Equal(len(runContainerOpts.Devices), len(expectedResp.Devices))
  867. as.Equal(len(runContainerOpts.Mounts), len(expectedResp.Mounts))
  868. as.Equal(len(runContainerOpts.Envs), len(expectedResp.Envs))
  869. }
  870. func TestResetExtendedResource(t *testing.T) {
  871. as := assert.New(t)
  872. tmpDir, err := ioutil.TempDir("", "checkpoint")
  873. as.Nil(err)
  874. ckm, err := checkpointmanager.NewCheckpointManager(tmpDir)
  875. as.Nil(err)
  876. testManager := &ManagerImpl{
  877. endpoints: make(map[string]endpointInfo),
  878. healthyDevices: make(map[string]sets.String),
  879. unhealthyDevices: make(map[string]sets.String),
  880. allocatedDevices: make(map[string]sets.String),
  881. podDevices: make(podDevices),
  882. checkpointManager: ckm,
  883. }
  884. extendedResourceName := "domain.com/resource"
  885. testManager.podDevices.insert("pod", "con", extendedResourceName,
  886. constructDevices([]string{"dev1"}),
  887. constructAllocResp(map[string]string{"/dev/dev1": "/dev/dev1"},
  888. map[string]string{"/home/lib1": "/usr/lib1"}, map[string]string{}))
  889. testManager.healthyDevices[extendedResourceName] = sets.NewString()
  890. testManager.healthyDevices[extendedResourceName].Insert("dev1")
  891. // checkpoint is present, indicating node hasn't been recreated
  892. err = testManager.writeCheckpoint()
  893. as.Nil(err)
  894. as.False(testManager.ShouldResetExtendedResourceCapacity())
  895. // checkpoint is absent, representing node recreation
  896. ckpts, err := ckm.ListCheckpoints()
  897. as.Nil(err)
  898. for _, ckpt := range ckpts {
  899. err = ckm.RemoveCheckpoint(ckpt)
  900. as.Nil(err)
  901. }
  902. as.True(testManager.ShouldResetExtendedResourceCapacity())
  903. }
  904. func allocateStubFunc() func(devs []string) (*pluginapi.AllocateResponse, error) {
  905. return func(devs []string) (*pluginapi.AllocateResponse, error) {
  906. resp := new(pluginapi.ContainerAllocateResponse)
  907. resp.Envs = make(map[string]string)
  908. for _, dev := range devs {
  909. switch dev {
  910. case "dev1":
  911. resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
  912. ContainerPath: "/dev/aaa",
  913. HostPath: "/dev/aaa",
  914. Permissions: "mrw",
  915. })
  916. resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
  917. ContainerPath: "/dev/bbb",
  918. HostPath: "/dev/bbb",
  919. Permissions: "mrw",
  920. })
  921. resp.Mounts = append(resp.Mounts, &pluginapi.Mount{
  922. ContainerPath: "/container_dir1/file1",
  923. HostPath: "host_dir1/file1",
  924. ReadOnly: true,
  925. })
  926. case "dev2":
  927. resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
  928. ContainerPath: "/dev/ccc",
  929. HostPath: "/dev/ccc",
  930. Permissions: "mrw",
  931. })
  932. resp.Mounts = append(resp.Mounts, &pluginapi.Mount{
  933. ContainerPath: "/container_dir1/file2",
  934. HostPath: "host_dir1/file2",
  935. ReadOnly: true,
  936. })
  937. resp.Envs["key1"] = "val1"
  938. }
  939. }
  940. resps := new(pluginapi.AllocateResponse)
  941. resps.ContainerResponses = append(resps.ContainerResponses, resp)
  942. return resps, nil
  943. }
  944. }