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