65ca5e212677a6346c605a81175c07d53c2d1b53
[transportpce.git] / tests / transportpce_tests / common / test_utils.py
1 #!/usr/bin/env python
2
3 ##############################################################################
4 # Copyright (c) 2020 Orange, Inc. and others.  All rights reserved.
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
10 ##############################################################################
11
12 # pylint: disable=no-member
13 # pylint: disable=too-many-arguments
14
15 import json
16 import os
17 # pylint: disable=wrong-import-order
18 import sys
19 import re
20 import signal
21 import subprocess
22 import time
23
24 import psutil
25 import requests
26
27 # pylint: disable=import-error
28 import simulators
29
30 SIMS = simulators.SIMS
31
32 HONEYNODE_OK_START_MSG = "Netconf SSH endpoint started successfully at 0.0.0.0"
33 KARAF_OK_START_MSG = re.escape(
34     "Blueprint container for bundle org.opendaylight.netconf.restconf")+".* was successfully created"
35 LIGHTY_OK_START_MSG = re.escape("lighty.io and RESTCONF-NETCONF started")
36
37 ODL_LOGIN = "admin"
38 ODL_PWD = "admin"
39 NODES_LOGIN = "admin"
40 NODES_PWD = "admin"
41 URL_CONFIG_NETCONF_TOPO = "{}/config/network-topology:network-topology/topology/topology-netconf/"
42 URL_CONFIG_ORDM_TOPO = "{}/config/ietf-network:networks/network/openroadm-topology/"
43 URL_CONFIG_OTN_TOPO = "{}/config/ietf-network:networks/network/otn-topology/"
44 URL_CONFIG_CLLI_NET = "{}/config/ietf-network:networks/network/clli-network/"
45 URL_CONFIG_ORDM_NET = "{}/config/ietf-network:networks/network/openroadm-network/"
46 URL_PORTMAPPING = "{}/config/transportpce-portmapping:network/nodes/"
47 URL_OPER_SERV_LIST = "{}/operational/org-openroadm-service:service-list/"
48 URL_OPER_SERV_PATH_LIST = "{}/operational/transportpce-service-path:service-path-list/"
49 URL_GET_NBINOTIFICATIONS_PROCESS_SERV = "{}/operations/nbi-notifications:get-notifications-process-service/"
50 URL_GET_NBINOTIFICATIONS_ALARM_SERV = "{}/operations/nbi-notifications:get-notifications-alarm-service/"
51 URL_SERV_CREATE = "{}/operations/org-openroadm-service:service-create"
52 URL_SERV_DELETE = "{}/operations/org-openroadm-service:service-delete"
53 URL_SERVICE_PATH = "{}/operations/transportpce-device-renderer:service-path"
54 URL_OTN_SERVICE_PATH = "{}/operations/transportpce-device-renderer:otn-service-path"
55 URL_TAPI_CREATE_CONNECTIVITY = "{}/operations/tapi-connectivity:create-connectivity-service"
56 URL_TAPI_DELETE_CONNECTIVITY = "{}/operations/tapi-connectivity:delete-connectivity-service"
57 URL_TAPI_GET_CONNECTIVITY = "{}/operations/tapi-connectivity:get-connectivity-service-details"
58 URL_CREATE_OTS_OMS = "{}/operations/transportpce-device-renderer:create-ots-oms"
59 URL_PATH_COMPUTATION_REQUEST = "{}/operations/transportpce-pce:path-computation-request"
60 URL_FULL_PORTMAPPING = "{}/config/transportpce-portmapping:network"
61 URL_TAPI_TOPOLOGY_DETAILS = "{}/operations/tapi-topology:get-topology-details"
62 URL_TAPI_NODE_DETAILS = "{}/operations/tapi-topology:get-node-details"
63 URL_TAPI_NEP_DETAILS = "{}/operations/tapi-topology:get-node-edge-point-details"
64 URL_TAPI_SIP_LIST = "{}/operations/tapi-common:get-service-interface-point-list"
65 URL_TAPI_SERVICE_LIST = "{}/operations/tapi-connectivity:get-connectivity-service-list"
66 URL_TAPI_NOTIFICATION_SUBS_SERVICE = "{}/operations/tapi-notification:create-notification-subscription-service"
67 URL_TAPI_GET_NOTIFICATION_LIST = "{}/operations/tapi-notification:get-notification-list"
68
69 TYPE_APPLICATION_JSON = {'Content-Type': 'application/json', 'Accept': 'application/json'}
70 TYPE_APPLICATION_XML = {'Content-Type': 'application/xml', 'Accept': 'application/xml'}
71
72 CODE_SHOULD_BE_200 = 'Http status code should be 200'
73 CODE_SHOULD_BE_201 = 'Http status code should be 201'
74
75 SIM_LOG_DIRECTORY = os.path.join(os.path.dirname(os.path.realpath(__file__)), "log")
76
77 process_list = []
78
79
80 if "USE_ODL_ALT_RESTCONF_PORT" in os.environ:
81     RESTCONF_BASE_URL = "http://localhost:" + os.environ['USE_ODL_ALT_RESTCONF_PORT'] + "/restconf"
82 else:
83     RESTCONF_BASE_URL = "http://localhost:8181/restconf"
84
85 if "USE_ODL_ALT_KARAF_INSTALL_DIR" in os.environ:
86     KARAF_INSTALLDIR = os.environ['USE_ODL_ALT_KARAF_INSTALL_DIR']
87 else:
88     KARAF_INSTALLDIR = "karaf"
89
90 KARAF_LOG = os.path.join(
91     os.path.dirname(os.path.realpath(__file__)),
92     "..", "..", "..", KARAF_INSTALLDIR, "target", "assembly", "data", "log", "karaf.log")
93
94 if "USE_LIGHTY" in os.environ and os.environ['USE_LIGHTY'] == 'True':
95     TPCE_LOG = 'odl-' + str(os.getpid()) + '.log'
96 else:
97     TPCE_LOG = KARAF_LOG
98
99
100 def start_sims(sims_list):
101     for sim in sims_list:
102         print("starting simulator " + sim[0] + " in OpenROADM device version " + sim[1] + "...")
103         log_file = os.path.join(SIM_LOG_DIRECTORY, SIMS[sim]['logfile'])
104         process = start_honeynode(log_file, sim)
105         if wait_until_log_contains(log_file, HONEYNODE_OK_START_MSG, 100):
106             print("simulator for " + sim[0] + " started")
107         else:
108             print("simulator for " + sim[0] + " failed to start")
109             shutdown_process(process)
110             for pid in process_list:
111                 shutdown_process(pid)
112             sys.exit(3)
113         process_list.append(process)
114     return process_list
115
116
117 def start_tpce():
118     print("starting OpenDaylight...")
119     if "USE_LIGHTY" in os.environ and os.environ['USE_LIGHTY'] == 'True':
120         process = start_lighty()
121         start_msg = LIGHTY_OK_START_MSG
122     else:
123         process = start_karaf()
124         start_msg = KARAF_OK_START_MSG
125     if wait_until_log_contains(TPCE_LOG, start_msg, time_to_wait=300):
126         print("OpenDaylight started !")
127     else:
128         print("OpenDaylight failed to start !")
129         shutdown_process(process)
130         for pid in process_list:
131             shutdown_process(pid)
132         sys.exit(1)
133     process_list.append(process)
134     return process_list
135
136
137 def start_karaf():
138     print("starting KARAF TransportPCE build...")
139     executable = os.path.join(
140         os.path.dirname(os.path.realpath(__file__)),
141         "..", "..", "..", KARAF_INSTALLDIR, "target", "assembly", "bin", "karaf")
142     with open('odl.log', 'w', encoding='utf-8') as outfile:
143         return subprocess.Popen(
144             ["sh", executable, "server"], stdout=outfile, stderr=outfile, stdin=None)
145
146
147 def start_lighty():
148     print("starting LIGHTY.IO TransportPCE build...")
149     executable = os.path.join(
150         os.path.dirname(os.path.realpath(__file__)),
151         "..", "..", "..", "lighty", "target", "tpce",
152         "clean-start-controller.sh")
153     with open(TPCE_LOG, 'w', encoding='utf-8') as outfile:
154         return subprocess.Popen(
155             ["sh", executable], stdout=outfile, stderr=outfile, stdin=None)
156
157
158 def install_karaf_feature(feature_name: str):
159     print("installing feature " + feature_name)
160     executable = os.path.join(
161         os.path.dirname(os.path.realpath(__file__)),
162         "..", "..", "..", KARAF_INSTALLDIR, "target", "assembly", "bin", "client")
163     return subprocess.run([executable],
164                           input='feature:install ' + feature_name + '\n feature:list | grep '
165                           + feature_name + ' \n logout \n',
166                           universal_newlines=True, check=False)
167
168
169 def get_request(url):
170     return requests.request(
171         "GET", url.format(RESTCONF_BASE_URL),
172         headers=TYPE_APPLICATION_JSON,
173         auth=(ODL_LOGIN, ODL_PWD))
174
175
176 def post_request(url, data):
177     if data:
178         print(json.dumps(data))
179         return requests.request(
180             "POST", url.format(RESTCONF_BASE_URL),
181             data=json.dumps(data),
182             headers=TYPE_APPLICATION_JSON,
183             auth=(ODL_LOGIN, ODL_PWD))
184
185     return requests.request(
186         "POST", url.format(RESTCONF_BASE_URL),
187         headers=TYPE_APPLICATION_JSON,
188         auth=(ODL_LOGIN, ODL_PWD))
189
190
191 def post_xmlrequest(url, data):
192     if data:
193         return requests.request(
194             "POST", url.format(RESTCONF_BASE_URL),
195             data=data,
196             headers=TYPE_APPLICATION_XML,
197             auth=(ODL_LOGIN, ODL_PWD))
198     return None
199
200
201 def put_request(url, data):
202     return requests.request(
203         "PUT", url.format(RESTCONF_BASE_URL),
204         data=json.dumps(data),
205         headers=TYPE_APPLICATION_JSON,
206         auth=(ODL_LOGIN, ODL_PWD))
207
208
209 def put_xmlrequest(url, data):
210     return requests.request(
211         "PUT", url.format(RESTCONF_BASE_URL),
212         data=data,
213         headers=TYPE_APPLICATION_XML,
214         auth=(ODL_LOGIN, ODL_PWD))
215
216
217 def put_jsonrequest(url, data):
218     return requests.request(
219         "PUT", url.format(RESTCONF_BASE_URL),
220         data=data,
221         headers=TYPE_APPLICATION_JSON,
222         auth=(ODL_LOGIN, ODL_PWD))
223
224
225 def rawput_request(url, data):
226     return requests.request(
227         "PUT", url.format(RESTCONF_BASE_URL),
228         data=data,
229         headers=TYPE_APPLICATION_JSON,
230         auth=(ODL_LOGIN, ODL_PWD))
231
232
233 def rawpost_request(url, data):
234     return requests.request(
235         "POST", url.format(RESTCONF_BASE_URL),
236         data=data,
237         headers=TYPE_APPLICATION_JSON,
238         auth=(ODL_LOGIN, ODL_PWD))
239
240
241 def delete_request(url):
242     return requests.request(
243         "DELETE", url.format(RESTCONF_BASE_URL),
244         headers=TYPE_APPLICATION_JSON,
245         auth=(ODL_LOGIN, ODL_PWD))
246
247
248 def mount_device(node_id, sim):
249     url = URL_CONFIG_NETCONF_TOPO + "node/" + node_id
250     body = {"node": [{
251         "node-id": node_id,
252         "netconf-node-topology:username": NODES_LOGIN,
253         "netconf-node-topology:password": NODES_PWD,
254         "netconf-node-topology:host": "127.0.0.1",
255         "netconf-node-topology:port": SIMS[sim]['port'],
256         "netconf-node-topology:tcp-only": "false",
257         "netconf-node-topology:pass-through": {}}]}
258     response = put_request(url, body)
259     if wait_until_log_contains(TPCE_LOG, re.escape("Triggering notification stream NETCONF for node " + node_id), 180):
260         print("Node " + node_id + " correctly added to tpce topology", end='... ', flush=True)
261     else:
262         print("Node " + node_id + " still not added to tpce topology", end='... ', flush=True)
263         if response.status_code == requests.codes.ok:
264             print("It was probably loaded at start-up", end='... ', flush=True)
265         # TODO an else-clause to abort test would probably be nice here
266     return response
267
268
269 def mount_tapi_device(node_id, sim):
270     url = URL_CONFIG_NETCONF_TOPO + "node/" + node_id
271     body = {"node": [{
272         "node-id": node_id,
273         "netconf-node-topology:username": NODES_LOGIN,
274         "netconf-node-topology:password": NODES_PWD,
275         "netconf-node-topology:host": "127.0.0.1",
276         "netconf-node-topology:port": SIMS[sim]['port'],
277         "netconf-node-topology:tcp-only": "false",
278         "netconf-node-topology:pass-through": {}}]}
279     response = put_request(url, body)
280     if wait_until_log_contains(TPCE_LOG, re.escape(f"TAPI node for or node {node_id} successfully merged"), 200):
281         print("Node " + node_id + " correctly added to tpce topology", end='... ', flush=True)
282     else:
283         print("Node " + node_id + " still not added to tpce topology", end='... ', flush=True)
284         if response.status_code == requests.codes.ok:
285             print("It was probably loaded at start-up", end='... ', flush=True)
286         # TODO an else-clause to abort test would probably be nice here
287     return response
288
289
290 def unmount_device(node_id):
291     url = URL_CONFIG_NETCONF_TOPO + "node/" + node_id
292     response = delete_request(url)
293     if wait_until_log_contains(TPCE_LOG, re.escape("onDeviceDisConnected: " + node_id), 180):
294         print("Node " + node_id + " correctly deleted from tpce topology", end='... ', flush=True)
295     else:
296         print("Node " + node_id + " still not deleted from tpce topology", end='... ', flush=True)
297     return response
298
299
300 def connect_xpdr_to_rdm_request(xpdr_node: str, xpdr_num: str, network_num: str,
301                                 rdm_node: str, srg_num: str, termination_num: str):
302     url = "{}/operations/transportpce-networkutils:init-xpdr-rdm-links"
303     data = {
304         "networkutils:input": {
305             "networkutils:links-input": {
306                 "networkutils:xpdr-node": xpdr_node,
307                 "networkutils:xpdr-num": xpdr_num,
308                 "networkutils:network-num": network_num,
309                 "networkutils:rdm-node": rdm_node,
310                 "networkutils:srg-num": srg_num,
311                 "networkutils:termination-point-num": termination_num
312             }
313         }
314     }
315     return post_request(url, data)
316
317
318 def connect_rdm_to_xpdr_request(xpdr_node: str, xpdr_num: str, network_num: str,
319                                 rdm_node: str, srg_num: str, termination_num: str):
320     url = "{}/operations/transportpce-networkutils:init-rdm-xpdr-links"
321     data = {
322         "networkutils:input": {
323             "networkutils:links-input": {
324                 "networkutils:xpdr-node": xpdr_node,
325                 "networkutils:xpdr-num": xpdr_num,
326                 "networkutils:network-num": network_num,
327                 "networkutils:rdm-node": rdm_node,
328                 "networkutils:srg-num": srg_num,
329                 "networkutils:termination-point-num": termination_num
330             }
331         }
332     }
333     return post_request(url, data)
334
335
336 def connect_xpdr_to_rdm_tapi_request(xpdr_node: str, xpdr_num: str, rdm_node: str, srg_num: str):
337     url = "{}/operations/transportpce-tapinetworkutils:init-xpdr-rdm-tapi-link"
338     data = {
339         "input": {
340             "xpdr-node": xpdr_node,
341             "network-tp": xpdr_num,
342             "rdm-node": rdm_node,
343             "add-drop-tp": srg_num
344         }
345     }
346     return post_request(url, data)
347
348
349 def check_netconf_node_request(node: str, suffix: str):
350     url = URL_CONFIG_NETCONF_TOPO + (
351         "node/" + node + "/yang-ext:mount/org-openroadm-device:org-openroadm-device/" + suffix
352     )
353     return get_request(url)
354
355
356 def get_netconf_oper_request(node: str):
357     url = "{}/operational/network-topology:network-topology/topology/topology-netconf/node/" + node
358     return get_request(url)
359
360
361 def get_ordm_topo_request(suffix: str):
362     url = URL_CONFIG_ORDM_TOPO + suffix
363     return get_request(url)
364
365
366 def add_oms_attr_request(link: str, attr):
367     url = URL_CONFIG_ORDM_TOPO + (
368         "ietf-network-topology:link/" + link + "/org-openroadm-network-topology:OMS-attributes/span"
369     )
370     return put_request(url, attr)
371
372
373 def del_oms_attr_request(link: str):
374     url = URL_CONFIG_ORDM_TOPO + (
375         "ietf-network-topology:link/" + link + "/org-openroadm-network-topology:OMS-attributes/span"
376     )
377     return delete_request(url)
378
379
380 def get_clli_net_request():
381     return get_request(URL_CONFIG_CLLI_NET)
382
383
384 def get_ordm_net_request():
385     return get_request(URL_CONFIG_ORDM_NET)
386
387
388 def get_otn_topo_request():
389     return get_request(URL_CONFIG_OTN_TOPO)
390
391
392 def del_link_request(link: str):
393     url = URL_CONFIG_ORDM_TOPO + ("ietf-network-topology:link/" + link)
394     return delete_request(url)
395
396
397 def del_node_request(node: str):
398     url = URL_CONFIG_CLLI_NET + ("node/" + node)
399     return delete_request(url)
400
401
402 def portmapping_request(suffix: str):
403     url = URL_PORTMAPPING + suffix
404     return get_request(url)
405
406
407 def get_notifications_process_service_request(attr):
408     return post_request(URL_GET_NBINOTIFICATIONS_PROCESS_SERV, attr)
409
410
411 def get_notifications_alarm_service_request(attr):
412     return post_request(URL_GET_NBINOTIFICATIONS_ALARM_SERV, attr)
413
414
415 def get_service_list_request(suffix: str):
416     return get_request(URL_OPER_SERV_LIST + suffix)
417
418
419 def get_service_path_list_request(suffix: str):
420     return get_request(URL_OPER_SERV_PATH_LIST + suffix)
421
422
423 def service_create_request(attr):
424     return post_request(URL_SERV_CREATE, attr)
425
426
427 def service_delete_request(servicename: str,
428                            requestid="e3028bae-a90f-4ddd-a83f-cf224eba0e58",
429                            notificationurl="http://localhost:8585/NotificationServer/notify"):
430     attr = {"input": {
431         "sdnc-request-header": {
432             "request-id": requestid,
433             "rpc-action": "service-delete",
434             "request-system-id": "appname",
435             "notification-url": notificationurl},
436         "service-delete-req-info": {
437             "service-name": servicename,
438             "tail-retention": "no"}}}
439     return post_request(URL_SERV_DELETE, attr)
440
441
442 def service_path_request(operation: str, servicename: str, wavenumber: str, nodes, centerfreq: str,
443                          slotwidth: int, minfreq: float, maxfreq: float, lowerslotnumber: int,
444                          higherslotnumber: int, modulation_format="dp-qpsk"):
445     attr = {"renderer:input": {
446         "renderer:service-name": servicename,
447         "renderer:wave-number": wavenumber,
448         "renderer:modulation-format": modulation_format,
449         "renderer:operation": operation,
450         "renderer:nodes": nodes,
451         "renderer:center-freq": centerfreq,
452         "renderer:nmc-width": slotwidth,
453         "renderer:min-freq": minfreq,
454         "renderer:max-freq": maxfreq,
455         "renderer:lower-spectral-slot-number": lowerslotnumber,
456         "renderer:higher-spectral-slot-number": higherslotnumber}}
457     return post_request(URL_SERVICE_PATH, attr)
458
459
460 def otn_service_path_request(operation: str, servicename: str, servicerate: str, serviceformat: str, nodes,
461                              eth_attr=None):
462     attr = {"service-name": servicename,
463             "operation": operation,
464             "service-rate": servicerate,
465             "service-format": serviceformat,
466             "nodes": nodes}
467     if eth_attr:
468         attr.update(eth_attr)
469     return post_request(URL_OTN_SERVICE_PATH, {"renderer:input": attr})
470
471
472 def create_ots_oms_request(nodeid: str, lcp: str):
473     attr = {"input": {
474         "node-id": nodeid,
475         "logical-connection-point": lcp}}
476     return post_request(URL_CREATE_OTS_OMS, attr)
477
478
479 def path_computation_request(requestid: str, servicename: str, serviceaend, servicezend,
480                              hardconstraints=None, softconstraints=None, metric="hop-count", other_attr=None):
481     attr = {"service-name": servicename,
482             "resource-reserve": "true",
483             "service-handler-header": {"request-id": requestid},
484             "service-a-end": serviceaend,
485             "service-z-end": servicezend,
486             "pce-routing-metric": metric}
487     if hardconstraints:
488         attr.update({"hard-constraints": hardconstraints})
489     if softconstraints:
490         attr.update({"soft-constraints": softconstraints})
491     if other_attr:
492         attr.update(other_attr)
493     return post_request(URL_PATH_COMPUTATION_REQUEST, {"input": attr})
494
495
496 def tapi_create_connectivity_request(topologyidorname):
497     return post_request(URL_TAPI_CREATE_CONNECTIVITY, topologyidorname)
498
499
500 def tapi_get_connectivity_request(serviceidorname):
501     attr = {
502         "input": {
503             "service-id-or-name": serviceidorname}}
504     return post_request(URL_TAPI_GET_CONNECTIVITY, attr)
505
506
507 def tapi_delete_connectivity_request(serviceidorname):
508     attr = {
509         "input": {
510             "service-id-or-name": serviceidorname}}
511     return post_request(URL_TAPI_DELETE_CONNECTIVITY, attr)
512
513
514 def tapi_get_topology_details_request(topologyidorname):
515     attr = {
516         "input": {
517             "topology-id-or-name": topologyidorname}}
518     return post_request(URL_TAPI_TOPOLOGY_DETAILS, attr)
519
520
521 def tapi_get_node_details_request(topologyidorname, nodeidorname):
522     attr = {
523         "input": {
524             "topology-id-or-name": topologyidorname,
525             "node-id-or-name": nodeidorname}}
526     return post_request(URL_TAPI_NODE_DETAILS, attr)
527
528
529 def tapi_get_node_edge_point_details_request(topologyidorname, nodeidorname, nepidorname):
530     attr = {
531         "input": {
532             "topology-id-or-name": topologyidorname,
533             "node-id-or-name": nodeidorname,
534             "ep-id-or-name": nepidorname}}
535     return post_request(URL_TAPI_NEP_DETAILS, attr)
536
537
538 def tapi_get_sip_details_request():
539     return post_request(URL_TAPI_SIP_LIST, "")
540
541
542 def tapi_get_service_list_request():
543     return post_request(URL_TAPI_SERVICE_LIST, "")
544
545
546 def tapi_create_notification_subscription_service_request(attr):
547     return post_request(URL_TAPI_NOTIFICATION_SUBS_SERVICE, attr)
548
549
550 def tapi_get_notifications_list_request(attr):
551     return post_request(URL_TAPI_GET_NOTIFICATION_LIST, attr)
552
553
554 def shutdown_process(process):
555     if process is not None:
556         for child in psutil.Process(process.pid).children():
557             child.send_signal(signal.SIGINT)
558             child.wait()
559         process.send_signal(signal.SIGINT)
560
561
562 def start_honeynode(log_file: str, sim):
563     executable = os.path.join(os.path.dirname(os.path.realpath(__file__)),
564                               "..", "..", "honeynode", sim[1], "honeynode-simulator", "honeycomb-tpce")
565     sample_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)),
566                                     "..", "..", "sample_configs", "openroadm", sim[1])
567     if os.path.isfile(executable):
568         with open(log_file, 'w', encoding='utf-8') as outfile:
569             return subprocess.Popen(
570                 [executable, SIMS[sim]['port'], os.path.join(sample_directory, SIMS[sim]['configfile'])],
571                 stdout=outfile, stderr=outfile)
572     return None
573
574
575 def wait_until_log_contains(log_file, regexp, time_to_wait=60):
576     # pylint: disable=lost-exception
577     # pylint: disable=consider-using-with
578     stringfound = False
579     filefound = False
580     line = None
581     try:
582         with TimeOut(seconds=time_to_wait):
583             while not os.path.exists(log_file):
584                 time.sleep(0.2)
585             filelogs = open(log_file, 'r', encoding='utf-8')
586             filelogs.seek(0, 2)
587             filefound = True
588             print("Searching for pattern '" + regexp + "' in " + os.path.basename(log_file), end='... ', flush=True)
589             compiled_regexp = re.compile(regexp)
590             while True:
591                 line = filelogs.readline()
592                 if compiled_regexp.search(line):
593                     print("Pattern found!", end=' ')
594                     stringfound = True
595                     break
596                 if not line:
597                     time.sleep(0.1)
598     except TimeoutError:
599         print("Pattern not found after " + str(time_to_wait), end=" seconds! ", flush=True)
600     except PermissionError:
601         print("Permission Error when trying to access the log file", end=" ... ", flush=True)
602     finally:
603         if filefound:
604             filelogs.close()
605         else:
606             print("log file does not exist or is not accessible... ", flush=True)
607         return stringfound
608
609
610 class TimeOut:
611     def __init__(self, seconds=1, error_message='Timeout'):
612         self.seconds = seconds
613         self.error_message = error_message
614
615     def handle_timeout(self, signum, frame):
616         raise TimeoutError(self.error_message)
617
618     def __enter__(self):
619         signal.signal(signal.SIGALRM, self.handle_timeout)
620         signal.alarm(self.seconds)
621
622     def __exit__(self, type, value, traceback):
623         # pylint: disable=W0622
624         signal.alarm(0)