| 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 | // This is the Source Based Routing plugin that sets up source based routing. |
| 16 | package main |
| 17 | |
| 18 | import ( |
| 19 | "encoding/json" |
| 20 | "fmt" |
| 21 | "log" |
| 22 | "net" |
| 23 | |
| 24 | "github.com/alexflint/go-filemutex" |
| 25 | "github.com/vishvananda/netlink" |
| 26 | |
| 27 | "github.com/containernetworking/cni/pkg/skel" |
| 28 | "github.com/containernetworking/cni/pkg/types" |
| 29 | current "github.com/containernetworking/cni/pkg/types/100" |
| 30 | "github.com/containernetworking/cni/pkg/version" |
| 31 | "github.com/containernetworking/plugins/pkg/netlinksafe" |
| 32 | "github.com/containernetworking/plugins/pkg/ns" |
| 33 | bv "github.com/containernetworking/plugins/pkg/utils/buildversion" |
| 34 | ) |
| 35 | |
| 36 | const firstTableID = 100 |
| 37 | |
| 38 | // PluginConf is the configuration document passed in. |
| 39 | type PluginConf struct { |
| 40 | types.NetConf |
| 41 | |
| 42 | // This is the previous result, when called in the context of a chained |
| 43 | // plugin. Because this plugin supports multiple versions, we'll have to |
| 44 | // parse this in two passes. If your plugin is not chained, this can be |
| 45 | // removed (though you may wish to error if a non-chainable plugin is |
| 46 | // chained). |
| 47 | RawPrevResult *map[string]interface{} `json:"prevResult"` |
| 48 | PrevResult *current.Result `json:"-"` |
| 49 | |
| 50 | // Add plugin-specific flags here |
| 51 | Table *int `json:"table,omitempty"` |
| 52 | } |
| 53 | |
| 54 | // Wrapper that does a lock before and unlock after operations to serialise |
| 55 | // this plugin. |
| 56 | func withLockAndNetNS(nspath string, toRun func(_ ns.NetNS) error) error { |
| 57 | // We lock on the network namespace to ensure that no other instance |
| 58 | // clashes with this one. |
| 59 | log.Printf("Network namespace to use and lock: %s", nspath) |
| 60 | lock, err := filemutex.New(nspath) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | |
| 65 | err = lock.Lock() |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | |
| 70 | err = ns.WithNetNSPath(nspath, toRun) |
| 71 | if err != nil { |
| 72 | return err |
| 73 | } |
| 74 | |
| 75 | // Cleaner to unlock even though about to exit |
| 76 | err = lock.Unlock() |
| 77 | |
| 78 | return err |
| 79 | } |
| 80 | |
| 81 | // parseConfig parses the supplied configuration (and prevResult) from stdin. |
| 82 | func parseConfig(stdin []byte) (*PluginConf, error) { |
| 83 | conf := PluginConf{} |
| 84 | |
| 85 | if err := json.Unmarshal(stdin, &conf); err != nil { |
| 86 | return nil, fmt.Errorf("failed to parse network configuration: %v", err) |
| 87 | } |
| 88 | |
| 89 | // Parse previous result. |
| 90 | if conf.RawPrevResult != nil { |
| 91 | resultBytes, err := json.Marshal(conf.RawPrevResult) |
| 92 | if err != nil { |
| 93 | return nil, fmt.Errorf("could not serialize prevResult: %v", err) |
| 94 | } |
| 95 | res, err := version.NewResult(conf.CNIVersion, resultBytes) |
| 96 | if err != nil { |
| 97 | return nil, fmt.Errorf("could not parse prevResult: %v", err) |
| 98 | } |
| 99 | conf.RawPrevResult = nil |
| 100 | conf.PrevResult, err = current.NewResultFromResult(res) |
| 101 | if err != nil { |
| 102 | return nil, fmt.Errorf("could not convert result to current version: %v", err) |
| 103 | } |
| 104 | } |
| 105 | // End previous result parsing |
| 106 | |
| 107 | return &conf, nil |
| 108 | } |
| 109 | |
| 110 | // getIPCfgs finds the IPs on the supplied interface, returning as IPConfig structures |
| 111 | func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, error) { |
| 112 | if len(prevResult.IPs) == 0 { |
| 113 | // No IP addresses; that makes no sense. Pack it in. |
| 114 | return nil, fmt.Errorf("No IP addresses supplied on interface: %s", iface) |
| 115 | } |
| 116 | |
| 117 | // We do a single interface name, stored in args.IfName |
| 118 | log.Printf("Checking for relevant interface: %s", iface) |
| 119 | |
| 120 | // ips contains the IPConfig structures that were passed, filtered somewhat |
| 121 | ipCfgs := make([]*current.IPConfig, 0, len(prevResult.IPs)) |
| 122 | |
| 123 | for _, ipCfg := range prevResult.IPs { |
| 124 | // IPs have an interface that is an index into the interfaces array. |
| 125 | // We assume a match if this index is missing. |
| 126 | if ipCfg.Interface == nil { |
| 127 | log.Printf("No interface for IP address %s", ipCfg.Address.IP) |
| 128 | ipCfgs = append(ipCfgs, ipCfg) |
| 129 | continue |
| 130 | } |
| 131 | |
| 132 | // Skip all IPs we know belong to an interface with the wrong name. |
| 133 | intIdx := *ipCfg.Interface |
| 134 | if intIdx >= 0 && intIdx < len(prevResult.Interfaces) && prevResult.Interfaces[intIdx].Name != iface { |
| 135 | log.Printf("Incorrect interface for IP address %s", ipCfg.Address.IP) |
| 136 | continue |
| 137 | } |
| 138 | |
| 139 | log.Printf("Found IP address %s", ipCfg.Address.IP.String()) |
| 140 | ipCfgs = append(ipCfgs, ipCfg) |
| 141 | } |
| 142 | |
| 143 | return ipCfgs, nil |
| 144 | } |
| 145 | |
| 146 | // cmdAdd is called for ADD requests |
| 147 | func cmdAdd(args *skel.CmdArgs) error { |
| 148 | conf, err := parseConfig(args.StdinData) |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | |
| 153 | log.Printf("Configure SBR for new interface %s - previous result: %v", |
| 154 | args.IfName, conf.PrevResult) |
| 155 | |
| 156 | if conf.PrevResult == nil { |
| 157 | return fmt.Errorf("This plugin must be called as chained plugin") |
| 158 | } |
| 159 | |
| 160 | // Get the list of relevant IPs. |
| 161 | ipCfgs, err := getIPCfgs(args.IfName, conf.PrevResult) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| 165 | |
| 166 | // Do the actual work. |
| 167 | err = withLockAndNetNS(args.Netns, func(_ ns.NetNS) error { |
| 168 | if conf.Table != nil { |
| 169 | return doRoutesWithTable(ipCfgs, *conf.Table) |
| 170 | } |
| 171 | return doRoutes(ipCfgs, args.IfName) |
| 172 | }) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | |
| 177 | // Pass through the result for the next plugin |
| 178 | return types.PrintResult(conf.PrevResult, conf.CNIVersion) |
| 179 | } |
| 180 | |
| 181 | // getNextTableID picks the first free table id from a giveen candidate id |
| 182 | func getNextTableID(rules []netlink.Rule, routes []netlink.Route, candidateID int) int { |
| 183 | table := candidateID |
| 184 | for { |
| 185 | foundExisting := false |
| 186 | for _, rule := range rules { |
| 187 | if rule.Table == table { |
| 188 | foundExisting = true |
| 189 | break |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | for _, route := range routes { |
| 194 | if route.Table == table { |
| 195 | foundExisting = true |
| 196 | break |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | if foundExisting { |
| 201 | table++ |
| 202 | } else { |
| 203 | break |
| 204 | } |
| 205 | } |
| 206 | return table |
| 207 | } |
| 208 | |
| 209 | // doRoutes does all the work to set up routes and rules during an add. |
| 210 | func doRoutes(ipCfgs []*current.IPConfig, iface string) error { |
| 211 | // Get a list of rules and routes ready. |
| 212 | rules, err := netlinksafe.RuleList(netlink.FAMILY_ALL) |
| 213 | if err != nil { |
| 214 | return fmt.Errorf("Failed to list all rules: %v", err) |
| 215 | } |
| 216 | |
| 217 | routes, err := netlinksafe.RouteList(nil, netlink.FAMILY_ALL) |
| 218 | if err != nil { |
| 219 | return fmt.Errorf("Failed to list all routes: %v", err) |
| 220 | } |
| 221 | |
| 222 | // Pick a table ID to use. We pick the first table ID from firstTableID |
| 223 | // on that has no existing rules mapping to it and no existing routes in |
| 224 | // it. |
| 225 | table := getNextTableID(rules, routes, firstTableID) |
| 226 | log.Printf("First unreferenced table: %d", table) |
| 227 | |
| 228 | link, err := netlinksafe.LinkByName(iface) |
| 229 | if err != nil { |
| 230 | return fmt.Errorf("Cannot find network interface %s: %v", iface, err) |
| 231 | } |
| 232 | |
| 233 | linkIndex := link.Attrs().Index |
| 234 | |
| 235 | // Get all routes for the interface in the default routing table |
| 236 | routes, err = netlinksafe.RouteList(link, netlink.FAMILY_ALL) |
| 237 | if err != nil { |
| 238 | return fmt.Errorf("Unable to list routes: %v", err) |
| 239 | } |
| 240 | |
| 241 | // Loop through setting up source based rules and default routes. |
| 242 | for _, ipCfg := range ipCfgs { |
| 243 | log.Printf("Set rule for source %s", ipCfg.String()) |
| 244 | rule := netlink.NewRule() |
| 245 | rule.Table = table |
| 246 | |
| 247 | // Source must be restricted to a single IP, not a full subnet |
| 248 | var src net.IPNet |
| 249 | src.IP = ipCfg.Address.IP |
| 250 | if src.IP.To4() != nil { |
| 251 | src.Mask = net.CIDRMask(32, 32) |
| 252 | } else { |
| 253 | src.Mask = net.CIDRMask(128, 128) |
| 254 | } |
| 255 | |
| 256 | log.Printf("Source to use %s", src.String()) |
| 257 | rule.Src = &src |
| 258 | |
| 259 | if err = netlink.RuleAdd(rule); err != nil { |
| 260 | return fmt.Errorf("Failed to add rule: %v", err) |
| 261 | } |
| 262 | |
| 263 | // Add a default route, since this may have been removed by previous |
| 264 | // plugin. |
| 265 | if ipCfg.Gateway != nil { |
| 266 | log.Printf("Adding default route to gateway %s", ipCfg.Gateway.String()) |
| 267 | |
| 268 | var dest net.IPNet |
| 269 | if ipCfg.Address.IP.To4() != nil { |
| 270 | dest.IP = net.IPv4zero |
| 271 | dest.Mask = net.CIDRMask(0, 32) |
| 272 | } else { |
| 273 | dest.IP = net.IPv6zero |
| 274 | dest.Mask = net.CIDRMask(0, 128) |
| 275 | } |
| 276 | |
| 277 | route := netlink.Route{ |
| 278 | Dst: &dest, |
| 279 | Gw: ipCfg.Gateway, |
| 280 | Table: table, |
| 281 | LinkIndex: linkIndex, |
| 282 | } |
| 283 | |
| 284 | err = netlink.RouteAdd(&route) |
| 285 | if err != nil { |
| 286 | return fmt.Errorf("Failed to add default route to %s: %v", |
| 287 | ipCfg.Gateway.String(), |
| 288 | err) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // Copy the previously added routes for the interface to the correct |
| 293 | // table; all the routes have been added to the interface anyway but |
| 294 | // in the wrong table, so instead of removing them we just move them |
| 295 | // to the table we want them in. |
| 296 | for _, r := range routes { |
| 297 | if ipCfg.Address.Contains(r.Src) || ipCfg.Address.Contains(r.Gw) || |
| 298 | (r.Src == nil && r.Gw == nil) { |
| 299 | // (r.Src == nil && r.Gw == nil) is inferred as a generic route |
| 300 | log.Printf("Copying route %s from table %d to %d", |
| 301 | r.String(), r.Table, table) |
| 302 | |
| 303 | r.Table = table |
| 304 | |
| 305 | // Reset the route flags since if it is dynamically created, |
| 306 | // adding it to the new table will fail with "invalid argument" |
| 307 | r.Flags = 0 |
| 308 | |
| 309 | // We use route replace in case the route already exists, which |
| 310 | // is possible for the default gateway we added above. |
| 311 | err = netlink.RouteReplace(&r) |
| 312 | if err != nil { |
| 313 | return fmt.Errorf("Failed to readd route: %v", err) |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | // Use a different table for each ipCfg |
| 319 | table++ |
| 320 | table = getNextTableID(rules, routes, table) |
| 321 | } |
| 322 | |
| 323 | // Delete all the interface routes in the default routing table, which were |
| 324 | // copied to source based routing tables. |
| 325 | // Not deleting them while copying to accommodate for multiple ipCfgs from |
| 326 | // the same subnet. Else, (error for network is unreachable while adding gateway) |
| 327 | for _, route := range routes { |
| 328 | log.Printf("Deleting route %s from table %d", route.String(), route.Table) |
| 329 | err := netlink.RouteDel(&route) |
| 330 | if err != nil { |
| 331 | return fmt.Errorf("Failed to delete route: %v", err) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | return nil |
| 336 | } |
| 337 | |
| 338 | func doRoutesWithTable(ipCfgs []*current.IPConfig, table int) error { |
| 339 | for _, ipCfg := range ipCfgs { |
| 340 | log.Printf("Set rule for source %s", ipCfg.String()) |
| 341 | rule := netlink.NewRule() |
| 342 | rule.Table = table |
| 343 | |
| 344 | // Source must be restricted to a single IP, not a full subnet |
| 345 | var src net.IPNet |
| 346 | src.IP = ipCfg.Address.IP |
| 347 | if src.IP.To4() != nil { |
| 348 | src.Mask = net.CIDRMask(32, 32) |
| 349 | } else { |
| 350 | src.Mask = net.CIDRMask(128, 128) |
| 351 | } |
| 352 | |
| 353 | log.Printf("Source to use %s", src.String()) |
| 354 | rule.Src = &src |
| 355 | |
| 356 | if err := netlink.RuleAdd(rule); err != nil { |
| 357 | return fmt.Errorf("failed to add rule: %v", err) |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | return nil |
| 362 | } |
| 363 | |
| 364 | // cmdDel is called for DELETE requests |
| 365 | func cmdDel(args *skel.CmdArgs) error { |
| 366 | // We care a bit about config because it sets log level. |
| 367 | conf, err := parseConfig(args.StdinData) |
| 368 | if err != nil { |
| 369 | return err |
| 370 | } |
| 371 | |
| 372 | log.Printf("Cleaning up SBR for %s", args.IfName) |
| 373 | err = withLockAndNetNS(args.Netns, func(_ ns.NetNS) error { |
| 374 | return tidyRules(args.IfName, conf.Table) |
| 375 | }) |
| 376 | |
| 377 | return err |
| 378 | } |
| 379 | |
| 380 | // Tidy up the rules for the deleted interface |
| 381 | func tidyRules(iface string, table *int) error { |
| 382 | // We keep on going on rule deletion error, but return the last failure. |
| 383 | var errReturn error |
| 384 | var err error |
| 385 | var rules []netlink.Rule |
| 386 | |
| 387 | if table != nil { |
| 388 | rules, err = netlinksafe.RuleListFiltered( |
| 389 | netlink.FAMILY_ALL, |
| 390 | &netlink.Rule{ |
| 391 | Table: *table, |
| 392 | }, |
| 393 | netlink.RT_FILTER_TABLE, |
| 394 | ) |
| 395 | if err != nil { |
| 396 | log.Printf("Failed to list rules of table %d to tidy: %v", *table, err) |
| 397 | return fmt.Errorf("failed to list rules of table %d to tidy: %v", *table, err) |
| 398 | } |
| 399 | } else { |
| 400 | rules, err = netlinksafe.RuleList(netlink.FAMILY_ALL) |
| 401 | if err != nil { |
| 402 | log.Printf("Failed to list all rules to tidy: %v", err) |
| 403 | return fmt.Errorf("Failed to list all rules to tidy: %v", err) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | link, err := netlinksafe.LinkByName(iface) |
| 408 | if err != nil { |
| 409 | // If interface is not found by any reason it's safe to ignore an error. Also, we don't need to raise an error |
| 410 | // during cmdDel call according to CNI spec: |
| 411 | // https://github.com/containernetworking/cni/blob/main/SPEC.md#del-remove-container-from-network-or-un-apply-modifications |
| 412 | _, notFound := err.(netlink.LinkNotFoundError) |
| 413 | if notFound { |
| 414 | return nil |
| 415 | } |
| 416 | log.Printf("Failed to get link %s: %v", iface, err) |
| 417 | return fmt.Errorf("Failed to get link %s: %v", iface, err) |
| 418 | } |
| 419 | |
| 420 | addrs, err := netlinksafe.AddrList(link, netlink.FAMILY_ALL) |
| 421 | if err != nil { |
| 422 | log.Printf("Failed to list all addrs: %v", err) |
| 423 | return fmt.Errorf("Failed to list all addrs: %v", err) |
| 424 | } |
| 425 | |
| 426 | RULE_LOOP: |
| 427 | for _, rule := range rules { |
| 428 | log.Printf("Check rule: %v", rule) |
| 429 | if rule.Src == nil { |
| 430 | continue |
| 431 | } |
| 432 | |
| 433 | for _, addr := range addrs { |
| 434 | if rule.Src.IP.Equal(addr.IP) { |
| 435 | log.Printf("Delete rule %v", rule) |
| 436 | err := netlink.RuleDel(&rule) |
| 437 | if err != nil { |
| 438 | errReturn = fmt.Errorf("Failed to delete rule %v", err) |
| 439 | log.Printf("... Failed! %v", err) |
| 440 | } |
| 441 | continue RULE_LOOP |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | } |
| 446 | |
| 447 | return errReturn |
| 448 | } |
| 449 | |
| 450 | func main() { |
| 451 | skel.PluginMainFuncs(skel.CNIFuncs{ |
| 452 | Add: cmdAdd, |
| 453 | Check: cmdCheck, |
| 454 | Del: cmdDel, |
| 455 | /* FIXME GC */ |
| 456 | /* FIXME Status */ |
| 457 | }, version.All, bv.BuildString("sbr")) |
| 458 | } |
| 459 | |
| 460 | func cmdCheck(_ *skel.CmdArgs) error { |
| 461 | return nil |
| 462 | } |