实验7:基于REST API的SDN北向应用实践

实验7:基于REST API的SDN北向应用实践

一、实验目的

  1. 能够编写程序调用OpenDaylight REST API实现特定网络功能;
  2. 能够编写程序调用Ryu REST API实现特定网络功能。

二、实验环境

  1. 下载虚拟机软件Oracle VisualBox或VMware;
  2. 在虚拟机中安装Ubuntu 20.04 Desktop amd64,并完整安装Mininet、OpenDaylight(Carbon版本)、Postman和Ryu;

三、实验要求

(一)基本要求

  1. 编写Python程序,调用OpenDaylight的北向接口实现以下功能
    (1) 利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight;

    新建拓扑图

    1
    sudo mn --topo=single,3 --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow13

    启动OpenDaylight

    1
    ./distribution-karaf-0.6.4-Carbon/bin/karaf

    在浏览器访问http://127.0.0.1:8181/index.html

    (2) 下发指令删除s1上的流表数据。

delete.py

复制代码
 1 #!/usr/bin/python
 2 import requests
 3 from requests.auth import HTTPBasicAuth
 4 
 5 def http_delete(url):
 6     url= url
 7     headers = {'Content-Type':'application/json'}
 8     resp = requests.delete(url, headers=headers, auth=HTTPBasicAuth('admin', 'admin'))
 9     return resp
10 
11 if __name__ == "__main__":
12     url = 'http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/'
13     resp = http_delete(url)
14     print(resp.content)
复制代码

(3) 下发硬超时流表,实现拓扑内主机h1和h3网络中断20s。

 

timeOut.py

复制代码
 1 # timeout.py
 2 import requests
 3 from requests.auth import HTTPBasicAuth
 4 if __name__ == "__main__":
 5     url = 'http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0/flow/1'
 6     with open("./timeOut.json") as file:
 7         str = file.read()
 8     headers = {'Content-Type': 'application/json'}
 9     res = requests.put(url, str, headers=headers, auth=HTTPBasicAuth('admin', 'admin'))
10     print (res.content)
复制代码

timeOut.json

复制代码
 1 # timeout.json
 2 {
 3     "flow": [
 4       {
 5         "id": "1",
 6         "match": {
 7           "in-port": "1",
 8           "ethernet-match": {
 9             "ethernet-type": {
10               "type": "0x0800"
11             }
12           },
13           "ipv4-destination": "10.0.0.3/32"
14         },
15         "instructions": {
16           "instruction": [
17             {
18               "order": "0",
19               "apply-actions": {
20                 "action": [
21                   {
22                     "order": "0",
23                     "drop-action": {}
24                   }
25                 ]
26               }
27             }
28           ]
29         },
30         "flow-name": "flow",
31         "priority": "65535",
32         "hard-timeout": "20",
33         "cookie": "2",
34         "table_id": "0"
35       }
36     ]
37   }
复制代码

(4) 获取s1上活动的流表数。

getflow.py

1 # getflow.py
2 import requests
3 from requests.auth import HTTPBasicAuth
4 if __name__ == "__main__":
5     url = 'http://127.0.0.1:8181/restconf/operational/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0/opendaylight-flow-table-statistics:flow-table-statistics'
6     headers = {'Content-Type': 'application/json'}
7     res = requests.get(url,headers=headers, auth=HTTPBasicAuth('admin', 'admin'))
8     print (res.content)
  1. 编写Python程序,调用Ryu的北向接口实现以下功能
    (1) 实现上述OpenDaylight实验拓扑上相同的硬超时流表下发。

    ryu_timeOut.py

    复制代码
    1 # ryu_timeout.py
    2 import requests
    3 if __name__ == "__main__":
    4     url = 'http://127.0.0.1:8080/stats/flowentry/add'
    5     with open("./ryu_timeOut.json") as file:
    6         str = file.read()
    7     headers = {'Content-Type': 'application/json'}
    8     res = requests.post(url, str, headers=headers)
    9     print (res.content)
    复制代码

    ryu_timeOut.json

    复制代码
    # ryu_timeout.json
    {
        "dpid": 1,
        "cookie": 1,
        "cookie_mask": 1,
        "table_id": 0,
        "hard_timeout": 20,
        "priority": 65535,
        "flags": 1,
        "match":{
            "in_port":1
        },
        "actions":[
    
    ]
    

    }

    复制代码

    启动ryu

    1
    ryu-manager ryu/ryu/app/ofctl_rest.py ryu/ryu/app/simple_switch_13.py

    创建拓扑图

    1
    sudo mn --topo=single,3 --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow13

    (2) 参考Ryu REST API的文档,基于VLAN实验的网络拓扑,编程实现相同的VLAN配置。
    提示:拓扑生成后需连接Ryu,且Ryu应能够提供REST API服务

