proxier_test.go 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143
  1. /*
  2. Copyright 2017 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 ipvs
  14. import (
  15. "bytes"
  16. "fmt"
  17. "net"
  18. "reflect"
  19. "strings"
  20. "testing"
  21. "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/apimachinery/pkg/util/intstr"
  25. "k8s.io/kubernetes/pkg/proxy"
  26. "k8s.io/utils/exec"
  27. fakeexec "k8s.io/utils/exec/testing"
  28. "k8s.io/apimachinery/pkg/util/sets"
  29. netlinktest "k8s.io/kubernetes/pkg/proxy/ipvs/testing"
  30. utilproxy "k8s.io/kubernetes/pkg/proxy/util"
  31. proxyutiltest "k8s.io/kubernetes/pkg/proxy/util/testing"
  32. utilipset "k8s.io/kubernetes/pkg/util/ipset"
  33. ipsettest "k8s.io/kubernetes/pkg/util/ipset/testing"
  34. utiliptables "k8s.io/kubernetes/pkg/util/iptables"
  35. iptablestest "k8s.io/kubernetes/pkg/util/iptables/testing"
  36. utilipvs "k8s.io/kubernetes/pkg/util/ipvs"
  37. ipvstest "k8s.io/kubernetes/pkg/util/ipvs/testing"
  38. )
  39. const testHostname = "test-hostname"
  40. type fakeIPGetter struct {
  41. nodeIPs []net.IP
  42. }
  43. func (f *fakeIPGetter) NodeIPs() ([]net.IP, error) {
  44. return f.nodeIPs, nil
  45. }
  46. type fakeHealthChecker struct {
  47. services map[types.NamespacedName]uint16
  48. Endpoints map[types.NamespacedName]int
  49. }
  50. func newFakeHealthChecker() *fakeHealthChecker {
  51. return &fakeHealthChecker{
  52. services: map[types.NamespacedName]uint16{},
  53. Endpoints: map[types.NamespacedName]int{},
  54. }
  55. }
  56. // fakePortOpener implements portOpener.
  57. type fakePortOpener struct {
  58. openPorts []*utilproxy.LocalPort
  59. }
  60. // OpenLocalPort fakes out the listen() and bind() used by syncProxyRules
  61. // to lock a local port.
  62. func (f *fakePortOpener) OpenLocalPort(lp *utilproxy.LocalPort) (utilproxy.Closeable, error) {
  63. f.openPorts = append(f.openPorts, lp)
  64. return nil, nil
  65. }
  66. func (fake *fakeHealthChecker) SyncServices(newServices map[types.NamespacedName]uint16) error {
  67. fake.services = newServices
  68. return nil
  69. }
  70. func (fake *fakeHealthChecker) SyncEndpoints(newEndpoints map[types.NamespacedName]int) error {
  71. fake.Endpoints = newEndpoints
  72. return nil
  73. }
  74. // fakeKernelHandler implements KernelHandler.
  75. type fakeKernelHandler struct {
  76. modules []string
  77. }
  78. func (fake *fakeKernelHandler) GetModules() ([]string, error) {
  79. return fake.modules, nil
  80. }
  81. // fakeKernelHandler implements KernelHandler.
  82. type fakeIPSetVersioner struct {
  83. version string
  84. err error
  85. }
  86. func (fake *fakeIPSetVersioner) GetVersion() (string, error) {
  87. return fake.version, fake.err
  88. }
  89. func NewFakeProxier(ipt utiliptables.Interface, ipvs utilipvs.Interface, ipset utilipset.Interface, nodeIPs []net.IP, excludeCIDRs []*net.IPNet) *Proxier {
  90. fcmd := fakeexec.FakeCmd{
  91. CombinedOutputScript: []fakeexec.FakeCombinedOutputAction{
  92. func() ([]byte, error) { return []byte("dummy device have been created"), nil },
  93. func() ([]byte, error) { return []byte(""), nil },
  94. },
  95. }
  96. fexec := &fakeexec.FakeExec{
  97. CommandScript: []fakeexec.FakeCommandAction{
  98. func(cmd string, args ...string) exec.Cmd { return fakeexec.InitFakeCmd(&fcmd, cmd, args...) },
  99. func(cmd string, args ...string) exec.Cmd { return fakeexec.InitFakeCmd(&fcmd, cmd, args...) },
  100. },
  101. LookPathFunc: func(cmd string) (string, error) { return cmd, nil },
  102. }
  103. // initialize ipsetList with all sets we needed
  104. ipsetList := make(map[string]*IPSet)
  105. for _, is := range ipsetInfo {
  106. ipsetList[is.name] = NewIPSet(ipset, is.name, is.setType, false, is.comment)
  107. }
  108. return &Proxier{
  109. exec: fexec,
  110. serviceMap: make(proxy.ServiceMap),
  111. serviceChanges: proxy.NewServiceChangeTracker(newServiceInfo, nil, nil),
  112. endpointsMap: make(proxy.EndpointsMap),
  113. endpointsChanges: proxy.NewEndpointChangeTracker(testHostname, nil, nil, nil),
  114. excludeCIDRs: excludeCIDRs,
  115. iptables: ipt,
  116. ipvs: ipvs,
  117. ipset: ipset,
  118. clusterCIDR: "10.0.0.0/24",
  119. strictARP: false,
  120. hostname: testHostname,
  121. portsMap: make(map[utilproxy.LocalPort]utilproxy.Closeable),
  122. portMapper: &fakePortOpener{[]*utilproxy.LocalPort{}},
  123. healthChecker: newFakeHealthChecker(),
  124. ipvsScheduler: DefaultScheduler,
  125. ipGetter: &fakeIPGetter{nodeIPs: nodeIPs},
  126. iptablesData: bytes.NewBuffer(nil),
  127. filterChainsData: bytes.NewBuffer(nil),
  128. natChains: bytes.NewBuffer(nil),
  129. natRules: bytes.NewBuffer(nil),
  130. filterChains: bytes.NewBuffer(nil),
  131. filterRules: bytes.NewBuffer(nil),
  132. netlinkHandle: netlinktest.NewFakeNetlinkHandle(),
  133. ipsetList: ipsetList,
  134. nodePortAddresses: make([]string, 0),
  135. networkInterfacer: proxyutiltest.NewFakeNetwork(),
  136. }
  137. }
  138. func makeNSN(namespace, name string) types.NamespacedName {
  139. return types.NamespacedName{Namespace: namespace, Name: name}
  140. }
  141. func makeServiceMap(proxier *Proxier, allServices ...*v1.Service) {
  142. for i := range allServices {
  143. proxier.OnServiceAdd(allServices[i])
  144. }
  145. proxier.mu.Lock()
  146. defer proxier.mu.Unlock()
  147. proxier.servicesSynced = true
  148. }
  149. func makeTestService(namespace, name string, svcFunc func(*v1.Service)) *v1.Service {
  150. svc := &v1.Service{
  151. ObjectMeta: metav1.ObjectMeta{
  152. Name: name,
  153. Namespace: namespace,
  154. Annotations: map[string]string{},
  155. },
  156. Spec: v1.ServiceSpec{},
  157. Status: v1.ServiceStatus{},
  158. }
  159. svcFunc(svc)
  160. return svc
  161. }
  162. func makeEndpointsMap(proxier *Proxier, allEndpoints ...*v1.Endpoints) {
  163. for i := range allEndpoints {
  164. proxier.OnEndpointsAdd(allEndpoints[i])
  165. }
  166. proxier.mu.Lock()
  167. defer proxier.mu.Unlock()
  168. proxier.endpointsSynced = true
  169. }
  170. func makeTestEndpoints(namespace, name string, eptFunc func(*v1.Endpoints)) *v1.Endpoints {
  171. ept := &v1.Endpoints{
  172. ObjectMeta: metav1.ObjectMeta{
  173. Name: name,
  174. Namespace: namespace,
  175. },
  176. }
  177. eptFunc(ept)
  178. return ept
  179. }
  180. func TestCleanupLeftovers(t *testing.T) {
  181. ipt := iptablestest.NewFake()
  182. ipvs := ipvstest.NewFake()
  183. ipset := ipsettest.NewFake(testIPSetVersion)
  184. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  185. svcIP := "10.20.30.41"
  186. svcPort := 80
  187. svcNodePort := 3001
  188. svcPortName := proxy.ServicePortName{
  189. NamespacedName: makeNSN("ns1", "svc1"),
  190. Port: "p80",
  191. }
  192. makeServiceMap(fp,
  193. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  194. svc.Spec.Type = "NodePort"
  195. svc.Spec.ClusterIP = svcIP
  196. svc.Spec.Ports = []v1.ServicePort{{
  197. Name: svcPortName.Port,
  198. Port: int32(svcPort),
  199. Protocol: v1.ProtocolTCP,
  200. NodePort: int32(svcNodePort),
  201. }}
  202. }),
  203. )
  204. epIP := "10.180.0.1"
  205. makeEndpointsMap(fp,
  206. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  207. ept.Subsets = []v1.EndpointSubset{{
  208. Addresses: []v1.EndpointAddress{{
  209. IP: epIP,
  210. }},
  211. Ports: []v1.EndpointPort{{
  212. Name: svcPortName.Port,
  213. Port: int32(svcPort),
  214. }},
  215. }}
  216. }),
  217. )
  218. fp.syncProxyRules()
  219. // test cleanup left over
  220. if CleanupLeftovers(ipvs, ipt, ipset, true) {
  221. t.Errorf("Cleanup leftovers failed")
  222. }
  223. }
  224. func TestCanUseIPVSProxier(t *testing.T) {
  225. testCases := []struct {
  226. mods []string
  227. kernelErr error
  228. ipsetVersion string
  229. ipsetErr error
  230. ok bool
  231. }{
  232. // case 0, kernel error
  233. {
  234. mods: []string{"foo", "bar", "baz"},
  235. kernelErr: fmt.Errorf("oops"),
  236. ipsetVersion: "0.0",
  237. ok: false,
  238. },
  239. // case 1, ipset error
  240. {
  241. mods: []string{"foo", "bar", "baz"},
  242. ipsetVersion: MinIPSetCheckVersion,
  243. ipsetErr: fmt.Errorf("oops"),
  244. ok: false,
  245. },
  246. // case 2, missing required kernel modules and ipset version too low
  247. {
  248. mods: []string{"foo", "bar", "baz"},
  249. ipsetVersion: "1.1",
  250. ok: false,
  251. },
  252. // case 3, missing required ip_vs_* kernel modules
  253. {
  254. mods: []string{"ip_vs", "a", "bc", "def"},
  255. ipsetVersion: MinIPSetCheckVersion,
  256. ok: false,
  257. },
  258. // case 4, ipset version too low
  259. {
  260. mods: []string{"ip_vs", "ip_vs_rr", "ip_vs_wrr", "ip_vs_sh", "nf_conntrack_ipv4"},
  261. ipsetVersion: "4.3.0",
  262. ok: false,
  263. },
  264. // case 5
  265. {
  266. mods: []string{"ip_vs", "ip_vs_rr", "ip_vs_wrr", "ip_vs_sh", "nf_conntrack_ipv4"},
  267. ipsetVersion: MinIPSetCheckVersion,
  268. ok: true,
  269. },
  270. // case 6
  271. {
  272. mods: []string{"ip_vs", "ip_vs_rr", "ip_vs_wrr", "ip_vs_sh", "nf_conntrack_ipv4", "foo", "bar"},
  273. ipsetVersion: "6.19",
  274. ok: true,
  275. },
  276. }
  277. for i := range testCases {
  278. handle := &fakeKernelHandler{modules: testCases[i].mods}
  279. versioner := &fakeIPSetVersioner{version: testCases[i].ipsetVersion, err: testCases[i].ipsetErr}
  280. ok, _ := CanUseIPVSProxier(handle, versioner)
  281. if ok != testCases[i].ok {
  282. t.Errorf("Case [%d], expect %v, got %v", i, testCases[i].ok, ok)
  283. }
  284. }
  285. }
  286. func TestGetNodeIPs(t *testing.T) {
  287. testCases := []struct {
  288. devAddresses map[string][]string
  289. expectIPs []string
  290. }{
  291. // case 0
  292. {
  293. devAddresses: map[string][]string{"eth0": {"1.2.3.4"}, "lo": {"127.0.0.1"}},
  294. expectIPs: []string{"1.2.3.4", "127.0.0.1"},
  295. },
  296. // case 1
  297. {
  298. devAddresses: map[string][]string{"lo": {"127.0.0.1"}},
  299. expectIPs: []string{"127.0.0.1"},
  300. },
  301. // case 2
  302. {
  303. devAddresses: map[string][]string{},
  304. expectIPs: []string{},
  305. },
  306. // case 3
  307. {
  308. devAddresses: map[string][]string{"encap0": {"10.20.30.40"}, "lo": {"127.0.0.1"}, "docker0": {"172.17.0.1"}},
  309. expectIPs: []string{"10.20.30.40", "127.0.0.1", "172.17.0.1"},
  310. },
  311. // case 4
  312. {
  313. devAddresses: map[string][]string{"encaps9": {"10.20.30.40"}, "lo": {"127.0.0.1"}, "encap7": {"10.20.30.31"}},
  314. expectIPs: []string{"10.20.30.40", "127.0.0.1", "10.20.30.31"},
  315. },
  316. // case 5
  317. {
  318. devAddresses: map[string][]string{"kube-ipvs0": {"1.2.3.4"}, "lo": {"127.0.0.1"}, "encap7": {"10.20.30.31"}},
  319. expectIPs: []string{"127.0.0.1", "10.20.30.31"},
  320. },
  321. // case 6
  322. {
  323. devAddresses: map[string][]string{"kube-ipvs0": {"1.2.3.4", "2.3.4.5"}, "lo": {"127.0.0.1"}},
  324. expectIPs: []string{"127.0.0.1"},
  325. },
  326. // case 7
  327. {
  328. devAddresses: map[string][]string{"kube-ipvs0": {"1.2.3.4", "2.3.4.5"}},
  329. expectIPs: []string{},
  330. },
  331. // case 8
  332. {
  333. devAddresses: map[string][]string{"kube-ipvs0": {"1.2.3.4", "2.3.4.5"}, "eth5": {"3.4.5.6"}, "lo": {"127.0.0.1"}},
  334. expectIPs: []string{"127.0.0.1", "3.4.5.6"},
  335. },
  336. // case 9
  337. {
  338. devAddresses: map[string][]string{"ipvs0": {"1.2.3.4"}, "lo": {"127.0.0.1"}, "encap7": {"10.20.30.31"}},
  339. expectIPs: []string{"127.0.0.1", "10.20.30.31", "1.2.3.4"},
  340. },
  341. }
  342. for i := range testCases {
  343. fake := netlinktest.NewFakeNetlinkHandle()
  344. for dev, addresses := range testCases[i].devAddresses {
  345. fake.SetLocalAddresses(dev, addresses...)
  346. }
  347. r := realIPGetter{nl: fake}
  348. ips, err := r.NodeIPs()
  349. if err != nil {
  350. t.Errorf("Unexpected error: %v", err)
  351. }
  352. ipStrs := sets.NewString()
  353. for _, ip := range ips {
  354. ipStrs.Insert(ip.String())
  355. }
  356. if !ipStrs.Equal(sets.NewString(testCases[i].expectIPs...)) {
  357. t.Errorf("case[%d], unexpected mismatch, expected: %v, got: %v", i, testCases[i].expectIPs, ips)
  358. }
  359. }
  360. }
  361. func TestNodePortUDP(t *testing.T) {
  362. nodeIP := net.ParseIP("100.101.102.103")
  363. ipt := iptablestest.NewFake()
  364. ipvs := ipvstest.NewFake()
  365. ipset := ipsettest.NewFake(testIPSetVersion)
  366. fp := NewFakeProxier(ipt, ipvs, ipset, []net.IP{nodeIP}, nil)
  367. svcIP := "10.20.30.41"
  368. svcPort := 80
  369. svcNodePort := 3001
  370. svcPortName := proxy.ServicePortName{
  371. NamespacedName: makeNSN("ns1", "svc1"),
  372. Port: "p80",
  373. }
  374. makeServiceMap(fp,
  375. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  376. svc.Spec.Type = "NodePort"
  377. svc.Spec.ClusterIP = svcIP
  378. svc.Spec.Ports = []v1.ServicePort{{
  379. Name: svcPortName.Port,
  380. Port: int32(svcPort),
  381. Protocol: v1.ProtocolUDP,
  382. NodePort: int32(svcNodePort),
  383. }}
  384. }),
  385. )
  386. epIP := "10.180.0.1"
  387. makeEndpointsMap(fp,
  388. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  389. ept.Subsets = []v1.EndpointSubset{{
  390. Addresses: []v1.EndpointAddress{{
  391. IP: epIP,
  392. }},
  393. Ports: []v1.EndpointPort{{
  394. Name: svcPortName.Port,
  395. Port: int32(svcPort),
  396. }},
  397. }}
  398. }),
  399. )
  400. fp.nodePortAddresses = []string{"0.0.0.0/0"}
  401. fp.syncProxyRules()
  402. // Check ipvs service and destinations
  403. epVS := &netlinktest.ExpectedVirtualServer{
  404. VSNum: 2, IP: nodeIP.String(), Port: uint16(svcNodePort), Protocol: string(v1.ProtocolTCP),
  405. RS: []netlinktest.ExpectedRealServer{{
  406. IP: epIP, Port: uint16(svcPort),
  407. }}}
  408. checkIPVS(t, fp, epVS)
  409. // check ipSet rules
  410. epIPSet := netlinktest.ExpectedIPSet{
  411. kubeNodePortSetUDP: {{
  412. Port: svcNodePort,
  413. Protocol: strings.ToLower(string(v1.ProtocolUDP)),
  414. SetType: utilipset.BitmapPort,
  415. }},
  416. }
  417. checkIPSet(t, fp, epIPSet)
  418. // Check iptables chain and rules
  419. epIpt := netlinktest.ExpectedIptablesChain{
  420. string(KubeNodePortChain): {{
  421. JumpChain: string(KubeMarkMasqChain), MatchSet: kubeNodePortSetUDP,
  422. }},
  423. string(kubeServicesChain): {{
  424. JumpChain: string(KubeNodePortChain), MatchSet: "",
  425. }},
  426. }
  427. checkIptables(t, ipt, epIpt)
  428. }
  429. func TestNodePort(t *testing.T) {
  430. ipt := iptablestest.NewFake()
  431. ipvs := ipvstest.NewFake()
  432. ipset := ipsettest.NewFake(testIPSetVersion)
  433. nodeIPv4 := net.ParseIP("100.101.102.103")
  434. nodeIPv6 := net.ParseIP("2001:db8::1:1")
  435. nodeIPs := sets.NewString(nodeIPv4.String(), nodeIPv6.String())
  436. fp := NewFakeProxier(ipt, ipvs, ipset, []net.IP{nodeIPv4, nodeIPv6}, nil)
  437. svcIP := "10.20.30.41"
  438. svcPort := 80
  439. svcNodePort := 3001
  440. svcPortName := proxy.ServicePortName{
  441. NamespacedName: makeNSN("ns1", "svc1"),
  442. Port: "p80",
  443. }
  444. makeServiceMap(fp,
  445. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  446. svc.Spec.Type = "NodePort"
  447. svc.Spec.ClusterIP = svcIP
  448. svc.Spec.Ports = []v1.ServicePort{{
  449. Name: svcPortName.Port,
  450. Port: int32(svcPort),
  451. Protocol: v1.ProtocolTCP,
  452. NodePort: int32(svcNodePort),
  453. }}
  454. }),
  455. )
  456. epIPv4 := "10.180.0.1"
  457. epIPv6 := "1002:ab8::2:10"
  458. epIPs := sets.NewString(epIPv4, epIPv6)
  459. makeEndpointsMap(fp,
  460. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  461. ept.Subsets = []v1.EndpointSubset{{
  462. Addresses: []v1.EndpointAddress{{
  463. IP: epIPv4,
  464. }, {
  465. IP: epIPv6,
  466. }},
  467. Ports: []v1.EndpointPort{{
  468. Name: svcPortName.Port,
  469. Port: int32(svcPort),
  470. }},
  471. }}
  472. }),
  473. )
  474. fp.nodePortAddresses = []string{"0.0.0.0/0"}
  475. fp.syncProxyRules()
  476. // Check ipvs service and destinations
  477. services, err := ipvs.GetVirtualServers()
  478. if err != nil {
  479. t.Errorf("Failed to get ipvs services, err: %v", err)
  480. }
  481. if len(services) != 3 {
  482. t.Errorf("Expect 3 ipvs services, got %d", len(services))
  483. }
  484. found := false
  485. for _, svc := range services {
  486. if nodeIPs.Has(svc.Address.String()) && svc.Port == uint16(svcNodePort) && svc.Protocol == string(v1.ProtocolTCP) {
  487. found = true
  488. destinations, err := ipvs.GetRealServers(svc)
  489. if err != nil {
  490. t.Errorf("Failed to get ipvs destinations, err: %v", err)
  491. }
  492. for _, dest := range destinations {
  493. if !epIPs.Has(dest.Address.String()) || dest.Port != uint16(svcPort) {
  494. t.Errorf("service Endpoint mismatch ipvs service destination")
  495. }
  496. }
  497. break
  498. }
  499. }
  500. if !found {
  501. t.Errorf("Expect node port type service, got none")
  502. }
  503. }
  504. func TestNodePortNoEndpoint(t *testing.T) {
  505. ipt := iptablestest.NewFake()
  506. ipvs := ipvstest.NewFake()
  507. ipset := ipsettest.NewFake(testIPSetVersion)
  508. nodeIP := net.ParseIP("100.101.102.103")
  509. fp := NewFakeProxier(ipt, ipvs, ipset, []net.IP{nodeIP}, nil)
  510. svcIP := "10.20.30.41"
  511. svcPort := 80
  512. svcNodePort := 3001
  513. svcPortName := proxy.ServicePortName{
  514. NamespacedName: makeNSN("ns1", "svc1"),
  515. Port: "p80",
  516. }
  517. makeServiceMap(fp,
  518. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  519. svc.Spec.Type = "NodePort"
  520. svc.Spec.ClusterIP = svcIP
  521. svc.Spec.Ports = []v1.ServicePort{{
  522. Name: svcPortName.Port,
  523. Port: int32(svcPort),
  524. Protocol: v1.ProtocolTCP,
  525. NodePort: int32(svcNodePort),
  526. }}
  527. }),
  528. )
  529. makeEndpointsMap(fp)
  530. fp.nodePortAddresses = []string{"0.0.0.0/0"}
  531. fp.syncProxyRules()
  532. // Check ipvs service and destinations
  533. services, err := ipvs.GetVirtualServers()
  534. if err != nil {
  535. t.Errorf("Failed to get ipvs services, err: %v", err)
  536. }
  537. if len(services) != 2 {
  538. t.Errorf("Expect 2 ipvs services, got %d", len(services))
  539. }
  540. found := false
  541. for _, svc := range services {
  542. if svc.Address.Equal(nodeIP) && svc.Port == uint16(svcNodePort) && svc.Protocol == string(v1.ProtocolTCP) {
  543. found = true
  544. destinations, _ := ipvs.GetRealServers(svc)
  545. if len(destinations) != 0 {
  546. t.Errorf("Unexpected %d destinations, expect 0 destinations", len(destinations))
  547. }
  548. break
  549. }
  550. }
  551. if !found {
  552. t.Errorf("Expect node port type service, got none")
  553. }
  554. }
  555. func TestClusterIPNoEndpoint(t *testing.T) {
  556. ipt := iptablestest.NewFake()
  557. ipvs := ipvstest.NewFake()
  558. ipset := ipsettest.NewFake(testIPSetVersion)
  559. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  560. svcIP := "10.20.30.41"
  561. svcPort := 80
  562. svcPortName := proxy.ServicePortName{
  563. NamespacedName: makeNSN("ns1", "svc1"),
  564. Port: "p80",
  565. }
  566. makeServiceMap(fp,
  567. makeTestService(svcPortName.Namespace, svcPortName.Namespace, func(svc *v1.Service) {
  568. svc.Spec.ClusterIP = svcIP
  569. svc.Spec.Ports = []v1.ServicePort{{
  570. Name: svcPortName.Port,
  571. Port: int32(svcPort),
  572. Protocol: v1.ProtocolTCP,
  573. }}
  574. }),
  575. )
  576. makeEndpointsMap(fp)
  577. fp.syncProxyRules()
  578. // check ipvs service and destinations
  579. services, err := ipvs.GetVirtualServers()
  580. if err != nil {
  581. t.Errorf("Failed to get ipvs services, err: %v", err)
  582. }
  583. if len(services) != 1 {
  584. t.Errorf("Expect 1 ipvs services, got %d", len(services))
  585. } else {
  586. if services[0].Address.String() != svcIP || services[0].Port != uint16(svcPort) || services[0].Protocol != string(v1.ProtocolTCP) {
  587. t.Errorf("Unexpected mismatch service")
  588. } else {
  589. destinations, _ := ipvs.GetRealServers(services[0])
  590. if len(destinations) != 0 {
  591. t.Errorf("Unexpected %d destinations, expect 0 destinations", len(destinations))
  592. }
  593. }
  594. }
  595. }
  596. func TestClusterIP(t *testing.T) {
  597. ipt := iptablestest.NewFake()
  598. ipvs := ipvstest.NewFake()
  599. ipset := ipsettest.NewFake(testIPSetVersion)
  600. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  601. svcIPv4 := "10.20.30.41"
  602. svcPortV4 := 80
  603. svcPortNameV4 := proxy.ServicePortName{
  604. NamespacedName: makeNSN("ns1", "svc1"),
  605. Port: "p80",
  606. }
  607. svcIPv6 := "1002:ab8::2:1"
  608. svcPortV6 := 8080
  609. svcPortNameV6 := proxy.ServicePortName{
  610. NamespacedName: makeNSN("ns2", "svc2"),
  611. Port: "p8080",
  612. }
  613. makeServiceMap(fp,
  614. makeTestService(svcPortNameV4.Namespace, svcPortNameV4.Name, func(svc *v1.Service) {
  615. svc.Spec.ClusterIP = svcIPv4
  616. svc.Spec.Ports = []v1.ServicePort{{
  617. Name: svcPortNameV4.Port,
  618. Port: int32(svcPortV4),
  619. Protocol: v1.ProtocolTCP,
  620. }}
  621. }),
  622. makeTestService(svcPortNameV6.Namespace, svcPortNameV6.Name, func(svc *v1.Service) {
  623. svc.Spec.ClusterIP = svcIPv6
  624. svc.Spec.Ports = []v1.ServicePort{{
  625. Name: svcPortNameV6.Port,
  626. Port: int32(svcPortV6),
  627. Protocol: v1.ProtocolTCP,
  628. }}
  629. }),
  630. )
  631. epIPv4 := "10.180.0.1"
  632. epIPv6 := "1009:ab8::5:6"
  633. makeEndpointsMap(fp,
  634. makeTestEndpoints(svcPortNameV4.Namespace, svcPortNameV4.Name, func(ept *v1.Endpoints) {
  635. ept.Subsets = []v1.EndpointSubset{{
  636. Addresses: []v1.EndpointAddress{{
  637. IP: epIPv4,
  638. }},
  639. Ports: []v1.EndpointPort{{
  640. Name: svcPortNameV4.Port,
  641. Port: int32(svcPortV4),
  642. }},
  643. }}
  644. }),
  645. makeTestEndpoints(svcPortNameV6.Namespace, svcPortNameV6.Name, func(ept *v1.Endpoints) {
  646. ept.Subsets = []v1.EndpointSubset{{
  647. Addresses: []v1.EndpointAddress{{
  648. IP: epIPv6,
  649. }},
  650. Ports: []v1.EndpointPort{{
  651. Name: svcPortNameV6.Port,
  652. Port: int32(svcPortV6),
  653. }},
  654. }}
  655. }),
  656. )
  657. fp.syncProxyRules()
  658. // check ipvs service and destinations
  659. services, err := ipvs.GetVirtualServers()
  660. if err != nil {
  661. t.Errorf("Failed to get ipvs services, err: %v", err)
  662. }
  663. if len(services) != 2 {
  664. t.Errorf("Expect 2 ipvs services, got %d", len(services))
  665. }
  666. for i := range services {
  667. // Check services
  668. if services[i].Address.String() == svcIPv4 {
  669. if services[i].Port != uint16(svcPortV4) || services[i].Protocol != string(v1.ProtocolTCP) {
  670. t.Errorf("Unexpected mismatch service")
  671. }
  672. // Check destinations
  673. destinations, _ := ipvs.GetRealServers(services[i])
  674. if len(destinations) != 1 {
  675. t.Errorf("Expected 1 destinations, got %d destinations", len(destinations))
  676. continue
  677. }
  678. if destinations[0].Address.String() != epIPv4 || destinations[0].Port != uint16(svcPortV4) {
  679. t.Errorf("Unexpected mismatch destinations")
  680. }
  681. }
  682. if services[i].Address.String() == svcIPv6 {
  683. if services[i].Port != uint16(svcPortV6) || services[i].Protocol != string(v1.ProtocolTCP) {
  684. t.Errorf("Unexpected mismatch service")
  685. }
  686. // Check destinations
  687. destinations, _ := ipvs.GetRealServers(services[i])
  688. if len(destinations) != 1 {
  689. t.Errorf("Expected 1 destinations, got %d destinations", len(destinations))
  690. continue
  691. }
  692. if destinations[0].Address.String() != epIPv6 || destinations[0].Port != uint16(svcPortV6) {
  693. t.Errorf("Unexpected mismatch destinations")
  694. }
  695. }
  696. }
  697. }
  698. func TestExternalIPsNoEndpoint(t *testing.T) {
  699. ipt := iptablestest.NewFake()
  700. ipvs := ipvstest.NewFake()
  701. ipset := ipsettest.NewFake(testIPSetVersion)
  702. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  703. svcIP := "10.20.30.41"
  704. svcPort := 80
  705. svcExternalIPs := "50.60.70.81"
  706. svcPortName := proxy.ServicePortName{
  707. NamespacedName: makeNSN("ns1", "svc1"),
  708. Port: "p80",
  709. }
  710. makeServiceMap(fp,
  711. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  712. svc.Spec.Type = "ClusterIP"
  713. svc.Spec.ClusterIP = svcIP
  714. svc.Spec.ExternalIPs = []string{svcExternalIPs}
  715. svc.Spec.Ports = []v1.ServicePort{{
  716. Name: svcPortName.Port,
  717. Port: int32(svcPort),
  718. Protocol: v1.ProtocolTCP,
  719. TargetPort: intstr.FromInt(svcPort),
  720. }}
  721. }),
  722. )
  723. makeEndpointsMap(fp)
  724. fp.syncProxyRules()
  725. // check ipvs service and destinations
  726. services, err := ipvs.GetVirtualServers()
  727. if err != nil {
  728. t.Errorf("Failed to get ipvs services, err: %v", err)
  729. }
  730. if len(services) != 2 {
  731. t.Errorf("Expect 2 ipvs services, got %d", len(services))
  732. }
  733. found := false
  734. for _, svc := range services {
  735. if svc.Address.String() == svcExternalIPs && svc.Port == uint16(svcPort) && svc.Protocol == string(v1.ProtocolTCP) {
  736. found = true
  737. destinations, _ := ipvs.GetRealServers(svc)
  738. if len(destinations) != 0 {
  739. t.Errorf("Unexpected %d destinations, expect 0 destinations", len(destinations))
  740. }
  741. break
  742. }
  743. }
  744. if !found {
  745. t.Errorf("Expect external ip type service, got none")
  746. }
  747. }
  748. func TestExternalIPs(t *testing.T) {
  749. ipt := iptablestest.NewFake()
  750. ipvs := ipvstest.NewFake()
  751. ipset := ipsettest.NewFake(testIPSetVersion)
  752. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  753. svcIP := "10.20.30.41"
  754. svcPort := 80
  755. svcExternalIPs := sets.NewString("50.60.70.81", "2012::51", "127.0.0.1")
  756. svcPortName := proxy.ServicePortName{
  757. NamespacedName: makeNSN("ns1", "svc1"),
  758. Port: "p80",
  759. }
  760. makeServiceMap(fp,
  761. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  762. svc.Spec.Type = "ClusterIP"
  763. svc.Spec.ClusterIP = svcIP
  764. svc.Spec.ExternalIPs = svcExternalIPs.UnsortedList()
  765. svc.Spec.Ports = []v1.ServicePort{{
  766. Name: svcPortName.Port,
  767. Port: int32(svcPort),
  768. Protocol: v1.ProtocolTCP,
  769. TargetPort: intstr.FromInt(svcPort),
  770. }}
  771. }),
  772. )
  773. epIP := "10.180.0.1"
  774. makeEndpointsMap(fp,
  775. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  776. ept.Subsets = []v1.EndpointSubset{{
  777. Addresses: []v1.EndpointAddress{{
  778. IP: epIP,
  779. }},
  780. Ports: []v1.EndpointPort{{
  781. Name: svcPortName.Port,
  782. Port: int32(svcPort),
  783. }},
  784. }}
  785. }),
  786. )
  787. fp.syncProxyRules()
  788. // check ipvs service and destinations
  789. services, err := ipvs.GetVirtualServers()
  790. if err != nil {
  791. t.Errorf("Failed to get ipvs services, err: %v", err)
  792. }
  793. if len(services) != 4 {
  794. t.Errorf("Expect 4 ipvs services, got %d", len(services))
  795. }
  796. found := false
  797. for _, svc := range services {
  798. if svcExternalIPs.Has(svc.Address.String()) && svc.Port == uint16(svcPort) && svc.Protocol == string(v1.ProtocolTCP) {
  799. found = true
  800. destinations, _ := ipvs.GetRealServers(svc)
  801. for _, dest := range destinations {
  802. if dest.Address.String() != epIP || dest.Port != uint16(svcPort) {
  803. t.Errorf("service Endpoint mismatch ipvs service destination")
  804. }
  805. }
  806. break
  807. }
  808. }
  809. if !found {
  810. t.Errorf("Expect external ip type service, got none")
  811. }
  812. }
  813. func TestLoadBalancer(t *testing.T) {
  814. ipt, fp := buildFakeProxier()
  815. svcIP := "10.20.30.41"
  816. svcPort := 80
  817. svcNodePort := 3001
  818. svcLBIP := "1.2.3.4"
  819. svcPortName := proxy.ServicePortName{
  820. NamespacedName: makeNSN("ns1", "svc1"),
  821. Port: "p80",
  822. }
  823. makeServiceMap(fp,
  824. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  825. svc.Spec.Type = "LoadBalancer"
  826. svc.Spec.ClusterIP = svcIP
  827. svc.Spec.Ports = []v1.ServicePort{{
  828. Name: svcPortName.Port,
  829. Port: int32(svcPort),
  830. Protocol: v1.ProtocolTCP,
  831. NodePort: int32(svcNodePort),
  832. }}
  833. svc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{{
  834. IP: svcLBIP,
  835. }}
  836. }),
  837. )
  838. epIP := "10.180.0.1"
  839. makeEndpointsMap(fp,
  840. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  841. ept.Subsets = []v1.EndpointSubset{{
  842. Addresses: []v1.EndpointAddress{{
  843. IP: epIP,
  844. }},
  845. Ports: []v1.EndpointPort{{
  846. Name: svcPortName.Port,
  847. Port: int32(svcPort),
  848. }},
  849. }}
  850. }),
  851. )
  852. fp.syncProxyRules()
  853. // Expect 2 services and 1 destination
  854. epVS := &netlinktest.ExpectedVirtualServer{
  855. VSNum: 2, IP: svcLBIP, Port: uint16(svcNodePort), Protocol: string(v1.ProtocolTCP),
  856. RS: []netlinktest.ExpectedRealServer{{
  857. IP: epIP, Port: uint16(svcPort),
  858. }}}
  859. checkIPVS(t, fp, epVS)
  860. // check ipSet rules
  861. epIPSet := netlinktest.ExpectedIPSet{
  862. kubeLoadBalancerSet: {{
  863. IP: svcLBIP,
  864. Port: svcPort,
  865. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  866. SetType: utilipset.HashIPPort,
  867. }},
  868. }
  869. checkIPSet(t, fp, epIPSet)
  870. // Check iptables chain and rules
  871. epIpt := netlinktest.ExpectedIptablesChain{
  872. string(kubeServicesChain): {{
  873. JumpChain: string(KubeLoadBalancerChain), MatchSet: kubeLoadBalancerSet,
  874. }},
  875. string(kubeLoadBalancerSet): {{
  876. JumpChain: string(KubeMarkMasqChain), MatchSet: "",
  877. }},
  878. }
  879. checkIptables(t, ipt, epIpt)
  880. }
  881. func TestOnlyLocalNodePorts(t *testing.T) {
  882. nodeIP := net.ParseIP("100.101.102.103")
  883. ipt, fp := buildFakeProxier()
  884. svcIP := "10.20.30.41"
  885. svcPort := 80
  886. svcNodePort := 3001
  887. svcPortName := proxy.ServicePortName{
  888. NamespacedName: makeNSN("ns1", "svc1"),
  889. Port: "p80",
  890. }
  891. makeServiceMap(fp,
  892. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  893. svc.Spec.Type = "NodePort"
  894. svc.Spec.ClusterIP = svcIP
  895. svc.Spec.Ports = []v1.ServicePort{{
  896. Name: svcPortName.Port,
  897. Port: int32(svcPort),
  898. Protocol: v1.ProtocolTCP,
  899. NodePort: int32(svcNodePort),
  900. }}
  901. svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal
  902. }),
  903. )
  904. epIP := "10.180.0.1"
  905. epIP1 := "10.180.1.1"
  906. thisHostname := testHostname
  907. otherHostname := "other-hostname"
  908. makeEndpointsMap(fp,
  909. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  910. ept.Subsets = []v1.EndpointSubset{
  911. { // **local** endpoint address, should be added as RS
  912. Addresses: []v1.EndpointAddress{{
  913. IP: epIP,
  914. NodeName: &thisHostname,
  915. }},
  916. Ports: []v1.EndpointPort{{
  917. Name: svcPortName.Port,
  918. Port: int32(svcPort),
  919. }}},
  920. { // **remote** endpoint address, should not be added as RS
  921. Addresses: []v1.EndpointAddress{{
  922. IP: epIP1,
  923. NodeName: &otherHostname,
  924. }},
  925. Ports: []v1.EndpointPort{{
  926. Name: svcPortName.Port,
  927. Port: int32(svcPort),
  928. }},
  929. }}
  930. }),
  931. )
  932. itf := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: 0}
  933. addrs := []net.Addr{proxyutiltest.AddrStruct{Val: "100.101.102.103/24"}}
  934. itf1 := net.Interface{Index: 1, MTU: 0, Name: "eth1", HardwareAddr: nil, Flags: 0}
  935. addrs1 := []net.Addr{proxyutiltest.AddrStruct{Val: "2001:db8::0/64"}}
  936. fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf, addrs)
  937. fp.networkInterfacer.(*proxyutiltest.FakeNetwork).AddInterfaceAddr(&itf1, addrs1)
  938. fp.nodePortAddresses = []string{"100.101.102.0/24", "2001:db8::0/64"}
  939. fp.syncProxyRules()
  940. // Expect 3 services and 1 destination
  941. epVS := &netlinktest.ExpectedVirtualServer{
  942. VSNum: 3, IP: nodeIP.String(), Port: uint16(svcNodePort), Protocol: string(v1.ProtocolTCP),
  943. RS: []netlinktest.ExpectedRealServer{{
  944. IP: epIP, Port: uint16(svcPort),
  945. }}}
  946. checkIPVS(t, fp, epVS)
  947. // check ipSet rules
  948. epEntry := &utilipset.Entry{
  949. Port: svcNodePort,
  950. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  951. SetType: utilipset.BitmapPort,
  952. }
  953. epIPSet := netlinktest.ExpectedIPSet{
  954. kubeNodePortSetTCP: {epEntry},
  955. kubeNodePortLocalSetTCP: {epEntry},
  956. }
  957. checkIPSet(t, fp, epIPSet)
  958. // Check iptables chain and rules
  959. epIpt := netlinktest.ExpectedIptablesChain{
  960. string(kubeServicesChain): {{
  961. JumpChain: string(KubeNodePortChain), MatchSet: "",
  962. }},
  963. string(KubeNodePortChain): {{
  964. JumpChain: "RETURN", MatchSet: kubeNodePortLocalSetTCP,
  965. }, {
  966. JumpChain: string(KubeMarkMasqChain), MatchSet: kubeNodePortSetTCP,
  967. }},
  968. }
  969. checkIptables(t, ipt, epIpt)
  970. }
  971. func TestLoadBalanceSourceRanges(t *testing.T) {
  972. ipt, fp := buildFakeProxier()
  973. svcIP := "10.20.30.41"
  974. svcPort := 80
  975. svcLBIP := "1.2.3.4"
  976. svcLBSource := "10.0.0.0/8"
  977. svcPortName := proxy.ServicePortName{
  978. NamespacedName: makeNSN("ns1", "svc1"),
  979. Port: "p80",
  980. }
  981. epIP := "10.180.0.1"
  982. makeServiceMap(fp,
  983. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  984. svc.Spec.Type = "LoadBalancer"
  985. svc.Spec.ClusterIP = svcIP
  986. svc.Spec.Ports = []v1.ServicePort{{
  987. Name: svcPortName.Port,
  988. Port: int32(svcPort),
  989. Protocol: v1.ProtocolTCP,
  990. }}
  991. svc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{{
  992. IP: svcLBIP,
  993. }}
  994. svc.Spec.LoadBalancerSourceRanges = []string{
  995. svcLBSource,
  996. }
  997. }),
  998. )
  999. makeEndpointsMap(fp,
  1000. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  1001. ept.Subsets = []v1.EndpointSubset{{
  1002. Addresses: []v1.EndpointAddress{{
  1003. IP: epIP,
  1004. NodeName: nil,
  1005. }},
  1006. Ports: []v1.EndpointPort{{
  1007. Name: svcPortName.Port,
  1008. Port: int32(svcPort),
  1009. }},
  1010. }}
  1011. }),
  1012. )
  1013. fp.syncProxyRules()
  1014. // Check ipvs service and destinations
  1015. epVS := &netlinktest.ExpectedVirtualServer{
  1016. VSNum: 2, IP: svcLBIP, Port: uint16(svcPort), Protocol: string(v1.ProtocolTCP),
  1017. RS: []netlinktest.ExpectedRealServer{{
  1018. IP: epIP, Port: uint16(svcPort),
  1019. }}}
  1020. checkIPVS(t, fp, epVS)
  1021. // Check ipset entry
  1022. epIPSet := netlinktest.ExpectedIPSet{
  1023. kubeLoadBalancerSet: {{
  1024. IP: svcLBIP,
  1025. Port: svcPort,
  1026. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  1027. SetType: utilipset.HashIPPort,
  1028. }},
  1029. kubeLoadbalancerFWSet: {{
  1030. IP: svcLBIP,
  1031. Port: svcPort,
  1032. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  1033. SetType: utilipset.HashIPPort,
  1034. }},
  1035. kubeLoadBalancerSourceCIDRSet: {{
  1036. IP: svcLBIP,
  1037. Port: svcPort,
  1038. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  1039. Net: svcLBSource,
  1040. SetType: utilipset.HashIPPortNet,
  1041. }},
  1042. }
  1043. checkIPSet(t, fp, epIPSet)
  1044. // Check iptables chain and rules
  1045. epIpt := netlinktest.ExpectedIptablesChain{
  1046. string(kubeServicesChain): {{
  1047. JumpChain: string(KubeLoadBalancerChain), MatchSet: kubeLoadBalancerSet,
  1048. }},
  1049. string(KubeLoadBalancerChain): {{
  1050. JumpChain: string(KubeFireWallChain), MatchSet: kubeLoadbalancerFWSet,
  1051. }, {
  1052. JumpChain: string(KubeMarkMasqChain), MatchSet: "",
  1053. }},
  1054. string(KubeFireWallChain): {{
  1055. JumpChain: "RETURN", MatchSet: kubeLoadBalancerSourceCIDRSet,
  1056. }, {
  1057. JumpChain: string(KubeMarkDropChain), MatchSet: "",
  1058. }},
  1059. }
  1060. checkIptables(t, ipt, epIpt)
  1061. }
  1062. func TestAcceptIPVSTraffic(t *testing.T) {
  1063. ipt, fp := buildFakeProxier()
  1064. ingressIP := "1.2.3.4"
  1065. externalIP := []string{"5.6.7.8"}
  1066. svcInfos := []struct {
  1067. svcType v1.ServiceType
  1068. svcIP string
  1069. svcName string
  1070. epIP string
  1071. }{
  1072. {v1.ServiceTypeClusterIP, "10.20.30.40", "svc1", "10.180.0.1"},
  1073. {v1.ServiceTypeLoadBalancer, "10.20.30.41", "svc2", "10.180.0.2"},
  1074. {v1.ServiceTypeNodePort, "10.20.30.42", "svc3", "10.180.0.3"},
  1075. }
  1076. for _, svcInfo := range svcInfos {
  1077. makeServiceMap(fp,
  1078. makeTestService("ns1", svcInfo.svcName, func(svc *v1.Service) {
  1079. svc.Spec.Type = svcInfo.svcType
  1080. svc.Spec.ClusterIP = svcInfo.svcIP
  1081. svc.Spec.Ports = []v1.ServicePort{{
  1082. Name: "p80",
  1083. Port: 80,
  1084. Protocol: v1.ProtocolTCP,
  1085. NodePort: 80,
  1086. }}
  1087. if svcInfo.svcType == v1.ServiceTypeLoadBalancer {
  1088. svc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{{
  1089. IP: ingressIP,
  1090. }}
  1091. }
  1092. if svcInfo.svcType == v1.ServiceTypeClusterIP {
  1093. svc.Spec.ExternalIPs = externalIP
  1094. }
  1095. }),
  1096. )
  1097. makeEndpointsMap(fp,
  1098. makeTestEndpoints("ns1", "p80", func(ept *v1.Endpoints) {
  1099. ept.Subsets = []v1.EndpointSubset{{
  1100. Addresses: []v1.EndpointAddress{{
  1101. IP: svcInfo.epIP,
  1102. }},
  1103. Ports: []v1.EndpointPort{{
  1104. Name: "p80",
  1105. Port: 80,
  1106. }},
  1107. }}
  1108. }),
  1109. )
  1110. }
  1111. fp.syncProxyRules()
  1112. // Check iptables chain and rules
  1113. epIpt := netlinktest.ExpectedIptablesChain{
  1114. string(kubeServicesChain): {
  1115. {JumpChain: "ACCEPT", MatchSet: kubeClusterIPSet},
  1116. {JumpChain: "ACCEPT", MatchSet: kubeLoadBalancerSet},
  1117. {JumpChain: "ACCEPT", MatchSet: kubeExternalIPSet},
  1118. },
  1119. }
  1120. checkIptables(t, ipt, epIpt)
  1121. }
  1122. func TestOnlyLocalLoadBalancing(t *testing.T) {
  1123. ipt, fp := buildFakeProxier()
  1124. svcIP := "10.20.30.41"
  1125. svcPort := 80
  1126. svcNodePort := 3001
  1127. svcLBIP := "1.2.3.4"
  1128. svcPortName := proxy.ServicePortName{
  1129. NamespacedName: makeNSN("ns1", "svc1"),
  1130. Port: "p80",
  1131. }
  1132. makeServiceMap(fp,
  1133. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  1134. svc.Spec.Type = "LoadBalancer"
  1135. svc.Spec.ClusterIP = svcIP
  1136. svc.Spec.Ports = []v1.ServicePort{{
  1137. Name: svcPortName.Port,
  1138. Port: int32(svcPort),
  1139. Protocol: v1.ProtocolTCP,
  1140. NodePort: int32(svcNodePort),
  1141. }}
  1142. svc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{{
  1143. IP: svcLBIP,
  1144. }}
  1145. svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal
  1146. }),
  1147. )
  1148. epIP := "10.180.0.1"
  1149. epIP1 := "10.180.1.1"
  1150. thisHostname := testHostname
  1151. otherHostname := "other-hostname"
  1152. makeEndpointsMap(fp,
  1153. makeTestEndpoints(svcPortName.Namespace, svcPortName.Name, func(ept *v1.Endpoints) {
  1154. ept.Subsets = []v1.EndpointSubset{
  1155. { // **local** endpoint address, should be added as RS
  1156. Addresses: []v1.EndpointAddress{{
  1157. IP: epIP,
  1158. NodeName: &thisHostname,
  1159. }},
  1160. Ports: []v1.EndpointPort{{
  1161. Name: svcPortName.Port,
  1162. Port: int32(svcPort),
  1163. }}},
  1164. { // **remote** endpoint address, should not be added as RS
  1165. Addresses: []v1.EndpointAddress{{
  1166. IP: epIP1,
  1167. NodeName: &otherHostname,
  1168. }},
  1169. Ports: []v1.EndpointPort{{
  1170. Name: svcPortName.Port,
  1171. Port: int32(svcPort),
  1172. }},
  1173. }}
  1174. }),
  1175. )
  1176. fp.syncProxyRules()
  1177. // Expect 2 services and 1 destination
  1178. epVS := &netlinktest.ExpectedVirtualServer{
  1179. VSNum: 2, IP: svcLBIP, Port: uint16(svcPort), Protocol: string(v1.ProtocolTCP),
  1180. RS: []netlinktest.ExpectedRealServer{{
  1181. IP: epIP, Port: uint16(svcPort),
  1182. }}}
  1183. checkIPVS(t, fp, epVS)
  1184. // check ipSet rules
  1185. epIPSet := netlinktest.ExpectedIPSet{
  1186. kubeLoadBalancerSet: {{
  1187. IP: svcLBIP,
  1188. Port: svcPort,
  1189. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  1190. SetType: utilipset.HashIPPort,
  1191. }},
  1192. kubeLoadBalancerLocalSet: {{
  1193. IP: svcLBIP,
  1194. Port: svcPort,
  1195. Protocol: strings.ToLower(string(v1.ProtocolTCP)),
  1196. SetType: utilipset.HashIPPort,
  1197. }},
  1198. }
  1199. checkIPSet(t, fp, epIPSet)
  1200. // Check iptables chain and rules
  1201. epIpt := netlinktest.ExpectedIptablesChain{
  1202. string(kubeServicesChain): {{
  1203. JumpChain: string(KubeLoadBalancerChain), MatchSet: kubeLoadBalancerSet,
  1204. }},
  1205. string(KubeLoadBalancerChain): {{
  1206. JumpChain: "RETURN", MatchSet: kubeLoadBalancerLocalSet,
  1207. }, {
  1208. JumpChain: string(KubeMarkMasqChain), MatchSet: "",
  1209. }},
  1210. }
  1211. checkIptables(t, ipt, epIpt)
  1212. }
  1213. func addTestPort(array []v1.ServicePort, name string, protocol v1.Protocol, port, nodeport int32, targetPort int) []v1.ServicePort {
  1214. svcPort := v1.ServicePort{
  1215. Name: name,
  1216. Protocol: protocol,
  1217. Port: port,
  1218. NodePort: nodeport,
  1219. TargetPort: intstr.FromInt(targetPort),
  1220. }
  1221. return append(array, svcPort)
  1222. }
  1223. func TestBuildServiceMapAddRemove(t *testing.T) {
  1224. ipt := iptablestest.NewFake()
  1225. ipvs := ipvstest.NewFake()
  1226. ipset := ipsettest.NewFake(testIPSetVersion)
  1227. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  1228. services := []*v1.Service{
  1229. makeTestService("somewhere-else", "cluster-ip", func(svc *v1.Service) {
  1230. svc.Spec.Type = v1.ServiceTypeClusterIP
  1231. svc.Spec.ClusterIP = "172.16.55.4"
  1232. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "something", "UDP", 1234, 4321, 0)
  1233. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "somethingelse", "UDP", 1235, 5321, 0)
  1234. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "somesctp", "SCTP", 1236, 6321, 0)
  1235. }),
  1236. makeTestService("somewhere-else", "node-port", func(svc *v1.Service) {
  1237. svc.Spec.Type = v1.ServiceTypeNodePort
  1238. svc.Spec.ClusterIP = "172.16.55.10"
  1239. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "blahblah", "UDP", 345, 678, 0)
  1240. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "moreblahblah", "TCP", 344, 677, 0)
  1241. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "sctpblah", "SCTP", 343, 676, 0)
  1242. }),
  1243. makeTestService("somewhere", "load-balancer", func(svc *v1.Service) {
  1244. svc.Spec.Type = v1.ServiceTypeLoadBalancer
  1245. svc.Spec.ClusterIP = "172.16.55.11"
  1246. svc.Spec.LoadBalancerIP = "5.6.7.8"
  1247. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "foobar", "UDP", 8675, 30061, 7000)
  1248. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "baz", "UDP", 8676, 30062, 7001)
  1249. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "sctpfoo", "SCTP", 8677, 30063, 7002)
  1250. svc.Status.LoadBalancer = v1.LoadBalancerStatus{
  1251. Ingress: []v1.LoadBalancerIngress{
  1252. {IP: "10.1.2.4"},
  1253. },
  1254. }
  1255. }),
  1256. makeTestService("somewhere", "only-local-load-balancer", func(svc *v1.Service) {
  1257. svc.Spec.Type = v1.ServiceTypeLoadBalancer
  1258. svc.Spec.ClusterIP = "172.16.55.12"
  1259. svc.Spec.LoadBalancerIP = "5.6.7.8"
  1260. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "foobar2", "UDP", 8677, 30063, 7002)
  1261. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "baz", "UDP", 8678, 30064, 7003)
  1262. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "sctpbaz", "SCTP", 8679, 30065, 7004)
  1263. svc.Status.LoadBalancer = v1.LoadBalancerStatus{
  1264. Ingress: []v1.LoadBalancerIngress{
  1265. {IP: "10.1.2.3"},
  1266. },
  1267. }
  1268. svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal
  1269. svc.Spec.HealthCheckNodePort = 345
  1270. }),
  1271. }
  1272. for i := range services {
  1273. fp.OnServiceAdd(services[i])
  1274. }
  1275. result := proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1276. if len(fp.serviceMap) != 12 {
  1277. t.Errorf("expected service map length 12, got %v", fp.serviceMap)
  1278. }
  1279. // The only-local-loadbalancer ones get added
  1280. if len(result.HCServiceNodePorts) != 1 {
  1281. t.Errorf("expected 1 healthcheck port, got %v", result.HCServiceNodePorts)
  1282. } else {
  1283. nsn := makeNSN("somewhere", "only-local-load-balancer")
  1284. if port, found := result.HCServiceNodePorts[nsn]; !found || port != 345 {
  1285. t.Errorf("expected healthcheck port [%q]=345: got %v", nsn, result.HCServiceNodePorts)
  1286. }
  1287. }
  1288. if len(result.UDPStaleClusterIP) != 0 {
  1289. // Services only added, so nothing stale yet
  1290. t.Errorf("expected stale UDP services length 0, got %d", len(result.UDPStaleClusterIP))
  1291. }
  1292. // Remove some stuff
  1293. // oneService is a modification of services[0] with removed first port.
  1294. oneService := makeTestService("somewhere-else", "cluster-ip", func(svc *v1.Service) {
  1295. svc.Spec.Type = v1.ServiceTypeClusterIP
  1296. svc.Spec.ClusterIP = "172.16.55.4"
  1297. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "somethingelse", "UDP", 1235, 5321, 0)
  1298. })
  1299. fp.OnServiceUpdate(services[0], oneService)
  1300. fp.OnServiceDelete(services[1])
  1301. fp.OnServiceDelete(services[2])
  1302. fp.OnServiceDelete(services[3])
  1303. result = proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1304. if len(fp.serviceMap) != 1 {
  1305. t.Errorf("expected service map length 1, got %v", fp.serviceMap)
  1306. }
  1307. if len(result.HCServiceNodePorts) != 0 {
  1308. t.Errorf("expected 0 healthcheck ports, got %v", result.HCServiceNodePorts)
  1309. }
  1310. // All services but one were deleted. While you'd expect only the ClusterIPs
  1311. // from the three deleted services here, we still have the ClusterIP for
  1312. // the not-deleted service, because one of it's ServicePorts was deleted.
  1313. expectedStaleUDPServices := []string{"172.16.55.10", "172.16.55.4", "172.16.55.11", "172.16.55.12"}
  1314. if len(result.UDPStaleClusterIP) != len(expectedStaleUDPServices) {
  1315. t.Errorf("expected stale UDP services length %d, got %v", len(expectedStaleUDPServices), result.UDPStaleClusterIP.List())
  1316. }
  1317. for _, ip := range expectedStaleUDPServices {
  1318. if !result.UDPStaleClusterIP.Has(ip) {
  1319. t.Errorf("expected stale UDP service service %s", ip)
  1320. }
  1321. }
  1322. }
  1323. func TestBuildServiceMapServiceHeadless(t *testing.T) {
  1324. ipt := iptablestest.NewFake()
  1325. ipvs := ipvstest.NewFake()
  1326. ipset := ipsettest.NewFake(testIPSetVersion)
  1327. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  1328. makeServiceMap(fp,
  1329. makeTestService("somewhere-else", "headless", func(svc *v1.Service) {
  1330. svc.Spec.Type = v1.ServiceTypeClusterIP
  1331. svc.Spec.ClusterIP = v1.ClusterIPNone
  1332. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "rpc", "UDP", 1234, 0, 0)
  1333. }),
  1334. makeTestService("somewhere-else", "headless-without-port", func(svc *v1.Service) {
  1335. svc.Spec.Type = v1.ServiceTypeClusterIP
  1336. svc.Spec.ClusterIP = v1.ClusterIPNone
  1337. }),
  1338. makeTestService("somewhere-else", "headless-sctp", func(svc *v1.Service) {
  1339. svc.Spec.Type = v1.ServiceTypeClusterIP
  1340. svc.Spec.ClusterIP = v1.ClusterIPNone
  1341. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "sip", "SCTP", 1235, 0, 0)
  1342. }),
  1343. )
  1344. // Headless service should be ignored
  1345. result := proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1346. if len(fp.serviceMap) != 0 {
  1347. t.Errorf("expected service map length 0, got %d", len(fp.serviceMap))
  1348. }
  1349. // No proxied services, so no healthchecks
  1350. if len(result.HCServiceNodePorts) != 0 {
  1351. t.Errorf("expected healthcheck ports length 0, got %d", len(result.HCServiceNodePorts))
  1352. }
  1353. if len(result.UDPStaleClusterIP) != 0 {
  1354. t.Errorf("expected stale UDP services length 0, got %d", len(result.UDPStaleClusterIP))
  1355. }
  1356. }
  1357. func TestBuildServiceMapServiceTypeExternalName(t *testing.T) {
  1358. ipt := iptablestest.NewFake()
  1359. ipvs := ipvstest.NewFake()
  1360. ipset := ipsettest.NewFake(testIPSetVersion)
  1361. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  1362. makeServiceMap(fp,
  1363. makeTestService("somewhere-else", "external-name", func(svc *v1.Service) {
  1364. svc.Spec.Type = v1.ServiceTypeExternalName
  1365. svc.Spec.ClusterIP = "172.16.55.4" // Should be ignored
  1366. svc.Spec.ExternalName = "foo2.bar.com"
  1367. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "blah", "UDP", 1235, 5321, 0)
  1368. }),
  1369. )
  1370. result := proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1371. if len(fp.serviceMap) != 0 {
  1372. t.Errorf("expected service map length 0, got %v", fp.serviceMap)
  1373. }
  1374. // No proxied services, so no healthchecks
  1375. if len(result.HCServiceNodePorts) != 0 {
  1376. t.Errorf("expected healthcheck ports length 0, got %v", result.HCServiceNodePorts)
  1377. }
  1378. if len(result.UDPStaleClusterIP) != 0 {
  1379. t.Errorf("expected stale UDP services length 0, got %v", result.UDPStaleClusterIP)
  1380. }
  1381. }
  1382. func TestBuildServiceMapServiceUpdate(t *testing.T) {
  1383. ipt := iptablestest.NewFake()
  1384. ipvs := ipvstest.NewFake()
  1385. ipset := ipsettest.NewFake(testIPSetVersion)
  1386. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  1387. servicev1 := makeTestService("somewhere", "some-service", func(svc *v1.Service) {
  1388. svc.Spec.Type = v1.ServiceTypeClusterIP
  1389. svc.Spec.ClusterIP = "172.16.55.4"
  1390. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "something", "UDP", 1234, 4321, 0)
  1391. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "somethingelse", "TCP", 1235, 5321, 0)
  1392. })
  1393. servicev2 := makeTestService("somewhere", "some-service", func(svc *v1.Service) {
  1394. svc.Spec.Type = v1.ServiceTypeLoadBalancer
  1395. svc.Spec.ClusterIP = "172.16.55.4"
  1396. svc.Spec.LoadBalancerIP = "5.6.7.8"
  1397. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "something", "UDP", 1234, 4321, 7002)
  1398. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "somethingelse", "TCP", 1235, 5321, 7003)
  1399. svc.Status.LoadBalancer = v1.LoadBalancerStatus{
  1400. Ingress: []v1.LoadBalancerIngress{
  1401. {IP: "10.1.2.3"},
  1402. },
  1403. }
  1404. svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal
  1405. svc.Spec.HealthCheckNodePort = 345
  1406. })
  1407. fp.OnServiceAdd(servicev1)
  1408. result := proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1409. if len(fp.serviceMap) != 2 {
  1410. t.Errorf("expected service map length 2, got %v", fp.serviceMap)
  1411. }
  1412. if len(result.HCServiceNodePorts) != 0 {
  1413. t.Errorf("expected healthcheck ports length 0, got %v", result.HCServiceNodePorts)
  1414. }
  1415. if len(result.UDPStaleClusterIP) != 0 {
  1416. // Services only added, so nothing stale yet
  1417. t.Errorf("expected stale UDP services length 0, got %d", len(result.UDPStaleClusterIP))
  1418. }
  1419. // Change service to load-balancer
  1420. fp.OnServiceUpdate(servicev1, servicev2)
  1421. result = proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1422. if len(fp.serviceMap) != 2 {
  1423. t.Errorf("expected service map length 2, got %v", fp.serviceMap)
  1424. }
  1425. if len(result.HCServiceNodePorts) != 1 {
  1426. t.Errorf("expected healthcheck ports length 1, got %v", result.HCServiceNodePorts)
  1427. }
  1428. if len(result.UDPStaleClusterIP) != 0 {
  1429. t.Errorf("expected stale UDP services length 0, got %v", result.UDPStaleClusterIP.List())
  1430. }
  1431. // No change; make sure the service map stays the same and there are
  1432. // no health-check changes
  1433. fp.OnServiceUpdate(servicev2, servicev2)
  1434. result = proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1435. if len(fp.serviceMap) != 2 {
  1436. t.Errorf("expected service map length 2, got %v", fp.serviceMap)
  1437. }
  1438. if len(result.HCServiceNodePorts) != 1 {
  1439. t.Errorf("expected healthcheck ports length 1, got %v", result.HCServiceNodePorts)
  1440. }
  1441. if len(result.UDPStaleClusterIP) != 0 {
  1442. t.Errorf("expected stale UDP services length 0, got %v", result.UDPStaleClusterIP.List())
  1443. }
  1444. // And back to ClusterIP
  1445. fp.OnServiceUpdate(servicev2, servicev1)
  1446. result = proxy.UpdateServiceMap(fp.serviceMap, fp.serviceChanges)
  1447. if len(fp.serviceMap) != 2 {
  1448. t.Errorf("expected service map length 2, got %v", fp.serviceMap)
  1449. }
  1450. if len(result.HCServiceNodePorts) != 0 {
  1451. t.Errorf("expected healthcheck ports length 0, got %v", result.HCServiceNodePorts)
  1452. }
  1453. if len(result.UDPStaleClusterIP) != 0 {
  1454. // Services only added, so nothing stale yet
  1455. t.Errorf("expected stale UDP services length 0, got %d", len(result.UDPStaleClusterIP))
  1456. }
  1457. }
  1458. func TestSessionAffinity(t *testing.T) {
  1459. ipt := iptablestest.NewFake()
  1460. ipvs := ipvstest.NewFake()
  1461. ipset := ipsettest.NewFake(testIPSetVersion)
  1462. nodeIP := net.ParseIP("100.101.102.103")
  1463. fp := NewFakeProxier(ipt, ipvs, ipset, []net.IP{nodeIP}, nil)
  1464. svcIP := "10.20.30.41"
  1465. svcPort := 80
  1466. svcNodePort := 3001
  1467. svcExternalIPs := "50.60.70.81"
  1468. svcPortName := proxy.ServicePortName{
  1469. NamespacedName: makeNSN("ns1", "svc1"),
  1470. Port: "p80",
  1471. }
  1472. timeoutSeconds := v1.DefaultClientIPServiceAffinitySeconds
  1473. makeServiceMap(fp,
  1474. makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) {
  1475. svc.Spec.Type = "NodePort"
  1476. svc.Spec.ClusterIP = svcIP
  1477. svc.Spec.ExternalIPs = []string{svcExternalIPs}
  1478. svc.Spec.SessionAffinity = v1.ServiceAffinityClientIP
  1479. svc.Spec.SessionAffinityConfig = &v1.SessionAffinityConfig{
  1480. ClientIP: &v1.ClientIPConfig{
  1481. TimeoutSeconds: &timeoutSeconds,
  1482. },
  1483. }
  1484. svc.Spec.Ports = []v1.ServicePort{{
  1485. Name: svcPortName.Port,
  1486. Port: int32(svcPort),
  1487. Protocol: v1.ProtocolTCP,
  1488. NodePort: int32(svcNodePort),
  1489. }}
  1490. }),
  1491. )
  1492. makeEndpointsMap(fp)
  1493. fp.syncProxyRules()
  1494. // check ipvs service and destinations
  1495. services, err := ipvs.GetVirtualServers()
  1496. if err != nil {
  1497. t.Errorf("Failed to get ipvs services, err: %v", err)
  1498. }
  1499. for _, svc := range services {
  1500. if svc.Timeout != uint32(v1.DefaultClientIPServiceAffinitySeconds) {
  1501. t.Errorf("Unexpected mismatch ipvs service session affinity timeout: %d, expected: %d", svc.Timeout, v1.DefaultClientIPServiceAffinitySeconds)
  1502. }
  1503. }
  1504. }
  1505. func makeServicePortName(ns, name, port string) proxy.ServicePortName {
  1506. return proxy.ServicePortName{
  1507. NamespacedName: makeNSN(ns, name),
  1508. Port: port,
  1509. }
  1510. }
  1511. func Test_updateEndpointsMap(t *testing.T) {
  1512. var nodeName = testHostname
  1513. emptyEndpoint := func(ept *v1.Endpoints) {
  1514. ept.Subsets = []v1.EndpointSubset{}
  1515. }
  1516. unnamedPort := func(ept *v1.Endpoints) {
  1517. ept.Subsets = []v1.EndpointSubset{{
  1518. Addresses: []v1.EndpointAddress{{
  1519. IP: "1.1.1.1",
  1520. }},
  1521. Ports: []v1.EndpointPort{{
  1522. Port: 11,
  1523. }},
  1524. }}
  1525. }
  1526. unnamedPortLocal := func(ept *v1.Endpoints) {
  1527. ept.Subsets = []v1.EndpointSubset{{
  1528. Addresses: []v1.EndpointAddress{{
  1529. IP: "1.1.1.1",
  1530. NodeName: &nodeName,
  1531. }},
  1532. Ports: []v1.EndpointPort{{
  1533. Port: 11,
  1534. }},
  1535. }}
  1536. }
  1537. namedPortLocal := func(ept *v1.Endpoints) {
  1538. ept.Subsets = []v1.EndpointSubset{{
  1539. Addresses: []v1.EndpointAddress{{
  1540. IP: "1.1.1.1",
  1541. NodeName: &nodeName,
  1542. }},
  1543. Ports: []v1.EndpointPort{{
  1544. Name: "p11",
  1545. Port: 11,
  1546. }},
  1547. }}
  1548. }
  1549. namedPort := func(ept *v1.Endpoints) {
  1550. ept.Subsets = []v1.EndpointSubset{{
  1551. Addresses: []v1.EndpointAddress{{
  1552. IP: "1.1.1.1",
  1553. }},
  1554. Ports: []v1.EndpointPort{{
  1555. Name: "p11",
  1556. Port: 11,
  1557. }},
  1558. }}
  1559. }
  1560. namedPortRenamed := func(ept *v1.Endpoints) {
  1561. ept.Subsets = []v1.EndpointSubset{{
  1562. Addresses: []v1.EndpointAddress{{
  1563. IP: "1.1.1.1",
  1564. }},
  1565. Ports: []v1.EndpointPort{{
  1566. Name: "p11-2",
  1567. Port: 11,
  1568. }},
  1569. }}
  1570. }
  1571. namedPortRenumbered := func(ept *v1.Endpoints) {
  1572. ept.Subsets = []v1.EndpointSubset{{
  1573. Addresses: []v1.EndpointAddress{{
  1574. IP: "1.1.1.1",
  1575. }},
  1576. Ports: []v1.EndpointPort{{
  1577. Name: "p11",
  1578. Port: 22,
  1579. }},
  1580. }}
  1581. }
  1582. namedPortsLocalNoLocal := func(ept *v1.Endpoints) {
  1583. ept.Subsets = []v1.EndpointSubset{{
  1584. Addresses: []v1.EndpointAddress{{
  1585. IP: "1.1.1.1",
  1586. }, {
  1587. IP: "1.1.1.2",
  1588. NodeName: &nodeName,
  1589. }},
  1590. Ports: []v1.EndpointPort{{
  1591. Name: "p11",
  1592. Port: 11,
  1593. }, {
  1594. Name: "p12",
  1595. Port: 12,
  1596. }},
  1597. }}
  1598. }
  1599. multipleSubsets := func(ept *v1.Endpoints) {
  1600. ept.Subsets = []v1.EndpointSubset{{
  1601. Addresses: []v1.EndpointAddress{{
  1602. IP: "1.1.1.1",
  1603. }},
  1604. Ports: []v1.EndpointPort{{
  1605. Name: "p11",
  1606. Port: 11,
  1607. }},
  1608. }, {
  1609. Addresses: []v1.EndpointAddress{{
  1610. IP: "1.1.1.2",
  1611. }},
  1612. Ports: []v1.EndpointPort{{
  1613. Name: "p12",
  1614. Port: 12,
  1615. }},
  1616. }}
  1617. }
  1618. multipleSubsetsWithLocal := func(ept *v1.Endpoints) {
  1619. ept.Subsets = []v1.EndpointSubset{{
  1620. Addresses: []v1.EndpointAddress{{
  1621. IP: "1.1.1.1",
  1622. }},
  1623. Ports: []v1.EndpointPort{{
  1624. Name: "p11",
  1625. Port: 11,
  1626. }},
  1627. }, {
  1628. Addresses: []v1.EndpointAddress{{
  1629. IP: "1.1.1.2",
  1630. NodeName: &nodeName,
  1631. }},
  1632. Ports: []v1.EndpointPort{{
  1633. Name: "p12",
  1634. Port: 12,
  1635. }},
  1636. }}
  1637. }
  1638. multipleSubsetsMultiplePortsLocal := func(ept *v1.Endpoints) {
  1639. ept.Subsets = []v1.EndpointSubset{{
  1640. Addresses: []v1.EndpointAddress{{
  1641. IP: "1.1.1.1",
  1642. NodeName: &nodeName,
  1643. }},
  1644. Ports: []v1.EndpointPort{{
  1645. Name: "p11",
  1646. Port: 11,
  1647. }, {
  1648. Name: "p12",
  1649. Port: 12,
  1650. }},
  1651. }, {
  1652. Addresses: []v1.EndpointAddress{{
  1653. IP: "1.1.1.3",
  1654. }},
  1655. Ports: []v1.EndpointPort{{
  1656. Name: "p13",
  1657. Port: 13,
  1658. }},
  1659. }}
  1660. }
  1661. multipleSubsetsIPsPorts1 := func(ept *v1.Endpoints) {
  1662. ept.Subsets = []v1.EndpointSubset{{
  1663. Addresses: []v1.EndpointAddress{{
  1664. IP: "1.1.1.1",
  1665. }, {
  1666. IP: "1.1.1.2",
  1667. NodeName: &nodeName,
  1668. }},
  1669. Ports: []v1.EndpointPort{{
  1670. Name: "p11",
  1671. Port: 11,
  1672. }, {
  1673. Name: "p12",
  1674. Port: 12,
  1675. }},
  1676. }, {
  1677. Addresses: []v1.EndpointAddress{{
  1678. IP: "1.1.1.3",
  1679. }, {
  1680. IP: "1.1.1.4",
  1681. NodeName: &nodeName,
  1682. }},
  1683. Ports: []v1.EndpointPort{{
  1684. Name: "p13",
  1685. Port: 13,
  1686. }, {
  1687. Name: "p14",
  1688. Port: 14,
  1689. }},
  1690. }}
  1691. }
  1692. multipleSubsetsIPsPorts2 := func(ept *v1.Endpoints) {
  1693. ept.Subsets = []v1.EndpointSubset{{
  1694. Addresses: []v1.EndpointAddress{{
  1695. IP: "2.2.2.1",
  1696. }, {
  1697. IP: "2.2.2.2",
  1698. NodeName: &nodeName,
  1699. }},
  1700. Ports: []v1.EndpointPort{{
  1701. Name: "p21",
  1702. Port: 21,
  1703. }, {
  1704. Name: "p22",
  1705. Port: 22,
  1706. }},
  1707. }}
  1708. }
  1709. complexBefore1 := func(ept *v1.Endpoints) {
  1710. ept.Subsets = []v1.EndpointSubset{{
  1711. Addresses: []v1.EndpointAddress{{
  1712. IP: "1.1.1.1",
  1713. }},
  1714. Ports: []v1.EndpointPort{{
  1715. Name: "p11",
  1716. Port: 11,
  1717. }},
  1718. }}
  1719. }
  1720. complexBefore2 := func(ept *v1.Endpoints) {
  1721. ept.Subsets = []v1.EndpointSubset{{
  1722. Addresses: []v1.EndpointAddress{{
  1723. IP: "2.2.2.2",
  1724. NodeName: &nodeName,
  1725. }, {
  1726. IP: "2.2.2.22",
  1727. NodeName: &nodeName,
  1728. }},
  1729. Ports: []v1.EndpointPort{{
  1730. Name: "p22",
  1731. Port: 22,
  1732. }},
  1733. }, {
  1734. Addresses: []v1.EndpointAddress{{
  1735. IP: "2.2.2.3",
  1736. NodeName: &nodeName,
  1737. }},
  1738. Ports: []v1.EndpointPort{{
  1739. Name: "p23",
  1740. Port: 23,
  1741. }},
  1742. }}
  1743. }
  1744. complexBefore4 := func(ept *v1.Endpoints) {
  1745. ept.Subsets = []v1.EndpointSubset{{
  1746. Addresses: []v1.EndpointAddress{{
  1747. IP: "4.4.4.4",
  1748. NodeName: &nodeName,
  1749. }, {
  1750. IP: "4.4.4.5",
  1751. NodeName: &nodeName,
  1752. }},
  1753. Ports: []v1.EndpointPort{{
  1754. Name: "p44",
  1755. Port: 44,
  1756. }},
  1757. }, {
  1758. Addresses: []v1.EndpointAddress{{
  1759. IP: "4.4.4.6",
  1760. NodeName: &nodeName,
  1761. }},
  1762. Ports: []v1.EndpointPort{{
  1763. Name: "p45",
  1764. Port: 45,
  1765. }},
  1766. }}
  1767. }
  1768. complexAfter1 := func(ept *v1.Endpoints) {
  1769. ept.Subsets = []v1.EndpointSubset{{
  1770. Addresses: []v1.EndpointAddress{{
  1771. IP: "1.1.1.1",
  1772. }, {
  1773. IP: "1.1.1.11",
  1774. }},
  1775. Ports: []v1.EndpointPort{{
  1776. Name: "p11",
  1777. Port: 11,
  1778. }},
  1779. }, {
  1780. Addresses: []v1.EndpointAddress{{
  1781. IP: "1.1.1.2",
  1782. }},
  1783. Ports: []v1.EndpointPort{{
  1784. Name: "p12",
  1785. Port: 12,
  1786. }, {
  1787. Name: "p122",
  1788. Port: 122,
  1789. }},
  1790. }}
  1791. }
  1792. complexAfter3 := func(ept *v1.Endpoints) {
  1793. ept.Subsets = []v1.EndpointSubset{{
  1794. Addresses: []v1.EndpointAddress{{
  1795. IP: "3.3.3.3",
  1796. }},
  1797. Ports: []v1.EndpointPort{{
  1798. Name: "p33",
  1799. Port: 33,
  1800. }},
  1801. }}
  1802. }
  1803. complexAfter4 := func(ept *v1.Endpoints) {
  1804. ept.Subsets = []v1.EndpointSubset{{
  1805. Addresses: []v1.EndpointAddress{{
  1806. IP: "4.4.4.4",
  1807. NodeName: &nodeName,
  1808. }},
  1809. Ports: []v1.EndpointPort{{
  1810. Name: "p44",
  1811. Port: 44,
  1812. }},
  1813. }}
  1814. }
  1815. testCases := []struct {
  1816. // previousEndpoints and currentEndpoints are used to call appropriate
  1817. // handlers OnEndpoints* (based on whether corresponding values are nil
  1818. // or non-nil) and must be of equal length.
  1819. previousEndpoints []*v1.Endpoints
  1820. currentEndpoints []*v1.Endpoints
  1821. oldEndpoints map[proxy.ServicePortName][]*proxy.BaseEndpointInfo
  1822. expectedResult map[proxy.ServicePortName][]*proxy.BaseEndpointInfo
  1823. expectedStaleEndpoints []proxy.ServiceEndpoint
  1824. expectedStaleServiceNames map[proxy.ServicePortName]bool
  1825. expectedHealthchecks map[types.NamespacedName]int
  1826. }{{
  1827. // Case[0]: nothing
  1828. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{},
  1829. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{},
  1830. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  1831. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  1832. expectedHealthchecks: map[types.NamespacedName]int{},
  1833. }, {
  1834. // Case[1]: no change, unnamed port
  1835. previousEndpoints: []*v1.Endpoints{
  1836. makeTestEndpoints("ns1", "ep1", unnamedPort),
  1837. },
  1838. currentEndpoints: []*v1.Endpoints{
  1839. makeTestEndpoints("ns1", "ep1", unnamedPort),
  1840. },
  1841. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1842. makeServicePortName("ns1", "ep1", ""): {
  1843. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1844. },
  1845. },
  1846. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1847. makeServicePortName("ns1", "ep1", ""): {
  1848. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1849. },
  1850. },
  1851. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  1852. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  1853. expectedHealthchecks: map[types.NamespacedName]int{},
  1854. }, {
  1855. // Case[2]: no change, named port, local
  1856. previousEndpoints: []*v1.Endpoints{
  1857. makeTestEndpoints("ns1", "ep1", namedPortLocal),
  1858. },
  1859. currentEndpoints: []*v1.Endpoints{
  1860. makeTestEndpoints("ns1", "ep1", namedPortLocal),
  1861. },
  1862. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1863. makeServicePortName("ns1", "ep1", "p11"): {
  1864. {Endpoint: "1.1.1.1:11", IsLocal: true},
  1865. },
  1866. },
  1867. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1868. makeServicePortName("ns1", "ep1", "p11"): {
  1869. {Endpoint: "1.1.1.1:11", IsLocal: true},
  1870. },
  1871. },
  1872. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  1873. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  1874. expectedHealthchecks: map[types.NamespacedName]int{
  1875. makeNSN("ns1", "ep1"): 1,
  1876. },
  1877. }, {
  1878. // Case[3]: no change, multiple subsets
  1879. previousEndpoints: []*v1.Endpoints{
  1880. makeTestEndpoints("ns1", "ep1", multipleSubsets),
  1881. },
  1882. currentEndpoints: []*v1.Endpoints{
  1883. makeTestEndpoints("ns1", "ep1", multipleSubsets),
  1884. },
  1885. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1886. makeServicePortName("ns1", "ep1", "p11"): {
  1887. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1888. },
  1889. makeServicePortName("ns1", "ep1", "p12"): {
  1890. {Endpoint: "1.1.1.2:12", IsLocal: false},
  1891. },
  1892. },
  1893. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1894. makeServicePortName("ns1", "ep1", "p11"): {
  1895. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1896. },
  1897. makeServicePortName("ns1", "ep1", "p12"): {
  1898. {Endpoint: "1.1.1.2:12", IsLocal: false},
  1899. },
  1900. },
  1901. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  1902. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  1903. expectedHealthchecks: map[types.NamespacedName]int{},
  1904. }, {
  1905. // Case[4]: no change, multiple subsets, multiple ports, local
  1906. previousEndpoints: []*v1.Endpoints{
  1907. makeTestEndpoints("ns1", "ep1", multipleSubsetsMultiplePortsLocal),
  1908. },
  1909. currentEndpoints: []*v1.Endpoints{
  1910. makeTestEndpoints("ns1", "ep1", multipleSubsetsMultiplePortsLocal),
  1911. },
  1912. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1913. makeServicePortName("ns1", "ep1", "p11"): {
  1914. {Endpoint: "1.1.1.1:11", IsLocal: true},
  1915. },
  1916. makeServicePortName("ns1", "ep1", "p12"): {
  1917. {Endpoint: "1.1.1.1:12", IsLocal: true},
  1918. },
  1919. makeServicePortName("ns1", "ep1", "p13"): {
  1920. {Endpoint: "1.1.1.3:13", IsLocal: false},
  1921. },
  1922. },
  1923. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1924. makeServicePortName("ns1", "ep1", "p11"): {
  1925. {Endpoint: "1.1.1.1:11", IsLocal: true},
  1926. },
  1927. makeServicePortName("ns1", "ep1", "p12"): {
  1928. {Endpoint: "1.1.1.1:12", IsLocal: true},
  1929. },
  1930. makeServicePortName("ns1", "ep1", "p13"): {
  1931. {Endpoint: "1.1.1.3:13", IsLocal: false},
  1932. },
  1933. },
  1934. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  1935. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  1936. expectedHealthchecks: map[types.NamespacedName]int{
  1937. makeNSN("ns1", "ep1"): 1,
  1938. },
  1939. }, {
  1940. // Case[5]: no change, multiple endpoints, subsets, IPs, and ports
  1941. previousEndpoints: []*v1.Endpoints{
  1942. makeTestEndpoints("ns1", "ep1", multipleSubsetsIPsPorts1),
  1943. makeTestEndpoints("ns2", "ep2", multipleSubsetsIPsPorts2),
  1944. },
  1945. currentEndpoints: []*v1.Endpoints{
  1946. makeTestEndpoints("ns1", "ep1", multipleSubsetsIPsPorts1),
  1947. makeTestEndpoints("ns2", "ep2", multipleSubsetsIPsPorts2),
  1948. },
  1949. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1950. makeServicePortName("ns1", "ep1", "p11"): {
  1951. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1952. {Endpoint: "1.1.1.2:11", IsLocal: true},
  1953. },
  1954. makeServicePortName("ns1", "ep1", "p12"): {
  1955. {Endpoint: "1.1.1.1:12", IsLocal: false},
  1956. {Endpoint: "1.1.1.2:12", IsLocal: true},
  1957. },
  1958. makeServicePortName("ns1", "ep1", "p13"): {
  1959. {Endpoint: "1.1.1.3:13", IsLocal: false},
  1960. {Endpoint: "1.1.1.4:13", IsLocal: true},
  1961. },
  1962. makeServicePortName("ns1", "ep1", "p14"): {
  1963. {Endpoint: "1.1.1.3:14", IsLocal: false},
  1964. {Endpoint: "1.1.1.4:14", IsLocal: true},
  1965. },
  1966. makeServicePortName("ns2", "ep2", "p21"): {
  1967. {Endpoint: "2.2.2.1:21", IsLocal: false},
  1968. {Endpoint: "2.2.2.2:21", IsLocal: true},
  1969. },
  1970. makeServicePortName("ns2", "ep2", "p22"): {
  1971. {Endpoint: "2.2.2.1:22", IsLocal: false},
  1972. {Endpoint: "2.2.2.2:22", IsLocal: true},
  1973. },
  1974. },
  1975. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  1976. makeServicePortName("ns1", "ep1", "p11"): {
  1977. {Endpoint: "1.1.1.1:11", IsLocal: false},
  1978. {Endpoint: "1.1.1.2:11", IsLocal: true},
  1979. },
  1980. makeServicePortName("ns1", "ep1", "p12"): {
  1981. {Endpoint: "1.1.1.1:12", IsLocal: false},
  1982. {Endpoint: "1.1.1.2:12", IsLocal: true},
  1983. },
  1984. makeServicePortName("ns1", "ep1", "p13"): {
  1985. {Endpoint: "1.1.1.3:13", IsLocal: false},
  1986. {Endpoint: "1.1.1.4:13", IsLocal: true},
  1987. },
  1988. makeServicePortName("ns1", "ep1", "p14"): {
  1989. {Endpoint: "1.1.1.3:14", IsLocal: false},
  1990. {Endpoint: "1.1.1.4:14", IsLocal: true},
  1991. },
  1992. makeServicePortName("ns2", "ep2", "p21"): {
  1993. {Endpoint: "2.2.2.1:21", IsLocal: false},
  1994. {Endpoint: "2.2.2.2:21", IsLocal: true},
  1995. },
  1996. makeServicePortName("ns2", "ep2", "p22"): {
  1997. {Endpoint: "2.2.2.1:22", IsLocal: false},
  1998. {Endpoint: "2.2.2.2:22", IsLocal: true},
  1999. },
  2000. },
  2001. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  2002. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  2003. expectedHealthchecks: map[types.NamespacedName]int{
  2004. makeNSN("ns1", "ep1"): 2,
  2005. makeNSN("ns2", "ep2"): 1,
  2006. },
  2007. }, {
  2008. // Case[6]: add an Endpoints
  2009. previousEndpoints: []*v1.Endpoints{
  2010. nil,
  2011. },
  2012. currentEndpoints: []*v1.Endpoints{
  2013. makeTestEndpoints("ns1", "ep1", unnamedPortLocal),
  2014. },
  2015. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{},
  2016. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2017. makeServicePortName("ns1", "ep1", ""): {
  2018. {Endpoint: "1.1.1.1:11", IsLocal: true},
  2019. },
  2020. },
  2021. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  2022. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2023. makeServicePortName("ns1", "ep1", ""): true,
  2024. },
  2025. expectedHealthchecks: map[types.NamespacedName]int{
  2026. makeNSN("ns1", "ep1"): 1,
  2027. },
  2028. }, {
  2029. // Case[7]: remove an Endpoints
  2030. previousEndpoints: []*v1.Endpoints{
  2031. makeTestEndpoints("ns1", "ep1", unnamedPortLocal),
  2032. },
  2033. currentEndpoints: []*v1.Endpoints{
  2034. nil,
  2035. },
  2036. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2037. makeServicePortName("ns1", "ep1", ""): {
  2038. {Endpoint: "1.1.1.1:11", IsLocal: true},
  2039. },
  2040. },
  2041. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{},
  2042. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2043. Endpoint: "1.1.1.1:11",
  2044. ServicePortName: makeServicePortName("ns1", "ep1", ""),
  2045. }},
  2046. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  2047. expectedHealthchecks: map[types.NamespacedName]int{},
  2048. }, {
  2049. // Case[8]: add an IP and port
  2050. previousEndpoints: []*v1.Endpoints{
  2051. makeTestEndpoints("ns1", "ep1", namedPort),
  2052. },
  2053. currentEndpoints: []*v1.Endpoints{
  2054. makeTestEndpoints("ns1", "ep1", namedPortsLocalNoLocal),
  2055. },
  2056. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2057. makeServicePortName("ns1", "ep1", "p11"): {
  2058. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2059. },
  2060. },
  2061. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2062. makeServicePortName("ns1", "ep1", "p11"): {
  2063. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2064. {Endpoint: "1.1.1.2:11", IsLocal: true},
  2065. },
  2066. makeServicePortName("ns1", "ep1", "p12"): {
  2067. {Endpoint: "1.1.1.1:12", IsLocal: false},
  2068. {Endpoint: "1.1.1.2:12", IsLocal: true},
  2069. },
  2070. },
  2071. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  2072. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2073. makeServicePortName("ns1", "ep1", "p12"): true,
  2074. },
  2075. expectedHealthchecks: map[types.NamespacedName]int{
  2076. makeNSN("ns1", "ep1"): 1,
  2077. },
  2078. }, {
  2079. // Case[9]: remove an IP and port
  2080. previousEndpoints: []*v1.Endpoints{
  2081. makeTestEndpoints("ns1", "ep1", namedPortsLocalNoLocal),
  2082. },
  2083. currentEndpoints: []*v1.Endpoints{
  2084. makeTestEndpoints("ns1", "ep1", namedPort),
  2085. },
  2086. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2087. makeServicePortName("ns1", "ep1", "p11"): {
  2088. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2089. {Endpoint: "1.1.1.2:11", IsLocal: true},
  2090. },
  2091. makeServicePortName("ns1", "ep1", "p12"): {
  2092. {Endpoint: "1.1.1.1:12", IsLocal: false},
  2093. {Endpoint: "1.1.1.2:12", IsLocal: true},
  2094. },
  2095. },
  2096. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2097. makeServicePortName("ns1", "ep1", "p11"): {
  2098. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2099. },
  2100. },
  2101. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2102. Endpoint: "1.1.1.2:11",
  2103. ServicePortName: makeServicePortName("ns1", "ep1", "p11"),
  2104. }, {
  2105. Endpoint: "1.1.1.1:12",
  2106. ServicePortName: makeServicePortName("ns1", "ep1", "p12"),
  2107. }, {
  2108. Endpoint: "1.1.1.2:12",
  2109. ServicePortName: makeServicePortName("ns1", "ep1", "p12"),
  2110. }},
  2111. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  2112. expectedHealthchecks: map[types.NamespacedName]int{},
  2113. }, {
  2114. // Case[10]: add a subset
  2115. previousEndpoints: []*v1.Endpoints{
  2116. makeTestEndpoints("ns1", "ep1", namedPort),
  2117. },
  2118. currentEndpoints: []*v1.Endpoints{
  2119. makeTestEndpoints("ns1", "ep1", multipleSubsetsWithLocal),
  2120. },
  2121. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2122. makeServicePortName("ns1", "ep1", "p11"): {
  2123. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2124. },
  2125. },
  2126. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2127. makeServicePortName("ns1", "ep1", "p11"): {
  2128. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2129. },
  2130. makeServicePortName("ns1", "ep1", "p12"): {
  2131. {Endpoint: "1.1.1.2:12", IsLocal: true},
  2132. },
  2133. },
  2134. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  2135. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2136. makeServicePortName("ns1", "ep1", "p12"): true,
  2137. },
  2138. expectedHealthchecks: map[types.NamespacedName]int{
  2139. makeNSN("ns1", "ep1"): 1,
  2140. },
  2141. }, {
  2142. // Case[11]: remove a subset
  2143. previousEndpoints: []*v1.Endpoints{
  2144. makeTestEndpoints("ns1", "ep1", multipleSubsets),
  2145. },
  2146. currentEndpoints: []*v1.Endpoints{
  2147. makeTestEndpoints("ns1", "ep1", namedPort),
  2148. },
  2149. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2150. makeServicePortName("ns1", "ep1", "p11"): {
  2151. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2152. },
  2153. makeServicePortName("ns1", "ep1", "p12"): {
  2154. {Endpoint: "1.1.1.2:12", IsLocal: false},
  2155. },
  2156. },
  2157. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2158. makeServicePortName("ns1", "ep1", "p11"): {
  2159. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2160. },
  2161. },
  2162. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2163. Endpoint: "1.1.1.2:12",
  2164. ServicePortName: makeServicePortName("ns1", "ep1", "p12"),
  2165. }},
  2166. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  2167. expectedHealthchecks: map[types.NamespacedName]int{},
  2168. }, {
  2169. // Case[12]: rename a port
  2170. previousEndpoints: []*v1.Endpoints{
  2171. makeTestEndpoints("ns1", "ep1", namedPort),
  2172. },
  2173. currentEndpoints: []*v1.Endpoints{
  2174. makeTestEndpoints("ns1", "ep1", namedPortRenamed),
  2175. },
  2176. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2177. makeServicePortName("ns1", "ep1", "p11"): {
  2178. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2179. },
  2180. },
  2181. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2182. makeServicePortName("ns1", "ep1", "p11-2"): {
  2183. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2184. },
  2185. },
  2186. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2187. Endpoint: "1.1.1.1:11",
  2188. ServicePortName: makeServicePortName("ns1", "ep1", "p11"),
  2189. }},
  2190. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2191. makeServicePortName("ns1", "ep1", "p11-2"): true,
  2192. },
  2193. expectedHealthchecks: map[types.NamespacedName]int{},
  2194. }, {
  2195. // Case[13]: renumber a port
  2196. previousEndpoints: []*v1.Endpoints{
  2197. makeTestEndpoints("ns1", "ep1", namedPort),
  2198. },
  2199. currentEndpoints: []*v1.Endpoints{
  2200. makeTestEndpoints("ns1", "ep1", namedPortRenumbered),
  2201. },
  2202. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2203. makeServicePortName("ns1", "ep1", "p11"): {
  2204. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2205. },
  2206. },
  2207. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2208. makeServicePortName("ns1", "ep1", "p11"): {
  2209. {Endpoint: "1.1.1.1:22", IsLocal: false},
  2210. },
  2211. },
  2212. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2213. Endpoint: "1.1.1.1:11",
  2214. ServicePortName: makeServicePortName("ns1", "ep1", "p11"),
  2215. }},
  2216. expectedStaleServiceNames: map[proxy.ServicePortName]bool{},
  2217. expectedHealthchecks: map[types.NamespacedName]int{},
  2218. }, {
  2219. // Case[14]: complex add and remove
  2220. previousEndpoints: []*v1.Endpoints{
  2221. makeTestEndpoints("ns1", "ep1", complexBefore1),
  2222. makeTestEndpoints("ns2", "ep2", complexBefore2),
  2223. nil,
  2224. makeTestEndpoints("ns4", "ep4", complexBefore4),
  2225. },
  2226. currentEndpoints: []*v1.Endpoints{
  2227. makeTestEndpoints("ns1", "ep1", complexAfter1),
  2228. nil,
  2229. makeTestEndpoints("ns3", "ep3", complexAfter3),
  2230. makeTestEndpoints("ns4", "ep4", complexAfter4),
  2231. },
  2232. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2233. makeServicePortName("ns1", "ep1", "p11"): {
  2234. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2235. },
  2236. makeServicePortName("ns2", "ep2", "p22"): {
  2237. {Endpoint: "2.2.2.2:22", IsLocal: true},
  2238. {Endpoint: "2.2.2.22:22", IsLocal: true},
  2239. },
  2240. makeServicePortName("ns2", "ep2", "p23"): {
  2241. {Endpoint: "2.2.2.3:23", IsLocal: true},
  2242. },
  2243. makeServicePortName("ns4", "ep4", "p44"): {
  2244. {Endpoint: "4.4.4.4:44", IsLocal: true},
  2245. {Endpoint: "4.4.4.5:44", IsLocal: true},
  2246. },
  2247. makeServicePortName("ns4", "ep4", "p45"): {
  2248. {Endpoint: "4.4.4.6:45", IsLocal: true},
  2249. },
  2250. },
  2251. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2252. makeServicePortName("ns1", "ep1", "p11"): {
  2253. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2254. {Endpoint: "1.1.1.11:11", IsLocal: false},
  2255. },
  2256. makeServicePortName("ns1", "ep1", "p12"): {
  2257. {Endpoint: "1.1.1.2:12", IsLocal: false},
  2258. },
  2259. makeServicePortName("ns1", "ep1", "p122"): {
  2260. {Endpoint: "1.1.1.2:122", IsLocal: false},
  2261. },
  2262. makeServicePortName("ns3", "ep3", "p33"): {
  2263. {Endpoint: "3.3.3.3:33", IsLocal: false},
  2264. },
  2265. makeServicePortName("ns4", "ep4", "p44"): {
  2266. {Endpoint: "4.4.4.4:44", IsLocal: true},
  2267. },
  2268. },
  2269. expectedStaleEndpoints: []proxy.ServiceEndpoint{{
  2270. Endpoint: "2.2.2.2:22",
  2271. ServicePortName: makeServicePortName("ns2", "ep2", "p22"),
  2272. }, {
  2273. Endpoint: "2.2.2.22:22",
  2274. ServicePortName: makeServicePortName("ns2", "ep2", "p22"),
  2275. }, {
  2276. Endpoint: "2.2.2.3:23",
  2277. ServicePortName: makeServicePortName("ns2", "ep2", "p23"),
  2278. }, {
  2279. Endpoint: "4.4.4.5:44",
  2280. ServicePortName: makeServicePortName("ns4", "ep4", "p44"),
  2281. }, {
  2282. Endpoint: "4.4.4.6:45",
  2283. ServicePortName: makeServicePortName("ns4", "ep4", "p45"),
  2284. }},
  2285. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2286. makeServicePortName("ns1", "ep1", "p12"): true,
  2287. makeServicePortName("ns1", "ep1", "p122"): true,
  2288. makeServicePortName("ns3", "ep3", "p33"): true,
  2289. },
  2290. expectedHealthchecks: map[types.NamespacedName]int{
  2291. makeNSN("ns4", "ep4"): 1,
  2292. },
  2293. }, {
  2294. // Case[15]: change from 0 endpoint address to 1 unnamed port
  2295. previousEndpoints: []*v1.Endpoints{
  2296. makeTestEndpoints("ns1", "ep1", emptyEndpoint),
  2297. },
  2298. currentEndpoints: []*v1.Endpoints{
  2299. makeTestEndpoints("ns1", "ep1", unnamedPort),
  2300. },
  2301. oldEndpoints: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{},
  2302. expectedResult: map[proxy.ServicePortName][]*proxy.BaseEndpointInfo{
  2303. makeServicePortName("ns1", "ep1", ""): {
  2304. {Endpoint: "1.1.1.1:11", IsLocal: false},
  2305. },
  2306. },
  2307. expectedStaleEndpoints: []proxy.ServiceEndpoint{},
  2308. expectedStaleServiceNames: map[proxy.ServicePortName]bool{
  2309. makeServicePortName("ns1", "ep1", ""): true,
  2310. },
  2311. expectedHealthchecks: map[types.NamespacedName]int{},
  2312. },
  2313. }
  2314. for tci, tc := range testCases {
  2315. ipt := iptablestest.NewFake()
  2316. ipvs := ipvstest.NewFake()
  2317. ipset := ipsettest.NewFake(testIPSetVersion)
  2318. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  2319. fp.hostname = nodeName
  2320. // First check that after adding all previous versions of endpoints,
  2321. // the fp.oldEndpoints is as we expect.
  2322. for i := range tc.previousEndpoints {
  2323. if tc.previousEndpoints[i] != nil {
  2324. fp.OnEndpointsAdd(tc.previousEndpoints[i])
  2325. }
  2326. }
  2327. fp.endpointsMap.Update(fp.endpointsChanges)
  2328. compareEndpointsMaps(t, tci, fp.endpointsMap, tc.oldEndpoints)
  2329. // Now let's call appropriate handlers to get to state we want to be.
  2330. if len(tc.previousEndpoints) != len(tc.currentEndpoints) {
  2331. t.Fatalf("[%d] different lengths of previous and current endpoints", tci)
  2332. continue
  2333. }
  2334. for i := range tc.previousEndpoints {
  2335. prev, curr := tc.previousEndpoints[i], tc.currentEndpoints[i]
  2336. switch {
  2337. case prev == nil:
  2338. fp.OnEndpointsAdd(curr)
  2339. case curr == nil:
  2340. fp.OnEndpointsDelete(prev)
  2341. default:
  2342. fp.OnEndpointsUpdate(prev, curr)
  2343. }
  2344. }
  2345. result := fp.endpointsMap.Update(fp.endpointsChanges)
  2346. newMap := fp.endpointsMap
  2347. compareEndpointsMaps(t, tci, newMap, tc.expectedResult)
  2348. if len(result.StaleEndpoints) != len(tc.expectedStaleEndpoints) {
  2349. t.Errorf("[%d] expected %d staleEndpoints, got %d: %v", tci, len(tc.expectedStaleEndpoints), len(result.StaleEndpoints), result.StaleEndpoints)
  2350. }
  2351. for _, x := range tc.expectedStaleEndpoints {
  2352. found := false
  2353. for _, stale := range result.StaleEndpoints {
  2354. if stale == x {
  2355. found = true
  2356. break
  2357. }
  2358. }
  2359. if !found {
  2360. t.Errorf("[%d] expected staleEndpoints[%v], but didn't find it: %v", tci, x, result.StaleEndpoints)
  2361. }
  2362. }
  2363. if len(result.StaleServiceNames) != len(tc.expectedStaleServiceNames) {
  2364. t.Errorf("[%d] expected %d staleServiceNames, got %d: %v", tci, len(tc.expectedStaleServiceNames), len(result.StaleServiceNames), result.StaleServiceNames)
  2365. }
  2366. for svcName := range tc.expectedStaleServiceNames {
  2367. found := false
  2368. for _, stale := range result.StaleServiceNames {
  2369. if stale == svcName {
  2370. found = true
  2371. break
  2372. }
  2373. }
  2374. if !found {
  2375. t.Errorf("[%d] expected staleServiceNames[%v], but didn't find it: %v", tci, svcName, result.StaleServiceNames)
  2376. }
  2377. }
  2378. if !reflect.DeepEqual(result.HCEndpointsLocalIPSize, tc.expectedHealthchecks) {
  2379. t.Errorf("[%d] expected healthchecks %v, got %v", tci, tc.expectedHealthchecks, result.HCEndpointsLocalIPSize)
  2380. }
  2381. }
  2382. }
  2383. func compareEndpointsMaps(t *testing.T, tci int, newMap proxy.EndpointsMap, expected map[proxy.ServicePortName][]*proxy.BaseEndpointInfo) {
  2384. if len(newMap) != len(expected) {
  2385. t.Errorf("[%d] expected %d results, got %d: %v", tci, len(expected), len(newMap), newMap)
  2386. }
  2387. for x := range expected {
  2388. if len(newMap[x]) != len(expected[x]) {
  2389. t.Errorf("[%d] expected %d endpoints for %v, got %d", tci, len(expected[x]), x, len(newMap[x]))
  2390. } else {
  2391. for i := range expected[x] {
  2392. newEp, ok := newMap[x][i].(*proxy.BaseEndpointInfo)
  2393. if !ok {
  2394. t.Errorf("Failed to cast proxy.BaseEndpointInfo")
  2395. continue
  2396. }
  2397. if *newEp != *(expected[x][i]) {
  2398. t.Errorf("[%d] expected new[%v][%d] to be %v, got %v", tci, x, i, expected[x][i], newEp)
  2399. }
  2400. }
  2401. }
  2402. }
  2403. }
  2404. func Test_syncService(t *testing.T) {
  2405. testCases := []struct {
  2406. oldVirtualServer *utilipvs.VirtualServer
  2407. svcName string
  2408. newVirtualServer *utilipvs.VirtualServer
  2409. bindAddr bool
  2410. }{
  2411. {
  2412. // case 0, old virtual server is same as new virtual server
  2413. oldVirtualServer: &utilipvs.VirtualServer{
  2414. Address: net.ParseIP("1.2.3.4"),
  2415. Protocol: string(v1.ProtocolTCP),
  2416. Port: 80,
  2417. Scheduler: "rr",
  2418. Flags: utilipvs.FlagHashed,
  2419. },
  2420. svcName: "foo",
  2421. newVirtualServer: &utilipvs.VirtualServer{
  2422. Address: net.ParseIP("1.2.3.4"),
  2423. Protocol: string(v1.ProtocolTCP),
  2424. Port: 80,
  2425. Scheduler: "rr",
  2426. Flags: utilipvs.FlagHashed,
  2427. },
  2428. bindAddr: false,
  2429. },
  2430. {
  2431. // case 1, old virtual server is different from new virtual server
  2432. oldVirtualServer: &utilipvs.VirtualServer{
  2433. Address: net.ParseIP("1.2.3.4"),
  2434. Protocol: string(v1.ProtocolTCP),
  2435. Port: 8080,
  2436. Scheduler: "rr",
  2437. Flags: utilipvs.FlagHashed,
  2438. },
  2439. svcName: "bar",
  2440. newVirtualServer: &utilipvs.VirtualServer{
  2441. Address: net.ParseIP("1.2.3.4"),
  2442. Protocol: string(v1.ProtocolTCP),
  2443. Port: 8080,
  2444. Scheduler: "rr",
  2445. Flags: utilipvs.FlagPersistent,
  2446. },
  2447. bindAddr: false,
  2448. },
  2449. {
  2450. // case 2, old virtual server is different from new virtual server
  2451. oldVirtualServer: &utilipvs.VirtualServer{
  2452. Address: net.ParseIP("1.2.3.4"),
  2453. Protocol: string(v1.ProtocolTCP),
  2454. Port: 8080,
  2455. Scheduler: "rr",
  2456. Flags: utilipvs.FlagHashed,
  2457. },
  2458. svcName: "bar",
  2459. newVirtualServer: &utilipvs.VirtualServer{
  2460. Address: net.ParseIP("1.2.3.4"),
  2461. Protocol: string(v1.ProtocolTCP),
  2462. Port: 8080,
  2463. Scheduler: "wlc",
  2464. Flags: utilipvs.FlagHashed,
  2465. },
  2466. bindAddr: false,
  2467. },
  2468. {
  2469. // case 3, old virtual server is nil, and create new virtual server
  2470. oldVirtualServer: nil,
  2471. svcName: "baz",
  2472. newVirtualServer: &utilipvs.VirtualServer{
  2473. Address: net.ParseIP("1.2.3.4"),
  2474. Protocol: string(v1.ProtocolUDP),
  2475. Port: 53,
  2476. Scheduler: "rr",
  2477. Flags: utilipvs.FlagHashed,
  2478. },
  2479. bindAddr: true,
  2480. },
  2481. {
  2482. // case 4, SCTP, old virtual server is same as new virtual server
  2483. oldVirtualServer: &utilipvs.VirtualServer{
  2484. Address: net.ParseIP("1.2.3.4"),
  2485. Protocol: string(v1.ProtocolSCTP),
  2486. Port: 80,
  2487. Scheduler: "rr",
  2488. Flags: utilipvs.FlagHashed,
  2489. },
  2490. svcName: "foo",
  2491. newVirtualServer: &utilipvs.VirtualServer{
  2492. Address: net.ParseIP("1.2.3.4"),
  2493. Protocol: string(v1.ProtocolSCTP),
  2494. Port: 80,
  2495. Scheduler: "rr",
  2496. Flags: utilipvs.FlagHashed,
  2497. },
  2498. bindAddr: false,
  2499. },
  2500. {
  2501. // case 5, old virtual server is different from new virtual server
  2502. oldVirtualServer: &utilipvs.VirtualServer{
  2503. Address: net.ParseIP("1.2.3.4"),
  2504. Protocol: string(v1.ProtocolSCTP),
  2505. Port: 8080,
  2506. Scheduler: "rr",
  2507. Flags: utilipvs.FlagHashed,
  2508. },
  2509. svcName: "bar",
  2510. newVirtualServer: &utilipvs.VirtualServer{
  2511. Address: net.ParseIP("1.2.3.4"),
  2512. Protocol: string(v1.ProtocolSCTP),
  2513. Port: 8080,
  2514. Scheduler: "rr",
  2515. Flags: utilipvs.FlagPersistent,
  2516. },
  2517. bindAddr: false,
  2518. },
  2519. {
  2520. // case 6, old virtual server is different from new virtual server
  2521. oldVirtualServer: &utilipvs.VirtualServer{
  2522. Address: net.ParseIP("1.2.3.4"),
  2523. Protocol: string(v1.ProtocolSCTP),
  2524. Port: 8080,
  2525. Scheduler: "rr",
  2526. Flags: utilipvs.FlagHashed,
  2527. },
  2528. svcName: "bar",
  2529. newVirtualServer: &utilipvs.VirtualServer{
  2530. Address: net.ParseIP("1.2.3.4"),
  2531. Protocol: string(v1.ProtocolSCTP),
  2532. Port: 8080,
  2533. Scheduler: "wlc",
  2534. Flags: utilipvs.FlagHashed,
  2535. },
  2536. bindAddr: false,
  2537. },
  2538. {
  2539. // case 7, old virtual server is nil, and create new virtual server
  2540. oldVirtualServer: nil,
  2541. svcName: "baz",
  2542. newVirtualServer: &utilipvs.VirtualServer{
  2543. Address: net.ParseIP("1.2.3.4"),
  2544. Protocol: string(v1.ProtocolSCTP),
  2545. Port: 53,
  2546. Scheduler: "rr",
  2547. Flags: utilipvs.FlagHashed,
  2548. },
  2549. bindAddr: true,
  2550. },
  2551. }
  2552. for i := range testCases {
  2553. ipt := iptablestest.NewFake()
  2554. ipvs := ipvstest.NewFake()
  2555. ipset := ipsettest.NewFake(testIPSetVersion)
  2556. proxier := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  2557. proxier.netlinkHandle.EnsureDummyDevice(DefaultDummyDevice)
  2558. if testCases[i].oldVirtualServer != nil {
  2559. if err := proxier.ipvs.AddVirtualServer(testCases[i].oldVirtualServer); err != nil {
  2560. t.Errorf("Case [%d], unexpected add IPVS virtual server error: %v", i, err)
  2561. }
  2562. }
  2563. if err := proxier.syncService(testCases[i].svcName, testCases[i].newVirtualServer, testCases[i].bindAddr); err != nil {
  2564. t.Errorf("Case [%d], unexpected sync IPVS virtual server error: %v", i, err)
  2565. }
  2566. // check
  2567. list, err := proxier.ipvs.GetVirtualServers()
  2568. if err != nil {
  2569. t.Errorf("Case [%d], unexpected list IPVS virtual server error: %v", i, err)
  2570. }
  2571. if len(list) != 1 {
  2572. t.Errorf("Case [%d], expect %d virtual servers, got %d", i, 1, len(list))
  2573. continue
  2574. }
  2575. if !list[0].Equal(testCases[i].newVirtualServer) {
  2576. t.Errorf("Case [%d], unexpected mismatch, expect: %#v, got: %#v", i, testCases[i].newVirtualServer, list[0])
  2577. }
  2578. }
  2579. }
  2580. func buildFakeProxier() (*iptablestest.FakeIPTables, *Proxier) {
  2581. ipt := iptablestest.NewFake()
  2582. ipvs := ipvstest.NewFake()
  2583. ipset := ipsettest.NewFake(testIPSetVersion)
  2584. return ipt, NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  2585. }
  2586. func hasJump(rules []iptablestest.Rule, destChain, ipSet string) bool {
  2587. for _, r := range rules {
  2588. if r[iptablestest.Jump] == destChain {
  2589. if ipSet == "" {
  2590. return true
  2591. }
  2592. if strings.Contains(r[iptablestest.MatchSet], ipSet) {
  2593. return true
  2594. }
  2595. }
  2596. }
  2597. return false
  2598. }
  2599. // checkIptabless to check expected iptables chain and rules
  2600. func checkIptables(t *testing.T, ipt *iptablestest.FakeIPTables, epIpt netlinktest.ExpectedIptablesChain) {
  2601. for epChain, epRules := range epIpt {
  2602. rules := ipt.GetRules(epChain)
  2603. for _, epRule := range epRules {
  2604. if !hasJump(rules, epRule.JumpChain, epRule.MatchSet) {
  2605. t.Errorf("Didn't find jump from chain %v match set %v to %v", epChain, epRule.MatchSet, epRule.JumpChain)
  2606. }
  2607. }
  2608. }
  2609. }
  2610. // checkIPSet to check expected ipset and entries
  2611. func checkIPSet(t *testing.T, fp *Proxier, ipSet netlinktest.ExpectedIPSet) {
  2612. for set, entries := range ipSet {
  2613. ents, err := fp.ipset.ListEntries(set)
  2614. if err != nil || len(ents) != len(entries) {
  2615. t.Errorf("Check ipset entries failed for ipset: %q, expect %d, got %d", set, len(entries), len(ents))
  2616. continue
  2617. }
  2618. if len(entries) == 1 {
  2619. if ents[0] != entries[0].String() {
  2620. t.Errorf("Check ipset entries failed for ipset: %q", set)
  2621. }
  2622. }
  2623. }
  2624. }
  2625. // checkIPVS to check expected ipvs service and destination
  2626. func checkIPVS(t *testing.T, fp *Proxier, vs *netlinktest.ExpectedVirtualServer) {
  2627. services, err := fp.ipvs.GetVirtualServers()
  2628. if err != nil {
  2629. t.Errorf("Failed to get ipvs services, err: %v", err)
  2630. }
  2631. if len(services) != vs.VSNum {
  2632. t.Errorf("Expect %d ipvs services, got %d", vs.VSNum, len(services))
  2633. }
  2634. for _, svc := range services {
  2635. if svc.Address.String() == vs.IP && svc.Port == vs.Port && svc.Protocol == vs.Protocol {
  2636. destinations, _ := fp.ipvs.GetRealServers(svc)
  2637. if len(destinations) != len(vs.RS) {
  2638. t.Errorf("Expected %d destinations, got %d destinations", len(vs.RS), len(destinations))
  2639. }
  2640. if len(vs.RS) == 1 {
  2641. if destinations[0].Address.String() != vs.RS[0].IP || destinations[0].Port != vs.RS[0].Port {
  2642. t.Errorf("Unexpected mismatch destinations")
  2643. }
  2644. }
  2645. }
  2646. }
  2647. }
  2648. func TestCleanLegacyService(t *testing.T) {
  2649. ipt := iptablestest.NewFake()
  2650. ipvs := ipvstest.NewFake()
  2651. ipset := ipsettest.NewFake(testIPSetVersion)
  2652. fp := NewFakeProxier(ipt, ipvs, ipset, nil, parseExcludedCIDRs([]string{"3.3.3.0/24", "4.4.4.0/24"}))
  2653. // All ipvs services that were processed in the latest sync loop.
  2654. activeServices := map[string]bool{"ipvs0": true, "ipvs1": true}
  2655. // All ipvs services in the system.
  2656. currentServices := map[string]*utilipvs.VirtualServer{
  2657. // Created by kube-proxy.
  2658. "ipvs0": {
  2659. Address: net.ParseIP("1.1.1.1"),
  2660. Protocol: string(v1.ProtocolUDP),
  2661. Port: 53,
  2662. Scheduler: "rr",
  2663. Flags: utilipvs.FlagHashed,
  2664. },
  2665. // Created by kube-proxy.
  2666. "ipvs1": {
  2667. Address: net.ParseIP("2.2.2.2"),
  2668. Protocol: string(v1.ProtocolUDP),
  2669. Port: 54,
  2670. Scheduler: "rr",
  2671. Flags: utilipvs.FlagHashed,
  2672. },
  2673. // Created by an external party.
  2674. "ipvs2": {
  2675. Address: net.ParseIP("3.3.3.3"),
  2676. Protocol: string(v1.ProtocolUDP),
  2677. Port: 55,
  2678. Scheduler: "rr",
  2679. Flags: utilipvs.FlagHashed,
  2680. },
  2681. // Created by an external party.
  2682. "ipvs3": {
  2683. Address: net.ParseIP("4.4.4.4"),
  2684. Protocol: string(v1.ProtocolUDP),
  2685. Port: 56,
  2686. Scheduler: "rr",
  2687. Flags: utilipvs.FlagHashed,
  2688. },
  2689. // Created by an external party.
  2690. "ipvs4": {
  2691. Address: net.ParseIP("5.5.5.5"),
  2692. Protocol: string(v1.ProtocolUDP),
  2693. Port: 57,
  2694. Scheduler: "rr",
  2695. Flags: utilipvs.FlagHashed,
  2696. },
  2697. // Created by kube-proxy, but now stale.
  2698. "ipvs5": {
  2699. Address: net.ParseIP("6.6.6.6"),
  2700. Protocol: string(v1.ProtocolUDP),
  2701. Port: 58,
  2702. Scheduler: "rr",
  2703. Flags: utilipvs.FlagHashed,
  2704. },
  2705. }
  2706. for v := range currentServices {
  2707. fp.ipvs.AddVirtualServer(currentServices[v])
  2708. }
  2709. fp.netlinkHandle.EnsureDummyDevice(DefaultDummyDevice)
  2710. activeBindAddrs := map[string]bool{"1.1.1.1": true, "2.2.2.2": true, "3.3.3.3": true, "4.4.4.4": true}
  2711. // This is ipv4-only so ipv6 addresses should be ignored
  2712. currentBindAddrs := []string{"1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4", "5.5.5.5", "6.6.6.6", "fd80::1:2:3", "fd80::1:2:4"}
  2713. for i := range currentBindAddrs {
  2714. fp.netlinkHandle.EnsureAddressBind(currentBindAddrs[i], DefaultDummyDevice)
  2715. }
  2716. fp.cleanLegacyService(activeServices, currentServices, map[string]bool{"5.5.5.5": true, "6.6.6.6": true})
  2717. // ipvs4 and ipvs5 should have been cleaned.
  2718. remainingVirtualServers, _ := fp.ipvs.GetVirtualServers()
  2719. if len(remainingVirtualServers) != 4 {
  2720. t.Errorf("Expected number of remaining IPVS services after cleanup to be %v. Got %v", 4, len(remainingVirtualServers))
  2721. }
  2722. for _, vs := range remainingVirtualServers {
  2723. // Checking that ipvs4 and ipvs5 were removed.
  2724. if vs.Port == 57 {
  2725. t.Errorf("Expected ipvs4 to be removed after cleanup. It still remains")
  2726. }
  2727. if vs.Port == 58 {
  2728. t.Errorf("Expected ipvs5 to be removed after cleanup. It still remains")
  2729. }
  2730. }
  2731. // Addresses 5.5.5.5 and 6.6.6.6 should not be bound any more, but the ipv6 addresses should remain
  2732. remainingAddrs, _ := fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2733. if len(remainingAddrs) != 6 {
  2734. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 6, len(remainingAddrs))
  2735. }
  2736. // check that address "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4" are bound, ignore ipv6 addresses
  2737. remainingAddrsMap := make(map[string]bool)
  2738. for _, a := range remainingAddrs {
  2739. if net.ParseIP(a).To4() == nil {
  2740. continue
  2741. }
  2742. remainingAddrsMap[a] = true
  2743. }
  2744. if !reflect.DeepEqual(activeBindAddrs, remainingAddrsMap) {
  2745. t.Errorf("Expected remainingAddrsMap %v, got %v", activeBindAddrs, remainingAddrsMap)
  2746. }
  2747. }
  2748. func TestCleanLegacyRealServersExcludeCIDRs(t *testing.T) {
  2749. ipt := iptablestest.NewFake()
  2750. ipvs := ipvstest.NewFake()
  2751. ipset := ipsettest.NewFake(testIPSetVersion)
  2752. gtm := NewGracefulTerminationManager(ipvs)
  2753. fp := NewFakeProxier(ipt, ipvs, ipset, nil, parseExcludedCIDRs([]string{"4.4.4.4/32"}))
  2754. fp.gracefuldeleteManager = gtm
  2755. vs := &utilipvs.VirtualServer{
  2756. Address: net.ParseIP("4.4.4.4"),
  2757. Protocol: string(v1.ProtocolUDP),
  2758. Port: 56,
  2759. Scheduler: "rr",
  2760. Flags: utilipvs.FlagHashed,
  2761. }
  2762. fp.ipvs.AddVirtualServer(vs)
  2763. rss := []*utilipvs.RealServer{
  2764. {
  2765. Address: net.ParseIP("10.10.10.10"),
  2766. Port: 56,
  2767. ActiveConn: 0,
  2768. InactiveConn: 0,
  2769. },
  2770. {
  2771. Address: net.ParseIP("11.11.11.11"),
  2772. Port: 56,
  2773. ActiveConn: 0,
  2774. InactiveConn: 0,
  2775. },
  2776. }
  2777. for _, rs := range rss {
  2778. fp.ipvs.AddRealServer(vs, rs)
  2779. }
  2780. fp.netlinkHandle.EnsureDummyDevice(DefaultDummyDevice)
  2781. fp.netlinkHandle.EnsureAddressBind("4.4.4.4", DefaultDummyDevice)
  2782. fp.cleanLegacyService(
  2783. map[string]bool{},
  2784. map[string]*utilipvs.VirtualServer{"ipvs0": vs},
  2785. map[string]bool{"4.4.4.4": true},
  2786. )
  2787. fp.gracefuldeleteManager.tryDeleteRs()
  2788. remainingRealServers, _ := fp.ipvs.GetRealServers(vs)
  2789. if len(remainingRealServers) != 2 {
  2790. t.Errorf("Expected number of remaining IPVS real servers after cleanup should be %v. Got %v", 2, len(remainingRealServers))
  2791. }
  2792. }
  2793. func TestCleanLegacyService6(t *testing.T) {
  2794. ipt := iptablestest.NewFake()
  2795. ipvs := ipvstest.NewFake()
  2796. ipset := ipsettest.NewFake(testIPSetVersion)
  2797. fp := NewFakeProxier(ipt, ipvs, ipset, nil, parseExcludedCIDRs([]string{"3000::/64", "4000::/64"}))
  2798. fp.nodeIP = net.ParseIP("::1")
  2799. // All ipvs services that were processed in the latest sync loop.
  2800. activeServices := map[string]bool{"ipvs0": true, "ipvs1": true}
  2801. // All ipvs services in the system.
  2802. currentServices := map[string]*utilipvs.VirtualServer{
  2803. // Created by kube-proxy.
  2804. "ipvs0": {
  2805. Address: net.ParseIP("1000::1"),
  2806. Protocol: string(v1.ProtocolUDP),
  2807. Port: 53,
  2808. Scheduler: "rr",
  2809. Flags: utilipvs.FlagHashed,
  2810. },
  2811. // Created by kube-proxy.
  2812. "ipvs1": {
  2813. Address: net.ParseIP("1000::2"),
  2814. Protocol: string(v1.ProtocolUDP),
  2815. Port: 54,
  2816. Scheduler: "rr",
  2817. Flags: utilipvs.FlagHashed,
  2818. },
  2819. // Created by an external party.
  2820. "ipvs2": {
  2821. Address: net.ParseIP("3000::1"),
  2822. Protocol: string(v1.ProtocolUDP),
  2823. Port: 55,
  2824. Scheduler: "rr",
  2825. Flags: utilipvs.FlagHashed,
  2826. },
  2827. // Created by an external party.
  2828. "ipvs3": {
  2829. Address: net.ParseIP("4000::1"),
  2830. Protocol: string(v1.ProtocolUDP),
  2831. Port: 56,
  2832. Scheduler: "rr",
  2833. Flags: utilipvs.FlagHashed,
  2834. },
  2835. // Created by an external party.
  2836. "ipvs4": {
  2837. Address: net.ParseIP("5000::1"),
  2838. Protocol: string(v1.ProtocolUDP),
  2839. Port: 57,
  2840. Scheduler: "rr",
  2841. Flags: utilipvs.FlagHashed,
  2842. },
  2843. // Created by kube-proxy, but now stale.
  2844. "ipvs5": {
  2845. Address: net.ParseIP("1000::6"),
  2846. Protocol: string(v1.ProtocolUDP),
  2847. Port: 58,
  2848. Scheduler: "rr",
  2849. Flags: utilipvs.FlagHashed,
  2850. },
  2851. }
  2852. for v := range currentServices {
  2853. fp.ipvs.AddVirtualServer(currentServices[v])
  2854. }
  2855. fp.netlinkHandle.EnsureDummyDevice(DefaultDummyDevice)
  2856. activeBindAddrs := map[string]bool{"1000::1": true, "1000::2": true, "3000::1": true, "4000::1": true}
  2857. // This is ipv6-only so ipv4 addresses should be ignored
  2858. currentBindAddrs := []string{"1000::1", "1000::2", "3000::1", "4000::1", "5000::1", "1000::6", "1.1.1.1", "2.2.2.2"}
  2859. for i := range currentBindAddrs {
  2860. fp.netlinkHandle.EnsureAddressBind(currentBindAddrs[i], DefaultDummyDevice)
  2861. }
  2862. fp.cleanLegacyService(activeServices, currentServices, map[string]bool{"5000::1": true, "1000::6": true})
  2863. // ipvs4 and ipvs5 should have been cleaned.
  2864. remainingVirtualServers, _ := fp.ipvs.GetVirtualServers()
  2865. if len(remainingVirtualServers) != 4 {
  2866. t.Errorf("Expected number of remaining IPVS services after cleanup to be %v. Got %v", 4, len(remainingVirtualServers))
  2867. }
  2868. for _, vs := range remainingVirtualServers {
  2869. // Checking that ipvs4 and ipvs5 were removed.
  2870. if vs.Port == 57 {
  2871. t.Errorf("Expected ipvs4 to be removed after cleanup. It still remains")
  2872. }
  2873. if vs.Port == 58 {
  2874. t.Errorf("Expected ipvs5 to be removed after cleanup. It still remains")
  2875. }
  2876. }
  2877. // Addresses 5000::1 and 1000::6 should not be bound any more, but the ipv4 addresses should remain
  2878. remainingAddrs, _ := fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2879. if len(remainingAddrs) != 6 {
  2880. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 6, len(remainingAddrs))
  2881. }
  2882. // check that address "1000::1", "1000::2", "3000::1", "4000::1" are still bound, ignore ipv4 addresses
  2883. remainingAddrsMap := make(map[string]bool)
  2884. for _, a := range remainingAddrs {
  2885. if net.ParseIP(a).To4() != nil {
  2886. continue
  2887. }
  2888. remainingAddrsMap[a] = true
  2889. }
  2890. if !reflect.DeepEqual(activeBindAddrs, remainingAddrsMap) {
  2891. t.Errorf("Expected remainingAddrsMap %v, got %v", activeBindAddrs, remainingAddrsMap)
  2892. }
  2893. }
  2894. func TestMultiPortServiceBindAddr(t *testing.T) {
  2895. ipt := iptablestest.NewFake()
  2896. ipvs := ipvstest.NewFake()
  2897. ipset := ipsettest.NewFake(testIPSetVersion)
  2898. fp := NewFakeProxier(ipt, ipvs, ipset, nil, nil)
  2899. service1 := makeTestService("ns1", "svc1", func(svc *v1.Service) {
  2900. svc.Spec.Type = v1.ServiceTypeClusterIP
  2901. svc.Spec.ClusterIP = "172.16.55.4"
  2902. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port1", "TCP", 1234, 0, 0)
  2903. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port2", "TCP", 1235, 0, 0)
  2904. })
  2905. service2 := makeTestService("ns1", "svc1", func(svc *v1.Service) {
  2906. svc.Spec.Type = v1.ServiceTypeClusterIP
  2907. svc.Spec.ClusterIP = "172.16.55.4"
  2908. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port1", "TCP", 1234, 0, 0)
  2909. })
  2910. service3 := makeTestService("ns1", "svc1", func(svc *v1.Service) {
  2911. svc.Spec.Type = v1.ServiceTypeClusterIP
  2912. svc.Spec.ClusterIP = "172.16.55.4"
  2913. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port1", "TCP", 1234, 0, 0)
  2914. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port2", "TCP", 1235, 0, 0)
  2915. svc.Spec.Ports = addTestPort(svc.Spec.Ports, "port3", "UDP", 1236, 0, 0)
  2916. })
  2917. fp.servicesSynced = true
  2918. fp.endpointsSynced = true
  2919. // first, add multi-port service1
  2920. fp.OnServiceAdd(service1)
  2921. fp.syncProxyRules()
  2922. remainingAddrs, _ := fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2923. // should only remain address "172.16.55.4"
  2924. if len(remainingAddrs) != 1 {
  2925. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 1, len(remainingAddrs))
  2926. }
  2927. if remainingAddrs[0] != "172.16.55.4" {
  2928. t.Errorf("Expected remaining address should be %s, got %s", "172.16.55.4", remainingAddrs[0])
  2929. }
  2930. // update multi-port service1 to single-port service2
  2931. fp.OnServiceUpdate(service1, service2)
  2932. fp.syncProxyRules()
  2933. remainingAddrs, _ = fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2934. // should still only remain address "172.16.55.4"
  2935. if len(remainingAddrs) != 1 {
  2936. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 1, len(remainingAddrs))
  2937. } else if remainingAddrs[0] != "172.16.55.4" {
  2938. t.Errorf("Expected remaining address should be %s, got %s", "172.16.55.4", remainingAddrs[0])
  2939. }
  2940. // update single-port service2 to multi-port service3
  2941. fp.OnServiceUpdate(service2, service3)
  2942. fp.syncProxyRules()
  2943. remainingAddrs, _ = fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2944. // should still only remain address "172.16.55.4"
  2945. if len(remainingAddrs) != 1 {
  2946. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 1, len(remainingAddrs))
  2947. } else if remainingAddrs[0] != "172.16.55.4" {
  2948. t.Errorf("Expected remaining address should be %s, got %s", "172.16.55.4", remainingAddrs[0])
  2949. }
  2950. // delete multi-port service3
  2951. fp.OnServiceDelete(service3)
  2952. fp.syncProxyRules()
  2953. remainingAddrs, _ = fp.netlinkHandle.ListBindAddress(DefaultDummyDevice)
  2954. // all addresses should be unbound
  2955. if len(remainingAddrs) != 0 {
  2956. t.Errorf("Expected number of remaining bound addrs after cleanup to be %v. Got %v", 0, len(remainingAddrs))
  2957. }
  2958. }