---
title: "P4 behavioral-model: BMv2"
author: "steeven"
date: "2016-10-16T16:03:25Z"
tags: []
categories: ["开源软件"]
slug: "p4-behavioral-model-bmv2"
draft: false
lastmod: "2016-10-16T20:45:29Z"
id: 2330830
url: "https://steeven.iteye.com/blog/2330830"
---

今天是10/15/2016，如果时间太久请移步https://github.com/p4lang/behavioral-model参考最新信息。

BMv2是一个交换机模拟引擎，和p4-factory不同，不依靠代码生成，而是根据p4c-bm编译生成的JSON动态生效。

安装：
===================================================
因为之前安装了p4-factory，所以相关软件可能已经安装好，如果缺东西，请参考github
还是ubuntu1404:
git clone https://github.com/p4lang/behavioral-model.git
cd behavioral-model
./autogen.sh
./configure --with-pdfixed
make
**sudo make install**
sudo ldconfig
#注意内存要够大，我的vm 1.5G内存要切换到runlevel 1才编译成功。
#make install 会安装bm开头的命令和simple_switch，用于启动bmv2, 编译switch项目必须
#运行simple_switch, 如果提示libruntimestubs.so.0找不到，需要运行sudo ldconfig


启动：
=======================================================
启动BMv2参考前面文章安装p4c-bm, 然后执行：
tools/veth_setup.sh 
p4c-bm --json simple_router.json targets/simple_router/simple_router.p4 //生成JSON文件
**sudo** targets/simple_router/simple_router **--log-console** -i 0@veth2 -i 1@veth4 simple_router.json 

> Thrift port was not specified, will use 9090
> Adding interface veth2 as port 0
> Adding interface veth4 as port 1
> Thrift server was started

设备成功启动~
#Targets下面各个目录的启动脚本都一样，建议看看其它参数。
#没有--log-console出错居然看不到。操作端口需要sudo权限
然后新开一个窗口运行**tools/runtime_CLI.py**, 在命令窗口中运行命令来操作BMv2的表、端口、

> RuntimeCmd: port_add veth4 2
> RuntimeCmd: show_ports
>   port #       iface name       status  extra info
> ==================================================
>     0            veth0            UP
>     1            veth2            UP
>     2            veth4            UP
> 

查看targets/simple_router/commands.txt里面有更多命令可以参考。

Mininet:
===================================
上面单独启动BMv2还是不方便用veth需要自己绑定到交换机或者容器去测试，这里有个现成的方式：
sudo python mininet/1sw_demo.py --behavioral-exe targets/simple_router/simple_router --json targets/simple_router/simple_router.json 
启动后一样h1 ping h2不通，因为转发表还没配置。在新窗口中运行：
tools/runtime_CLI.py < targets/simple_router/commands.txt
导入规则之后mininet窗口h1 ping h2成功。

开发自己的p4模型：
===================================
应该是这样：
1. 写好p4文件
2. 用p4c-bm编译成json
3. 启动mininet加载json
4. 启动runtime_CLI.py配置


====================================
BMv2可以定制，如果你是设备商或者芯片厂家，要定义自己的设备来模拟，需要生成参考doxgen：
doxgen Doxfile
生成的文档在doxgen-out目录