namespace_controller_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. Copyright 2015 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 namespace
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/http/httptest"
  18. "path"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/api/errors"
  24. "k8s.io/kubernetes/pkg/api/unversioned"
  25. clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
  26. "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
  27. "k8s.io/kubernetes/pkg/client/restclient"
  28. "k8s.io/kubernetes/pkg/client/testing/core"
  29. "k8s.io/kubernetes/pkg/client/typed/dynamic"
  30. "k8s.io/kubernetes/pkg/runtime"
  31. "k8s.io/kubernetes/pkg/util/sets"
  32. )
  33. func TestFinalized(t *testing.T) {
  34. testNamespace := &api.Namespace{
  35. Spec: api.NamespaceSpec{
  36. Finalizers: []api.FinalizerName{"a", "b"},
  37. },
  38. }
  39. if finalized(testNamespace) {
  40. t.Errorf("Unexpected result, namespace is not finalized")
  41. }
  42. testNamespace.Spec.Finalizers = []api.FinalizerName{}
  43. if !finalized(testNamespace) {
  44. t.Errorf("Expected object to be finalized")
  45. }
  46. }
  47. func TestFinalizeNamespaceFunc(t *testing.T) {
  48. mockClient := &fake.Clientset{}
  49. testNamespace := &api.Namespace{
  50. ObjectMeta: api.ObjectMeta{
  51. Name: "test",
  52. ResourceVersion: "1",
  53. },
  54. Spec: api.NamespaceSpec{
  55. Finalizers: []api.FinalizerName{"kubernetes", "other"},
  56. },
  57. }
  58. finalizeNamespace(mockClient, testNamespace, api.FinalizerKubernetes)
  59. actions := mockClient.Actions()
  60. if len(actions) != 1 {
  61. t.Errorf("Expected 1 mock client action, but got %v", len(actions))
  62. }
  63. if !actions[0].Matches("create", "namespaces") || actions[0].GetSubresource() != "finalize" {
  64. t.Errorf("Expected finalize-namespace action %v", actions[0])
  65. }
  66. finalizers := actions[0].(core.CreateAction).GetObject().(*api.Namespace).Spec.Finalizers
  67. if len(finalizers) != 1 {
  68. t.Errorf("There should be a single finalizer remaining")
  69. }
  70. if "other" != string(finalizers[0]) {
  71. t.Errorf("Unexpected finalizer value, %v", finalizers[0])
  72. }
  73. }
  74. func testSyncNamespaceThatIsTerminating(t *testing.T, versions *unversioned.APIVersions) {
  75. now := unversioned.Now()
  76. namespaceName := "test"
  77. testNamespacePendingFinalize := &api.Namespace{
  78. ObjectMeta: api.ObjectMeta{
  79. Name: namespaceName,
  80. ResourceVersion: "1",
  81. DeletionTimestamp: &now,
  82. },
  83. Spec: api.NamespaceSpec{
  84. Finalizers: []api.FinalizerName{"kubernetes"},
  85. },
  86. Status: api.NamespaceStatus{
  87. Phase: api.NamespaceTerminating,
  88. },
  89. }
  90. testNamespaceFinalizeComplete := &api.Namespace{
  91. ObjectMeta: api.ObjectMeta{
  92. Name: namespaceName,
  93. ResourceVersion: "1",
  94. DeletionTimestamp: &now,
  95. },
  96. Spec: api.NamespaceSpec{},
  97. Status: api.NamespaceStatus{
  98. Phase: api.NamespaceTerminating,
  99. },
  100. }
  101. // when doing a delete all of content, we will do a GET of a collection, and DELETE of a collection by default
  102. dynamicClientActionSet := sets.NewString()
  103. groupVersionResources := testGroupVersionResources()
  104. for _, groupVersionResource := range groupVersionResources {
  105. urlPath := path.Join([]string{
  106. dynamic.LegacyAPIPathResolverFunc(groupVersionResource.GroupVersion()),
  107. groupVersionResource.Group,
  108. groupVersionResource.Version,
  109. "namespaces",
  110. namespaceName,
  111. groupVersionResource.Resource,
  112. }...)
  113. dynamicClientActionSet.Insert((&fakeAction{method: "GET", path: urlPath}).String())
  114. dynamicClientActionSet.Insert((&fakeAction{method: "DELETE", path: urlPath}).String())
  115. }
  116. scenarios := map[string]struct {
  117. testNamespace *api.Namespace
  118. kubeClientActionSet sets.String
  119. dynamicClientActionSet sets.String
  120. }{
  121. "pending-finalize": {
  122. testNamespace: testNamespacePendingFinalize,
  123. kubeClientActionSet: sets.NewString(
  124. strings.Join([]string{"get", "namespaces", ""}, "-"),
  125. strings.Join([]string{"create", "namespaces", "finalize"}, "-"),
  126. strings.Join([]string{"list", "pods", ""}, "-"),
  127. strings.Join([]string{"delete", "namespaces", ""}, "-"),
  128. ),
  129. dynamicClientActionSet: dynamicClientActionSet,
  130. },
  131. "complete-finalize": {
  132. testNamespace: testNamespaceFinalizeComplete,
  133. kubeClientActionSet: sets.NewString(
  134. strings.Join([]string{"get", "namespaces", ""}, "-"),
  135. strings.Join([]string{"delete", "namespaces", ""}, "-"),
  136. ),
  137. dynamicClientActionSet: sets.NewString(),
  138. },
  139. }
  140. for scenario, testInput := range scenarios {
  141. testHandler := &fakeActionHandler{statusCode: 200}
  142. srv, clientConfig := testServerAndClientConfig(testHandler.ServeHTTP)
  143. defer srv.Close()
  144. mockClient := fake.NewSimpleClientset(testInput.testNamespace)
  145. clientPool := dynamic.NewClientPool(clientConfig, dynamic.LegacyAPIPathResolverFunc)
  146. err := syncNamespace(mockClient, clientPool, operationNotSupportedCache{}, groupVersionResources, testInput.testNamespace, api.FinalizerKubernetes)
  147. if err != nil {
  148. t.Errorf("scenario %s - Unexpected error when synching namespace %v", scenario, err)
  149. }
  150. // validate traffic from kube client
  151. actionSet := sets.NewString()
  152. for _, action := range mockClient.Actions() {
  153. actionSet.Insert(strings.Join([]string{action.GetVerb(), action.GetResource().Resource, action.GetSubresource()}, "-"))
  154. }
  155. if !actionSet.Equal(testInput.kubeClientActionSet) {
  156. t.Errorf("scenario %s - mock client expected actions:\n%v\n but got:\n%v\nDifference:\n%v", scenario,
  157. testInput.kubeClientActionSet, actionSet, testInput.kubeClientActionSet.Difference(actionSet))
  158. }
  159. // validate traffic from dynamic client
  160. actionSet = sets.NewString()
  161. for _, action := range testHandler.actions {
  162. actionSet.Insert(action.String())
  163. }
  164. if !actionSet.Equal(testInput.dynamicClientActionSet) {
  165. t.Errorf("scenario %s - dynamic client expected actions:\n%v\n but got:\n%v\nDifference:\n%v", scenario,
  166. testInput.dynamicClientActionSet, actionSet, testInput.dynamicClientActionSet.Difference(actionSet))
  167. }
  168. }
  169. }
  170. func TestRetryOnConflictError(t *testing.T) {
  171. mockClient := &fake.Clientset{}
  172. numTries := 0
  173. retryOnce := func(kubeClient clientset.Interface, namespace *api.Namespace) (*api.Namespace, error) {
  174. numTries++
  175. if numTries <= 1 {
  176. return namespace, errors.NewConflict(api.Resource("namespaces"), namespace.Name, fmt.Errorf("ERROR!"))
  177. }
  178. return namespace, nil
  179. }
  180. namespace := &api.Namespace{}
  181. _, err := retryOnConflictError(mockClient, namespace, retryOnce)
  182. if err != nil {
  183. t.Errorf("Unexpected error %v", err)
  184. }
  185. if numTries != 2 {
  186. t.Errorf("Expected %v, but got %v", 2, numTries)
  187. }
  188. }
  189. func TestSyncNamespaceThatIsTerminatingNonExperimental(t *testing.T) {
  190. testSyncNamespaceThatIsTerminating(t, &unversioned.APIVersions{})
  191. }
  192. func TestSyncNamespaceThatIsTerminatingV1Beta1(t *testing.T) {
  193. testSyncNamespaceThatIsTerminating(t, &unversioned.APIVersions{Versions: []string{"extensions/v1beta1"}})
  194. }
  195. func TestSyncNamespaceThatIsActive(t *testing.T) {
  196. mockClient := &fake.Clientset{}
  197. testNamespace := &api.Namespace{
  198. ObjectMeta: api.ObjectMeta{
  199. Name: "test",
  200. ResourceVersion: "1",
  201. },
  202. Spec: api.NamespaceSpec{
  203. Finalizers: []api.FinalizerName{"kubernetes"},
  204. },
  205. Status: api.NamespaceStatus{
  206. Phase: api.NamespaceActive,
  207. },
  208. }
  209. err := syncNamespace(mockClient, nil, operationNotSupportedCache{}, testGroupVersionResources(), testNamespace, api.FinalizerKubernetes)
  210. if err != nil {
  211. t.Errorf("Unexpected error when synching namespace %v", err)
  212. }
  213. if len(mockClient.Actions()) != 0 {
  214. t.Errorf("Expected no action from controller, but got: %v", mockClient.Actions())
  215. }
  216. }
  217. // testServerAndClientConfig returns a server that listens and a config that can reference it
  218. func testServerAndClientConfig(handler func(http.ResponseWriter, *http.Request)) (*httptest.Server, *restclient.Config) {
  219. srv := httptest.NewServer(http.HandlerFunc(handler))
  220. config := &restclient.Config{
  221. Host: srv.URL,
  222. }
  223. return srv, config
  224. }
  225. // fakeAction records information about requests to aid in testing.
  226. type fakeAction struct {
  227. method string
  228. path string
  229. }
  230. // String returns method=path to aid in testing
  231. func (f *fakeAction) String() string {
  232. return strings.Join([]string{f.method, f.path}, "=")
  233. }
  234. // fakeActionHandler holds a list of fakeActions received
  235. type fakeActionHandler struct {
  236. // statusCode returned by this handler
  237. statusCode int
  238. lock sync.Mutex
  239. actions []fakeAction
  240. }
  241. // ServeHTTP logs the action that occurred and always returns the associated status code
  242. func (f *fakeActionHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
  243. f.lock.Lock()
  244. defer f.lock.Unlock()
  245. f.actions = append(f.actions, fakeAction{method: request.Method, path: request.URL.Path})
  246. response.Header().Set("Content-Type", runtime.ContentTypeJSON)
  247. response.WriteHeader(f.statusCode)
  248. response.Write([]byte("{\"kind\": \"List\",\"items\":null}"))
  249. }
  250. // testGroupVersionResources returns a mocked up set of resources across different api groups for testing namespace controller.
  251. func testGroupVersionResources() []unversioned.GroupVersionResource {
  252. results := []unversioned.GroupVersionResource{}
  253. results = append(results, unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"})
  254. results = append(results, unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "services"})
  255. results = append(results, unversioned.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"})
  256. return results
  257. }