Fix Pep8 issues related to \
[functest.git] / functest / opnfv_tests / sdn / onos / sfc / sfc_onos.py
1 import os
2 import re
3 import time
4 import json
5 import requests
6
7 from multiprocessing import Process
8 from multiprocessing import Queue
9 from pexpect import pxssh
10
11 import functest.utils.functest_logger as ft_logger
12
13 OK = 200
14 CREATED = 201
15 ACCEPTED = 202
16 NO_CONTENT = 204
17
18
19 class SfcOnos:
20     """Defines all the def function of SFC."""
21
22     def __init__(self):
23         """Initialization of variables."""
24         self.logger = ft_logger.Logger("sfc_fun").getLogger()
25         self.osver = "v2.0"
26         self.token_id = 0
27         self.net_id = 0
28         self.image_id = 0
29         self.keystone_hostname = 'keystone_ip'
30         self.neutron_hostname = 'neutron_ip'
31         self.nova_hostname = 'nova_ip'
32         self.glance_hostname = 'glance_ip'
33         self.onos_hostname = 'onos_ip'
34         # Network variables #######
35         self.netname = "test_nw"
36         self.admin_state_up = True
37         self.tenant_id = 0
38         self.subnetId = 0
39         # #########################
40         # SubNet variables#########
41         self.ip_version = 4
42         self.cidr = "20.20.20.0/24"
43         self.subnetname = "test_nw_subnets"
44         # ###############################
45         # Port variable
46         self.port = "port"
47         self.port_num = []
48         self.vm_id = 0
49         self.port_ip = []
50         self.count = 0
51         self.i = 0
52         self.numTerms = 3
53         self.security_groups = []
54         self.port_security_enabled = False
55         # ###############################
56         # VM creation variable
57         self.container_format = "bare"
58         self.disk_format = "qcow2"
59         self.imagename = "TestSfcVm"
60         self.createImage = ("/home/root1/devstack/files/images/"
61                             "firewall_block_image.img")
62
63         self.vm_name = "vm"
64         self.imageRef = "test"
65         self.flavorRef = "1"
66         self.max_count = "1"
67         self.min_count = "1"
68         self.org_nw_port = []
69         self.image_id = 0
70         self.routername = "router1"
71         self.router_id = 0
72         # #####################################
73         # Port pair
74         self.port_pair_ingress = 0
75         self.port_pair_egress = 0
76         self.port_pair_name = "PP"
77         self.port_pair_id = []
78         # ####################################
79         # Port Group
80         self.port_group_name = "PG"
81         self.port_grp_id = []
82         # ####################################
83         # FlowClassifier
84         self.source_ip_prefix = "20.20.20.0/24"
85         self.destination_ip_prefix = "20.20.20.0/24"
86         self.logical_source_port = 0
87         self.fcname = "FC"
88         self.ethertype = "IPv4"
89         # #####################################
90         self.flow_class_if = 0
91         # #####################################
92         # Port Chain variables
93         self.pcname = 'PC'
94         self.PC_id = 0
95         # #####################################
96         # Port Chain variables
97         self.flowadd = ''
98         # #####################################
99         self.ip_pool = 0
100         self.vm_public_ip = []
101         self.vm_public_id = []
102         self.net_id1 = 0
103         self.vm = []
104         self.address = 0
105         self.value = 0
106         self.pub_net_id = 0
107
108     def getToken(self):
109         """Get the keystone token value from Openstack ."""
110         url = 'http://%s:5000/%s/tokens' % (self.keystone_hostname,
111                                             self.osver)
112         data = ('{"auth": {"tenantName": "admin", "passwordCredentials":'
113                 '{ "username": "admin", "password": "console"}}}')
114         headers = {"Accept": "application/json"}
115         response = requests.post(url, headers=headers,  data=data)
116         if (response.status_code == OK):
117             json1_data = json.loads(response.content)
118             self.logger.debug(response.status_code)
119             self.logger.debug(response.content)
120             self.logger.debug(json1_data)
121             self.token_id = json1_data['access']['token']['id']
122             self.tenant_id = json1_data['access']['token']['tenant']['id']
123             return(response.status_code)
124         else:
125             return(response.status_code)
126
127     def createNetworks(self):
128         """Creation of networks."""
129         Dicdata = {}
130         if self.netname != '':
131             Dicdata['name'] = self.netname
132         if self.admin_state_up != '':
133             Dicdata['admin_state_up'] = self.admin_state_up
134         Dicdata = {'network': Dicdata}
135         data = json.dumps(Dicdata,  indent=4)
136         url = 'http://%s:9696/%s/networks' % (self.neutron_hostname,
137                                               self.osver)
138         headers = {"Accept": "application/json",
139                    "X-Auth-Token": self.token_id}
140         response = requests.post(url, headers=headers,  data=data)
141         if (response.status_code == CREATED):
142             self.logger.debug(response.status_code)
143             self.logger.debug(response.content)
144
145             json1_data = json.loads(response.content)
146             self.logger.debug(json1_data)
147             self.net_id = json1_data['network']['id']
148             return(response.status_code)
149         else:
150             return(response.status_code)
151
152     def createSubnets(self):
153         """Creation of SubNets."""
154         Dicdata = {}
155         if self.net_id != 0:
156             Dicdata['network_id'] = self.net_id
157         if self.ip_version != '':
158             Dicdata['ip_version'] = self.ip_version
159         if self.cidr != '':
160             Dicdata['cidr'] = self.cidr
161         if self.subnetname != '':
162             Dicdata['name'] = self.subnetname
163
164         Dicdata = {'subnet': Dicdata}
165         data = json.dumps(Dicdata, indent=4)
166         url = 'http://%s:9696/%s/subnets' % (self.neutron_hostname,
167                                              self.osver)
168         headers = {"Accept": "application/json",
169                    "X-Auth-Token": self.token_id}
170         response = requests.post(url, headers=headers,  data=data)
171
172         if (response.status_code == CREATED):
173             self.logger.debug(response.status_code)
174             self.logger.debug(response.content)
175             json1_data = json.loads(response.content)
176             self.logger.debug(json1_data)
177             self.subnetId = json1_data['subnet']['id']
178             return(response.status_code)
179         else:
180             return(response.status_code)
181
182     def createPorts(self):
183         """Creation of Ports."""
184         for x in range(self.i, self.numTerms):
185             Dicdata = {}
186             if self.net_id != '':
187                 Dicdata['network_id'] = self.net_id
188             if self.port != '':
189                 Dicdata['name'] = "port" + str(x)
190             if self.admin_state_up != '':
191                 Dicdata['admin_state_up'] = self.admin_state_up
192             if self.security_groups != '':
193                 Dicdata['security_groups'] = self.security_groups
194             # if self.port_security_enabled != '':
195             #    Dicdata['port_security_enabled'] = self.port_security_enabled
196
197             Dicdata = {'port': Dicdata}
198             data = json.dumps(Dicdata, indent=4)
199             url = 'http://%s:9696/%s/ports' % (self.neutron_hostname,
200                                                self.osver)
201             headers = {"Accept": "application/json",
202                        "X-Auth-Token": self.token_id}
203             response = requests.post(url, headers=headers,  data=data)
204
205             if (response.status_code == CREATED):
206                 self.logger.debug(response.status_code)
207                 self.logger.debug(response.content)
208
209                 json1_data = json.loads(response.content)
210                 self.logger.debug(json1_data)
211                 self.port_num.append(json1_data['port']['id'])
212                 self.port_ip.append(json1_data['port']['fixed_ips'][0]
213                                     ['ip_address'])
214             else:
215                 return(response.status_code)
216         return(response.status_code)
217
218     def createVm(self):
219         """Creation of Instance, using  firewall image."""
220         url = ("http://%s:9292/v2/images?"
221                "name=TestSfcVm" % (self.glance_hostname))
222         headers = {"Accept": "application/json", "Content-Type": "application/\
223                     octet-stream",  "X-Auth-Token": self.token_id}
224         response = requests.get(url, headers=headers)
225         if (response.status_code == OK):
226             self.logger.debug(response.status_code)
227             self.logger.debug(response.content)
228             self.logger.info("FireWall Image is available")
229             json1_data = json.loads(response.content)
230             self.logger.debug(json1_data)
231             self.image_id = json1_data['images'][0]['id']
232         else:
233             return(response.status_code)
234
235         url = ("http://%s:8774//v2.1/%s/ports/"
236                "%s/flavors?name=m1.tiny" % (self.nova_hostname,
237                                             self.tenant_id))
238
239         headers = {"Accept": "application/json", "Content-Type":
240                    "application/json", "X-Auth-Token": self.token_id}
241         response = requests.get(url, headers=headers)
242
243         if (response.status_code == OK):
244             self.logger.debug(response.status_code)
245             self.logger.debug(response.content)
246             self.logger.info("Flavor is available")
247             json1_data = json.loads(response.content)
248             self.logger.debug(json1_data)
249             self.flavorRef = json1_data['flavors'][0]['id']
250         else:
251             return(response.status_code)
252
253         for y in range(0, 3):
254             Dicdata = {}
255             org_nw_port = []
256             org_nw_port.append({'port': self.port_num[y]})
257             if self.vm_name != '':
258                 Dicdata['name'] = "vm" + str(y)
259             if self.imageRef != '':
260                 Dicdata['imageRef'] = self.image_id
261             if self.flavorRef != '':
262                 Dicdata['flavorRef'] = self.flavorRef
263             if self.max_count != '':
264                 Dicdata['max_count'] = self.max_count
265             if self.min_count != '':
266                 Dicdata['min_count'] = self.min_count
267             if self.org_nw_port != '':
268                 Dicdata['networks'] = org_nw_port
269             Dicdata = {'server': Dicdata}
270             data = json.dumps(Dicdata, indent=4)
271             url = 'http://%s:8774/v2.1/%s/servers' % (self.nova_hostname,
272                                                       self.tenant_id)
273             headers = {"Accept": "application/json", "Content-Type":
274                        "application/json", "X-Auth-Token": self.token_id}
275             response = requests.post(url, headers=headers,  data=data)
276             if (response.status_code == ACCEPTED):
277                 self.logger.debug(response.status_code)
278                 self.logger.debug(response.content)
279                 info = "Creation of VM" + str(y) + " is successfull"
280                 self.logger.debug(info)
281
282                 json1_data = json.loads(response.content)
283                 self.logger.debug(json1_data)
284                 self.vm_id = json1_data['server']['id']
285                 self.vm.append(json1_data['server']['id'])
286             else:
287                 return(response.status_code)
288
289         return(response.status_code)
290
291     def checkVmState(self):
292         """Checking the Status of the Instance."""
293         time.sleep(10)
294         for y in range(0, 3):
295             url = ("http://%s:8774/v2.1/servers/"
296                    "detail?name=vm" + str(y)) % (self.neutron_hostname)
297             headers = {"Accept": "application/json",  "X-Auth-Token":
298                        self.token_id}
299             response = requests.get(url, headers=headers)
300             if (response.status_code == OK):
301                 self.logger.debug(response.status_code)
302                 self.logger.debug(response.content)
303                 json1_data = json.loads(response.content)
304                 self.logger.debug(json1_data)
305                 self.vm_active = json1_data['servers'][0]['status']
306                 if (self.vm_active == "ACTIVE"):
307                     info = "VM" + str(y) + " is Active : " + self.vm_active
308                 else:
309                     info = "VM" + str(y) + " is NOT Active : " + self.vm_active
310                 self.logger.debug(info)
311             else:
312                 return(response.status_code)
313         return(response.status_code)
314         time.sleep(10)
315
316     def createPortPair(self):
317         """Creation of Port Pair."""
318         for p in range(1, 2):
319             Dicdata = {}
320             if self.port_pair_ingress != '':
321                 Dicdata['ingress'] = self.port_num[p]
322             if self.port_pair_egress != '':
323                 egress = p
324                 Dicdata['egress'] = self.port_num[egress]
325             if self.port_pair_name != '':
326                 Dicdata['name'] = "PP" + str(p)
327
328             Dicdata = {'port_pair': Dicdata}
329             data = json.dumps(Dicdata, indent=4)
330             url = 'http://%s:9696/%s/sfc/port_pairs' % (self.neutron_hostname,
331                                                         self.osver)
332             headers = {"Accept": "application/json", "X-Auth-Token":
333                        self.token_id}
334             response = requests.post(url, headers=headers,  data=data)
335             if (response.status_code == CREATED):
336                 info = ("Creation of Port Pair PP" + str(p) +
337                         " is successful")
338                 self.logger.debug(info)
339             else:
340                 return(response.status_code)
341
342         return(response.status_code)
343
344     def getPortPair(self):
345         """Query the Portpair id value."""
346         for p in range(0, 1):
347             url = ("http://%s:9696/%s/ports/"
348                    "sfc/port_pairs?name=PP1" % (self.neutron_hostname,
349                                                 self.osver))
350             headers = {"Accept": "application/json",
351                        "X-Auth-Token": self.token_id}
352             response = requests.get(url, headers=headers)
353
354             if (response.status_code == OK):
355                 self.logger.debug(response.status_code)
356                 self.logger.debug(response.content)
357                 json1_data = json.loads(response.content)
358                 self.logger.debug(json1_data)
359                 self.port_pair_id.append(json1_data['port_pairs'][0]['id'])
360             else:
361                 return(response.status_code)
362         return(response.status_code)
363
364     def createPortGroup(self):
365         """Creation of PortGroup."""
366         for p in range(0, 1):
367             Dicdata = {}
368             port_pair_list = []
369             port_pair_list.append(self.port_pair_id[p])
370             if self.port_group_name != '':
371                 Dicdata['name'] = "PG" + str(p)
372             if self.port_pair_id != '':
373                 Dicdata['port_pairs'] = port_pair_list
374
375             Dicdata = {'port_pair_group': Dicdata}
376             data = json.dumps(Dicdata, indent=4)
377             url = ("http://%s:9696/%s/"
378                    "sfc/port_pair_groups" % (self.neutron_hostname,
379                                              self.osver))
380             headers = {"Accept": "application/json", "X-Auth-Token":
381                        self.token_id}
382             response = requests.post(url, headers=headers,  data=data)
383             if (response.status_code == CREATED):
384                 info = ("Creation of Port Group PG" + str(p) +
385                         "is successful")
386                 self.logger.debug(info)
387             else:
388                 return(response.status_code)
389
390         return(response.status_code)
391
392     def getPortGroup(self):
393         """Query the PortGroup id."""
394         for p in range(0, 1):
395             url = ("http://%s:9696/%s/sfc/port_pair_groups"
396                    "?name=PG" + str(p)) % (self.neutron_hostname,
397                                            self.osver)
398             headers = {"Accept": "application/json", "X-Auth-Token":
399                        self.token_id}
400             response = requests.get(url, headers=headers)
401
402             if (response.status_code == OK):
403                 self.logger.debug(response.status_code)
404                 self.logger.debug(response.content)
405                 json1_data = json.loads(response.content)
406                 self.port_grp_id.append(json1_data['port_pair_groups']
407                                         [0]['id'])
408             else:
409                 return(response.status_code)
410         return(response.status_code)
411
412     def createFlowClassifier(self):
413         """Creation of Flow Classifier."""
414         Dicdata = {}
415         if self.source_ip_prefix != '':
416             Dicdata['source_ip_prefix'] = self.source_ip_prefix
417         if self.destination_ip_prefix != '':
418             Dicdata['destination_ip_prefix'] = self.destination_ip_prefix
419         if self.logical_source_port != '':
420             Dicdata['logical_source_port'] = self.port_num[0]
421         if self.fcname != '':
422             Dicdata['name'] = "FC1"
423         if self.ethertype != '':
424             Dicdata['ethertype'] = self.ethertype
425
426         Dicdata = {'flow_classifier': Dicdata}
427         data = json.dumps(Dicdata, indent=4)
428         url = ("http://%s:9696/%s/"
429                "sfc/flow_classifiers" % (self.neutron_hostname,
430                                          self.osver))
431         headers = {"Accept": "application/json",
432                    "X-Auth-Token": self.token_id}
433         response = requests.post(url, headers=headers,  data=data)
434         if (response.status_code == CREATED):
435             json1_data = json.loads(response.content)
436             self.flow_class_if = json1_data['flow_classifier']['id']
437             self.logger.debug("Creation of Flow Classifier is successful")
438             return(response.status_code)
439         else:
440             return(response.status_code)
441
442     def createPortChain(self):
443         """Creation of PortChain."""
444         Dicdata = {}
445         flow_class_list = []
446         flow_class_list.append(self.flow_class_if)
447         port_pair_groups_list = []
448         port_pair_groups_list.append(self.port_grp_id[0])
449
450         if flow_class_list != '':
451             Dicdata['flow_classifiers'] = flow_class_list
452         if self.pcname != '':
453             Dicdata['name'] = "PC1"
454         if port_pair_groups_list != '':
455             Dicdata['port_pair_groups'] = port_pair_groups_list
456
457         Dicdata = {'port_chain': Dicdata}
458         data = json.dumps(Dicdata, indent=4)
459         url = 'http://%s:9696/%s/sfc/port_chains' % (self.neutron_hostname,
460                                                      self.osver)
461         headers = {"Accept": "application/json",
462                    "Content-Type": "application/json",
463                    "X-Auth-Token": self.token_id}
464         response = requests.post(url, headers=headers,  data=data)
465         if (response.status_code == CREATED):
466             self.logger.debug("Creation of PORT CHAIN is successful")
467             json1_data = json.loads(response.content)
468             self.PC_id = json1_data['port_chain']['id']
469             return(response.status_code)
470         else:
471             return(response.status_code)
472
473     def checkFlowAdded(self):
474         """Check whether the Flows are downloaded successfully."""
475         time.sleep(5)
476         response = requests.get('http://' + self.onos_hostname +
477                                 ':8181/onos/v1/flows',
478                                 auth=("karaf",  "karaf"))
479         if (response.status_code == OK):
480             self.logger.debug("Flow is successfully Queries")
481             json1_data = json.loads(response.content)
482             self.flowadd = json1_data['flows'][0]['state']
483
484             if (self.flowadd == "ADDED"):
485                 self.logger.info("Flow is successfully added to OVS")
486                 return(response.status_code)
487             else:
488                 return(404)
489         else:
490             return(response.status_code)
491 ####################################################################
492
493     def createRouter(self):
494         """Creation of Router."""
495         Dicdata = {}
496         if self.routername != '':
497             Dicdata['name'] = "router1"
498         if self.admin_state_up != '':
499             Dicdata['admin_state_up'] = self.admin_state_up
500
501         Dicdata = {'router': Dicdata}
502         data = json.dumps(Dicdata, indent=4)
503         url = 'http://%s:9696/%s/routers.json' % (self.neutron_hostname,
504                                                   self.osver)
505         headers = {"Accept": "application/json",
506                    "X-Auth-Token": self.token_id}
507         response = requests.post(url, headers=headers,  data=data)
508         if (response.status_code == CREATED):
509             self.logger.debug(response.status_code)
510             self.logger.debug(response.content)
511             self.logger.debug("Creation of Router is successfull")
512             json1_data = json.loads(response.content)
513             self.logger.debug(json1_data)
514             self.router_id = json1_data['router']['id']
515             return(response.status_code)
516         else:
517             return(response.status_code)
518
519     def attachInterface(self):
520         """Attachment of instance ports to the Router."""
521         url = ("http://%s:9696/%s/networks"
522                "?name=admin_floating_net" % (self.neutron_hostname,
523                                              self.osver))
524         headers = {"Accept": "application/json", "X-Auth-Token": self.token_id}
525         response = requests.get(url, headers=headers)
526         if (response.status_code == OK):
527             self.logger.debug(response.status_code)
528             self.logger.debug(response.content)
529             json1_data = json.loads(response.content)
530             self.logger.debug(json1_data)
531             self.net_name = json1_data['networks'][0]['name']
532             if (self.net_name == "admin_floating_net"):
533                 self.pub_net_id = json1_data['networks'][0]['id']
534             else:
535                 return(response.status_code)
536         ############################################################
537
538         self.logger.info("Attachment of Instance interface to Router")
539         Dicdata = {}
540         if self.subnetId != '':
541             Dicdata['subnet_id'] = self.subnetId
542
543         data = json.dumps(Dicdata, indent=4)
544         url = ("http://%s:9696/%s/routers"
545                "/%s/add_router_interface" % (self.neutron_hostname,
546                                              self.osver,
547                                              self.router_id))
548         headers = {"Accept": "application/json",
549                    "X-Auth-Token": self.token_id}
550         response = requests.put(url, headers=headers,  data=data)
551         if (response.status_code == OK):
552             self.logger.debug(response.status_code)
553             self.logger.debug(response.content)
554             self.logger.info("Interface attached successfull")
555         else:
556             return(response.status_code)
557         ############################################################
558         self.logger.info("Attachment of Gateway to Router")
559
560         Dicdata1 = {}
561         if self.pub_net_id != 0:
562             Dicdata1['network_id'] = self.pub_net_id
563
564         Dicdata1 = {'external_gateway_info': Dicdata1}
565         Dicdata1 = {'router': Dicdata1}
566         data = json.dumps(Dicdata1, indent=4)
567         url = 'http://%s:9696/%s/routers/%s' % (self.neutron_hostname,
568                                                 self.osver,
569                                                 self.router_id)
570         headers = {"Accept": "application/json",
571                    "X-Auth-Token": self.token_id}
572         response = requests.put(url, headers=headers,  data=data)
573         if (response.status_code == OK):
574             self.logger.debug(response.status_code)
575             self.logger.debug(response.content)
576             self.logger.info("Gateway Interface attached successfull")
577             return(response.status_code)
578         else:
579             return(response.status_code)
580
581     def addFloatingIp(self):
582         """Attachment of Floating Ip to the Router."""
583         for ip_num in range(0, 2):
584             Dicdata = {}
585             Dicdata['pool'] = "admin_floating_net"
586
587             data = json.dumps(Dicdata, indent=4)
588             url = ("http://%s:8774/v2.1/"
589                    "os-floating-ips" % (self.nova_hostname))
590             headers = {"Accept": "application/json",
591                        "X-Auth-Token": self.token_id}
592             response = requests.post(url, headers=headers,  data=data)
593             if (response.status_code == OK):
594                 self.logger.debug(response.status_code)
595                 self.logger.debug(response.content)
596                 self.logger.info("Floating ip created successfully")
597                 json1_data = json.loads(response.content)
598                 self.logger.debug(json1_data)
599                 self.vm_public_ip.append(json1_data['floating_ip']['ip'])
600                 self.vm_public_id.append(json1_data['floating_ip']['id'])
601             else:
602                 self.logger.error("Floating ip NOT created successfully")
603
604             Dicdata1 = {}
605             if self.address != '':
606                 Dicdata1['address'] = self.vm_public_ip[ip_num]
607
608             Dicdata1 = {'addFloatingIp': Dicdata1}
609             data = json.dumps(Dicdata1, indent=4)
610             url = ("http://%s:8774/v2.1/"
611                    "servers/%s/action" % (self.nova_hostname,
612                                           self.vm[ip_num]))
613
614             headers = {"Accept": "application/json",
615                        "X-Auth-Token": self.token_id}
616             response = requests.post(url, headers=headers,  data=data)
617             if(response.status_code == ACCEPTED):
618                 self.logger.debug(response.status_code)
619                 self.logger.debug(response.content)
620                 self.logger.info("Public Ip successfully added to VM")
621             else:
622                 return(response.status_code)
623         return(response.status_code)
624
625     def loginToVM(self):
626         """Login to the VM to check NSH packets are received."""
627         queue1 = "0"
628
629         def vm0():
630
631             s = pxssh.pxssh()
632             hostname = self.vm_public_ip[0]
633             username = "cirros"
634             password = "cubswin:)"
635             s.login(hostname,  username,  password)
636             s.sendline("ping -c 5 " + str(self.port_ip[2]))
637             s.prompt()             # match the prompt
638
639             ping_re = re.search("transmitted.*received",  s.before).group()
640             x = re.split('\s+',  ping_re)
641             if (x[1] >= "1"):
642                 self.logger.info("Ping is Successfull")
643             else:
644                 self.logger.info("Ping is NOT Successfull")
645
646         def vm1(queue1):
647             s = pxssh.pxssh()
648             hostname = self.vm_public_ip[1]
649             username = "cirros"
650             password = "cubswin:)"
651             s.login(hostname,  username,  password)
652             s.sendline('sudo ./firewall')
653             s.prompt()
654             output_pack = s.before
655
656             if(output_pack.find("nshc") != -1):
657                 self.logger.info("The packet has reached VM2 Instance")
658                 queue1.put("1")
659             else:
660                 self.logger.info("Packet not received in Instance")
661                 queue1.put("0")
662
663         def ping(ip, timeout=300):
664             while True:
665                 time.sleep(1)
666                 self.logger.debug("Pinging %s. Waiting for response..." % ip)
667                 response = os.system("ping -c 1 " + ip + " >/dev/null 2>&1")
668                 if response == 0:
669                     self.logger.info("Ping " + ip + " detected!")
670                     return 0
671
672                 elif timeout == 0:
673                     self.logger.info("Ping " + ip + " timeout reached.")
674                     return 1
675                 timeout -= 1
676
677         result0 = ping(self.vm_public_ip[0])
678         result1 = ping(self.vm_public_ip[1])
679         if result0 == 0 and result1 == 0:
680             time.sleep(300)
681             queue1 = Queue()
682             p1 = Process(target=vm1,  args=(queue1, ))
683             p1.start()
684             p2 = Process(target=vm0)
685             p2.start()
686             p1.join(10)
687             return (queue1.get())
688         else:
689             self.logger.error("Thread didnt run")
690
691     """##################################################################"""
692     """ ########################  Stats Functions ################# #####"""
693
694     def portChainDeviceMap(self):
695         """Check the PC Device Stats in the ONOS."""
696         response = requests.get('http://' + self.onos_hostname +
697                                 ':8181/onos/vtn/portChainDeviceMap/' +
698                                 self.PC_id, auth=("karaf", "karaf"))
699         if (response.status_code == OK):
700             self.logger.info("PortChainDeviceMap is successfully Queries")
701             return(response.status_code)
702         else:
703             return(response.status_code)
704
705     def portChainSfMap(self):
706         """Check the PC SF Map Stats in the ONOS."""
707         response = requests.get('http://' + self.onos_hostname +
708                                 ':8181/onos/vtn/portChainSfMap/' +
709                                 self.PC_id, auth=("karaf",  "karaf"))
710         if (response.status_code == OK):
711             self.logger.info("portChainSfMap is successfully Queries")
712             return(response.status_code)
713         else:
714             return(response.status_code)
715
716     """###################################################################"""
717
718     def deletePortChain(self):
719         """Deletion of PortChain."""
720         url = ('http://' + self.neutron_hostname + ':9696/' +
721                self.osver + '/sfc/port_chains/' + self.PC_id)
722         headers = {"Accept": "application/json", "Content-Type":
723                    "application/json", "X-Auth-Token": self.token_id}
724         response = requests.delete(url, headers=headers)
725         if (response.status_code == OK):
726             self.logger.debug(response.status_code)
727             self.logger.debug(response.content)
728             return(response.status_code)
729         else:
730             return(response.status_code)
731
732     def deleteFlowClassifier(self):
733         """Deletion of Flow Classifier."""
734         url = ("http://%s:9696/%s/sfc/"
735                "flow_classifiers/%s" % (self.neutron_hostname,
736                                         self.osver,
737                                         self.flow_class_if))
738         headers = {"Accept": "application/json",
739                    "X-Auth-Token": self.token_id}
740         response = requests.delete(url, headers=headers)
741         if (response.status_code == OK):
742             self.logger.debug(response.status_code)
743             self.logger.debug(response.content)
744             return(response.status_code)
745         else:
746             return(response.status_code)
747
748     def deletePortGroup(self):
749         """Deletion of PortGroup."""
750         for p in range(0, 1):
751             url = ("http://%s:9696/%s/sfc/"
752                    "port_pair_groups/%s" % (self.neutron_hostname,
753                                             self.osver,
754                                             self.port_grp_id[p]))
755             headers = {"Accept": "application/json", "X-Auth-Token":
756                        self.token_id}
757             response = requests.delete(url, headers=headers)
758             if (response.status_code == NO_CONTENT):
759                 self.logger.debug(response.status_code)
760                 self.logger.debug(response.content)
761             else:
762                 return(response.status_code)
763         return(response.status_code)
764
765     def deletePortPair(self):
766         """Deletion of Portpair."""
767         for p in range(1,  2):
768             url = ("http://%s:9696/%s/sfc/"
769                    "port_pairs/%s" % (self.neutron_hostname,
770                                       self.osver,
771                                       self.port_pair_id[0]))
772             headers = {"Accept": "application/json",
773                        "X-Auth-Token": self.token_id}
774             response = requests.delete(url, headers=headers)
775             if (response.status_code == NO_CONTENT):
776                 self.logger.debug(response.status_code)
777                 self.logger.debug(response.content)
778             else:
779                 return(response.status_code)
780         return(response.status_code)
781
782     def cleanup(self):
783         """Cleanup."""
784         self.logger.info("Deleting VMs")
785         for y in range(0, 3):
786             url = ("http://%s:8774/v2.1/"
787                    "/servers/%s" % (self.nova_hostname,
788                                     self.vm[y]))
789             headers = {"Accept": "application/json",
790                        "X-Auth-Token": self.token_id}
791             response = requests.delete(url, headers=headers)
792             if (response.status_code == NO_CONTENT):
793                 self.logger.debug(response.status_code)
794                 self.logger.debug(response.content)
795                 self.logger.debug("VM" + str(y) + " is Deleted : ")
796                 time.sleep(10)
797             else:
798                 return(response.status_code)
799         self.logger.info("Deleting Ports")
800         for x in range(self.i, self.numTerms):
801             url = ('http://' + self.neutron_hostname + ':9696/' +
802                    self.osver + '/ports/' + self.port_num[x])
803             headers = {"Accept": "application/json", "X-Auth-Token":
804                        self.token_id}
805             response = requests.delete(url, headers=headers)
806
807             if (response.status_code == NO_CONTENT):
808                 self.logger.debug(response.status_code)
809                 self.logger.debug(response.content)
810                 self.logger.debug("Port" + str(x) + "  Deleted")
811             else:
812                 return(response.status_code)
813         self.logger.info("Deleting Router")
814
815         Dicdata = {}
816         Dicdata['external_gateway_info'] = {}
817         Dicdata = {'router': Dicdata}
818         data = json.dumps(Dicdata, indent=4)
819         url = ("http://%s:9696/%s/"
820                "/routers/%s" % (self.neutron_hostname,
821                                 self.osver,
822                                 self.router_id))
823         headers = {"Accept": "application/json",
824                    "X-Auth-Token": self.token_id}
825         response = requests.put(url, headers=headers,  data=data)
826         if (response.status_code == OK):
827             self.logger.debug(response.status_code)
828             self.logger.debug(response.content)
829             Dicdata1 = {}
830             if self.subnetId != '':
831                 Dicdata1['subnet_id'] = self.subnetId
832             data = json.dumps(Dicdata1, indent=4)
833             url = ("http://%s:9696/%s/routers/%s"
834                    "/remove_router_interface.json" % (self.neutron_hostname,
835                                                       self.osver,
836                                                       self.router_id))
837             headers = {"Accept": "application/json",
838                        "X-Auth-Token": self.token_id}
839             response = requests.put(url, headers=headers,  data=data)
840             if (response.status_code == OK):
841                 url = ("http://%s:9696/%s/"
842                        "routers/%s" % (self.neutron_hostname,
843                                        self.osver,
844                                        self.router_id))
845                 headers = {"Accept": "application/json",  "X-Auth-Token":
846                            self.token_id}
847                 response = requests.delete(url, headers=headers)
848                 if (response.status_code == NO_CONTENT):
849                     self.logger.debug(response.status_code)
850                     self.logger.debug(response.content)
851                 else:
852                     return(response.status_code)
853             else:
854                 return(response.status_code)
855         else:
856             return(response.status_code)
857
858         self.logger.info("Deleting Network")
859         url = "http://%s:9696/%s/networks/%s" % (self.neutron_hostname,
860                                                  self.osver,
861                                                  self.net_id)
862
863         headers = {"Accept": "application/json",
864                    "X-Auth-Token": self.token_id}
865         response = requests.delete(url, headers=headers)
866         if (response.status_code == NO_CONTENT):
867             self.logger.debug(response.status_code)
868             self.logger.debug(response.content)
869         else:
870             return(response.status_code)
871
872         self.logger.info("Deleting Floating ip")
873         for ip_num in range(0, 2):
874             url = ("http://%s:9696/%s/floatingips"
875                    "/%s" % (self.neutron_hostname,
876                             self.osver,
877                             self.vm_public_id[ip_num]))
878
879             headers = {"Accept": "application/json", "X-Auth-Token":
880                        self.token_id}
881             response = requests.delete(url, headers=headers)
882             if (response.status_code == NO_CONTENT):
883                 self.logger.debug(response.status_code)
884                 self.logger.debug(response.content)
885             else:
886                 return(response.status_code)
887         return(response.status_code)