namespaced_resources_deleter_test.go 11 KB

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