cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
edgediscovery/allregions/region.go
82lines · modecode
| 1 | package allregions |
| 2 | |
| 3 | import ( |
| 4 | "net" |
| 5 | ) |
| 6 | |
| 7 | // Region contains cloudflared edge addresses. The edge is partitioned into several regions for |
| 8 | // redundancy purposes. |
| 9 | type Region struct { |
| 10 | connFor map[*net.TCPAddr]UsedBy |
| 11 | } |
| 12 | |
| 13 | // NewRegion creates a region with the given addresses, which are all unused. |
| 14 | func NewRegion(addrs []*net.TCPAddr) Region { |
| 15 | // The zero value of UsedBy is Unused(), so we can just initialize the map's values with their |
| 16 | // zero values. |
| 17 | m := make(map[*net.TCPAddr]UsedBy) |
| 18 | for _, addr := range addrs { |
| 19 | m[addr] = Unused() |
| 20 | } |
| 21 | return Region{connFor: m} |
| 22 | } |
| 23 | |
| 24 | // AddrUsedBy finds the address used by the given connection in this region. |
| 25 | // Returns nil if the connection isn't using any IP. |
| 26 | func (r *Region) AddrUsedBy(connID int) *net.TCPAddr { |
| 27 | for addr, used := range r.connFor { |
| 28 | if used.Used && used.ConnID == connID { |
| 29 | return addr |
| 30 | } |
| 31 | } |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // AvailableAddrs counts how many unused addresses this region contains. |
| 36 | func (r Region) AvailableAddrs() int { |
| 37 | n := 0 |
| 38 | for _, usedby := range r.connFor { |
| 39 | if !usedby.Used { |
| 40 | n++ |
| 41 | } |
| 42 | } |
| 43 | return n |
| 44 | } |
| 45 | |
| 46 | // GetUnusedIP returns a random unused address in this region. |
| 47 | // Returns nil if all addresses are in use. |
| 48 | func (r Region) GetUnusedIP(excluding *net.TCPAddr) *net.TCPAddr { |
| 49 | for addr, usedby := range r.connFor { |
| 50 | if !usedby.Used && addr != excluding { |
| 51 | return addr |
| 52 | } |
| 53 | } |
| 54 | return nil |
| 55 | } |
| 56 | |
| 57 | // Use the address, assigning it to a proxy connection. |
| 58 | func (r Region) Use(addr *net.TCPAddr, connID int) { |
| 59 | if addr == nil { |
| 60 | //logrus.Errorf("Attempted to use nil address for connection %d", connID) |
| 61 | return |
| 62 | } |
| 63 | r.connFor[addr] = InUse(connID) |
| 64 | } |
| 65 | |
| 66 | // GetAnyAddress returns an arbitrary address from the region. |
| 67 | func (r Region) GetAnyAddress() *net.TCPAddr { |
| 68 | for addr := range r.connFor { |
| 69 | return addr |
| 70 | } |
| 71 | return nil |
| 72 | } |
| 73 | |
| 74 | // GiveBack the address, ensuring it is no longer assigned to an IP. |
| 75 | // Returns true if the address is in this region. |
| 76 | func (r Region) GiveBack(addr *net.TCPAddr) (ok bool) { |
| 77 | if _, ok := r.connFor[addr]; !ok { |
| 78 | return false |
| 79 | } |
| 80 | r.connFor[addr] = Unused() |
| 81 | return true |
| 82 | } |
| 83 | |