├── sriov.json ├── README.md ├── LICENSE └── plugin.go /sriov.json: -------------------------------------------------------------------------------- 1 | { 2 | "Name": "sriov", 3 | "Addr": "http://127.0.0.1:9599" 4 | } 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DISCONTINUATION OF PROJECT 2 | 3 | This project will no longer be maintained by Intel. 4 | 5 | Intel has ceased development and contributions including, but not limited to, maintenance, bug fixes, new releases, or updates, to this project. 6 | 7 | Intel no longer accepts patches to this project. 8 | 9 | If you have an ongoing need to use this project, are interested in independently developing it, or would like to maintain patches for the open source software community, please create your own fork of this project. 10 | # sriov 11 | Simple standalone Docker Plugin implementation to demonstrate Clear Containers with SRIOV 12 | 13 | For more details about Clear Containers https://github.com/clearcontainers https://clearlinux.org/clear-containers 14 | 15 | This plugin supports Docker containers with runc or Clear Containers as the OCI runtime. The plugin is responsible for assigning a SRIOV Virtual Function (VF) into the container namespace. 16 | 17 | In the case of runc containers, the VF is directly usable by the container. 18 | 19 | In the case of clear containers, if clear containers detect a VF in the namespace, the runtime will unbind the VF from the host, bind it to VFIO and assign it to the clear container using PCI device pass thro. 20 | The clear container runtime which support SRIOV can be found at https://github.com/clearcontainers/runtime 21 | 22 | # How to use this plugin 23 | 24 | 25 | 0. Build this plugin. 26 | 27 | go build 28 | 29 | 1. Ensure that your plugin is discoverable https://docs.docker.com/engine/extend/plugin_api/#/plugin-discovery 30 | 31 | sudo cp sriov.json /etc/docker/plugins 32 | 33 | 34 | 2. Start the plugin 35 | 36 | sudo ./sriov & 37 | 38 | 3. Identify the network interface name of the SRIOV NIC Physical Function (PF) that is connected to the physical network of interest. 39 | 40 | 4. Try plugin with Docker runc containers 41 | 42 | #Create a virtual network on physical network b2b with vlanid 100 43 | sudo docker network create -d sriov --internal --opt pf_iface=eth0 --opt vlanid=100 vfnet 44 | 45 | #Create container on the network vfnet 46 | sudo docker run --net=vfnet -itd busybox top 47 | 48 | #Check that your containers are running 49 | sudo docker ps 50 | 51 | #Cleanup 52 | sudo docker stop $(sudo docker ps -a -q) 53 | sudo docker rm $(sudo docker ps -a -q) 54 | sudo docker network rm vfnet 55 | 56 | 4. Try plugin with Docker Clear containers 57 | For Clear Containers, the steps to create network and container are essentially the same. 58 | However, before we create Clear Container using SRIOV, host OS needs to boot with intel_iommu=on and have vfio-pci module loaded. 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /plugin.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2016 Intel Corporation 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | package main 18 | 19 | import ( 20 | "bufio" 21 | "bytes" 22 | "encoding/gob" 23 | "encoding/json" 24 | "flag" 25 | "fmt" 26 | "io/ioutil" 27 | "net" 28 | "net/http" 29 | "sync" 30 | "time" 31 | "os" 32 | "strconv" 33 | "strings" 34 | "github.com/01org/ciao/uuid" 35 | "github.com/boltdb/bolt" 36 | "github.com/docker/libnetwork/drivers/remote/api" 37 | ipamapi "github.com/docker/libnetwork/ipams/remote/api" 38 | "github.com/gorilla/mux" 39 | "github.com/golang/glog" 40 | "github.com/vishvananda/netlink" 41 | ) 42 | 43 | type epVal struct { 44 | Id string 45 | SrcName string 46 | Config vfinfo 47 | } 48 | 49 | type vfinfo struct { 50 | Bdf string 51 | Id int 52 | } 53 | 54 | type nwVal struct { 55 | Id string 56 | Config configuration 57 | } 58 | 59 | type configuration struct { 60 | Iface string 61 | Pf string 62 | Vlanid int 63 | Phys_network string 64 | } 65 | 66 | type epMap struct { 67 | sync.Mutex 68 | m map[string]*epVal 69 | } 70 | 71 | type pfMap struct { 72 | sync.Mutex 73 | m map[string][]vfinfo 74 | } 75 | type nwMap struct { 76 | sync.Mutex 77 | m map[string]*nwVal 78 | } 79 | 80 | var driver struct { 81 | networks nwMap 82 | endpoints epMap 83 | pfs pfMap 84 | } 85 | 86 | var dbFile string 87 | var db *bolt.DB 88 | 89 | const ( 90 | network_to_if_path = "/tmp/vfvlan/" 91 | sys_class_net_path = "/sys/class/net/" 92 | pci_devices_path = "/sys/bus/pci/devices/" 93 | ) 94 | 95 | func init() { 96 | driver.networks = nwMap{} 97 | driver.networks.m = make(map[string]*nwVal) 98 | 99 | driver.pfs = pfMap{} 100 | driver.pfs.m = make(map[string][]vfinfo) 101 | 102 | driver.endpoints = epMap{} 103 | driver.endpoints.m = make(map[string]*epVal) 104 | 105 | dbFile = "/tmp/sriov-bolt.db" 106 | } 107 | 108 | //We should never see any errors in this function 109 | func sendResponse(resp interface{}, w http.ResponseWriter) { 110 | rb, err := json.Marshal(resp) 111 | if err != nil { 112 | glog.Errorf("unable to marshal response %v", err) 113 | } 114 | glog.Infof("Sending response := %v, %v", resp, err) 115 | fmt.Fprintf(w, "%s", rb) 116 | return 117 | } 118 | 119 | func getBody(r *http.Request) ([]byte, error) { 120 | body, err := ioutil.ReadAll(r.Body) 121 | glog.Infof("URL [%s] Body [%s] Error [%v]", r.URL.Path[1:], string(body), err) 122 | return body, err 123 | } 124 | 125 | func handler(w http.ResponseWriter, r *http.Request) { 126 | body, _ := getBody(r) 127 | resp := api.Response{} 128 | resp.Err = "Unhandled API request " + string(r.URL.Path[1:]) + " " + string(body) 129 | sendResponse(resp, w) 130 | } 131 | 132 | func handlerPluginActivate(w http.ResponseWriter, r *http.Request) { 133 | _, _ = getBody(r) 134 | //TODO: Where is this encoding? 135 | resp := `{ 136 | "Implements": ["NetworkDriver"] 137 | }` 138 | fmt.Fprintf(w, "%s", resp) 139 | } 140 | 141 | func handlerGetCapabilities(w http.ResponseWriter, r *http.Request) { 142 | _, _ = getBody(r) 143 | resp := api.GetCapabilityResponse{Scope: "local"} 144 | sendResponse(resp, w) 145 | } 146 | 147 | func handlerCreateNetwork(w http.ResponseWriter, r *http.Request) { 148 | resp := api.CreateNetworkResponse{} 149 | 150 | body, err := getBody(r) 151 | if err != nil { 152 | resp.Err = "Error: " + err.Error() 153 | sendResponse(resp, w) 154 | return 155 | } 156 | 157 | req := api.CreateNetworkRequest{} 158 | if err := json.Unmarshal(body, &req); err != nil { 159 | resp.Err = "Error: " + err.Error() 160 | sendResponse(resp, w) 161 | return 162 | } 163 | 164 | v, ok := req.Options["com.docker.network.generic"].(map[string]interface{}) 165 | if !ok { 166 | resp.Err = "Error: network options incorrect or unspecified. Please provide bridge info" 167 | sendResponse(resp, w) 168 | return 169 | } 170 | 171 | phys_network, ok := v["phys_network"].(string) 172 | 173 | Iface, ok := v["pf_iface"].(string) 174 | 175 | if (phys_network == "") && (Iface == "") { 176 | resp.Err = "Error: network incorrect or unspecified. Please provide either name of interface connected to physical network (pf_iface) or name of physical network (phys_network)" 177 | sendResponse(resp, w) 178 | return 179 | } 180 | 181 | vlanid, ok := v["vlanid"].(string) 182 | if !ok { 183 | resp.Err = "Error: network incorrect or unspecified. Please provide vlan id for the virtual network (vlanid)" 184 | sendResponse(resp, w) 185 | return 186 | } 187 | 188 | nw := &nwVal { 189 | Id: req.NetworkID, 190 | Config: configuration{}, 191 | } 192 | 193 | nw.Config.Phys_network = phys_network 194 | nw.Config.Vlanid, _ = strconv.Atoi(vlanid) 195 | nw.Config.Iface = Iface 196 | 197 | err = SetupInterface(nw) 198 | 199 | if err != nil { 200 | resp.Err = err.Error() 201 | sendResponse(resp, w) 202 | return 203 | } 204 | 205 | 206 | driver.networks.Lock() 207 | defer driver.networks.Unlock() 208 | 209 | //Record the docker network UUID to SDN bridge mapping 210 | //This has to survive a plugin crash/restart and needs to be persisted 211 | driver.networks.m[req.NetworkID] = nw 212 | 213 | if err := dbAdd("nwMap", req.NetworkID, driver.networks.m[req.NetworkID]); err != nil { 214 | glog.Errorf("Unable to update db %v", err) 215 | } 216 | 217 | sendResponse(resp, w) 218 | } 219 | 220 | func SetupInterface (nw *nwVal) error { 221 | if nw.Config.Phys_network != "" { 222 | 223 | map_path := network_to_if_path + nw.Config.Phys_network 224 | glog.Infof("vfvlan - map path: %s", map_path) 225 | 226 | map_file, err := os.Open(map_path) 227 | if err != nil { 228 | glog.Errorf("vfvlan - Unable to open the opening physical network to iface mapping file %s", nw.Config.Phys_network) 229 | return fmt.Errorf("Error with mapping physical network to SR-IOv PF") 230 | } 231 | 232 | scanner := bufio.NewScanner(map_file) 233 | scanner.Scan() 234 | nw.Config.Iface = scanner.Text() 235 | glog.Infof("vfvlan - interface used for network %s - %s", nw.Id, nw.Config.Iface) 236 | } 237 | 238 | if_device_path := sys_class_net_path + nw.Config.Iface + "/" + "device" 239 | glog.Infof("vfvlan - iface device path for network %s - %s", nw.Id, if_device_path) 240 | 241 | device_info, err := os.Readlink(if_device_path) 242 | if err != nil { 243 | glog.Errorf("vfvlan - Unable to open the device path for iface %s", nw.Config.Iface) 244 | return fmt.Errorf("Error with mapping physical network to SR-IOv PF") 245 | } 246 | 247 | substrings := strings.SplitN(device_info, "/", 4) 248 | device_bdf := substrings[3] 249 | 250 | nw.Config.Pf = device_bdf 251 | glog.Infof("vfvlan - iface b.d.f for networks %s - %s", nw.Id, nw.Config.Pf) 252 | 253 | driver.pfs.Lock() 254 | 255 | _, ok := driver.pfs.m[nw.Config.Pf] 256 | if (ok) { 257 | glog.Infof("vfvlan - SR-IOv interface for network %s is already initialized", nw.Id) 258 | driver.pfs.Unlock() 259 | return nil 260 | } else { 261 | driver.pfs.m[nw.Config.Pf] = make([]vfinfo, 0) 262 | } 263 | 264 | err = initialize_pf(nw.Config.Pf) 265 | driver.pfs.Unlock() 266 | 267 | if err != nil { 268 | return fmt.Errorf("Error with initializing the underlying SR-IOv PF") 269 | } 270 | return nil 271 | } 272 | 273 | func initialize_pf (pf string) error { 274 | var totalvfs_path, numvfs_path, totalvfs string 275 | 276 | device_path := pci_devices_path + pf 277 | 278 | totalvfs_path = device_path + "/" + "sriov_totalvfs" 279 | totalvfs_file, err := os.Open(totalvfs_path) 280 | 281 | if err != nil { 282 | glog.Errorf("Error opening the totalvfs filr on the PF"); 283 | return err 284 | } 285 | 286 | totalvfs_scanner := bufio.NewScanner(totalvfs_file) 287 | totalvfs_scanner.Scan() 288 | totalvfs = totalvfs_scanner.Text() 289 | 290 | numvfs_path = device_path + "/" + "sriov_numvfs" 291 | numvfs_file, err := os.Open(numvfs_path) 292 | 293 | numvfs_scanner := bufio.NewScanner(numvfs_file) 294 | numvfs_scanner.Scan() 295 | numvfs := numvfs_scanner.Text() 296 | 297 | if strings.EqualFold (totalvfs, numvfs) == false { 298 | glog.Errorf("Numvfs and Totalvfs are not same on the PF - Initialize numvfs to totalvfs") 299 | // return fmt.Errorf("Error with initializing the underlying SR-IOv PF") 300 | } 301 | 302 | device_info, err := os.Open(device_path) 303 | device_info_files, err := device_info.Readdir(0) 304 | if err == nil { 305 | for _, value := range device_info_files { 306 | if strings.Contains(value.Name(), "virtfn") { 307 | link, _ := os.Readlink(device_path + "/" + value.Name()) 308 | substrings := strings.SplitN(link, "/", 2) 309 | device_bdf := substrings[1] 310 | vf_id_str := strings.TrimPrefix(value.Name(), "virtfn") 311 | vf_id, _ := strconv.Atoi(vf_id_str) 312 | vf_info := vfinfo{ 313 | Bdf: device_bdf, 314 | Id: vf_id, 315 | } 316 | driver.pfs.m[pf] = append(driver.pfs.m[pf], vf_info) 317 | glog.Infof("vfvlan" + device_bdf) 318 | } 319 | } 320 | } 321 | return nil 322 | 323 | } 324 | 325 | func handlerDeleteNetwork(w http.ResponseWriter, r *http.Request) { 326 | resp := api.DeleteNetworkResponse{} 327 | 328 | body, err := getBody(r) 329 | if err != nil { 330 | resp.Err = "Error: " + err.Error() 331 | sendResponse(resp, w) 332 | return 333 | } 334 | 335 | req := api.DeleteNetworkRequest{} 336 | if err = json.Unmarshal(body, &req); err != nil { 337 | resp.Err = "Error: " + err.Error() 338 | sendResponse(resp, w) 339 | return 340 | } 341 | 342 | glog.Infof("Delete Network := %v", req.NetworkID) 343 | 344 | //This would have already been done in the SDN controller 345 | //Remove the UUID to bridge mapping in cache and in the 346 | //persistent data store 347 | driver.networks.Lock() 348 | delete(driver.networks.m, req.NetworkID) 349 | if err := dbDelete("nwMap", req.NetworkID); err != nil { 350 | glog.Errorf("Unable to update db %v", err) 351 | } 352 | driver.networks.Unlock() 353 | 354 | sendResponse(resp, w) 355 | return 356 | } 357 | 358 | func handlerEndpointOperInfof(w http.ResponseWriter, r *http.Request) { 359 | resp := api.EndpointInfoResponse{} 360 | body, err := getBody(r) 361 | 362 | if err != nil { 363 | resp.Err = "Error: " + err.Error() 364 | sendResponse(resp, w) 365 | return 366 | } 367 | 368 | req := api.EndpointInfoRequest{} 369 | err = json.Unmarshal(body, &req) 370 | 371 | if err != nil { 372 | resp.Err = "Error: " + err.Error() 373 | sendResponse(resp, w) 374 | return 375 | } 376 | 377 | sendResponse(resp, w) 378 | } 379 | 380 | func handlerCreateEndpoint(w http.ResponseWriter, r *http.Request) { 381 | resp := api.CreateEndpointResponse{} 382 | 383 | body, err := getBody(r) 384 | if err != nil { 385 | resp.Err = "Error: " + err.Error() 386 | sendResponse(resp, w) 387 | return 388 | } 389 | 390 | req := api.CreateEndpointRequest{} 391 | if err = json.Unmarshal(body, &req); err != nil { 392 | resp.Err = "Error: " + err.Error() 393 | sendResponse(resp, w) 394 | return 395 | } 396 | 397 | if req.Interface.Address == "" { 398 | resp.Err = "Error: IP Address parameter not provided in docker run" 399 | sendResponse(resp, w) 400 | return 401 | } 402 | 403 | ip, _, err := net.ParseCIDR(req.Interface.Address) 404 | if err != nil { 405 | resp.Err = "Error: Invalid IP Address " + err.Error() 406 | sendResponse(resp, w) 407 | return 408 | } 409 | 410 | glog.Infof("IP from the docker default IPAM [%v]", ip.String()) 411 | 412 | driver.networks.Lock() 413 | nw := driver.networks.m[req.NetworkID] 414 | driver.networks.Unlock() 415 | 416 | pf := nw.Config.Pf 417 | 418 | driver.endpoints.Lock() 419 | defer driver.endpoints.Unlock() 420 | 421 | driver.pfs.Lock() 422 | defer driver.pfs.Unlock() 423 | 424 | ep := &epVal { 425 | Id: req.EndpointID, 426 | } 427 | 428 | glog.Infof("vfvlan - CreateEndpoint number of VFs available %d", len(driver.pfs.m[pf])) 429 | 430 | if len(driver.pfs.m[pf]) == 0 { 431 | glog.Infof("All the vfs on this interface are currently in use"); 432 | resp.Err = fmt.Sprintf("No VFs are available on the SR-IOv PF") 433 | sendResponse(resp, w) 434 | return 435 | } else { 436 | ep.Config = driver.pfs.m[pf][0] 437 | driver.pfs.m[pf] = driver.pfs.m[pf][1:] 438 | } 439 | 440 | driver.endpoints.m[req.EndpointID] = ep 441 | 442 | if err := dbAdd("epMap", req.EndpointID, driver.endpoints.m[req.EndpointID]); err != nil { 443 | glog.Errorf("Unable to update db %v", err) 444 | } 445 | 446 | sendResponse(resp, w) 447 | } 448 | 449 | func handlerDeleteEndpoint(w http.ResponseWriter, r *http.Request) { 450 | resp := api.DeleteEndpointResponse{} 451 | 452 | body, err := getBody(r) 453 | if err != nil { 454 | resp.Err = "Error: " + err.Error() 455 | sendResponse(resp, w) 456 | return 457 | } 458 | 459 | req := api.DeleteEndpointRequest{} 460 | if err = json.Unmarshal(body, &req); err != nil { 461 | resp.Err = "Error: " + err.Error() 462 | sendResponse(resp, w) 463 | return 464 | } 465 | 466 | driver.endpoints.Lock() 467 | driver.pfs.Lock() 468 | nw := driver.networks.m[req.NetworkID] 469 | pf := nw.Config.Pf 470 | 471 | ep := driver.endpoints.m[req.EndpointID] 472 | driver.pfs.m[pf] = append(driver.pfs.m[pf], ep.Config) 473 | 474 | pf_link, _ := netlink.LinkByName(nw.Config.Iface) 475 | err = netlink.LinkSetVfVlan(pf_link, ep.Config.Id, 0) 476 | 477 | glog.Infof("vfvlan - DeleteEndpoint number of VFs available %d", len(driver.pfs.m[pf])) 478 | delete(driver.endpoints.m, req.EndpointID) 479 | if err := dbDelete("epMap", req.EndpointID); err != nil { 480 | glog.Errorf("Unable to update db %v", err) 481 | } 482 | driver.endpoints.Unlock() 483 | driver.pfs.Unlock() 484 | //Figure out how to a vpp tap delete 485 | 486 | sendResponse(resp, w) 487 | } 488 | 489 | func handlerJoin(w http.ResponseWriter, r *http.Request) { 490 | resp := api.JoinResponse{} 491 | 492 | body, err := getBody(r) 493 | if err != nil { 494 | resp.Err = "Error: " + err.Error() 495 | sendResponse(resp, w) 496 | return 497 | } 498 | 499 | req := api.JoinRequest{} 500 | if err := json.Unmarshal(body, &req); err != nil { 501 | resp.Err = "Error: " + err.Error() 502 | sendResponse(resp, w) 503 | return 504 | } 505 | 506 | driver.networks.Lock() 507 | driver.endpoints.Lock() 508 | 509 | nw := driver.networks.m[req.NetworkID] 510 | em := driver.endpoints.m[req.EndpointID] 511 | 512 | driver.networks.Unlock() 513 | driver.endpoints.Unlock() 514 | 515 | pf_link, _ := netlink.LinkByName(nw.Config.Iface) 516 | err = netlink.LinkSetVfVlan(pf_link, em.Config.Id, nw.Config.Vlanid) 517 | 518 | vf_path := pci_devices_path + em.Config.Bdf 519 | vf_iface := vf_path + "/net" 520 | iface_info, _ := os.Open(vf_iface) 521 | iface_info_dir, err := iface_info.Readdir(0) 522 | if err == nil { 523 | for _, value := range iface_info_dir { 524 | em.SrcName = value.Name() 525 | glog.Infof("vfvlan - ep srcname %s", em.SrcName) 526 | } 527 | } 528 | 529 | resp.InterfaceName = &api.InterfaceName{ 530 | SrcName: em.SrcName, 531 | DstPrefix: "eth", 532 | } 533 | glog.Infof("Join Response %v", resp) 534 | sendResponse(resp, w) 535 | } 536 | 537 | func handlerLeave(w http.ResponseWriter, r *http.Request) { 538 | resp := api.LeaveResponse{} 539 | 540 | body, err := getBody(r) 541 | if err != nil { 542 | resp.Err = "Error: " + err.Error() 543 | sendResponse(resp, w) 544 | return 545 | } 546 | 547 | req := api.LeaveRequest{} 548 | if err := json.Unmarshal(body, &req); err != nil { 549 | resp.Err = "Error: " + err.Error() 550 | sendResponse(resp, w) 551 | return 552 | } 553 | 554 | sendResponse(resp, w) 555 | } 556 | 557 | func handlerDiscoverNew(w http.ResponseWriter, r *http.Request) { 558 | resp := api.DiscoveryResponse{} 559 | 560 | body, err := getBody(r) 561 | if err != nil { 562 | resp.Err = "Error: " + err.Error() 563 | sendResponse(resp, w) 564 | return 565 | } 566 | 567 | req := api.DiscoveryNotification{} 568 | if err := json.Unmarshal(body, &req); err != nil { 569 | resp.Err = "Error: " + err.Error() 570 | sendResponse(resp, w) 571 | return 572 | } 573 | 574 | sendResponse(resp, w) 575 | } 576 | 577 | func handlerDiscoverDelete(w http.ResponseWriter, r *http.Request) { 578 | resp := api.DiscoveryResponse{} 579 | 580 | body, err := getBody(r) 581 | if err != nil { 582 | resp.Err = "Error: " + err.Error() 583 | sendResponse(resp, w) 584 | return 585 | } 586 | 587 | req := api.DiscoveryNotification{} 588 | if err := json.Unmarshal(body, &req); err != nil { 589 | resp.Err = "Error: " + err.Error() 590 | sendResponse(resp, w) 591 | return 592 | } 593 | 594 | sendResponse(resp, w) 595 | } 596 | 597 | func handlerExternalConnectivity(w http.ResponseWriter, r *http.Request) { 598 | resp := api.ProgramExternalConnectivityResponse{} 599 | 600 | body, err := getBody(r) 601 | if err != nil { 602 | resp.Err = "Error: " + err.Error() 603 | sendResponse(resp, w) 604 | return 605 | } 606 | 607 | req := api.ProgramExternalConnectivityRequest{} 608 | if err := json.Unmarshal(body, &req); err != nil { 609 | resp.Err = "Error: " + err.Error() 610 | sendResponse(resp, w) 611 | return 612 | } 613 | 614 | sendResponse(resp, w) 615 | } 616 | 617 | func handlerRevokeExternalConnectivity(w http.ResponseWriter, r *http.Request) { 618 | resp := api.RevokeExternalConnectivityResponse{} 619 | 620 | body, err := getBody(r) 621 | if err != nil { 622 | resp.Err = "Error: " + err.Error() 623 | sendResponse(resp, w) 624 | return 625 | } 626 | 627 | req := api.RevokeExternalConnectivityResponse{} 628 | if err := json.Unmarshal(body, &req); err != nil { 629 | resp.Err = "Error: " + err.Error() 630 | sendResponse(resp, w) 631 | return 632 | } 633 | 634 | sendResponse(resp, w) 635 | } 636 | 637 | func ipamGetCapabilities(w http.ResponseWriter, r *http.Request) { 638 | if _, err := getBody(r); err != nil { 639 | glog.Infof("ipamGetCapabilities: unable to get request body [%v]", err) 640 | } 641 | resp := ipamapi.GetCapabilityResponse{RequiresMACAddress: true} 642 | sendResponse(resp, w) 643 | } 644 | 645 | func ipamGetDefaultAddressSpaces(w http.ResponseWriter, r *http.Request) { 646 | resp := ipamapi.GetAddressSpacesResponse{} 647 | if _, err := getBody(r); err != nil { 648 | glog.Infof("ipamGetDefaultAddressSpaces: unable to get request body [%v]", err) 649 | } 650 | 651 | resp.GlobalDefaultAddressSpace = "" 652 | resp.LocalDefaultAddressSpace = "" 653 | sendResponse(resp, w) 654 | } 655 | 656 | func ipamRequestPool(w http.ResponseWriter, r *http.Request) { 657 | resp := ipamapi.RequestPoolResponse{} 658 | 659 | body, err := getBody(r) 660 | if err != nil { 661 | resp.Error = "Error: " + err.Error() 662 | sendResponse(resp, w) 663 | return 664 | } 665 | 666 | req := ipamapi.RequestPoolRequest{} 667 | if err := json.Unmarshal(body, &req); err != nil { 668 | resp.Error = "Error: " + err.Error() 669 | sendResponse(resp, w) 670 | return 671 | } 672 | 673 | resp.PoolID = uuid.Generate().String() 674 | resp.Pool = req.Pool 675 | sendResponse(resp, w) 676 | } 677 | 678 | func ipamReleasePool(w http.ResponseWriter, r *http.Request) { 679 | resp := ipamapi.ReleasePoolResponse{} 680 | 681 | body, err := getBody(r) 682 | if err != nil { 683 | resp.Error = "Error: " + err.Error() 684 | sendResponse(resp, w) 685 | return 686 | } 687 | 688 | req := ipamapi.ReleasePoolRequest{} 689 | if err := json.Unmarshal(body, &req); err != nil { 690 | resp.Error = "Error: " + err.Error() 691 | sendResponse(resp, w) 692 | return 693 | } 694 | 695 | sendResponse(resp, w) 696 | } 697 | 698 | func ipamRequestAddress(w http.ResponseWriter, r *http.Request) { 699 | resp := ipamapi.RequestAddressResponse{} 700 | 701 | body, err := getBody(r) 702 | if err != nil { 703 | resp.Error = "Error: " + err.Error() 704 | sendResponse(resp, w) 705 | return 706 | } 707 | 708 | req := ipamapi.RequestAddressRequest{} 709 | if err := json.Unmarshal(body, &req); err != nil { 710 | resp.Error = "Error: " + err.Error() 711 | sendResponse(resp, w) 712 | return 713 | } 714 | 715 | //TODO: Should come from the subnet mask for the subnet 716 | if req.Address != "" { 717 | resp.Address = req.Address + "/24" 718 | } else { 719 | resp.Error = "Error: Request does not have IP address. Specify using --ip" 720 | } 721 | sendResponse(resp, w) 722 | } 723 | 724 | func ipamReleaseAddress(w http.ResponseWriter, r *http.Request) { 725 | resp := ipamapi.ReleaseAddressResponse{} 726 | 727 | body, err := getBody(r) 728 | if err != nil { 729 | resp.Error = "Error: " + err.Error() 730 | sendResponse(resp, w) 731 | return 732 | } 733 | 734 | req := ipamapi.ReleaseAddressRequest{} 735 | if err := json.Unmarshal(body, &req); err != nil { 736 | resp.Error = "Error: " + err.Error() 737 | sendResponse(resp, w) 738 | return 739 | } 740 | 741 | sendResponse(resp, w) 742 | } 743 | 744 | func dbTableInit(tables []string) (err error) { 745 | 746 | glog.Infof("dbInit Tables := %v", tables) 747 | for i, v := range tables { 748 | glog.Infof("table[%v] := %v, %v", i, v, []byte(v)) 749 | } 750 | 751 | err = db.Update(func(tx *bolt.Tx) error { 752 | for _, table := range tables { 753 | _, err := tx.CreateBucketIfNotExists([]byte(table)) 754 | if err != nil { 755 | return fmt.Errorf("Bucket creation error: %v %v", table, err) 756 | } 757 | } 758 | return nil 759 | }) 760 | 761 | if err != nil { 762 | glog.Errorf("Table creation error %v", err) 763 | } 764 | 765 | return err 766 | } 767 | 768 | func dbAdd(table string, key string, value interface{}) (err error) { 769 | 770 | err = db.Update(func(tx *bolt.Tx) error { 771 | var v bytes.Buffer 772 | 773 | if err := gob.NewEncoder(&v).Encode(value); err != nil { 774 | glog.Errorf("Encode Error: %v %v", err, value) 775 | return err 776 | } 777 | 778 | bucket := tx.Bucket([]byte(table)) 779 | if bucket == nil { 780 | return fmt.Errorf("Bucket %v not found", table) 781 | } 782 | 783 | err = bucket.Put([]byte(key), v.Bytes()) 784 | if err != nil { 785 | return fmt.Errorf("Key Store error: %v %v %v %v", table, key, value, err) 786 | } 787 | return nil 788 | }) 789 | 790 | return err 791 | } 792 | 793 | func dbDelete(table string, key string) (err error) { 794 | 795 | err = db.Update(func(tx *bolt.Tx) error { 796 | 797 | bucket := tx.Bucket([]byte(table)) 798 | if bucket == nil { 799 | return fmt.Errorf("Bucket %v not found", table) 800 | } 801 | 802 | err = bucket.Delete([]byte(key)) 803 | if err != nil { 804 | return fmt.Errorf("Key Delete error: %v %v ", key, err) 805 | } 806 | return nil 807 | }) 808 | 809 | return err 810 | } 811 | 812 | func dbGet(table string, key string) (value interface{}, err error) { 813 | 814 | err = db.View(func(tx *bolt.Tx) error { 815 | 816 | bucket := tx.Bucket([]byte(table)) 817 | if bucket == nil { 818 | return fmt.Errorf("Bucket %v not found", table) 819 | } 820 | 821 | val := bucket.Get([]byte(key)) 822 | if val == nil { 823 | return nil 824 | } 825 | 826 | v := bytes.NewReader(val) 827 | if err := gob.NewDecoder(v).Decode(value); err != nil { 828 | glog.Errorf("Decode Error: %v %v %v", table, key, err) 829 | return err 830 | } 831 | 832 | return nil 833 | }) 834 | 835 | return value, err 836 | } 837 | 838 | func initDb() error { 839 | 840 | options := bolt.Options{ 841 | Timeout: 3 * time.Second, 842 | } 843 | 844 | var err error 845 | db, err = bolt.Open(dbFile, 0644, &options) 846 | if err != nil { 847 | return fmt.Errorf("dbInit failed %v", err) 848 | } 849 | 850 | tables := []string{"global", "nwMap", "epMap"} 851 | if err := dbTableInit(tables); err != nil { 852 | return fmt.Errorf("dbInit failed %v", err) 853 | } 854 | 855 | err = db.View(func(tx *bolt.Tx) error { 856 | b := tx.Bucket([]byte("nwMap")) 857 | 858 | err := b.ForEach(func(k, v []byte) error { 859 | vr := bytes.NewReader(v) 860 | nVal := &nwVal{} 861 | if err := gob.NewDecoder(vr).Decode(nVal); err != nil { 862 | return fmt.Errorf("Decode Error: %v %v %v", string(k), string(v), err) 863 | } 864 | driver.networks.m[string(k)] = nVal 865 | glog.Infof("nwMap key=%v, value=%v\n", string(k), nVal) 866 | return nil 867 | }) 868 | return err 869 | }) 870 | 871 | if err != nil { 872 | return err 873 | } 874 | 875 | err = db.View(func(tx *bolt.Tx) error { 876 | b := tx.Bucket([]byte("epMap")) 877 | 878 | err := b.ForEach(func(k, v []byte) error { 879 | vr := bytes.NewReader(v) 880 | eVal := &epVal{} 881 | if err := gob.NewDecoder(vr).Decode(eVal); err != nil { 882 | return fmt.Errorf("Decode Error: %v %v %v", string(k), string(v), err) 883 | } 884 | driver.endpoints.m[string(k)] = eVal 885 | glog.Infof("epMap key=%v, value=%v\n", string(k), eVal) 886 | return nil 887 | }) 888 | return err 889 | }) 890 | 891 | return err 892 | } 893 | 894 | func main() { 895 | flag.Parse() 896 | 897 | if err := initDb(); err != nil { 898 | glog.Fatalf("db init failed, quitting [%v]", err) 899 | } 900 | defer func() { 901 | err := db.Close() 902 | glog.Errorf("unable to close database [%v]", err) 903 | }() 904 | 905 | r := mux.NewRouter() 906 | r.HandleFunc("/Plugin.Activate", handlerPluginActivate) 907 | r.HandleFunc("/NetworkDriver.GetCapabilities", handlerGetCapabilities) 908 | r.HandleFunc("/NetworkDriver.CreateNetwork", handlerCreateNetwork) 909 | r.HandleFunc("/NetworkDriver.DeleteNetwork", handlerDeleteNetwork) 910 | r.HandleFunc("/NetworkDriver.CreateEndpoint", handlerCreateEndpoint) 911 | r.HandleFunc("/NetworkDriver.DeleteEndpoint", handlerDeleteEndpoint) 912 | r.HandleFunc("/NetworkDriver.EndpointOperInfo", handlerEndpointOperInfof) 913 | r.HandleFunc("/NetworkDriver.Join", handlerJoin) 914 | r.HandleFunc("/NetworkDriver.Leave", handlerLeave) 915 | r.HandleFunc("/NetworkDriver.DiscoverNew", handlerDiscoverNew) 916 | r.HandleFunc("/NetworkDriver.DiscoverDelete", handlerDiscoverDelete) 917 | r.HandleFunc("/NetworkDriver.ProgramExternalConnectivity", handlerExternalConnectivity) 918 | r.HandleFunc("/NetworkDriver.RevokeExternalConnectivity", handlerRevokeExternalConnectivity) 919 | 920 | 921 | r.HandleFunc("/", handler) 922 | err := http.ListenAndServe("127.0.0.1:9599", r) 923 | if err != nil { 924 | glog.Errorf("docker plugin http server failed, [%v]", err) 925 | } 926 | } 927 | --------------------------------------------------------------------------------