plugin_watcher_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. Copyright 2018 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 pluginwatcher
  14. import (
  15. "flag"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "sync"
  20. "testing"
  21. "time"
  22. "github.com/stretchr/testify/require"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. "k8s.io/klog"
  25. registerapi "k8s.io/kubelet/pkg/apis/pluginregistration/v1"
  26. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache"
  27. )
  28. var (
  29. socketDir string
  30. supportedVersions = []string{"v1beta1", "v1beta2"}
  31. )
  32. func init() {
  33. var logLevel string
  34. klog.InitFlags(flag.CommandLine)
  35. flag.Set("alsologtostderr", fmt.Sprintf("%t", true))
  36. flag.StringVar(&logLevel, "logLevel", "6", "test")
  37. flag.Lookup("v").Value.Set(logLevel)
  38. d, err := ioutil.TempDir("", "plugin_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 waitForRegistration(
  49. t *testing.T,
  50. socketPath string,
  51. dsw cache.DesiredStateOfWorld) {
  52. err := retryWithExponentialBackOff(
  53. time.Duration(500*time.Millisecond),
  54. func() (bool, error) {
  55. if dsw.PluginExists(socketPath) {
  56. return true, nil
  57. }
  58. return false, nil
  59. },
  60. )
  61. if err != nil {
  62. t.Fatalf("Timed out waiting for plugin to be added to desired state of world cache:\n%s.", socketPath)
  63. }
  64. }
  65. func waitForUnregistration(
  66. t *testing.T,
  67. socketPath string,
  68. dsw cache.DesiredStateOfWorld) {
  69. err := retryWithExponentialBackOff(
  70. time.Duration(500*time.Millisecond),
  71. func() (bool, error) {
  72. if !dsw.PluginExists(socketPath) {
  73. return true, nil
  74. }
  75. return false, nil
  76. },
  77. )
  78. if err != nil {
  79. t.Fatalf("Timed out waiting for plugin to be unregistered:\n%s.", socketPath)
  80. }
  81. }
  82. func retryWithExponentialBackOff(initialDuration time.Duration, fn wait.ConditionFunc) error {
  83. backoff := wait.Backoff{
  84. Duration: initialDuration,
  85. Factor: 3,
  86. Jitter: 0,
  87. Steps: 6,
  88. }
  89. return wait.ExponentialBackoff(backoff, fn)
  90. }
  91. func TestPluginRegistration(t *testing.T) {
  92. defer cleanup(t)
  93. dsw := cache.NewDesiredStateOfWorld()
  94. newWatcher(t, dsw, wait.NeverStop)
  95. for i := 0; i < 10; i++ {
  96. socketPath := fmt.Sprintf("%s/plugin-%d.sock", socketDir, i)
  97. pluginName := fmt.Sprintf("example-plugin-%d", i)
  98. p := NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  99. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  100. pluginInfo := GetPluginInfo(p)
  101. waitForRegistration(t, pluginInfo.SocketPath, dsw)
  102. // Check the desired state for plugins
  103. dswPlugins := dsw.GetPluginsToRegister()
  104. if len(dswPlugins) != 1 {
  105. t.Fatalf("TestPluginRegistration: desired state of world length should be 1 but it's %d", len(dswPlugins))
  106. }
  107. // Stop the plugin; the plugin should be removed from the desired state of world cache
  108. require.NoError(t, p.Stop())
  109. // The following doesn't work when running the unit tests locally: event.Op of plugin watcher won't pick up the delete event
  110. waitForUnregistration(t, pluginInfo.SocketPath, dsw)
  111. dswPlugins = dsw.GetPluginsToRegister()
  112. if len(dswPlugins) != 0 {
  113. t.Fatalf("TestPluginRegistration: desired state of world length should be 0 but it's %d", len(dswPlugins))
  114. }
  115. }
  116. }
  117. func TestPluginRegistrationSameName(t *testing.T) {
  118. defer cleanup(t)
  119. dsw := cache.NewDesiredStateOfWorld()
  120. newWatcher(t, dsw, wait.NeverStop)
  121. // Make 10 plugins with the same name and same type but different socket path;
  122. // all 10 should be in desired state of world cache
  123. pluginName := "dep-example-plugin"
  124. for i := 0; i < 10; i++ {
  125. socketPath := fmt.Sprintf("%s/plugin-%d.sock", socketDir, i)
  126. p := NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  127. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  128. pluginInfo := GetPluginInfo(p)
  129. waitForRegistration(t, pluginInfo.SocketPath, dsw)
  130. // Check the desired state for plugins
  131. dswPlugins := dsw.GetPluginsToRegister()
  132. if len(dswPlugins) != i+1 {
  133. t.Fatalf("TestPluginRegistrationSameName: desired state of world length should be %d but it's %d", i+1, len(dswPlugins))
  134. }
  135. }
  136. }
  137. func TestPluginReRegistration(t *testing.T) {
  138. defer cleanup(t)
  139. dsw := cache.NewDesiredStateOfWorld()
  140. newWatcher(t, dsw, wait.NeverStop)
  141. // Create a plugin first, we are then going to remove the plugin, update the plugin with a different name
  142. // and recreate it.
  143. socketPath := fmt.Sprintf("%s/plugin-reregistration.sock", socketDir)
  144. pluginName := "reregister-plugin"
  145. p := NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  146. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  147. pluginInfo := GetPluginInfo(p)
  148. lastTimestamp := time.Now()
  149. waitForRegistration(t, pluginInfo.SocketPath, dsw)
  150. // Remove this plugin, then recreate it again with a different name for 10 times
  151. // The updated plugin should be in the desired state of world cache
  152. for i := 0; i < 10; i++ {
  153. // Stop the plugin; the plugin should be removed from the desired state of world cache
  154. // The plugin removel doesn't work when running the unit tests locally: event.Op of plugin watcher won't pick up the delete event
  155. require.NoError(t, p.Stop())
  156. waitForUnregistration(t, pluginInfo.SocketPath, dsw)
  157. // Add the plugin again
  158. pluginName := fmt.Sprintf("dep-example-plugin-%d", i)
  159. p := NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  160. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  161. waitForRegistration(t, pluginInfo.SocketPath, dsw)
  162. // Check the dsw cache. The updated plugin should be the only plugin in it
  163. dswPlugins := dsw.GetPluginsToRegister()
  164. if len(dswPlugins) != 1 {
  165. t.Fatalf("TestPluginReRegistration: desired state of world length should be 1 but it's %d", len(dswPlugins))
  166. }
  167. if !dswPlugins[0].Timestamp.After(lastTimestamp) {
  168. t.Fatalf("TestPluginReRegistration: for plugin %s timestamp of plugin is not updated", pluginName)
  169. }
  170. lastTimestamp = dswPlugins[0].Timestamp
  171. }
  172. }
  173. func TestPluginRegistrationAtKubeletStart(t *testing.T) {
  174. defer cleanup(t)
  175. plugins := make([]*examplePlugin, 10)
  176. for i := 0; i < len(plugins); i++ {
  177. socketPath := fmt.Sprintf("%s/plugin-%d.sock", socketDir, i)
  178. pluginName := fmt.Sprintf("example-plugin-%d", i)
  179. p := NewTestExamplePlugin(pluginName, registerapi.DevicePlugin, socketPath, supportedVersions...)
  180. require.NoError(t, p.Serve("v1beta1", "v1beta2"))
  181. defer func(p *examplePlugin) {
  182. require.NoError(t, p.Stop())
  183. }(p)
  184. plugins[i] = p
  185. }
  186. dsw := cache.NewDesiredStateOfWorld()
  187. newWatcher(t, dsw, wait.NeverStop)
  188. var wg sync.WaitGroup
  189. for i := 0; i < len(plugins); i++ {
  190. wg.Add(1)
  191. go func(p *examplePlugin) {
  192. defer wg.Done()
  193. pluginInfo := GetPluginInfo(p)
  194. // Validate that the plugin is in the desired state cache
  195. waitForRegistration(t, pluginInfo.SocketPath, dsw)
  196. }(plugins[i])
  197. }
  198. c := make(chan struct{})
  199. go func() {
  200. defer close(c)
  201. wg.Wait()
  202. }()
  203. select {
  204. case <-c:
  205. return
  206. case <-time.After(wait.ForeverTestTimeout):
  207. t.Fatalf("Timeout while waiting for the plugin registration status")
  208. }
  209. }
  210. func newWatcher(t *testing.T, desiredStateOfWorldCache cache.DesiredStateOfWorld, stopCh <-chan struct{}) *Watcher {
  211. w := NewWatcher(socketDir, desiredStateOfWorldCache)
  212. require.NoError(t, w.Start(stopCh))
  213. return w
  214. }