flowtrack.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //
  4. // Original implementation (from same author) from which this was derived was:
  5. // https://github.com/golang/groupcache/blob/5b532d6fd5efaf7fa130d4e859a2fde0fc3a9e1b/lru/lru.go
  6. // ... which was Apache licensed:
  7. // https://github.com/golang/groupcache/blob/master/LICENSE
  8. // Package flowtrack contains types for tracking TCP/UDP flows by 4-tuples.
  9. package flowtrack
  10. import (
  11. "container/list"
  12. "encoding/json"
  13. "fmt"
  14. "net/netip"
  15. "tailscale.com/types/ipproto"
  16. )
  17. // MakeTuple makes a Tuple out of netip.AddrPort values.
  18. func MakeTuple(proto ipproto.Proto, src, dst netip.AddrPort) Tuple {
  19. return Tuple{
  20. proto: proto,
  21. src: src.Addr().As16(),
  22. srcPort: src.Port(),
  23. dst: dst.Addr().As16(),
  24. dstPort: dst.Port(),
  25. }
  26. }
  27. // Tuple is a 5-tuple of proto, source and destination IP and port.
  28. //
  29. // This struct originally used netip.AddrPort, but that was about twice as slow
  30. // when used as a map key due to the alignment and extra space for the IPv6 zone
  31. // pointers (unneeded for all our current 2024-06-17 flowtrack needs).
  32. //
  33. // This struct is packed optimally and doesn't contain gaps or pointers.
  34. type Tuple struct {
  35. src [16]byte
  36. dst [16]byte
  37. srcPort uint16
  38. dstPort uint16
  39. proto ipproto.Proto
  40. }
  41. func (t Tuple) SrcAddr() netip.Addr {
  42. return netip.AddrFrom16(t.src).Unmap()
  43. }
  44. func (t Tuple) DstAddr() netip.Addr {
  45. return netip.AddrFrom16(t.dst).Unmap()
  46. }
  47. func (t Tuple) SrcPort() uint16 { return t.srcPort }
  48. func (t Tuple) DstPort() uint16 { return t.dstPort }
  49. func (t Tuple) String() string {
  50. return fmt.Sprintf("(%v %v => %v)", t.proto,
  51. netip.AddrPortFrom(t.SrcAddr(), t.srcPort),
  52. netip.AddrPortFrom(t.DstAddr(), t.dstPort))
  53. }
  54. func (t Tuple) MarshalJSON() ([]byte, error) {
  55. return json.Marshal(tupleOld{
  56. Proto: t.proto,
  57. Src: netip.AddrPortFrom(t.SrcAddr(), t.srcPort),
  58. Dst: netip.AddrPortFrom(t.DstAddr(), t.dstPort),
  59. })
  60. }
  61. func (t *Tuple) UnmarshalJSON(b []byte) error {
  62. var ot tupleOld
  63. if err := json.Unmarshal(b, &ot); err != nil {
  64. return err
  65. }
  66. *t = MakeTuple(ot.Proto, ot.Src, ot.Dst)
  67. return nil
  68. }
  69. // tupleOld is the old JSON representation of Tuple, before
  70. // we split and rearranged the fields for efficiency. This type
  71. // is the JSON adapter type to make sure we still generate
  72. // the same JSON as before.
  73. type tupleOld struct {
  74. Proto ipproto.Proto `json:"proto"`
  75. Src netip.AddrPort `json:"src"`
  76. Dst netip.AddrPort `json:"dst"`
  77. }
  78. // Cache is an LRU cache keyed by Tuple.
  79. //
  80. // The zero value is valid to use.
  81. //
  82. // It is not safe for concurrent access.
  83. type Cache[Value any] struct {
  84. // MaxEntries is the maximum number of cache entries before
  85. // an item is evicted. Zero means no limit.
  86. MaxEntries int
  87. ll *list.List
  88. m map[Tuple]*list.Element // of *entry
  89. }
  90. // entry is the container/list element type.
  91. type entry[Value any] struct {
  92. key Tuple
  93. value Value
  94. }
  95. // Add adds a value to the cache, set or updating its associated
  96. // value.
  97. //
  98. // If MaxEntries is non-zero and the length of the cache is greater
  99. // after any addition, the least recently used value is evicted.
  100. func (c *Cache[Value]) Add(key Tuple, value Value) {
  101. if c.m == nil {
  102. c.m = make(map[Tuple]*list.Element)
  103. c.ll = list.New()
  104. }
  105. if ee, ok := c.m[key]; ok {
  106. c.ll.MoveToFront(ee)
  107. ee.Value.(*entry[Value]).value = value
  108. return
  109. }
  110. ele := c.ll.PushFront(&entry[Value]{key, value})
  111. c.m[key] = ele
  112. if c.MaxEntries != 0 && c.Len() > c.MaxEntries {
  113. c.RemoveOldest()
  114. }
  115. }
  116. // Get looks up a key's value from the cache, also reporting
  117. // whether it was present.
  118. func (c *Cache[Value]) Get(key Tuple) (value *Value, ok bool) {
  119. if ele, hit := c.m[key]; hit {
  120. c.ll.MoveToFront(ele)
  121. return &ele.Value.(*entry[Value]).value, true
  122. }
  123. return nil, false
  124. }
  125. // Remove removes the provided key from the cache if it was present.
  126. func (c *Cache[Value]) Remove(key Tuple) {
  127. if ele, hit := c.m[key]; hit {
  128. c.removeElement(ele)
  129. }
  130. }
  131. // RemoveOldest removes the oldest item from the cache, if any.
  132. func (c *Cache[Value]) RemoveOldest() {
  133. if c.ll != nil {
  134. if ele := c.ll.Back(); ele != nil {
  135. c.removeElement(ele)
  136. }
  137. }
  138. }
  139. func (c *Cache[Value]) removeElement(e *list.Element) {
  140. c.ll.Remove(e)
  141. delete(c.m, e.Value.(*entry[Value]).key)
  142. }
  143. // Len returns the number of items in the cache.
  144. func (c *Cache[Value]) Len() int { return len(c.m) }