utils_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 endpointslice
  14. import (
  15. "fmt"
  16. "reflect"
  17. "testing"
  18. "time"
  19. "github.com/stretchr/testify/assert"
  20. v1 "k8s.io/api/core/v1"
  21. discovery "k8s.io/api/discovery/v1beta1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/runtime/schema"
  25. "k8s.io/apimachinery/pkg/util/intstr"
  26. "k8s.io/apimachinery/pkg/util/rand"
  27. "k8s.io/client-go/kubernetes/fake"
  28. k8stesting "k8s.io/client-go/testing"
  29. "k8s.io/client-go/tools/cache"
  30. endpointutil "k8s.io/kubernetes/pkg/controller/util/endpoint"
  31. utilpointer "k8s.io/utils/pointer"
  32. )
  33. func TestNewEndpointSlice(t *testing.T) {
  34. ipAddressType := discovery.AddressTypeIPv4
  35. portName := "foo"
  36. protocol := v1.ProtocolTCP
  37. endpointMeta := endpointMeta{
  38. Ports: []discovery.EndpointPort{{Name: &portName, Protocol: &protocol}},
  39. AddressType: ipAddressType,
  40. }
  41. service := v1.Service{
  42. ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "test"},
  43. Spec: v1.ServiceSpec{
  44. Ports: []v1.ServicePort{{Port: 80}},
  45. Selector: map[string]string{"foo": "bar"},
  46. },
  47. }
  48. gvk := schema.GroupVersionKind{Version: "v1", Kind: "Service"}
  49. ownerRef := metav1.NewControllerRef(&service, gvk)
  50. expectedSlice := discovery.EndpointSlice{
  51. ObjectMeta: metav1.ObjectMeta{
  52. Labels: map[string]string{
  53. discovery.LabelServiceName: service.Name,
  54. discovery.LabelManagedBy: controllerName,
  55. },
  56. GenerateName: fmt.Sprintf("%s-", service.Name),
  57. OwnerReferences: []metav1.OwnerReference{*ownerRef},
  58. Namespace: service.Namespace,
  59. },
  60. Ports: endpointMeta.Ports,
  61. AddressType: endpointMeta.AddressType,
  62. Endpoints: []discovery.Endpoint{},
  63. }
  64. generatedSlice := newEndpointSlice(&service, &endpointMeta)
  65. assert.EqualValues(t, expectedSlice, *generatedSlice)
  66. }
  67. func TestPodToEndpoint(t *testing.T) {
  68. ns := "test"
  69. svc, _ := newServiceAndEndpointMeta("foo", ns)
  70. svcPublishNotReady, _ := newServiceAndEndpointMeta("publishnotready", ns)
  71. svcPublishNotReady.Spec.PublishNotReadyAddresses = true
  72. readyPod := newPod(1, ns, true, 1)
  73. readyPodHostname := newPod(1, ns, true, 1)
  74. readyPodHostname.Spec.Subdomain = svc.Name
  75. readyPodHostname.Spec.Hostname = "example-hostname"
  76. unreadyPod := newPod(1, ns, false, 1)
  77. multiIPPod := newPod(1, ns, true, 1)
  78. multiIPPod.Status.PodIPs = []v1.PodIP{{IP: "1.2.3.4"}, {IP: "1234::5678:0000:0000:9abc:def0"}}
  79. node1 := &v1.Node{
  80. ObjectMeta: metav1.ObjectMeta{
  81. Name: readyPod.Spec.NodeName,
  82. Labels: map[string]string{
  83. "topology.kubernetes.io/zone": "us-central1-a",
  84. "topology.kubernetes.io/region": "us-central1",
  85. },
  86. },
  87. }
  88. testCases := []struct {
  89. name string
  90. pod *v1.Pod
  91. node *v1.Node
  92. svc *v1.Service
  93. expectedEndpoint discovery.Endpoint
  94. publishNotReadyAddresses bool
  95. }{
  96. {
  97. name: "Ready pod",
  98. pod: readyPod,
  99. svc: &svc,
  100. expectedEndpoint: discovery.Endpoint{
  101. Addresses: []string{"1.2.3.5"},
  102. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  103. Topology: map[string]string{"kubernetes.io/hostname": "node-1"},
  104. TargetRef: &v1.ObjectReference{
  105. Kind: "Pod",
  106. Namespace: ns,
  107. Name: readyPod.Name,
  108. UID: readyPod.UID,
  109. ResourceVersion: readyPod.ResourceVersion,
  110. },
  111. },
  112. },
  113. {
  114. name: "Ready pod + publishNotReadyAddresses",
  115. pod: readyPod,
  116. svc: &svcPublishNotReady,
  117. expectedEndpoint: discovery.Endpoint{
  118. Addresses: []string{"1.2.3.5"},
  119. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  120. Topology: map[string]string{"kubernetes.io/hostname": "node-1"},
  121. TargetRef: &v1.ObjectReference{
  122. Kind: "Pod",
  123. Namespace: ns,
  124. Name: readyPod.Name,
  125. UID: readyPod.UID,
  126. ResourceVersion: readyPod.ResourceVersion,
  127. },
  128. },
  129. },
  130. {
  131. name: "Unready pod",
  132. pod: unreadyPod,
  133. svc: &svc,
  134. expectedEndpoint: discovery.Endpoint{
  135. Addresses: []string{"1.2.3.5"},
  136. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(false)},
  137. Topology: map[string]string{"kubernetes.io/hostname": "node-1"},
  138. TargetRef: &v1.ObjectReference{
  139. Kind: "Pod",
  140. Namespace: ns,
  141. Name: readyPod.Name,
  142. UID: readyPod.UID,
  143. ResourceVersion: readyPod.ResourceVersion,
  144. },
  145. },
  146. },
  147. {
  148. name: "Unready pod + publishNotReadyAddresses",
  149. pod: unreadyPod,
  150. svc: &svcPublishNotReady,
  151. expectedEndpoint: discovery.Endpoint{
  152. Addresses: []string{"1.2.3.5"},
  153. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  154. Topology: map[string]string{"kubernetes.io/hostname": "node-1"},
  155. TargetRef: &v1.ObjectReference{
  156. Kind: "Pod",
  157. Namespace: ns,
  158. Name: readyPod.Name,
  159. UID: readyPod.UID,
  160. ResourceVersion: readyPod.ResourceVersion,
  161. },
  162. },
  163. },
  164. {
  165. name: "Ready pod + node labels",
  166. pod: readyPod,
  167. node: node1,
  168. svc: &svc,
  169. expectedEndpoint: discovery.Endpoint{
  170. Addresses: []string{"1.2.3.5"},
  171. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  172. Topology: map[string]string{
  173. "kubernetes.io/hostname": "node-1",
  174. "topology.kubernetes.io/zone": "us-central1-a",
  175. "topology.kubernetes.io/region": "us-central1",
  176. },
  177. TargetRef: &v1.ObjectReference{
  178. Kind: "Pod",
  179. Namespace: ns,
  180. Name: readyPod.Name,
  181. UID: readyPod.UID,
  182. ResourceVersion: readyPod.ResourceVersion,
  183. },
  184. },
  185. },
  186. {
  187. name: "Multi IP Ready pod + node labels",
  188. pod: multiIPPod,
  189. node: node1,
  190. svc: &svc,
  191. expectedEndpoint: discovery.Endpoint{
  192. Addresses: []string{"1.2.3.4"},
  193. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  194. Topology: map[string]string{
  195. "kubernetes.io/hostname": "node-1",
  196. "topology.kubernetes.io/zone": "us-central1-a",
  197. "topology.kubernetes.io/region": "us-central1",
  198. },
  199. TargetRef: &v1.ObjectReference{
  200. Kind: "Pod",
  201. Namespace: ns,
  202. Name: readyPod.Name,
  203. UID: readyPod.UID,
  204. ResourceVersion: readyPod.ResourceVersion,
  205. },
  206. },
  207. },
  208. {
  209. name: "Ready pod + hostname",
  210. pod: readyPodHostname,
  211. node: node1,
  212. svc: &svc,
  213. expectedEndpoint: discovery.Endpoint{
  214. Addresses: []string{"1.2.3.5"},
  215. Conditions: discovery.EndpointConditions{Ready: utilpointer.BoolPtr(true)},
  216. Hostname: &readyPodHostname.Spec.Hostname,
  217. Topology: map[string]string{
  218. "kubernetes.io/hostname": "node-1",
  219. "topology.kubernetes.io/zone": "us-central1-a",
  220. "topology.kubernetes.io/region": "us-central1",
  221. },
  222. TargetRef: &v1.ObjectReference{
  223. Kind: "Pod",
  224. Namespace: ns,
  225. Name: readyPodHostname.Name,
  226. UID: readyPodHostname.UID,
  227. ResourceVersion: readyPodHostname.ResourceVersion,
  228. },
  229. },
  230. },
  231. }
  232. for _, testCase := range testCases {
  233. t.Run(testCase.name, func(t *testing.T) {
  234. endpoint := podToEndpoint(testCase.pod, testCase.node, testCase.svc)
  235. if !reflect.DeepEqual(testCase.expectedEndpoint, endpoint) {
  236. t.Errorf("Expected endpoint: %v, got: %v", testCase.expectedEndpoint, endpoint)
  237. }
  238. })
  239. }
  240. }
  241. func TestPodChangedWithPodEndpointChanged(t *testing.T) {
  242. podStore := cache.NewStore(cache.DeletionHandlingMetaNamespaceKeyFunc)
  243. ns := "test"
  244. podStore.Add(newPod(1, ns, true, 1))
  245. pods := podStore.List()
  246. if len(pods) != 1 {
  247. t.Errorf("podStore size: expected: %d, got: %d", 1, len(pods))
  248. return
  249. }
  250. oldPod := pods[0].(*v1.Pod)
  251. newPod := oldPod.DeepCopy()
  252. if podChangedHelper(oldPod, newPod, podEndpointChanged) {
  253. t.Errorf("Expected pod to be unchanged for copied pod")
  254. }
  255. newPod.Spec.NodeName = "changed"
  256. if !podChangedHelper(oldPod, newPod, podEndpointChanged) {
  257. t.Errorf("Expected pod to be changed for pod with NodeName changed")
  258. }
  259. newPod.Spec.NodeName = oldPod.Spec.NodeName
  260. newPod.ObjectMeta.ResourceVersion = "changed"
  261. if podChangedHelper(oldPod, newPod, podEndpointChanged) {
  262. t.Errorf("Expected pod to be unchanged for pod with only ResourceVersion changed")
  263. }
  264. newPod.ObjectMeta.ResourceVersion = oldPod.ObjectMeta.ResourceVersion
  265. newPod.Status.PodIPs = []v1.PodIP{{IP: "1.2.3.1"}}
  266. if !podChangedHelper(oldPod, newPod, podEndpointChanged) {
  267. t.Errorf("Expected pod to be changed with pod IP address change")
  268. }
  269. newPod.Status.PodIPs = oldPod.Status.PodIPs
  270. newPod.ObjectMeta.Name = "wrong-name"
  271. if !podChangedHelper(oldPod, newPod, podEndpointChanged) {
  272. t.Errorf("Expected pod to be changed with pod name change")
  273. }
  274. newPod.ObjectMeta.Name = oldPod.ObjectMeta.Name
  275. saveConditions := oldPod.Status.Conditions
  276. oldPod.Status.Conditions = nil
  277. if !podChangedHelper(oldPod, newPod, podEndpointChanged) {
  278. t.Errorf("Expected pod to be changed with pod readiness change")
  279. }
  280. oldPod.Status.Conditions = saveConditions
  281. now := metav1.NewTime(time.Now().UTC())
  282. newPod.ObjectMeta.DeletionTimestamp = &now
  283. if !podChangedHelper(oldPod, newPod, podEndpointChanged) {
  284. t.Errorf("Expected pod to be changed with DeletionTimestamp change")
  285. }
  286. newPod.ObjectMeta.DeletionTimestamp = oldPod.ObjectMeta.DeletionTimestamp.DeepCopy()
  287. }
  288. func TestServiceControllerKey(t *testing.T) {
  289. testCases := map[string]struct {
  290. endpointSlice *discovery.EndpointSlice
  291. expectedKey string
  292. expectedErr error
  293. }{
  294. "nil EndpointSlice": {
  295. endpointSlice: nil,
  296. expectedKey: "",
  297. expectedErr: fmt.Errorf("nil EndpointSlice passed to serviceControllerKey()"),
  298. },
  299. "empty EndpointSlice": {
  300. endpointSlice: &discovery.EndpointSlice{},
  301. expectedKey: "",
  302. expectedErr: fmt.Errorf("EndpointSlice missing kubernetes.io/service-name label"),
  303. },
  304. "valid EndpointSlice": {
  305. endpointSlice: &discovery.EndpointSlice{
  306. ObjectMeta: metav1.ObjectMeta{
  307. Namespace: "ns",
  308. Labels: map[string]string{
  309. discovery.LabelServiceName: "svc",
  310. },
  311. },
  312. },
  313. expectedKey: "ns/svc",
  314. expectedErr: nil,
  315. },
  316. }
  317. for name, tc := range testCases {
  318. t.Run(name, func(t *testing.T) {
  319. actualKey, actualErr := serviceControllerKey(tc.endpointSlice)
  320. if !reflect.DeepEqual(actualErr, tc.expectedErr) {
  321. t.Errorf("Expected %s, got %s", tc.expectedErr, actualErr)
  322. }
  323. if actualKey != tc.expectedKey {
  324. t.Errorf("Expected %s, got %s", tc.expectedKey, actualKey)
  325. }
  326. })
  327. }
  328. }
  329. // Test helpers
  330. func newPod(n int, namespace string, ready bool, nPorts int) *v1.Pod {
  331. status := v1.ConditionTrue
  332. if !ready {
  333. status = v1.ConditionFalse
  334. }
  335. p := &v1.Pod{
  336. TypeMeta: metav1.TypeMeta{APIVersion: "v1"},
  337. ObjectMeta: metav1.ObjectMeta{
  338. Namespace: namespace,
  339. Name: fmt.Sprintf("pod%d", n),
  340. Labels: map[string]string{"foo": "bar"},
  341. },
  342. Spec: v1.PodSpec{
  343. Containers: []v1.Container{{
  344. Name: "container-1",
  345. }},
  346. NodeName: "node-1",
  347. },
  348. Status: v1.PodStatus{
  349. PodIP: fmt.Sprintf("1.2.3.%d", 4+n),
  350. PodIPs: []v1.PodIP{{
  351. IP: fmt.Sprintf("1.2.3.%d", 4+n),
  352. }},
  353. Conditions: []v1.PodCondition{
  354. {
  355. Type: v1.PodReady,
  356. Status: status,
  357. },
  358. },
  359. },
  360. }
  361. return p
  362. }
  363. func newClientset() *fake.Clientset {
  364. client := fake.NewSimpleClientset()
  365. client.PrependReactor("create", "endpointslices", k8stesting.ReactionFunc(func(action k8stesting.Action) (bool, runtime.Object, error) {
  366. endpointSlice := action.(k8stesting.CreateAction).GetObject().(*discovery.EndpointSlice)
  367. if endpointSlice.ObjectMeta.GenerateName != "" {
  368. endpointSlice.ObjectMeta.Name = fmt.Sprintf("%s-%s", endpointSlice.ObjectMeta.GenerateName, rand.String(8))
  369. endpointSlice.ObjectMeta.GenerateName = ""
  370. }
  371. endpointSlice.ObjectMeta.ResourceVersion = "100"
  372. return false, endpointSlice, nil
  373. }))
  374. client.PrependReactor("update", "endpointslices", k8stesting.ReactionFunc(func(action k8stesting.Action) (bool, runtime.Object, error) {
  375. endpointSlice := action.(k8stesting.CreateAction).GetObject().(*discovery.EndpointSlice)
  376. endpointSlice.ObjectMeta.ResourceVersion = "200"
  377. return false, endpointSlice, nil
  378. }))
  379. return client
  380. }
  381. func newServiceAndEndpointMeta(name, namespace string) (v1.Service, endpointMeta) {
  382. portNum := int32(80)
  383. portNameIntStr := intstr.IntOrString{
  384. Type: intstr.Int,
  385. IntVal: portNum,
  386. }
  387. svc := v1.Service{
  388. ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
  389. Spec: v1.ServiceSpec{
  390. Ports: []v1.ServicePort{{
  391. TargetPort: portNameIntStr,
  392. Protocol: v1.ProtocolTCP,
  393. Name: name,
  394. }},
  395. Selector: map[string]string{"foo": "bar"},
  396. },
  397. }
  398. addressType := discovery.AddressTypeIPv4
  399. protocol := v1.ProtocolTCP
  400. endpointMeta := endpointMeta{
  401. AddressType: addressType,
  402. Ports: []discovery.EndpointPort{{Name: &name, Port: &portNum, Protocol: &protocol}},
  403. }
  404. return svc, endpointMeta
  405. }
  406. func newEmptyEndpointSlice(n int, namespace string, endpointMeta endpointMeta, svc v1.Service) *discovery.EndpointSlice {
  407. return &discovery.EndpointSlice{
  408. ObjectMeta: metav1.ObjectMeta{
  409. Name: fmt.Sprintf("%s.%d", svc.Name, n),
  410. Namespace: namespace,
  411. },
  412. Ports: endpointMeta.Ports,
  413. AddressType: endpointMeta.AddressType,
  414. Endpoints: []discovery.Endpoint{},
  415. }
  416. }
  417. func podChangedHelper(oldPod, newPod *v1.Pod, endpointChanged endpointutil.EndpointsMatch) bool {
  418. podChanged, _ := endpointutil.PodChanged(oldPod, newPod, podEndpointChanged)
  419. return podChanged
  420. }