reconciler_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. Copyright 2019 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 reconciler
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/require"
  21. "k8s.io/apimachinery/pkg/util/wait"
  22. "k8s.io/client-go/tools/record"
  23. registerapi "k8s.io/kubelet/pkg/apis/pluginregistration/v1"
  24. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache"
  25. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/operationexecutor"
  26. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/pluginwatcher"
  27. )
  28. const (
  29. // reconcilerLoopSleepDuration is the amount of time the reconciler loop
  30. // waits between successive executions
  31. reconcilerLoopSleepDuration time.Duration = 1 * time.Nanosecond
  32. )
  33. var (
  34. socketDir string
  35. supportedVersions = []string{"v1beta1", "v1beta2"}
  36. )
  37. func init() {
  38. d, err := ioutil.TempDir("", "reconciler_test")
  39. if err != nil {
  40. panic(fmt.Sprintf("Could not create a temp directory: %s", d))
  41. }
  42. socketDir = d
  43. }
  44. func cleanup(t *testing.T) {
  45. require.NoError(t, os.RemoveAll(socketDir))
  46. os.MkdirAll(socketDir, 0755)
  47. }
  48. func runReconciler(reconciler Reconciler) {
  49. go reconciler.Run(wait.NeverStop)
  50. }
  51. func waitForRegistration(
  52. t *testing.T,
  53. socketPath string,
  54. previousTimestamp time.Time,
  55. asw cache.ActualStateOfWorld) {
  56. err := retryWithExponentialBackOff(
  57. time.Duration(500*time.Millisecond),
  58. func() (bool, error) {
  59. registeredPlugins := asw.GetRegisteredPlugins()
  60. for _, plugin := range registeredPlugins {
  61. if plugin.SocketPath == socketPath && plugin.Timestamp.After(previousTimestamp) {
  62. return true, nil
  63. }
  64. }
  65. return false, nil
  66. },
  67. )
  68. if err != nil {
  69. t.Fatalf("Timed out waiting for plugin to be registered:\n%s.", socketPath)
  70. }
  71. }
  72. func waitForUnregistration(
  73. t *testing.T,
  74. socketPath string,
  75. asw cache.ActualStateOfWorld) {
  76. err := retryWithExponentialBackOff(
  77. time.Duration(500*time.Millisecond),
  78. func() (bool, error) {
  79. registeredPlugins := asw.GetRegisteredPlugins()
  80. for _, plugin := range registeredPlugins {
  81. if plugin.SocketPath == socketPath {
  82. return false, nil
  83. }
  84. }
  85. return true, nil
  86. },
  87. )
  88. if err != nil {
  89. t.Fatalf("Timed out waiting for plugin to be unregistered:\n%s.", socketPath)
  90. }
  91. }
  92. func retryWithExponentialBackOff(initialDuration time.Duration, fn wait.ConditionFunc) error {
  93. backoff := wait.Backoff{
  94. Duration: initialDuration,
  95. Factor: 3,
  96. Jitter: 0,
  97. Steps: 6,
  98. }
  99. return wait.ExponentialBackoff(backoff, fn)
  100. }
  101. type DummyImpl struct{}
  102. func NewDummyImpl() *DummyImpl {
  103. return &DummyImpl{}
  104. }
  105. // ValidatePlugin is a dummy implementation
  106. func (d *DummyImpl) ValidatePlugin(pluginName string, endpoint string, versions []string) error {
  107. return nil
  108. }
  109. // RegisterPlugin is a dummy implementation
  110. func (d *DummyImpl) RegisterPlugin(pluginName string, endpoint string, versions []string) error {
  111. return nil
  112. }
  113. // DeRegisterPlugin is a dummy implementation
  114. func (d *DummyImpl) DeRegisterPlugin(pluginName string) {
  115. }
  116. // Calls Run()
  117. // Verifies that asw and dsw have no plugins
  118. func Test_Run_Positive_DoNothing(t *testing.T) {
  119. defer cleanup(t)
  120. dsw := cache.NewDesiredStateOfWorld()
  121. asw := cache.NewActualStateOfWorld()
  122. fakeRecorder := &record.FakeRecorder{}
  123. oex := operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(
  124. fakeRecorder,
  125. ))
  126. reconciler := NewReconciler(
  127. oex,
  128. reconcilerLoopSleepDuration,
  129. dsw,
  130. asw,
  131. )
  132. // Act
  133. runReconciler(reconciler)
  134. // Get dsw and asw plugins; they should both be empty
  135. if len(asw.GetRegisteredPlugins()) != 0 {
  136. t.Fatalf("Test_Run_Positive_DoNothing: actual state of world should be empty but it's not")
  137. }
  138. if len(dsw.GetPluginsToRegister()) != 0 {
  139. t.Fatalf("Test_Run_Positive_DoNothing: desired state of world should be empty but it's not")
  140. }
  141. }
  142. // Populates desiredStateOfWorld cache with one plugin.
  143. // Calls Run()
  144. // Verifies the actual state of world contains that plugin
  145. func Test_Run_Positive_Register(t *testing.T) {
  146. defer cleanup(t)
  147. dsw := cache.NewDesiredStateOfWorld()
  148. asw := cache.NewActualStateOfWorld()
  149. di := NewDummyImpl()
  150. fakeRecorder := &record.FakeRecorder{}
  151. oex := operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(
  152. fakeRecorder,
  153. ))
  154. reconciler := NewReconciler(
  155. oex,
  156. reconcilerLoopSleepDuration,
  157. dsw,
  158. asw,
  159. )
  160. reconciler.AddHandler(registerapi.DevicePlugin, cache.PluginHandler(di))
  161. // Start the reconciler to fill ASW.
  162. stopChan := make(chan struct{})
  163. defer close(stopChan)
  164. go reconciler.Run(stopChan)
  165. socketPath := fmt.Sprintf("%s/plugin.sock", socketDir)
  166. pluginName := fmt.Sprintf("example-plugin")
  167. p := pluginwatcher.NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  168. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  169. timestampBeforeRegistration := time.Now()
  170. dsw.AddOrUpdatePlugin(socketPath)
  171. waitForRegistration(t, socketPath, timestampBeforeRegistration, asw)
  172. // Get asw plugins; it should contain the added plugin
  173. aswPlugins := asw.GetRegisteredPlugins()
  174. if len(aswPlugins) != 1 {
  175. t.Fatalf("Test_Run_Positive_Register: actual state of world length should be one but it's %d", len(aswPlugins))
  176. }
  177. if aswPlugins[0].SocketPath != socketPath {
  178. t.Fatalf("Test_Run_Positive_Register: expected\n%s\nin actual state of world, but got\n%v\n", socketPath, aswPlugins[0])
  179. }
  180. }
  181. // Populates desiredStateOfWorld cache with one plugin
  182. // Calls Run()
  183. // Verifies there is one plugin now in actual state of world.
  184. // Deletes plugin from desired state of world.
  185. // Verifies that plugin no longer exists in actual state of world.
  186. func Test_Run_Positive_RegisterThenUnregister(t *testing.T) {
  187. defer cleanup(t)
  188. dsw := cache.NewDesiredStateOfWorld()
  189. asw := cache.NewActualStateOfWorld()
  190. di := NewDummyImpl()
  191. fakeRecorder := &record.FakeRecorder{}
  192. oex := operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(
  193. fakeRecorder,
  194. ))
  195. reconciler := NewReconciler(
  196. oex,
  197. reconcilerLoopSleepDuration,
  198. dsw,
  199. asw,
  200. )
  201. reconciler.AddHandler(registerapi.DevicePlugin, cache.PluginHandler(di))
  202. // Start the reconciler to fill ASW.
  203. stopChan := make(chan struct{})
  204. defer close(stopChan)
  205. go reconciler.Run(stopChan)
  206. socketPath := fmt.Sprintf("%s/plugin.sock", socketDir)
  207. pluginName := fmt.Sprintf("example-plugin")
  208. p := pluginwatcher.NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  209. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  210. timestampBeforeRegistration := time.Now()
  211. dsw.AddOrUpdatePlugin(socketPath)
  212. waitForRegistration(t, socketPath, timestampBeforeRegistration, asw)
  213. // Get asw plugins; it should contain the added plugin
  214. aswPlugins := asw.GetRegisteredPlugins()
  215. if len(aswPlugins) != 1 {
  216. t.Fatalf("Test_Run_Positive_RegisterThenUnregister: actual state of world length should be one but it's %d", len(aswPlugins))
  217. }
  218. if aswPlugins[0].SocketPath != socketPath {
  219. t.Fatalf("Test_Run_Positive_RegisterThenUnregister: expected\n%s\nin actual state of world, but got\n%v\n", socketPath, aswPlugins[0])
  220. }
  221. dsw.RemovePlugin(socketPath)
  222. waitForUnregistration(t, socketPath, asw)
  223. // Get asw plugins; it should no longer contain the added plugin
  224. aswPlugins = asw.GetRegisteredPlugins()
  225. if len(aswPlugins) != 0 {
  226. t.Fatalf("Test_Run_Positive_RegisterThenUnregister: actual state of world length should be zero but it's %d", len(aswPlugins))
  227. }
  228. }
  229. // Populates desiredStateOfWorld cache with one plugin
  230. // Calls Run()
  231. // Then update the timestamp of the plugin
  232. // Verifies that the plugin is reregistered.
  233. // Verifies the plugin with updated timestamp now in actual state of world.
  234. func Test_Run_Positive_ReRegister(t *testing.T) {
  235. defer cleanup(t)
  236. dsw := cache.NewDesiredStateOfWorld()
  237. asw := cache.NewActualStateOfWorld()
  238. di := NewDummyImpl()
  239. fakeRecorder := &record.FakeRecorder{}
  240. oex := operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(
  241. fakeRecorder,
  242. ))
  243. reconciler := NewReconciler(
  244. oex,
  245. reconcilerLoopSleepDuration,
  246. dsw,
  247. asw,
  248. )
  249. reconciler.AddHandler(registerapi.DevicePlugin, cache.PluginHandler(di))
  250. // Start the reconciler to fill ASW.
  251. stopChan := make(chan struct{})
  252. defer close(stopChan)
  253. go reconciler.Run(stopChan)
  254. socketPath := fmt.Sprintf("%s/plugin2.sock", socketDir)
  255. pluginName := fmt.Sprintf("example-plugin2")
  256. p := pluginwatcher.NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  257. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  258. timestampBeforeRegistration := time.Now()
  259. dsw.AddOrUpdatePlugin(socketPath)
  260. waitForRegistration(t, socketPath, timestampBeforeRegistration, asw)
  261. timeStampBeforeReRegistration := time.Now()
  262. // Add the plugin again to update the timestamp
  263. dsw.AddOrUpdatePlugin(socketPath)
  264. // This should trigger a deregistration and a regitration
  265. // The process of unregistration and reregistration can happen so fast that
  266. // we are not able to catch it with waitForUnregistration, so here we are checking
  267. // the plugin has an updated timestamp.
  268. waitForRegistration(t, socketPath, timeStampBeforeReRegistration, asw)
  269. // Get asw plugins; it should contain the added plugin
  270. aswPlugins := asw.GetRegisteredPlugins()
  271. if len(aswPlugins) != 1 {
  272. t.Fatalf("Test_Run_Positive_RegisterThenUnregister: actual state of world length should be one but it's %d", len(aswPlugins))
  273. }
  274. if aswPlugins[0].SocketPath != socketPath {
  275. t.Fatalf("Test_Run_Positive_RegisterThenUnregister: expected\n%s\nin actual state of world, but got\n%v\n", socketPath, aswPlugins[0])
  276. }
  277. }