proxier.go 48 KB

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