├── .dockerignore ├── .github └── workflows │ └── main.yaml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md └── bmv2.py /.dockerignore: -------------------------------------------------------------------------------- 1 | * 2 | !bmv2.py -------------------------------------------------------------------------------- /.github/workflows/main.yaml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow that is triggered periodically on PR and post-merge, 2 | # building docker images for p4mn. 3 | 4 | name: Build-P4mn-Image 5 | 6 | on: 7 | schedule: 8 | - cron: '0 0 * * *' # start daily at 00:00 9 | push: 10 | branches: 11 | - master 12 | pull_request: 13 | 14 | jobs: 15 | solve_env: 16 | runs-on: ubuntu-20.04 17 | steps: 18 | - name: Find latest behavioral-model commit 19 | id: eval 20 | run: | 21 | echo "::set-output name=BMV2_COMMIT::`wget -qO- http://api.github.com/repos/p4lang/behavioral-model/commits/master | grep -m1 '\"sha\"' | cut -d '\"' -f4 | cut -c1-7`" 22 | echo "::set-output name=PI_COMMIT::`wget -qO- http://api.github.com/repos/p4lang/PI/commits/master | grep -m1 '\"sha\"' | cut -d '\"' -f4 | cut -c1-7`" 23 | outputs: 24 | LATEST_BMV2_COMMIT: ${{ steps.eval.outputs.BMV2_COMMIT }} 25 | LATEST_PI_COMMIT: ${{ steps.eval.outputs.PI_COMMIT }} 26 | 27 | 28 | build_matrix: 29 | needs: solve_env 30 | runs-on: ubuntu-20.04 31 | env: 32 | JOBS: '2' 33 | DOCKER_REPO: "opennetworking/p4mn" 34 | GRPC_VER: 1.19.0 35 | PI_CONFIGURE_FLAGS: "--with-proto" 36 | strategy: 37 | fail-fast: false # if enabled, in case of error in a matrix job, all the other jobs will be aborted. 38 | matrix: 39 | include: 40 | - TAGNAME: latest 41 | PI_COMMIT: ${{ needs.solve_env.outputs.LATEST_PI_COMMIT }} 42 | BMV2_COMMIT: ${{ needs.solve_env.outputs.LATEST_BMV2_COMMIT }} 43 | BMV2_CONFIGURE_FLAGS: "--with-pi --disable-elogger --without-nanomsg --without-thrift" 44 | - TAGNAME: latest-no-logging 45 | PI_COMMIT: ${{ needs.solve_env.outputs.LATEST_PI_COMMIT }} 46 | BMV2_COMMIT: ${{ needs.solve_env.outputs.LATEST_BMV2_COMMIT }} 47 | BMV2_CONFIGURE_FLAGS: "--with-pi --disable-elogger --without-nanomsg --without-thrift --disable-logging-macros" 48 | - TAGNAME: stable 49 | PI_COMMIT: 9f6c1f2 50 | BMV2_COMMIT: 8c6f852 51 | BMV2_CONFIGURE_FLAGS: "--with-pi --disable-elogger --without-nanomsg --without-thrift --disable-logging-macros" 52 | - TAGNAME: stable-no-logging 53 | PI_COMMIT: 9f6c1f2 54 | BMV2_COMMIT: 8c6f852 55 | BMV2_CONFIGURE_FLAGS: "--with-pi --disable-elogger --without-nanomsg --without-thrift --disable-logging-macros" 56 | 57 | steps: 58 | - name: Checkout this repository 59 | uses: actions/checkout@v2 60 | 61 | - name: Login to DockerHub 62 | uses: docker/login-action@v1 63 | if: ${{ github.event_name != 'pull_request' }} 64 | with: 65 | username: ${{ secrets.DOCKER_USERNAME }} 66 | password: ${{ secrets.DOCKER_PASSWORD }} 67 | 68 | - name: Build and export to Docker for testing. 69 | uses: docker/build-push-action@v2 70 | with: 71 | context: . 72 | push: false 73 | load: true # load the builded image to local docker instance. Needed for testing step. 74 | cache-from: "${{ env.DOCKER_REPO }}:${{ matrix.TAGNAME }}" 75 | build-args: | 76 | "JOBS=${{ env.JOBS }}" 77 | "GRPC_VER=${{ env.GRPC_VER }}" 78 | "PI_COMMIT=${{ matrix.PI_COMMIT }}" 79 | "BMV2_COMMIT=${{ matrix.BMV2_COMMIT }}" 80 | "PI_CONFIGURE_FLAGS=${{ env.PI_CONFIGURE_FLAGS }}" 81 | "BMV2_CONFIGURE_FLAGS=${{ matrix.BMV2_CONFIGURE_FLAGS }}" 82 | "TAGNAME=${{ matrix.TAGNAME }}" 83 | tags: "${{ env.DOCKER_REPO }}:p4mn-${{ matrix.TAGNAME }}" # Local Runtime image 84 | target: "runtime" 85 | 86 | - name: Test docker build 87 | run: | 88 | docker run --rm --entrypoint simple_switch_grpc ${{ env.DOCKER_REPO }}:p4mn-${{ matrix.TAGNAME }} --help 89 | docker run --rm ${{ env.DOCKER_REPO }}:p4mn-${{ matrix.TAGNAME }} --help 90 | 91 | - name: Push to registry 92 | uses: docker/build-push-action@v2 93 | if: ${{ github.event_name != 'pull_request' }} 94 | with: 95 | context: . 96 | push: true 97 | tags: "${{ env.DOCKER_REPO }}:${{ matrix.TAGNAME }}" 98 | build-args: | 99 | "JOBS=${{ env.JOBS }}" 100 | "GRPC_VER=${{ env.GRPC_VER }}" 101 | "PI_COMMIT=${{ matrix.PI_COMMIT }}" 102 | "BMV2_COMMIT=${{ matrix.BMV2_COMMIT }}" 103 | "PI_CONFIGURE_FLAGS=${{ env.PI_CONFIGURE_FLAGS }}" 104 | "BMV2_CONFIGURE_FLAGS=${{ matrix.BMV2_CONFIGURE_FLAGS }}" 105 | "TAGNAME=${{ matrix.TAGNAME }}" 106 | target: "runtime" 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2019-present Open Networking Foundation 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Default build args. 16 | ARG GRPC_VER=1.19.0 17 | ARG PI_COMMIT=main 18 | ARG BMV2_COMMIT=main 19 | ARG TAGNAME=latest 20 | ARG BMV2_CONFIGURE_FLAGS="--with-pi --disable-elogger --without-nanomsg --without-thrift" 21 | ARG PI_CONFIGURE_FLAGS="--with-proto" 22 | ARG JOBS=2 23 | 24 | # We use a 2-stage build. Build everything then copy only the strict necessary 25 | # to a new image with runtime dependencies. 26 | FROM bitnami/minideb:stretch as builder 27 | 28 | ENV BUILD_DEPS \ 29 | autoconf \ 30 | automake \ 31 | build-essential \ 32 | ca-certificates \ 33 | curl \ 34 | g++ \ 35 | git \ 36 | help2man \ 37 | libboost-dev \ 38 | libboost-filesystem-dev \ 39 | libboost-program-options-dev \ 40 | libboost-system-dev \ 41 | libboost-test-dev \ 42 | libboost-thread-dev \ 43 | libevent-dev \ 44 | libgmp-dev \ 45 | libjudy-dev \ 46 | libpcap-dev \ 47 | libssl-dev \ 48 | libtool \ 49 | make \ 50 | pkg-config \ 51 | python \ 52 | python-dev \ 53 | python-pip \ 54 | python-setuptools \ 55 | unzip 56 | RUN install_packages $BUILD_DEPS 57 | 58 | # Install extra PIP dependencies 59 | ENV PIP_DEPS \ 60 | ipaddress 61 | RUN pip install --no-cache-dir --root /output $PIP_DEPS 62 | 63 | ARG GRPC_VER 64 | ARG JOBS 65 | 66 | # Install protobuf and grpc. 67 | RUN echo "*** Building gRPC v$GRPC_VER" 68 | RUN git clone https://github.com/grpc/grpc.git /tmp/grpc && \ 69 | cd /tmp/grpc && git fetch --tags && git checkout v$GRPC_VER 70 | WORKDIR /tmp/grpc 71 | RUN git submodule update --init --recursive 72 | 73 | WORKDIR third_party/protobuf 74 | RUN ./autogen.sh 75 | RUN ./configure --enable-shared 76 | RUN make -j$JOBS 77 | RUN make install-strip 78 | RUN ldconfig 79 | 80 | WORKDIR /tmp/grpc 81 | RUN make -j$JOBS 82 | RUN make install 83 | RUN ldconfig 84 | 85 | ARG PI_COMMIT 86 | ARG PI_CONFIGURE_FLAGS 87 | 88 | # Build PI 89 | RUN echo "*** Building PI $PI_COMMIT - $PI_CONFIGURE_FLAGS" 90 | RUN git clone https://github.com/p4lang/PI.git /tmp/PI && \ 91 | cd /tmp/PI && git checkout ${PI_COMMIT} 92 | WORKDIR /tmp/PI 93 | RUN git submodule update --init --recursive 94 | RUN ./autogen.sh 95 | RUN ./configure $PI_CONFIGURE_FLAGS 96 | RUN make -j${JOBS} 97 | RUN make install 98 | RUN ldconfig 99 | 100 | ARG BMV2_COMMIT 101 | ARG BMV2_CONFIGURE_FLAGS 102 | 103 | # Build simple_switch 104 | RUN echo "*** Building BMv2 $BMV2_COMMIT - $BMV2_CONFIGURE_FLAGS" 105 | RUN git clone https://github.com/p4lang/behavioral-model.git /tmp/bmv2 && \ 106 | cd /tmp/bmv2 && git checkout ${BMV2_COMMIT} 107 | WORKDIR /tmp/bmv2 108 | RUN ./autogen.sh 109 | # Build only simple_switch and simple_switch_grpc 110 | RUN ./configure $BMV2_CONFIGURE_FLAGS \ 111 | --without-targets CPPFLAGS="-I${PWD}/targets/simple_switch -DWITH_SIMPLE_SWITCH" 112 | RUN make -j${JOBS} 113 | RUN make install 114 | RUN ldconfig 115 | 116 | WORKDIR /tmp/bmv2/targets/simple_switch 117 | RUN make -j${JOBS} 118 | RUN make install 119 | RUN ldconfig 120 | 121 | ARG TAGNAME 122 | 123 | WORKDIR /tmp/bmv2/targets/simple_switch_grpc 124 | 125 | RUN if echo ${TAGNAME} | grep -v "latest"; then ./autogen.sh; fi 126 | RUN if echo ${TAGNAME} | grep -v "latest"; then ./configure; fi 127 | RUN make -j${JOBS} 128 | RUN make install 129 | RUN ldconfig 130 | 131 | # Build Mininet 132 | RUN echo "*** Building Mininet" 133 | RUN mkdir /tmp/mininet 134 | WORKDIR /tmp/mininet 135 | RUN curl -L https://github.com/mininet/mininet/tarball/master | \ 136 | tar xz --strip-components 1 137 | # Install in a special directory that we will copy to the runtime image. 138 | RUN mkdir -p /output 139 | RUN PREFIX=/output make install-mnexec install-manpages 140 | RUN python setup.py install --root /output 141 | # Install `m` utility so user can attach to a mininet host directly 142 | RUN cp util/m /output/bin/m && sed -i 's#sudo##g' /output/bin/m 143 | 144 | # From `ldd /usr/local/bin/simple_switch_grpc`, we put aside just the strict 145 | # necessary to run simple_switch_grpc, i.e. the binary and some (not all) of the 146 | # shared objects we just built. Other shared objects (such as boost) will be 147 | # installed via apt-get. 148 | RUN mkdir -p /output/usr/local/bin 149 | RUN mkdir -p /output/usr/local/lib 150 | 151 | RUN cp --parents /usr/local/bin/simple_switch_grpc /output 152 | 153 | # Protobuf 154 | RUN cp --parents --preserve=links /usr/local/lib/libprotobuf.so.* /output 155 | # gRPC 156 | RUN cp --parents --preserve=links /usr/local/lib/libgpr.so.* /output 157 | RUN cp --parents --preserve=links /usr/local/lib/libgrpc++.so.* /output 158 | RUN cp --parents --preserve=links /usr/local/lib/libgrpc++_reflection.so.* /output 159 | RUN cp --parents --preserve=links /usr/local/lib/libgrpc.so.* /output 160 | # PI 161 | RUN cp --parents --preserve=links /usr/local/lib/libpi.so.* /output 162 | RUN cp --parents --preserve=links /usr/local/lib/libpiconvertproto.so.* /output 163 | RUN cp --parents --preserve=links /usr/local/lib/libpifecpp.so.* /output 164 | RUN cp --parents --preserve=links /usr/local/lib/libpifeproto.so.* /output 165 | RUN cp --parents --preserve=links /usr/local/lib/libpigrpcserver.so.* /output 166 | RUN cp --parents --preserve=links /usr/local/lib/libpip4info.so.* /output 167 | RUN cp --parents --preserve=links /usr/local/lib/libpiprotobuf.so.* /output 168 | RUN cp --parents --preserve=links /usr/local/lib/libpiprotogrpc.so.* /output 169 | # BMv2 170 | RUN cp --parents --preserve=links /usr/local/lib/libbm_grpc_dataplane.so.* /output 171 | RUN cp --parents --preserve=links /usr/local/lib/libbmpi.so.* /output 172 | 173 | # We now install Python bindings to use P4Runtime. This is not required to run 174 | # Mininet but it's useful for running Python scripts using P4Runtime, e.g. PTF 175 | # tests or Python-based control planes. As before, we put the strict necessary 176 | # in /output. 177 | 178 | # Protobuf 179 | WORKDIR /tmp/grpc/third_party/protobuf/python 180 | RUN python setup.py install --root /output --cpp_implementation 181 | 182 | # gRPC 183 | WORKDIR /tmp/grpc 184 | # Install build dependencies from requirements.txt, but not protobuf, that's 185 | # only required at runtime and we just installed it 186 | RUN cat requirements.txt | grep -v protobuf | grep -v "#" | xargs pip install 187 | # Build and install gRPC Python bindings in /output 188 | RUN GRPC_PYTHON_BUILD_WITH_CYTHON=1 pip install --root /output . 189 | # Install again requirements in /output for runtime 190 | RUN cat requirements.txt | grep -v protobuf | grep -v "#" | xargs pip install --ignore-installed --root /output 191 | 192 | # Finally, copy to /ouput P4Runtime Python bindings installed by PI... 193 | RUN cp --parents -r /usr/local/lib/python2.7/dist-packages/p4/* /output 194 | # ...and Google API ones (e.g. Status) needed by P4Runtime. 195 | RUN cp --parents -r /usr/local/lib/python2.7/dist-packages/google/* /output 196 | 197 | # Final stage, runtime. 198 | FROM bitnami/minideb:stretch as runtime 199 | 200 | LABEL maintainer="Carmelo Cascone " 201 | LABEL description="P4Runtime-enabled Mininet that uses BMv2 simple_switch_grpc as the default switch" 202 | 203 | ARG GRPC_VER 204 | ARG PI_COMMIT 205 | ARG PI_CONFIGURE_FLAGS 206 | ARG BMV2_COMMIT 207 | ARG BMV2_CONFIGURE_FLAGS 208 | 209 | LABEL grpc-version="$GRPC_VER" 210 | LABEL pi-commit="$PI_COMMIT" 211 | LABEL bmv2-commit="$BMV2_COMMIT" 212 | LABEL pi-configure-flags="$PI_CONFIGURE_FLAGS" 213 | LABEL bmv2-configure-flags="$BMV2_CONFIGURE_FLAGS" 214 | 215 | # Mininet and BMv2 runtime dependencies. 216 | ENV RUNTIME_DEPS \ 217 | iproute2 \ 218 | iputils-ping \ 219 | net-tools \ 220 | ethtool \ 221 | socat \ 222 | psmisc \ 223 | procps \ 224 | iperf \ 225 | arping \ 226 | telnet \ 227 | python-setuptools \ 228 | python-pexpect \ 229 | tcpdump \ 230 | libboost-filesystem1.62.0 \ 231 | libboost-program-options1.62.0 \ 232 | libboost-thread1.62.0 \ 233 | libjudydebian1 \ 234 | libgmp10 \ 235 | libpcap0.8 236 | RUN install_packages $RUNTIME_DEPS 237 | 238 | COPY --from=builder /output / 239 | RUN ldconfig 240 | 241 | WORKDIR /root 242 | COPY bmv2.py . 243 | ENV PYTHONPATH $PYTHONPATH:/root 244 | 245 | # Expose one port per switch (gRPC server), hence the number of exposed ports 246 | # limit the number of switches that can be controlled from an external P4Runtime 247 | # controller. 248 | EXPOSE 50001-50999 249 | ENTRYPOINT ["mn", "--custom", "/root/bmv2.py", "--switch", "simple_switch_grpc", "--host", "onoshost", "--controller", "none"] 250 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # P4Runtime-enabled Mininet Docker Image 2 | 3 | Docker image that can execute a Mininet-emulated network of BMv2 virtual 4 | switches, controlled by an external SDN controller via P4Runtime. 5 | 6 | This image was created to facilitate testing of P4Runtime support in the ONOS 7 | controller, but you can use it without ONOS. 8 | 9 | To obtain the image: 10 | 11 | docker pull opennetworking/p4mn: 12 | 13 | ## Tags 14 | 15 | The image comes in two versions (tags): 16 | 17 | * `opennetworking/p4mn:latest` Updated daily and built from the master branch of 18 | the [BMv2][BMv2] and [PI][PI] (P4Runtime server implementation) repositories; 19 | * `opennetworking/p4mn:stable` Built using selected BMv2 and PI versions that 20 | are known to work well with ONOS master. 21 | 22 | Moreover, each tag is available in a "no-logging" version with disabled logging 23 | macros in BMv2 to improve packet forwarding performance: 24 | 25 | * `opennetworking/p4mn:latest-no-logging` 26 | * `opennetworking/p4mn:stable-no-logging` 27 | 28 | ## Status [![Build Status](https://github.com/opennetworkinglab/p4mn-docker/actions/workflows/main.yml/badge.svg)](https://github.com/opennetworkinglab/p4mn-docker/actions/workflows/main.yml) 29 | 30 | Images are built daily using [Github Actions][GH Actions] and pushed to 31 | [Docker Hub][Docker Hub]. 32 | 33 | ## Steps to run p4mn 34 | 35 | To run the container: 36 | 37 | docker run --privileged --rm -it opennetworking/p4mn [MININET ARGS] 38 | 39 | After running this command, you should see the mininet CLI (`mininet>`). 40 | 41 | It is important to run this container in privileged mode (`--privileged`) so 42 | mininet can modify the network interfaces and properties to emulate the desired 43 | topology. 44 | 45 | The image defines as entry point the mininet executable configured to use BMv2 46 | `simple_switch_grpc` as the default switch. Options to the docker run command 47 | (`[MININET ARGS]`) are passed as parameters to the mininet process. For more 48 | information on the supported mininet options, please check the official mininet 49 | documentation. 50 | 51 | For example, to run a linear topology with 3 switches: 52 | 53 | docker run --privileged --rm -it opennetworking/p4mn --topo linear,3 54 | 55 | ### P4Runtime server ports 56 | 57 | Each switch starts a P4Runtime server which is bound to a different port, 58 | starting from 50001 and increasing. To connect an external P4Runtime client 59 | (e.g. an SDN controller) to the switches, you have to publish the corresponding 60 | ports. 61 | 62 | For example, when running a topology with 3 switches: 63 | 64 | docker run --privileged --rm -it -p 50001-50003:50001-50003 opennetworking/p4mn --topo linear,3 65 | 66 | ### BMv2 logs and other temporary files 67 | 68 | To allow easier access to BMv2 logs and other files, we suggest sharing the 69 | `/tmp` directory inside the container on the host system using the docker run 70 | `-v` option, for example: 71 | 72 | docker run ... -v /tmp/p4mn:/tmp ... opennetworking/p4mn ... 73 | 74 | By using this option, during the container execution, a number of files related 75 | to the execution of the BMv2 switches will be available under `/tmp/p4mn` in the 76 | host system. The name of these files depends on the switch name used in Mininet, 77 | e.g. s1, s2, etc. 78 | 79 | Example of these files are: 80 | 81 | * `bmv2-s1-grpc-port`: contains the port used for the P4Runtime server executed 82 | by the switch instance named `s1`; 83 | * `bmv2-s1-log`: contains the BMv2 log; 84 | * `bmv2-s1-netcfg.json`: ONOS netcfg JSON file that can be pushed to ONOS 85 | to discover this switch instance. This file assumes that ONOS is running on 86 | the same host as the container. If this is not the case, you will need to 87 | modify the `managementAddress` property in the JSON file, replacing 88 | `localhost` with the IP address of the host system of the `p4mn` container. 89 | 90 | ### Bash alias 91 | 92 | A convenient way to quickly start the p4mn container is to create an alias in 93 | your bash profile file (`.bashrc`, `.bash_aliases`, or `.bash_profile`) . For 94 | example: 95 | 96 | alias p4mn="rm -rf /tmp/p4mn && docker run --privileged --rm -it -v /tmp/p4mn:/tmp -p50001-50030:50001-50030 --name p4mn --hostname p4mn opennetworking/p4mn" 97 | 98 | Then, to run a a simple 1-switch 2-host topology: 99 | 100 | $ p4mn 101 | *** Creating network 102 | *** Adding controller 103 | *** Adding hosts: 104 | h1 h2 105 | *** Adding switches: 106 | s1 107 | *** Adding links: 108 | (h1, s1) (h2, s1) 109 | *** Configuring hosts 110 | h1 h2 111 | *** Starting controller 112 | 113 | *** Starting 1 switches 114 | s1 ....⚡️ simple_switch_grpc @ 50001 115 | 116 | *** Starting CLI: 117 | mininet> 118 | 119 | Or a linear one with 3 switches and 3 hosts: 120 | 121 | $ p4mn --topo linear,3 122 | *** Creating network 123 | *** Adding controller 124 | *** Adding hosts: 125 | h1 h2 h3 126 | *** Adding switches: 127 | s1 s2 s3 128 | *** Adding links: 129 | (h1, s1) (h2, s2) (h3, s3) (s2, s1) (s3, s2) 130 | *** Configuring hosts 131 | h1 h2 h3 132 | *** Starting controller 133 | 134 | *** Starting 3 switches 135 | s1 .....⚡️ simple_switch_grpc @ 50001 136 | s2 .....⚡️ simple_switch_grpc @ 50002 137 | s3 .....⚡️ simple_switch_grpc @ 50003 138 | 139 | *** Starting CLI: 140 | mininet> 141 | 142 | [Travis]: https://travis-ci.org/opennetworkinglab/p4mn-docker 143 | [Docker Hub]: https://hub.docker.com/r/opennetworking/p4mn 144 | [BMv2]: https://github.com/p4lang/behavioral-model 145 | [PI]: https://github.com/p4lang/PI 146 | -------------------------------------------------------------------------------- /bmv2.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | """ 3 | Copyright 2019-present Open Networking Foundation 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | """ 17 | import json 18 | import multiprocessing 19 | import os 20 | import socket 21 | import sys 22 | import threading 23 | import time 24 | from contextlib import closing 25 | 26 | from mininet.log import info, warn, debug 27 | from mininet.node import Switch, Host 28 | 29 | SIMPLE_SWITCH_GRPC = 'simple_switch_grpc' 30 | PKT_BYTES_TO_DUMP = 80 31 | VALGRIND_PREFIX = 'valgrind --leak-check=yes' 32 | SWITCH_START_TIMEOUT = 10 # seconds 33 | BMV2_LOG_LINES = 5 34 | BMV2_DEFAULT_DEVICE_ID = 1 35 | DEFAULT_PIPECONF = "org.onosproject.pipelines.basic" 36 | 37 | # Stratum paths relative to stratum repo root 38 | STRATUM_BMV2 = 'stratum_bmv2' 39 | STRATUM_BINARY = '/bazel-bin/stratum/hal/bin/bmv2/' + STRATUM_BMV2 40 | STRATUM_INIT_PIPELINE = '/stratum/hal/bin/bmv2/dummy.json' 41 | 42 | 43 | def getStratumRoot(): 44 | if 'STRATUM_ROOT' not in os.environ: 45 | raise Exception("Env variable STRATUM_ROOT not set") 46 | return os.environ['STRATUM_ROOT'] 47 | 48 | 49 | def parseBoolean(value): 50 | if value in ['1', 1, 'true', 'True']: 51 | return True 52 | else: 53 | return False 54 | 55 | 56 | def pickUnusedPort(): 57 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 58 | s.bind(('localhost', 0)) 59 | addr, port = s.getsockname() 60 | s.close() 61 | return port 62 | 63 | 64 | def writeToFile(path, value): 65 | with open(path, "w") as f: 66 | f.write(str(value)) 67 | 68 | 69 | def watchDog(sw): 70 | try: 71 | writeToFile(sw.keepaliveFile, 72 | "Remove this file to terminate %s" % sw.name) 73 | while True: 74 | if ONOSBmv2Switch.mininet_exception == 1 \ 75 | or not os.path.isfile(sw.keepaliveFile): 76 | sw.killBmv2(log=False) 77 | return 78 | if sw.stopped: 79 | return 80 | with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: 81 | port = sw.grpcPortInternal if sw.grpcPortInternal else sw.grpcPort 82 | if s.connect_ex(('localhost', port)) == 0: 83 | time.sleep(1) 84 | else: 85 | warn("\n*** WARN: switch %s died ☠️ \n" % sw.name) 86 | sw.printBmv2Log() 87 | print ("-" * 80) + "\n" 88 | return 89 | except Exception as e: 90 | warn("*** ERROR: " + e.message) 91 | sw.killBmv2(log=True) 92 | 93 | 94 | class ONOSHost(Host): 95 | def __init__(self, name, inNamespace=True, **params): 96 | Host.__init__(self, name, inNamespace=inNamespace, **params) 97 | 98 | def config(self, **params): 99 | r = super(Host, self).config(**params) 100 | for off in ["rx", "tx", "sg"]: 101 | cmd = "/sbin/ethtool --offload %s %s off" \ 102 | % (self.defaultIntf(), off) 103 | self.cmd(cmd) 104 | # disable IPv6 105 | self.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1") 106 | self.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1") 107 | self.cmd("sysctl -w net.ipv6.conf.lo.disable_ipv6=1") 108 | return r 109 | 110 | 111 | class ONOSBmv2Switch(Switch): 112 | """BMv2 software switch with gRPC server""" 113 | # Shared value used to notify to all instances of this class that a Mininet 114 | # exception occurred. Mininet exception handling doesn't call the stop() 115 | # method, so the mn process would hang after clean-up since Bmv2 would still 116 | # be running. 117 | mininet_exception = multiprocessing.Value('i', 0) 118 | 119 | nextGrpcPort = 50001 120 | 121 | def __init__(self, name, json=None, debugger=False, loglevel="warn", 122 | elogger=False, cpuport=255, notifications=False, 123 | thrift=False, dryrun=False, 124 | pipeconf=DEFAULT_PIPECONF, pktdump=False, valgrind=False, 125 | gnmi=False, portcfg=True, onosdevid=None, stratum=False, 126 | **kwargs): 127 | Switch.__init__(self, name, **kwargs) 128 | self.grpcPort = ONOSBmv2Switch.nextGrpcPort 129 | ONOSBmv2Switch.nextGrpcPort += 1 130 | self.grpcPortInternal = None # Needed for Stratum (local_hercules_url) 131 | if not thrift: 132 | self.thriftPort = None 133 | else: 134 | raise Exception("Support for thrift not implemented") 135 | self.cpuPort = cpuport 136 | self.json = json 137 | self.useStratum = parseBoolean(stratum) 138 | self.debugger = parseBoolean(debugger) 139 | self.notifications = parseBoolean(notifications) 140 | self.loglevel = loglevel 141 | # Important: Mininet removes all /tmp/*.log files in case of exceptions. 142 | # We want to be able to see the bmv2 log if anything goes wrong, hence 143 | # avoid the .log extension. 144 | self.logfile = '/tmp/bmv2-%s-log' % self.name 145 | self.elogger = parseBoolean(elogger) 146 | self.pktdump = parseBoolean(pktdump) 147 | self.dryrun = parseBoolean(dryrun) 148 | self.valgrind = parseBoolean(valgrind) 149 | self.netcfgfile = '/tmp/bmv2-%s-netcfg.json' % self.name 150 | self.chassisConfigFile = '/tmp/bmv2-%s-chassis-config.txt' % self.name 151 | self.pipeconfId = pipeconf 152 | self.injectPorts = parseBoolean(portcfg) 153 | self.withGnmi = parseBoolean(gnmi) 154 | self.longitude = kwargs['longitude'] if 'longitude' in kwargs else None 155 | self.latitude = kwargs['latitude'] if 'latitude' in kwargs else None 156 | if onosdevid is not None and len(onosdevid) > 0: 157 | self.onosDeviceId = onosdevid 158 | else: 159 | self.onosDeviceId = "device:bmv2:%s" % self.name 160 | self.p4DeviceId = BMV2_DEFAULT_DEVICE_ID 161 | self.logfd = None 162 | self.bmv2popen = None 163 | self.stopped = True 164 | # In case of exceptions, mininet removes *.out files from /tmp. We use 165 | # this as a signal to terminate the switch instance (if active). 166 | self.keepaliveFile = '/tmp/bmv2-%s-watchdog.out' % self.name 167 | self.targetName = STRATUM_BMV2 if self.useStratum else SIMPLE_SWITCH_GRPC 168 | 169 | # Remove files from previous executions 170 | self.cleanupTmpFiles() 171 | 172 | def getDeviceConfig(self): 173 | 174 | basicCfg = { 175 | "managementAddress": "grpc://localhost:%d?device_id=%d" % ( 176 | self.grpcPort, self.p4DeviceId), 177 | "driver": "stratum-bmv2" if self.useStratum else "bmv2", 178 | "pipeconf": self.pipeconfId 179 | } 180 | 181 | if self.longitude and self.latitude: 182 | basicCfg["longitude"] = self.longitude 183 | basicCfg["latitude"] = self.latitude 184 | 185 | cfgData = { 186 | "basic": basicCfg 187 | } 188 | 189 | if not self.useStratum and self.injectPorts: 190 | portData = {} 191 | portId = 1 192 | for intfName in self.intfNames(): 193 | if intfName == 'lo': 194 | continue 195 | portData[str(portId)] = { 196 | "number": portId, 197 | "name": intfName, 198 | "enabled": True, 199 | "removed": False, 200 | "type": "copper", 201 | "speed": 10000 202 | } 203 | portId += 1 204 | 205 | cfgData['ports'] = portData 206 | 207 | return cfgData 208 | 209 | def chassisConfig(self): 210 | config = """description: "BMv2 simple_switch {name}" 211 | chassis {{ 212 | platform: PLT_P4_SOFT_SWITCH 213 | name: "{name}" 214 | }} 215 | nodes {{ 216 | id: {nodeId} 217 | name: "{name} node {nodeId}" 218 | slot: 1 219 | index: 1 220 | }}\n""".format(name=self.name, nodeId=self.p4DeviceId) 221 | 222 | intfNumber = 1 223 | for intfName in self.intfNames(): 224 | if intfName == 'lo': 225 | continue 226 | config = config + """singleton_ports {{ 227 | id: {intfNumber} 228 | name: "{intfName}" 229 | slot: 1 230 | port: {intfNumber} 231 | channel: 1 232 | speed_bps: 10000000000 233 | config_params {{ 234 | admin_state: ADMIN_STATE_ENABLED 235 | }} 236 | node: {nodeId} 237 | }}\n""".format(intfName=intfName, intfNumber=intfNumber, 238 | nodeId=self.p4DeviceId) 239 | intfNumber += 1 240 | 241 | return config 242 | 243 | def doOnosNetcfg(self): 244 | """ 245 | Writes ONOS netcfg file for this switch. 246 | """ 247 | 248 | cfgData = { 249 | "devices": { 250 | self.onosDeviceId: self.getDeviceConfig() 251 | } 252 | } 253 | with open(self.netcfgfile, 'w') as fp: 254 | json.dump(cfgData, fp, indent=4) 255 | 256 | def start(self, controllers): 257 | 258 | if not self.stopped: 259 | warn("*** %s is already running!\n" % self.name) 260 | return 261 | 262 | # Remove files from previous executions (if we are restarting) 263 | self.cleanupTmpFiles() 264 | 265 | if self.grpcPort: 266 | writeToFile("/tmp/bmv2-%s-grpc-port" % self.name, self.grpcPort) 267 | 268 | if self.useStratum: 269 | config_dir = "/tmp/bmv2-%s-stratum" % self.name 270 | os.mkdir(config_dir) 271 | with open(self.chassisConfigFile, 'w') as fp: 272 | fp.write(self.chassisConfig()) 273 | if self.grpcPortInternal is None: 274 | self.grpcPortInternal = pickUnusedPort() 275 | cmdString = self.getStratumCmdString(config_dir) 276 | else: 277 | if self.thriftPort: 278 | writeToFile("/tmp/bmv2-%s-thrift-port" % self.name, self.thriftPort) 279 | cmdString = self.getBmv2CmdString() 280 | 281 | if self.dryrun: 282 | info("\n*** DRY RUN (not executing %s)\n" % self.targetName) 283 | 284 | debug("\n%s\n" % cmdString) 285 | 286 | try: 287 | if not self.dryrun: 288 | # Start the switch 289 | self.stopped = False 290 | self.logfd = open(self.logfile, "w") 291 | self.logfd.write(cmdString + "\n\n" + "-" * 80 + "\n\n") 292 | self.logfd.flush() 293 | self.bmv2popen = self.popen(cmdString, 294 | stdout=self.logfd, 295 | stderr=self.logfd) 296 | self.waitBmv2Start() 297 | # We want to be notified if BMv2/Stratum dies... 298 | threading.Thread(target=watchDog, args=[self]).start() 299 | 300 | self.doOnosNetcfg() 301 | except Exception: 302 | ONOSBmv2Switch.mininet_exception = 1 303 | self.killBmv2() 304 | self.printBmv2Log() 305 | raise 306 | 307 | def getBmv2CmdString(self): 308 | bmv2Args = [SIMPLE_SWITCH_GRPC] + self.bmv2Args() 309 | if self.valgrind: 310 | bmv2Args = VALGRIND_PREFIX.split() + bmv2Args 311 | return " ".join(bmv2Args) 312 | 313 | def getStratumCmdString(self, config_dir): 314 | stratumRoot = getStratumRoot() 315 | args = [ 316 | stratumRoot + STRATUM_BINARY, 317 | '-device_id=%d' % self.p4DeviceId, 318 | '-chassis_config_file=%s' % self.chassisConfigFile, 319 | '-forwarding_pipeline_configs_file=%s/pipeline_config.txt' % config_dir, 320 | '-persistent_config_dir=' + config_dir, 321 | '-initial_pipeline=' + stratumRoot + STRATUM_INIT_PIPELINE, 322 | '-cpu_port=%s' % self.cpuPort, 323 | '-external_hercules_urls=0.0.0.0:%d' % self.grpcPort, 324 | '-local_hercules_url=localhost:%d' % self.grpcPortInternal, 325 | '-max_num_controllers_per_node=10' 326 | ] 327 | return " ".join(args) 328 | 329 | def bmv2Args(self): 330 | args = ['--device-id %s' % str(self.p4DeviceId)] 331 | for port, intf in self.intfs.items(): 332 | if not intf.IP(): 333 | args.append('-i %d@%s' % (port, intf.name)) 334 | if self.thriftPort: 335 | args.append('--thrift-port %s' % self.thriftPort) 336 | if self.notifications: 337 | ntfaddr = 'ipc:///tmp/bmv2-%s-notifications.ipc' % self.name 338 | args.append('--notifications-addr %s' % ntfaddr) 339 | if self.elogger: 340 | nanologaddr = 'ipc:///tmp/bmv2-%s-nanolog.ipc' % self.name 341 | args.append('--nanolog %s' % nanologaddr) 342 | if self.debugger: 343 | dbgaddr = 'ipc:///tmp/bmv2-%s-debug.ipc' % self.name 344 | args.append('--debugger-addr %s' % dbgaddr) 345 | args.append('--log-console') 346 | if self.pktdump: 347 | args.append('--pcap --dump-packet-data %s' % PKT_BYTES_TO_DUMP) 348 | args.append('-L%s' % self.loglevel) 349 | if not self.json: 350 | args.append('--no-p4') 351 | else: 352 | args.append(self.json) 353 | # gRPC target-specific options 354 | args.append('--') 355 | args.append('--cpu-port %s' % self.cpuPort) 356 | args.append('--grpc-server-addr 0.0.0.0:%s' % self.grpcPort) 357 | return args 358 | 359 | def waitBmv2Start(self): 360 | # Wait for switch to open gRPC port, before sending ONOS the netcfg. 361 | # Include time-out just in case something hangs. 362 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 363 | endtime = time.time() + SWITCH_START_TIMEOUT 364 | while True: 365 | port = self.grpcPortInternal if self.grpcPortInternal else self.grpcPort 366 | result = sock.connect_ex(('localhost', port)) 367 | if result == 0: 368 | # No new line 369 | print "⚡️ %s @ %d" % (self.targetName, self.grpcPort) 370 | # The port is open. Let's go! (Close socket first) 371 | sock.close() 372 | break 373 | # Port is not open yet. If there is time, we wait a bit. 374 | if endtime > time.time(): 375 | sys.stdout.write('.') 376 | sys.stdout.flush() 377 | time.sleep(0.05) 378 | else: 379 | # Time's up. 380 | raise Exception("Switch did not start before timeout") 381 | 382 | def printBmv2Log(self): 383 | if os.path.isfile(self.logfile): 384 | print "-" * 80 385 | print "%s log (from %s):" % (self.name, self.logfile) 386 | with open(self.logfile, 'r') as f: 387 | lines = f.readlines() 388 | if len(lines) > BMV2_LOG_LINES: 389 | print "..." 390 | for line in lines[-BMV2_LOG_LINES:]: 391 | print line.rstrip() 392 | 393 | def killBmv2(self, log=False): 394 | self.stopped = True 395 | if self.bmv2popen is not None: 396 | self.bmv2popen.terminate() 397 | self.bmv2popen.wait() 398 | self.bmv2popen = None 399 | if self.logfd is not None: 400 | if log: 401 | self.logfd.write("*** PROCESS TERMINATED BY MININET ***\n") 402 | self.logfd.close() 403 | self.logfd = None 404 | 405 | def cleanupTmpFiles(self): 406 | self.cmd("rm -rf /tmp/bmv2-%s-*" % self.name) 407 | 408 | def stop(self, deleteIntfs=True): 409 | """Terminate switch.""" 410 | self.killBmv2(log=True) 411 | Switch.stop(self, deleteIntfs) 412 | 413 | 414 | class ONOSStratumSwitch(ONOSBmv2Switch): 415 | def __init__(self, name, **kwargs): 416 | kwargs["stratum"] = True 417 | super(ONOSStratumSwitch, self).__init__(name, **kwargs) 418 | 419 | 420 | # Exports for bin/mn 421 | switches = { 422 | 'simple_switch_grpc': ONOSBmv2Switch, 423 | 'stratum_bmv2': ONOSStratumSwitch, 424 | } 425 | hosts = {'onoshost': ONOSHost} 426 | --------------------------------------------------------------------------------