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

一、基本要求

1.编写Python程序,调用OpenDaylight的北向接口实现以下功能

(1)利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight



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

delete.py

import requests
from requests.auth import HTTPBasicAuth

if __name__ == "__main__":
    url = 'http://127.0.0.1:8181/restconf/config/opendaylight-inventory:nodes/node/openflow:1/'
    headers = {'Content-Type': 'application/json'}
    res = requests.delete(url, headers=headers, auth=HTTPBasicAuth('admin', 'admin'))
    print (res.content)

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

timeout.py

#!/usr/bin/python

import requests
from requests.auth import HTTPBasicAuth

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("./timeout.json") as file:
        str = file.read()
    headers = {'Content-Type': 'application/json'}
    res = requests.put(url, str, headers=headers, auth=HTTPBasicAuth('admin', 'admin'))
    print (res.content)

timeout.json

{
    "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": "flow",
        "priority": "65535",
        "hard-timeout": "20",
        "cookie": "2",
        "table_id": "0"
      }
    ]
  }


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

getflow.py

import requests as rq
from requests.auth import HTTPBasicAuth

def http_get(url):
    url= url
    headers = {'Content-Type':'application/json'}
    resp = rq.get(url,headers=headers,auth=HTTPBasicAuth('admin','admin'))
    return resp

if __name__ == "__main__":
    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'
    resp = http_get(url)
    print(resp.content)

2.编写Python程序,调用Ryu的北向接口实现以下功能

(1)实现上述OpenDaylight实验拓扑上相同的硬超时流表下发

timeout_ryu.py

import requests as rq

if __name__ == "__main__":
    url = 'http://127.0.0.1:8080/stats/flowentry/add'
    with open("./timeout_ryu.json") as f:
        jstr = f.read()
    headers = {'Content-Type': 'application/json'}
    res = rq.post(url, jstr, headers=headers)
    print (res.content)

timeout_ryu.json

{
    "dpid": 1,
    "cookie": 1,
    "cookie_mask": 1,
    "table_id": 0,
    "hard_timeout": 20,
    "priority": 65535,
    "flags": 1,
    "match":{
        "in_port":1
    },
    "actions":[
    ]
 }

(2)参考Ryu REST API的文档,基于VLAN实验的网络拓扑,编程实现相同的VLAN配置

topo.py

#topo.py
from mininet.topo import Topo

class MyTopo( Topo ):

    def __init__( self ):
        Topo.__init__(self)
       
        # Add hosts and switches

        host1 = self.addHost('h1')
        host2 = self.addHost('h2')
        host3 = self.addHost('h3')
        host4 = self.addHost('h4')

        switch1 = self.addSwitch('s1')
        switch2 = self.addSwitch('s2')

        # Add links
        self.addLink(host1,switch1,1,1)
        self.addLink(host2,switch1,1,2)
        self.addLink(host3,switch2,1,1)
        self.addLink(host4,switch2,1,2)
        self.addLink(switch1,switch2,3,3)
topos = { 'mytopo': ( lambda: MyTopo() ) }

vlan_ryu.py

import json
import requests as rq

if __name__ == '__main__':
    url = 'http://127.0.0.1:8080/stats/flowentry/add'
    headers = {'Content-Type': 'application/json'}
    f = open('vlan_ryu.json').read()
    flows = json.loads(f)['flows']
    [rq.post(url, data=json.dumps(flows[i]), headers=headers) for i in range(0, 8)]

vlan_ryu.json

