Debian Codegraph @

plugins/ipam/host-local/backend/allocator/range_set.go

raw symbols SCIP
1 // Copyright 2017 CNI authors
2 //
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 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package allocator
16
17 import (
18 "fmt"
19 "net"
20 "strings"
21 )
22
23 // Contains returns true if any range in this set contains an IP
24 func (s *RangeSet) Contains(addr net.IP) bool {
25 r, _ := s.RangeFor(addr)
26 return r != nil
27 }
28
29 // RangeFor finds the range that contains an IP, or nil if not found
30 func (s *RangeSet) RangeFor(addr net.IP) (*Range, error) {
31 if err := canonicalizeIP(&addr); err != nil {
32 return nil, err
33 }
34
35 for _, r := range *s {
36 if r.Contains(addr) {
37 return &r, nil
38 }
39 }
40
41 return nil, fmt.Errorf("%s not in range set %s", addr.String(), s.String())
42 }
43
44 // Overlaps returns true if any ranges in any set overlap with this one
45 func (s *RangeSet) Overlaps(p1 *RangeSet) bool {
46 for _, r := range *s {
47 for _, r1 := range *p1 {
48 if r.Overlaps(&r1) {
49 return true
50 }
51 }
52 }
53 return false
54 }
55
56 // Canonicalize ensures the RangeSet is in a standard form, and detects any
57 // invalid input. Call Range.Canonicalize() on every Range in the set
58 func (s *RangeSet) Canonicalize() error {
59 if len(*s) == 0 {
60 return fmt.Errorf("empty range set")
61 }
62
63 fam := 0
64 for i := range *s {
65 if err := (*s)[i].Canonicalize(); err != nil {
66 return err
67 }
68 if i == 0 {
69 fam = len((*s)[i].RangeStart)
70 } else if fam != len((*s)[i].RangeStart) {
71 return fmt.Errorf("mixed address families")
72 }
73 }
74
75 // Make sure none of the ranges in the set overlap
76 l := len(*s)
77 for i, r1 := range (*s)[:l-1] {
78 for _, r2 := range (*s)[i+1:] {
79 if r1.Overlaps(&r2) {
80 return fmt.Errorf("subnets %s and %s overlap", r1.String(), r2.String())
81 }
82 }
83 }
84
85 return nil
86 }
87
88 func (s *RangeSet) String() string {
89 out := []string{}
90 for _, r := range *s {
91 out = append(out, r.String())
92 }
93
94 return strings.Join(out, ",")
95 }