實驗7:基於REST API的SDN北向應用實踐
實驗步驟
一、搭建拓撲,連接 OpenDaylight,下發流表
- 編寫Python程序,調用OpenDaylight的北向接口下發指令刪除s1上的流表數據
#!/usr/bin/python
import requests
from requests.auth import HTTPBasicAuth
def http_delete(url):
url= url
headers = {'Content-Type':'application/json'}
resp = requests.delete(url,headers=headers,auth=HTTPBasicAuth('admin', 'admin'))
return resp
if __name__ == "__main__":
url='http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/'
resp = http_delete(url)
print (resp.content)
- 編寫Python程序,調用OpenDaylight的北向接口下發硬超時流表,實現拓撲內主機h1和h3網絡中斷20s
#!/usr/bin/python
import requests
from requests.auth import HTTPBasicAuth
def http_put(url,jstr):
url= url
headers = {'Content-Type':'application/json'}
resp = requests.put(url,jstr,headers=headers,auth=HTTPBasicAuth('admin', 'admin'))
return resp
if __name__ == "__main__":
url='http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0/flow/1'
with open('h_timeout.json') as f:
jstr = f.read()
resp = http_put(url,jstr)
print (resp.content)
{
"flow": [
{
"id": "1",
"match": {
"in-port": "1",
"ethernet-match": {
"ethernet-type": {
"type": "0x0800"
}
},
"ipv4-destination": "10.0.0.3/32"
},
"instructions": {
"instruction": [
{
"order": "0",
"apply-actions": {
"action": [
{
"order": "0",
"drop-action": {}
}
]
}
}
]
},
"flow-name": "flow1",
"priority": "65535",
"hard-timeout": "20",
"cookie": "2",
"table_id": "0"
}
]
}
- 編寫Python程序,調用OpenDaylight的北向接口獲取s1上活動的流表數
#!/usr/bin/python
import requests
import json
from requests.auth import HTTPBasicAuth
def http_get(url):
url= url
headers = {'Content-Type':'application/json'}
resp = requests.get(url,headers=headers,auth=HTTPBasicAuth('admin','admin'))
return resp
if __name__ == "__main__":
url='http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/flow-node-inventory:table/0'
resp = http_get(url)
res = json.loads(resp.text)
# print(resp.text)
print(len(res['flow-node-inventory:table'][0]['flow']))
二、搭建拓撲,連接 Ryu,下發流表
- 編寫Python程序,調用Ryu的北向接口,實現上述OpenDaylight實驗拓撲上相同的硬超時流表下發
#!/usr/bin/python
import requests
from requests.auth import HTTPBasicAuth
def http_post(url,jstr):
url= url
headers = {'Content-Type':'application/json'}
resp = requests.post(url,jstr,headers=headers)
return resp
if __name__ == "__main__":
url='http://127.0.0.1:8080/stats/flowentry/add'
with open('ryu_htimeout.json') as f:
jstr = f.read()
resp = http_post(url,jstr)
print (resp.content)
{
"dpid": 1,
"cookie": 1,
"cookie_mask": 1,
"table_id": 0,
"hard_timeout": 20,
"priority": 65535,
"flags": 1,
"match":{
"in_port":1
},
"actions":[
{
"type":"OUTPUT",
"port": 2
}
]
}
個人總結
-
本次實驗難度適中,實驗期間遇到的第一個問題是運行上一次實驗創建的 L2Switch.py 出現錯誤,報錯“AttributeError: module 'ryu.ofproto.ofproto_v1_0' has no attribute 'OFPET_EXPERIMENTER'
”,未找到最終原因。改用安裝 Ryu 時自帶的 simple_switch_13.py,成功啟動。 -
第二個問題是啟動 simple_switch_13.py 時沒有一起運行 ofctl_rest.py 開啟控制器的北向接口,導致下發流表失敗。
-
通過這次實驗學習了使用 python 向指定 url 發送請求來調用 REST API,了解了相關 API 的使用。