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