├── .github └── workflows │ ├── docker.yml │ ├── golint.yml │ └── reuse.yml ├── .gitignore ├── .golangci.yml ├── .reuse └── dep5 ├── Dockerfile ├── LICENSES ├── Apache-2.0.txt └── GPL-2.0-only.txt ├── Makefile ├── README.md ├── bpf ├── common.h ├── flags.h └── int-datapath.c ├── cmd └── int-host-reporter │ └── main.go ├── configs └── watchlist.yaml ├── deployment ├── ci │ ├── Makefile │ ├── README.md │ ├── Vagrantfile │ ├── inventory.ini │ ├── playbook.deletecluster.yml │ ├── playbook.kubecluster.yml │ ├── provision-tester.sh │ ├── provision.sh │ ├── requirements.txt │ └── roles │ │ ├── docker │ │ └── tasks │ │ │ └── main.yml │ │ ├── join │ │ ├── tasks │ │ │ └── main.yml │ │ └── templates │ │ │ └── kubelet.j2 │ │ ├── kube │ │ └── tasks │ │ │ └── main.yml │ │ ├── kubeconfig │ │ └── tasks │ │ │ └── main.yml │ │ ├── kubectl │ │ └── tasks │ │ │ └── main.yml │ │ ├── master │ │ └── tasks │ │ │ └── main.yml │ │ └── teardown │ │ └── tasks │ │ └── main.yml ├── helm │ └── int-host-reporter │ │ ├── .helmignore │ │ ├── Chart.yaml │ │ ├── templates │ │ ├── configmap-watchlist.yaml │ │ └── daemonset.yaml │ │ └── values.yaml └── kubernetes │ └── inthostreporter.yaml ├── docs └── static │ └── images │ ├── design.png │ └── di-topo.png ├── examples └── deepinsight │ └── topo.json ├── go.mod ├── go.sum ├── pkg ├── common │ ├── contants.go │ ├── globals.go │ └── helpers.go ├── dataplane │ ├── dataplane_event.go │ └── dataplane_interface.go ├── inthostreporter │ ├── handler.go │ └── reporter.go ├── loader │ └── compile.go ├── packet │ └── int_report.go ├── service │ ├── service.go │ └── topology.go ├── system │ └── netsys.go └── watchlist │ └── watchlist.go └── scripts └── compile-bpf.sh /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | --- 5 | name: Docker Build and Push 6 | 7 | on: 8 | push: 9 | branches: [ main ] 10 | pull_request: 11 | branches: [ main ] 12 | 13 | jobs: 14 | build-and-push: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Build the Docker images 19 | run: make build 20 | - name: Login to DockerHub 21 | run: docker login --username ${{ secrets.DOCKERHUB_USERNAME }} --password ${{ secrets.DOCKERHUB_PASSWORD }} 22 | if: github.ref == 'refs/heads/main' 23 | - name: Push image to DockerHub 24 | run: docker push opennetworking/int-host-reporter:latest 25 | if: github.ref == 'refs/heads/main' -------------------------------------------------------------------------------- /.github/workflows/golint.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | --- 5 | name: golint 6 | 7 | on: 8 | push: 9 | branches: 10 | pull_request: 11 | branches: [master, main] 12 | 13 | jobs: 14 | golangci-lint: 15 | name: Golangci-lint 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Set up Go 1.16 19 | uses: actions/setup-go@v2 20 | with: 21 | go-version: 1.16 22 | - name: Check-out code 23 | uses: actions/checkout@v2 24 | - name: Run golangci-lint 25 | run: make golint 26 | -------------------------------------------------------------------------------- /.github/workflows/reuse.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | --- 5 | name: REUSE 6 | 7 | on: 8 | push: 9 | branches: [master, main] 10 | pull_request: 11 | branches: [master, main] 12 | 13 | jobs: 14 | license-check: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: reuse lint 19 | uses: fsfe/reuse-action@v1 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | .idea/ 4 | .golangci-bin/ -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # golangci-lint configuration used for CI 5 | run: 6 | tests: true 7 | timeout: 10m 8 | 9 | linters: 10 | disable-all: true 11 | enable: 12 | - misspell 13 | - gofmt 14 | - deadcode 15 | - staticcheck 16 | - gosec 17 | - vet 18 | - revive -------------------------------------------------------------------------------- /.reuse/dep5: -------------------------------------------------------------------------------- 1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: int-host-reporter 3 | Upstream-Contact: Tomasz Osiński 4 | Source: https://github.com/opennetworkinglab/int-host-reporter 5 | 6 | Files: go.mod go.sum 7 | Copyright: 2021-present Open Networking Foundation 8 | License: Apache-2.0 9 | 10 | Files: docs/static/images/*.png 11 | Copyright: 2021-present Open Networking Foundation 12 | License: Apache-2.0 13 | 14 | Files: examples/deepinsight/topo.json 15 | Copyright: 2021-present Open Networking Foundation 16 | License: Apache-2.0 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | FROM golang:1.16 as builder 5 | 6 | WORKDIR /go/src/app 7 | COPY . . 8 | 9 | RUN go get -d -v ./... 10 | RUN go install -v ./... 11 | 12 | FROM ubuntu:20.10 13 | COPY --from=builder /go/src/app . 14 | COPY --from=builder /go/bin/int-host-reporter /usr/local/bin 15 | 16 | RUN apt update 17 | RUN apt install -y iproute2 clang-10 libbpf-dev llvm-10 gcc-multilib 18 | 19 | CMD ["int-host-reporter"] -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 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} Authors of Cilium 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 | -------------------------------------------------------------------------------- /LICENSES/GPL-2.0-only.txt: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 2, June 1991 4 | 5 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 6 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 12 | The licenses for most software are designed to take away your 13 | freedom to share and change it. By contrast, the GNU General Public 14 | License is intended to guarantee your freedom to share and change free 15 | software--to make sure the software is free for all its users. This 16 | General Public License applies to most of the Free Software 17 | Foundation's software and to any other program whose authors commit to 18 | using it. (Some other Free Software Foundation software is covered by 19 | the GNU Library General Public License instead.) You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | this service if you wish), that you receive source code or can get it 26 | if you want it, that you can change the software or use pieces of it 27 | in new free programs; and that you know you can do these things. 28 | 29 | To protect your rights, we need to make restrictions that forbid 30 | anyone to deny you these rights or to ask you to surrender the rights. 31 | These restrictions translate to certain responsibilities for you if you 32 | distribute copies of the software, or if you modify it. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must give the recipients all the rights that 36 | you have. You must make sure that they, too, receive or can get the 37 | source code. And you must show them these terms so they know their 38 | rights. 39 | 40 | We protect your rights with two steps: (1) copyright the software, and 41 | (2) offer you this license which gives you legal permission to copy, 42 | distribute and/or modify the software. 43 | 44 | Also, for each author's protection and ours, we want to make certain 45 | that everyone understands that there is no warranty for this free 46 | software. If the software is modified by someone else and passed on, we 47 | want its recipients to know that what they have is not the original, so 48 | that any problems introduced by others will not reflect on the original 49 | authors' reputations. 50 | 51 | Finally, any free program is threatened constantly by software 52 | patents. We wish to avoid the danger that redistributors of a free 53 | program will individually obtain patent licenses, in effect making the 54 | program proprietary. To prevent this, we have made it clear that any 55 | patent must be licensed for everyone's free use or not licensed at all. 56 | 57 | The precise terms and conditions for copying, distribution and 58 | modification follow. 59 | 60 | GNU GENERAL PUBLIC LICENSE 61 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 62 | 63 | 0. This License applies to any program or other work which contains 64 | a notice placed by the copyright holder saying it may be distributed 65 | under the terms of this General Public License. The "Program", below, 66 | refers to any such program or work, and a "work based on the Program" 67 | means either the Program or any derivative work under copyright law: 68 | that is to say, a work containing the Program or a portion of it, 69 | either verbatim or with modifications and/or translated into another 70 | language. (Hereinafter, translation is included without limitation in 71 | the term "modification".) Each licensee is addressed as "you". 72 | 73 | Activities other than copying, distribution and modification are not 74 | covered by this License; they are outside its scope. The act of 75 | running the Program is not restricted, and the output from the Program 76 | is covered only if its contents constitute a work based on the 77 | Program (independent of having been made by running the Program). 78 | Whether that is true depends on what the Program does. 79 | 80 | 1. You may copy and distribute verbatim copies of the Program's 81 | source code as you receive it, in any medium, provided that you 82 | conspicuously and appropriately publish on each copy an appropriate 83 | copyright notice and disclaimer of warranty; keep intact all the 84 | notices that refer to this License and to the absence of any warranty; 85 | and give any other recipients of the Program a copy of this License 86 | along with the Program. 87 | 88 | You may charge a fee for the physical act of transferring a copy, and 89 | you may at your option offer warranty protection in exchange for a fee. 90 | 91 | 2. You may modify your copy or copies of the Program or any portion 92 | of it, thus forming a work based on the Program, and copy and 93 | distribute such modifications or work under the terms of Section 1 94 | above, provided that you also meet all of these conditions: 95 | 96 | a) You must cause the modified files to carry prominent notices 97 | stating that you changed the files and the date of any change. 98 | 99 | b) You must cause any work that you distribute or publish, that in 100 | whole or in part contains or is derived from the Program or any 101 | part thereof, to be licensed as a whole at no charge to all third 102 | parties under the terms of this License. 103 | 104 | c) If the modified program normally reads commands interactively 105 | when run, you must cause it, when started running for such 106 | interactive use in the most ordinary way, to print or display an 107 | announcement including an appropriate copyright notice and a 108 | notice that there is no warranty (or else, saying that you provide 109 | a warranty) and that users may redistribute the program under 110 | these conditions, and telling the user how to view a copy of this 111 | License. (Exception: if the Program itself is interactive but 112 | does not normally print such an announcement, your work based on 113 | the Program is not required to print an announcement.) 114 | 115 | These requirements apply to the modified work as a whole. If 116 | identifiable sections of that work are not derived from the Program, 117 | and can be reasonably considered independent and separate works in 118 | themselves, then this License, and its terms, do not apply to those 119 | sections when you distribute them as separate works. But when you 120 | distribute the same sections as part of a whole which is a work based 121 | on the Program, the distribution of the whole must be on the terms of 122 | this License, whose permissions for other licensees extend to the 123 | entire whole, and thus to each and every part regardless of who wrote it. 124 | 125 | Thus, it is not the intent of this section to claim rights or contest 126 | your rights to work written entirely by you; rather, the intent is to 127 | exercise the right to control the distribution of derivative or 128 | collective works based on the Program. 129 | 130 | In addition, mere aggregation of another work not based on the Program 131 | with the Program (or with a work based on the Program) on a volume of 132 | a storage or distribution medium does not bring the other work under 133 | the scope of this License. 134 | 135 | 3. You may copy and distribute the Program (or a work based on it, 136 | under Section 2) in object code or executable form under the terms of 137 | Sections 1 and 2 above provided that you also do one of the following: 138 | 139 | a) Accompany it with the complete corresponding machine-readable 140 | source code, which must be distributed under the terms of Sections 141 | 1 and 2 above on a medium customarily used for software interchange; or, 142 | 143 | b) Accompany it with a written offer, valid for at least three 144 | years, to give any third party, for a charge no more than your 145 | cost of physically performing source distribution, a complete 146 | machine-readable copy of the corresponding source code, to be 147 | distributed under the terms of Sections 1 and 2 above on a medium 148 | customarily used for software interchange; or, 149 | 150 | c) Accompany it with the information you received as to the offer 151 | to distribute corresponding source code. (This alternative is 152 | allowed only for noncommercial distribution and only if you 153 | received the program in object code or executable form with such 154 | an offer, in accord with Subsection b above.) 155 | 156 | The source code for a work means the preferred form of the work for 157 | making modifications to it. For an executable work, complete source 158 | code means all the source code for all modules it contains, plus any 159 | associated interface definition files, plus the scripts used to 160 | control compilation and installation of the executable. However, as a 161 | special exception, the source code distributed need not include 162 | anything that is normally distributed (in either source or binary 163 | form) with the major components (compiler, kernel, and so on) of the 164 | operating system on which the executable runs, unless that component 165 | itself accompanies the executable. 166 | 167 | If distribution of executable or object code is made by offering 168 | access to copy from a designated place, then offering equivalent 169 | access to copy the source code from the same place counts as 170 | distribution of the source code, even though third parties are not 171 | compelled to copy the source along with the object code. 172 | 173 | 4. You may not copy, modify, sublicense, or distribute the Program 174 | except as expressly provided under this License. Any attempt 175 | otherwise to copy, modify, sublicense or distribute the Program is 176 | void, and will automatically terminate your rights under this License. 177 | However, parties who have received copies, or rights, from you under 178 | this License will not have their licenses terminated so long as such 179 | parties remain in full compliance. 180 | 181 | 5. You are not required to accept this License, since you have not 182 | signed it. However, nothing else grants you permission to modify or 183 | distribute the Program or its derivative works. These actions are 184 | prohibited by law if you do not accept this License. Therefore, by 185 | modifying or distributing the Program (or any work based on the 186 | Program), you indicate your acceptance of this License to do so, and 187 | all its terms and conditions for copying, distributing or modifying 188 | the Program or works based on it. 189 | 190 | 6. Each time you redistribute the Program (or any work based on the 191 | Program), the recipient automatically receives a license from the 192 | original licensor to copy, distribute or modify the Program subject to 193 | these terms and conditions. You may not impose any further 194 | restrictions on the recipients' exercise of the rights granted herein. 195 | You are not responsible for enforcing compliance by third parties to 196 | this License. 197 | 198 | 7. If, as a consequence of a court judgment or allegation of patent 199 | infringement or for any other reason (not limited to patent issues), 200 | conditions are imposed on you (whether by court order, agreement or 201 | otherwise) that contradict the conditions of this License, they do not 202 | excuse you from the conditions of this License. If you cannot 203 | distribute so as to satisfy simultaneously your obligations under this 204 | License and any other pertinent obligations, then as a consequence you 205 | may not distribute the Program at all. For example, if a patent 206 | license would not permit royalty-free redistribution of the Program by 207 | all those who receive copies directly or indirectly through you, then 208 | the only way you could satisfy both it and this License would be to 209 | refrain entirely from distribution of the Program. 210 | 211 | If any portion of this section is held invalid or unenforceable under 212 | any particular circumstance, the balance of the section is intended to 213 | apply and the section as a whole is intended to apply in other 214 | circumstances. 215 | 216 | It is not the purpose of this section to induce you to infringe any 217 | patents or other property right claims or to contest validity of any 218 | such claims; this section has the sole purpose of protecting the 219 | integrity of the free software distribution system, which is 220 | implemented by public license practices. Many people have made 221 | generous contributions to the wide range of software distributed 222 | through that system in reliance on consistent application of that 223 | system; it is up to the author/donor to decide if he or she is willing 224 | to distribute software through any other system and a licensee cannot 225 | impose that choice. 226 | 227 | This section is intended to make thoroughly clear what is believed to 228 | be a consequence of the rest of this License. 229 | 230 | 8. If the distribution and/or use of the Program is restricted in 231 | certain countries either by patents or by copyrighted interfaces, the 232 | original copyright holder who places the Program under this License 233 | may add an explicit geographical distribution limitation excluding 234 | those countries, so that distribution is permitted only in or among 235 | countries not thus excluded. In such case, this License incorporates 236 | the limitation as if written in the body of this License. 237 | 238 | 9. The Free Software Foundation may publish revised and/or new versions 239 | of the General Public License from time to time. Such new versions will 240 | be similar in spirit to the present version, but may differ in detail to 241 | address new problems or concerns. 242 | 243 | Each version is given a distinguishing version number. If the Program 244 | specifies a version number of this License which applies to it and "any 245 | later version", you have the option of following the terms and conditions 246 | either of that version or of any later version published by the Free 247 | Software Foundation. If the Program does not specify a version number of 248 | this License, you may choose any version ever published by the Free Software 249 | Foundation. 250 | 251 | 10. If you wish to incorporate parts of the Program into other free 252 | programs whose distribution conditions are different, write to the author 253 | to ask for permission. For software which is copyrighted by the Free 254 | Software Foundation, write to the Free Software Foundation; we sometimes 255 | make exceptions for this. Our decision will be guided by the two goals 256 | of preserving the free status of all derivatives of our free software and 257 | of promoting the sharing and reuse of software generally. 258 | 259 | NO WARRANTY 260 | 261 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 262 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 263 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 264 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 265 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 266 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 267 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 268 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 269 | REPAIR OR CORRECTION. 270 | 271 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 272 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 273 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 274 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 275 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 276 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 277 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 278 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 279 | POSSIBILITY OF SUCH DAMAGES. 280 | 281 | END OF TERMS AND CONDITIONS 282 | 283 | How to Apply These Terms to Your New Programs 284 | 285 | If you develop a new program, and you want it to be of the greatest 286 | possible use to the public, the best way to achieve this is to make it 287 | free software which everyone can redistribute and change under these terms. 288 | 289 | To do so, attach the following notices to the program. It is safest 290 | to attach them to the start of each source file to most effectively 291 | convey the exclusion of warranty; and each file should have at least 292 | the "copyright" line and a pointer to where the full notice is found. 293 | 294 | 295 | Copyright (C) 296 | 297 | This program is free software; you can redistribute it and/or modify 298 | it under the terms of the GNU General Public License as published by 299 | the Free Software Foundation; either version 2 of the License, or 300 | (at your option) any later version. 301 | 302 | This program is distributed in the hope that it will be useful, 303 | but WITHOUT ANY WARRANTY; without even the implied warranty of 304 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 305 | GNU General Public License for more details. 306 | 307 | You should have received a copy of the GNU General Public License 308 | along with this program; if not, write to the Free Software 309 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 310 | 311 | 312 | Also add information on how to contact you by electronic and paper mail. 313 | 314 | If the program is interactive, make it output a short notice like this 315 | when it starts in an interactive mode: 316 | 317 | Gnomovision version 69, Copyright (C) year name of author 318 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 319 | This is free software, and you are welcome to redistribute it 320 | under certain conditions; type `show c' for details. 321 | 322 | The hypothetical commands `show w' and `show c' should show the appropriate 323 | parts of the General Public License. Of course, the commands you use may 324 | be called something other than `show w' and `show c'; they could even be 325 | mouse-clicks or menu items--whatever suits your program. 326 | 327 | You should also get your employer (if you work as a programmer) or your 328 | school, if any, to sign a "copyright disclaimer" for the program, if 329 | necessary. Here is a sample; alter the names: 330 | 331 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 332 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 333 | 334 | , 1 April 1989 335 | Ty Coon, President of Vice 336 | 337 | This General Public License does not permit incorporating your program into 338 | proprietary programs. If your program is a subroutine library, you may 339 | consider it more useful to permit linking proprietary applications with the 340 | library. If this is what you want to do, use the GNU Library General 341 | Public License instead of this License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Open Networking Foundation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | GO_FILES := $(shell find . -type d -name '.cache' -prune -o -type f -name '*.go' -print) 6 | 7 | fmt: 8 | @echo 9 | @echo "===> Formatting Go files <===" 10 | @gofmt -s -l -w $(GO_FILES) 11 | 12 | .golangci-bin: 13 | @echo "===> Installing Golangci-lint <===" 14 | @curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $@ v1.41.1 15 | 16 | golint: .golangci-bin 17 | @echo "===> Running golangci (linux) <===" 18 | @GOOS=linux $(CURDIR)/.golangci-bin/golangci-lint run -c $(CURDIR)/.golangci.yml 19 | 20 | build: 21 | @echo "===> Building int-host-reporter image <===" 22 | docker build -t opennetworking/int-host-reporter:latest . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 5 | 6 | # INT Host Reporter 7 | 8 | The In-Band Network Telemetry (INT) standard is a network telemetry solution providing an in-depth, per-packet network visibility. 9 | So far, the INT standard has been mainly implemented by the network switches (this implementation is somewhere referred as "switch-INT"). 10 | 11 | The INT Host Reporter is the implementation of the "host-INT" approach - the concept of extending the In-Band Network Telemetry (INT) 12 | support to the end hosts. 13 | The INT Host Reporter is tightly integrated with Kubernetes and generates an INT report (flow or drop report) for each packet being sent between (virtual) network interfaces managed by the Kubernetes Container Network Interface (CNI). 14 | The INT reports are furhter sent to the INT collector that gathers INT reports from different network devices (e.g. switches, hosts) and shows the end-to-end network statistics. 15 | This enables observing E2E network flows traversing the Kubernetes cluster (e.g. Pod-to-Pod communication or packets to/from Kubernetes Services). 16 | 17 | ## Overview 18 | 19 | `INT Host Reporter` implements the "host-INT" approach by using a combination of the eBPF code running in the Linux kernel 20 | and a Go application running as an userspace agent. The diagram below shows the high-level design of the host-INT solution, which is independent of the Kubernetes CNI being used. 21 | 22 | ![Design](docs/static/images/design.png?raw=true "High-level design of CNI-independent host-INT") 23 | 24 | As depicted in the diagram, the system consists of two pieces: 25 | 26 | - the **INT-aware eBPF programs** are attached to both TC Ingress and TC Egress hooks. The ingress eBPF program 27 | does a basic packet pre-processing and collects ingress metadata that is further stored in a shared BPF map. 28 | The egress eBPF program reads the per-packet metadata and generates a data plane report by pushing an event to the 29 | `BPF_PERF_EVENT_ARRAY` map . 30 | - the **INT Host Reporter** application listens to the events from the `BPF_PERF_EVENT_ARRAY` map, converts 31 | the data plane reports into INT reports and sends the INT reports to the INT collector. 32 | 33 | As mentioned before, the INT Host Reporter works in the CNI-independent fashion, so the target goal is to enable using INT Host Reporter with _any_ Kubernetes CNI. 34 | So far, we have tested the INT Host Reporter with [Calico](https://docs.projectcalico.org/getting-started/kubernetes/) and [Cilium](https://cilium.io/) and DeepInsight from Intel as an INT collector. 35 | 36 | ## Building INT Host Reporter 37 | 38 | To build the INT Host Reporter image from scratch run the below command from the main directory: 39 | 40 | ```bash 41 | $ docker build -t : . 42 | ``` 43 | 44 | ## Downloading INT Host Reporter image 45 | 46 | Alternatively, the Docker image of INT Host Reporter can be downloaded from the ONF registry. 47 | 48 | ```bash 49 | $ docker pull opennetworking/int-host-reporter:latest 50 | ``` 51 | 52 | ## Deployment guide 53 | 54 | ### Requirements 55 | 56 | - Kernel version v5.11 or higher. 57 | - `CAP_SYS_ADMIN` privileges with access to the host network (`hostNetwork: true`). 58 | - Access to the eBPF filesystem (`/sys/fs/bpf`). 59 | - INT Host Reporter exposes REST API on `tcp/4048` port. Make sure this port is accessible. 60 | 61 | ### Install the K8s cluster 62 | 63 | The installation of a Kubernetes cluster is basically out of scope of this document. 64 | You should follow the instructions to deploy the Kubernetes cluster using the installer of your choice ([see Kubernetes documentation](https://kubernetes.io/docs/setup/)). 65 | 66 | ### Deploy INT Host Reporter 67 | 68 | #### Using Kubernetes deployment files 69 | 70 | Edit `deployment/kubernetes/inthostreporter.yaml` and configure the following variables: 71 | 72 | - `CNI` should define the Kubernetes CNI being used for the cluster. We currently support the following values: `cilium`, `calico-ebpf`, `calico-iptables`. 73 | - `COLLECTOR` should point to the address of the INT collector (e.g. 192.168.50.99:32766). 74 | - `DATA_INTERFACE` should be set to the name of physical interface that has the `status.hostIP` assigned. 75 | For instance, if Kubernetes API server is advertised on `192.168.99.20`, the data interface is the interface that has this IP address assigned. 76 | 77 | Next, prepare the INT watchlist file (modify `configs/watchlist.yaml` if needed) and deploy it as ConfigMap. 78 | 79 | `$ kubectl create -n kube-system configmap watchlist-conf --from-file=./configs/watchlist.yaml` 80 | 81 | Then, run the below command to deploy the INT Host Reporter. 82 | 83 | `$ kubectl apply -f deployment/kubernetes/inthostreporter.yaml` 84 | 85 | Verify that the `int-host-reporter` is in the Running state on each node: 86 | 87 | ```bash 88 | $ kubectl get pods --all-namespaces -o wide 89 | NAMESPACE NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES 90 | kube-system int-host-reporter-jpdl2 1/1 Running 0 9m11s 10.79.233.238 worker2 91 | kube-system int-host-reporter-ljwvs 1/1 Running 0 9m11s 10.68.235.172 worker1 92 | kube-system int-host-reporter-x48ps 1/1 Running 0 9m11s 10.67.219.106 kubemaster 93 | ``` 94 | 95 | For the CNIs that we have tested, there are no CNI-specific configuration steps required for the INT Host Reporter to work properly. 96 | Once the INT Host Reporter is successfully deployed, it should start sending INT reports to the collector. 97 | 98 | You can uninstall `int-host-reporter` using: 99 | 100 | `$ kubectl delete -f deployment/kubernetes/inthostreporter.yaml` 101 | 102 | #### Using Helm 103 | 104 | We also provide Helm charts to deploy INT Host Reporter. 105 | You can customize your deployment by changing configuration in `deployments/helm/int-host-reporter/Values.yaml`. 106 | 107 | To deploy `int-host-reporter` run the below command: 108 | 109 | `$ helm install --namespace ./deployments/helm/int-host-reporter [-f .yaml]` 110 | 111 | To uninstall the Helm deployment run: 112 | 113 | `$ helm uninstall --namespace ` 114 | 115 | ## Using INT Host Reporter with DeepInsight 116 | 117 | If the INT Host Reporter has been successfully deployed, it will start generating and sending INT reports to the INT collector. 118 | So far, the Host INT Reporter has been tested with DeepInsight (DI) - the INT collector provided by Intel. 119 | DeepInsight requires the additional configuration step to start visualizing network statistics. 120 | 121 | The additional configuration step is to upload the DI topology file - the JSON file that describes 122 | the topology of a network. In particular, the DI topology should have the following sections defined: 123 | 124 | - `switches` - the list of switches in the network. In the case of host-INT, the virtual switch (CNI datapath) is also defined as the switch. 125 | Thus, this section should contain each network switch plus all the hosts, where the Kubernetes is running on. 126 | - `hosts` - the list of hosts in the network. In the case of host-INT, the `hosts` section should contain all servers attached to the network, 127 | except those being used as K8s nodes. 128 | - `subnets` - the list of subnets in the network. In the case of host-INT, it should contain the subnet used to interconnect Kubernetes nodes, as well as 129 | the all the Pod subnets (the range of IP addresses, from which the Pod IPs are assigned from). Typically, a CNI will use a single IP subnet per Kubernetes worker, 130 | so there should be at least as many subnets defined as the number of Kubernetes workers. 131 | - `links` - the list of links in the network. It represents links between 2 switches, between a switch and a host, or between a switch and a subnet - 132 | the last way of representing a link is an abstraction introduced by DeepInsight and means that we can access a subnet via a given interface of a switch. 133 | In the case of host-INT, Pods are not defined as `hosts`, but we use `subnet` to represent the group of Pods attached to the network. Therefore, 134 | the `links` section should contain the links between a virtual switch and a Pod's subnet for each virtual interface configured on the Kubernetes node. 135 | 136 | As a reference, we provide a sample DI topology file in in the `examples/deepinsight/` directory. The sample DI topology file is visualized below. The dashed lines 137 | represents the abstraction of connections between switch and subnet. 138 | 139 | ![The visualization of a sample DI topology](docs/static/images/di-topo.png?raw=true "The visualization of a sample DI topology") 140 | 141 | However, building the DI topology file manually is time-consuming and error-prone. Therefore, we have created the `./di gen-topology` script 142 | to automate this process. You can find the guide how to use this script in [the sdfabric-utils repository](https://github.com/opennetworkinglab/sdfabric-utils) (member-only, please reach out to your ONF representative to get access). 143 | 144 | The `./di gen-topology` scipt leverages INT Host Reporter's `GET /api/v1/topology` API exposed on each 145 | K8s nodes to retrieve information about local links. 146 | 147 | ## Current limitations 148 | 149 | - Only IPv4 endpoints are supported. 150 | - INT Host Reporter only supports UDP/TCP packets; ICMP packets are not reported. 151 | - System flows (e.g. traffic between Kubernetes agents) are not reported. 152 | - INT Host Reporeter doesn't work with CNIs making use of XDP hook yet. 153 | If you want to use INT Host Reporter with Calico-eBPF or Cilium please make sure that XDP acceleration is disabled. 154 | 155 | ## License 156 | 157 | The user space components of INT Host Reporter are licensed under the [Apache License, Version 2.0](LICENSES/Apache-2.0.txt). The BPF code 158 | is licensed under the [General Public License, Version 2.0](LICENSES/GPL-2.0-only.txt). 159 | -------------------------------------------------------------------------------- /bpf/common.h: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: GPL-2.0-only 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define PIN_GLOBAL_NS 2 10 | 11 | #ifdef DEBUG 12 | #define bpf_printk(fmt, ...) \ 13 | ({ \ 14 | char ____fmt[] = fmt; \ 15 | bpf_trace_printk(____fmt, sizeof(____fmt), \ 16 | ##__VA_ARGS__); \ 17 | }) 18 | #else 19 | #define bpf_printk(fmt, ...) do {} while(0) 20 | #endif 21 | 22 | #pragma clang diagnostic push 23 | #pragma clang diagnostic ignored "-Wreserved-id-macro" 24 | 25 | #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ 26 | # define __bpf_ntohs(x) __builtin_bswap16(x) 27 | # define __bpf_htons(x) __builtin_bswap16(x) 28 | # define __bpf_constant_ntohs(x) ___constant_swab16(x) 29 | # define __bpf_constant_htons(x) ___constant_swab16(x) 30 | # define __bpf_ntohl(x) __builtin_bswap32(x) 31 | # define __bpf_htonl(x) __builtin_bswap32(x) 32 | # define __bpf_constant_ntohl(x) ___constant_swab32(x) 33 | # define __bpf_constant_htonl(x) ___constant_swab32(x) 34 | #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ 35 | # define __bpf_ntohs(x) (x) 36 | # define __bpf_htons(x) (x) 37 | # define __bpf_constant_ntohs(x) (x) 38 | # define __bpf_constant_htons(x) (x) 39 | # define __bpf_ntohl(x) (x) 40 | # define __bpf_htonl(x) (x) 41 | # define __bpf_constant_ntohl(x) (x) 42 | # define __bpf_constant_htonl(x) (x) 43 | #else 44 | # error "Fix your compiler's __BYTE_ORDER__?!" 45 | #endif 46 | #pragma clang diagnostic pop 47 | 48 | #define bpf_htons(x) \ 49 | (__builtin_constant_p(x) ? \ 50 | __bpf_constant_htons(x) : __bpf_htons(x)) 51 | #define bpf_ntohs(x) \ 52 | (__builtin_constant_p(x) ? \ 53 | __bpf_constant_ntohs(x) : __bpf_ntohs(x)) 54 | #define bpf_htonl(x) \ 55 | (__builtin_constant_p(x) ? \ 56 | __bpf_constant_htonl(x) : __bpf_htonl(x)) 57 | #define bpf_ntohl(x) \ 58 | (__builtin_constant_p(x) ? \ 59 | __bpf_constant_ntohl(x) : __bpf_ntohl(x)) 60 | 61 | struct bpf_elf_map { 62 | /* 63 | * The various BPF MAP types supported (see enum bpf_map_type) 64 | * https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf.h 65 | */ 66 | __u32 type; 67 | __u32 size_key; 68 | __u32 size_value; 69 | __u32 max_elem; 70 | /* 71 | * Various flags you can place such as `BPF_F_NO_COMMON_LRU` 72 | */ 73 | __u32 flags; 74 | __u32 id; 75 | /* 76 | * Pinning is how the map are shared across process boundary. 77 | * Cillium has a good explanation of them: http://docs.cilium.io/en/v1.3/bpf/#llvm 78 | * PIN_GLOBAL_NS - will get pinned to `/sys/fs/bpf/tc/globals/${variable-name}` 79 | * PIN_OBJECT_NS - will get pinned to a directory that is unique to this object 80 | * PIN_NONE - the map is not placed into the BPF file system as a node, 81 | and as a result will not be accessible from user space 82 | */ 83 | __u32 pinning; 84 | }; -------------------------------------------------------------------------------- /bpf/flags.h: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: GPL-2.0-only 3 | 4 | /* Bridged metadata modes */ 5 | /* BMD_MODE_SKB_CB: use skb->cb to pass random packet identifier */ 6 | #define BMD_MODE_SKB_CB 0 7 | /* BMD_MODE_SKB_PTR: use address of skb descriptor as packet identifier */ 8 | #define BMD_MODE_SKB_PTR 1 9 | /* BMD_MODE_FLOW_HASH: use flow hash retrieved by bpf_get_hash_recalc() as packet identifier. */ 10 | #define BMD_MODE_FLOW_HASH 2 11 | 12 | #ifndef BMD_MODE 13 | #define BMD_MODE BMD_MODE_SKB_CB 14 | #endif 15 | 16 | #ifndef __NR_CPUS__ 17 | #define __NR_CPUS__ 1 18 | #endif -------------------------------------------------------------------------------- /bpf/int-datapath.c: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: GPL-2.0-only 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "common.h" 11 | #include "flags.h" 12 | 13 | #define SAMPLE_SIZE 128ul 14 | #define DP_EVENT_TRACE 1 15 | #define DP_EVENT_DROP 2 16 | 17 | /* struct bridged_metadata is used to pass per-packet metadata between TC Ingress and TC Egress */ 18 | struct bridged_metadata { 19 | __u64 ingress_timestamp; 20 | __u32 ingress_port; 21 | __u32 pre_nat_ip_dst; 22 | __u32 pre_nat_ip_src; 23 | __u16 pre_nat_proto; 24 | __u16 pad0; 25 | __u16 pre_nat_sport; 26 | __u16 pre_nat_dport; 27 | __u16 seq_no; 28 | /* This field is used by userspace for the packet drop detection process. 29 | The userspace sets this field if it sees the bridged metadata for the first time. 30 | If the field is still set the second time the userspace sees it, 31 | the entry is removed by userspace and the packet drop is reported. */ 32 | __u16 seen_by_userspace; 33 | }; 34 | 35 | /* struct dp_event opaques information passed to the userspace. 36 | The content will be used by userspace agent to create an INT report */ 37 | struct dp_event { 38 | __u8 type; // either DP_EVENT_TRACE or DP_EVENT_DROP notification 39 | __u8 reason; // drop reason or 0 40 | __u32 pre_nat_ip_src; 41 | __u32 pre_nat_ip_dst; // Set to the original pre-DNAT ip_dst in the "to-endpoint" direction. Otherwise, set to 0. 42 | __u16 pre_nat_sport; 43 | __u16 pre_nat_dport; // Set to the original pre-DNAT dport in the "to-endpoint" direction. Otherwise, set to 0. 44 | __u32 ingress_ifindex; // ingress port 45 | __u32 egress_ifindex; // egress port 46 | __u64 ig_tstamp; 47 | __u64 eg_tstamp; 48 | } __packed; 49 | 50 | struct flow_filter_value { 51 | __u64 timestamp; 52 | __u32 ig_port; 53 | __u32 eg_port; 54 | __u32 flow_hash; 55 | __u32 hop_latency; 56 | }; 57 | 58 | struct shared_map_key { 59 | __u64 packet_id; 60 | __u32 flow_hash; 61 | // padding is added to pass BPF verifier, see: 62 | // https://stackoverflow.com/questions/60601180/af-xdp-invalid-indirect-read-from-stack 63 | __u32 padding; 64 | }; 65 | 66 | struct bpf_elf_map SEC("maps") SHARED_MAP = { 67 | .type = BPF_MAP_TYPE_HASH, 68 | .size_key = sizeof(struct shared_map_key), 69 | .size_value = sizeof(struct bridged_metadata), 70 | .pinning = PIN_GLOBAL_NS, 71 | .max_elem = 65536, 72 | }; 73 | 74 | struct bpf_elf_map SEC("maps") INT_EVENTS_MAP = { 75 | .type = BPF_MAP_TYPE_PERF_EVENT_ARRAY, 76 | .size_key = sizeof(__u32), 77 | .size_value = sizeof(__u32), 78 | .pinning = PIN_GLOBAL_NS, 79 | .max_elem = __NR_CPUS__, 80 | }; 81 | 82 | struct bpf_elf_map SEC("maps") INT_FLOW_FILTER1 = { 83 | .type = BPF_MAP_TYPE_ARRAY, 84 | .size_key = sizeof(__u32), 85 | .size_value = sizeof(struct flow_filter_value), 86 | .pinning = PIN_GLOBAL_NS, 87 | .max_elem = 65536, 88 | }; 89 | 90 | struct bpf_elf_map SEC("maps") INT_FLOW_FILTER2 = { 91 | .type = BPF_MAP_TYPE_ARRAY, 92 | .size_key = sizeof(__u32), 93 | .size_value = sizeof(struct flow_filter_value), 94 | .pinning = PIN_GLOBAL_NS, 95 | .max_elem = 65536, 96 | }; 97 | 98 | static __always_inline bool flow_filter_contains(void *map, __u32 hash, struct flow_filter_value *flow_info) 99 | { 100 | bool result = false; 101 | hash &= 0x0000ffff; 102 | struct flow_filter_value *stored_flow_info = bpf_map_lookup_elem(map, &hash); 103 | if (!stored_flow_info) { 104 | return false; 105 | } 106 | if (stored_flow_info->ig_port == flow_info->ig_port && 107 | stored_flow_info->eg_port == flow_info->eg_port && 108 | stored_flow_info->flow_hash == flow_info->flow_hash && 109 | stored_flow_info->timestamp == flow_info->timestamp && 110 | stored_flow_info->hop_latency == flow_info->hop_latency) { 111 | result = true; 112 | } 113 | 114 | stored_flow_info->ig_port = flow_info->ig_port; 115 | stored_flow_info->eg_port = flow_info->eg_port; 116 | stored_flow_info->flow_hash = flow_info->flow_hash; 117 | stored_flow_info->timestamp = flow_info->timestamp; 118 | stored_flow_info->hop_latency = flow_info->hop_latency; 119 | 120 | return result; 121 | } 122 | 123 | static __always_inline bool filter_allow(__u32 ig_port, __u32 eg_port, __u32 flow_hash, __u64 current_timestamp, __u32 hop_latency) 124 | { 125 | /* Report every 1 second. */ 126 | __u64 timestamp = current_timestamp & 0xffffffffc0000000; 127 | /* Report if hop latency change is greater than 2^16ns (~64 us). */ 128 | hop_latency &= 0xfffe0000; 129 | struct flow_filter_value new_flow_info = { 130 | .ig_port = ig_port, 131 | .eg_port = eg_port, 132 | .flow_hash = flow_hash, 133 | .timestamp = timestamp, 134 | .hop_latency = hop_latency, 135 | }; 136 | 137 | bpf_printk("Applying flow filter for: flow_hash=%x, quantized_tstamp=%llx, quantized_hop_latency=%x", 138 | flow_hash, timestamp, hop_latency); 139 | 140 | bool flag = false; 141 | flag = flow_filter_contains(&INT_FLOW_FILTER1, flow_hash, &new_flow_info); 142 | flag = flag || flow_filter_contains(&INT_FLOW_FILTER2, flow_hash >> 16, &new_flow_info); 143 | if (!flag) { 144 | bpf_printk("Flow filter detected change, allow to report."); 145 | return true; 146 | } 147 | 148 | return false; 149 | } 150 | 151 | SEC("classifier/ingress") 152 | int ingress(struct __sk_buff *skb) 153 | { 154 | __u64 ingress_timestamp = bpf_ktime_get_ns(); 155 | __u32 hash = bpf_get_hash_recalc(skb); 156 | bpf_printk("Ingress, port=%d, hash=%x", skb->ifindex, hash); 157 | 158 | void *data = (void *)(long)skb->data; 159 | void *data_end = (void *)(long)skb->data_end; 160 | struct ethhdr *eth = data; 161 | 162 | if (data + sizeof(*eth) > data_end) 163 | return TC_ACT_SHOT; 164 | 165 | if (bpf_htons(eth->h_proto) != 0x0800) { 166 | return TC_ACT_UNSPEC; 167 | } 168 | 169 | struct iphdr *iph = data + sizeof(*eth); 170 | 171 | if (data + sizeof(*eth) + sizeof(*iph) > data_end) 172 | return TC_ACT_SHOT; 173 | 174 | // FIXME: we don't support ICMP traffic yet 175 | if (iph->protocol == 0x1) { 176 | return TC_ACT_UNSPEC; 177 | } 178 | 179 | // we parse UDP, because we are only interested in src & dst ports of L4 180 | struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph); 181 | if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end) 182 | return TC_ACT_SHOT; 183 | 184 | // only for the PoC purpose; don't report system flows 185 | if (udp->source == bpf_htons(6443) || udp->dest == bpf_htons(6443) || 186 | udp->source == bpf_htons(8181) || udp->dest == bpf_htons(8181) || 187 | udp->source == bpf_htons(8080) || udp->dest == bpf_htons(8080) || 188 | bpf_htons(udp->source) == 4240 || bpf_htons(udp->dest) == 4240) { 189 | return TC_ACT_UNSPEC; 190 | } 191 | 192 | __u32 ip_src, ip_dst; 193 | __u32 ip_protocol; 194 | __u16 l4_sport, l4_dport; 195 | if (bpf_htons(udp->dest) == 8472 || bpf_htons(udp->dest) == 4789) { 196 | struct iphdr *inner_ip = data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) + 197 | 8 + sizeof(*eth); 198 | if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) + 8 + sizeof(*eth) + sizeof(*iph) > data_end) 199 | return TC_ACT_SHOT; 200 | 201 | struct ethhdr *inner_eth = data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) + 8; 202 | if (bpf_ntohs(inner_eth->h_proto) == 0x86dd || inner_ip->protocol == 0x1) { 203 | return TC_ACT_UNSPEC; 204 | } 205 | ip_src = inner_ip->saddr; 206 | ip_dst = inner_ip->daddr; 207 | ip_protocol = inner_ip->protocol; 208 | struct udphdr *inner_udp = data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) + 8 + sizeof(*eth) + sizeof(*iph); 209 | if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) + 8 + sizeof(*eth) + sizeof(*iph) + sizeof(*inner_udp) > data_end) 210 | return TC_ACT_SHOT; 211 | l4_sport = inner_udp->source; 212 | l4_dport = inner_udp->dest; 213 | 214 | // only for the PoC purpose; don't report system flows 215 | if (bpf_ntohs(inner_udp->source) == 8080 || bpf_ntohs(inner_udp->dest) == 8080 || 216 | bpf_ntohs(inner_udp->source) == 4240 || bpf_ntohs(inner_udp->dest) == 4240) { 217 | return TC_ACT_UNSPEC; 218 | } 219 | } else { 220 | ip_src = iph->saddr; 221 | ip_dst = iph->daddr; 222 | ip_protocol = iph->protocol; 223 | l4_sport = udp->source; 224 | l4_dport = udp->dest; 225 | } 226 | 227 | bpf_printk("ip_src=%x, ip_dst=%x, proto=%d", bpf_htonl(ip_src), bpf_htonl(ip_dst), ip_protocol); 228 | bpf_printk("l4_sport=%d, l4_dport=%d", bpf_htons(l4_sport), bpf_htons(l4_dport)); 229 | 230 | struct shared_map_key key = {}; 231 | __builtin_memset(&key, 0, sizeof(key)); 232 | #if BMD_MODE == BMD_MODE_SKB_PTR 233 | key.packet_id = (__u64) skb; 234 | #elif BMD_MODE == BMD_MODE_FLOW_HASH 235 | key.packet_id = (__u64) hash; 236 | #else 237 | __u8 rand_id = bpf_get_prandom_u32() % 255; 238 | skb->cb[4] = rand_id << 24; 239 | key.packet_id = (__u64) rand_id; 240 | #endif 241 | key.flow_hash = hash; 242 | key.padding = 0; 243 | 244 | struct bridged_metadata bmd = {}; 245 | __builtin_memset(&bmd, 0, sizeof(bmd)); 246 | bmd.ingress_timestamp = ingress_timestamp; 247 | bmd.ingress_port = skb->ifindex; 248 | bmd.pre_nat_ip_src = ip_src; 249 | bmd.pre_nat_ip_dst = ip_dst; 250 | bmd.pre_nat_proto = ip_protocol; 251 | bmd.pre_nat_dport = l4_dport; 252 | bmd.pre_nat_sport = l4_sport; 253 | bmd.seq_no = 0; 254 | 255 | bpf_printk("Saving bridged metadata under key: hash=%x, packet_id=%llx", 256 | key.flow_hash, key.packet_id); 257 | 258 | bpf_map_update_elem(&SHARED_MAP, &key, &bmd, 0); 259 | 260 | return TC_ACT_UNSPEC; 261 | } 262 | 263 | SEC("classifier/egress") 264 | int egress(struct __sk_buff *skb) 265 | { 266 | __u64 egress_timestamp = bpf_ktime_get_ns(); 267 | __u32 hash = bpf_get_hash_recalc(skb); 268 | 269 | #if BMD_MODE == BMD_MODE_SKB_PTR 270 | __u64 packet_id = (__u64) skb; 271 | #elif BMD_MODE == BMD_MODE_FLOW_HASH 272 | __u64 packet_id = (__u64) hash; 273 | #else 274 | __u64 packet_id = (__u64) (skb->cb[4] >> 24); 275 | #endif 276 | bpf_printk("Egress, packet_id=%llx, port=%d, hash=%x", packet_id, skb->ifindex, hash); 277 | 278 | void *data = (void *)(long)skb->data; 279 | void *data_end = (void *)(long)skb->data_end; 280 | struct ethhdr *eth = data; 281 | 282 | if (data + sizeof(*eth) > data_end) 283 | return TC_ACT_SHOT; 284 | 285 | bpf_printk("eth_type=%x", bpf_htons(eth->h_proto)); 286 | 287 | struct iphdr *iph = data + sizeof(*eth); 288 | 289 | if (data + sizeof(*eth) + sizeof(*iph) > data_end) 290 | return TC_ACT_SHOT; 291 | 292 | bpf_printk("ip_src=%x, ip_dst=%x", bpf_htonl(iph->saddr), bpf_htonl(iph->daddr)); 293 | 294 | struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph); 295 | if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end) 296 | return TC_ACT_SHOT; 297 | 298 | bpf_printk("l4_sport=%d, l4_dport=%d", bpf_htons(udp->source), bpf_htons(udp->dest)); 299 | 300 | struct shared_map_key key = {}; 301 | __builtin_memset(&key, 0, sizeof(struct shared_map_key)); 302 | key.packet_id = packet_id; 303 | key.flow_hash = hash; 304 | 305 | struct bridged_metadata *b = bpf_map_lookup_elem(&SHARED_MAP, &key); 306 | if (!b) { 307 | bpf_printk("No bridged metadata found for hash=%x, packet_id=%llx.", key.flow_hash, key.packet_id); 308 | return TC_ACT_UNSPEC; 309 | } 310 | 311 | bpf_printk("Read bridged metadata for %x: ingress_tstamp=%llu, ingress_port=%d", hash, b->ingress_timestamp, 312 | b->ingress_port); 313 | 314 | __u32 hop_latency = egress_timestamp-b->ingress_timestamp; 315 | bpf_printk("Hop latency=%llu, egress_port=%d, seq_no=%u", hop_latency, skb->ifindex, 316 | b->seq_no); 317 | 318 | if (filter_allow(b->ingress_port, skb->ifindex, hash, egress_timestamp, hop_latency)) { 319 | struct dp_event evt = {}; 320 | evt.type = DP_EVENT_TRACE; 321 | evt.egress_ifindex = skb->ifindex; 322 | evt.eg_tstamp = egress_timestamp; 323 | evt.ingress_ifindex = b->ingress_port; 324 | evt.ig_tstamp = b->ingress_timestamp; 325 | evt.pre_nat_ip_src = b->pre_nat_ip_src; 326 | evt.pre_nat_ip_dst = b->pre_nat_ip_dst; 327 | evt.pre_nat_sport = b->pre_nat_sport; 328 | evt.pre_nat_dport = b->pre_nat_dport; 329 | __u64 sample_size = skb->len < SAMPLE_SIZE ? skb->len : SAMPLE_SIZE; 330 | bpf_perf_event_output(skb, &INT_EVENTS_MAP, (sample_size << 32) | BPF_F_CURRENT_CPU, 331 | &evt, sizeof(evt)); 332 | } 333 | 334 | bpf_map_delete_elem(&SHARED_MAP, &key); 335 | bpf_printk("Delete element from SHARED_MAP: packet_id=%llx, hash=%x", key.packet_id, key.flow_hash); 336 | 337 | return TC_ACT_UNSPEC; 338 | } 339 | 340 | char _license[] SEC("license") = "GPL"; -------------------------------------------------------------------------------- /cmd/int-host-reporter/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package main 5 | 6 | import ( 7 | "flag" 8 | "github.com/gin-gonic/gin" 9 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 10 | "github.com/opennetworkinglab/int-host-reporter/pkg/inthostreporter" 11 | "github.com/opennetworkinglab/int-host-reporter/pkg/watchlist" 12 | log "github.com/sirupsen/logrus" 13 | ) 14 | 15 | var ( 16 | watchlistConfiguration = flag.String("watchlist-conf", "", "File with INT watchlist configuration") 17 | cniInUse = flag.String("cni", "", "Kubernetes CNI used by the cluster (supported CNIs: cilium, calico-ebpf, calico-legacy") 18 | logLevel = flag.String("log-level", "info", "Set log level (info/debug/trace).") 19 | ) 20 | 21 | func init() { 22 | flag.StringVar(watchlistConfiguration, "f", "", "") 23 | flag.StringVar(cniInUse, "c", "", "") 24 | } 25 | 26 | func parseLogLevel() log.Level { 27 | switch *logLevel { 28 | case "info": 29 | return log.InfoLevel 30 | case "debug": 31 | return log.DebugLevel 32 | case "trace": 33 | return log.TraceLevel 34 | default: 35 | log.Println("Unknown log level provided, defaulting to 'info'..") 36 | return log.InfoLevel 37 | } 38 | } 39 | 40 | func main() { 41 | flag.Parse() 42 | logLevel := parseLogLevel() 43 | log.SetLevel(logLevel) 44 | log.WithFields(log.Fields{ 45 | "collector": *inthostreporter.INTCollectorServer, 46 | "switchID": *inthostreporter.INTSwitchID, 47 | }).Info("Starting INT Host Reporter.") 48 | 49 | if logLevel != log.TraceLevel { 50 | // default Gin mode is debug. 51 | // Keep it in debug mode only if trace is enabled. 52 | gin.SetMode(gin.ReleaseMode) 53 | } 54 | 55 | err := common.ParseCNIType(*cniInUse) 56 | if err != nil { 57 | log.Fatalf("failed to start INT Host Reporter: %v", err.Error()) 58 | } 59 | 60 | wlist := watchlist.NewINTWatchlist() 61 | if *watchlistConfiguration != "" { 62 | err := watchlist.FillFromFile(wlist, *watchlistConfiguration) 63 | if err != nil { 64 | log.WithFields(log.Fields{ 65 | "error": err, 66 | }).Fatal("Failed to parse the watchlist configuration file..") 67 | } 68 | } 69 | 70 | intReporter := inthostreporter.NewIntHostReporter(wlist) 71 | 72 | // Blocking 73 | err = intReporter.Start() 74 | if err != nil { 75 | log.Fatalf("Error while running INT Host Reporter: %v", err) 76 | } 77 | log.Info("INT Host Reporter stopped.") 78 | } 79 | -------------------------------------------------------------------------------- /configs/watchlist.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # Sample INT watchlist configuration; only exact/LPM match fields are supported now. 5 | # All 3 fields (protocol, src-addr, dst-addr) are mandatory. 6 | rules: 7 | - protocol: "UDP" 8 | src-addr: "192.168.99.50/32" 9 | dst-addr: "192.168.99.20/32" 10 | - protocol: "TCP" 11 | src-addr: "192.168.99.50/32" 12 | dst-addr: "192.168.99.20/32" 13 | - protocol: "TCP" 14 | src-addr: "192.168.99.20/32" 15 | dst-addr: "192.168.99.50/32" 16 | - protocol: "TCP" 17 | src-addr: "10.68.235.0/24" 18 | dst-addr: "10.68.235.0/24" 19 | - protocol: "TCP" 20 | src-addr: "192.168.33.50/32" 21 | dst-addr: "192.168.33.11/32" 22 | -------------------------------------------------------------------------------- /deployment/ci/Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Open Networking Foundation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | vagrant: 6 | vagrant up 7 | 8 | cluster: 9 | ansible-playbook playbook.kubecluster.yml -i inventory.ini 10 | 11 | destroy: 12 | vagrant destroy 13 | 14 | clean: 15 | ansible-playbook playbook.deletecluster.yml -i inventory.ini 16 | -------------------------------------------------------------------------------- /deployment/ci/README.md: -------------------------------------------------------------------------------- 1 | 5 | 6 | # CI test infra deployment 7 | 8 | This sub-directory contains Vagrant scripts to build a simple Kubernetes cluster (1 master, 1 worker + tester VM) that is used to run CI integration tests. 9 | 10 | The scripts are based on [Kubeclust](https://github.com/kosyfrances/kubeclust). 11 | 12 | ## Build CI test infra 13 | 14 | The scripts use `vagrant` with `libvirt` provider to boostrap VMs. Make sure you have both installed. 15 | 16 | Ansible is used to install Kubernetes cluster on the VMs. Install the required software first: 17 | 18 | ```bash 19 | $ pip install -r requirements.txt 20 | ``` 21 | 22 | To create Virtual Machines: 23 | 24 | ```bash 25 | $ make vagrant 26 | ``` 27 | 28 | To install Kubernetes cluster: 29 | 30 | ```bash 31 | $ make cluster 32 | ``` 33 | 34 | ## Clean up 35 | 36 | To remove Kubernetes cluster from VMs: 37 | 38 | ```bash 39 | $ make clean 40 | ``` 41 | 42 | To destroy the entire Vagrant setup: 43 | 44 | ```bash 45 | $ make destroy 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /deployment/ci/Vagrantfile: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Open Networking Foundation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | # -*- mode: ruby -*- 6 | # vi: set ft=ruby : 7 | 8 | Vagrant.configure("2") do |config| 9 | 10 | config.vm.define "test_kubemaster" do |kubemaster| 11 | kubemaster.vm.hostname = "kubemaster" 12 | kubemaster.vm.box = "abi/ubuntu2004" 13 | kubemaster.vm.network "private_network", ip: "192.168.101.20" 14 | kubemaster.vm.provision "shell", path: "provision.sh" 15 | kubemaster.vm.provider "libvirt" do |vb| 16 | vb.memory = "2048" 17 | vb.cpus = 2 18 | end 19 | end 20 | 21 | config.vm.define "test_worker" do |worker| 22 | worker.vm.hostname = "worker" 23 | worker.vm.box = "abi/ubuntu2004" 24 | worker.vm.network "private_network", ip: "192.168.101.21" 25 | worker.vm.provision "shell", path: "provision.sh" 26 | worker.vm.provider "libvirt" do |vb| 27 | vb.memory = "2048" 28 | vb.cpus = 2 29 | end 30 | end 31 | 32 | config.vm.define "tester" do |tester| 33 | tester.vm.hostname = "tester" 34 | tester.vm.box = "abi/ubuntu2004" 35 | tester.vm.network "private_network", ip: "192.168.101.22" 36 | tester.vm.provision "shell", path: "provision.sh" 37 | tester.vm.provision "shell", path: "provision-tester.sh" 38 | tester.vm.provider "libvirt" do |vb| 39 | vb.memory = "2048" 40 | vb.cpus = 2 41 | end 42 | end 43 | 44 | end 45 | -------------------------------------------------------------------------------- /deployment/ci/inventory.ini: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | [master] 4 | 192.168.101.20 ansible_ssh_private_key_file=.vagrant/machines/test_kubemaster/libvirt/private_key ansible_ssh_user=vagrant ansible_ssh_extra_args='-o StrictHostKeyChecking=no' ansible_python_interpreter=/usr/bin/python3 5 | 6 | [worker] 7 | 192.168.101.21 ansible_ssh_private_key_file=.vagrant/machines/test_worker/libvirt/private_key ansible_ssh_user=vagrant ansible_ssh_extra_args='-o StrictHostKeyChecking=no' ansible_python_interpreter=/usr/bin/python3 8 | 9 | [tester] 10 | 192.168.101.22 ansible_ssh_private_key_file=.vagrant/machines/tester/libvirt/private_key ansible_ssh_user=vagrant ansible_ssh_extra_args='-o StrictHostKeyChecking=no' ansible_python_interpreter=/usr/bin/python3 11 | -------------------------------------------------------------------------------- /deployment/ci/playbook.deletecluster.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - hosts: master 5 | roles: 6 | - teardown 7 | -------------------------------------------------------------------------------- /deployment/ci/playbook.kubecluster.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - hosts: all 5 | become: yes 6 | roles: 7 | - docker 8 | - kubectl 9 | 10 | - hosts: master 11 | become: yes 12 | roles: 13 | - kube 14 | - master 15 | 16 | - hosts: worker 17 | become: yes 18 | roles: 19 | - kube 20 | - join 21 | 22 | - hosts: tester 23 | become: yes 24 | roles: 25 | - kubeconfig 26 | -------------------------------------------------------------------------------- /deployment/ci/provision-tester.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # Install ptf 5 | pip3 install ptf 6 | 7 | -------------------------------------------------------------------------------- /deployment/ci/provision.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | sudo apt-get -y upgrade 5 | sudo apt-get update 6 | 7 | # Install python3 for ansible 8 | sudo apt-get -y install python3 python3-pip python3-apt net-tools 9 | 10 | # Disable swap 11 | swapoff -a 12 | -------------------------------------------------------------------------------- /deployment/ci/requirements.txt: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | ansible==4.2.0 5 | ansible-base==2.10.5 6 | cffi==1.14.4 7 | cryptography==3.3.2 8 | Jinja2==2.11.3 9 | MarkupSafe==1.1.1 10 | packaging==20.8 11 | pycparser==2.20 12 | pyparsing==2.4.7 13 | PyYAML==5.4.1 14 | six==1.15.0 15 | -------------------------------------------------------------------------------- /deployment/ci/roles/docker/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Install containerd 5 | apt: 6 | name: containerd 7 | update_cache: yes 8 | 9 | - name: Install docker 10 | apt: 11 | name: docker.io 12 | update_cache: yes 13 | 14 | - name: Create the docker group 15 | group: 16 | name: docker 17 | 18 | - name: Add vagrant user to the docker group 19 | user: 20 | name: vagrant 21 | groups: docker 22 | append: yes 23 | 24 | - name: Start docker 25 | systemd: 26 | name: docker 27 | state: started 28 | enabled: yes 29 | -------------------------------------------------------------------------------- /deployment/ci/roles/join/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Reset all kubeadm installed state 5 | command: kubeadm reset --force 6 | ignore_errors: true 7 | 8 | - name: Join cluster 9 | command: '{{ hostvars[groups["master"][0]]["kubeadm_join_cmd"] }}' 10 | 11 | - name: Update kubelet configuration 12 | template: 13 | src: templates/kubelet.j2 14 | dest: /etc/systemd/system/kubelet.service.d/10-kubeadm.conf 15 | 16 | - name: Reload kubelet configuration 17 | systemd: 18 | state: restarted 19 | daemon_reload: yes 20 | name: kubelet 21 | -------------------------------------------------------------------------------- /deployment/ci/roles/join/templates/kubelet.j2: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | # Note: This dropin only works with kubeadm and kubelet v1.11+ 4 | [Service] 5 | Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf" 6 | Environment="KUBELET_CONFIG_ARGS=--config=/var/lib/kubelet/config.yaml" 7 | # Tell kubelet what IP address to use 8 | Environment="KUBELET_EXTRA_ARGS=--node-ip={{ ansible_host }}" 9 | # This is a file that "kubeadm init" and "kubeadm join" generates at runtime, populating the KUBELET_KUBEADM_ARGS variable dynamically 10 | EnvironmentFile=-/var/lib/kubelet/kubeadm-flags.env 11 | # This is a file that the user can use for overrides of the kubelet args as a last resort. Preferably, the user should use 12 | # the .NodeRegistration.KubeletExtraArgs object in the configuration files instead. KUBELET_EXTRA_ARGS should be sourced from this file. 13 | EnvironmentFile=-/etc/default/kubelet 14 | ExecStart= 15 | ExecStart=/usr/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_KUBEADM_ARGS $KUBELET_EXTRA_ARGS 16 | -------------------------------------------------------------------------------- /deployment/ci/roles/kube/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Install prerequisites 5 | apt: 6 | name: apt-transport-https 7 | update_cache: yes 8 | 9 | - name: Add apt signing key 10 | apt_key: 11 | url: https://packages.cloud.google.com/apt/doc/apt-key.gpg 12 | 13 | - name: Add to kubernetes.list 14 | lineinfile: 15 | path: /etc/apt/sources.list.d/kubernetes.list 16 | line: 'deb http://apt.kubernetes.io/ kubernetes-xenial main' 17 | create: yes 18 | 19 | - name: Install kubelet and kubeadm 20 | apt: 21 | name: ['kubelet=1.20.2-00', 'kubeadm=1.20.2-00'] 22 | update_cache: yes 23 | 24 | - name: Hold kubelet and kubeadm 25 | dpkg_selections: 26 | name: '{{ item }}' 27 | selection: hold 28 | with_items: 29 | - kubelet 30 | - kubeadm 31 | -------------------------------------------------------------------------------- /deployment/ci/roles/kubeconfig/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Transfer kubeconfig from master to tester 5 | synchronize: 6 | src: /home/vagrant/.kube 7 | dest: /home/vagrant/.kube 8 | delegate_to: kubemaster 9 | -------------------------------------------------------------------------------- /deployment/ci/roles/kubectl/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Install prerequisites 5 | apt: 6 | name: apt-transport-https 7 | update_cache: yes 8 | 9 | - name: Add apt signing key 10 | apt_key: 11 | url: https://packages.cloud.google.com/apt/doc/apt-key.gpg 12 | 13 | - name: Add to kubernetes.list 14 | lineinfile: 15 | path: /etc/apt/sources.list.d/kubernetes.list 16 | line: 'deb http://apt.kubernetes.io/ kubernetes-xenial main' 17 | create: yes 18 | 19 | - name: Install kubectl 20 | apt: 21 | name: ['kubectl'] 22 | update_cache: yes 23 | 24 | - name: Hold kubectl 25 | dpkg_selections: 26 | name: '{{ item }}' 27 | selection: hold 28 | with_items: 29 | - kubectl 30 | -------------------------------------------------------------------------------- /deployment/ci/roles/master/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Reset all kubeadm installed state 5 | command: kubeadm reset --force 6 | ignore_errors: true 7 | 8 | - name: Initialise Master node 9 | command: kubeadm init --apiserver-advertise-address=192.168.101.20 --pod-network-cidr=192.168.0.0/16 10 | register: kubeadm_output 11 | 12 | - name: Set fact for kubeadm join command which will be used later 13 | set_fact: 14 | kubeadm_join_cmd: '{{ kubeadm_output.stdout_lines[-2][:-2] }}{{ kubeadm_output.stdout_lines[-1] }}' 15 | 16 | - name: Create .kube directory 17 | become: no 18 | file: 19 | path: /home/vagrant/.kube 20 | state: directory 21 | owner: vagrant 22 | group: vagrant 23 | register: kube_dir 24 | 25 | - name: Copy kube config 26 | copy: 27 | src: /etc/kubernetes/admin.conf 28 | dest: '{{ kube_dir.path }}/config' 29 | remote_src: yes 30 | owner: vagrant 31 | group: vagrant 32 | -------------------------------------------------------------------------------- /deployment/ci/roles/teardown/tasks/main.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | - name: Drain nodes 5 | command: kubectl drain {{ item }} --delete-local-data --force --ignore-daemonsets 6 | loop: 7 | - worker 8 | - kubemaster 9 | ignore_errors: true 10 | 11 | - name: Delete nodes 12 | command: kubectl delete node {{ item }} 13 | loop: 14 | - worker 15 | - kubemaster 16 | ignore_errors: true 17 | 18 | - name: Reset kubeadm installed state 19 | command: kubeadm reset --force 20 | become: yes 21 | -------------------------------------------------------------------------------- /deployment/helm/int-host-reporter/.helmignore: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # Patterns to ignore when building packages. 5 | # This supports shell glob matching, relative path matching, and 6 | # negation (prefixed with !). Only one pattern per line. 7 | .DS_Store 8 | # Common VCS dirs 9 | .git/ 10 | .gitignore 11 | .bzr/ 12 | .bzrignore 13 | .hg/ 14 | .hgignore 15 | .svn/ 16 | # Common backup files 17 | *.swp 18 | *.bak 19 | *.tmp 20 | *.orig 21 | *~ 22 | # Various IDEs 23 | .project 24 | .idea/ 25 | *.tmproj 26 | .vscode/ 27 | -------------------------------------------------------------------------------- /deployment/helm/int-host-reporter/Chart.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | apiVersion: v2 5 | name: int-host-reporter 6 | version: 0.1.0 7 | kubeVersion: ">=1.16.0" 8 | type: application 9 | keywords: 10 | - In-band Network Telemetry 11 | - SDN 12 | - eBPF 13 | description: Host-INT -------------------------------------------------------------------------------- /deployment/helm/int-host-reporter/templates/configmap-watchlist.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | apiVersion: v1 5 | kind: ConfigMap 6 | metadata: 7 | name: int-watchlist 8 | labels: 9 | app: int-host-reporter 10 | chart: "{{ .Chart.Name }}-{{ .Chart.Version }}" 11 | release: "{{ .Release.Name }}" 12 | heritage: "{{ .Release.Service }}" 13 | data: 14 | watchlist.yaml: | 15 | rules: 16 | {{- range .Values.intWatchlistRules }} 17 | - protocol: "{{ .protocol }}" 18 | src-addr: "{{ .srcAddr }}" 19 | dst-addr: "{{ .dstAddr }}" 20 | {{- end }} -------------------------------------------------------------------------------- /deployment/helm/int-host-reporter/templates/daemonset.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | apiVersion: apps/v1 5 | kind: DaemonSet 6 | metadata: 7 | name: {{ .Values.name }} 8 | namespace: {{ .Release.Namespace }} 9 | labels: 10 | k8s-app: {{ .Values.name }} 11 | spec: 12 | selector: 13 | matchLabels: 14 | name: {{ .Values.name }} 15 | template: 16 | metadata: 17 | labels: 18 | name: {{ .Values.name }} 19 | spec: 20 | nodeSelector: 21 | kubernetes.io/os: linux 22 | hostNetwork: true 23 | containers: 24 | - name: {{ .Values.name }} 25 | image: {{ .Values.image.repository }}:{{ .Values.image.tag }} 26 | imagePullPolicy: {{ .Values.image.pullPolicy }} 27 | env: 28 | - name: LOG_LEVEL 29 | value: "{{ .Values.logLevel }}" 30 | - name: CNI 31 | value: "{{ .Values.cni }}" 32 | - name: DATA_INTERFACE 33 | value: "{{ .Values.dataInterface }}" 34 | - name: COLLECTOR 35 | value: "{{ .Values.intCollector }}" 36 | # we use Node IP as switch ID 37 | - name: NODE_IP 38 | valueFrom: 39 | fieldRef: 40 | fieldPath: status.hostIP 41 | command: ["int-host-reporter"] 42 | args: ["--cni", "$(CNI)", "--log-level", "$(LOG_LEVEL)", "--data-interface", "$(DATA_INTERFACE)", "--collector", "$(COLLECTOR)", "--switch-id", "$(NODE_IP)", "-f", "/etc/watchlist/watchlist.yaml"] 43 | volumeMounts: 44 | - name: bpffs 45 | mountPath: /sys/fs/bpf 46 | - name: int-watchlist 47 | mountPath: /etc/watchlist/watchlist.yaml 48 | subPath: watchlist.yaml 49 | securityContext: 50 | privileged: true 51 | capabilities: 52 | add: [ "NET_ADMIN","NET_RAW" ] 53 | volumes: 54 | - name: bpffs 55 | hostPath: 56 | path: /sys/fs/bpf 57 | - name: int-watchlist 58 | configMap: 59 | name: int-watchlist 60 | -------------------------------------------------------------------------------- /deployment/helm/int-host-reporter/values.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | name: int-host-reporter 5 | 6 | image: 7 | repository: opennetworking/int-host-reporter 8 | pullPolicy: Always 9 | # Overrides the image tag whose default is the chart appVersion. 10 | tag: "latest" 11 | 12 | # CNI in use, possible values: cilium, calico-ebpf, calico-iptables 13 | cni: cilium 14 | dataInterface: enp0s8 15 | intCollector: 192.168.33.50:30001 16 | # Log level values: info, debug, trace 17 | logLevel: info 18 | 19 | intWatchlistRules: 20 | - protocol: "UDP" 21 | srcAddr: "192.168.99.50/32" 22 | dstAddr: "192.168.99.20/32" 23 | - protocol: "TCP" 24 | srcAddr: "192.168.99.50/32" 25 | dstAddr: "192.168.99.20/32" 26 | - protocol: "TCP" 27 | srcAddr: "192.168.99.20/32" 28 | dstAddr: "192.168.99.50/32" 29 | - protocol: "TCP" 30 | srcAddr: "10.68.235.0/24" 31 | dstAddr: "10.68.235.0/24" 32 | - protocol: "TCP" 33 | srcAddr: "192.168.33.50/32" 34 | dstAddr: "192.168.33.11/32" 35 | - protocol: "TCP" 36 | srcAddr: "192.168.33.11/32" 37 | dstAddr: "192.168.33.50/32" -------------------------------------------------------------------------------- /deployment/kubernetes/inthostreporter.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | --- 4 | apiVersion: apps/v1 5 | kind: DaemonSet 6 | metadata: 7 | name: int-host-reporter 8 | namespace: kube-system 9 | labels: 10 | k8s-app: int-host-reporter 11 | spec: 12 | selector: 13 | matchLabels: 14 | name: int-host-reporter 15 | template: 16 | metadata: 17 | labels: 18 | name: int-host-reporter 19 | spec: 20 | nodeSelector: 21 | kubernetes.io/os: linux 22 | hostNetwork: true 23 | containers: 24 | - name: int-host-reporter 25 | image: opennetworking/int-host-reporter:cilium-dev 26 | imagePullPolicy: "IfNotPresent" 27 | env: 28 | - name: LOG_LEVEL 29 | value: "info" 30 | - name: CNI 31 | value: "cilium" 32 | - name: DATA_INTERFACE 33 | value: "enp0s8" 34 | - name: COLLECTOR 35 | value: "192.168.33.50:30001" 36 | # we use Node IP as switch ID 37 | - name: NODE_IP 38 | valueFrom: 39 | fieldRef: 40 | fieldPath: status.hostIP 41 | command: ["int-host-reporter"] 42 | args: ["--cni", "$(CNI)", "--log-level", "$(LOG_LEVEL)","--data-interface", "$(DATA_INTERFACE)", "--collector", "$(COLLECTOR)", "--switch-id", "$(NODE_IP)", "-f", "/etc/watchlist/watchlist.yaml"] 43 | volumeMounts: 44 | - name: bpffs 45 | mountPath: /sys/fs/bpf 46 | - name: watchlist 47 | mountPath: /etc/watchlist/watchlist.yaml 48 | subPath: watchlist.yaml 49 | securityContext: 50 | privileged: true 51 | capabilities: 52 | add: [ "NET_ADMIN","NET_RAW" ] 53 | volumes: 54 | - name: bpffs 55 | hostPath: 56 | path: /sys/fs/bpf 57 | - name: watchlist 58 | configMap: 59 | name: watchlist-conf 60 | -------------------------------------------------------------------------------- /docs/static/images/design.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opennetworkinglab/int-host-reporter/91db10513566a61ee08c86c0320a31784cb9bb32/docs/static/images/design.png -------------------------------------------------------------------------------- /docs/static/images/di-topo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opennetworkinglab/int-host-reporter/91db10513566a61ee08c86c0320a31784cb9bb32/docs/static/images/di-topo.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/opennetworkinglab/int-host-reporter 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/cilium/ebpf v0.5.0 7 | github.com/gin-gonic/gin v1.7.4 8 | github.com/google/gopacket v1.1.19 9 | github.com/sirupsen/logrus v1.8.1 10 | github.com/vishvananda/netlink v1.1.0 11 | github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f // indirect 12 | golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect 13 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b 14 | ) 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cilium/ebpf v0.5.0 h1:E1KshmrMEtkMP2UjlWzfmUV1owWY+BnbL5FxxuatnrU= 2 | github.com/cilium/ebpf v0.5.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/frankban/quicktest v1.11.3 h1:8sXhOn0uLys67V8EsXLc6eszDs8VXWxL3iRvebPhedY= 7 | github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= 8 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 9 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 10 | github.com/gin-gonic/gin v1.7.4 h1:QmUZXrvJ9qZ3GfWvQ+2wnW/1ePrTEJqPKMYEU3lD/DM= 11 | github.com/gin-gonic/gin v1.7.4/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= 12 | github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= 13 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 14 | github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= 15 | github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= 16 | github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= 17 | github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= 18 | github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= 19 | github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= 20 | github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= 21 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 22 | github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= 23 | github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 24 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 25 | github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= 26 | github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= 27 | github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= 28 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 29 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 30 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 31 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 32 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 33 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 34 | github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= 35 | github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= 36 | github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= 37 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 38 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= 39 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 40 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= 41 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 42 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 43 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 44 | github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= 45 | github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 46 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 47 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 48 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 49 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 50 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 51 | github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= 52 | github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= 53 | github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= 54 | github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= 55 | github.com/vishvananda/netlink v1.1.0 h1:1iyaYNBLmP6L0220aDnYQpo1QEV4t4hJ+xEEhhJH8j0= 56 | github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= 57 | github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= 58 | github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f h1:p4VB7kIXpOQvVn1ZaTIVp+3vuYAXFe3OJEvjbUYJLaA= 59 | github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= 60 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 61 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 62 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= 63 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 64 | golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= 65 | golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= 66 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 67 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 68 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 69 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 70 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 71 | golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 72 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 73 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 74 | golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 75 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 76 | golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf h1:2ucpDCmfkl8Bd/FsLtiD653Wf96cW37s+iGx93zsu4k= 77 | golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 78 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 79 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 80 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 81 | golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= 82 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 83 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 84 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 85 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 86 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 87 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 88 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 89 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 90 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= 91 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 92 | -------------------------------------------------------------------------------- /pkg/common/contants.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package common 5 | 6 | type CNIType uint32 7 | 8 | const ( 9 | CNITypeCilium = iota 10 | CNITypeCalicoEBPF 11 | CNITypeCalicoIPTables 12 | ) 13 | 14 | const ( 15 | INTWatchlistProtoSrcAddrMap = "WATCHLIST_PROTO_SRCADDR_MAP" 16 | 17 | INTWatchlistDstAddrMap = "WATCHLIST_DSTADDR_MAP" 18 | 19 | INTEventsMap = "INT_EVENTS_MAP" 20 | 21 | INTSharedMap = "SHARED_MAP" 22 | 23 | // DefaultMapRoot is the default path where BPFFS should be mounted 24 | DefaultMapRoot = "/sys/fs/bpf" 25 | 26 | // DefaultMapPrefix is the default prefix for all BPF maps. 27 | DefaultMapPrefix = "tc/globals" 28 | ) 29 | 30 | const ( 31 | // Common drop reasons 32 | DropReasonUnknown = 0 33 | DropReasonIPVersionInvalid = 25 34 | DropReasonIPTTLZero = 26 35 | DropReasonIPIHLInvalid = 30 36 | DropReasonIPInvalidChecksum = 31 37 | DropReasonRoutingMiss = 29 38 | DropReasonPortVLANMappingMiss = 55 39 | DropReasonTrafficManager = 71 40 | DropReasonACLDeny = 80 41 | DropReasonBridginMiss = 89 42 | 43 | // Calico-specific drop reasons 44 | DropReasonEncapFail = 180 45 | DropReasonDecapFail = 181 46 | DropReasonChecksumFail = 182 47 | DropReasonIPOptions = 183 48 | DropReasonUnauthSource = 184 49 | ) 50 | -------------------------------------------------------------------------------- /pkg/common/globals.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package common 5 | 6 | import "flag" 7 | 8 | var CNITypeInUse CNIType 9 | 10 | var ( 11 | DataInterface = flag.String("data-interface", "", "") 12 | ) 13 | -------------------------------------------------------------------------------- /pkg/common/helpers.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package common 5 | 6 | import ( 7 | "fmt" 8 | log "github.com/sirupsen/logrus" 9 | "io" 10 | "net" 11 | "os" 12 | "strings" 13 | ) 14 | 15 | const ( 16 | // PossibleCPUSysfsPath is used to retrieve the number of CPUs for per-CPU maps. 17 | PossibleCPUSysfsPath = "/sys/devices/system/cpu/possible" 18 | ) 19 | 20 | func ToNetIP(val uint32) net.IP { 21 | return net.IPv4(byte(val&0xFF), byte(val>>8)&0xFF, 22 | byte(val>>16)&0xFF, byte(val>>24)&0xFF) 23 | } 24 | 25 | func ParseCNIType(cniName string) error { 26 | if cniName == "" { 27 | return fmt.Errorf("CNI implementation not provided") 28 | } 29 | 30 | switch cniName { 31 | case "cilium": 32 | CNITypeInUse = CNITypeCilium 33 | case "calico-ebpf": 34 | CNITypeInUse = CNITypeCalicoEBPF 35 | case "calico-iptables": 36 | CNITypeInUse = CNITypeCalicoIPTables 37 | default: 38 | return fmt.Errorf("CNI type not supported") 39 | } 40 | 41 | return nil 42 | } 43 | 44 | func IsManagedByCilium(intfName string) bool { 45 | if strings.Contains(intfName, "lxc") && intfName != "lxc_health" { 46 | return true 47 | } 48 | 49 | return false 50 | } 51 | 52 | func IsManagedByCalico(intfName string) bool { 53 | if strings.Contains(intfName, "cali") && intfName != "vxlan.calico" { // Calico 54 | return true 55 | } 56 | return false 57 | } 58 | 59 | func IsInterfaceManagedByCNI(intfName string) bool { 60 | switch CNITypeInUse { 61 | case CNITypeCilium: 62 | return IsManagedByCilium(intfName) 63 | case CNITypeCalicoEBPF, CNITypeCalicoIPTables: 64 | return IsManagedByCalico(intfName) 65 | default: 66 | return false 67 | } 68 | } 69 | 70 | func GetNumPossibleCPUs() int { 71 | f, err := os.Open(PossibleCPUSysfsPath) 72 | if err != nil { 73 | log.WithError(err).Errorf("unable to open %q", PossibleCPUSysfsPath) 74 | return 0 75 | } 76 | defer f.Close() 77 | 78 | return getNumPossibleCPUsFromReader(f) 79 | } 80 | 81 | func getNumPossibleCPUsFromReader(r io.Reader) int { 82 | out, err := io.ReadAll(r) 83 | if err != nil { 84 | log.WithError(err).Errorf("unable to read %q to get CPU count", PossibleCPUSysfsPath) 85 | return 0 86 | } 87 | 88 | var start, end int 89 | count := 0 90 | for _, s := range strings.Split(string(out), ",") { 91 | // Go's scanf will return an error if a format cannot be fully matched. 92 | // So, just ignore it, as a partial match (e.g. when there is only one 93 | // CPU) is expected. 94 | n, err := fmt.Sscanf(s, "%d-%d", &start, &end) 95 | 96 | switch n { 97 | case 0: 98 | log.WithError(err).Errorf("failed to scan %q to retrieve number of possible CPUs!", s) 99 | return 0 100 | case 1: 101 | count++ 102 | default: 103 | count += (end - start + 1) 104 | } 105 | } 106 | 107 | return count 108 | } 109 | -------------------------------------------------------------------------------- /pkg/dataplane/dataplane_event.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package dataplane 5 | 6 | import ( 7 | "encoding/binary" 8 | "fmt" 9 | "github.com/google/gopacket" 10 | "github.com/google/gopacket/layers" 11 | log "github.com/sirupsen/logrus" 12 | "net" 13 | ) 14 | 15 | type DatapathReportType uint8 16 | 17 | // DataPlaneReportSize 18 | // IMPORTANT! 19 | // Keep in sync with DatapathReport. 20 | const ( 21 | DataPlaneReportSize = 40 22 | ) 23 | 24 | // IMPORTANT! 25 | // Keep in sync with data plane. 26 | const ( 27 | TraceReport DatapathReportType = 1 28 | DropReport DatapathReportType = 2 29 | ) 30 | 31 | var ( 32 | LayerTypeDataPlaneReport = gopacket.RegisterLayerType(1000, gopacket.LayerTypeMetadata{ 33 | Name: "DatapathReport", 34 | Decoder: gopacket.DecodeFunc(decodeDataPlaneReport), 35 | }) 36 | ) 37 | 38 | type Event struct { 39 | Data []byte 40 | CPU int 41 | } 42 | 43 | // DatapathReport 44 | // IMPORTANT! 45 | // This struct must be kept in sync with 'struct dp_event` from bpf-gpl/fib.h (calico-felix). 46 | type DatapathReport struct { 47 | layers.BaseLayer 48 | Type DatapathReportType 49 | Reason uint8 50 | PreNATSourceIP net.IP 51 | PreNATDestinationIP net.IP 52 | PreNATSourcePort uint16 53 | PreNATDestinationPort uint16 54 | IngressPort uint32 55 | EgressPort uint32 56 | IngressTimestamp uint64 57 | EgressTimestamp uint64 58 | } 59 | 60 | func (dpr *DatapathReport) String() string { 61 | return fmt.Sprintf("DatapathReport(type=%d, reason=%d, "+ 62 | "PreNATSourceIP=%s, "+ 63 | "PreNATDestinationIP=%s, "+ 64 | "PreNATSourcePort=%d, "+ 65 | "PreNATDestinationPort=%d, "+ 66 | "IngressPort=%d, "+ 67 | "EgressPort=%d, "+ 68 | "IngressTimestamp=%v, "+ 69 | "EgressTimeStamp=%v)", 70 | dpr.Type, dpr.Reason, dpr.PreNATSourceIP.String(), 71 | dpr.PreNATDestinationIP.String(), dpr.PreNATSourcePort, 72 | dpr.PreNATDestinationPort, dpr.IngressPort, dpr.EgressPort, 73 | dpr.IngressTimestamp, dpr.EgressTimestamp) 74 | } 75 | 76 | func (dpr *DatapathReport) LayerType() gopacket.LayerType { 77 | return LayerTypeDataPlaneReport 78 | } 79 | 80 | // CanDecode returns the set of layer types that this DecodingLayer can decode. 81 | func (dpr *DatapathReport) CanDecode() gopacket.LayerClass { 82 | return LayerTypeDataPlaneReport 83 | } 84 | 85 | func (dpr *DatapathReport) NextLayerType() gopacket.LayerType { 86 | return layers.LayerTypeEthernet 87 | } 88 | 89 | func (dpr *DatapathReport) DecodeFromBytes(data []byte, p gopacket.PacketBuilder) error { 90 | if len(data) < DataPlaneReportSize { 91 | return fmt.Errorf("invalid data plane report. Length %d less than %d", 92 | len(data), DataPlaneReportSize) 93 | } 94 | dpr.Type = DatapathReportType(data[0]) 95 | dpr.Reason = uint8(data[1]) 96 | // 2 bytes of padding 97 | srcIPv4 := binary.LittleEndian.Uint32(data[4:8]) 98 | dpr.PreNATSourceIP = make(net.IP, 4) 99 | binary.LittleEndian.PutUint32(dpr.PreNATSourceIP, srcIPv4) 100 | dstIPv4 := binary.LittleEndian.Uint32(data[8:12]) 101 | dpr.PreNATDestinationIP = make(net.IP, 4) 102 | binary.LittleEndian.PutUint32(dpr.PreNATDestinationIP, dstIPv4) 103 | dpr.PreNATSourcePort = binary.BigEndian.Uint16(data[12:14]) 104 | dpr.PreNATDestinationPort = binary.BigEndian.Uint16(data[14:16]) 105 | dpr.IngressPort = binary.LittleEndian.Uint32(data[16:20]) 106 | dpr.EgressPort = binary.LittleEndian.Uint32(data[20:24]) 107 | dpr.IngressTimestamp = binary.LittleEndian.Uint64(data[24:32]) 108 | dpr.EgressTimestamp = binary.LittleEndian.Uint64(data[32:40]) 109 | 110 | dpr.BaseLayer = layers.BaseLayer{Contents: data} 111 | dpr.Contents = data[:DataPlaneReportSize] 112 | dpr.Payload = data[DataPlaneReportSize:] 113 | return nil 114 | } 115 | 116 | func decodeDataPlaneReport(data []byte, p gopacket.PacketBuilder) error { 117 | dpr := &DatapathReport{} 118 | err := dpr.DecodeFromBytes(data, p) 119 | if err != nil { 120 | return err 121 | } 122 | p.AddLayer(dpr) 123 | next := dpr.NextLayerType() 124 | if next == gopacket.LayerTypeZero { 125 | return nil 126 | } 127 | return p.NextDecoder(next) 128 | } 129 | 130 | type PacketMetadata struct { 131 | DataPlaneReport *DatapathReport 132 | EncapMode string 133 | DstAddr net.IP 134 | SrcAddr net.IP 135 | Protocol uint8 136 | DstPort uint16 137 | SrcPort uint16 138 | 139 | MatchedPostNAT bool 140 | 141 | // raw data of the data plane packet. DataPlaneReport is excluded. 142 | RawData []byte 143 | 144 | // IP layer 145 | IPLayer *layers.IPv4 146 | } 147 | 148 | func (dpe Event) Parse() *PacketMetadata { 149 | pktMd := &PacketMetadata{ 150 | EncapMode: "none", 151 | MatchedPostNAT: false, 152 | } 153 | pktMd.RawData = dpe.Data[DataPlaneReportSize:] 154 | parsedPacket := gopacket.NewPacket(dpe.Data, LayerTypeDataPlaneReport, gopacket.Default) 155 | log.Trace(parsedPacket.Dump()) 156 | if dataPlaneReportLayer := parsedPacket.Layer(LayerTypeDataPlaneReport); dataPlaneReportLayer != nil { 157 | pktMd.DataPlaneReport = dataPlaneReportLayer.(*DatapathReport) 158 | if vxlanLayer := parsedPacket.Layer(layers.LayerTypeVXLAN); vxlanLayer != nil { 159 | // TODO: we support only VXLAN in the PoC 160 | pktMd.EncapMode = "vxlan" 161 | // if VXLAN exists it means we received reports from the "relay" node and we need to look deeper. 162 | parsedPacket = gopacket.NewPacket(vxlanLayer.LayerPayload(), layers.LayerTypeEthernet, gopacket.Default) 163 | } 164 | if ipv4Layer := parsedPacket.Layer(layers.LayerTypeIPv4); ipv4Layer != nil { 165 | ipv4, _ := ipv4Layer.(*layers.IPv4) 166 | pktMd.IPLayer = ipv4 167 | pktMd.DstAddr = ipv4.DstIP.To4() 168 | pktMd.SrcAddr = ipv4.SrcIP.To4() 169 | pktMd.Protocol = uint8(ipv4.Protocol) 170 | if l4Layer := parsedPacket.Layer(ipv4.NextLayerType()); l4Layer != nil { 171 | switch ipv4.Protocol { 172 | case layers.IPProtocolTCP: 173 | tcp, _ := l4Layer.(*layers.TCP) 174 | pktMd.SrcPort = uint16(tcp.SrcPort) 175 | pktMd.DstPort = uint16(tcp.DstPort) 176 | case layers.IPProtocolUDP: 177 | udp, _ := l4Layer.(*layers.UDP) 178 | pktMd.SrcPort = uint16(udp.SrcPort) 179 | pktMd.DstPort = uint16(udp.DstPort) 180 | } 181 | } 182 | } 183 | } 184 | 185 | // FIXME: commented out at least for now; as it's not decided yet whether to report pre- or post-NAT'ed tuple to INT collector 186 | //if pktMd.DatapathReport.PreNATDestinationPort != 0 && !pktMd.DatapathReport.PreNATDestinationIP.IsUnspecified() { 187 | // pktMd.DstPort = pktMd.DatapathReport.PreNATDestinationPort 188 | // copy(pktMd.DstAddr, pktMd.DatapathReport.PreNATDestinationIP) 189 | //} 190 | 191 | return pktMd 192 | } 193 | -------------------------------------------------------------------------------- /pkg/dataplane/dataplane_interface.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package dataplane 5 | 6 | import ( 7 | "bytes" 8 | "context" 9 | "encoding/binary" 10 | "fmt" 11 | "github.com/cilium/ebpf" 12 | "github.com/cilium/ebpf/perf" 13 | "github.com/google/gopacket/layers" 14 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 15 | "github.com/opennetworkinglab/int-host-reporter/pkg/watchlist" 16 | log "github.com/sirupsen/logrus" 17 | "math/bits" 18 | "net" 19 | "os" 20 | "time" 21 | ) 22 | 23 | type EBPFDatapathInterface struct { 24 | eventsChannel chan *PacketMetadata 25 | 26 | watchlistMapProtoSrcAddr *ebpf.Map 27 | watchlistMapDstAddr *ebpf.Map 28 | 29 | sharedMap *ebpf.Map 30 | 31 | ingressSeqNumMap *ebpf.Map 32 | egressSeqNumMap *ebpf.Map 33 | 34 | perfEventArray *ebpf.Map 35 | dataPlaneReader *perf.Reader 36 | } 37 | 38 | type SharedMapKey struct { 39 | PacketIdentifier uint64 40 | FlowHash uint32 41 | Padding uint32 42 | } 43 | 44 | type SharedMapValue struct { 45 | IngressTimestamp uint64 46 | IngressPort uint32 47 | PreNATIPDest uint32 48 | PreNATIPSource uint32 49 | PreNATProto uint16 50 | Padding0 uint16 51 | PreNATSourcePort uint16 52 | PreNATDestPort uint16 53 | SeqNo uint16 54 | SeenByUserspace uint16 55 | } 56 | 57 | type IngressSeqNumValue struct { 58 | IngressTimestamp uint64 59 | IngressPort uint32 60 | SeqNum uint32 61 | SrcIP uint32 62 | DstIP uint32 63 | IPProtocol uint32 64 | SourcePort uint16 65 | DestPort uint16 66 | } 67 | 68 | func (key SharedMapKey) String() string { 69 | return fmt.Sprintf("SharedMapKey={packet-identifier=%v, flow_hash=%x}", 70 | key.PacketIdentifier, key.FlowHash) 71 | } 72 | 73 | func (value SharedMapValue) String() string { 74 | return fmt.Sprintf("SharedMapValue={ig_timestamp=%v, ig_port=%v, pre-nat-ip-dst=%v,"+ 75 | "pre-nat-ip-src=%v, pre-nat-source-port=%v, pre-nat-dest-port=%v, seen-by-userspace=%v}", 76 | value.IngressTimestamp, value.IngressPort, 77 | common.ToNetIP(value.PreNATIPDest).String(), 78 | common.ToNetIP(value.PreNATIPSource).String(), 79 | bits.ReverseBytes16(value.PreNATSourcePort), 80 | bits.ReverseBytes16(value.PreNATDestPort), value.SeenByUserspace) 81 | } 82 | 83 | func init() { 84 | // clear SHARED_MAP; ignore err 85 | os.Remove(common.DefaultMapRoot + "/" + common.DefaultMapPrefix + "/" + common.INTSharedMap) 86 | // clear INT_EVENTS_MAP; ignore err 87 | os.Remove(common.DefaultMapRoot + "/" + common.DefaultMapPrefix + "/" + common.INTEventsMap) 88 | } 89 | 90 | func NewDataPlaneInterface() *EBPFDatapathInterface { 91 | return &EBPFDatapathInterface{} 92 | } 93 | 94 | func (d *EBPFDatapathInterface) SetEventChannel(ch chan *PacketMetadata) { 95 | d.eventsChannel = ch 96 | } 97 | 98 | func (d *EBPFDatapathInterface) Init() error { 99 | layers.RegisterUDPPortLayerType(8472, layers.LayerTypeVXLAN) 100 | 101 | commonPath := common.DefaultMapRoot + "/" + common.DefaultMapPrefix 102 | path := commonPath + "/" + common.INTSharedMap 103 | sharedMap, err := ebpf.LoadPinnedMap(path, nil) 104 | if err != nil { 105 | return err 106 | } 107 | d.sharedMap = sharedMap 108 | 109 | path = commonPath + "/" + common.INTEventsMap 110 | eventsMap, err := ebpf.LoadPinnedMap(path, nil) 111 | if err != nil { 112 | return err 113 | } 114 | d.perfEventArray = eventsMap 115 | 116 | // TODO (tomasz): make it configurable 117 | bufferSize := 100 118 | events, err := perf.NewReader(d.perfEventArray, bufferSize) 119 | if err != nil { 120 | return err 121 | } 122 | d.dataPlaneReader = events 123 | return nil 124 | } 125 | 126 | func (d *EBPFDatapathInterface) Start(stopCtx context.Context) error { 127 | defer func() { 128 | d.dataPlaneReader.Close() 129 | }() 130 | log.Infof("Listening for perf events from %s", d.perfEventArray.String()) 131 | for { 132 | select { 133 | case <-stopCtx.Done(): 134 | log.Info("Data plane interface has stopped listening to events..") 135 | return nil 136 | default: 137 | { 138 | record, err := d.dataPlaneReader.Read() 139 | if err != nil { 140 | log.Warnf("Error received while reading from perf buffer: %v", err) 141 | continue 142 | } 143 | d.processPerfRecord(record) 144 | } 145 | } 146 | } 147 | } 148 | 149 | func (d *EBPFDatapathInterface) Stop() { 150 | d.dataPlaneReader.Close() 151 | } 152 | 153 | func (d *EBPFDatapathInterface) doDetectPacketDrops() { 154 | var key SharedMapKey 155 | var value SharedMapValue 156 | iter := d.sharedMap.Iterate() 157 | for iter.Next(&key, &value) { 158 | err := d.sharedMap.Lookup(&key, &value) 159 | if err != nil { 160 | log.Debugf("failed to lookup from shared map: %v", err) 161 | continue 162 | } 163 | 164 | if value.SeenByUserspace == 1 { 165 | pktMd := PacketMetadata{ 166 | DataPlaneReport: &DatapathReport{ 167 | Type: DropReport, 168 | Reason: common.DropReasonUnknown, 169 | PreNATSourceIP: common.ToNetIP(value.PreNATIPSource), 170 | PreNATDestinationIP: common.ToNetIP(value.PreNATIPDest), 171 | PreNATSourcePort: bits.ReverseBytes16(value.PreNATSourcePort), 172 | PreNATDestinationPort: bits.ReverseBytes16(value.PreNATDestPort), 173 | IngressPort: value.IngressPort, 174 | EgressPort: 0, 175 | IngressTimestamp: value.IngressTimestamp, 176 | EgressTimestamp: 0, 177 | }, 178 | EncapMode: "", 179 | DstAddr: net.IPv4zero, 180 | SrcAddr: net.IPv4zero, 181 | Protocol: uint8(value.PreNATProto), 182 | DstPort: 0, 183 | SrcPort: 0, 184 | } 185 | 186 | d.eventsChannel <- &pktMd 187 | 188 | // this is the second time we see this entry, 189 | // so it's very likely that this packet haven't reached any egress program. 190 | // Therefore, we can delete it from map and report a potential packet drop. 191 | err = d.sharedMap.Delete(&key) 192 | if err != nil { 193 | log.Debugf("failed to delete key %v from shared map: %v", key, err) 194 | } 195 | log.WithFields(log.Fields{ 196 | "key": key, 197 | "value": value, 198 | }).Trace("Deleted entry from map") 199 | continue 200 | } 201 | 202 | value.SeenByUserspace = 1 203 | 204 | err = d.sharedMap.Put(&key, &value) 205 | if err != nil { 206 | log.Debugf("Failed to set seen-by-userspace flag") 207 | continue 208 | } 209 | 210 | log.WithFields(log.Fields{ 211 | "key": key, 212 | "value": value, 213 | }).Trace("seen-by-userspace flag set for entry") 214 | } 215 | time.Sleep(time.Second) 216 | } 217 | 218 | func (d *EBPFDatapathInterface) DetectPacketDrops(stopCtx context.Context) { 219 | log.Debug("Starting packet drop detection process..") 220 | for { 221 | select { 222 | case <-stopCtx.Done(): 223 | log.Info("Packet drop detection has stopped..") 224 | return 225 | default: 226 | d.doDetectPacketDrops() 227 | } 228 | } 229 | } 230 | 231 | func calculateBitVectorForProtoSrcAddrMap(protocol uint32, srcAddr net.IPNet, allRules []watchlist.INTWatchlistRule) uint64 { 232 | log.Debugf("Calculating BitVector for Protocol=%v, SrcAddr=%v", protocol, srcAddr) 233 | var bitvector uint64 234 | for idx, rule := range allRules { 235 | if protocol == uint32(rule.GetProtocol()) && 236 | (rule.GetSrcAddr().IP.Equal(srcAddr.IP) && bytes.Equal(rule.GetSrcAddr().Mask, srcAddr.Mask)) { 237 | bitvector = bitvector | (1 << idx) 238 | } 239 | } 240 | return bitvector 241 | } 242 | 243 | func calculateBitVectorForDstAddr(dstAddr net.IPNet, allRules []watchlist.INTWatchlistRule) uint64 { 244 | log.Debugf("Calculating BitVector for DstAddr=%v", dstAddr) 245 | var bitvector uint64 246 | for idx, rule := range allRules { 247 | if rule.GetDstAddr().IP.Equal(dstAddr.IP) && bytes.Equal(rule.GetDstAddr().Mask, dstAddr.Mask) { 248 | bitvector = bitvector | (1 << idx) 249 | } 250 | } 251 | return bitvector 252 | } 253 | 254 | func (d *EBPFDatapathInterface) UpdateWatchlist(protocol uint8, srcAddr net.IPNet, dstAddr net.IPNet, allRules []watchlist.INTWatchlistRule) error { 255 | keyProtoSrcAddr := struct { 256 | prefixlen uint32 257 | protocol uint32 258 | saddr uint32 259 | }{} 260 | ones, _ := srcAddr.Mask.Size() 261 | keyProtoSrcAddr.prefixlen = 32 + uint32(ones) 262 | keyProtoSrcAddr.protocol = uint32(protocol) 263 | keyProtoSrcAddr.saddr = binary.LittleEndian.Uint32(srcAddr.IP.To4()) 264 | 265 | value := calculateBitVectorForProtoSrcAddrMap(uint32(protocol), srcAddr, allRules) 266 | log.Debugf("Bitvector for protoSrcAddr: %x", value) 267 | err := d.watchlistMapProtoSrcAddr.Update(keyProtoSrcAddr, value, ebpf.UpdateAny) 268 | if err != nil { 269 | log.Errorf("failed to insert watchlist entry: %v", err) 270 | return err 271 | } 272 | 273 | keyDstAddr := struct { 274 | prefixlen uint32 275 | daddr uint32 276 | }{} 277 | ones, _ = dstAddr.Mask.Size() 278 | keyDstAddr.prefixlen = uint32(ones) 279 | keyDstAddr.daddr = binary.LittleEndian.Uint32(dstAddr.IP.To4()) 280 | value = calculateBitVectorForDstAddr(dstAddr, allRules) 281 | log.Debugf("Bitvector for DstAddr: %x", value) 282 | err = d.watchlistMapDstAddr.Update(keyDstAddr, value, ebpf.UpdateAny) 283 | if err != nil { 284 | log.Errorf("failed to insert watchlist entry: %v", err) 285 | return err 286 | } 287 | 288 | return nil 289 | } 290 | 291 | func (d *EBPFDatapathInterface) processPerfRecord(record perf.Record) { 292 | log.WithFields(log.Fields{ 293 | "CPU": record.CPU, 294 | "HasLostSamples": record.LostSamples > 0, 295 | "DataSize": len(record.RawSample), 296 | }).Trace("perf event read") 297 | 298 | if record.LostSamples > 0 { 299 | log.WithFields(log.Fields{ 300 | "lost": record.LostSamples, 301 | }).Warn("Records has been lost because ring buffer is full, consider to increase size?") 302 | return 303 | } 304 | 305 | event := Event{ 306 | Data: record.RawSample, 307 | CPU: record.CPU, 308 | } 309 | pktMd := event.Parse() 310 | select { 311 | case d.eventsChannel <- pktMd: 312 | default: 313 | log.Warn("Dropped event because events channel is full or closed") 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /pkg/inthostreporter/handler.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package inthostreporter 5 | 6 | import ( 7 | "encoding/binary" 8 | "flag" 9 | "fmt" 10 | "github.com/opennetworkinglab/int-host-reporter/pkg/dataplane" 11 | "github.com/opennetworkinglab/int-host-reporter/pkg/packet" 12 | "github.com/opennetworkinglab/int-host-reporter/pkg/watchlist" 13 | log "github.com/sirupsen/logrus" 14 | "math" 15 | "net" 16 | "strconv" 17 | ) 18 | 19 | const ( 20 | // TODO (tomasz): make it configurable 21 | rxChannelSize = 100 22 | rxWorkers = 2 23 | ) 24 | 25 | var ( 26 | INTCollectorServer = flag.String("collector", "", "Address (IP:Port) of the INT collector server.") 27 | // FIXME: we provide Switch ID as a command line argument for now; it should be probably configured via ConfigMap. 28 | INTSwitchID = flag.String("switch-id", "", "Switch ID used by INT Host Reporter to identify the end host") 29 | ) 30 | 31 | type ReportHandler struct { 32 | switchID uint32 33 | 34 | // thread-safe 35 | udpConn *net.UDPConn 36 | 37 | watchlist []watchlist.INTWatchlistRule 38 | reportsChannel chan *dataplane.PacketMetadata 39 | dataPlaneInterface *dataplane.EBPFDatapathInterface 40 | } 41 | 42 | func NewReportHandler(dpi *dataplane.EBPFDatapathInterface) *ReportHandler { 43 | rh := &ReportHandler{} 44 | rh.dataPlaneInterface = dpi 45 | rh.reportsChannel = make(chan *dataplane.PacketMetadata, rxChannelSize) 46 | return rh 47 | } 48 | 49 | func (rh *ReportHandler) SetINTWatchlist(watchlist []watchlist.INTWatchlistRule) { 50 | rh.watchlist = watchlist 51 | } 52 | 53 | func getSwitchID() (uint32, error) { 54 | swID, err := strconv.ParseUint(*INTSwitchID, 10, 32) 55 | if err == nil { 56 | return uint32(swID), nil 57 | } 58 | 59 | // try IP format 60 | ip := net.ParseIP(*INTSwitchID).To4() 61 | if ip != nil { 62 | return binary.BigEndian.Uint32(ip), nil 63 | } 64 | 65 | return 0, fmt.Errorf("unsupported format of switch ID") 66 | } 67 | 68 | func (rh *ReportHandler) Start() error { 69 | // TODO: use github.com/jessevdk/go-flags to configure mandatory flags. 70 | if *INTCollectorServer == "" || *INTSwitchID == "" { 71 | log.Fatal("The required flags are not provided") 72 | } 73 | 74 | switchID, err := getSwitchID() 75 | if err != nil { 76 | log.Fatalf("Failed to start: %v", err) 77 | } 78 | rh.switchID = switchID 79 | log.Debugf("INT Host Reporter will use switch ID = %v", rh.switchID) 80 | 81 | remoteAddr, err := net.ResolveUDPAddr("udp", *INTCollectorServer) 82 | if err != nil { 83 | return err 84 | } 85 | 86 | conn, err := net.DialUDP("udp", &net.UDPAddr{}, remoteAddr) 87 | if err != nil { 88 | return err 89 | } 90 | rh.udpConn = conn 91 | 92 | rh.dataPlaneInterface.SetEventChannel(rh.reportsChannel) 93 | for i := 0; i < rxWorkers; i++ { 94 | log.Debugf("Starting RX worker %d listening for data plane events.", i) 95 | go rh.rxFn(i) 96 | } 97 | 98 | log.Debug("All RX workers started.") 99 | return nil 100 | } 101 | 102 | func (rh *ReportHandler) Stop() { 103 | rh.udpConn.Close() 104 | close(rh.reportsChannel) 105 | } 106 | 107 | func (rh *ReportHandler) applyWatchlist(pktMd *dataplane.PacketMetadata) bool { 108 | packetLog := log.Fields{ 109 | "protocol": pktMd.Protocol, 110 | "src-addr": pktMd.SrcAddr.String(), 111 | "dst-addr": pktMd.DstAddr.String(), 112 | "src-port": pktMd.SrcPort, 113 | "dst-port": pktMd.DstPort, 114 | } 115 | 116 | log.WithFields(packetLog).Trace("Applying INT watchlist for packet.") 117 | 118 | // apply for post-NAT 5-tuple 119 | for _, rule := range rh.watchlist { 120 | if pktMd.Protocol == rule.GetProtocol() && 121 | rule.GetSrcAddr().Contains(pktMd.SrcAddr) && 122 | rule.GetDstAddr().Contains(pktMd.DstAddr) { 123 | log.WithFields(log.Fields{ 124 | "packet": packetLog, 125 | "rule-matched": rule.String(), 126 | }).Debug("Match for post-NAT tuple found") 127 | pktMd.MatchedPostNAT = true 128 | return true 129 | } 130 | } 131 | 132 | // apply for pre-NAT 5-tuple 133 | for _, rule := range rh.watchlist { 134 | if pktMd.Protocol == rule.GetProtocol() && 135 | rule.GetSrcAddr().Contains(pktMd.DataPlaneReport.PreNATSourceIP) && 136 | rule.GetDstAddr().Contains(pktMd.DataPlaneReport.PreNATDestinationIP) { 137 | log.WithFields(log.Fields{ 138 | "packet": packetLog, 139 | "rule-matched": rule.String(), 140 | }).Debug("Match for pre-NAT tuple found") 141 | return true 142 | } 143 | } 144 | 145 | log.WithFields(packetLog).Trace("No INT watchlist match found for packet.") 146 | 147 | return false 148 | } 149 | 150 | func (rh *ReportHandler) rxFn(id int) { 151 | hwID := uint8(id) 152 | seqNo := uint32(0) 153 | for pktMd := range rh.reportsChannel { 154 | if !rh.applyWatchlist(pktMd) { 155 | continue 156 | } 157 | 158 | fields := log.WithFields(log.Fields{ 159 | "DatapathReport": pktMd.DataPlaneReport, 160 | "SrcAddr": pktMd.SrcAddr, 161 | "DstAddr": pktMd.DstAddr, 162 | "IPProtocol": pktMd.Protocol, 163 | "SrcPort": pktMd.SrcPort, 164 | "DstPort": pktMd.DstPort, 165 | "Encapsulation": pktMd.EncapMode, 166 | }) 167 | fields.Debugf("RX worker %d parsed data plane event.", id) 168 | 169 | if seqNo == math.MaxUint32 { 170 | seqNo = 0 171 | } else { 172 | seqNo++ 173 | } 174 | 175 | data, err := packet.BuildINTReport(pktMd, rh.switchID, hwID, seqNo) 176 | if err != nil { 177 | fields.Errorf("failed to build INT report: %v", err) 178 | continue 179 | } 180 | 181 | n, err := rh.udpConn.Write(data) 182 | if err != nil { 183 | fields.Errorf("failed to sent UDP packet: %v", err) 184 | continue 185 | } 186 | fields.Tracef("RX worker %d sent %d bytes to %v", id, n, rh.udpConn.RemoteAddr()) 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /pkg/inthostreporter/reporter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package inthostreporter 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 10 | "github.com/opennetworkinglab/int-host-reporter/pkg/dataplane" 11 | "github.com/opennetworkinglab/int-host-reporter/pkg/loader" 12 | "github.com/opennetworkinglab/int-host-reporter/pkg/service" 13 | "github.com/opennetworkinglab/int-host-reporter/pkg/watchlist" 14 | log "github.com/sirupsen/logrus" 15 | "github.com/vishvananda/netlink" 16 | "net/http" 17 | "os" 18 | "os/exec" 19 | "os/signal" 20 | "syscall" 21 | "time" 22 | ) 23 | 24 | const ( 25 | INTProgramHandle = 3 26 | ) 27 | 28 | type IntHostReporter struct { 29 | ctx context.Context 30 | cancelFunc context.CancelFunc 31 | 32 | restService *http.Server 33 | reportHandler *ReportHandler 34 | dataPlaneInterface *dataplane.EBPFDatapathInterface 35 | 36 | signals chan os.Signal 37 | } 38 | 39 | func NewIntHostReporter(watchlist *watchlist.INTWatchlist) *IntHostReporter { 40 | itr := &IntHostReporter{} 41 | itr.ctx = context.Background() 42 | itr.dataPlaneInterface = dataplane.NewDataPlaneInterface() 43 | itr.reportHandler = NewReportHandler(itr.dataPlaneInterface) 44 | itr.signals = make(chan os.Signal, 1) 45 | itr.initWatchlist(watchlist) 46 | return itr 47 | } 48 | 49 | func (itr *IntHostReporter) initWatchlist(watchlist *watchlist.INTWatchlist) { 50 | if len(watchlist.GetRules()) > 0 { 51 | log.WithFields(log.Fields{ 52 | "rules": watchlist.GetRules(), 53 | }).Debug("Starting with the pre-configured INT watchlist") 54 | } 55 | 56 | itr.reportHandler.SetINTWatchlist(watchlist.GetRules()) 57 | } 58 | 59 | func tcQdiscExists(ifName string) bool { 60 | link, err := netlink.LinkByName(ifName) 61 | if err != nil { 62 | return false 63 | } 64 | 65 | qdiscs, _ := netlink.QdiscList(link) 66 | for _, qdisc := range qdiscs { 67 | if qdisc.Attrs().Parent == netlink.HANDLE_CLSACT { 68 | return true 69 | } 70 | } 71 | 72 | return false 73 | } 74 | 75 | func addTcQdisc(ifName string) error { 76 | link, err := netlink.LinkByName(ifName) 77 | if err != nil { 78 | return err 79 | } 80 | 81 | attrs := netlink.QdiscAttrs{ 82 | LinkIndex: link.Attrs().Index, 83 | Handle: netlink.MakeHandle(0xffff, 0), 84 | Parent: netlink.HANDLE_CLSACT, 85 | } 86 | 87 | qdisc := &netlink.GenericQdisc{ 88 | QdiscAttrs: attrs, 89 | QdiscType: "clsact", 90 | } 91 | 92 | if err = netlink.QdiscReplace(qdisc); err != nil { 93 | return fmt.Errorf("replacing qdisc for %s failed: %s", ifName, err) 94 | } 95 | 96 | log.Debugf("replacing qdisc for %s succeeded", ifName) 97 | return nil 98 | } 99 | 100 | func (itr *IntHostReporter) loadBPFProgram(ifName string) error { 101 | if !tcQdiscExists(ifName) { 102 | err := addTcQdisc(ifName) 103 | if err != nil { 104 | log.Debugf("failed to add clsact qdisc for %v: %v", ifName, err) 105 | return err 106 | } 107 | } 108 | 109 | loaderProg := "tc" 110 | ingressArgs := []string{"filter", "replace", "dev", ifName, "ingress", 111 | "prio", "1", "handle", "3", "bpf", "da", "obj", "/opt/out.o", 112 | "sec", "classifier/ingress", 113 | } 114 | egressArgs := []string{"filter", "replace", "dev", ifName, "egress", 115 | "prio", "1", "handle", "3", "bpf", "da", "obj", "/opt/out.o", 116 | "sec", "classifier/egress", 117 | } 118 | 119 | cmd := exec.Command(loaderProg, ingressArgs...) 120 | out, err := cmd.CombinedOutput() 121 | if err != nil { 122 | log.Debugf("ingress filter replace failed: %v", string(out)) 123 | return err 124 | } 125 | 126 | cmd = exec.Command(loaderProg, egressArgs...) 127 | out, err = cmd.CombinedOutput() 128 | if err != nil { 129 | log.Debugf("egress filter replace failed: %v", string(out)) 130 | return err 131 | } 132 | 133 | return nil 134 | } 135 | 136 | func (itr *IntHostReporter) removeBPFProgram(ifName string) error { 137 | loaderProg := "tc" 138 | baseCmd := []string{"filter", "del", "dev", ifName} 139 | clearIngressCmd := append(baseCmd, "ingress") 140 | clearEgressCmd := append(baseCmd, "egress") 141 | 142 | clearIngressCmd = append(clearIngressCmd, []string{"prio", "1", "handle", "3", "bpf"}...) 143 | clearEgressCmd = append(clearEgressCmd, []string{"prio", "1", "handle", "3", "bpf"}...) 144 | 145 | cmd := exec.Command(loaderProg, clearIngressCmd...) 146 | out, err := cmd.CombinedOutput() 147 | if err != nil { 148 | log.Debugf("failed to remove ingress filter from interface %s: %v", 149 | ifName, string(out)) 150 | return err 151 | } 152 | 153 | cmd = exec.Command(loaderProg, clearEgressCmd...) 154 | out, err = cmd.CombinedOutput() 155 | if err != nil { 156 | log.Debugf("failed to remove egress filter from interface %s: %v", 157 | ifName, string(out)) 158 | return err 159 | } 160 | 161 | return nil 162 | } 163 | 164 | func (itr *IntHostReporter) attachINTProgramsAtStartup() error { 165 | options := loader.CompileOptions{} 166 | if log.GetLevel() == log.TraceLevel || log.GetLevel() == log.DebugLevel { 167 | options.Debug = true 168 | } 169 | err := loader.CompileDatapath(options) 170 | if err != nil { 171 | return fmt.Errorf("failed to compile datapath: %v", err) 172 | } 173 | 174 | noProgramsAttached := true 175 | links, _ := netlink.LinkList() 176 | for _, link := range links { 177 | if link.Attrs().Name == *common.DataInterface || common.IsInterfaceManagedByCNI(link.Attrs().Name) { 178 | log.Debugf("Trying to load BPF program to %s", link.Attrs().Name) 179 | err = itr.loadBPFProgram(link.Attrs().Name) 180 | if err != nil { 181 | log.Errorf("Failed to load BPF program to %s: %v", link.Attrs().Name, err) 182 | } else { 183 | noProgramsAttached = false 184 | log.Debugf("Successfully loaded BPF program to %s", link.Attrs().Name) 185 | } 186 | } 187 | } 188 | 189 | if noProgramsAttached { 190 | return fmt.Errorf("no BPF program has been attached, verify if data interface is configured") 191 | } 192 | 193 | return nil 194 | } 195 | 196 | func (itr *IntHostReporter) clearINTPrograms() (err error) { 197 | links, _ := netlink.LinkList() 198 | for _, link := range links { 199 | if link.Attrs().Name == *common.DataInterface || common.IsInterfaceManagedByCNI(link.Attrs().Name) { 200 | log.Debugf("Clearing BPF program from %s", link.Attrs().Name) 201 | err = itr.removeBPFProgram(link.Attrs().Name) 202 | } 203 | } 204 | 205 | if err == nil { 206 | log.Info("Successfully removed BPF programs from all interfaces.") 207 | } 208 | return err 209 | } 210 | 211 | func interfaceHasINTProgram(link netlink.Link, handle uint32) bool { 212 | filters, err := netlink.FilterList(link, handle) 213 | if err != nil { 214 | log.Errorf("failed to get filter list for link %v: %v", link.Attrs().Name, err.Error()) 215 | return false 216 | } 217 | for _, f := range filters { 218 | if f.Attrs().Handle == INTProgramHandle { 219 | return true 220 | } 221 | } 222 | 223 | return false 224 | } 225 | 226 | // This function will (re-)load INT programs in two cases: 227 | // 1) when a new container's interface is created 228 | // 2) when a CNI will clear INT programs from a container's interface 229 | func (itr *IntHostReporter) reloadINTProgramsIfNeeded(stopCtx context.Context) { 230 | for { 231 | select { 232 | case <-stopCtx.Done(): 233 | return 234 | default: 235 | { 236 | links, _ := netlink.LinkList() 237 | for _, link := range links { 238 | if link.Attrs().Name == *common.DataInterface || 239 | common.IsInterfaceManagedByCNI(link.Attrs().Name) { 240 | if !interfaceHasINTProgram(link, netlink.HANDLE_MIN_INGRESS) || 241 | !interfaceHasINTProgram(link, netlink.HANDLE_MIN_EGRESS) { 242 | log.Debugf("Re-loading INT eBPF program to interface %v", link.Attrs().Name) 243 | err := itr.loadBPFProgram(link.Attrs().Name) 244 | if err != nil { 245 | log.Errorf("Failed to load BPF program to %s: %v", link.Attrs().Name, err) 246 | } 247 | } 248 | } 249 | } 250 | time.Sleep(time.Second) 251 | } 252 | } 253 | } 254 | } 255 | 256 | func (itr *IntHostReporter) Start() error { 257 | // Setup signal handler. 258 | signal.Notify(itr.signals, syscall.SIGINT, syscall.SIGTERM) 259 | 260 | ctx, cancel := context.WithCancel(itr.ctx) 261 | itr.cancelFunc = cancel 262 | 263 | itr.restService = service.New(":4048") 264 | log.Info("Starting REST service listening on :4048") 265 | go itr.restService.ListenAndServe() 266 | 267 | err := itr.attachINTProgramsAtStartup() 268 | if err != nil { 269 | return err 270 | } 271 | 272 | err = itr.dataPlaneInterface.Init() 273 | if err != nil { 274 | return err 275 | } 276 | 277 | err = itr.reportHandler.Start() 278 | if err != nil { 279 | return err 280 | } 281 | 282 | go itr.reloadINTProgramsIfNeeded(ctx) 283 | go itr.dataPlaneInterface.DetectPacketDrops(ctx) 284 | 285 | go itr.HandleSignals() 286 | 287 | // Blocking 288 | err = itr.dataPlaneInterface.Start(ctx) 289 | if err != nil { 290 | return err 291 | } 292 | 293 | return nil 294 | } 295 | 296 | func (itr *IntHostReporter) Stop() (err error) { 297 | itr.cancelFunc() 298 | itr.restService.Close() 299 | itr.reportHandler.Stop() 300 | err = itr.clearINTPrograms() 301 | itr.dataPlaneInterface.Stop() 302 | close(itr.signals) 303 | return 304 | } 305 | 306 | func (itr *IntHostReporter) HandleSignals() { 307 | for { 308 | sig, ok := <-itr.signals 309 | if !ok { 310 | return 311 | } 312 | log.Debugf("Got signal %v", sig) 313 | if err := itr.Stop(); err != nil { 314 | log.Fatal("Error stopping INT Host Reporter:", err) 315 | } 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /pkg/loader/compile.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package loader 5 | 6 | import ( 7 | "bufio" 8 | "bytes" 9 | "fmt" 10 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 11 | log "github.com/sirupsen/logrus" 12 | "io" 13 | "os/exec" 14 | ) 15 | 16 | const ( 17 | compiler = "clang-10" 18 | linker = "llc-10" 19 | ) 20 | 21 | var ( 22 | standardCFlags = []string{"-O2", "-target", "bpf", 23 | fmt.Sprintf("-D__NR_CPUS__=%d", common.GetNumPossibleCPUs()), 24 | } 25 | 26 | standardLDFlags = []string{"-march=bpf", "-filetype=obj"} 27 | ) 28 | 29 | type CompileOptions struct { 30 | Debug bool 31 | } 32 | 33 | func prepareCmdPipes(cmd *exec.Cmd) (io.ReadCloser, io.ReadCloser, error) { 34 | stdout, err := cmd.StdoutPipe() 35 | if err != nil { 36 | return nil, nil, fmt.Errorf("Failed to get stdout pipe: %s", err) 37 | } 38 | 39 | stderr, err := cmd.StderrPipe() 40 | if err != nil { 41 | stdout.Close() 42 | return nil, nil, fmt.Errorf("Failed to get stderr pipe: %s", err) 43 | } 44 | 45 | return stdout, stderr, nil 46 | } 47 | 48 | func CompileDatapath(options CompileOptions) error { 49 | compilerArgs := make([]string, 0, 16) 50 | 51 | versionCmd := exec.Command(compiler, "--version") 52 | compilerVersion, err := versionCmd.CombinedOutput() 53 | if err != nil { 54 | return err 55 | } 56 | versionCmd = exec.Command(linker, "--version") 57 | linkerVersion, err := versionCmd.CombinedOutput() 58 | if err != nil { 59 | return err 60 | } 61 | 62 | log.WithFields(log.Fields{ 63 | compiler: string(compilerVersion), 64 | linker: string(linkerVersion), 65 | }).Debug("Compiling datapath") 66 | 67 | if options.Debug { 68 | compilerArgs = append(compilerArgs, "-DDEBUG") 69 | } 70 | compilerArgs = append(compilerArgs, "-emit-llvm") 71 | compilerArgs = append(compilerArgs, "-g") 72 | compilerArgs = append(compilerArgs, standardCFlags...) 73 | compilerArgs = append(compilerArgs, "-c", "bpf/int-datapath.c") 74 | compilerArgs = append(compilerArgs, "-o", "-") 75 | 76 | // Compilation is split between two exec calls. First clang generates 77 | // LLVM bitcode and then later llc compiles it to byte-code. 78 | log.WithFields(log.Fields{ 79 | "target": compiler, 80 | "args": compilerArgs, 81 | }).Debug("Launching compiler") 82 | 83 | compilerCmd := exec.Command(compiler, compilerArgs...) 84 | compilerStdout, compilerStderr, err := prepareCmdPipes(compilerCmd) 85 | if err != nil { 86 | return err 87 | } 88 | 89 | linkArgs := make([]string, 0, 8) 90 | linkArgs = append(linkArgs, standardLDFlags...) 91 | linkArgs = append(linkArgs, "-o", "/opt/out.o") 92 | 93 | log.WithFields(log.Fields{ 94 | "target": linker, 95 | "args": linkArgs, 96 | }).Debug("Launching linker") 97 | linkerCmd := exec.Command(linker, linkArgs...) 98 | linkerCmd.Stdin = compilerStdout 99 | if err := compilerCmd.Start(); err != nil { 100 | return fmt.Errorf("failed to start command %s: %s", compilerCmd.Args, err) 101 | } 102 | 103 | var compileOut []byte 104 | _, err = linkerCmd.CombinedOutput() 105 | if err == nil { 106 | compileOut, _ = io.ReadAll(compilerStderr) 107 | err = compilerCmd.Wait() 108 | } 109 | 110 | if err != nil { 111 | err = fmt.Errorf("failed to compile: %s", err) 112 | if compileOut != nil { 113 | scanner := bufio.NewScanner(bytes.NewReader(compileOut)) 114 | for scanner.Scan() { 115 | log.Debug(scanner.Text()) 116 | } 117 | } 118 | return err 119 | } 120 | 121 | log.Debug("Datapath compiled successfully") 122 | return nil 123 | } 124 | -------------------------------------------------------------------------------- /pkg/packet/int_report.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package packet 5 | 6 | import ( 7 | "encoding/binary" 8 | "fmt" 9 | "github.com/google/gopacket" 10 | "github.com/google/gopacket/layers" 11 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 12 | "github.com/opennetworkinglab/int-host-reporter/pkg/dataplane" 13 | log "github.com/sirupsen/logrus" 14 | "net" 15 | ) 16 | 17 | const ( 18 | NProtoEthernet = 0 19 | NProtoTelemetryDrop = 1 20 | NProtoTelemetrySwitchLocal = 2 21 | 22 | SizeINTFixedHeader = 12 23 | SizeINTDropReportHeader = 12 24 | SizeINTFlowReportHeader = 16 25 | // SizeEthernetIPv4UDPVXLAN specifies the total length of Ethernet, IPv4, UDP and VXLAN headers. 26 | // Used to strip out the outer headers. 27 | SizeEthernetIPv4UDPVXLAN = 50 28 | 29 | OffsetDestinationIPVXLAN = 80 30 | OffsetDestinationPortVXLAN = 86 31 | OffsetDestinationIPNoEncap = 30 32 | OffsetDestinationPortNoEncap = 36 33 | ) 34 | 35 | var ( 36 | LayerTypeINTReportFixedHeader = gopacket.RegisterLayerType(1001, gopacket.LayerTypeMetadata{ 37 | Name: "INTReportFixedHeader", 38 | // we won't be decoding INT Report Fixed Header as we only send reports. 39 | Decoder: gopacket.DecodeUnknown, 40 | }) 41 | LayerTypeINTFlowReportHeader = gopacket.RegisterLayerType(1002, gopacket.LayerTypeMetadata{ 42 | Name: "INTFlowReport", 43 | // we won't be decoding INT Flow Report as we only send reports. 44 | Decoder: gopacket.DecodeUnknown, 45 | }) 46 | LayerTypeINTDropReportHeader = gopacket.RegisterLayerType(1003, gopacket.LayerTypeMetadata{ 47 | Name: "INTDropReport", 48 | // we won't be decoding INT Drop Report as we only send reports. 49 | Decoder: gopacket.DecodeUnknown, 50 | }) 51 | ) 52 | 53 | type INTReportFixedHeader struct { 54 | layers.BaseLayer 55 | Version uint8 56 | NProto uint8 57 | // 1-bit field 58 | Dropped bool 59 | // 1-bit field 60 | CongestedQueueAssociation bool 61 | // 1-bit field 62 | TrackedFlowAssociation bool 63 | // 6-bit field 64 | HwID uint8 65 | SeqNo uint32 66 | IngressTimestamp uint32 67 | } 68 | 69 | type INTCommonReportHeader struct { 70 | layers.BaseLayer 71 | SwitchID uint32 72 | IngressPort uint16 73 | EgressPort uint16 74 | QueueID uint8 75 | } 76 | 77 | type INTDropReportHeader struct { 78 | layers.BaseLayer 79 | INTCommonReportHeader 80 | DropReason uint8 81 | } 82 | 83 | type INTLocalReportHeader struct { 84 | layers.BaseLayer 85 | INTCommonReportHeader 86 | // 24-bit field 87 | QueueOccupancy uint32 88 | EgressTimestamp uint32 89 | } 90 | 91 | func (f INTReportFixedHeader) String() string { 92 | return fmt.Sprintf("NProto=%v, HwID=%v, SeqNo=%v, IngressTimestamp=%v", 93 | f.NProto, f.HwID, f.SeqNo, f.IngressTimestamp) 94 | } 95 | 96 | func (f INTReportFixedHeader) LayerType() gopacket.LayerType { 97 | return LayerTypeINTReportFixedHeader 98 | } 99 | 100 | func (f INTReportFixedHeader) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 101 | bytes, err := b.PrependBytes(SizeINTFixedHeader) 102 | if err != nil { 103 | return err 104 | } 105 | 106 | bytes[0] = (f.Version << 4) | f.NProto 107 | if f.Dropped { 108 | bytes[1] |= 1 << 7 109 | } 110 | if f.CongestedQueueAssociation { 111 | bytes[1] |= 1 << 6 112 | } 113 | if f.TrackedFlowAssociation { 114 | bytes[1] |= 1 << 5 115 | } 116 | 117 | bytes[2] = byte(0) 118 | bytes[3] = f.HwID &^ (3 << 6) 119 | binary.BigEndian.PutUint32(bytes[4:], f.SeqNo) 120 | binary.BigEndian.PutUint32(bytes[8:], f.IngressTimestamp) 121 | 122 | return nil 123 | } 124 | 125 | func (l INTLocalReportHeader) String() string { 126 | return fmt.Sprintf("SwitchID=%v, IngressPort=%v, EgressPort=%v, EgressTimestamp=%v", 127 | l.SwitchID, l.IngressPort, l.EgressPort, l.EgressTimestamp) 128 | } 129 | 130 | func (l INTLocalReportHeader) LayerType() gopacket.LayerType { 131 | return LayerTypeINTFlowReportHeader 132 | } 133 | 134 | func (l INTLocalReportHeader) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 135 | bytes, err := b.PrependBytes(SizeINTFlowReportHeader) 136 | if err != nil { 137 | return err 138 | } 139 | 140 | binary.BigEndian.PutUint32(bytes[0:], l.SwitchID) 141 | binary.BigEndian.PutUint16(bytes[4:], l.IngressPort) 142 | binary.BigEndian.PutUint16(bytes[6:], l.EgressPort) 143 | bytes[8] = l.QueueID 144 | 145 | // End host doesn't have any queues. Zero-initialize the fields related to queues. 146 | copy(bytes[9:12], []byte{0, 0, 0}) 147 | 148 | binary.BigEndian.PutUint32(bytes[12:], l.EgressTimestamp) 149 | 150 | return nil 151 | } 152 | 153 | func (d INTDropReportHeader) String() string { 154 | return fmt.Sprintf("SwitchID=%v, IngressPort=%v, EgressPort=%v, DropReason=%v", 155 | d.SwitchID, d.IngressPort, d.EgressPort, d.DropReason) 156 | } 157 | 158 | func (d INTDropReportHeader) LayerType() gopacket.LayerType { 159 | return LayerTypeINTDropReportHeader 160 | } 161 | 162 | func (d INTDropReportHeader) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { 163 | bytes, err := b.PrependBytes(SizeINTDropReportHeader) 164 | if err != nil { 165 | return err 166 | } 167 | 168 | binary.BigEndian.PutUint32(bytes[0:], d.SwitchID) 169 | binary.BigEndian.PutUint16(bytes[4:], d.IngressPort) 170 | binary.BigEndian.PutUint16(bytes[6:], d.EgressPort) 171 | bytes[8] = d.QueueID 172 | bytes[9] = d.DropReason 173 | 174 | return nil 175 | } 176 | 177 | func dropReasonConvertFromDatapathToINT(datapathCode uint8) uint8 { 178 | switch datapathCode { 179 | case 0: 180 | // unknown reason has the same code. 181 | return datapathCode 182 | case 207: 183 | return common.DropReasonChecksumFail 184 | case 239: 185 | return common.DropReasonEncapFail 186 | case 223: 187 | return common.DropReasonDecapFail 188 | case 235: 189 | return common.DropReasonIPOptions 190 | case 236: 191 | return common.DropReasonIPIHLInvalid 192 | case 237: 193 | return common.DropReasonUnauthSource 194 | case 240: 195 | return common.DropReasonIPTTLZero 196 | case 241: 197 | return common.DropReasonACLDeny 198 | default: 199 | log.WithFields(log.Fields{ 200 | "code": datapathCode, 201 | }).Warning("unknown drop reason reported by datapath. Returning unknown reason.") 202 | return common.DropReasonUnknown 203 | } 204 | } 205 | 206 | func getINTFixedHeader(pktMd *dataplane.PacketMetadata, hwID uint8, seqNo uint32) INTReportFixedHeader { 207 | return INTReportFixedHeader{ 208 | Version: 0, 209 | NProto: 0, 210 | Dropped: false, 211 | CongestedQueueAssociation: false, 212 | TrackedFlowAssociation: false, 213 | HwID: hwID, 214 | SeqNo: seqNo, 215 | IngressTimestamp: uint32(pktMd.DataPlaneReport.IngressTimestamp), 216 | } 217 | } 218 | 219 | func getINTCommonHeader(pktMd *dataplane.PacketMetadata, switchID uint32) INTCommonReportHeader { 220 | return INTCommonReportHeader{ 221 | SwitchID: switchID, 222 | IngressPort: uint16(pktMd.DataPlaneReport.IngressPort), 223 | EgressPort: uint16(pktMd.DataPlaneReport.EgressPort), 224 | QueueID: 0, 225 | } 226 | } 227 | 228 | func constructPayloadFromFiveTuple(srcAddr, dstAddr net.IP, protocol uint8, srcPort, dstPort uint16) ([]byte, error) { 229 | // Set up buffer and options for serialization. 230 | buf := gopacket.NewSerializeBuffer() 231 | opts := gopacket.SerializeOptions{ 232 | FixLengths: true, 233 | ComputeChecksums: true, 234 | } 235 | 236 | eth := layers.Ethernet{ 237 | // dummy Eth addresses; INT collector should not care about L2 238 | SrcMAC: net.HardwareAddr{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, 239 | DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, 240 | EthernetType: layers.EthernetTypeIPv4, 241 | } 242 | 243 | ipv4 := &layers.IPv4{ 244 | Version: 4, 245 | TTL: 64, 246 | Protocol: layers.IPProtocol(protocol), 247 | SrcIP: srcAddr, 248 | DstIP: dstAddr, 249 | } 250 | 251 | var l4 gopacket.SerializableLayer 252 | switch protocol { 253 | case 6: 254 | udp := &layers.UDP{ 255 | SrcPort: layers.UDPPort(srcPort), 256 | DstPort: layers.UDPPort(dstPort), 257 | } 258 | udp.SetNetworkLayerForChecksum(ipv4) 259 | l4 = udp 260 | case 17: 261 | tcp := &layers.TCP{ 262 | SrcPort: layers.TCPPort(srcPort), 263 | DstPort: layers.TCPPort(dstPort), 264 | } 265 | tcp.SetNetworkLayerForChecksum(ipv4) 266 | l4 = tcp 267 | default: 268 | return []byte{}, fmt.Errorf("protocol not supported") 269 | } 270 | 271 | dummyPayload := gopacket.Payload{0x01, 0x02, 0x03, 0x04, 0x05, 0x06} 272 | err := gopacket.SerializeLayers(buf, opts, ð, ipv4, l4, &dummyPayload) 273 | if err != nil { 274 | return []byte{}, err 275 | } 276 | 277 | return buf.Bytes(), nil 278 | } 279 | 280 | func getINTPayload(pktMd *dataplane.PacketMetadata) gopacket.Payload { 281 | if len(pktMd.DataPlaneReport.Payload) == 0 { 282 | payload, err := constructPayloadFromFiveTuple(pktMd.SrcAddr, 283 | pktMd.DstAddr, pktMd.Protocol, pktMd.SrcPort, pktMd.DstPort) 284 | if err != nil { 285 | log.WithFields(log.Fields{ 286 | "srcAddr": pktMd.SrcAddr.String(), 287 | "dstAddr": pktMd.DstAddr.String(), 288 | "protocol": pktMd.Protocol, 289 | "srcPort": pktMd.SrcPort, 290 | "dstPort": pktMd.DstPort, 291 | "error": err.Error(), 292 | }).Error("failed to construct INT payload for 5-tuple") 293 | } 294 | pktMd.DataPlaneReport.Payload = payload 295 | } 296 | 297 | payload := gopacket.Payload(pktMd.DataPlaneReport.LayerPayload()) 298 | if pktMd.EncapMode == "vxlan" { 299 | // strip VXLAN out - our design choice is to report only the inner headers 300 | payload = payload[SizeEthernetIPv4UDPVXLAN:] 301 | } 302 | 303 | if !pktMd.MatchedPostNAT && !pktMd.DataPlaneReport.PreNATDestinationIP.IsUnspecified() && 304 | pktMd.DataPlaneReport.PreNATDestinationPort != 0 && 305 | !pktMd.DataPlaneReport.PreNATSourceIP.IsUnspecified() && 306 | pktMd.DataPlaneReport.PreNATSourcePort != 0 { 307 | // if a watchlist matched on pre-NAT and data plane provides pre-NAT IP and port we should restore an original IP and port 308 | // FIXME: this should be changed once INT collector will have support for NAT correlation 309 | copy(payload[OffsetDestinationIPNoEncap-4:OffsetDestinationIPNoEncap], pktMd.DataPlaneReport.PreNATSourceIP) 310 | copy(payload[OffsetDestinationIPNoEncap:OffsetDestinationIPNoEncap+4], pktMd.DataPlaneReport.PreNATDestinationIP) 311 | b := make([]byte, 2) 312 | binary.BigEndian.PutUint16(b, pktMd.DataPlaneReport.PreNATDestinationPort) 313 | copy(payload[OffsetDestinationPortNoEncap:OffsetDestinationPortNoEncap+2], b) 314 | binary.BigEndian.PutUint16(b, pktMd.DataPlaneReport.PreNATSourcePort) 315 | copy(payload[OffsetDestinationPortNoEncap-2:OffsetDestinationPortNoEncap], b) 316 | } 317 | 318 | return payload 319 | } 320 | 321 | func stringify5TupleFromPayload(payload gopacket.Payload) string { 322 | var srcAddr, dstAddr net.IP 323 | var srcPort, dstPort uint16 324 | var protocol uint8 325 | 326 | pkt := gopacket.NewPacket(payload, layers.LayerTypeEthernet, gopacket.Default) 327 | 328 | if ipv4Layer := pkt.Layer(layers.LayerTypeIPv4); ipv4Layer != nil { 329 | ipv4 := ipv4Layer.(*layers.IPv4) 330 | srcAddr = ipv4.SrcIP 331 | dstAddr = ipv4.DstIP 332 | protocol = uint8(ipv4.Protocol) 333 | 334 | if l4Layer := pkt.Layer(ipv4.NextLayerType()); l4Layer != nil { 335 | switch ipv4.Protocol { 336 | case layers.IPProtocolTCP: 337 | tcp, _ := l4Layer.(*layers.TCP) 338 | srcPort = uint16(tcp.SrcPort) 339 | dstPort = uint16(tcp.DstPort) 340 | case layers.IPProtocolUDP: 341 | udp, _ := l4Layer.(*layers.UDP) 342 | srcPort = uint16(udp.SrcPort) 343 | dstPort = uint16(udp.DstPort) 344 | } 345 | } 346 | } else { 347 | return "failed to build 5-tuple from payload, no IPv4 layer?" 348 | } 349 | 350 | return fmt.Sprintf("SrcIP=%v, DstIP=%v, Protocol=%v, SrcPort=%v, DstPort=%v", 351 | srcAddr.String(), dstAddr.String(), protocol, srcPort, dstPort) 352 | } 353 | 354 | func buildINTFlowReport(pktMd *dataplane.PacketMetadata, switchID uint32, hwID uint8, seqNo uint32) ([]byte, error) { 355 | fixedReport := getINTFixedHeader(pktMd, hwID, seqNo) 356 | fixedReport.NProto = NProtoTelemetrySwitchLocal 357 | fixedReport.TrackedFlowAssociation = true 358 | commonHeader := getINTCommonHeader(pktMd, switchID) 359 | localReport := INTLocalReportHeader{ 360 | INTCommonReportHeader: commonHeader, 361 | QueueOccupancy: 0, 362 | EgressTimestamp: uint32(pktMd.DataPlaneReport.EgressTimestamp), 363 | } 364 | payload := getINTPayload(pktMd) 365 | 366 | log.WithFields(log.Fields{ 367 | "fixed-report": fixedReport, 368 | "flow-report": localReport, 369 | "5-tuple": stringify5TupleFromPayload(payload), 370 | }).Debug("INT Flow Report built") 371 | 372 | buf := gopacket.NewSerializeBuffer() 373 | opts := gopacket.SerializeOptions{} 374 | err := gopacket.SerializeLayers(buf, opts, 375 | &fixedReport, 376 | &localReport, 377 | payload) 378 | if err != nil { 379 | return []byte{}, fmt.Errorf("failed to serialize INT Flow Report: %v", err) 380 | } 381 | 382 | return buf.Bytes(), nil 383 | } 384 | 385 | func buildINTDropReport(pktMd *dataplane.PacketMetadata, switchID uint32, hwID uint8, seqNo uint32) ([]byte, error) { 386 | fixedReport := getINTFixedHeader(pktMd, hwID, seqNo) 387 | fixedReport.Dropped = true 388 | fixedReport.NProto = NProtoTelemetryDrop 389 | commonHeader := getINTCommonHeader(pktMd, switchID) 390 | payload := getINTPayload(pktMd) 391 | 392 | dropReport := INTDropReportHeader{ 393 | INTCommonReportHeader: commonHeader, 394 | DropReason: dropReasonConvertFromDatapathToINT(pktMd.DataPlaneReport.Reason), 395 | } 396 | 397 | log.WithFields(log.Fields{ 398 | "fixed-report": fixedReport, 399 | "drop-report": dropReport, 400 | "5-tuple": stringify5TupleFromPayload(payload), 401 | }).Debug("INT Drop Report built") 402 | 403 | buf := gopacket.NewSerializeBuffer() 404 | opts := gopacket.SerializeOptions{} 405 | err := gopacket.SerializeLayers(buf, opts, 406 | &fixedReport, 407 | &dropReport, 408 | payload) 409 | if err != nil { 410 | return []byte{}, fmt.Errorf("failed to serialize INT Flow Report: %v", err) 411 | } 412 | 413 | return buf.Bytes(), nil 414 | } 415 | 416 | func BuildINTReport(pktMd *dataplane.PacketMetadata, switchID uint32, hwID uint8, seqNo uint32) (data []byte, err error) { 417 | switch pktMd.DataPlaneReport.Type { 418 | case dataplane.TraceReport: 419 | data, err = buildINTFlowReport(pktMd, switchID, hwID, seqNo) 420 | case dataplane.DropReport: 421 | data, err = buildINTDropReport(pktMd, switchID, hwID, seqNo) 422 | default: 423 | return []byte{}, fmt.Errorf("unknown report type") 424 | } 425 | 426 | return data, err 427 | } 428 | -------------------------------------------------------------------------------- /pkg/service/service.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package service 5 | 6 | import ( 7 | "github.com/gin-gonic/gin" 8 | "net/http" 9 | ) 10 | 11 | func getRouter() *gin.Engine { 12 | engine := gin.Default() 13 | 14 | engine.GET("/api/v1/topology", GetTopology) 15 | 16 | return engine 17 | } 18 | 19 | func New(endpoint string) *http.Server { 20 | router := getRouter() 21 | return &http.Server{ 22 | Addr: endpoint, 23 | Handler: router, 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /pkg/service/topology.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package service 5 | 6 | import ( 7 | "github.com/gin-gonic/gin" 8 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 9 | "github.com/opennetworkinglab/int-host-reporter/pkg/system" 10 | "net" 11 | "net/http" 12 | ) 13 | 14 | // Represents local link inside a host. 15 | type localLink struct { 16 | ID uint64 `json:"id"` 17 | Name string `json:"name"` 18 | IPs []net.IP `json:"ip-addresses"` 19 | NodeIface bool `json:"is-node-iface"` 20 | } 21 | 22 | type topology struct { 23 | Links []localLink `json:"links"` 24 | } 25 | 26 | func GetTopology(c *gin.Context) { 27 | var topologyData topology 28 | systemLinks := system.GetAllLinks() 29 | for _, sysLink := range systemLinks { 30 | l := localLink{ 31 | ID: sysLink.ID, 32 | Name: sysLink.Name, 33 | IPs: sysLink.IPAddresses, 34 | NodeIface: false, 35 | } 36 | if sysLink.Name == *common.DataInterface { 37 | l.NodeIface = true 38 | } 39 | topologyData.Links = append(topologyData.Links, l) 40 | } 41 | 42 | c.IndentedJSON(http.StatusOK, topologyData) 43 | } 44 | -------------------------------------------------------------------------------- /pkg/system/netsys.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package system 5 | 6 | import ( 7 | "github.com/opennetworkinglab/int-host-reporter/pkg/common" 8 | log "github.com/sirupsen/logrus" 9 | "github.com/vishvananda/netlink" 10 | "golang.org/x/sys/unix" 11 | "net" 12 | ) 13 | 14 | type SysLink struct { 15 | ID uint64 16 | Name string 17 | IPAddresses []net.IP 18 | } 19 | 20 | func GetAllLinks() []SysLink { 21 | log.Debug("Finding all local links in the system..") 22 | var systemLinks []SysLink 23 | links, _ := netlink.LinkList() 24 | for _, link := range links { 25 | if link.Attrs().Name == *common.DataInterface || 26 | common.IsInterfaceManagedByCNI(link.Attrs().Name) { 27 | ipv4Addrs := []net.IP{} 28 | addrs, _ := netlink.AddrList(link, unix.AF_INET) 29 | for _, addr := range addrs { 30 | if addr.IP.To4() != nil { 31 | ipv4Addrs = append(ipv4Addrs, addr.IP.To4()) 32 | } 33 | } 34 | l := SysLink{ 35 | ID: uint64(link.Attrs().Index), 36 | Name: link.Attrs().Name, 37 | IPAddresses: ipv4Addrs, 38 | } 39 | log.WithFields(log.Fields{ 40 | "name": l.Name, 41 | "ID": l.ID, 42 | "ip-addresses": l.IPAddresses, 43 | }).Debug("Adding local link to the list.") 44 | systemLinks = append(systemLinks, l) 45 | } 46 | } 47 | return systemLinks 48 | } 49 | -------------------------------------------------------------------------------- /pkg/watchlist/watchlist.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021-present Open Networking Foundation 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package watchlist 5 | 6 | import ( 7 | "fmt" 8 | "gopkg.in/yaml.v3" 9 | "io/ioutil" 10 | "net" 11 | ) 12 | 13 | type INTWatchlistRuleYAML struct { 14 | DstAddr string `yaml:"dst-addr,omitempty"` 15 | Protocol string `yaml:"protocol"` 16 | SrcAddr string `yaml:"src-addr,omitempty"` 17 | DstPort string `yaml:"dst-port,omitempty"` 18 | SrcPort string `yaml:"src-port"` 19 | } 20 | 21 | type INTWatchlistYAML struct { 22 | Rules []INTWatchlistRuleYAML `yaml:"rules"` 23 | } 24 | 25 | type INTWatchlistRule struct { 26 | protocol uint8 27 | srcAddr net.IPNet 28 | dstAddr net.IPNet 29 | // TODO: currently we don't match on L4 ports 30 | //srcPort uint16 31 | //dstPort uint16 32 | } 33 | 34 | func (rule INTWatchlistRule) String() string { 35 | return fmt.Sprintf("rule=[protocol=%v, srcAddr=%v, dstAddr=%v]", rule.protocol, 36 | rule.srcAddr, rule.dstAddr) 37 | } 38 | 39 | func (rule INTWatchlistRule) GetProtocol() uint8 { 40 | return rule.protocol 41 | } 42 | 43 | func (rule INTWatchlistRule) GetSrcAddr() *net.IPNet { 44 | return &rule.srcAddr 45 | } 46 | 47 | func (rule INTWatchlistRule) GetDstAddr() *net.IPNet { 48 | return &rule.dstAddr 49 | } 50 | 51 | type INTWatchlist struct { 52 | rules []INTWatchlistRule 53 | } 54 | 55 | func NewINTWatchlistRule() INTWatchlistRule { 56 | return INTWatchlistRule{} 57 | } 58 | 59 | func NewINTWatchlist() *INTWatchlist { 60 | w := &INTWatchlist{} 61 | w.rules = make([]INTWatchlistRule, 0) 62 | return w 63 | } 64 | 65 | func FillFromFile(w *INTWatchlist, filename string) error { 66 | buf, err := ioutil.ReadFile(filename) 67 | if err != nil { 68 | return err 69 | } 70 | 71 | watchlist := &INTWatchlistYAML{} 72 | err = yaml.Unmarshal(buf, watchlist) 73 | if err != nil { 74 | return fmt.Errorf("in file %q: %v", filename, err) 75 | } 76 | 77 | for _, r := range watchlist.Rules { 78 | rule, err := parseINTWatchlistRule(r) 79 | if err != nil { 80 | return err 81 | } 82 | w.InsertRule(rule) 83 | } 84 | return nil 85 | } 86 | 87 | func protocolTextToDecimal(proto string) (uint8, error) { 88 | if proto == "" { 89 | return 0, fmt.Errorf("protocol field is mandatory, but not provided") 90 | } 91 | 92 | switch proto { 93 | case "UDP": 94 | return 17, nil 95 | case "TCP": 96 | return 6, nil 97 | default: 98 | return 0, fmt.Errorf("unknown protocol type") 99 | } 100 | } 101 | 102 | func parseINTWatchlistRule(rule INTWatchlistRuleYAML) (INTWatchlistRule, error) { 103 | r := NewINTWatchlistRule() 104 | proto, err := protocolTextToDecimal(rule.Protocol) 105 | if err != nil { 106 | return INTWatchlistRule{}, fmt.Errorf("failed to parse Protocol: %v", err) 107 | } 108 | r.protocol = proto 109 | if rule.SrcAddr != "" { 110 | _, ipNet, err := net.ParseCIDR(rule.SrcAddr) 111 | if err != nil { 112 | return INTWatchlistRule{}, fmt.Errorf("failed to parse SrcAddr") 113 | } 114 | r.srcAddr = *ipNet 115 | } 116 | if rule.DstAddr != "" { 117 | _, ipNet, err := net.ParseCIDR(rule.DstAddr) 118 | if err != nil { 119 | return INTWatchlistRule{}, fmt.Errorf("failed to parse SrcAddr") 120 | } 121 | r.dstAddr = *ipNet 122 | } 123 | 124 | return r, nil 125 | } 126 | 127 | func (w *INTWatchlist) GetRules() []INTWatchlistRule { 128 | return w.rules 129 | } 130 | 131 | func (w *INTWatchlist) InsertRule(rule INTWatchlistRule) { 132 | // TODO: potential data race if we will enable runtime changes to the watchlist 133 | w.rules = append(w.rules, rule) 134 | } 135 | -------------------------------------------------------------------------------- /scripts/compile-bpf.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021-present Open Networking Foundation 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # Flags: 5 | # -DBMD_MODE=, default=BMD_MODE_SKB_CB 6 | # -DDEBUG 7 | clang-10 -O2 -emit-llvm -g -c bpf/int-datapath.c -o - | llc-10 -march=bpf -filetype=obj -o /opt/out.o 8 | --------------------------------------------------------------------------------