strategy_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. Copyright 2014 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 service
  14. import (
  15. "reflect"
  16. "testing"
  17. "k8s.io/apimachinery/pkg/api/errors"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/apimachinery/pkg/util/diff"
  21. "k8s.io/apimachinery/pkg/util/intstr"
  22. genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
  23. "k8s.io/apiserver/pkg/registry/rest"
  24. api "k8s.io/kubernetes/pkg/apis/core"
  25. _ "k8s.io/kubernetes/pkg/apis/core/install"
  26. utilfeature "k8s.io/apiserver/pkg/util/feature"
  27. featuregatetesting "k8s.io/component-base/featuregate/testing"
  28. "k8s.io/kubernetes/pkg/features"
  29. )
  30. func TestExportService(t *testing.T) {
  31. tests := []struct {
  32. objIn runtime.Object
  33. objOut runtime.Object
  34. exact bool
  35. expectErr bool
  36. }{
  37. {
  38. objIn: &api.Service{
  39. ObjectMeta: metav1.ObjectMeta{
  40. Name: "foo",
  41. Namespace: "bar",
  42. },
  43. Status: api.ServiceStatus{
  44. LoadBalancer: api.LoadBalancerStatus{
  45. Ingress: []api.LoadBalancerIngress{
  46. {IP: "1.2.3.4"},
  47. },
  48. },
  49. },
  50. },
  51. objOut: &api.Service{
  52. ObjectMeta: metav1.ObjectMeta{
  53. Name: "foo",
  54. Namespace: "bar",
  55. },
  56. },
  57. exact: true,
  58. },
  59. {
  60. objIn: &api.Service{
  61. ObjectMeta: metav1.ObjectMeta{
  62. Name: "foo",
  63. Namespace: "bar",
  64. },
  65. Spec: api.ServiceSpec{
  66. ClusterIP: "10.0.0.1",
  67. },
  68. Status: api.ServiceStatus{
  69. LoadBalancer: api.LoadBalancerStatus{
  70. Ingress: []api.LoadBalancerIngress{
  71. {IP: "1.2.3.4"},
  72. },
  73. },
  74. },
  75. },
  76. objOut: &api.Service{
  77. ObjectMeta: metav1.ObjectMeta{
  78. Name: "foo",
  79. Namespace: "bar",
  80. },
  81. Spec: api.ServiceSpec{
  82. ClusterIP: "",
  83. },
  84. },
  85. },
  86. {
  87. objIn: &api.Pod{},
  88. expectErr: true,
  89. },
  90. }
  91. for _, test := range tests {
  92. err := Strategy.Export(genericapirequest.NewContext(), test.objIn, test.exact)
  93. if err != nil {
  94. if !test.expectErr {
  95. t.Errorf("unexpected error: %v", err)
  96. }
  97. continue
  98. }
  99. if test.expectErr {
  100. t.Error("unexpected non-error")
  101. continue
  102. }
  103. if !reflect.DeepEqual(test.objIn, test.objOut) {
  104. t.Errorf("expected:\n%v\nsaw:\n%v\n", test.objOut, test.objIn)
  105. }
  106. }
  107. }
  108. func TestCheckGeneratedNameError(t *testing.T) {
  109. expect := errors.NewNotFound(api.Resource("foos"), "bar")
  110. if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Service{}); err != expect {
  111. t.Errorf("NotFoundError should be ignored: %v", err)
  112. }
  113. expect = errors.NewAlreadyExists(api.Resource("foos"), "bar")
  114. if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Service{}); err != expect {
  115. t.Errorf("AlreadyExists should be returned when no GenerateName field: %v", err)
  116. }
  117. expect = errors.NewAlreadyExists(api.Resource("foos"), "bar")
  118. if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Service{ObjectMeta: metav1.ObjectMeta{GenerateName: "foo"}}); err == nil || !errors.IsServerTimeout(err) {
  119. t.Errorf("expected try again later error: %v", err)
  120. }
  121. }
  122. func makeValidService() api.Service {
  123. defaultServiceIPFamily := api.IPv4Protocol
  124. return api.Service{
  125. ObjectMeta: metav1.ObjectMeta{
  126. Name: "valid",
  127. Namespace: "default",
  128. Labels: map[string]string{},
  129. Annotations: map[string]string{},
  130. ResourceVersion: "1",
  131. },
  132. Spec: api.ServiceSpec{
  133. Selector: map[string]string{"key": "val"},
  134. SessionAffinity: "None",
  135. Type: api.ServiceTypeClusterIP,
  136. Ports: []api.ServicePort{{Name: "p", Protocol: "TCP", Port: 8675, TargetPort: intstr.FromInt(8675)}},
  137. IPFamily: &defaultServiceIPFamily,
  138. },
  139. }
  140. }
  141. // TODO: This should be done on types that are not part of our API
  142. func TestBeforeUpdate(t *testing.T) {
  143. testCases := []struct {
  144. name string
  145. tweakSvc func(oldSvc, newSvc *api.Service) // given basic valid services, each test case can customize them
  146. expectErr bool
  147. }{
  148. {
  149. name: "no change",
  150. tweakSvc: func(oldSvc, newSvc *api.Service) {
  151. // nothing
  152. },
  153. expectErr: false,
  154. },
  155. {
  156. name: "change port",
  157. tweakSvc: func(oldSvc, newSvc *api.Service) {
  158. newSvc.Spec.Ports[0].Port++
  159. },
  160. expectErr: false,
  161. },
  162. {
  163. name: "bad namespace",
  164. tweakSvc: func(oldSvc, newSvc *api.Service) {
  165. newSvc.Namespace = "#$%%invalid"
  166. },
  167. expectErr: true,
  168. },
  169. {
  170. name: "change name",
  171. tweakSvc: func(oldSvc, newSvc *api.Service) {
  172. newSvc.Name += "2"
  173. },
  174. expectErr: true,
  175. },
  176. {
  177. name: "change ClusterIP",
  178. tweakSvc: func(oldSvc, newSvc *api.Service) {
  179. oldSvc.Spec.ClusterIP = "1.2.3.4"
  180. newSvc.Spec.ClusterIP = "4.3.2.1"
  181. },
  182. expectErr: true,
  183. },
  184. {
  185. name: "change selector",
  186. tweakSvc: func(oldSvc, newSvc *api.Service) {
  187. newSvc.Spec.Selector = map[string]string{"newkey": "newvalue"}
  188. },
  189. expectErr: false,
  190. },
  191. }
  192. for _, tc := range testCases {
  193. oldSvc := makeValidService()
  194. newSvc := makeValidService()
  195. tc.tweakSvc(&oldSvc, &newSvc)
  196. ctx := genericapirequest.NewDefaultContext()
  197. err := rest.BeforeUpdate(Strategy, ctx, runtime.Object(&oldSvc), runtime.Object(&newSvc))
  198. if tc.expectErr && err == nil {
  199. t.Errorf("unexpected non-error for %q", tc.name)
  200. }
  201. if !tc.expectErr && err != nil {
  202. t.Errorf("unexpected error for %q: %v", tc.name, err)
  203. }
  204. }
  205. }
  206. func TestServiceStatusStrategy(t *testing.T) {
  207. ctx := genericapirequest.NewDefaultContext()
  208. if !StatusStrategy.NamespaceScoped() {
  209. t.Errorf("Service must be namespace scoped")
  210. }
  211. oldService := makeValidService()
  212. newService := makeValidService()
  213. oldService.ResourceVersion = "4"
  214. newService.ResourceVersion = "4"
  215. newService.Spec.SessionAffinity = "ClientIP"
  216. newService.Status = api.ServiceStatus{
  217. LoadBalancer: api.LoadBalancerStatus{
  218. Ingress: []api.LoadBalancerIngress{
  219. {IP: "127.0.0.2"},
  220. },
  221. },
  222. }
  223. StatusStrategy.PrepareForUpdate(ctx, &newService, &oldService)
  224. if newService.Status.LoadBalancer.Ingress[0].IP != "127.0.0.2" {
  225. t.Errorf("Service status updates should allow change of status fields")
  226. }
  227. if newService.Spec.SessionAffinity != "None" {
  228. t.Errorf("PrepareForUpdate should have preserved old spec")
  229. }
  230. errs := StatusStrategy.ValidateUpdate(ctx, &newService, &oldService)
  231. if len(errs) != 0 {
  232. t.Errorf("Unexpected error %v", errs)
  233. }
  234. }
  235. func makeServiceWithIPFamily(IPFamily *api.IPFamily) *api.Service {
  236. return &api.Service{
  237. Spec: api.ServiceSpec{
  238. IPFamily: IPFamily,
  239. },
  240. }
  241. }
  242. func TestDropDisabledField(t *testing.T) {
  243. ipv4Service := api.IPv4Protocol
  244. ipv6Service := api.IPv6Protocol
  245. testCases := []struct {
  246. name string
  247. enableDualStack bool
  248. svc *api.Service
  249. oldSvc *api.Service
  250. compareSvc *api.Service
  251. }{
  252. {
  253. name: "not dual stack, field not used",
  254. enableDualStack: false,
  255. svc: makeServiceWithIPFamily(nil),
  256. oldSvc: nil,
  257. compareSvc: makeServiceWithIPFamily(nil),
  258. },
  259. {
  260. name: "not dual stack, field used in new, not in old",
  261. enableDualStack: false,
  262. svc: makeServiceWithIPFamily(&ipv4Service),
  263. oldSvc: nil,
  264. compareSvc: makeServiceWithIPFamily(nil),
  265. },
  266. {
  267. name: "not dual stack, field used in old and new",
  268. enableDualStack: false,
  269. svc: makeServiceWithIPFamily(&ipv4Service),
  270. oldSvc: makeServiceWithIPFamily(&ipv4Service),
  271. compareSvc: makeServiceWithIPFamily(&ipv4Service),
  272. },
  273. {
  274. name: "dualstack, field used",
  275. enableDualStack: true,
  276. svc: makeServiceWithIPFamily(&ipv6Service),
  277. oldSvc: nil,
  278. compareSvc: makeServiceWithIPFamily(&ipv6Service),
  279. },
  280. /* add more tests for other dropped fields as needed */
  281. }
  282. for _, tc := range testCases {
  283. func() {
  284. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, tc.enableDualStack)()
  285. old := tc.oldSvc.DeepCopy()
  286. dropServiceDisabledFields(tc.svc, tc.oldSvc)
  287. // old node should never be changed
  288. if !reflect.DeepEqual(tc.oldSvc, old) {
  289. t.Errorf("%v: old svc changed: %v", tc.name, diff.ObjectReflectDiff(tc.oldSvc, old))
  290. }
  291. if !reflect.DeepEqual(tc.svc, tc.compareSvc) {
  292. t.Errorf("%v: unexpected svc spec: %v", tc.name, diff.ObjectReflectDiff(tc.svc, tc.compareSvc))
  293. }
  294. }()
  295. }
  296. }