Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/python
import requests
import json
import sys
import os
import glob
debug=1
def AuthenticatedHTTP_GetRequest(urlPre,service,user,passw):
URI=urlPre+service
if debug: print URI
myHeaders={}
myHeaders['Content-Type']='application/json;charset=utf8'
myHeaders['Accept']= 'application/json'
try:
response=requests.get(URI,auth=(user,passw),headers=myHeaders)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print "{}\n".format(e)
return response
except requests.exceptions.RequestException as ex:
print ex
return None
return response.json()
def AuthenticatedHTTP_PutRequest(urlPre,service,
user,passw,payLoad):
URI=urlPre+service
if debug: print URI
myHeaders={}
myHeaders['Content-Type']='application/json;charset=utf8'
myHeaders['Accept']= 'application/json'
try :
response=requests.put(URI,data=json.dumps(payLoad),auth=(user,passw),headers=myHeaders)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print "{}\n".format(e)
return response
except requests.exceptions.RequestException as ex:
print ex
return None
return response
def AuthenticatedHTTP_DeleteRequest(urlPre,service,
user,passw):
URI=urlPre+service
if debug: print URI
#myHeaders={}
#myHeaders['Content-Type']='application/json;charset=utf8'
#myHeaders['Accept']= 'application/json'
try :
response=requests.delete(URI,auth=(user,passw))
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print "{}\n".format(e)
return response
except requests.exceptions.RequestException as ex:
print ex
return None
return response
def statsRender(httpResp,flowTag):
''' render flow statitics '''
statsDic=httpResp
msg="[Cookie {cookie}] active since {secs} seconds\n Bytes {byte} - Packets {packets}"
# si potrebbe ottimizzare facendo una sola scansione
for flows in statsDic['flow-node-inventory:table']:
for flow in flows['flow']:
cookie=int(flow['cookie'])
if cookie==int(flowTag):
seconds=flow['opendaylight-flow-statistics:flow-statistics']['duration']['second']
byteTot=flow['opendaylight-flow-statistics:flow-statistics']['byte-count']
packTot=flow['opendaylight-flow-statistics:flow-statistics']['packet-count']
print msg.format(cookie=cookie,byte=byteTot,packets=packTot,secs=seconds)
break
else:
continue
print "\n-------------------\n"
if __name__ == '__main__':
urlPref="http://127.0.0.1:8181/restconf"
targetTemplConfig="/config/opendaylight-inventory:nodes/node/{nodeid}/flow-node-inventory:table/1/flow/{flowid}/"
targetTemplOperat="/operational/opendaylight-inventory:nodes/node/{nodeid}/table/0"
# si potrebbe interrogare il controller, invece di metterli statici
#id_SCBD="openflow:585045261839360"
#id_SCSF="openflow:303570285128704"
# DA RISCRIVERE
serviceExmpl='/config/network-topology:network-topology/topology/ovsdb:1/node/ovsdb:%2F%2FHOST1'
jsonFileExmpl="json-rul"
if len(sys.argv) < 2:
print "Usage: \n{} {} {} [{}]".format(sys.argv[0],"<jsonFilePrefix>","push|pull|stats","outputNodeID")
print "For instance:\n{} {} {}\n".format(sys.argv[0],serviceExmpl,jsonFileExmpl)
print "will post all the json-rul* files in our current dir to the target URL"
print "Target url is built from hardcoded [{}] and <targetAPI>".format(urlPref)
sys.exit(-1)
filePref=sys.argv[1]
mode=sys.argv[2]
if len(sys.argv) > 3:
outputNodeID=sys.argv[3]
else:
outputNodeID=""
filePref+="*json"
username='admin'
password='admin'
for jsonfile in os.listdir("."):
if jsonfile in glob.glob(filePref):
print "sourcing {}".format(jsonfile)
with open(jsonfile,'r') as jfile:
payload=json.load(jfile)
if mode=="push":
payload['flow'][0]['hard-timeout']=unicode('0')
#payload['flow']['hard-timeout']=unicode('0')
elif mode=="pull":
payload['flow'][0]['hard-timeout']=unicode('1')
#:payload['flow']['hard-timeout']=unicode('1')
elif mode=="stats":
myCookie=payload['flow'][0]['cookie']
else:
print "{} : unknown operating mode".format(mode)
sys.exit(-1)
# DA verificare con altre regole
flowID=payload['flow'][0]['id']
#flowID=payload['flow']['id']
if outputNodeID=="":
try:
outputNodeID=payload['flow'][0]['instructions']['instruction'][0]['apply-actions']['action'][0]['output-action']['output-node-connector']
#outputNodeID=payload['flow']['instructions']['instruction'][0]['apply-actions']['action'][0]['output-action']['output-node-connector']
portSeparatorIndex=outputNodeID.rindex(':')
outputNodeID=outputNodeID[0:portSeparatorIndex]
except KeyError:
print 'Fatal : flow output node is not specified from command line and cannot be deduced from json file.'
sys.exit(-1)
if mode=="stats":
targetAPI=targetTemplOperat.format(nodeid=outputNodeID)
res=AuthenticatedHTTP_GetRequest(urlPref,targetAPI,username,password)
statsRender(res,myCookie)
else:
targetAPI=targetTemplConfig.format(nodeid=outputNodeID,flowid=flowID)
#print targetAPI
if mode == "push":
res=AuthenticatedHTTP_PutRequest(urlPref,targetAPI,username,password,payload)
elif mode == "pull":
res=AuthenticatedHTTP_DeleteRequest(urlPref,targetAPI,username,password)
else:
print "{} mode unknown, don't know what to do".format(mode)
sys.exit(-2)
# da ottimizzare !!
if mode != "stats":
if res.status_code == 201 or res.status_code == 200:
httpRes="HTTP is OK"
else:
httpRes="HTTP returned with an error code :("
print httpRes
#outMsg="========\n{}{}\n{}\n{}\n=========".format(urlPref,targetAPI,payload,httpRes)
outMsg="========\n{}{}\n{}\n=========".format(urlPref,targetAPI,payload)
jfile.close()