VLAN_IDHosts
0 h1 h3
1 h2 h4


 

拓扑代码topo.py

复制代码
 1 from mininet.topo import Topo
 2 
 3 class MyTopo(Topo):
 4     def __init__(self):
 5         # initilaize topology
 6         Topo.__init__(self)
 7 
 8         self.addSwitch("s1")
 9         self.addSwitch("s2")
10 
11         self.addHost("h1")
12         self.addHost("h2")
13         self.addHost("h3")
14         self.addHost("h4")
15 
16         self.addLink("s1", "h1")
17         self.addLink("s1", "h2")
18         self.addLink("s2", "h3")
19         self.addLink("s2", "h4")
20         self.addLink("s1", "s2")
21 
22 topos = {'mytopo': (lambda: MyTopo())}
复制代码

ryu_vlan.py

复制代码
  1 import json
  2 import requests
  3 
  4 if __name__ == "__main__":
  5     url = 'http://127.0.0.1:8080/stats/flowentry/add'
  6     headers = {'Content-Type': 'application/json'}
  7     flow1 = {
  8         "dpid": 1,
  9         "priority": 1,
 10         "match":{
 11             "in_port": 1
 12         },
 13         "actions":[
 14             {
 15                 "type": "PUSH_VLAN",
 16                 "ethertype": 33024
 17             },
 18             {
 19                 "type": "SET_FIELD",
 20                 "field": "vlan_vid",
 21                 "value": 4096
 22             },
 23             {
 24                 "type": "OUTPUT",
 25                 "port": 3
 26             }
 27         ]
 28     }
 29     flow2 = {
 30         "dpid": 1,
 31         "priority": 1,
 32         "match":{
 33             "in_port": 2
 34         },
 35         "actions":[
 36             {
 37                 "type": "PUSH_VLAN",
 38                 "ethertype": 33024
 39             },
 40             {
 41                 "type": "SET_FIELD",
 42                 "field": "vlan_vid",
 43                 "value": 4097
 44             },
 45             {
 46                 "type": "OUTPUT",
 47                 "port": 3
 48             }
 49         ]
 50     }
 51     flow3 = {
 52         "dpid": 1,
 53         "priority": 1,
 54         "match":{
 55             "vlan_vid": 0
 56         },
 57         "actions":[
 58             {
 59                 "type": "POP_VLAN",
 60                 "ethertype": 33024
 61             },
 62             {
 63                 "type": "OUTPUT",
 64                 "port": 1
 65             }
 66         ]
 67     }
 68     flow4 = {
 69         "dpid": 1,
 70         "priority": 1,
 71         "match": {
 72             "vlan_vid": 1
 73         },
 74         "actions": [
 75             {
 76                 "type": "POP_VLAN",
 77                 "ethertype": 33024
 78             },
 79             {
 80                 "type": "OUTPUT",
 81                 "port": 2
 82             }
 83         ]
 84     }
 85     flow5 = {
 86         "dpid": 2,
 87         "priority": 1,
 88         "match": {
 89             "in_port": 1
 90         },
 91         "actions": [
 92             {
 93                 "type": "PUSH_VLAN",
 94                 "ethertype": 33024
 95             },
 96             {
 97                 "type": "SET_FIELD",
 98                 "field": "vlan_vid",
 99                 "value": 4096
100             },
101             {
102                 "type": "OUTPUT",
103                 "port": 3
104             }
105         ]
106     }
107     flow6 = {
108         "dpid": 2,
109         "priority": 1,
110         "match": {
111             "in_port": 2
112         },
113         "actions": [
114             {
115                 "type": "PUSH_VLAN",
116                 "ethertype": 33024
117             },
118             {
119                 "type": "SET_FIELD",
120                 "field": "vlan_vid",
121                 "value": 4097
122             },
123             {
124                 "type": "OUTPUT",
125                 "port": 3
126             }
127         ]
128     }
129     flow7 = {
130         "dpid": 2,
131         "priority": 1,
132         "match": {
133             "vlan_vid": 0
134         },
135         "actions": [
136             {
137                 "type": "POP_VLAN",
138                 "ethertype": 33024
139             },
140             {
141                 "type": "OUTPUT",
142                 "port": 1
143             }
144         ]
145     }
146     flow8 = {
147         "dpid": 2,
148         "priority": 1,
149         "match": {
150             "vlan_vid": 1
151         },
152         "actions": [
153             {
154                 "type": "POP_VLAN",
155                 "ethertype": 33024
156             },
157             {
158                 "type": "OUTPUT",
159                 "port": 2
160             }
161         ]
162     }
163     res1 = requests.post(url, json.dumps(flow1), headers=headers)
164     res2 = requests.post(url, json.dumps(flow2), headers=headers)
165     res3 = requests.post(url, json.dumps(flow3), headers=headers)
166     res4 = requests.post(url, json.dumps(flow4), headers=headers)
167     res5 = requests.post(url, json.dumps(flow5), headers=headers)
168     res6 = requests.post(url, json.dumps(flow6), headers=headers)
169     res7 = requests.post(url, json.dumps(flow7), headers=headers)
170     res8 = requests.post(url, json.dumps(flow8), headers=headers)
复制代码

