structures.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package ipam
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strings"
  7. "sync"
  8. "github.com/docker/libnetwork/datastore"
  9. "github.com/docker/libnetwork/ipamapi"
  10. "github.com/docker/libnetwork/types"
  11. )
  12. // SubnetKey is the pointer to the configured pools in each address space
  13. type SubnetKey struct {
  14. AddressSpace string
  15. Subnet string
  16. ChildSubnet string
  17. }
  18. // PoolData contains the configured pool data
  19. type PoolData struct {
  20. ParentKey SubnetKey
  21. Pool *net.IPNet
  22. Range *AddressRange `json:",omitempty"`
  23. RefCount int
  24. }
  25. // addrSpace contains the pool configurations for the address space
  26. type addrSpace struct {
  27. subnets map[SubnetKey]*PoolData
  28. dbIndex uint64
  29. dbExists bool
  30. id string
  31. scope string
  32. ds datastore.DataStore
  33. alloc *Allocator
  34. sync.Mutex
  35. }
  36. // AddressRange specifies first and last ip ordinal which
  37. // identifies a range in a pool of addresses
  38. type AddressRange struct {
  39. Sub *net.IPNet
  40. Start, End uint64
  41. }
  42. // String returns the string form of the AddressRange object
  43. func (r *AddressRange) String() string {
  44. return fmt.Sprintf("Sub: %s, range [%d, %d]", r.Sub, r.Start, r.End)
  45. }
  46. // MarshalJSON returns the JSON encoding of the Range object
  47. func (r *AddressRange) MarshalJSON() ([]byte, error) {
  48. m := map[string]interface{}{
  49. "Sub": r.Sub.String(),
  50. "Start": r.Start,
  51. "End": r.End,
  52. }
  53. return json.Marshal(m)
  54. }
  55. // UnmarshalJSON decodes data into the Range object
  56. func (r *AddressRange) UnmarshalJSON(data []byte) error {
  57. m := map[string]interface{}{}
  58. err := json.Unmarshal(data, &m)
  59. if err != nil {
  60. return err
  61. }
  62. if r.Sub, err = types.ParseCIDR(m["Sub"].(string)); err != nil {
  63. return err
  64. }
  65. r.Start = uint64(m["Start"].(float64))
  66. r.End = uint64(m["End"].(float64))
  67. return nil
  68. }
  69. // String returns the string form of the SubnetKey object
  70. func (s *SubnetKey) String() string {
  71. k := fmt.Sprintf("%s/%s", s.AddressSpace, s.Subnet)
  72. if s.ChildSubnet != "" {
  73. k = fmt.Sprintf("%s/%s", k, s.ChildSubnet)
  74. }
  75. return k
  76. }
  77. // FromString populates the SubnetKey object reading it from string
  78. func (s *SubnetKey) FromString(str string) error {
  79. if str == "" || !strings.Contains(str, "/") {
  80. return types.BadRequestErrorf("invalid string form for subnetkey: %s", str)
  81. }
  82. p := strings.Split(str, "/")
  83. if len(p) != 3 && len(p) != 5 {
  84. return types.BadRequestErrorf("invalid string form for subnetkey: %s", str)
  85. }
  86. s.AddressSpace = p[0]
  87. s.Subnet = fmt.Sprintf("%s/%s", p[1], p[2])
  88. if len(p) == 5 {
  89. s.ChildSubnet = fmt.Sprintf("%s/%s", p[3], p[4])
  90. }
  91. return nil
  92. }
  93. // String returns the string form of the PoolData object
  94. func (p *PoolData) String() string {
  95. return fmt.Sprintf("ParentKey: %s, Pool: %s, Range: %s, RefCount: %d",
  96. p.ParentKey.String(), p.Pool.String(), p.Range, p.RefCount)
  97. }
  98. // MarshalJSON returns the JSON encoding of the PoolData object
  99. func (p *PoolData) MarshalJSON() ([]byte, error) {
  100. m := map[string]interface{}{
  101. "ParentKey": p.ParentKey,
  102. "RefCount": p.RefCount,
  103. }
  104. if p.Pool != nil {
  105. m["Pool"] = p.Pool.String()
  106. }
  107. if p.Range != nil {
  108. m["Range"] = p.Range
  109. }
  110. return json.Marshal(m)
  111. }
  112. // UnmarshalJSON decodes data into the PoolData object
  113. func (p *PoolData) UnmarshalJSON(data []byte) error {
  114. var (
  115. err error
  116. t struct {
  117. ParentKey SubnetKey
  118. Pool string
  119. Range *AddressRange `json:",omitempty"`
  120. RefCount int
  121. }
  122. )
  123. if err = json.Unmarshal(data, &t); err != nil {
  124. return err
  125. }
  126. p.ParentKey = t.ParentKey
  127. p.Range = t.Range
  128. p.RefCount = t.RefCount
  129. if t.Pool != "" {
  130. if p.Pool, err = types.ParseCIDR(t.Pool); err != nil {
  131. return err
  132. }
  133. }
  134. return nil
  135. }
  136. // MarshalJSON returns the JSON encoding of the addrSpace object
  137. func (aSpace *addrSpace) MarshalJSON() ([]byte, error) {
  138. aSpace.Lock()
  139. defer aSpace.Unlock()
  140. m := map[string]interface{}{
  141. "Scope": string(aSpace.scope),
  142. }
  143. if aSpace.subnets != nil {
  144. s := map[string]*PoolData{}
  145. for k, v := range aSpace.subnets {
  146. s[k.String()] = v
  147. }
  148. m["Subnets"] = s
  149. }
  150. return json.Marshal(m)
  151. }
  152. // UnmarshalJSON decodes data into the addrSpace object
  153. func (aSpace *addrSpace) UnmarshalJSON(data []byte) error {
  154. aSpace.Lock()
  155. defer aSpace.Unlock()
  156. m := map[string]interface{}{}
  157. err := json.Unmarshal(data, &m)
  158. if err != nil {
  159. return err
  160. }
  161. aSpace.scope = datastore.LocalScope
  162. s := m["Scope"].(string)
  163. if s == string(datastore.GlobalScope) {
  164. aSpace.scope = datastore.GlobalScope
  165. }
  166. if v, ok := m["Subnets"]; ok {
  167. sb, _ := json.Marshal(v)
  168. var s map[string]*PoolData
  169. err := json.Unmarshal(sb, &s)
  170. if err != nil {
  171. return err
  172. }
  173. for ks, v := range s {
  174. k := SubnetKey{}
  175. k.FromString(ks)
  176. aSpace.subnets[k] = v
  177. }
  178. }
  179. return nil
  180. }
  181. // CopyTo deep copies the pool data to the destination pooldata
  182. func (p *PoolData) CopyTo(dstP *PoolData) error {
  183. dstP.ParentKey = p.ParentKey
  184. dstP.Pool = types.GetIPNetCopy(p.Pool)
  185. if p.Range != nil {
  186. dstP.Range = &AddressRange{}
  187. dstP.Range.Sub = types.GetIPNetCopy(p.Range.Sub)
  188. dstP.Range.Start = p.Range.Start
  189. dstP.Range.End = p.Range.End
  190. }
  191. dstP.RefCount = p.RefCount
  192. return nil
  193. }
  194. func (aSpace *addrSpace) CopyTo(o datastore.KVObject) error {
  195. aSpace.Lock()
  196. defer aSpace.Unlock()
  197. dstAspace := o.(*addrSpace)
  198. dstAspace.id = aSpace.id
  199. dstAspace.ds = aSpace.ds
  200. dstAspace.alloc = aSpace.alloc
  201. dstAspace.scope = aSpace.scope
  202. dstAspace.dbIndex = aSpace.dbIndex
  203. dstAspace.dbExists = aSpace.dbExists
  204. dstAspace.subnets = make(map[SubnetKey]*PoolData)
  205. for k, v := range aSpace.subnets {
  206. dstAspace.subnets[k] = &PoolData{}
  207. v.CopyTo(dstAspace.subnets[k])
  208. }
  209. return nil
  210. }
  211. func (aSpace *addrSpace) New() datastore.KVObject {
  212. aSpace.Lock()
  213. defer aSpace.Unlock()
  214. return &addrSpace{
  215. id: aSpace.id,
  216. ds: aSpace.ds,
  217. alloc: aSpace.alloc,
  218. scope: aSpace.scope,
  219. }
  220. }
  221. func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) {
  222. aSpace.Lock()
  223. defer aSpace.Unlock()
  224. // Check if already allocated
  225. if p, ok := aSpace.subnets[k]; ok {
  226. if pdf {
  227. return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw)
  228. }
  229. aSpace.incRefCount(p, 1)
  230. return func() error { return nil }, nil
  231. }
  232. // If master pool, check for overlap
  233. if ipr == nil {
  234. if aSpace.contains(k.AddressSpace, nw) {
  235. return nil, ipamapi.ErrPoolOverlap
  236. }
  237. // This is a new master pool, add it along with corresponding bitmask
  238. aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1}
  239. return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil
  240. }
  241. // This is a new non-master pool
  242. p := &PoolData{
  243. ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet},
  244. Pool: nw,
  245. Range: ipr,
  246. RefCount: 1,
  247. }
  248. aSpace.subnets[k] = p
  249. // Look for parent pool
  250. pp, ok := aSpace.subnets[p.ParentKey]
  251. if ok {
  252. aSpace.incRefCount(pp, 1)
  253. return func() error { return nil }, nil
  254. }
  255. // Parent pool does not exist, add it along with corresponding bitmask
  256. aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1}
  257. return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil
  258. }
  259. func (aSpace *addrSpace) updatePoolDBOnRemoval(k SubnetKey) (func() error, error) {
  260. aSpace.Lock()
  261. defer aSpace.Unlock()
  262. p, ok := aSpace.subnets[k]
  263. if !ok {
  264. return nil, ipamapi.ErrBadPool
  265. }
  266. aSpace.incRefCount(p, -1)
  267. c := p
  268. for ok {
  269. if c.RefCount == 0 {
  270. delete(aSpace.subnets, k)
  271. if c.Range == nil {
  272. return func() error {
  273. bm, err := aSpace.alloc.retrieveBitmask(k, c.Pool)
  274. if err != nil {
  275. return types.InternalErrorf("could not find bitmask in datastore for pool %s removal: %v", k.String(), err)
  276. }
  277. return bm.Destroy()
  278. }, nil
  279. }
  280. }
  281. k = c.ParentKey
  282. c, ok = aSpace.subnets[k]
  283. }
  284. return func() error { return nil }, nil
  285. }
  286. func (aSpace *addrSpace) incRefCount(p *PoolData, delta int) {
  287. c := p
  288. ok := true
  289. for ok {
  290. c.RefCount += delta
  291. c, ok = aSpace.subnets[c.ParentKey]
  292. }
  293. }
  294. // Checks whether the passed subnet is a superset or subset of any of the subset in this config db
  295. func (aSpace *addrSpace) contains(space string, nw *net.IPNet) bool {
  296. for k, v := range aSpace.subnets {
  297. if space == k.AddressSpace && k.ChildSubnet == "" {
  298. if nw.Contains(v.Pool.IP) || v.Pool.Contains(nw.IP) {
  299. return true
  300. }
  301. }
  302. }
  303. return false
  304. }
  305. func (aSpace *addrSpace) store() datastore.DataStore {
  306. aSpace.Lock()
  307. defer aSpace.Unlock()
  308. return aSpace.ds
  309. }