{
	"flows": [{
			"dpid": 1,
			"priority": 1,
			"match": {
				"in_port": 1
			},
			"actions": [{
					"type": "PUSH_VLAN",
					"ethertype": 33024
				},
				{
					"type": "SET_FIELD",
					"field": "vlan_vid",
					"value": 4096
				},
				{
					"type": "OUTPUT",
					"port": 3
				}
			]
		},
		{
			"dpid": 1,
			"priority": 1,
			"match": {
				"in_port": 2
			},
			"actions": [{
					"type": "PUSH_VLAN",
					"ethertype": 33024
				},
				{
					"type": "SET_FIELD",
					"field": "vlan_vid",
					"value": 4097
				},
				{
					"type": "OUTPUT",
					"port": 3
				}
			]
		},
		{
			"dpid": 1,
			"priority": 1,
			"match": {
				"vlan_vid": 0
			},
			"actions": [{
					"type": "POP_VLAN",
					"ethertype": 33024
				},
				{
					"type": "OUTPUT",
					"port": 1
				}
			]
		},
		{
			"dpid": 1,
			"priority": 1,
			"match": {
				"vlan_vid": 1
			},
			"actions": [{
					"type": "POP_VLAN",
					"ethertype": 33024
				},
				{
					"type": "OUTPUT",
					"port": 2
				}
			]
		},
		{
			"dpid": 2,
			"priority": 1,
			"match": {
				"in_port": 1
			},
			"actions": [{
					"type": "PUSH_VLAN",
					"ethertype": 33024
				},
				{
					"type": "SET_FIELD",
					"field": "vlan_vid",
					"value": 4096
				},
				{
					"type": "OUTPUT",
					"port": 3
				}
			]
		}, {
			"dpid": 2,
			"priority": 1,
			"match": {
				"in_port": 2
			},
			"actions": [{
					"type": "PUSH_VLAN",
					"ethertype": 33024
				},
				{
					"type": "SET_FIELD",
					"field": "vlan_vid",
					"value": 4097
				},
				{
					"type": "OUTPUT",
					"port": 3
				}
			]
		},
		{
			"dpid": 2,
			"priority": 1,
			"match": {
				"vlan_vid": 0
			},
			"actions": [{
					"type": "POP_VLAN",

					"ethertype": 33024
				},
				{
					"type": "OUTPUT",
					"port": 1
				}
			]
		},
		{
			"dpid": 2,
			"priority": 1,
			"match": {
				"vlan_vid": 1
			},
			"actions": [{
					"type": "POP_VLAN",
					"ethertype": 33024
				},
				{
					"type": "OUTPUT",
					"port": 2
				}
			]
		}
	]
}

二、进阶要求

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

get_info.py

import requests as rq
import time
import re


class Get_Info:
    def __init__(self, ip):
        self.ip = ip
        

    def get_switch_id(self):
        url = 'http://' + self.ip + '/stats/switches'
        re_switch_id = rq.get(url=url).json()
        switch_id_hex = []
        for i in re_switch_id:
            switch_id_hex.append(hex(i))

        return switch_id_hex


    def get_flow_table(self):
        url = 'http://' + self.ip + '/stats/flow/%d'
        switch_list = self.get_switch_id()
        all_flow = []
        for switch in switch_list:
            new_url = format(url % int(switch, 16))
            re_switch_flow = rq.get(url=new_url).json()
            all_flow.append(re_switch_flow)
        return all_flow

   
    def show_names(self):	
        list_flow = self.get_flow_table()
        for flow in list_flow:
            for dpid in flow.keys():
                dp_id = dpid
                switch_num= '{1}'.format(hex(int(dp_id)), int(dp_id))        
                print('s'+switch_num)
                switch_num = int(switch_num)
            for list_table in flow.values():
                count = 0
                for table in list_table:
                    string1 = str(table)

                    
                    if re.search("'dl_vlan': '(.*?)'", string1) is not None:
                       num = re.search("'dl_vlan': '(.*?)'", string1).group(1);
                       if num == '0' and switch_num == 1:
                          print('h1')
                       if num == '1' and switch_num == 1:
                          print('h2')
                       if num == '0' and switch_num == 2:
                          print('h3')
                       if num == '1' and switch_num == 2:
                          print('h4')                        


    def show_flows(self):
        list_flow = self.get_flow_table()
        for flow in list_flow:
            for dpid in flow.keys():
                dp_id = dpid
                print('switch_name:s{1}'.format(hex(int(dp_id)), int(dp_id)))
            for list_table in flow.values():
                for table in list_table:
                    print(table)

                                              
s1 = Get_Info("127.0.0.1:8080");
s1.show_names();
s1.show_flows();

三、个人总结

本次实验总体步骤并不是很多,但和以往相比复杂了不少,综合性较高,而且有许多地方需要格外注意细节,花费了比较多的时间去学习和编写,在实践REST API服务的时候,尝试了好几次都没能成功,最后比对并修改了代码,重新进行运行才解决了问题。总体来说通过这次作业还是收获了很多的知识以及技巧的。

posted @ 2022-10-26 13:23  A1tair  阅读(3)  评论(0编辑  收藏  举报