创建拓扑图

1
<pre> sudo mn  --custom topo.py --topo mytopo --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow13</pre>

 

(二)进阶要求

OpenDaylight或Ryu任选其一,编程实现查看前序VLAN实验拓扑中所有节点(含交换机、主机)的名称,以及显示每台交换机的所有流表项。

GetNode.py

复制代码
 1 import requests
 2 import time
 3 import re
 4 
 5 
 6 class GetNodes:
 7     def __init__(self, ip):
 8         self.ip = ip
 9         
10     def get_switch_id(self):
11         url = 'http://' + self.ip + '/stats/switches'
12         re_switch_id = requests.get(url=url).json()
13         switch_id_hex = []
14         for i in re_switch_id:
15             switch_id_hex.append(hex(i))
16 
17         return switch_id_hex
18 
19     def getflow(self):
20         url = 'http://' + self.ip + '/stats/flow/%d'
21         switch_list = self.get_switch_id()
22         ret_flow = []
23         for switch in switch_list:
24             new_url = format(url % int(switch, 16))
25             re_switch_flow = requests.get(url=new_url).json()
26             ret_flow.append(re_switch_flow)
27         return ret_flow
28 
29     def show(self):
30         flow_list = self.getflow()
31         for flow in flow_list:
32             for dpid in flow.keys():
33                 dp_id = dpid
34                 switchnum= '{1}'.format(hex(int(dp_id)), int(dp_id))        
35                 print('s'+switchnum,end = " ")
36                 switchnum = int(switchnum)
37             for list_table in flow.values():
38                 for table in list_table:          
39                     string1 = str(table)
40                     if re.search("'dl_vlan': '(.*?)'", string1) is not None:
41                        num = re.search("'dl_vlan': '(.*?)'", string1).group(1);
42                        if num == '0' and switchnum == 1:
43                           print('h1',end = " ")
44                        if num == '1' and switchnum == 1:
45                           print('h2',end = " ")
46                        if num == '0' and switchnum == 2:
47                           print('h3',end = " ")
48                        if num == '1' and switchnum == 2:
49                           print('h4',end = " ")
50         print("")
51         flow_list = self.getflow()
52         for flow in flow_list:
53             for dpid in flow.keys():
54                 dp_id = dpid
55                 print('switch_name:s{1}'.format(hex(int(dp_id)), int(dp_id)))
56             for list_table in flow.values():
57                 for table in list_table:
58                     print(table)
59 s1 = GetNodes("127.0.0.1:8080")
60 s1.show()
复制代码

(三)实验小结

    本次实验难度比较大,遇到了很多的问题,由于以前一直没有更改默认的python版本号,以前使用的python命令是python3,但是这次做的时候忘记了,导致一直使用python,打开python文件,结果一直错误,但是之后改用了python3 的打开方式之后,解决问题。在利用curl命令删除流表时,需要使用sudo apt install curl安装才可以使用,还有就是编写Python程序生成拓扑时,命令一直错误,后面发现是创建指令没有写完整的程序名。同时也复习了关于Ryu的运行方面的操作命令,以及关于.sh脚本的命令。ryu实验中创建的拓扑无法连接上控制器,需要使用命令ryu-manager ryu.app.simple_switch_13 ryu.app.ofctl_rest打开Ryu控制器。

posted @   三维世界是个球  阅读(222)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示