proxier.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package userspace
  14. import (
  15. "fmt"
  16. "net"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. v1 "k8s.io/api/core/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  26. utilnet "k8s.io/apimachinery/pkg/util/net"
  27. "k8s.io/apimachinery/pkg/util/runtime"
  28. "k8s.io/apimachinery/pkg/util/sets"
  29. servicehelper "k8s.io/cloud-provider/service/helpers"
  30. "k8s.io/klog"
  31. "k8s.io/kubernetes/pkg/proxy"
  32. "k8s.io/kubernetes/pkg/proxy/config"
  33. utilproxy "k8s.io/kubernetes/pkg/proxy/util"
  34. "k8s.io/kubernetes/pkg/util/async"
  35. "k8s.io/kubernetes/pkg/util/conntrack"
  36. "k8s.io/kubernetes/pkg/util/iptables"
  37. utilexec "k8s.io/utils/exec"
  38. )
  39. type portal struct {
  40. ip net.IP
  41. port int
  42. isExternal bool
  43. }
  44. // ServiceInfo contains information and state for a particular proxied service
  45. type ServiceInfo struct {
  46. // Timeout is the read/write timeout (used for UDP connections)
  47. Timeout time.Duration
  48. // ActiveClients is the cache of active UDP clients being proxied by this proxy for this service
  49. ActiveClients *ClientCache
  50. isAliveAtomic int32 // Only access this with atomic ops
  51. portal portal
  52. protocol v1.Protocol
  53. proxyPort int
  54. socket ProxySocket
  55. nodePort int
  56. loadBalancerStatus v1.LoadBalancerStatus
  57. sessionAffinityType v1.ServiceAffinity
  58. stickyMaxAgeSeconds int
  59. // Deprecated, but required for back-compat (including e2e)
  60. externalIPs []string
  61. }
  62. func (info *ServiceInfo) setAlive(b bool) {
  63. var i int32
  64. if b {
  65. i = 1
  66. }
  67. atomic.StoreInt32(&info.isAliveAtomic, i)
  68. }
  69. func (info *ServiceInfo) IsAlive() bool {
  70. return atomic.LoadInt32(&info.isAliveAtomic) != 0
  71. }
  72. func logTimeout(err error) bool {
  73. if e, ok := err.(net.Error); ok {
  74. if e.Timeout() {
  75. klog.V(3).Infof("connection to endpoint closed due to inactivity")
  76. return true
  77. }
  78. }
  79. return false
  80. }
  81. // ProxySocketFunc is a function which constructs a ProxySocket from a protocol, ip, and port
  82. type ProxySocketFunc func(protocol v1.Protocol, ip net.IP, port int) (ProxySocket, error)
  83. const numBurstSyncs int = 2
  84. type serviceChange struct {
  85. current *v1.Service
  86. previous *v1.Service
  87. }
  88. // Interface for async runner; abstracted for testing
  89. type asyncRunnerInterface interface {
  90. Run()
  91. Loop(<-chan struct{})
  92. }
  93. // Proxier is a simple proxy for TCP connections between a localhost:lport
  94. // and services that provide the actual implementations.
  95. type Proxier struct {
  96. // EndpointSlice support has not been added for this proxier yet.
  97. config.NoopEndpointSliceHandler
  98. // TODO(imroc): implement node handler for userspace proxier.
  99. config.NoopNodeHandler
  100. loadBalancer LoadBalancer
  101. mu sync.Mutex // protects serviceMap
  102. serviceMap map[proxy.ServicePortName]*ServiceInfo
  103. syncPeriod time.Duration
  104. minSyncPeriod time.Duration
  105. udpIdleTimeout time.Duration
  106. portMapMutex sync.Mutex
  107. portMap map[portMapKey]*portMapValue
  108. numProxyLoops int32 // use atomic ops to access this; mostly for testing
  109. listenIP net.IP
  110. iptables iptables.Interface
  111. hostIP net.IP
  112. proxyPorts PortAllocator
  113. makeProxySocket ProxySocketFunc
  114. exec utilexec.Interface
  115. // endpointsSynced and servicesSynced are set to 1 when the corresponding
  116. // objects are synced after startup. This is used to avoid updating iptables
  117. // with some partial data after kube-proxy restart.
  118. endpointsSynced int32
  119. servicesSynced int32
  120. initialized int32
  121. // protects serviceChanges
  122. serviceChangesLock sync.Mutex
  123. serviceChanges map[types.NamespacedName]*serviceChange // map of service changes
  124. syncRunner asyncRunnerInterface // governs calls to syncProxyRules
  125. stopChan chan struct{}
  126. }
  127. // assert Proxier is a proxy.Provider
  128. var _ proxy.Provider = &Proxier{}
  129. // A key for the portMap. The ip has to be a string because slices can't be map
  130. // keys.
  131. type portMapKey struct {
  132. ip string
  133. port int
  134. protocol v1.Protocol
  135. }
  136. func (k *portMapKey) String() string {
  137. return fmt.Sprintf("%s/%s", net.JoinHostPort(k.ip, strconv.Itoa(k.port)), k.protocol)
  138. }
  139. // A value for the portMap
  140. type portMapValue struct {
  141. owner proxy.ServicePortName
  142. socket interface {
  143. Close() error
  144. }
  145. }
  146. var (
  147. // ErrProxyOnLocalhost is returned by NewProxier if the user requests a proxier on
  148. // the loopback address. May be checked for by callers of NewProxier to know whether
  149. // the caller provided invalid input.
  150. ErrProxyOnLocalhost = fmt.Errorf("cannot proxy on localhost")
  151. )
  152. // NewProxier returns a new Proxier given a LoadBalancer and an address on
  153. // which to listen. Because of the iptables logic, It is assumed that there
  154. // is only a single Proxier active on a machine. An error will be returned if
  155. // the proxier cannot be started due to an invalid ListenIP (loopback) or
  156. // if iptables fails to update or acquire the initial lock. Once a proxier is
  157. // created, it will keep iptables up to date in the background and will not
  158. // terminate if a particular iptables call fails.
  159. func NewProxier(loadBalancer LoadBalancer, listenIP net.IP, iptables iptables.Interface, exec utilexec.Interface, pr utilnet.PortRange, syncPeriod, minSyncPeriod, udpIdleTimeout time.Duration, nodePortAddresses []string) (*Proxier, error) {
  160. return NewCustomProxier(loadBalancer, listenIP, iptables, exec, pr, syncPeriod, minSyncPeriod, udpIdleTimeout, nodePortAddresses, newProxySocket)
  161. }
  162. // NewCustomProxier functions similarly to NewProxier, returning a new Proxier
  163. // for the given LoadBalancer and address. The new proxier is constructed using
  164. // the ProxySocket constructor provided, however, instead of constructing the
  165. // default ProxySockets.
  166. func NewCustomProxier(loadBalancer LoadBalancer, listenIP net.IP, iptables iptables.Interface, exec utilexec.Interface, pr utilnet.PortRange, syncPeriod, minSyncPeriod, udpIdleTimeout time.Duration, nodePortAddresses []string, makeProxySocket ProxySocketFunc) (*Proxier, error) {
  167. if listenIP.Equal(localhostIPv4) || listenIP.Equal(localhostIPv6) {
  168. return nil, ErrProxyOnLocalhost
  169. }
  170. // If listenIP is given, assume that is the intended host IP. Otherwise
  171. // try to find a suitable host IP address from network interfaces.
  172. var err error
  173. hostIP := listenIP
  174. if hostIP.Equal(net.IPv4zero) || hostIP.Equal(net.IPv6zero) {
  175. hostIP, err = utilnet.ChooseHostInterface()
  176. if err != nil {
  177. return nil, fmt.Errorf("failed to select a host interface: %v", err)
  178. }
  179. }
  180. err = setRLimit(64 * 1000)
  181. if err != nil {
  182. return nil, fmt.Errorf("failed to set open file handler limit: %v", err)
  183. }
  184. proxyPorts := newPortAllocator(pr)
  185. klog.V(2).Infof("Setting proxy IP to %v and initializing iptables", hostIP)
  186. return createProxier(loadBalancer, listenIP, iptables, exec, hostIP, proxyPorts, syncPeriod, minSyncPeriod, udpIdleTimeout, makeProxySocket)
  187. }
  188. func createProxier(loadBalancer LoadBalancer, listenIP net.IP, iptables iptables.Interface, exec utilexec.Interface, hostIP net.IP, proxyPorts PortAllocator, syncPeriod, minSyncPeriod, udpIdleTimeout time.Duration, makeProxySocket ProxySocketFunc) (*Proxier, error) {
  189. // convenient to pass nil for tests..
  190. if proxyPorts == nil {
  191. proxyPorts = newPortAllocator(utilnet.PortRange{})
  192. }
  193. // Set up the iptables foundations we need.
  194. if err := iptablesInit(iptables); err != nil {
  195. return nil, fmt.Errorf("failed to initialize iptables: %v", err)
  196. }
  197. // Flush old iptables rules (since the bound ports will be invalid after a restart).
  198. // When OnUpdate() is first called, the rules will be recreated.
  199. if err := iptablesFlush(iptables); err != nil {
  200. return nil, fmt.Errorf("failed to flush iptables: %v", err)
  201. }
  202. proxier := &Proxier{
  203. loadBalancer: loadBalancer,
  204. serviceMap: make(map[proxy.ServicePortName]*ServiceInfo),
  205. serviceChanges: make(map[types.NamespacedName]*serviceChange),
  206. portMap: make(map[portMapKey]*portMapValue),
  207. syncPeriod: syncPeriod,
  208. minSyncPeriod: minSyncPeriod,
  209. udpIdleTimeout: udpIdleTimeout,
  210. listenIP: listenIP,
  211. iptables: iptables,
  212. hostIP: hostIP,
  213. proxyPorts: proxyPorts,
  214. makeProxySocket: makeProxySocket,
  215. exec: exec,
  216. stopChan: make(chan struct{}),
  217. }
  218. klog.V(3).Infof("minSyncPeriod: %v, syncPeriod: %v, burstSyncs: %d", minSyncPeriod, syncPeriod, numBurstSyncs)
  219. proxier.syncRunner = async.NewBoundedFrequencyRunner("userspace-proxy-sync-runner", proxier.syncProxyRules, minSyncPeriod, syncPeriod, numBurstSyncs)
  220. return proxier, nil
  221. }
  222. // CleanupLeftovers removes all iptables rules and chains created by the Proxier
  223. // It returns true if an error was encountered. Errors are logged.
  224. func CleanupLeftovers(ipt iptables.Interface) (encounteredError bool) {
  225. // NOTE: Warning, this needs to be kept in sync with the userspace Proxier,
  226. // we want to ensure we remove all of the iptables rules it creates.
  227. // Currently they are all in iptablesInit()
  228. // Delete Rules first, then Flush and Delete Chains
  229. args := []string{"-m", "comment", "--comment", "handle ClusterIPs; NOTE: this must be before the NodePort rules"}
  230. if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostPortalChain))...); err != nil {
  231. if !iptables.IsNotFoundError(err) {
  232. klog.Errorf("Error removing userspace rule: %v", err)
  233. encounteredError = true
  234. }
  235. }
  236. if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerPortalChain))...); err != nil {
  237. if !iptables.IsNotFoundError(err) {
  238. klog.Errorf("Error removing userspace rule: %v", err)
  239. encounteredError = true
  240. }
  241. }
  242. args = []string{"-m", "addrtype", "--dst-type", "LOCAL"}
  243. args = append(args, "-m", "comment", "--comment", "handle service NodePorts; NOTE: this must be the last rule in the chain")
  244. if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostNodePortChain))...); err != nil {
  245. if !iptables.IsNotFoundError(err) {
  246. klog.Errorf("Error removing userspace rule: %v", err)
  247. encounteredError = true
  248. }
  249. }
  250. if err := ipt.DeleteRule(iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerNodePortChain))...); err != nil {
  251. if !iptables.IsNotFoundError(err) {
  252. klog.Errorf("Error removing userspace rule: %v", err)
  253. encounteredError = true
  254. }
  255. }
  256. args = []string{"-m", "comment", "--comment", "Ensure that non-local NodePort traffic can flow"}
  257. if err := ipt.DeleteRule(iptables.TableFilter, iptables.ChainInput, append(args, "-j", string(iptablesNonLocalNodePortChain))...); err != nil {
  258. if !iptables.IsNotFoundError(err) {
  259. klog.Errorf("Error removing userspace rule: %v", err)
  260. encounteredError = true
  261. }
  262. }
  263. // flush and delete chains.
  264. tableChains := map[iptables.Table][]iptables.Chain{
  265. iptables.TableNAT: {iptablesContainerPortalChain, iptablesHostPortalChain, iptablesHostNodePortChain, iptablesContainerNodePortChain},
  266. iptables.TableFilter: {iptablesNonLocalNodePortChain},
  267. }
  268. for table, chains := range tableChains {
  269. for _, c := range chains {
  270. // flush chain, then if successful delete, delete will fail if flush fails.
  271. if err := ipt.FlushChain(table, c); err != nil {
  272. if !iptables.IsNotFoundError(err) {
  273. klog.Errorf("Error flushing userspace chain: %v", err)
  274. encounteredError = true
  275. }
  276. } else {
  277. if err = ipt.DeleteChain(table, c); err != nil {
  278. if !iptables.IsNotFoundError(err) {
  279. klog.Errorf("Error deleting userspace chain: %v", err)
  280. encounteredError = true
  281. }
  282. }
  283. }
  284. }
  285. }
  286. return encounteredError
  287. }
  288. // shutdown closes all service port proxies and returns from the proxy's
  289. // sync loop. Used from testcases.
  290. func (proxier *Proxier) shutdown() {
  291. proxier.mu.Lock()
  292. defer proxier.mu.Unlock()
  293. for serviceName, info := range proxier.serviceMap {
  294. proxier.stopProxy(serviceName, info)
  295. }
  296. proxier.cleanupStaleStickySessions()
  297. close(proxier.stopChan)
  298. }
  299. func (proxier *Proxier) isInitialized() bool {
  300. return atomic.LoadInt32(&proxier.initialized) > 0
  301. }
  302. // Sync is called to synchronize the proxier state to iptables as soon as possible.
  303. func (proxier *Proxier) Sync() {
  304. proxier.syncRunner.Run()
  305. }
  306. func (proxier *Proxier) syncProxyRules() {
  307. start := time.Now()
  308. defer func() {
  309. klog.V(2).Infof("userspace syncProxyRules took %v", time.Since(start))
  310. }()
  311. // don't sync rules till we've received services and endpoints
  312. if !proxier.isInitialized() {
  313. klog.V(2).Info("Not syncing userspace proxy until Services and Endpoints have been received from master")
  314. return
  315. }
  316. if err := iptablesInit(proxier.iptables); err != nil {
  317. klog.Errorf("Failed to ensure iptables: %v", err)
  318. }
  319. proxier.serviceChangesLock.Lock()
  320. changes := proxier.serviceChanges
  321. proxier.serviceChanges = make(map[types.NamespacedName]*serviceChange)
  322. proxier.serviceChangesLock.Unlock()
  323. proxier.mu.Lock()
  324. defer proxier.mu.Unlock()
  325. klog.V(2).Infof("userspace proxy: processing %d service events", len(changes))
  326. for _, change := range changes {
  327. existingPorts := proxier.mergeService(change.current)
  328. proxier.unmergeService(change.previous, existingPorts)
  329. }
  330. proxier.ensurePortals()
  331. proxier.cleanupStaleStickySessions()
  332. }
  333. // SyncLoop runs periodic work. This is expected to run as a goroutine or as the main loop of the app. It does not return.
  334. func (proxier *Proxier) SyncLoop() {
  335. proxier.syncRunner.Loop(proxier.stopChan)
  336. }
  337. // Ensure that portals exist for all services.
  338. func (proxier *Proxier) ensurePortals() {
  339. // NB: This does not remove rules that should not be present.
  340. for name, info := range proxier.serviceMap {
  341. err := proxier.openPortal(name, info)
  342. if err != nil {
  343. klog.Errorf("Failed to ensure portal for %q: %v", name, err)
  344. }
  345. }
  346. }
  347. // clean up any stale sticky session records in the hash map.
  348. func (proxier *Proxier) cleanupStaleStickySessions() {
  349. for name := range proxier.serviceMap {
  350. proxier.loadBalancer.CleanupStaleStickySessions(name)
  351. }
  352. }
  353. func (proxier *Proxier) stopProxy(service proxy.ServicePortName, info *ServiceInfo) error {
  354. delete(proxier.serviceMap, service)
  355. info.setAlive(false)
  356. err := info.socket.Close()
  357. port := info.socket.ListenPort()
  358. proxier.proxyPorts.Release(port)
  359. return err
  360. }
  361. func (proxier *Proxier) getServiceInfo(service proxy.ServicePortName) (*ServiceInfo, bool) {
  362. proxier.mu.Lock()
  363. defer proxier.mu.Unlock()
  364. info, ok := proxier.serviceMap[service]
  365. return info, ok
  366. }
  367. // addServiceOnPort lockes the proxy before calling addServiceOnPortInternal.
  368. // Used from testcases.
  369. func (proxier *Proxier) addServiceOnPort(service proxy.ServicePortName, protocol v1.Protocol, proxyPort int, timeout time.Duration) (*ServiceInfo, error) {
  370. proxier.mu.Lock()
  371. defer proxier.mu.Unlock()
  372. return proxier.addServiceOnPortInternal(service, protocol, proxyPort, timeout)
  373. }
  374. // addServiceOnPortInternal starts listening for a new service, returning the ServiceInfo.
  375. // Pass proxyPort=0 to allocate a random port. The timeout only applies to UDP
  376. // connections, for now.
  377. func (proxier *Proxier) addServiceOnPortInternal(service proxy.ServicePortName, protocol v1.Protocol, proxyPort int, timeout time.Duration) (*ServiceInfo, error) {
  378. sock, err := proxier.makeProxySocket(protocol, proxier.listenIP, proxyPort)
  379. if err != nil {
  380. return nil, err
  381. }
  382. _, portStr, err := net.SplitHostPort(sock.Addr().String())
  383. if err != nil {
  384. sock.Close()
  385. return nil, err
  386. }
  387. portNum, err := strconv.Atoi(portStr)
  388. if err != nil {
  389. sock.Close()
  390. return nil, err
  391. }
  392. si := &ServiceInfo{
  393. Timeout: timeout,
  394. ActiveClients: newClientCache(),
  395. isAliveAtomic: 1,
  396. proxyPort: portNum,
  397. protocol: protocol,
  398. socket: sock,
  399. sessionAffinityType: v1.ServiceAffinityNone, // default
  400. }
  401. proxier.serviceMap[service] = si
  402. klog.V(2).Infof("Proxying for service %q on %s port %d", service, protocol, portNum)
  403. go func(service proxy.ServicePortName, proxier *Proxier) {
  404. defer runtime.HandleCrash()
  405. atomic.AddInt32(&proxier.numProxyLoops, 1)
  406. sock.ProxyLoop(service, si, proxier.loadBalancer)
  407. atomic.AddInt32(&proxier.numProxyLoops, -1)
  408. }(service, proxier)
  409. return si, nil
  410. }
  411. func (proxier *Proxier) cleanupPortalAndProxy(serviceName proxy.ServicePortName, info *ServiceInfo) error {
  412. if err := proxier.closePortal(serviceName, info); err != nil {
  413. return fmt.Errorf("Failed to close portal for %q: %v", serviceName, err)
  414. }
  415. if err := proxier.stopProxy(serviceName, info); err != nil {
  416. return fmt.Errorf("Failed to stop service %q: %v", serviceName, err)
  417. }
  418. return nil
  419. }
  420. func (proxier *Proxier) mergeService(service *v1.Service) sets.String {
  421. if service == nil {
  422. return nil
  423. }
  424. svcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
  425. if utilproxy.ShouldSkipService(svcName, service) {
  426. klog.V(3).Infof("Skipping service %s due to clusterIP = %q", svcName, service.Spec.ClusterIP)
  427. return nil
  428. }
  429. existingPorts := sets.NewString()
  430. for i := range service.Spec.Ports {
  431. servicePort := &service.Spec.Ports[i]
  432. serviceName := proxy.ServicePortName{NamespacedName: svcName, Port: servicePort.Name}
  433. existingPorts.Insert(servicePort.Name)
  434. info, exists := proxier.serviceMap[serviceName]
  435. // TODO: check health of the socket? What if ProxyLoop exited?
  436. if exists && sameConfig(info, service, servicePort) {
  437. // Nothing changed.
  438. continue
  439. }
  440. if exists {
  441. klog.V(4).Infof("Something changed for service %q: stopping it", serviceName)
  442. if err := proxier.cleanupPortalAndProxy(serviceName, info); err != nil {
  443. klog.Error(err)
  444. }
  445. }
  446. proxyPort, err := proxier.proxyPorts.AllocateNext()
  447. if err != nil {
  448. klog.Errorf("failed to allocate proxy port for service %q: %v", serviceName, err)
  449. continue
  450. }
  451. serviceIP := net.ParseIP(service.Spec.ClusterIP)
  452. klog.V(1).Infof("Adding new service %q at %s/%s", serviceName, net.JoinHostPort(serviceIP.String(), strconv.Itoa(int(servicePort.Port))), servicePort.Protocol)
  453. info, err = proxier.addServiceOnPortInternal(serviceName, servicePort.Protocol, proxyPort, proxier.udpIdleTimeout)
  454. if err != nil {
  455. klog.Errorf("Failed to start proxy for %q: %v", serviceName, err)
  456. continue
  457. }
  458. info.portal.ip = serviceIP
  459. info.portal.port = int(servicePort.Port)
  460. info.externalIPs = service.Spec.ExternalIPs
  461. // Deep-copy in case the service instance changes
  462. info.loadBalancerStatus = *service.Status.LoadBalancer.DeepCopy()
  463. info.nodePort = int(servicePort.NodePort)
  464. info.sessionAffinityType = service.Spec.SessionAffinity
  465. // Kube-apiserver side guarantees SessionAffinityConfig won't be nil when session affinity type is ClientIP
  466. if service.Spec.SessionAffinity == v1.ServiceAffinityClientIP {
  467. info.stickyMaxAgeSeconds = int(*service.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds)
  468. }
  469. klog.V(4).Infof("info: %#v", info)
  470. if err := proxier.openPortal(serviceName, info); err != nil {
  471. klog.Errorf("Failed to open portal for %q: %v", serviceName, err)
  472. }
  473. proxier.loadBalancer.NewService(serviceName, info.sessionAffinityType, info.stickyMaxAgeSeconds)
  474. }
  475. return existingPorts
  476. }
  477. func (proxier *Proxier) unmergeService(service *v1.Service, existingPorts sets.String) {
  478. if service == nil {
  479. return
  480. }
  481. svcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
  482. if utilproxy.ShouldSkipService(svcName, service) {
  483. klog.V(3).Infof("Skipping service %s due to clusterIP = %q", svcName, service.Spec.ClusterIP)
  484. return
  485. }
  486. staleUDPServices := sets.NewString()
  487. for i := range service.Spec.Ports {
  488. servicePort := &service.Spec.Ports[i]
  489. if existingPorts.Has(servicePort.Name) {
  490. continue
  491. }
  492. serviceName := proxy.ServicePortName{NamespacedName: svcName, Port: servicePort.Name}
  493. klog.V(1).Infof("Stopping service %q", serviceName)
  494. info, exists := proxier.serviceMap[serviceName]
  495. if !exists {
  496. klog.Errorf("Service %q is being removed but doesn't exist", serviceName)
  497. continue
  498. }
  499. if proxier.serviceMap[serviceName].protocol == v1.ProtocolUDP {
  500. staleUDPServices.Insert(proxier.serviceMap[serviceName].portal.ip.String())
  501. }
  502. if err := proxier.cleanupPortalAndProxy(serviceName, info); err != nil {
  503. klog.Error(err)
  504. }
  505. proxier.loadBalancer.DeleteService(serviceName)
  506. }
  507. for _, svcIP := range staleUDPServices.UnsortedList() {
  508. if err := conntrack.ClearEntriesForIP(proxier.exec, svcIP, v1.ProtocolUDP); err != nil {
  509. klog.Errorf("Failed to delete stale service IP %s connections, error: %v", svcIP, err)
  510. }
  511. }
  512. }
  513. func (proxier *Proxier) serviceChange(previous, current *v1.Service, detail string) {
  514. var svcName types.NamespacedName
  515. if current != nil {
  516. svcName = types.NamespacedName{Namespace: current.Namespace, Name: current.Name}
  517. } else {
  518. svcName = types.NamespacedName{Namespace: previous.Namespace, Name: previous.Name}
  519. }
  520. klog.V(4).Infof("userspace proxy: %s for %s", detail, svcName)
  521. proxier.serviceChangesLock.Lock()
  522. defer proxier.serviceChangesLock.Unlock()
  523. change, exists := proxier.serviceChanges[svcName]
  524. if !exists {
  525. // change.previous is only set for new changes. We must keep
  526. // the oldest service info (or nil) because correct unmerging
  527. // depends on the next update/del after a merge, not subsequent
  528. // updates.
  529. change = &serviceChange{previous: previous}
  530. proxier.serviceChanges[svcName] = change
  531. }
  532. // Always use the most current service (or nil) as change.current
  533. change.current = current
  534. if reflect.DeepEqual(change.previous, change.current) {
  535. // collapsed change had no effect
  536. delete(proxier.serviceChanges, svcName)
  537. } else if proxier.isInitialized() {
  538. // change will have an effect, ask the proxy to sync
  539. proxier.syncRunner.Run()
  540. }
  541. }
  542. func (proxier *Proxier) OnServiceAdd(service *v1.Service) {
  543. proxier.serviceChange(nil, service, "OnServiceAdd")
  544. }
  545. func (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service) {
  546. proxier.serviceChange(oldService, service, "OnServiceUpdate")
  547. }
  548. func (proxier *Proxier) OnServiceDelete(service *v1.Service) {
  549. proxier.serviceChange(service, nil, "OnServiceDelete")
  550. }
  551. func (proxier *Proxier) OnServiceSynced() {
  552. klog.V(2).Infof("userspace OnServiceSynced")
  553. // Mark services as initialized and (if endpoints are already
  554. // initialized) the entire proxy as initialized
  555. atomic.StoreInt32(&proxier.servicesSynced, 1)
  556. if atomic.LoadInt32(&proxier.endpointsSynced) > 0 {
  557. atomic.StoreInt32(&proxier.initialized, 1)
  558. }
  559. // Must sync from a goroutine to avoid blocking the
  560. // service event handler on startup with large numbers
  561. // of initial objects
  562. go proxier.syncProxyRules()
  563. }
  564. func (proxier *Proxier) OnEndpointsAdd(endpoints *v1.Endpoints) {
  565. proxier.loadBalancer.OnEndpointsAdd(endpoints)
  566. }
  567. func (proxier *Proxier) OnEndpointsUpdate(oldEndpoints, endpoints *v1.Endpoints) {
  568. proxier.loadBalancer.OnEndpointsUpdate(oldEndpoints, endpoints)
  569. }
  570. func (proxier *Proxier) OnEndpointsDelete(endpoints *v1.Endpoints) {
  571. proxier.loadBalancer.OnEndpointsDelete(endpoints)
  572. }
  573. func (proxier *Proxier) OnEndpointsSynced() {
  574. klog.V(2).Infof("userspace OnEndpointsSynced")
  575. proxier.loadBalancer.OnEndpointsSynced()
  576. // Mark endpoints as initialized and (if services are already
  577. // initialized) the entire proxy as initialized
  578. atomic.StoreInt32(&proxier.endpointsSynced, 1)
  579. if atomic.LoadInt32(&proxier.servicesSynced) > 0 {
  580. atomic.StoreInt32(&proxier.initialized, 1)
  581. }
  582. // Must sync from a goroutine to avoid blocking the
  583. // service event handler on startup with large numbers
  584. // of initial objects
  585. go proxier.syncProxyRules()
  586. }
  587. func sameConfig(info *ServiceInfo, service *v1.Service, port *v1.ServicePort) bool {
  588. if info.protocol != port.Protocol || info.portal.port != int(port.Port) || info.nodePort != int(port.NodePort) {
  589. return false
  590. }
  591. if !info.portal.ip.Equal(net.ParseIP(service.Spec.ClusterIP)) {
  592. return false
  593. }
  594. if !ipsEqual(info.externalIPs, service.Spec.ExternalIPs) {
  595. return false
  596. }
  597. if !servicehelper.LoadBalancerStatusEqual(&info.loadBalancerStatus, &service.Status.LoadBalancer) {
  598. return false
  599. }
  600. if info.sessionAffinityType != service.Spec.SessionAffinity {
  601. return false
  602. }
  603. return true
  604. }
  605. func ipsEqual(lhs, rhs []string) bool {
  606. if len(lhs) != len(rhs) {
  607. return false
  608. }
  609. for i := range lhs {
  610. if lhs[i] != rhs[i] {
  611. return false
  612. }
  613. }
  614. return true
  615. }
  616. func (proxier *Proxier) openPortal(service proxy.ServicePortName, info *ServiceInfo) error {
  617. err := proxier.openOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
  618. if err != nil {
  619. return err
  620. }
  621. for _, publicIP := range info.externalIPs {
  622. err = proxier.openOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)
  623. if err != nil {
  624. return err
  625. }
  626. }
  627. for _, ingress := range info.loadBalancerStatus.Ingress {
  628. if ingress.IP != "" {
  629. err = proxier.openOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)
  630. if err != nil {
  631. return err
  632. }
  633. }
  634. }
  635. if info.nodePort != 0 {
  636. err = proxier.openNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)
  637. if err != nil {
  638. return err
  639. }
  640. }
  641. return nil
  642. }
  643. func (proxier *Proxier) openOnePortal(portal portal, protocol v1.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) error {
  644. if local, err := utilproxy.IsLocalIP(portal.ip.String()); err != nil {
  645. return fmt.Errorf("can't determine if IP %s is local, assuming not: %v", portal.ip, err)
  646. } else if local {
  647. err := proxier.claimNodePort(portal.ip, portal.port, protocol, name)
  648. if err != nil {
  649. return err
  650. }
  651. }
  652. // Handle traffic from containers.
  653. args := proxier.iptablesContainerPortalArgs(portal.ip, portal.isExternal, false, portal.port, protocol, proxyIP, proxyPort, name)
  654. portalAddress := net.JoinHostPort(portal.ip.String(), strconv.Itoa(portal.port))
  655. existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerPortalChain, args...)
  656. if err != nil {
  657. klog.Errorf("Failed to install iptables %s rule for service %q, args:%v", iptablesContainerPortalChain, name, args)
  658. return err
  659. }
  660. if !existed {
  661. klog.V(3).Infof("Opened iptables from-containers portal for service %q on %s %s", name, protocol, portalAddress)
  662. }
  663. if portal.isExternal {
  664. args := proxier.iptablesContainerPortalArgs(portal.ip, false, true, portal.port, protocol, proxyIP, proxyPort, name)
  665. existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerPortalChain, args...)
  666. if err != nil {
  667. klog.Errorf("Failed to install iptables %s rule that opens service %q for local traffic, args:%v", iptablesContainerPortalChain, name, args)
  668. return err
  669. }
  670. if !existed {
  671. klog.V(3).Infof("Opened iptables from-containers portal for service %q on %s %s for local traffic", name, protocol, portalAddress)
  672. }
  673. args = proxier.iptablesHostPortalArgs(portal.ip, true, portal.port, protocol, proxyIP, proxyPort, name)
  674. existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostPortalChain, args...)
  675. if err != nil {
  676. klog.Errorf("Failed to install iptables %s rule for service %q for dst-local traffic", iptablesHostPortalChain, name)
  677. return err
  678. }
  679. if !existed {
  680. klog.V(3).Infof("Opened iptables from-host portal for service %q on %s %s for dst-local traffic", name, protocol, portalAddress)
  681. }
  682. return nil
  683. }
  684. // Handle traffic from the host.
  685. args = proxier.iptablesHostPortalArgs(portal.ip, false, portal.port, protocol, proxyIP, proxyPort, name)
  686. existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostPortalChain, args...)
  687. if err != nil {
  688. klog.Errorf("Failed to install iptables %s rule for service %q", iptablesHostPortalChain, name)
  689. return err
  690. }
  691. if !existed {
  692. klog.V(3).Infof("Opened iptables from-host portal for service %q on %s %s", name, protocol, portalAddress)
  693. }
  694. return nil
  695. }
  696. // Marks a port as being owned by a particular service, or returns error if already claimed.
  697. // Idempotent: reclaiming with the same owner is not an error
  698. func (proxier *Proxier) claimNodePort(ip net.IP, port int, protocol v1.Protocol, owner proxy.ServicePortName) error {
  699. proxier.portMapMutex.Lock()
  700. defer proxier.portMapMutex.Unlock()
  701. // TODO: We could pre-populate some reserved ports into portMap and/or blacklist some well-known ports
  702. key := portMapKey{ip: ip.String(), port: port, protocol: protocol}
  703. existing, found := proxier.portMap[key]
  704. if !found {
  705. // Hold the actual port open, even though we use iptables to redirect
  706. // it. This ensures that a) it's safe to take and b) that stays true.
  707. // NOTE: We should not need to have a real listen()ing socket - bind()
  708. // should be enough, but I can't figure out a way to e2e test without
  709. // it. Tools like 'ss' and 'netstat' do not show sockets that are
  710. // bind()ed but not listen()ed, and at least the default debian netcat
  711. // has no way to avoid about 10 seconds of retries.
  712. socket, err := proxier.makeProxySocket(protocol, ip, port)
  713. if err != nil {
  714. return fmt.Errorf("can't open node port for %s: %v", key.String(), err)
  715. }
  716. proxier.portMap[key] = &portMapValue{owner: owner, socket: socket}
  717. klog.V(2).Infof("Claimed local port %s", key.String())
  718. return nil
  719. }
  720. if existing.owner == owner {
  721. // We are idempotent
  722. return nil
  723. }
  724. return fmt.Errorf("Port conflict detected on port %s. %v vs %v", key.String(), owner, existing)
  725. }
  726. // Release a claim on a port. Returns an error if the owner does not match the claim.
  727. // Tolerates release on an unclaimed port, to simplify .
  728. func (proxier *Proxier) releaseNodePort(ip net.IP, port int, protocol v1.Protocol, owner proxy.ServicePortName) error {
  729. proxier.portMapMutex.Lock()
  730. defer proxier.portMapMutex.Unlock()
  731. key := portMapKey{ip: ip.String(), port: port, protocol: protocol}
  732. existing, found := proxier.portMap[key]
  733. if !found {
  734. // We tolerate this, it happens if we are cleaning up a failed allocation
  735. klog.Infof("Ignoring release on unowned port: %v", key)
  736. return nil
  737. }
  738. if existing.owner != owner {
  739. return fmt.Errorf("Port conflict detected on port %v (unowned unlock). %v vs %v", key, owner, existing)
  740. }
  741. delete(proxier.portMap, key)
  742. existing.socket.Close()
  743. return nil
  744. }
  745. func (proxier *Proxier) openNodePort(nodePort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) error {
  746. // TODO: Do we want to allow containers to access public services? Probably yes.
  747. // TODO: We could refactor this to be the same code as portal, but with IP == nil
  748. err := proxier.claimNodePort(nil, nodePort, protocol, name)
  749. if err != nil {
  750. return err
  751. }
  752. // Handle traffic from containers.
  753. args := proxier.iptablesContainerPortalArgs(nil, false, false, nodePort, protocol, proxyIP, proxyPort, name)
  754. existed, err := proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesContainerNodePortChain, args...)
  755. if err != nil {
  756. klog.Errorf("Failed to install iptables %s rule for service %q", iptablesContainerNodePortChain, name)
  757. return err
  758. }
  759. if !existed {
  760. klog.Infof("Opened iptables from-containers public port for service %q on %s port %d", name, protocol, nodePort)
  761. }
  762. // Handle traffic from the host.
  763. args = proxier.iptablesHostNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
  764. existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableNAT, iptablesHostNodePortChain, args...)
  765. if err != nil {
  766. klog.Errorf("Failed to install iptables %s rule for service %q", iptablesHostNodePortChain, name)
  767. return err
  768. }
  769. if !existed {
  770. klog.Infof("Opened iptables from-host public port for service %q on %s port %d", name, protocol, nodePort)
  771. }
  772. args = proxier.iptablesNonLocalNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
  773. existed, err = proxier.iptables.EnsureRule(iptables.Append, iptables.TableFilter, iptablesNonLocalNodePortChain, args...)
  774. if err != nil {
  775. klog.Errorf("Failed to install iptables %s rule for service %q", iptablesNonLocalNodePortChain, name)
  776. return err
  777. }
  778. if !existed {
  779. klog.Infof("Opened iptables from-non-local public port for service %q on %s port %d", name, protocol, nodePort)
  780. }
  781. return nil
  782. }
  783. func (proxier *Proxier) closePortal(service proxy.ServicePortName, info *ServiceInfo) error {
  784. // Collect errors and report them all at the end.
  785. el := proxier.closeOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
  786. for _, publicIP := range info.externalIPs {
  787. el = append(el, proxier.closeOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)...)
  788. }
  789. for _, ingress := range info.loadBalancerStatus.Ingress {
  790. if ingress.IP != "" {
  791. el = append(el, proxier.closeOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)...)
  792. }
  793. }
  794. if info.nodePort != 0 {
  795. el = append(el, proxier.closeNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)...)
  796. }
  797. if len(el) == 0 {
  798. klog.V(3).Infof("Closed iptables portals for service %q", service)
  799. } else {
  800. klog.Errorf("Some errors closing iptables portals for service %q", service)
  801. }
  802. return utilerrors.NewAggregate(el)
  803. }
  804. func (proxier *Proxier) closeOnePortal(portal portal, protocol v1.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) []error {
  805. el := []error{}
  806. if local, err := utilproxy.IsLocalIP(portal.ip.String()); err != nil {
  807. el = append(el, fmt.Errorf("can't determine if IP %s is local, assuming not: %v", portal.ip, err))
  808. } else if local {
  809. if err := proxier.releaseNodePort(portal.ip, portal.port, protocol, name); err != nil {
  810. el = append(el, err)
  811. }
  812. }
  813. // Handle traffic from containers.
  814. args := proxier.iptablesContainerPortalArgs(portal.ip, portal.isExternal, false, portal.port, protocol, proxyIP, proxyPort, name)
  815. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerPortalChain, args...); err != nil {
  816. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerPortalChain, name)
  817. el = append(el, err)
  818. }
  819. if portal.isExternal {
  820. args := proxier.iptablesContainerPortalArgs(portal.ip, false, true, portal.port, protocol, proxyIP, proxyPort, name)
  821. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerPortalChain, args...); err != nil {
  822. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerPortalChain, name)
  823. el = append(el, err)
  824. }
  825. args = proxier.iptablesHostPortalArgs(portal.ip, true, portal.port, protocol, proxyIP, proxyPort, name)
  826. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostPortalChain, args...); err != nil {
  827. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostPortalChain, name)
  828. el = append(el, err)
  829. }
  830. return el
  831. }
  832. // Handle traffic from the host (portalIP is not external).
  833. args = proxier.iptablesHostPortalArgs(portal.ip, false, portal.port, protocol, proxyIP, proxyPort, name)
  834. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostPortalChain, args...); err != nil {
  835. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostPortalChain, name)
  836. el = append(el, err)
  837. }
  838. return el
  839. }
  840. func (proxier *Proxier) closeNodePort(nodePort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, name proxy.ServicePortName) []error {
  841. el := []error{}
  842. // Handle traffic from containers.
  843. args := proxier.iptablesContainerPortalArgs(nil, false, false, nodePort, protocol, proxyIP, proxyPort, name)
  844. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesContainerNodePortChain, args...); err != nil {
  845. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesContainerNodePortChain, name)
  846. el = append(el, err)
  847. }
  848. // Handle traffic from the host.
  849. args = proxier.iptablesHostNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
  850. if err := proxier.iptables.DeleteRule(iptables.TableNAT, iptablesHostNodePortChain, args...); err != nil {
  851. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesHostNodePortChain, name)
  852. el = append(el, err)
  853. }
  854. // Handle traffic not local to the host
  855. args = proxier.iptablesNonLocalNodePortArgs(nodePort, protocol, proxyIP, proxyPort, name)
  856. if err := proxier.iptables.DeleteRule(iptables.TableFilter, iptablesNonLocalNodePortChain, args...); err != nil {
  857. klog.Errorf("Failed to delete iptables %s rule for service %q", iptablesNonLocalNodePortChain, name)
  858. el = append(el, err)
  859. }
  860. if err := proxier.releaseNodePort(nil, nodePort, protocol, name); err != nil {
  861. el = append(el, err)
  862. }
  863. return el
  864. }
  865. // See comments in the *PortalArgs() functions for some details about why we
  866. // use two chains for portals.
  867. var iptablesContainerPortalChain iptables.Chain = "KUBE-PORTALS-CONTAINER"
  868. var iptablesHostPortalChain iptables.Chain = "KUBE-PORTALS-HOST"
  869. // Chains for NodePort services
  870. var iptablesContainerNodePortChain iptables.Chain = "KUBE-NODEPORT-CONTAINER"
  871. var iptablesHostNodePortChain iptables.Chain = "KUBE-NODEPORT-HOST"
  872. var iptablesNonLocalNodePortChain iptables.Chain = "KUBE-NODEPORT-NON-LOCAL"
  873. // Ensure that the iptables infrastructure we use is set up. This can safely be called periodically.
  874. func iptablesInit(ipt iptables.Interface) error {
  875. // TODO: There is almost certainly room for optimization here. E.g. If
  876. // we knew the service-cluster-ip-range CIDR we could fast-track outbound packets not
  877. // destined for a service. There's probably more, help wanted.
  878. // Danger - order of these rules matters here:
  879. //
  880. // We match portal rules first, then NodePort rules. For NodePort rules, we filter primarily on --dst-type LOCAL,
  881. // because we want to listen on all local addresses, but don't match internet traffic with the same dst port number.
  882. //
  883. // There is one complication (per thockin):
  884. // -m addrtype --dst-type LOCAL is what we want except that it is broken (by intent without foresight to our usecase)
  885. // on at least GCE. Specifically, GCE machines have a daemon which learns what external IPs are forwarded to that
  886. // machine, and configure a local route for that IP, making a match for --dst-type LOCAL when we don't want it to.
  887. // Removing the route gives correct behavior until the daemon recreates it.
  888. // Killing the daemon is an option, but means that any non-kubernetes use of the machine with external IP will be broken.
  889. //
  890. // This applies to IPs on GCE that are actually from a load-balancer; they will be categorized as LOCAL.
  891. // _If_ the chains were in the wrong order, and the LB traffic had dst-port == a NodePort on some other service,
  892. // the NodePort would take priority (incorrectly).
  893. // This is unlikely (and would only affect outgoing traffic from the cluster to the load balancer, which seems
  894. // doubly-unlikely), but we need to be careful to keep the rules in the right order.
  895. args := []string{ /* service-cluster-ip-range matching could go here */ }
  896. args = append(args, "-m", "comment", "--comment", "handle ClusterIPs; NOTE: this must be before the NodePort rules")
  897. if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesContainerPortalChain); err != nil {
  898. return err
  899. }
  900. if _, err := ipt.EnsureRule(iptables.Prepend, iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerPortalChain))...); err != nil {
  901. return err
  902. }
  903. if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesHostPortalChain); err != nil {
  904. return err
  905. }
  906. if _, err := ipt.EnsureRule(iptables.Prepend, iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostPortalChain))...); err != nil {
  907. return err
  908. }
  909. // This set of rules matches broadly (addrtype & destination port), and therefore must come after the portal rules
  910. args = []string{"-m", "addrtype", "--dst-type", "LOCAL"}
  911. args = append(args, "-m", "comment", "--comment", "handle service NodePorts; NOTE: this must be the last rule in the chain")
  912. if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesContainerNodePortChain); err != nil {
  913. return err
  914. }
  915. if _, err := ipt.EnsureRule(iptables.Append, iptables.TableNAT, iptables.ChainPrerouting, append(args, "-j", string(iptablesContainerNodePortChain))...); err != nil {
  916. return err
  917. }
  918. if _, err := ipt.EnsureChain(iptables.TableNAT, iptablesHostNodePortChain); err != nil {
  919. return err
  920. }
  921. if _, err := ipt.EnsureRule(iptables.Append, iptables.TableNAT, iptables.ChainOutput, append(args, "-j", string(iptablesHostNodePortChain))...); err != nil {
  922. return err
  923. }
  924. // Create a chain intended to explicitly allow non-local NodePort
  925. // traffic to work around default-deny iptables configurations
  926. // that would otherwise reject such traffic.
  927. args = []string{"-m", "comment", "--comment", "Ensure that non-local NodePort traffic can flow"}
  928. if _, err := ipt.EnsureChain(iptables.TableFilter, iptablesNonLocalNodePortChain); err != nil {
  929. return err
  930. }
  931. if _, err := ipt.EnsureRule(iptables.Prepend, iptables.TableFilter, iptables.ChainInput, append(args, "-j", string(iptablesNonLocalNodePortChain))...); err != nil {
  932. return err
  933. }
  934. // TODO: Verify order of rules.
  935. return nil
  936. }
  937. // Flush all of our custom iptables rules.
  938. func iptablesFlush(ipt iptables.Interface) error {
  939. el := []error{}
  940. if err := ipt.FlushChain(iptables.TableNAT, iptablesContainerPortalChain); err != nil {
  941. el = append(el, err)
  942. }
  943. if err := ipt.FlushChain(iptables.TableNAT, iptablesHostPortalChain); err != nil {
  944. el = append(el, err)
  945. }
  946. if err := ipt.FlushChain(iptables.TableNAT, iptablesContainerNodePortChain); err != nil {
  947. el = append(el, err)
  948. }
  949. if err := ipt.FlushChain(iptables.TableNAT, iptablesHostNodePortChain); err != nil {
  950. el = append(el, err)
  951. }
  952. if err := ipt.FlushChain(iptables.TableFilter, iptablesNonLocalNodePortChain); err != nil {
  953. el = append(el, err)
  954. }
  955. if len(el) != 0 {
  956. klog.Errorf("Some errors flushing old iptables portals: %v", el)
  957. }
  958. return utilerrors.NewAggregate(el)
  959. }
  960. // Used below.
  961. var zeroIPv4 = net.ParseIP("0.0.0.0")
  962. var localhostIPv4 = net.ParseIP("127.0.0.1")
  963. var zeroIPv6 = net.ParseIP("::")
  964. var localhostIPv6 = net.ParseIP("::1")
  965. // Build a slice of iptables args that are common to from-container and from-host portal rules.
  966. func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol v1.Protocol, service proxy.ServicePortName) []string {
  967. // This list needs to include all fields as they are eventually spit out
  968. // by iptables-save. This is because some systems do not support the
  969. // 'iptables -C' arg, and so fall back on parsing iptables-save output.
  970. // If this does not match, it will not pass the check. For example:
  971. // adding the /32 on the destination IP arg is not strictly required,
  972. // but causes this list to not match the final iptables-save output.
  973. // This is fragile and I hope one day we can stop supporting such old
  974. // iptables versions.
  975. args := []string{
  976. "-m", "comment",
  977. "--comment", service.String(),
  978. "-p", strings.ToLower(string(protocol)),
  979. "-m", strings.ToLower(string(protocol)),
  980. "--dport", fmt.Sprintf("%d", destPort),
  981. }
  982. if destIP != nil {
  983. args = append(args, "-d", utilproxy.ToCIDR(destIP))
  984. }
  985. if addPhysicalInterfaceMatch {
  986. args = append(args, "-m", "physdev", "!", "--physdev-is-in")
  987. }
  988. if addDstLocalMatch {
  989. args = append(args, "-m", "addrtype", "--dst-type", "LOCAL")
  990. }
  991. return args
  992. }
  993. // Build a slice of iptables args for a from-container portal rule.
  994. func (proxier *Proxier) iptablesContainerPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
  995. args := iptablesCommonPortalArgs(destIP, addPhysicalInterfaceMatch, addDstLocalMatch, destPort, protocol, service)
  996. // This is tricky.
  997. //
  998. // If the proxy is bound (see Proxier.listenIP) to 0.0.0.0 ("any
  999. // interface") we want to use REDIRECT, which sends traffic to the
  1000. // "primary address of the incoming interface" which means the container
  1001. // bridge, if there is one. When the response comes, it comes from that
  1002. // same interface, so the NAT matches and the response packet is
  1003. // correct. This matters for UDP, since there is no per-connection port
  1004. // number.
  1005. //
  1006. // The alternative would be to use DNAT, except that it doesn't work
  1007. // (empirically):
  1008. // * DNAT to 127.0.0.1 = Packets just disappear - this seems to be a
  1009. // well-known limitation of iptables.
  1010. // * DNAT to eth0's IP = Response packets come from the bridge, which
  1011. // breaks the NAT, and makes things like DNS not accept them. If
  1012. // this could be resolved, it would simplify all of this code.
  1013. //
  1014. // If the proxy is bound to a specific IP, then we have to use DNAT to
  1015. // that IP. Unlike the previous case, this works because the proxy is
  1016. // ONLY listening on that IP, not the bridge.
  1017. //
  1018. // Why would anyone bind to an address that is not inclusive of
  1019. // localhost? Apparently some cloud environments have their public IP
  1020. // exposed as a real network interface AND do not have firewalling. We
  1021. // don't want to expose everything out to the world.
  1022. //
  1023. // Unfortunately, I don't know of any way to listen on some (N > 1)
  1024. // interfaces but not ALL interfaces, short of doing it manually, and
  1025. // this is simpler than that.
  1026. //
  1027. // If the proxy is bound to localhost only, all of this is broken. Not
  1028. // allowed.
  1029. if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
  1030. // TODO: Can we REDIRECT with IPv6?
  1031. args = append(args, "-j", "REDIRECT", "--to-ports", fmt.Sprintf("%d", proxyPort))
  1032. } else {
  1033. // TODO: Can we DNAT with IPv6?
  1034. args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
  1035. }
  1036. return args
  1037. }
  1038. // Build a slice of iptables args for a from-host portal rule.
  1039. func (proxier *Proxier) iptablesHostPortalArgs(destIP net.IP, addDstLocalMatch bool, destPort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
  1040. args := iptablesCommonPortalArgs(destIP, false, addDstLocalMatch, destPort, protocol, service)
  1041. // This is tricky.
  1042. //
  1043. // If the proxy is bound (see Proxier.listenIP) to 0.0.0.0 ("any
  1044. // interface") we want to do the same as from-container traffic and use
  1045. // REDIRECT. Except that it doesn't work (empirically). REDIRECT on
  1046. // local packets sends the traffic to localhost (special case, but it is
  1047. // documented) but the response comes from the eth0 IP (not sure why,
  1048. // truthfully), which makes DNS unhappy.
  1049. //
  1050. // So we have to use DNAT. DNAT to 127.0.0.1 can't work for the same
  1051. // reason.
  1052. //
  1053. // So we do our best to find an interface that is not a loopback and
  1054. // DNAT to that. This works (again, empirically).
  1055. //
  1056. // If the proxy is bound to a specific IP, then we have to use DNAT to
  1057. // that IP. Unlike the previous case, this works because the proxy is
  1058. // ONLY listening on that IP, not the bridge.
  1059. //
  1060. // If the proxy is bound to localhost only, this should work, but we
  1061. // don't allow it for now.
  1062. if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
  1063. proxyIP = proxier.hostIP
  1064. }
  1065. // TODO: Can we DNAT with IPv6?
  1066. args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
  1067. return args
  1068. }
  1069. // Build a slice of iptables args for a from-host public-port rule.
  1070. // See iptablesHostPortalArgs
  1071. // TODO: Should we just reuse iptablesHostPortalArgs?
  1072. func (proxier *Proxier) iptablesHostNodePortArgs(nodePort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
  1073. args := iptablesCommonPortalArgs(nil, false, false, nodePort, protocol, service)
  1074. if proxyIP.Equal(zeroIPv4) || proxyIP.Equal(zeroIPv6) {
  1075. proxyIP = proxier.hostIP
  1076. }
  1077. // TODO: Can we DNAT with IPv6?
  1078. args = append(args, "-j", "DNAT", "--to-destination", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort)))
  1079. return args
  1080. }
  1081. // Build a slice of iptables args for an from-non-local public-port rule.
  1082. func (proxier *Proxier) iptablesNonLocalNodePortArgs(nodePort int, protocol v1.Protocol, proxyIP net.IP, proxyPort int, service proxy.ServicePortName) []string {
  1083. args := iptablesCommonPortalArgs(nil, false, false, proxyPort, protocol, service)
  1084. args = append(args, "-m", "state", "--state", "NEW", "-j", "ACCEPT")
  1085. return args
  1086. }
  1087. func isTooManyFDsError(err error) bool {
  1088. return strings.Contains(err.Error(), "too many open files")
  1089. }
  1090. func isClosedError(err error) bool {
  1091. // A brief discussion about handling closed error here:
  1092. // https://code.google.com/p/go/issues/detail?id=4373#c14
  1093. // TODO: maybe create a stoppable TCP listener that returns a StoppedError
  1094. return strings.HasSuffix(err.Error(), "use of closed network connection")
  1095. }